text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/behaviors/ball_spawning_behavior.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.load(theme.Assets.images.dash.ball.keyName); } Future<void> pump( List<Component> children, { GameBloc? gameBloc, }) async { await ensureAdd( FlameMultiBlocProvider( providers: [ FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc ?? GameBloc(), ), FlameBlocProvider<CharacterThemeCubit, CharacterThemeState>.value( value: CharacterThemeCubit(), ), ], children: children, ), ); } } class _MockGameState extends Mock implements GameState {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group( 'BallSpawningBehavior', () { final flameTester = FlameTester(_TestGame.new); test('can be instantiated', () { expect( BallSpawningBehavior(), isA<BallSpawningBehavior>(), ); }); flameTester.test( 'loads', (game) async { final behavior = BallSpawningBehavior(); await game.pump([behavior]); expect(game.descendants(), contains(behavior)); }, ); group('listenWhen', () { test( 'never listens when new state not playing', () { final waiting = const GameState.initial() ..copyWith(status: GameStatus.waiting); final gameOver = const GameState.initial() ..copyWith(status: GameStatus.gameOver); final behavior = BallSpawningBehavior(); expect(behavior.listenWhen(_MockGameState(), waiting), isFalse); expect(behavior.listenWhen(_MockGameState(), gameOver), isFalse); }, ); test( 'listens when started playing', () { final waiting = const GameState.initial().copyWith(status: GameStatus.waiting); final playing = const GameState.initial().copyWith(status: GameStatus.playing); final behavior = BallSpawningBehavior(); expect(behavior.listenWhen(waiting, playing), isTrue); }, ); test( 'listens when lost rounds', () { final playing1 = const GameState.initial().copyWith( status: GameStatus.playing, rounds: 2, ); final playing2 = const GameState.initial().copyWith( status: GameStatus.playing, rounds: 1, ); final behavior = BallSpawningBehavior(); expect(behavior.listenWhen(playing1, playing2), isTrue); }, ); test( "doesn't listen when didn't lose any rounds", () { final playing = const GameState.initial().copyWith( status: GameStatus.playing, rounds: 2, ); final behavior = BallSpawningBehavior(); expect(behavior.listenWhen(playing, playing), isFalse); }, ); }); flameTester.test( 'onNewState adds a ball', (game) async { final behavior = BallSpawningBehavior(); await game.pump([ behavior, ZCanvasComponent(), Plunger.test(), ]); expect(game.descendants().whereType<Ball>(), isEmpty); behavior.onNewState(_MockGameState()); await game.ready(); expect(game.descendants().whereType<Ball>(), isNotEmpty); }, ); }, ); }
pinball/test/game/behaviors/ball_spawning_behavior_test.dart/0
{ "file_path": "pinball/test/game/behaviors/ball_spawning_behavior_test.dart", "repo_id": "pinball", "token_count": 1927 }
1,239
// ignore_for_file: cascade_invocations, prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.android.ramp.boardOpening.keyName, Assets.images.android.ramp.railingForeground.keyName, Assets.images.android.ramp.railingBackground.keyName, Assets.images.android.ramp.main.keyName, Assets.images.android.ramp.arrow.inactive.keyName, Assets.images.android.ramp.arrow.active1.keyName, Assets.images.android.ramp.arrow.active2.keyName, Assets.images.android.ramp.arrow.active3.keyName, Assets.images.android.ramp.arrow.active4.keyName, Assets.images.android.ramp.arrow.active5.keyName, Assets.images.android.rail.main.keyName, Assets.images.android.rail.exit.keyName, Assets.images.score.fiveThousand.keyName, ]); } Future<void> pump( SpaceshipRamp child, { required GameBloc gameBloc, required SpaceshipRampCubit bloc, }) async { await ensureAdd( FlameMultiBlocProvider( providers: [ FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc, ), FlameBlocProvider<SpaceshipRampCubit, SpaceshipRampState>.value( value: bloc, ), ], children: [ ZCanvasComponent(children: [child]), ], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockSpaceshipRampCubit extends Mock implements SpaceshipRampCubit {} class _FakeGameEvent extends Fake implements GameEvent {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('RampMultiplierBehavior', () { late GameBloc gameBloc; setUp(() { registerFallbackValue(_FakeGameEvent()); gameBloc = _MockGameBloc(); }); final flameTester = FlameTester(_TestGame.new); flameTester.test( 'adds MultiplierIncreased ' 'when hits are multiples of 5 times and multiplier is less than 6', (game) async { final bloc = _MockSpaceshipRampCubit(); final state = SpaceshipRampState.initial(); final streamController = StreamController<SpaceshipRampState>(); whenListen( bloc, streamController.stream, initialState: state, ); when(() => gameBloc.state).thenReturn( GameState.initial().copyWith( multiplier: 5, ), ); when(() => gameBloc.add(any())).thenAnswer((_) async {}); final behavior = RampMultiplierBehavior(); final parent = SpaceshipRamp.test(children: [behavior]); await game.pump( parent, gameBloc: gameBloc, bloc: bloc, ); streamController.add(state.copyWith(hits: 5)); await Future<void>.delayed(Duration.zero); verify(() => gameBloc.add(const MultiplierIncreased())).called(1); }, ); flameTester.test( "doesn't add MultiplierIncreased " 'when hits are multiples of 5 times but multiplier is 6', (game) async { final bloc = _MockSpaceshipRampCubit(); final state = SpaceshipRampState.initial(); final streamController = StreamController<SpaceshipRampState>(); whenListen( bloc, streamController.stream, initialState: state, ); when(() => gameBloc.state).thenReturn( GameState.initial().copyWith( multiplier: 6, ), ); final behavior = RampMultiplierBehavior(); final parent = SpaceshipRamp.test(children: [behavior]); await game.pump( parent, gameBloc: gameBloc, bloc: bloc, ); streamController.add(state.copyWith(hits: 5)); await Future<void>.delayed(Duration.zero); verifyNever(() => gameBloc.add(const MultiplierIncreased())); }, ); flameTester.test( "doesn't add MultiplierIncreased " "when hits aren't multiples of 5 times", (game) async { final bloc = _MockSpaceshipRampCubit(); final state = SpaceshipRampState.initial(); final streamController = StreamController<SpaceshipRampState>(); whenListen( bloc, streamController.stream, initialState: state, ); when(() => gameBloc.state).thenReturn( GameState.initial().copyWith( multiplier: 5, ), ); final behavior = RampMultiplierBehavior(); final parent = SpaceshipRamp.test(children: [behavior]); await game.pump( parent, gameBloc: gameBloc, bloc: bloc, ); streamController.add(state.copyWith(hits: 1)); await game.ready(); verifyNever(() => gameBloc.add(const MultiplierIncreased())); }, ); }); }
pinball/test/game/components/android_acres/behaviors/ramp_multiplier_behavior_test.dart/0
{ "file_path": "pinball/test/game/components/android_acres/behaviors/ramp_multiplier_behavior_test.dart", "repo_id": "pinball", "token_count": 2342 }
1,240
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/forge2d_game.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.kicker.left.lit.keyName, Assets.images.kicker.left.dimmed.keyName, Assets.images.kicker.right.lit.keyName, Assets.images.kicker.right.dimmed.keyName, Assets.images.baseboard.left.keyName, Assets.images.baseboard.right.keyName, Assets.images.flipper.left.keyName, Assets.images.flipper.right.keyName, ]); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('BottomGroup', () { final flameTester = FlameTester(_TestGame.new); flameTester.test( 'loads correctly', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); expect(game.descendants(), contains(bottomGroup)); }, ); group('loads', () { flameTester.test( 'one left flipper', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); final leftFlippers = bottomGroup.descendants().whereType<Flipper>().where( (flipper) => flipper.side.isLeft, ); expect(leftFlippers.length, equals(1)); }, ); flameTester.test( 'one right flipper', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); final rightFlippers = bottomGroup.descendants().whereType<Flipper>().where( (flipper) => flipper.side.isRight, ); expect(rightFlippers.length, equals(1)); }, ); flameTester.test( 'two Baseboards', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); final baseBottomGroups = bottomGroup.descendants().whereType<Baseboard>(); expect(baseBottomGroups.length, equals(2)); }, ); flameTester.test( 'two Kickers', (game) async { final bottomGroup = BottomGroup(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [bottomGroup], ), ); final kickers = bottomGroup.descendants().whereType<Kicker>(); expect(kickers.length, equals(2)); }, ); }); }); }
pinball/test/game/components/bottom_group_test.dart/0
{ "file_path": "pinball/test/game/components/bottom_group_test.dart", "repo_id": "pinball", "token_count": 1640 }
1,241
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/sparky_scorch/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.sparky.computer.top.keyName, Assets.images.sparky.computer.base.keyName, Assets.images.sparky.computer.glow.keyName, Assets.images.sparky.bumper.a.lit.keyName, Assets.images.sparky.bumper.a.dimmed.keyName, Assets.images.sparky.bumper.b.lit.keyName, Assets.images.sparky.bumper.b.dimmed.keyName, Assets.images.sparky.bumper.c.lit.keyName, Assets.images.sparky.bumper.c.dimmed.keyName, ]); } Future<void> pump( SparkyScorch child, { required GameBloc gameBloc, }) async { // Not needed once https://github.com/flame-engine/flame/issues/1607 // is fixed await onLoad(); await ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc, children: [child], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('SparkyComputerBonusBehavior', () { late GameBloc gameBloc; setUp(() { gameBloc = _MockGameBloc(); }); final flameTester = FlameTester(_TestGame.new); flameTester.testGameWidget( 'adds GameBonus.sparkyTurboCharge to the game ' 'when SparkyComputerState.withBall is emitted', setUp: (game, tester) async { final behavior = SparkyComputerBonusBehavior(); final parent = SparkyScorch.test(); final sparkyComputer = SparkyComputer(); await parent.add(sparkyComputer); await game.pump(parent, gameBloc: gameBloc); await parent.ensureAdd(behavior); sparkyComputer.bloc.onBallEntered(); await tester.pump(); verify( () => gameBloc.add(const BonusActivated(GameBonus.sparkyTurboCharge)), ).called(1); }, ); }); }
pinball/test/game/components/sparky_scorch/behaviors/sparky_computer_bonus_behavior_test.dart/0
{ "file_path": "pinball/test/game/components/sparky_scorch/behaviors/sparky_computer_bonus_behavior_test.dart", "repo_id": "pinball", "token_count": 986 }
1,242
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:pinball/leaderboard/models/leader_board_entry.dart'; import 'package:pinball_theme/pinball_theme.dart'; void main() { group('LeaderboardEntry', () { group('toEntry', () { test('returns the correct from a to entry data', () { expect( LeaderboardEntryData.empty.toEntry(1), LeaderboardEntry( rank: '1', playerInitials: '', score: 0, character: CharacterType.dash.toTheme.leaderboardIcon, ), ); }); }); group('CharacterType', () { test('toTheme returns the correct theme', () { expect(CharacterType.dash.toTheme, equals(DashTheme())); expect(CharacterType.sparky.toTheme, equals(SparkyTheme())); expect(CharacterType.android.toTheme, equals(AndroidTheme())); expect(CharacterType.dino.toTheme, equals(DinoTheme())); }); }); group('CharacterTheme', () { test('toType returns the correct type', () { expect(DashTheme().toType, equals(CharacterType.dash)); expect(SparkyTheme().toType, equals(CharacterType.sparky)); expect(AndroidTheme().toType, equals(CharacterType.android)); expect(DinoTheme().toType, equals(CharacterType.dino)); }); }); }); }
pinball/test/leaderboard/models/leader_board_entry_test.dart/0
{ "file_path": "pinball/test/leaderboard/models/leader_board_entry_test.dart", "repo_id": "pinball", "token_count": 582 }
1,243
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh - name: create all_plugins app script: .ci/scripts/create_all_plugins_app.sh - name: build all_plugins for macOS debug script: .ci/scripts/build_all_plugins.sh args: ["macos", "debug"] - name: build all_plugins for macOS release script: .ci/scripts/build_all_plugins.sh args: ["macos", "release"]
plugins/.ci/targets/macos_build_all_plugins.yaml/0
{ "file_path": "plugins/.ci/targets/macos_build_all_plugins.yaml", "repo_id": "plugins", "token_count": 144 }
1,244
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera; import android.os.Handler; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.camera.features.autofocus.FocusMode; import io.flutter.plugins.camera.features.exposurelock.ExposureMode; import java.util.HashMap; import java.util.Map; /** Utility class that facilitates communication to the Flutter client */ public class DartMessenger { @NonNull private final Handler handler; @Nullable private MethodChannel cameraChannel; @Nullable private MethodChannel deviceChannel; /** Specifies the different device related message types. */ enum DeviceEventType { /** Indicates the device's orientation has changed. */ ORIENTATION_CHANGED("orientation_changed"); private final String method; DeviceEventType(String method) { this.method = method; } } /** Specifies the different camera related message types. */ enum CameraEventType { /** Indicates that an error occurred while interacting with the camera. */ ERROR("error"), /** Indicates that the camera is closing. */ CLOSING("camera_closing"), /** Indicates that the camera is initialized. */ INITIALIZED("initialized"); private final String method; /** * Converts the supplied method name to the matching {@link CameraEventType}. * * @param method name to be converted into a {@link CameraEventType}. */ CameraEventType(String method) { this.method = method; } } /** * Creates a new instance of the {@link DartMessenger} class. * * @param messenger is the {@link BinaryMessenger} that is used to communicate with Flutter. * @param cameraId identifies the camera which is the source of the communication. * @param handler the handler used to manage the thread's message queue. This should always be a * handler managing the main thread since communication with Flutter should always happen on * the main thread. The handler is mainly supplied so it will be easier test this class. */ DartMessenger(BinaryMessenger messenger, long cameraId, @NonNull Handler handler) { cameraChannel = new MethodChannel(messenger, "plugins.flutter.io/camera_android/camera" + cameraId); deviceChannel = new MethodChannel(messenger, "plugins.flutter.io/camera_android/fromPlatform"); this.handler = handler; } /** * Sends a message to the Flutter client informing the orientation of the device has been changed. * * @param orientation specifies the new orientation of the device. */ public void sendDeviceOrientationChangeEvent(PlatformChannel.DeviceOrientation orientation) { assert (orientation != null); this.send( DeviceEventType.ORIENTATION_CHANGED, new HashMap<String, Object>() { { put("orientation", CameraUtils.serializeDeviceOrientation(orientation)); } }); } /** * Sends a message to the Flutter client informing that the camera has been initialized. * * @param previewWidth describes the preview width that is supported by the camera. * @param previewHeight describes the preview height that is supported by the camera. * @param exposureMode describes the current exposure mode that is set on the camera. * @param focusMode describes the current focus mode that is set on the camera. * @param exposurePointSupported indicates if the camera supports setting an exposure point. * @param focusPointSupported indicates if the camera supports setting a focus point. */ void sendCameraInitializedEvent( Integer previewWidth, Integer previewHeight, ExposureMode exposureMode, FocusMode focusMode, Boolean exposurePointSupported, Boolean focusPointSupported) { assert (previewWidth != null); assert (previewHeight != null); assert (exposureMode != null); assert (focusMode != null); assert (exposurePointSupported != null); assert (focusPointSupported != null); this.send( CameraEventType.INITIALIZED, new HashMap<String, Object>() { { put("previewWidth", previewWidth.doubleValue()); put("previewHeight", previewHeight.doubleValue()); put("exposureMode", exposureMode.toString()); put("focusMode", focusMode.toString()); put("exposurePointSupported", exposurePointSupported); put("focusPointSupported", focusPointSupported); } }); } /** Sends a message to the Flutter client informing that the camera is closing. */ void sendCameraClosingEvent() { send(CameraEventType.CLOSING); } /** * Sends a message to the Flutter client informing that an error occurred while interacting with * the camera. * * @param description contains details regarding the error that occurred. */ void sendCameraErrorEvent(@Nullable String description) { this.send( CameraEventType.ERROR, new HashMap<String, Object>() { { if (!TextUtils.isEmpty(description)) put("description", description); } }); } private void send(CameraEventType eventType) { send(eventType, new HashMap<>()); } private void send(CameraEventType eventType, Map<String, Object> args) { if (cameraChannel == null) { return; } handler.post( new Runnable() { @Override public void run() { cameraChannel.invokeMethod(eventType.method, args); } }); } private void send(DeviceEventType eventType) { send(eventType, new HashMap<>()); } private void send(DeviceEventType eventType, Map<String, Object> args) { if (deviceChannel == null) { return; } handler.post( new Runnable() { @Override public void run() { deviceChannel.invokeMethod(eventType.method, args); } }); } /** * Send a success payload to a {@link MethodChannel.Result} on the main thread. * * @param payload The payload to send. */ public void finish(MethodChannel.Result result, Object payload) { handler.post(() -> result.success(payload)); } /** * Send an error payload to a {@link MethodChannel.Result} on the main thread. * * @param errorCode error code. * @param errorMessage error message. * @param errorDetails error details. */ public void error( MethodChannel.Result result, String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) { handler.post(() -> result.error(errorCode, errorMessage, errorDetails)); } }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/DartMessenger.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/DartMessenger.java", "repo_id": "plugins", "token_count": 2302 }
1,245
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera.features.focuspoint; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.MeteringRectangle; import android.util.Size; import androidx.annotation.NonNull; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.CameraRegionUtils; import io.flutter.plugins.camera.features.CameraFeature; import io.flutter.plugins.camera.features.Point; import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature; /** Focus point controls where in the frame focus will come from. */ public class FocusPointFeature extends CameraFeature<Point> { private Size cameraBoundaries; private Point focusPoint; private MeteringRectangle focusRectangle; private final SensorOrientationFeature sensorOrientationFeature; /** * Creates a new instance of the {@link FocusPointFeature}. * * @param cameraProperties Collection of the characteristics for the current camera device. */ public FocusPointFeature( CameraProperties cameraProperties, SensorOrientationFeature sensorOrientationFeature) { super(cameraProperties); this.sensorOrientationFeature = sensorOrientationFeature; } /** * Sets the camera boundaries that are required for the focus point feature to function. * * @param cameraBoundaries - The camera boundaries to set. */ public void setCameraBoundaries(@NonNull Size cameraBoundaries) { this.cameraBoundaries = cameraBoundaries; this.buildFocusRectangle(); } @Override public String getDebugName() { return "FocusPointFeature"; } @Override public Point getValue() { return focusPoint; } @Override public void setValue(Point value) { this.focusPoint = value == null || value.x == null || value.y == null ? null : value; this.buildFocusRectangle(); } // Whether or not this camera can set the focus point. @Override public boolean checkIsSupported() { Integer supportedRegions = cameraProperties.getControlMaxRegionsAutoFocus(); return supportedRegions != null && supportedRegions > 0; } @Override public void updateBuilder(CaptureRequest.Builder requestBuilder) { if (!checkIsSupported()) { return; } requestBuilder.set( CaptureRequest.CONTROL_AF_REGIONS, focusRectangle == null ? null : new MeteringRectangle[] {focusRectangle}); } private void buildFocusRectangle() { if (this.cameraBoundaries == null) { throw new AssertionError( "The cameraBoundaries should be set (using `FocusPointFeature.setCameraBoundaries(Size)`) before updating the focus point."); } if (this.focusPoint == null) { this.focusRectangle = null; } else { PlatformChannel.DeviceOrientation orientation = this.sensorOrientationFeature.getLockedCaptureOrientation(); if (orientation == null) { orientation = this.sensorOrientationFeature.getDeviceOrientationManager().getLastUIOrientation(); } this.focusRectangle = CameraRegionUtils.convertPointToMeteringRectangle( this.cameraBoundaries, this.focusPoint.x, this.focusPoint.y, orientation); } } }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/focuspoint/FocusPointFeature.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/focuspoint/FocusPointFeature.java", "repo_id": "plugins", "token_count": 1073 }
1,246
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera.features.exposurelock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.hardware.camera2.CaptureRequest; import io.flutter.plugins.camera.CameraProperties; import org.junit.Test; public class ExposureLockFeatureTest { @Test public void getDebugName_shouldReturnTheNameOfTheFeature() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposureLockFeature exposureLockFeature = new ExposureLockFeature(mockCameraProperties); assertEquals("ExposureLockFeature", exposureLockFeature.getDebugName()); } @Test public void getValue_shouldReturnAutoIfNotSet() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposureLockFeature exposureLockFeature = new ExposureLockFeature(mockCameraProperties); assertEquals(ExposureMode.auto, exposureLockFeature.getValue()); } @Test public void getValue_shouldEchoTheSetValue() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposureLockFeature exposureLockFeature = new ExposureLockFeature(mockCameraProperties); ExposureMode expectedValue = ExposureMode.locked; exposureLockFeature.setValue(expectedValue); ExposureMode actualValue = exposureLockFeature.getValue(); assertEquals(expectedValue, actualValue); } @Test public void checkIsSupported_shouldReturnTrue() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposureLockFeature exposureLockFeature = new ExposureLockFeature(mockCameraProperties); assertTrue(exposureLockFeature.checkIsSupported()); } @Test public void updateBuilder_shouldSetControlAeLockToFalseWhenAutoExposureIsSetToAuto() { CameraProperties mockCameraProperties = mock(CameraProperties.class); CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class); ExposureLockFeature exposureLockFeature = new ExposureLockFeature(mockCameraProperties); exposureLockFeature.setValue(ExposureMode.auto); exposureLockFeature.updateBuilder(mockBuilder); verify(mockBuilder, times(1)).set(CaptureRequest.CONTROL_AE_LOCK, false); } @Test public void updateBuilder_shouldSetControlAeLockToFalseWhenAutoExposureIsSetToLocked() { CameraProperties mockCameraProperties = mock(CameraProperties.class); CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class); ExposureLockFeature exposureLockFeature = new ExposureLockFeature(mockCameraProperties); exposureLockFeature.setValue(ExposureMode.locked); exposureLockFeature.updateBuilder(mockBuilder); verify(mockBuilder, times(1)).set(CaptureRequest.CONTROL_AE_LOCK, true); } }
plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/exposurelock/ExposureLockFeatureTest.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/exposurelock/ExposureLockFeatureTest.java", "repo_id": "plugins", "token_count": 868 }
1,247
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera.types; import static org.junit.Assert.assertEquals; import org.junit.Test; public class FlashModeTest { @Test public void getValueForString_returnsCorrectValues() { assertEquals( "Returns FlashMode.off for 'off'", FlashMode.getValueForString("off"), FlashMode.off); assertEquals( "Returns FlashMode.auto for 'auto'", FlashMode.getValueForString("auto"), FlashMode.auto); assertEquals( "Returns FlashMode.always for 'always'", FlashMode.getValueForString("always"), FlashMode.always); assertEquals( "Returns FlashMode.torch for 'torch'", FlashMode.getValueForString("torch"), FlashMode.torch); } @Test public void getValueForString_returnsNullForNonexistantValue() { assertEquals( "Returns null for 'nonexistant'", FlashMode.getValueForString("nonexistant"), null); } @Test public void toString_returnsCorrectValue() { assertEquals("Returns 'off' for FlashMode.off", FlashMode.off.toString(), "off"); assertEquals("Returns 'auto' for FlashMode.auto", FlashMode.auto.toString(), "auto"); assertEquals("Returns 'always' for FlashMode.always", FlashMode.always.toString(), "always"); assertEquals("Returns 'torch' for FlashMode.torch", FlashMode.torch.toString(), "torch"); } }
plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/types/FlashModeTest.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/types/FlashModeTest.java", "repo_id": "plugins", "token_count": 523 }
1,248
// 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'; class MethodChannelMock { MethodChannelMock({ required String channelName, this.delay, required this.methods, }) : methodChannel = MethodChannel(channelName) { _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler(methodChannel, _handler); } final Duration? delay; final MethodChannel methodChannel; final Map<String, dynamic> methods; final List<MethodCall> log = <MethodCall>[]; Future<dynamic> _handler(MethodCall methodCall) async { log.add(methodCall); if (!methods.containsKey(methodCall.method)) { throw MissingPluginException('No implementation found for method ' '${methodCall.method} on channel ${methodChannel.name}'); } return Future<dynamic>.delayed(delay ?? Duration.zero, () { final dynamic result = methods[methodCall.method]; if (result is Exception) { throw result; } return Future<dynamic>.value(result); }); } } /// This allows a value of type T or T? to be treated as a value of type T?. /// /// We use this so that APIs that have become non-nullable can still be used /// with `!` and `?` on the stable branch. T? _ambiguate<T>(T? value) => value;
plugins/packages/camera/camera_android/test/method_channel_mock.dart/0
{ "file_path": "plugins/packages/camera/camera_android/test/method_channel_mock.dart", "repo_id": "plugins", "token_count": 496 }
1,249
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.camera.core.CameraSelector; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraSelectorFlutterApi; public class CameraSelectorFlutterApiImpl extends CameraSelectorFlutterApi { private final InstanceManager instanceManager; public CameraSelectorFlutterApiImpl( BinaryMessenger binaryMessenger, InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } void create(CameraSelector cameraSelector, Long lensFacing, Reply<Void> reply) { create(instanceManager.addHostCreatedInstance(cameraSelector), lensFacing, reply); } }
plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorFlutterApiImpl.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorFlutterApiImpl.java", "repo_id": "plugins", "token_count": 254 }
1,250
// 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.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.provider.Settings; import android.view.Display; import android.view.Surface; import android.view.WindowManager; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; import io.flutter.plugins.camerax.DeviceOrientationManager.DeviceOrientationChangeCallback; import org.junit.Before; import org.junit.Test; import org.mockito.MockedStatic; public class DeviceOrientationManagerTest { private Activity mockActivity; private DeviceOrientationChangeCallback mockDeviceOrientationChangeCallback; private WindowManager mockWindowManager; private Display mockDisplay; private DeviceOrientationManager deviceOrientationManager; @Before @SuppressWarnings("deprecation") public void before() { mockActivity = mock(Activity.class); mockDisplay = mock(Display.class); mockWindowManager = mock(WindowManager.class); mockDeviceOrientationChangeCallback = mock(DeviceOrientationChangeCallback.class); when(mockActivity.getSystemService(Context.WINDOW_SERVICE)).thenReturn(mockWindowManager); when(mockWindowManager.getDefaultDisplay()).thenReturn(mockDisplay); deviceOrientationManager = new DeviceOrientationManager(mockActivity, false, 0, mockDeviceOrientationChangeCallback); } @Test public void getVideoOrientation_whenNaturalScreenOrientationEqualsPortraitUp() { int degreesPortraitUp = deviceOrientationManager.getVideoOrientation(DeviceOrientation.PORTRAIT_UP); int degreesPortraitDown = deviceOrientationManager.getVideoOrientation(DeviceOrientation.PORTRAIT_DOWN); int degreesLandscapeLeft = deviceOrientationManager.getVideoOrientation(DeviceOrientation.LANDSCAPE_LEFT); int degreesLandscapeRight = deviceOrientationManager.getVideoOrientation(DeviceOrientation.LANDSCAPE_RIGHT); assertEquals(0, degreesPortraitUp); assertEquals(270, degreesLandscapeLeft); assertEquals(180, degreesPortraitDown); assertEquals(90, degreesLandscapeRight); } @Test public void getVideoOrientation_whenNaturalScreenOrientationEqualsLandscapeLeft() { DeviceOrientationManager orientationManager = new DeviceOrientationManager(mockActivity, false, 90, mockDeviceOrientationChangeCallback); int degreesPortraitUp = orientationManager.getVideoOrientation(DeviceOrientation.PORTRAIT_UP); int degreesPortraitDown = orientationManager.getVideoOrientation(DeviceOrientation.PORTRAIT_DOWN); int degreesLandscapeLeft = orientationManager.getVideoOrientation(DeviceOrientation.LANDSCAPE_LEFT); int degreesLandscapeRight = orientationManager.getVideoOrientation(DeviceOrientation.LANDSCAPE_RIGHT); assertEquals(90, degreesPortraitUp); assertEquals(0, degreesLandscapeLeft); assertEquals(270, degreesPortraitDown); assertEquals(180, degreesLandscapeRight); } @Test public void getVideoOrientation_fallbackToPortraitSensorOrientationWhenOrientationIsNull() { setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_0); int degrees = deviceOrientationManager.getVideoOrientation(null); assertEquals(0, degrees); } @Test public void getVideoOrientation_fallbackToLandscapeSensorOrientationWhenOrientationIsNull() { setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_0); DeviceOrientationManager orientationManager = new DeviceOrientationManager(mockActivity, false, 90, mockDeviceOrientationChangeCallback); int degrees = orientationManager.getVideoOrientation(null); assertEquals(0, degrees); } @Test public void getPhotoOrientation_whenNaturalScreenOrientationEqualsPortraitUp() { int degreesPortraitUp = deviceOrientationManager.getPhotoOrientation(DeviceOrientation.PORTRAIT_UP); int degreesPortraitDown = deviceOrientationManager.getPhotoOrientation(DeviceOrientation.PORTRAIT_DOWN); int degreesLandscapeLeft = deviceOrientationManager.getPhotoOrientation(DeviceOrientation.LANDSCAPE_LEFT); int degreesLandscapeRight = deviceOrientationManager.getPhotoOrientation(DeviceOrientation.LANDSCAPE_RIGHT); assertEquals(0, degreesPortraitUp); assertEquals(90, degreesLandscapeRight); assertEquals(180, degreesPortraitDown); assertEquals(270, degreesLandscapeLeft); } @Test public void getPhotoOrientation_whenNaturalScreenOrientationEqualsLandscapeLeft() { DeviceOrientationManager orientationManager = new DeviceOrientationManager(mockActivity, false, 90, mockDeviceOrientationChangeCallback); int degreesPortraitUp = orientationManager.getPhotoOrientation(DeviceOrientation.PORTRAIT_UP); int degreesPortraitDown = orientationManager.getPhotoOrientation(DeviceOrientation.PORTRAIT_DOWN); int degreesLandscapeLeft = orientationManager.getPhotoOrientation(DeviceOrientation.LANDSCAPE_LEFT); int degreesLandscapeRight = orientationManager.getPhotoOrientation(DeviceOrientation.LANDSCAPE_RIGHT); assertEquals(90, degreesPortraitUp); assertEquals(180, degreesLandscapeRight); assertEquals(270, degreesPortraitDown); assertEquals(0, degreesLandscapeLeft); } @Test public void getPhotoOrientation_shouldFallbackToCurrentOrientationWhenOrientationIsNull() { setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_0); int degrees = deviceOrientationManager.getPhotoOrientation(null); assertEquals(270, degrees); } @Test public void handleUIOrientationChange_shouldSendMessageWhenSensorAccessIsAllowed() { try (MockedStatic<Settings.System> mockedSystem = mockStatic(Settings.System.class)) { mockedSystem .when( () -> Settings.System.getInt(any(), eq(Settings.System.ACCELEROMETER_ROTATION), eq(0))) .thenReturn(0); setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_0); deviceOrientationManager.handleUIOrientationChange(); } verify(mockDeviceOrientationChangeCallback, times(1)) .onChange(DeviceOrientation.LANDSCAPE_LEFT); } @Test public void handleOrientationChange_shouldSendMessageWhenOrientationIsUpdated() { DeviceOrientation previousOrientation = DeviceOrientation.PORTRAIT_UP; DeviceOrientation newOrientation = DeviceOrientation.LANDSCAPE_LEFT; DeviceOrientationManager.handleOrientationChange( newOrientation, previousOrientation, mockDeviceOrientationChangeCallback); verify(mockDeviceOrientationChangeCallback, times(1)).onChange(newOrientation); } @Test public void handleOrientationChange_shouldNotSendMessageWhenOrientationIsNotUpdated() { DeviceOrientation previousOrientation = DeviceOrientation.PORTRAIT_UP; DeviceOrientation newOrientation = DeviceOrientation.PORTRAIT_UP; DeviceOrientationManager.handleOrientationChange( newOrientation, previousOrientation, mockDeviceOrientationChangeCallback); verify(mockDeviceOrientationChangeCallback, never()).onChange(any()); } @Test public void getUIOrientation() { // Orientation portrait and rotation of 0 should translate to "PORTRAIT_UP". setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_0); DeviceOrientation uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_UP, uiOrientation); // Orientation portrait and rotation of 90 should translate to "PORTRAIT_UP". setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_90); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_UP, uiOrientation); // Orientation portrait and rotation of 180 should translate to "PORTRAIT_DOWN". setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_180); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_DOWN, uiOrientation); // Orientation portrait and rotation of 270 should translate to "PORTRAIT_DOWN". setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_270); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_DOWN, uiOrientation); // Orientation landscape and rotation of 0 should translate to "LANDSCAPE_LEFT". setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_0); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.LANDSCAPE_LEFT, uiOrientation); // Orientation landscape and rotation of 90 should translate to "LANDSCAPE_LEFT". setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_90); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.LANDSCAPE_LEFT, uiOrientation); // Orientation landscape and rotation of 180 should translate to "LANDSCAPE_RIGHT". setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_180); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.LANDSCAPE_RIGHT, uiOrientation); // Orientation landscape and rotation of 270 should translate to "LANDSCAPE_RIGHT". setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_270); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.LANDSCAPE_RIGHT, uiOrientation); // Orientation undefined should default to "PORTRAIT_UP". setUpUIOrientationMocks(Configuration.ORIENTATION_UNDEFINED, Surface.ROTATION_0); uiOrientation = deviceOrientationManager.getUIOrientation(); assertEquals(DeviceOrientation.PORTRAIT_UP, uiOrientation); } @Test public void getDeviceDefaultOrientation() { setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_0); int orientation = deviceOrientationManager.getDeviceDefaultOrientation(); assertEquals(Configuration.ORIENTATION_PORTRAIT, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_180); orientation = deviceOrientationManager.getDeviceDefaultOrientation(); assertEquals(Configuration.ORIENTATION_PORTRAIT, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_90); orientation = deviceOrientationManager.getDeviceDefaultOrientation(); assertEquals(Configuration.ORIENTATION_LANDSCAPE, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_270); orientation = deviceOrientationManager.getDeviceDefaultOrientation(); assertEquals(Configuration.ORIENTATION_LANDSCAPE, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_0); orientation = deviceOrientationManager.getDeviceDefaultOrientation(); assertEquals(Configuration.ORIENTATION_LANDSCAPE, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_180); orientation = deviceOrientationManager.getDeviceDefaultOrientation(); assertEquals(Configuration.ORIENTATION_LANDSCAPE, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_90); orientation = deviceOrientationManager.getDeviceDefaultOrientation(); assertEquals(Configuration.ORIENTATION_PORTRAIT, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_LANDSCAPE, Surface.ROTATION_270); orientation = deviceOrientationManager.getDeviceDefaultOrientation(); assertEquals(Configuration.ORIENTATION_PORTRAIT, orientation); } @Test public void calculateSensorOrientation() { setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_0); DeviceOrientation orientation = deviceOrientationManager.calculateSensorOrientation(0); assertEquals(DeviceOrientation.PORTRAIT_UP, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_0); orientation = deviceOrientationManager.calculateSensorOrientation(90); assertEquals(DeviceOrientation.LANDSCAPE_LEFT, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_0); orientation = deviceOrientationManager.calculateSensorOrientation(180); assertEquals(DeviceOrientation.PORTRAIT_DOWN, orientation); setUpUIOrientationMocks(Configuration.ORIENTATION_PORTRAIT, Surface.ROTATION_0); orientation = deviceOrientationManager.calculateSensorOrientation(270); assertEquals(DeviceOrientation.LANDSCAPE_RIGHT, orientation); } private void setUpUIOrientationMocks(int orientation, int rotation) { Resources mockResources = mock(Resources.class); Configuration mockConfiguration = mock(Configuration.class); when(mockDisplay.getRotation()).thenReturn(rotation); mockConfiguration.orientation = orientation; when(mockActivity.getResources()).thenReturn(mockResources); when(mockResources.getConfiguration()).thenReturn(mockConfiguration); } @Test public void getDisplayTest() { Display display = deviceOrientationManager.getDisplay(); assertEquals(mockDisplay, display); } }
plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerTest.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerTest.java", "repo_id": "plugins", "token_count": 4584 }
1,251
name: camera_android_camerax_example description: Demonstrates how to use the camera_android_camerax plugin. publish_to: 'none' environment: sdk: '>=2.17.0 <3.0.0' flutter: ">=3.0.0" dependencies: camera_android_camerax: # When depending on this package from a real application you should use: # camera_android_camerax: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ camera_platform_interface: ^2.2.0 flutter: sdk: flutter video_player: ^2.4.10 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
plugins/packages/camera/camera_android_camerax/example/pubspec.yaml/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/example/pubspec.yaml", "repo_id": "plugins", "token_count": 293 }
1,252
// Mocks generated by Mockito 5.3.2 from annotations // in camera_android_camerax/test/system_services_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i4; 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: 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 [TestSystemServicesHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestSystemServicesHostApi extends _i1.Mock implements _i2.TestSystemServicesHostApi { MockTestSystemServicesHostApi() { _i1.throwOnMissingStub(this); } @override _i3.Future<_i4.CameraPermissionsErrorData?> requestCameraPermissions( bool? enableAudio) => (super.noSuchMethod( Invocation.method( #requestCameraPermissions, [enableAudio], ), returnValue: _i3.Future<_i4.CameraPermissionsErrorData?>.value(), ) as _i3.Future<_i4.CameraPermissionsErrorData?>); @override void startListeningForDeviceOrientationChange( bool? isFrontFacing, int? sensorOrientation, ) => super.noSuchMethod( Invocation.method( #startListeningForDeviceOrientationChange, [ isFrontFacing, sensorOrientation, ], ), returnValueForMissingStub: null, ); @override void stopListeningForDeviceOrientationChange() => super.noSuchMethod( Invocation.method( #stopListeningForDeviceOrientationChange, [], ), returnValueForMissingStub: null, ); }
plugins/packages/camera/camera_android_camerax/test/system_services_test.mocks.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/test/system_services_test.mocks.dart", "repo_id": "plugins", "token_count": 852 }
1,253
// 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 camera_avfoundation; @import camera_avfoundation.Test; @import AVFoundation; @import XCTest; #import <OCMock/OCMock.h> #import "CameraTestUtils.h" @interface CameraPermissionTests : XCTestCase @end @implementation CameraPermissionTests #pragma mark - camera permissions - (void)testRequestCameraPermission_completeWithoutErrorIfPrevoiuslyAuthorized { XCTestExpectation *expectation = [self expectationWithDescription: @"Must copmlete without error if camera access was previously authorized."]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusAuthorized); FLTRequestCameraPermissionWithCompletionHandler(^(FlutterError *error) { if (error == nil) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testRequestCameraPermission_completeWithErrorIfPreviouslyDenied { XCTestExpectation *expectation = [self expectationWithDescription: @"Must complete with error if camera access was previously denied."]; FlutterError *expectedError = [FlutterError errorWithCode:@"CameraAccessDeniedWithoutPrompt" message:@"User has previously denied the camera access request. Go to " @"Settings to enable camera access." details:nil]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusDenied); FLTRequestCameraPermissionWithCompletionHandler(^(FlutterError *error) { if ([error isEqual:expectedError]) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testRequestCameraPermission_completeWithErrorIfRestricted { XCTestExpectation *expectation = [self expectationWithDescription:@"Must complete with error if camera access is restricted."]; FlutterError *expectedError = [FlutterError errorWithCode:@"CameraAccessRestricted" message:@"Camera access is restricted. " details:nil]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusRestricted); FLTRequestCameraPermissionWithCompletionHandler(^(FlutterError *error) { if ([error isEqual:expectedError]) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testRequestCameraPermission_completeWithoutErrorIfUserGrantAccess { XCTestExpectation *grantedExpectation = [self expectationWithDescription:@"Must complete without error if user choose to grant access"]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusNotDetermined); // Mimic user choosing "allow" in permission dialog. OCMStub([mockDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:[OCMArg checkWithBlock:^BOOL(void (^block)(BOOL)) { block(YES); return YES; }]]); FLTRequestCameraPermissionWithCompletionHandler(^(FlutterError *error) { if (error == nil) { [grantedExpectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testRequestCameraPermission_completeWithErrorIfUserDenyAccess { XCTestExpectation *expectation = [self expectationWithDescription:@"Must complete with error if user choose to deny access"]; FlutterError *expectedError = [FlutterError errorWithCode:@"CameraAccessDenied" message:@"User denied the camera access request." details:nil]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeVideo]) .andReturn(AVAuthorizationStatusNotDetermined); // Mimic user choosing "deny" in permission dialog. OCMStub([mockDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:[OCMArg checkWithBlock:^BOOL(void (^block)(BOOL)) { block(NO); return YES; }]]); FLTRequestCameraPermissionWithCompletionHandler(^(FlutterError *error) { if ([error isEqual:expectedError]) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } #pragma mark - audio permissions - (void)testRequestAudioPermission_completeWithoutErrorIfPrevoiuslyAuthorized { XCTestExpectation *expectation = [self expectationWithDescription: @"Must copmlete without error if audio access was previously authorized."]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeAudio]) .andReturn(AVAuthorizationStatusAuthorized); FLTRequestAudioPermissionWithCompletionHandler(^(FlutterError *error) { if (error == nil) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testRequestAudioPermission_completeWithErrorIfPreviouslyDenied { XCTestExpectation *expectation = [self expectationWithDescription: @"Must complete with error if audio access was previously denied."]; FlutterError *expectedError = [FlutterError errorWithCode:@"AudioAccessDeniedWithoutPrompt" message:@"User has previously denied the audio access request. Go to " @"Settings to enable audio access." details:nil]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeAudio]) .andReturn(AVAuthorizationStatusDenied); FLTRequestAudioPermissionWithCompletionHandler(^(FlutterError *error) { if ([error isEqual:expectedError]) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testRequestAudioPermission_completeWithErrorIfRestricted { XCTestExpectation *expectation = [self expectationWithDescription:@"Must complete with error if audio access is restricted."]; FlutterError *expectedError = [FlutterError errorWithCode:@"AudioAccessRestricted" message:@"Audio access is restricted. " details:nil]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeAudio]) .andReturn(AVAuthorizationStatusRestricted); FLTRequestAudioPermissionWithCompletionHandler(^(FlutterError *error) { if ([error isEqual:expectedError]) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testRequestAudioPermission_completeWithoutErrorIfUserGrantAccess { XCTestExpectation *grantedExpectation = [self expectationWithDescription:@"Must complete without error if user choose to grant access"]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeAudio]) .andReturn(AVAuthorizationStatusNotDetermined); // Mimic user choosing "allow" in permission dialog. OCMStub([mockDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:[OCMArg checkWithBlock:^BOOL(void (^block)(BOOL)) { block(YES); return YES; }]]); FLTRequestAudioPermissionWithCompletionHandler(^(FlutterError *error) { if (error == nil) { [grantedExpectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testRequestAudioPermission_completeWithErrorIfUserDenyAccess { XCTestExpectation *expectation = [self expectationWithDescription:@"Must complete with error if user choose to deny access"]; FlutterError *expectedError = [FlutterError errorWithCode:@"AudioAccessDenied" message:@"User denied the audio access request." details:nil]; id mockDevice = OCMClassMock([AVCaptureDevice class]); OCMStub([mockDevice authorizationStatusForMediaType:AVMediaTypeAudio]) .andReturn(AVAuthorizationStatusNotDetermined); // Mimic user choosing "deny" in permission dialog. OCMStub([mockDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:[OCMArg checkWithBlock:^BOOL(void (^block)(BOOL)) { block(NO); return YES; }]]); FLTRequestAudioPermissionWithCompletionHandler(^(FlutterError *error) { if ([error isEqual:expectedError]) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } @end
plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPermissionTests.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPermissionTests.m", "repo_id": "plugins", "token_count": 3701 }
1,254
// 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 camera_avfoundation; @import XCTest; #import <OCMock/OCMock.h> @interface ThreadSafeMethodChannelTests : XCTestCase @end @implementation ThreadSafeMethodChannelTests - (void)testInvokeMethod_shouldStayOnMainThreadIfCalledFromMainThread { FlutterMethodChannel *mockMethodChannel = OCMClassMock([FlutterMethodChannel class]); FLTThreadSafeMethodChannel *threadSafeMethodChannel = [[FLTThreadSafeMethodChannel alloc] initWithMethodChannel:mockMethodChannel]; XCTestExpectation *mainThreadExpectation = [self expectationWithDescription:@"invokeMethod must be called on the main thread"]; OCMStub([mockMethodChannel invokeMethod:[OCMArg any] arguments:[OCMArg any]]) .andDo(^(NSInvocation *invocation) { if (NSThread.isMainThread) { [mainThreadExpectation fulfill]; } }); [threadSafeMethodChannel invokeMethod:@"foo" arguments:nil]; [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testInvokeMethod__shouldDispatchToMainThreadIfCalledFromBackgroundThread { FlutterMethodChannel *mockMethodChannel = OCMClassMock([FlutterMethodChannel class]); FLTThreadSafeMethodChannel *threadSafeMethodChannel = [[FLTThreadSafeMethodChannel alloc] initWithMethodChannel:mockMethodChannel]; XCTestExpectation *mainThreadExpectation = [self expectationWithDescription:@"invokeMethod must be called on the main thread"]; OCMStub([mockMethodChannel invokeMethod:[OCMArg any] arguments:[OCMArg any]]) .andDo(^(NSInvocation *invocation) { if (NSThread.isMainThread) { [mainThreadExpectation fulfill]; } }); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [threadSafeMethodChannel invokeMethod:@"foo" arguments:nil]; }); [self waitForExpectationsWithTimeout:1 handler:nil]; } @end
plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeMethodChannelTests.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeMethodChannelTests.m", "repo_id": "plugins", "token_count": 668 }
1,255
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import AVFoundation; @import Foundation; @import Flutter; #import "CameraProperties.h" #import "FLTThreadSafeEventChannel.h" #import "FLTThreadSafeFlutterResult.h" #import "FLTThreadSafeMethodChannel.h" #import "FLTThreadSafeTextureRegistry.h" NS_ASSUME_NONNULL_BEGIN /** * A class that manages camera's state and performs camera operations. */ @interface FLTCam : NSObject <FlutterTexture> @property(readonly, nonatomic) AVCaptureDevice *captureDevice; @property(readonly, nonatomic) CGSize previewSize; @property(assign, nonatomic) BOOL isPreviewPaused; @property(nonatomic, copy) void (^onFrameAvailable)(void); @property(nonatomic) FLTThreadSafeMethodChannel *methodChannel; @property(assign, nonatomic) FLTResolutionPreset resolutionPreset; @property(assign, nonatomic) FLTExposureMode exposureMode; @property(assign, nonatomic) FLTFocusMode focusMode; @property(assign, nonatomic) FLTFlashMode flashMode; // Format used for video and image streaming. @property(assign, nonatomic) FourCharCode videoFormat; /// Initializes an `FLTCam` instance. /// @param cameraName a name used to uniquely identify the camera. /// @param resolutionPreset the resolution preset /// @param enableAudio YES if audio should be enabled for video capturing; NO otherwise. /// @param orientation the orientation of camera /// @param captureSessionQueue the queue on which camera's capture session operations happen. /// @param error report to the caller if any error happened creating the camera. - (instancetype)initWithCameraName:(NSString *)cameraName resolutionPreset:(NSString *)resolutionPreset enableAudio:(BOOL)enableAudio orientation:(UIDeviceOrientation)orientation captureSessionQueue:(dispatch_queue_t)captureSessionQueue error:(NSError **)error; - (void)start; - (void)stop; - (void)setDeviceOrientation:(UIDeviceOrientation)orientation; - (void)captureToFile:(FLTThreadSafeFlutterResult *)result API_AVAILABLE(ios(10)); - (void)close; - (void)startVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result; /** * Starts recording a video with an optional streaming messenger. * If the messenger is non-null then it will be called for each * captured frame, allowing streaming concurrently with recording. * * @param messenger Nullable messenger for capturing each frame. */ - (void)startVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result messengerForStreaming:(nullable NSObject<FlutterBinaryMessenger> *)messenger; - (void)stopVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result; - (void)pauseVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result; - (void)resumeVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result; - (void)lockCaptureOrientationWithResult:(FLTThreadSafeFlutterResult *)result orientation:(NSString *)orientationStr; - (void)unlockCaptureOrientationWithResult:(FLTThreadSafeFlutterResult *)result; - (void)setFlashModeWithResult:(FLTThreadSafeFlutterResult *)result mode:(NSString *)modeStr; - (void)setExposureModeWithResult:(FLTThreadSafeFlutterResult *)result mode:(NSString *)modeStr; - (void)setFocusModeWithResult:(FLTThreadSafeFlutterResult *)result mode:(NSString *)modeStr; - (void)applyFocusMode; /** * Acknowledges the receipt of one image stream frame. * * This should be called each time a frame is received. Failing to call it may * cause later frames to be dropped instead of streamed. */ - (void)receivedImageStreamData; /** * Applies FocusMode on the AVCaptureDevice. * * If the @c focusMode is set to FocusModeAuto the AVCaptureDevice is configured to use * AVCaptureFocusModeContinuousModeAutoFocus when supported, otherwise it is set to * AVCaptureFocusModeAutoFocus. If neither AVCaptureFocusModeContinuousModeAutoFocus nor * AVCaptureFocusModeAutoFocus are supported focus mode will not be set. * If @c focusMode is set to FocusModeLocked the AVCaptureDevice is configured to use * AVCaptureFocusModeAutoFocus. If AVCaptureFocusModeAutoFocus is not supported focus mode will not * be set. * * @param focusMode The focus mode that should be applied to the @captureDevice instance. * @param captureDevice The AVCaptureDevice to which the @focusMode will be applied. */ - (void)applyFocusMode:(FLTFocusMode)focusMode onDevice:(AVCaptureDevice *)captureDevice; - (void)pausePreviewWithResult:(FLTThreadSafeFlutterResult *)result; - (void)resumePreviewWithResult:(FLTThreadSafeFlutterResult *)result; - (void)setExposurePointWithResult:(FLTThreadSafeFlutterResult *)result x:(double)x y:(double)y; - (void)setFocusPointWithResult:(FLTThreadSafeFlutterResult *)result x:(double)x y:(double)y; - (void)setExposureOffsetWithResult:(FLTThreadSafeFlutterResult *)result offset:(double)offset; - (void)startImageStreamWithMessenger:(NSObject<FlutterBinaryMessenger> *)messenger; - (void)stopImageStream; - (void)getMaxZoomLevelWithResult:(FLTThreadSafeFlutterResult *)result; - (void)getMinZoomLevelWithResult:(FLTThreadSafeFlutterResult *)result; - (void)setZoomLevel:(CGFloat)zoom Result:(FLTThreadSafeFlutterResult *)result; - (void)setUpCaptureSessionForAudio; @end NS_ASSUME_NONNULL_END
plugins/packages/camera/camera_avfoundation/ios/Classes/FLTCam.h/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTCam.h", "repo_id": "plugins", "token_count": 1639 }
1,256
// 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; import '../../camera_platform_interface.dart'; /// Generic Event coming from the native side of Camera, /// related to a specific camera module. /// /// All [CameraEvent]s contain the `cameraId` that originated the event. This /// should never be `null`. /// /// This class is used as a base class for all the events that might be /// triggered from a Camera, but it is never used directly as an event type. /// /// Do NOT instantiate new events like `CameraEvent(cameraId)` directly, /// use a specific class instead: /// /// Do `class NewEvent extend CameraEvent` when creating your own events. /// See below for examples: `CameraClosingEvent`, `CameraErrorEvent`... /// These events are more semantic and more pleasant to use than raw generics. /// They can be (and in fact, are) filtered by the `instanceof`-operator. @immutable abstract class CameraEvent { /// Build a Camera Event, that relates a `cameraId`. /// /// The `cameraId` is the ID of the camera that triggered the event. const CameraEvent(this.cameraId) : assert(cameraId != null); /// The ID of the Camera this event is associated to. final int cameraId; @override bool operator ==(Object other) => identical(this, other) || other is CameraEvent && runtimeType == other.runtimeType && cameraId == other.cameraId; @override int get hashCode => cameraId.hashCode; } /// An event fired when the camera has finished initializing. class CameraInitializedEvent extends CameraEvent { /// Build a CameraInitialized event triggered from the camera represented by /// `cameraId`. /// /// The `previewWidth` represents the width of the generated preview in pixels. /// The `previewHeight` represents the height of the generated preview in pixels. const CameraInitializedEvent( int cameraId, this.previewWidth, this.previewHeight, this.exposureMode, this.exposurePointSupported, this.focusMode, this.focusPointSupported, ) : super(cameraId); /// Converts the supplied [Map] to an instance of the [CameraInitializedEvent] /// class. CameraInitializedEvent.fromJson(Map<String, dynamic> json) : previewWidth = json['previewWidth']! as double, previewHeight = json['previewHeight']! as double, exposureMode = deserializeExposureMode(json['exposureMode']! as String), exposurePointSupported = (json['exposurePointSupported'] as bool?) ?? false, focusMode = deserializeFocusMode(json['focusMode']! as String), focusPointSupported = (json['focusPointSupported'] as bool?) ?? false, super(json['cameraId']! as int); /// The width of the preview in pixels. final double previewWidth; /// The height of the preview in pixels. final double previewHeight; /// The default exposure mode final ExposureMode exposureMode; /// The default focus mode final FocusMode focusMode; /// Whether setting exposure points is supported. final bool exposurePointSupported; /// Whether setting focus points is supported. final bool focusPointSupported; /// Converts the [CameraInitializedEvent] instance into a [Map] instance that /// can be serialized to JSON. Map<String, dynamic> toJson() => <String, Object>{ 'cameraId': cameraId, 'previewWidth': previewWidth, 'previewHeight': previewHeight, 'exposureMode': serializeExposureMode(exposureMode), 'exposurePointSupported': exposurePointSupported, 'focusMode': serializeFocusMode(focusMode), 'focusPointSupported': focusPointSupported, }; @override bool operator ==(Object other) => identical(this, other) || super == other && other is CameraInitializedEvent && runtimeType == other.runtimeType && previewWidth == other.previewWidth && previewHeight == other.previewHeight && exposureMode == other.exposureMode && exposurePointSupported == other.exposurePointSupported && focusMode == other.focusMode && focusPointSupported == other.focusPointSupported; @override int get hashCode => Object.hash( super.hashCode, previewWidth, previewHeight, exposureMode, exposurePointSupported, focusMode, focusPointSupported, ); } /// An event fired when the resolution preset of the camera has changed. class CameraResolutionChangedEvent extends CameraEvent { /// Build a CameraResolutionChanged event triggered from the camera /// represented by `cameraId`. /// /// The `captureWidth` represents the width of the resulting image in pixels. /// The `captureHeight` represents the height of the resulting image in pixels. const CameraResolutionChangedEvent( int cameraId, this.captureWidth, this.captureHeight, ) : super(cameraId); /// Converts the supplied [Map] to an instance of the /// [CameraResolutionChangedEvent] class. CameraResolutionChangedEvent.fromJson(Map<String, dynamic> json) : captureWidth = json['captureWidth']! as double, captureHeight = json['captureHeight']! as double, super(json['cameraId']! as int); /// The capture width in pixels. final double captureWidth; /// The capture height in pixels. final double captureHeight; /// Converts the [CameraResolutionChangedEvent] instance into a [Map] instance /// that can be serialized to JSON. Map<String, dynamic> toJson() => <String, Object>{ 'cameraId': cameraId, 'captureWidth': captureWidth, 'captureHeight': captureHeight, }; @override bool operator ==(Object other) => identical(this, other) || other is CameraResolutionChangedEvent && super == other && runtimeType == other.runtimeType && captureWidth == other.captureWidth && captureHeight == other.captureHeight; @override int get hashCode => Object.hash(super.hashCode, captureWidth, captureHeight); } /// An event fired when the camera is going to close. class CameraClosingEvent extends CameraEvent { /// Build a CameraClosing event triggered from the camera represented by /// `cameraId`. const CameraClosingEvent(int cameraId) : super(cameraId); /// Converts the supplied [Map] to an instance of the [CameraClosingEvent] /// class. CameraClosingEvent.fromJson(Map<String, dynamic> json) : super(json['cameraId']! as int); /// Converts the [CameraClosingEvent] instance into a [Map] instance that can /// be serialized to JSON. Map<String, dynamic> toJson() => <String, Object>{ 'cameraId': cameraId, }; @override bool operator ==(Object other) => identical(this, other) || super == other && other is CameraClosingEvent && runtimeType == other.runtimeType; @override // This is here even though it just calls super to make it less likely that // operator== would be changed without changing `hashCode`. // ignore: unnecessary_overrides int get hashCode => super.hashCode; } /// An event fired when an error occured while operating the camera. class CameraErrorEvent extends CameraEvent { /// Build a CameraError event triggered from the camera represented by /// `cameraId`. /// /// The `description` represents the error occured on the camera. const CameraErrorEvent(int cameraId, this.description) : super(cameraId); /// Converts the supplied [Map] to an instance of the [CameraErrorEvent] /// class. CameraErrorEvent.fromJson(Map<String, dynamic> json) : description = json['description']! as String, super(json['cameraId']! as int); /// Description of the error. final String description; /// Converts the [CameraErrorEvent] instance into a [Map] instance that can be /// serialized to JSON. Map<String, dynamic> toJson() => <String, Object>{ 'cameraId': cameraId, 'description': description, }; @override bool operator ==(Object other) => identical(this, other) || super == other && other is CameraErrorEvent && runtimeType == other.runtimeType && description == other.description; @override int get hashCode => Object.hash(super.hashCode, description); } /// An event fired when a video has finished recording. class VideoRecordedEvent extends CameraEvent { /// Build a VideoRecordedEvent triggered from the camera with the `cameraId`. /// /// The `file` represents the file of the video. /// The `maxVideoDuration` shows if a maxVideoDuration shows if a maximum /// video duration was set. const VideoRecordedEvent(int cameraId, this.file, this.maxVideoDuration) : super(cameraId); /// Converts the supplied [Map] to an instance of the [VideoRecordedEvent] /// class. VideoRecordedEvent.fromJson(Map<String, dynamic> json) : file = XFile(json['path']! as String), maxVideoDuration = json['maxVideoDuration'] != null ? Duration(milliseconds: json['maxVideoDuration'] as int) : null, super(json['cameraId']! as int); /// XFile of the recorded video. final XFile file; /// Maximum duration of the recorded video. final Duration? maxVideoDuration; /// Converts the [VideoRecordedEvent] instance into a [Map] instance that can be /// serialized to JSON. Map<String, dynamic> toJson() => <String, Object?>{ 'cameraId': cameraId, 'path': file.path, 'maxVideoDuration': maxVideoDuration?.inMilliseconds }; @override bool operator ==(Object other) => identical(this, other) || super == other && other is VideoRecordedEvent && runtimeType == other.runtimeType && maxVideoDuration == other.maxVideoDuration; @override int get hashCode => Object.hash(super.hashCode, file, maxVideoDuration); }
plugins/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart/0
{ "file_path": "plugins/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart", "repo_id": "plugins", "token_count": 3178 }
1,257
name: camera_platform_interface description: A common platform interface for the camera plugin. repository: https://github.com/flutter/plugins/tree/main/packages/camera/camera_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 # NOTE: We strongly prefer non-breaking changes, even at the expense of a # less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes version: 2.4.0 environment: sdk: '>=2.12.0 <3.0.0' flutter: ">=3.0.0" dependencies: cross_file: ^0.3.1 flutter: sdk: flutter plugin_platform_interface: ^2.1.0 stream_transform: ^2.0.0 dev_dependencies: async: ^2.5.0 flutter_test: sdk: flutter
plugins/packages/camera/camera_platform_interface/pubspec.yaml/0
{ "file_path": "plugins/packages/camera/camera_platform_interface/pubspec.yaml", "repo_id": "plugins", "token_count": 275 }
1,258
name: camera_web_integration_tests publish_to: none environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter dev_dependencies: async: ^2.5.0 camera_platform_interface: ^2.1.0 camera_web: path: ../ cross_file: ^0.3.1 flutter_driver: sdk: flutter flutter_test: sdk: flutter integration_test: sdk: flutter mocktail: ^0.3.0
plugins/packages/camera/camera_web/example/pubspec.yaml/0
{ "file_path": "plugins/packages/camera/camera_web/example/pubspec.yaml", "repo_id": "plugins", "token_count": 190 }
1,259
// 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. /// A kind of a media device. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/kind abstract class MediaDeviceKind { /// A video input media device kind. static const String videoInput = 'videoinput'; /// An audio input media device kind. static const String audioInput = 'audioinput'; /// An audio output media device kind. static const String audioOutput = 'audiooutput'; }
plugins/packages/camera/camera_web/lib/src/types/media_device_kind.dart/0
{ "file_path": "plugins/packages/camera/camera_web/lib/src/types/media_device_kind.dart", "repo_id": "plugins", "token_count": 158 }
1,260
// 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:async/async.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; // Note that these integration tests do not currently cover // most features and code paths, as they can only be tested if // one or more cameras are available in the test environment. // Native unit tests with better coverage are available at // the native part of the plugin implementation. void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('initializeCamera', () { testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; expect(() async => camera.initializeCamera(1234), throwsA(isA<CameraException>())); }); }); group('takePicture', () { testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; expect(() async => camera.takePicture(1234), throwsA(isA<PlatformException>())); }); }); group('startVideoRecording', () { testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; expect(() async => camera.startVideoRecording(1234), throwsA(isA<PlatformException>())); }); }); group('stopVideoRecording', () { testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; expect(() async => camera.stopVideoRecording(1234), throwsA(isA<PlatformException>())); }); }); group('pausePreview', () { testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; expect(() async => camera.pausePreview(1234), throwsA(isA<PlatformException>())); }); }); group('resumePreview', () { testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; expect(() async => camera.resumePreview(1234), throwsA(isA<PlatformException>())); }); }); group('onDeviceOrientationChanged', () { testWidgets('emits the initial DeviceOrientationChangedEvent', (WidgetTester _) async { final Stream<DeviceOrientationChangedEvent> eventStream = CameraPlatform.instance.onDeviceOrientationChanged(); final StreamQueue<DeviceOrientationChangedEvent> streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream); expect( await streamQueue.next, equals( const DeviceOrientationChangedEvent( DeviceOrientation.landscapeRight, ), ), ); }); }); }
plugins/packages/camera/camera_windows/example/integration_test/camera_test.dart/0
{ "file_path": "plugins/packages/camera/camera_windows/example/integration_test/camera_test.dart", "repo_id": "plugins", "token_count": 1112 }
1,261
// 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. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_H_ #include <d3d11.h> #include <flutter/texture_registrar.h> #include <mfapi.h> #include <mfcaptureengine.h> #include <mferror.h> #include <mfidl.h> #include <windows.h> #include <wrl/client.h> #include <memory> #include <string> #include "capture_controller_listener.h" #include "capture_engine_listener.h" #include "photo_handler.h" #include "preview_handler.h" #include "record_handler.h" #include "texture_handler.h" namespace camera_windows { using flutter::TextureRegistrar; using Microsoft::WRL::ComPtr; // Camera resolution presets. Used to request a capture resolution. enum class ResolutionPreset { // Automatic resolution, uses the highest resolution available. kAuto, // 240p (320x240) kLow, // 480p (720x480) kMedium, // 720p (1280x720) kHigh, // 1080p (1920x1080) kVeryHigh, // 2160p (4096x2160) kUltraHigh, // The highest resolution available. kMax, }; // Camera capture engine state. // // On creation, |CaptureControllers| start in state |kNotInitialized|. // On initialization, the capture controller transitions to the |kInitializing| // and then |kInitialized| state. enum class CaptureEngineState { kNotInitialized, kInitializing, kInitialized }; // Interface for a class that enumerates video capture device sources. class VideoCaptureDeviceEnumerator { private: virtual bool EnumerateVideoCaptureDeviceSources(IMFActivate*** devices, UINT32* count) = 0; }; // Interface implemented by capture controllers. // // Capture controllers are used to capture video streams or still photos from // their associated |Camera|. class CaptureController { public: CaptureController() {} virtual ~CaptureController() = default; // Disallow copy and move. CaptureController(const CaptureController&) = delete; CaptureController& operator=(const CaptureController&) = delete; // Initializes the capture controller with the specified device id. // // Returns false if the capture controller could not be initialized // or is already initialized. // // texture_registrar: Pointer to Flutter TextureRegistrar instance. Used to // register texture for capture preview. // device_id: A string that holds information of camera device id to // be captured. // record_audio: A boolean value telling if audio should be captured on // video recording. // resolution_preset: Maximum capture resolution height. virtual bool InitCaptureDevice(TextureRegistrar* texture_registrar, const std::string& device_id, bool record_audio, ResolutionPreset resolution_preset) = 0; // Returns preview frame width virtual uint32_t GetPreviewWidth() const = 0; // Returns preview frame height virtual uint32_t GetPreviewHeight() const = 0; // Starts the preview. virtual void StartPreview() = 0; // Pauses the preview. virtual void PausePreview() = 0; // Resumes the preview. virtual void ResumePreview() = 0; // Starts recording video. virtual void StartRecord(const std::string& file_path, int64_t max_video_duration_ms) = 0; // Stops the current video recording. virtual void StopRecord() = 0; // Captures a still photo. virtual void TakePicture(const std::string& file_path) = 0; }; // Concrete implementation of the |CaptureController| interface. // // Handles the video preview stream via a |PreviewHandler| instance, video // capture via a |RecordHandler| instance, and still photo capture via a // |PhotoHandler| instance. class CaptureControllerImpl : public CaptureController, public CaptureEngineObserver { public: static bool EnumerateVideoCaptureDeviceSources(IMFActivate*** devices, UINT32* count); explicit CaptureControllerImpl(CaptureControllerListener* listener); virtual ~CaptureControllerImpl(); // Disallow copy and move. CaptureControllerImpl(const CaptureControllerImpl&) = delete; CaptureControllerImpl& operator=(const CaptureControllerImpl&) = delete; // CaptureController bool InitCaptureDevice(TextureRegistrar* texture_registrar, const std::string& device_id, bool record_audio, ResolutionPreset resolution_preset) override; uint32_t GetPreviewWidth() const override { return preview_frame_width_; } uint32_t GetPreviewHeight() const override { return preview_frame_height_; } void StartPreview() override; void PausePreview() override; void ResumePreview() override; void StartRecord(const std::string& file_path, int64_t max_video_duration_ms) override; void StopRecord() override; void TakePicture(const std::string& file_path) override; // CaptureEngineObserver void OnEvent(IMFMediaEvent* event) override; bool IsReadyForSample() const override { return capture_engine_state_ == CaptureEngineState::kInitialized && preview_handler_ && preview_handler_->IsRunning(); } bool UpdateBuffer(uint8_t* data, uint32_t data_length) override; void UpdateCaptureTime(uint64_t capture_time) override; // Sets capture engine, for testing purposes. void SetCaptureEngine(IMFCaptureEngine* capture_engine) { capture_engine_ = capture_engine; } // Sets video source, for testing purposes. void SetVideoSource(IMFMediaSource* video_source) { video_source_ = video_source; } // Sets audio source, for testing purposes. void SetAudioSource(IMFMediaSource* audio_source) { audio_source_ = audio_source; } private: // Helper function to return initialized state as boolean; bool IsInitialized() const { return capture_engine_state_ == CaptureEngineState::kInitialized; } // Resets capture controller state. // This is called if capture engine creation fails or is disposed. void ResetCaptureController(); // Returns max preview height calculated from resolution present. uint32_t GetMaxPreviewHeight() const; // Uses first audio source to capture audio. // Note: Enumerating audio sources via platform interface is not supported. HRESULT CreateDefaultAudioCaptureSource(); // Initializes video capture source from camera device. HRESULT CreateVideoCaptureSourceForDevice(const std::string& video_device_id); // Creates DX11 Device and D3D Manager. HRESULT CreateD3DManagerWithDX11Device(); // Initializes capture engine object. HRESULT CreateCaptureEngine(); // Enumerates video_sources media types and finds out best resolution // for preview and video capture. HRESULT FindBaseMediaTypes(); // Stops timed video record. Called internally when record handler when max // recording time is exceeded. void StopTimedRecord(); // Stops preview. Called internally on camera reset and dispose. HRESULT StopPreview(); // Handles capture engine initalization event. void OnCaptureEngineInitialized(CameraResult result, const std::string& error); // Handles capture engine errors. void OnCaptureEngineError(CameraResult result, const std::string& error); // Handles picture events. void OnPicture(CameraResult result, const std::string& error); // Handles preview started events. void OnPreviewStarted(CameraResult result, const std::string& error); // Handles preview stopped events. void OnPreviewStopped(CameraResult result, const std::string& error); // Handles record started events. void OnRecordStarted(CameraResult result, const std::string& error); // Handles record stopped events. void OnRecordStopped(CameraResult result, const std::string& error); bool media_foundation_started_ = false; bool record_audio_ = false; uint32_t preview_frame_width_ = 0; uint32_t preview_frame_height_ = 0; UINT dx_device_reset_token_ = 0; std::unique_ptr<RecordHandler> record_handler_; std::unique_ptr<PreviewHandler> preview_handler_; std::unique_ptr<PhotoHandler> photo_handler_; std::unique_ptr<TextureHandler> texture_handler_; CaptureControllerListener* capture_controller_listener_; std::string video_device_id_; CaptureEngineState capture_engine_state_ = CaptureEngineState::kNotInitialized; ResolutionPreset resolution_preset_ = ResolutionPreset::kMedium; ComPtr<IMFCaptureEngine> capture_engine_; ComPtr<CaptureEngineListener> capture_engine_callback_handler_; ComPtr<IMFDXGIDeviceManager> dxgi_device_manager_; ComPtr<ID3D11Device> dx11_device_; ComPtr<IMFMediaType> base_capture_media_type_; ComPtr<IMFMediaType> base_preview_media_type_; ComPtr<IMFMediaSource> video_source_; ComPtr<IMFMediaSource> audio_source_; TextureRegistrar* texture_registrar_ = nullptr; }; // Inferface for factory classes that create |CaptureController| instances. class CaptureControllerFactory { public: CaptureControllerFactory() {} virtual ~CaptureControllerFactory() = default; // Disallow copy and move. CaptureControllerFactory(const CaptureControllerFactory&) = delete; CaptureControllerFactory& operator=(const CaptureControllerFactory&) = delete; // Create and return a |CaptureController| that makes callbacks on the // specified |CaptureControllerListener|, which must not be null. virtual std::unique_ptr<CaptureController> CreateCaptureController( CaptureControllerListener* listener) = 0; }; // Concreate implementation of |CaptureControllerFactory|. class CaptureControllerFactoryImpl : public CaptureControllerFactory { public: CaptureControllerFactoryImpl() {} virtual ~CaptureControllerFactoryImpl() = default; // Disallow copy and move. CaptureControllerFactoryImpl(const CaptureControllerFactoryImpl&) = delete; CaptureControllerFactoryImpl& operator=(const CaptureControllerFactoryImpl&) = delete; std::unique_ptr<CaptureController> CreateCaptureController( CaptureControllerListener* listener) override { return std::make_unique<CaptureControllerImpl>(listener); } }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_H_
plugins/packages/camera/camera_windows/windows/capture_controller.h/0
{ "file_path": "plugins/packages/camera/camera_windows/windows/capture_controller.h", "repo_id": "plugins", "token_count": 3256 }
1,262
// 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 "camera_plugin.h" #include <flutter/method_call.h> #include <flutter/method_result_functions.h> #include <flutter/standard_method_codec.h> #include <flutter/texture_registrar.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <windows.h> #include <functional> #include <memory> #include <string> #include "mocks.h" namespace camera_windows { namespace test { using flutter::EncodableMap; using flutter::EncodableValue; using ::testing::_; using ::testing::DoAll; using ::testing::EndsWith; using ::testing::Eq; using ::testing::Pointee; using ::testing::Return; void MockInitCamera(MockCamera* camera, bool success) { EXPECT_CALL(*camera, HasPendingResultByType(Eq(PendingResultType::kCreateCamera))) .Times(1) .WillOnce(Return(false)); EXPECT_CALL(*camera, AddPendingResult(Eq(PendingResultType::kCreateCamera), _)) .Times(1) .WillOnce([camera](PendingResultType type, std::unique_ptr<MethodResult<>> result) { camera->pending_result_ = std::move(result); return true; }); EXPECT_CALL(*camera, HasDeviceId(Eq(camera->device_id_))) .WillRepeatedly(Return(true)); EXPECT_CALL(*camera, InitCamera) .Times(1) .WillOnce([camera, success](flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset) { assert(camera->pending_result_); if (success) { camera->pending_result_->Success(EncodableValue(1)); return true; } else { camera->pending_result_->Error("camera_error", "InitCamera failed."); return false; } }); } TEST(CameraPlugin, AvailableCamerasHandlerSuccessIfNoCameras) { std::unique_ptr<MockTextureRegistrar> texture_registrar_ = std::make_unique<MockTextureRegistrar>(); std::unique_ptr<MockBinaryMessenger> messenger_ = std::make_unique<MockBinaryMessenger>(); std::unique_ptr<MockCameraFactory> camera_factory_ = std::make_unique<MockCameraFactory>(); std::unique_ptr<MockMethodResult> result = std::make_unique<MockMethodResult>(); MockCameraPlugin plugin(texture_registrar_.get(), messenger_.get(), std::move(camera_factory_)); EXPECT_CALL(plugin, EnumerateVideoCaptureDeviceSources) .Times(1) .WillOnce([](IMFActivate*** devices, UINT32* count) { *count = 0U; *devices = static_cast<IMFActivate**>( CoTaskMemAlloc(sizeof(IMFActivate*) * (*count))); return true; }); EXPECT_CALL(*result, ErrorInternal).Times(0); EXPECT_CALL(*result, SuccessInternal).Times(1); plugin.HandleMethodCall( flutter::MethodCall("availableCameras", std::make_unique<EncodableValue>()), std::move(result)); } TEST(CameraPlugin, AvailableCamerasHandlerErrorIfFailsToEnumerateDevices) { std::unique_ptr<MockTextureRegistrar> texture_registrar_ = std::make_unique<MockTextureRegistrar>(); std::unique_ptr<MockBinaryMessenger> messenger_ = std::make_unique<MockBinaryMessenger>(); std::unique_ptr<MockCameraFactory> camera_factory_ = std::make_unique<MockCameraFactory>(); std::unique_ptr<MockMethodResult> result = std::make_unique<MockMethodResult>(); MockCameraPlugin plugin(texture_registrar_.get(), messenger_.get(), std::move(camera_factory_)); EXPECT_CALL(plugin, EnumerateVideoCaptureDeviceSources) .Times(1) .WillOnce([](IMFActivate*** devices, UINT32* count) { return false; }); EXPECT_CALL(*result, ErrorInternal).Times(1); EXPECT_CALL(*result, SuccessInternal).Times(0); plugin.HandleMethodCall( flutter::MethodCall("availableCameras", std::make_unique<EncodableValue>()), std::move(result)); } TEST(CameraPlugin, CreateHandlerCallsInitCamera) { std::unique_ptr<MockMethodResult> result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockTextureRegistrar> texture_registrar_ = std::make_unique<MockTextureRegistrar>(); std::unique_ptr<MockBinaryMessenger> messenger_ = std::make_unique<MockBinaryMessenger>(); std::unique_ptr<MockCameraFactory> camera_factory_ = std::make_unique<MockCameraFactory>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); MockInitCamera(camera.get(), true); // Move mocked camera to the factory to be passed // for plugin with CreateCamera function. camera_factory_->pending_camera_ = std::move(camera); EXPECT_CALL(*camera_factory_, CreateCamera(MOCK_DEVICE_ID)); EXPECT_CALL(*result, ErrorInternal).Times(0); EXPECT_CALL(*result, SuccessInternal(Pointee(EncodableValue(1)))); CameraPlugin plugin(texture_registrar_.get(), messenger_.get(), std::move(camera_factory_)); EncodableMap args = { {EncodableValue("cameraName"), EncodableValue(MOCK_CAMERA_NAME)}, {EncodableValue("resolutionPreset"), EncodableValue(nullptr)}, {EncodableValue("enableAudio"), EncodableValue(true)}, }; plugin.HandleMethodCall( flutter::MethodCall("create", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(result)); } TEST(CameraPlugin, CreateHandlerErrorOnInvalidDeviceId) { std::unique_ptr<MockMethodResult> result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockTextureRegistrar> texture_registrar_ = std::make_unique<MockTextureRegistrar>(); std::unique_ptr<MockBinaryMessenger> messenger_ = std::make_unique<MockBinaryMessenger>(); std::unique_ptr<MockCameraFactory> camera_factory_ = std::make_unique<MockCameraFactory>(); CameraPlugin plugin(texture_registrar_.get(), messenger_.get(), std::move(camera_factory_)); EncodableMap args = { {EncodableValue("cameraName"), EncodableValue(MOCK_INVALID_CAMERA_NAME)}, {EncodableValue("resolutionPreset"), EncodableValue(nullptr)}, {EncodableValue("enableAudio"), EncodableValue(true)}, }; EXPECT_CALL(*result, ErrorInternal).Times(1); plugin.HandleMethodCall( flutter::MethodCall("create", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(result)); } TEST(CameraPlugin, CreateHandlerErrorOnExistingDeviceId) { std::unique_ptr<MockMethodResult> first_create_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockMethodResult> second_create_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockTextureRegistrar> texture_registrar_ = std::make_unique<MockTextureRegistrar>(); std::unique_ptr<MockBinaryMessenger> messenger_ = std::make_unique<MockBinaryMessenger>(); std::unique_ptr<MockCameraFactory> camera_factory_ = std::make_unique<MockCameraFactory>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); MockInitCamera(camera.get(), true); // Move mocked camera to the factory to be passed // for plugin with CreateCamera function. camera_factory_->pending_camera_ = std::move(camera); EXPECT_CALL(*camera_factory_, CreateCamera(MOCK_DEVICE_ID)); EXPECT_CALL(*first_create_result, ErrorInternal).Times(0); EXPECT_CALL(*first_create_result, SuccessInternal(Pointee(EncodableValue(1)))); CameraPlugin plugin(texture_registrar_.get(), messenger_.get(), std::move(camera_factory_)); EncodableMap args = { {EncodableValue("cameraName"), EncodableValue(MOCK_CAMERA_NAME)}, {EncodableValue("resolutionPreset"), EncodableValue(nullptr)}, {EncodableValue("enableAudio"), EncodableValue(true)}, }; plugin.HandleMethodCall( flutter::MethodCall("create", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(first_create_result)); EXPECT_CALL(*second_create_result, ErrorInternal).Times(1); EXPECT_CALL(*second_create_result, SuccessInternal).Times(0); plugin.HandleMethodCall( flutter::MethodCall("create", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(second_create_result)); } TEST(CameraPlugin, CreateHandlerAllowsRetry) { std::unique_ptr<MockMethodResult> first_create_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockMethodResult> second_create_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockTextureRegistrar> texture_registrar_ = std::make_unique<MockTextureRegistrar>(); std::unique_ptr<MockBinaryMessenger> messenger_ = std::make_unique<MockBinaryMessenger>(); std::unique_ptr<MockCameraFactory> camera_factory_ = std::make_unique<MockCameraFactory>(); // The camera will fail initialization once and then succeed. EXPECT_CALL(*camera_factory_, CreateCamera(MOCK_DEVICE_ID)) .Times(2) .WillOnce([](const std::string& device_id) { std::unique_ptr<MockCamera> first_camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); MockInitCamera(first_camera.get(), false); return first_camera; }) .WillOnce([](const std::string& device_id) { std::unique_ptr<MockCamera> second_camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); MockInitCamera(second_camera.get(), true); return second_camera; }); EXPECT_CALL(*first_create_result, ErrorInternal).Times(1); EXPECT_CALL(*first_create_result, SuccessInternal).Times(0); CameraPlugin plugin(texture_registrar_.get(), messenger_.get(), std::move(camera_factory_)); EncodableMap args = { {EncodableValue("cameraName"), EncodableValue(MOCK_CAMERA_NAME)}, {EncodableValue("resolutionPreset"), EncodableValue(nullptr)}, {EncodableValue("enableAudio"), EncodableValue(true)}, }; plugin.HandleMethodCall( flutter::MethodCall("create", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(first_create_result)); EXPECT_CALL(*second_create_result, ErrorInternal).Times(0); EXPECT_CALL(*second_create_result, SuccessInternal(Pointee(EncodableValue(1)))); plugin.HandleMethodCall( flutter::MethodCall("create", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(second_create_result)); } TEST(CameraPlugin, InitializeHandlerCallStartPreview) { int64_t mock_camera_id = 1234; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId(Eq(mock_camera_id))) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType(Eq(PendingResultType::kInitialize))) .Times(1) .WillOnce(Return(false)); EXPECT_CALL(*camera, AddPendingResult(Eq(PendingResultType::kInitialize), _)) .Times(1) .WillOnce([cam = camera.get()](PendingResultType type, std::unique_ptr<MethodResult<>> result) { cam->pending_result_ = std::move(result); return true; }); EXPECT_CALL(*camera, GetCaptureController) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->capture_controller_.get(); }); EXPECT_CALL(*capture_controller, StartPreview()) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->pending_result_->Success(); }); camera->camera_id_ = mock_camera_id; camera->capture_controller_ = std::move(capture_controller); MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(0); EXPECT_CALL(*initialize_result, SuccessInternal).Times(1); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(mock_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("initialize", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, InitializeHandlerErrorOnInvalidCameraId) { int64_t mock_camera_id = 1234; int64_t missing_camera_id = 5678; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType).Times(0); EXPECT_CALL(*camera, AddPendingResult).Times(0); EXPECT_CALL(*camera, GetCaptureController).Times(0); EXPECT_CALL(*capture_controller, StartPreview).Times(0); camera->camera_id_ = mock_camera_id; MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(1); EXPECT_CALL(*initialize_result, SuccessInternal).Times(0); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(missing_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("initialize", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, TakePictureHandlerCallsTakePictureWithPath) { int64_t mock_camera_id = 1234; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId(Eq(mock_camera_id))) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType(Eq(PendingResultType::kTakePicture))) .Times(1) .WillOnce(Return(false)); EXPECT_CALL(*camera, AddPendingResult(Eq(PendingResultType::kTakePicture), _)) .Times(1) .WillOnce([cam = camera.get()](PendingResultType type, std::unique_ptr<MethodResult<>> result) { cam->pending_result_ = std::move(result); return true; }); EXPECT_CALL(*camera, GetCaptureController) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->capture_controller_.get(); }); EXPECT_CALL(*capture_controller, TakePicture(EndsWith(".jpeg"))) .Times(1) .WillOnce([cam = camera.get()](const std::string& file_path) { assert(cam->pending_result_); return cam->pending_result_->Success(); }); camera->camera_id_ = mock_camera_id; camera->capture_controller_ = std::move(capture_controller); MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(0); EXPECT_CALL(*initialize_result, SuccessInternal).Times(1); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(mock_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("takePicture", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, TakePictureHandlerErrorOnInvalidCameraId) { int64_t mock_camera_id = 1234; int64_t missing_camera_id = 5678; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType).Times(0); EXPECT_CALL(*camera, AddPendingResult).Times(0); EXPECT_CALL(*camera, GetCaptureController).Times(0); EXPECT_CALL(*capture_controller, TakePicture).Times(0); camera->camera_id_ = mock_camera_id; MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(1); EXPECT_CALL(*initialize_result, SuccessInternal).Times(0); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(missing_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("takePicture", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, StartVideoRecordingHandlerCallsStartRecordWithPath) { int64_t mock_camera_id = 1234; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId(Eq(mock_camera_id))) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType(Eq(PendingResultType::kStartRecord))) .Times(1) .WillOnce(Return(false)); EXPECT_CALL(*camera, AddPendingResult(Eq(PendingResultType::kStartRecord), _)) .Times(1) .WillOnce([cam = camera.get()](PendingResultType type, std::unique_ptr<MethodResult<>> result) { cam->pending_result_ = std::move(result); return true; }); EXPECT_CALL(*camera, GetCaptureController) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->capture_controller_.get(); }); EXPECT_CALL(*capture_controller, StartRecord(EndsWith(".mp4"), -1)) .Times(1) .WillOnce([cam = camera.get()](const std::string& file_path, int64_t max_video_duration_ms) { assert(cam->pending_result_); return cam->pending_result_->Success(); }); camera->camera_id_ = mock_camera_id; camera->capture_controller_ = std::move(capture_controller); MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(0); EXPECT_CALL(*initialize_result, SuccessInternal).Times(1); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(mock_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("startVideoRecording", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, StartVideoRecordingHandlerCallsStartRecordWithPathAndCaptureDuration) { int64_t mock_camera_id = 1234; int32_t mock_video_duration = 100000; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId(Eq(mock_camera_id))) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType(Eq(PendingResultType::kStartRecord))) .Times(1) .WillOnce(Return(false)); EXPECT_CALL(*camera, AddPendingResult(Eq(PendingResultType::kStartRecord), _)) .Times(1) .WillOnce([cam = camera.get()](PendingResultType type, std::unique_ptr<MethodResult<>> result) { cam->pending_result_ = std::move(result); return true; }); EXPECT_CALL(*camera, GetCaptureController) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->capture_controller_.get(); }); EXPECT_CALL(*capture_controller, StartRecord(EndsWith(".mp4"), Eq(mock_video_duration))) .Times(1) .WillOnce([cam = camera.get()](const std::string& file_path, int64_t max_video_duration_ms) { assert(cam->pending_result_); return cam->pending_result_->Success(); }); camera->camera_id_ = mock_camera_id; camera->capture_controller_ = std::move(capture_controller); MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(0); EXPECT_CALL(*initialize_result, SuccessInternal).Times(1); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(mock_camera_id)}, {EncodableValue("maxVideoDuration"), EncodableValue(mock_video_duration)}, }; plugin.HandleMethodCall( flutter::MethodCall("startVideoRecording", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, StartVideoRecordingHandlerErrorOnInvalidCameraId) { int64_t mock_camera_id = 1234; int64_t missing_camera_id = 5678; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType).Times(0); EXPECT_CALL(*camera, AddPendingResult).Times(0); EXPECT_CALL(*camera, GetCaptureController).Times(0); EXPECT_CALL(*capture_controller, StartRecord(_, -1)).Times(0); camera->camera_id_ = mock_camera_id; MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(1); EXPECT_CALL(*initialize_result, SuccessInternal).Times(0); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(missing_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("startVideoRecording", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, StopVideoRecordingHandlerCallsStopRecord) { int64_t mock_camera_id = 1234; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId(Eq(mock_camera_id))) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType(Eq(PendingResultType::kStopRecord))) .Times(1) .WillOnce(Return(false)); EXPECT_CALL(*camera, AddPendingResult(Eq(PendingResultType::kStopRecord), _)) .Times(1) .WillOnce([cam = camera.get()](PendingResultType type, std::unique_ptr<MethodResult<>> result) { cam->pending_result_ = std::move(result); return true; }); EXPECT_CALL(*camera, GetCaptureController) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->capture_controller_.get(); }); EXPECT_CALL(*capture_controller, StopRecord) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->pending_result_->Success(); }); camera->camera_id_ = mock_camera_id; camera->capture_controller_ = std::move(capture_controller); MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(0); EXPECT_CALL(*initialize_result, SuccessInternal).Times(1); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(mock_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("stopVideoRecording", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, StopVideoRecordingHandlerErrorOnInvalidCameraId) { int64_t mock_camera_id = 1234; int64_t missing_camera_id = 5678; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType).Times(0); EXPECT_CALL(*camera, AddPendingResult).Times(0); EXPECT_CALL(*camera, GetCaptureController).Times(0); EXPECT_CALL(*capture_controller, StopRecord).Times(0); camera->camera_id_ = mock_camera_id; MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(1); EXPECT_CALL(*initialize_result, SuccessInternal).Times(0); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(missing_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("stopVideoRecording", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, ResumePreviewHandlerCallsResumePreview) { int64_t mock_camera_id = 1234; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId(Eq(mock_camera_id))) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType(Eq(PendingResultType::kResumePreview))) .Times(1) .WillOnce(Return(false)); EXPECT_CALL(*camera, AddPendingResult(Eq(PendingResultType::kResumePreview), _)) .Times(1) .WillOnce([cam = camera.get()](PendingResultType type, std::unique_ptr<MethodResult<>> result) { cam->pending_result_ = std::move(result); return true; }); EXPECT_CALL(*camera, GetCaptureController) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->capture_controller_.get(); }); EXPECT_CALL(*capture_controller, ResumePreview) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->pending_result_->Success(); }); camera->camera_id_ = mock_camera_id; camera->capture_controller_ = std::move(capture_controller); MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(0); EXPECT_CALL(*initialize_result, SuccessInternal).Times(1); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(mock_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("resumePreview", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, ResumePreviewHandlerErrorOnInvalidCameraId) { int64_t mock_camera_id = 1234; int64_t missing_camera_id = 5678; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType).Times(0); EXPECT_CALL(*camera, AddPendingResult).Times(0); EXPECT_CALL(*camera, GetCaptureController).Times(0); EXPECT_CALL(*capture_controller, ResumePreview).Times(0); camera->camera_id_ = mock_camera_id; MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(1); EXPECT_CALL(*initialize_result, SuccessInternal).Times(0); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(missing_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("resumePreview", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, PausePreviewHandlerCallsPausePreview) { int64_t mock_camera_id = 1234; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId(Eq(mock_camera_id))) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType(Eq(PendingResultType::kPausePreview))) .Times(1) .WillOnce(Return(false)); EXPECT_CALL(*camera, AddPendingResult(Eq(PendingResultType::kPausePreview), _)) .Times(1) .WillOnce([cam = camera.get()](PendingResultType type, std::unique_ptr<MethodResult<>> result) { cam->pending_result_ = std::move(result); return true; }); EXPECT_CALL(*camera, GetCaptureController) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->capture_controller_.get(); }); EXPECT_CALL(*capture_controller, PausePreview) .Times(1) .WillOnce([cam = camera.get()]() { assert(cam->pending_result_); return cam->pending_result_->Success(); }); camera->camera_id_ = mock_camera_id; camera->capture_controller_ = std::move(capture_controller); MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(0); EXPECT_CALL(*initialize_result, SuccessInternal).Times(1); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(mock_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("pausePreview", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } TEST(CameraPlugin, PausePreviewHandlerErrorOnInvalidCameraId) { int64_t mock_camera_id = 1234; int64_t missing_camera_id = 5678; std::unique_ptr<MockMethodResult> initialize_result = std::make_unique<MockMethodResult>(); std::unique_ptr<MockCamera> camera = std::make_unique<MockCamera>(MOCK_DEVICE_ID); std::unique_ptr<MockCaptureController> capture_controller = std::make_unique<MockCaptureController>(); EXPECT_CALL(*camera, HasCameraId) .Times(1) .WillOnce([cam = camera.get()](int64_t camera_id) { return cam->camera_id_ == camera_id; }); EXPECT_CALL(*camera, HasPendingResultByType).Times(0); EXPECT_CALL(*camera, AddPendingResult).Times(0); EXPECT_CALL(*camera, GetCaptureController).Times(0); EXPECT_CALL(*capture_controller, PausePreview).Times(0); camera->camera_id_ = mock_camera_id; MockCameraPlugin plugin(std::make_unique<MockTextureRegistrar>().get(), std::make_unique<MockBinaryMessenger>().get(), std::make_unique<MockCameraFactory>()); // Add mocked camera to plugins camera list. plugin.AddCamera(std::move(camera)); EXPECT_CALL(*initialize_result, ErrorInternal).Times(1); EXPECT_CALL(*initialize_result, SuccessInternal).Times(0); EncodableMap args = { {EncodableValue("cameraId"), EncodableValue(missing_camera_id)}, }; plugin.HandleMethodCall( flutter::MethodCall("pausePreview", std::make_unique<EncodableValue>(EncodableMap(args))), std::move(initialize_result)); } } // namespace test } // namespace camera_windows
plugins/packages/camera/camera_windows/windows/test/camera_plugin_test.cpp/0
{ "file_path": "plugins/packages/camera/camera_windows/windows/test/camera_plugin_test.cpp", "repo_id": "plugins", "token_count": 14997 }
1,263
rootProject.name = 'espresso'
plugins/packages/espresso/android/settings.gradle/0
{ "file_path": "plugins/packages/espresso/android/settings.gradle", "repo_id": "plugins", "token_count": 10 }
1,264
// 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.view.View; import androidx.test.espresso.UiController; import com.google.common.annotations.Beta; import java.util.concurrent.Future; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Responsible for performing an interaction on the given Flutter widget. * * <p>This is part of the Espresso-Flutter test framework public API - developers are free to write * their own {@code WidgetAction} implementation when necessary. */ @Beta public interface WidgetAction extends FlutterAction<Void> { /** * Performs this action on the given Flutter widget. * * <p>If the given {@code targetWidget} is {@code null}, this action shall be performed on the * entire {@code FlutterView} in context. * * @param targetWidget the matcher that uniquely identifies a Flutter widget on the given {@code * FlutterView}. {@code Null} if it's a global action on the {@code FlutterView} in context. * @param flutterView the Flutter view that this widget lives in. * @param flutterTestingProtocol the channel for talking to Flutter app directly. * @param androidUiController the interface for issuing UI operations to the Android system. * @return a {@code Future} representing pending completion of performing the action, or yields an * exception if the action failed to perform. */ @Override Future<Void> perform( @Nullable WidgetMatcher targetWidget, @Nonnull View flutterView, @Nonnull FlutterTestingProtocol flutterTestingProtocol, @Nonnull UiController androidUiController); }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/WidgetAction.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/WidgetAction.java", "repo_id": "plugins", "token_count": 523 }
1,265
// 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.isNullOrEmpty; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import java.util.Objects; /** * JSON-RPC 2.0 response object. * * <p>See https://www.jsonrpc.org/specification for detailed specification. */ public final class JsonRpcResponse { private static final Gson gson = new Gson(); private static final String JSON_RPC_VERSION = "2.0"; /** Specifying the version of the JSON-RPC protocol. Must be "2.0". */ @SerializedName("jsonrpc") private final String version; /** * Required. Must be the same as the value of the id in the corresponding JsonRpcRequest object. */ private String id; /** The result of the JSON-RPC call. Required on success. */ private JsonObject result; /** Error occurred in the JSON-RPC call. Required on error. */ private ErrorObject error; /** * Deserializes the given Json string to a {@code JsonRpcResponse} object. * * @param jsonString the string from which the object is to be deserialized. * @return the deserialized object. */ public static JsonRpcResponse fromJson(String jsonString) { checkArgument(!isNullOrEmpty(jsonString), "Json string cannot be null or empty."); JsonRpcResponse response = gson.fromJson(jsonString, JsonRpcResponse.class); checkState(!isNullOrEmpty(response.getId())); checkState(JSON_RPC_VERSION.equals(response.getVersion()), "JSON-RPC version must be 2.0."); return response; } /** * Constructs with the given id and. The JSON-RPC version will be defaulted to "2.0". * * @param id the id of this response. Should be the same as the corresponding request. */ public JsonRpcResponse(String id) { this.version = JSON_RPC_VERSION; setId(id); } /** * Gets the JSON-RPC version. * * @return the JSON-RPC version. Should always be "2.0". */ public String getVersion() { return version; } /** Gets the id of this JSON-RPC response. */ public String getId() { return id; } /** * Sets the id of this JSON-RPC response. * * @param id the id to be set. Cannot be null. */ public void setId(String id) { this.id = checkNotNull(id); } /** Gets the result of this JSON-RPC response. Should be present on success. */ public JsonObject getResult() { return result; } /** * Sets the result of this JSON-RPC response. * * @param result */ public void setResult(JsonObject result) { this.result = result; } /** Gets the error object of this JSON-RPC response. Should be present on error. */ public ErrorObject getError() { return error; } /** * Sets the error object of this JSON-RPC response. * * @param error the error to be set. */ public void setError(ErrorObject error) { this.error = error; } /** * Serializes this object to its equivalent Json representation. * * @return the Json representation of this object. */ public String toJson() { return gson.toJson(this); } /** * Equivalent to {@link #toJson()}. * * @return the Json representation of this object. */ @Override public String toString() { return toJson(); } @Override public boolean equals(Object obj) { if (obj instanceof JsonRpcResponse) { JsonRpcResponse objResponse = (JsonRpcResponse) obj; return Objects.equals(objResponse.id, this.id) && Objects.equals(objResponse.result, this.result) && Objects.equals(objResponse.error, this.error); } else { return false; } } @Override public int hashCode() { int hash = Objects.hashCode(id); hash = hash * 31 + Objects.hashCode(result); hash = hash * 31 + Objects.hashCode(error); return hash; } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/jsonrpc/message/JsonRpcResponse.java", "repo_id": "plugins", "token_count": 1437 }
1,266
// 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.matcher; import static com.google.common.base.Preconditions.checkNotNull; import androidx.test.espresso.flutter.api.WidgetMatcher; import androidx.test.espresso.flutter.model.WidgetInfo; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import javax.annotation.Nonnull; import org.hamcrest.Description; /** A matcher that matches a Flutter widget with a given ancestor. */ public final class IsDescendantOfMatcher extends WidgetMatcher { private static final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); private final WidgetMatcher ancestorMatcher; private final WidgetMatcher widgetMatcher; // Flutter Driver extension APIs only support JSON strings, not other JSON structures. // Thus, explicitly convert the matchers to JSON strings. @SerializedName("of") @Expose private final String jsonAncestorMatcher; @SerializedName("matching") @Expose private final String jsonWidgetMatcher; IsDescendantOfMatcher( @Nonnull WidgetMatcher ancestorMatcher, @Nonnull WidgetMatcher widgetMatcher) { super("Descendant"); this.ancestorMatcher = checkNotNull(ancestorMatcher); this.widgetMatcher = checkNotNull(widgetMatcher); jsonAncestorMatcher = gson.toJson(ancestorMatcher); jsonWidgetMatcher = gson.toJson(widgetMatcher); } /** Returns the matcher to match the widget's ancestor. */ public WidgetMatcher getAncestorMatcher() { return ancestorMatcher; } /** Returns the matcher to match the widget itself. */ public WidgetMatcher getWidgetMatcher() { return widgetMatcher; } @Override public String toString() { return "matched with " + widgetMatcher + " with ancestor: " + ancestorMatcher; } @Override protected boolean matchesSafely(WidgetInfo widget) { // TODO: Using this matcher in the assertion is not supported yet. throw new UnsupportedOperationException("IsDescendantMatcher is not supported for assertion."); } @Override public void describeTo(Description description) { description .appendText("matched with ") .appendText(widgetMatcher.toString()) .appendText(" with ancestor: ") .appendText(ancestorMatcher.toString()); } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/IsDescendantOfMatcher.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/IsDescendantOfMatcher.java", "repo_id": "plugins", "token_count": 783 }
1,267
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.espresso_example"> <application android:label="espresso_example" android:icon="@mipmap/ic_launcher"> <activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <!-- Don't delete the meta-data below. This is used by the Flutter tool to generate GeneratedPluginRegistrant.java --> <meta-data android:name="flutterEmbedding" android:value="2" /> </application> </manifest>
plugins/packages/espresso/example/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "plugins/packages/espresso/example/android/app/src/main/AndroidManifest.xml", "repo_id": "plugins", "token_count": 479 }
1,268
// 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 "FFSFileSelectorPlugin.h" #import "messages.g.h" // This header is available in the Test module. Import via "@import file_selector_ios.Test;". @interface FFSFileSelectorPlugin () <FFSFileSelectorApi, UIDocumentPickerDelegate> /** * Overrides the view controller used for presenting the document picker. */ @property(nonatomic) UIViewController *_Nullable presentingViewControllerOverride; /** * Overrides the UIDocumentPickerViewController used for file picking. */ @property(nonatomic) UIDocumentPickerViewController *_Nullable documentPickerViewControllerOverride; @end
plugins/packages/file_selector/file_selector_ios/ios/Classes/FFSFileSelectorPlugin_Test.h/0
{ "file_path": "plugins/packages/file_selector/file_selector_ios/ios/Classes/FFSFileSelectorPlugin_Test.h", "repo_id": "plugins", "token_count": 210 }
1,269
## NEXT * Updates example code for `use_build_context_synchronously` lint. * Updates minimum Flutter version to 3.0. ## 0.9.1 * Adds `getDirectoryPaths` implementation. ## 0.9.0+1 * Changes XTypeGroup initialization from final to const. * Updates minimum Flutter version to 2.10. ## 0.9.0 * Moves source to flutter/plugins. ## 0.0.3 * Adds Dart implementation for in-package method channel. ## 0.0.2+1 * Updates README ## 0.0.2 * Updates SDK constraint to signal compatibility with null safety. ## 0.0.1 * Initial Linux implementation of `file_selector`.
plugins/packages/file_selector/file_selector_linux/CHANGELOG.md/0
{ "file_path": "plugins/packages/file_selector/file_selector_linux/CHANGELOG.md", "repo_id": "plugins", "token_count": 189 }
1,270
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import FlutterMacOS import Foundation /// Protocol for showing panels, allowing for depenedency injection in tests. protocol PanelController { /// Displays the given save panel, and provides the selected URL, or nil if the panel is /// cancelled, to the handler. /// - Parameters: /// - panel: The panel to show. /// - window: The window to display the panel for. /// - completionHandler: The completion handler to receive the results. func display( _ panel: NSSavePanel, for window: NSWindow?, completionHandler: @escaping (URL?) -> Void); /// Displays the given open panel, and provides the selected URLs, or nil if the panel is /// cancelled, to the handler. /// - Parameters: /// - panel: The panel to show. /// - window: The window to display the panel for. /// - completionHandler: The completion handler to receive the results. func display( _ panel: NSOpenPanel, for window: NSWindow?, completionHandler: @escaping ([URL]?) -> Void); } /// Protocol to provide access to the Flutter view, allowing for dependency injection in tests. /// /// This is necessary because Swift doesn't allow for only partially implementing a protocol, so /// a stub implementation of FlutterPluginRegistrar for tests would break any time something was /// added to that protocol. protocol ViewProvider { /// Returns the view associated with the Flutter content. var view: NSView? { get } } public class FileSelectorPlugin: NSObject, FlutterPlugin, FileSelectorApi { private let viewProvider: ViewProvider private let panelController: PanelController private let openMethod = "openFile" private let openDirectoryMethod = "getDirectoryPath" private let saveMethod = "getSavePath" public static func register(with registrar: FlutterPluginRegistrar) { let instance = FileSelectorPlugin( viewProvider: DefaultViewProvider(registrar: registrar), panelController: DefaultPanelController()) FileSelectorApiSetup.setUp(binaryMessenger: registrar.messenger, api: instance) } init(viewProvider: ViewProvider, panelController: PanelController) { self.viewProvider = viewProvider self.panelController = panelController } func displayOpenPanel(options: OpenPanelOptions, completion: @escaping ([String?]) -> Void) { let panel = NSOpenPanel() configure(openPanel: panel, with: options) panelController.display(panel, for: viewProvider.view?.window) { (selection: [URL]?) in completion(selection?.map({ item in item.path }) ?? []) } } func displaySavePanel(options: SavePanelOptions, completion: @escaping (String?) -> Void) { let panel = NSSavePanel() configure(panel: panel, with: options) panelController.display(panel, for: viewProvider.view?.window) { (selection: URL?) in completion(selection?.path) } } /// Configures an NSSavePanel based on channel method call arguments. /// - Parameters: /// - panel: The panel to configure. /// - arguments: The arguments dictionary from a FlutterMethodCall to this plugin. private func configure(panel: NSSavePanel, with options: SavePanelOptions) { if let directoryPath = options.directoryPath { panel.directoryURL = URL(fileURLWithPath: directoryPath) } if let suggestedName = options.nameFieldStringValue { panel.nameFieldStringValue = suggestedName } if let prompt = options.prompt { panel.prompt = prompt } if let acceptedTypes = options.allowedFileTypes { var allowedTypes: [String] = [] // The array values are non-null by convention even though Pigeon can't currently express // that via the types; see messages.dart. allowedTypes.append(contentsOf: acceptedTypes.extensions.map({ $0! })) allowedTypes.append(contentsOf: acceptedTypes.utis.map({ $0! })) // TODO: Add support for mimeTypes in macOS 11+. See // https://github.com/flutter/flutter/issues/117843 if !allowedTypes.isEmpty { panel.allowedFileTypes = allowedTypes } } } /// Configures an NSOpenPanel based on channel method call arguments. /// - Parameters: /// - panel: The panel to configure. /// - arguments: The arguments dictionary from a FlutterMethodCall to this plugin. /// - choosingDirectory: True if the panel should allow choosing directories rather than files. private func configure( openPanel panel: NSOpenPanel, with options: OpenPanelOptions ) { configure(panel: panel, with: options.baseOptions) panel.allowsMultipleSelection = options.allowsMultipleSelection panel.canChooseDirectories = options.canChooseDirectories; panel.canChooseFiles = options.canChooseFiles; } } /// Non-test implementation of PanelController that calls the standard methods to display the panel /// either as a sheet (if a window is provided) or modal (if not). private class DefaultPanelController: PanelController { func display( _ panel: NSSavePanel, for window: NSWindow?, completionHandler: @escaping (URL?) -> Void ) { let completionAdapter = { response in completionHandler((response == NSApplication.ModalResponse.OK) ? panel.url : nil) } if let window = window { panel.beginSheetModal(for: window, completionHandler: completionAdapter) } else { completionAdapter(panel.runModal()) } } func display( _ panel: NSOpenPanel, for window: NSWindow?, completionHandler: @escaping ([URL]?) -> Void ) { let completionAdapter = { response in completionHandler((response == NSApplication.ModalResponse.OK) ? panel.urls : nil) } if let window = window { panel.beginSheetModal(for: window, completionHandler: completionAdapter) } else { completionAdapter(panel.runModal()) } } } /// Non-test implementation of PanelController that forwards to the plugin registrar. private class DefaultViewProvider: ViewProvider { private let registrar: FlutterPluginRegistrar init(registrar: FlutterPluginRegistrar) { self.registrar = registrar } var view: NSView? { get { registrar.view } } }
plugins/packages/file_selector/file_selector_macos/macos/Classes/FileSelectorPlugin.swift/0
{ "file_path": "plugins/packages/file_selector/file_selector_macos/macos/Classes/FileSelectorPlugin.swift", "repo_id": "plugins", "token_count": 1904 }
1,271
// Mocks generated by Mockito 5.2.0 from annotations // in file_selector_windows/example/windows/flutter/ephemeral/.plugin_symlinks/file_selector_windows/test/file_selector_windows_test.dart. // Do not manually edit this file. import 'package:file_selector_windows/src/messages.g.dart' as _i3; import 'package:mockito/mockito.dart' as _i1; import 'test_api.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: 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 /// A class which mocks [TestFileSelectorApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestFileSelectorApi extends _i1.Mock implements _i2.TestFileSelectorApi { MockTestFileSelectorApi() { _i1.throwOnMissingStub(this); } @override List<String?> showOpenDialog(_i3.SelectionOptions? options, String? initialDirectory, String? confirmButtonText) => (super.noSuchMethod( Invocation.method( #showOpenDialog, [options, initialDirectory, confirmButtonText]), returnValue: <String?>[]) as List<String?>); @override List<String?> showSaveDialog( _i3.SelectionOptions? options, String? initialDirectory, String? suggestedName, String? confirmButtonText) => (super.noSuchMethod( Invocation.method(#showSaveDialog, [options, initialDirectory, suggestedName, confirmButtonText]), returnValue: <String?>[]) as List<String?>); }
plugins/packages/file_selector/file_selector_windows/test/file_selector_windows_test.mocks.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector_windows/test/file_selector_windows_test.mocks.dart", "repo_id": "plugins", "token_count": 663 }
1,272
// 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. #ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_ #include <comdef.h> #include <comip.h> #include <windows.h> #include <functional> #include <memory> #include <variant> #include <vector> #include "file_dialog_controller.h" #include "test/test_utils.h" _COM_SMARTPTR_TYPEDEF(IFileDialog, IID_IFileDialog); namespace file_selector_windows { namespace test { class TestFileDialogController; // A value to use for GetResult(s) in TestFileDialogController. The type depends // on whether the dialog is an open or save dialog. using MockShowResult = std::variant<std::monostate, IShellItemPtr, IShellItemArrayPtr>; // Called for TestFileDialogController::Show, to do validation and provide a // mock return value for GetResult(s). using MockShow = std::function<MockShowResult(const TestFileDialogController&, HWND)>; // A C++-friendly version of a COMDLG_FILTERSPEC. struct DialogFilter { std::wstring name; std::wstring spec; DialogFilter(const wchar_t* name, const wchar_t* spec) : name(name), spec(spec) {} }; // An extension of the normal file dialog controller that: // - Allows for inspection of set values. // - Allows faking the 'Show' interaction, providing tests an opportunity to // validate the dialog settings and provide a return value, via MockShow. class TestFileDialogController : public FileDialogController { public: TestFileDialogController(IFileDialog* dialog, MockShow mock_show); ~TestFileDialogController(); // FileDialogController: HRESULT SetFolder(IShellItem* folder) override; HRESULT SetFileTypes(UINT count, COMDLG_FILTERSPEC* filters) override; HRESULT SetOkButtonLabel(const wchar_t* text) override; HRESULT Show(HWND parent) override; HRESULT GetResult(IShellItem** out_item) const override; HRESULT GetResults(IShellItemArray** out_items) const override; // Accessors for validating IFileDialogController setter calls. // Gets the folder path set by FileDialogController::SetFolder. // // This exists because there are multiple ways that the value returned by // GetDialogFolderPath can be changed, so this allows specifically validating // calls to SetFolder. std::wstring GetSetFolderPath() const; // Gets dialog folder path by calling IFileDialog::GetFolder. std::wstring GetDialogFolderPath() const; std::wstring GetFileName() const; const std::vector<DialogFilter>& GetFileTypes() const; std::wstring GetOkButtonLabel() const; private: IFileDialogPtr dialog_; MockShow mock_show_; MockShowResult mock_result_; // The last set values, for IFileDialog properties that have setters but no // corresponding getters. std::wstring set_folder_path_; std::wstring ok_button_label_; std::vector<DialogFilter> filter_groups_; }; // A controller factory that vends TestFileDialogController instances. class TestFileDialogControllerFactory : public FileDialogControllerFactory { public: // Creates a factory whose instances use mock_show for the Show callback. TestFileDialogControllerFactory(MockShow mock_show); virtual ~TestFileDialogControllerFactory(); // Disallow copy and assign. TestFileDialogControllerFactory(const TestFileDialogControllerFactory&) = delete; TestFileDialogControllerFactory& operator=( const TestFileDialogControllerFactory&) = delete; // FileDialogControllerFactory: std::unique_ptr<FileDialogController> CreateController( IFileDialog* dialog) const override; private: MockShow mock_show_; }; } // namespace test } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_FILE_DIALOG_CONTROLLER_H_
plugins/packages/file_selector/file_selector_windows/windows/test/test_file_dialog_controller.h/0
{ "file_path": "plugins/packages/file_selector/file_selector_windows/windows/test/test_file_dialog_controller.h", "repo_id": "plugins", "token_count": 1187 }
1,273
// 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; import androidx.annotation.NonNull; import io.flutter.embedding.engine.plugins.FlutterPlugin; /** * Plugin class that exists because the Flutter tool expects such a class to exist for every Android * plugin. * * <p><strong>DO NOT USE THIS CLASS.</strong> */ public class FlutterAndroidLifecyclePlugin implements FlutterPlugin { @SuppressWarnings("deprecation") public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) { // no-op } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { // no-op } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { // no-op } }
plugins/packages/flutter_plugin_android_lifecycle/android/src/main/java/io/flutter/plugins/flutter_plugin_android_lifecycle/FlutterAndroidLifecyclePlugin.java/0
{ "file_path": "plugins/packages/flutter_plugin_android_lifecycle/android/src/main/java/io/flutter/plugins/flutter_plugin_android_lifecycle/FlutterAndroidLifecyclePlugin.java", "repo_id": "plugins", "token_count": 279 }
1,274
# google_maps_flutter_example Demonstrates how to use the google_maps_flutter plugin.
plugins/packages/google_maps_flutter/google_maps_flutter/example/README.md/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/example/README.md", "repo_id": "plugins", "token_count": 27 }
1,275
org.gradle.jvmargs=-Xmx4G android.enableR8=true android.useAndroidX=true android.enableJetifier=true
plugins/packages/google_maps_flutter/google_maps_flutter/example/android/gradle.properties/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,276
// 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 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; const CameraPosition _kInitialPosition = CameraPosition(target: LatLng(-33.852, 151.211), zoom: 11.0); class MapClickPage extends GoogleMapExampleAppPage { const MapClickPage({Key? key}) : super(const Icon(Icons.mouse), 'Map click', key: key); @override Widget build(BuildContext context) { return const _MapClickBody(); } } class _MapClickBody extends StatefulWidget { const _MapClickBody(); @override State<StatefulWidget> createState() => _MapClickBodyState(); } class _MapClickBodyState extends State<_MapClickBody> { _MapClickBodyState(); GoogleMapController? mapController; LatLng? _lastTap; LatLng? _lastLongPress; @override Widget build(BuildContext context) { final GoogleMap googleMap = GoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, onTap: (LatLng pos) { setState(() { _lastTap = pos; }); }, onLongPress: (LatLng pos) { setState(() { _lastLongPress = pos; }); }, ); final List<Widget> columnChildren = <Widget>[ Padding( padding: const EdgeInsets.all(10.0), child: Center( child: SizedBox( width: 300.0, height: 200.0, child: googleMap, ), ), ), ]; if (mapController != null) { final String lastTap = 'Tap:\n${_lastTap ?? ""}\n'; final String lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; columnChildren.add(Center( child: Text( lastTap, textAlign: TextAlign.center, ))); columnChildren.add(Center( child: Text( _lastTap != null ? 'Tapped' : '', textAlign: TextAlign.center, ))); columnChildren.add(Center( child: Text( lastLongPress, textAlign: TextAlign.center, ))); columnChildren.add(Center( child: Text( _lastLongPress != null ? 'Long pressed' : '', textAlign: TextAlign.center, ))); } return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren, ); } Future<void> onMapCreated(GoogleMapController controller) async { setState(() { mapController = controller; }); } }
plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/map_click.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/example/lib/map_click.dart", "repo_id": "plugins", "token_count": 1104 }
1,277
# google\_maps\_flutter\_android <?code-excerpt path-base="excerpts/packages/google_maps_flutter_example"?> The Android implementation of [`google_maps_flutter`][1]. ## Usage This package is [endorsed][2], which means you can simply use `google_maps_flutter` normally. This package will be automatically included in your app when you do. ## Display Mode This plugin supports two different [platform view display modes][3]. The default display mode is subject to change in the future, and will not be considered a breaking change, so if you want to ensure a specific mode you can set it explicitly: <?code-excerpt "readme_excerpts.dart (DisplayMode)"?> ```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'; void main() { // Require Hybrid Composition mode on Android. final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { mapsImplementation.useAndroidViewSurface = true; } // ··· } ``` ### Hybrid Composition This is the current default mode, and corresponds to `useAndroidViewSurface = true`. It ensures that the map display will work as expected, at the cost of some performance. ### Texture Layer Hybrid Composition This is a new display mode used by most plugins starting with Flutter 3.0, and corresponds to `useAndroidViewSurface = false`. This is more performant than Hybrid Composition, but currently [misses certain map updates][4]. This mode will likely become the default in future versions if/when the missed updates issue can be resolved. ## Map renderer This plugin supports the option to request a specific [map renderer][5]. The renderer must be requested before creating GoogleMap instances, as the renderer can be initialized only once per application context. <?code-excerpt "readme_excerpts.dart (MapRenderer)"?> ```dart AndroidMapRenderer mapRenderer = AndroidMapRenderer.platformDefault; // ··· final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { WidgetsFlutterBinding.ensureInitialized(); mapRenderer = await mapsImplementation .initializeWithRenderer(AndroidMapRenderer.latest); } ``` Available values are `AndroidMapRenderer.latest`, `AndroidMapRenderer.legacy`, `AndroidMapRenderer.platformDefault`. Note that getting the requested renderer as a response is not guaranteed. [1]: https://pub.dev/packages/google_maps_flutter [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin [3]: https://docs.flutter.dev/development/platform-integration/android/platform-views [4]: https://github.com/flutter/flutter/issues/103686 [5]: https://developers.google.com/maps/documentation/android-sdk/renderer
plugins/packages/google_maps_flutter/google_maps_flutter_android/README.md/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/README.md", "repo_id": "plugins", "token_count": 854 }
1,278
// 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.GoogleMap; import com.google.android.gms.maps.model.TileOverlay; import com.google.android.gms.maps.model.TileOverlayOptions; import io.flutter.plugin.common.MethodChannel; import java.util.HashMap; import java.util.List; import java.util.Map; class TileOverlaysController { private final Map<String, TileOverlayController> tileOverlayIdToController; private final MethodChannel methodChannel; private GoogleMap googleMap; TileOverlaysController(MethodChannel methodChannel) { this.tileOverlayIdToController = new HashMap<>(); this.methodChannel = methodChannel; } void setGoogleMap(GoogleMap googleMap) { this.googleMap = googleMap; } void addTileOverlays(List<Map<String, ?>> tileOverlaysToAdd) { if (tileOverlaysToAdd == null) { return; } for (Map<String, ?> tileOverlayToAdd : tileOverlaysToAdd) { addTileOverlay(tileOverlayToAdd); } } void changeTileOverlays(List<Map<String, ?>> tileOverlaysToChange) { if (tileOverlaysToChange == null) { return; } for (Map<String, ?> tileOverlayToChange : tileOverlaysToChange) { changeTileOverlay(tileOverlayToChange); } } void removeTileOverlays(List<String> tileOverlayIdsToRemove) { if (tileOverlayIdsToRemove == null) { return; } for (String tileOverlayId : tileOverlayIdsToRemove) { if (tileOverlayId == null) { continue; } removeTileOverlay(tileOverlayId); } } void clearTileCache(String tileOverlayId) { if (tileOverlayId == null) { return; } TileOverlayController tileOverlayController = tileOverlayIdToController.get(tileOverlayId); if (tileOverlayController != null) { tileOverlayController.clearTileCache(); } } Map<String, Object> getTileOverlayInfo(String tileOverlayId) { if (tileOverlayId == null) { return null; } TileOverlayController tileOverlayController = tileOverlayIdToController.get(tileOverlayId); if (tileOverlayController == null) { return null; } return tileOverlayController.getTileOverlayInfo(); } private void addTileOverlay(Map<String, ?> tileOverlayOptions) { if (tileOverlayOptions == null) { return; } TileOverlayBuilder tileOverlayOptionsBuilder = new TileOverlayBuilder(); String tileOverlayId = Convert.interpretTileOverlayOptions(tileOverlayOptions, tileOverlayOptionsBuilder); TileProviderController tileProviderController = new TileProviderController(methodChannel, tileOverlayId); tileOverlayOptionsBuilder.setTileProvider(tileProviderController); TileOverlayOptions options = tileOverlayOptionsBuilder.build(); TileOverlay tileOverlay = googleMap.addTileOverlay(options); TileOverlayController tileOverlayController = new TileOverlayController(tileOverlay); tileOverlayIdToController.put(tileOverlayId, tileOverlayController); } private void changeTileOverlay(Map<String, ?> tileOverlayOptions) { if (tileOverlayOptions == null) { return; } String tileOverlayId = getTileOverlayId(tileOverlayOptions); TileOverlayController tileOverlayController = tileOverlayIdToController.get(tileOverlayId); if (tileOverlayController != null) { Convert.interpretTileOverlayOptions(tileOverlayOptions, tileOverlayController); } } private void removeTileOverlay(String tileOverlayId) { TileOverlayController tileOverlayController = tileOverlayIdToController.get(tileOverlayId); if (tileOverlayController != null) { tileOverlayController.remove(); tileOverlayIdToController.remove(tileOverlayId); } } @SuppressWarnings("unchecked") private static String getTileOverlayId(Map<String, ?> tileOverlay) { return (String) tileOverlay.get("tileOverlayId"); } }
plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileOverlaysController.java/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileOverlaysController.java", "repo_id": "plugins", "token_count": 1380 }
1,279
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; /// An Android of implementation of [GoogleMapsInspectorPlatform]. @visibleForTesting class GoogleMapsInspectorAndroid extends GoogleMapsInspectorPlatform { /// Creates a method-channel-based inspector instance that gets the channel /// for a given map ID from [channelProvider]. GoogleMapsInspectorAndroid(MethodChannel? Function(int mapId) channelProvider) : _channelProvider = channelProvider; final MethodChannel? Function(int mapId) _channelProvider; @override Future<bool> areBuildingsEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isBuildingsEnabled'))!; } @override Future<bool> areRotateGesturesEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isRotateGesturesEnabled'))!; } @override Future<bool> areScrollGesturesEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isScrollGesturesEnabled'))!; } @override Future<bool> areTiltGesturesEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isTiltGesturesEnabled'))!; } @override Future<bool> areZoomControlsEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isZoomControlsEnabled'))!; } @override Future<bool> areZoomGesturesEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isZoomGesturesEnabled'))!; } @override Future<MinMaxZoomPreference> getMinMaxZoomLevels({required int mapId}) async { final List<double> zoomLevels = (await _channelProvider(mapId)! .invokeMethod<List<dynamic>>('map#getMinMaxZoomLevels'))! .cast<double>(); return MinMaxZoomPreference(zoomLevels[0], zoomLevels[1]); } @override Future<TileOverlay?> getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) async { final Map<String, Object?>? tileInfo = await _channelProvider(mapId)! .invokeMapMethod<String, dynamic>( 'map#getTileOverlayInfo', <String, String>{ 'tileOverlayId': tileOverlayId.value, }); if (tileInfo == null) { return null; } return TileOverlay( tileOverlayId: tileOverlayId, fadeIn: tileInfo['fadeIn']! as bool, transparency: tileInfo['transparency']! as double, visible: tileInfo['visible']! as bool, // Android and iOS return different types. zIndex: (tileInfo['zIndex']! as num).toInt(), ); } @override Future<bool> isCompassEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isCompassEnabled'))!; } @override Future<bool> isLiteModeEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isLiteModeEnabled'))!; } @override Future<bool> isMapToolbarEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isMapToolbarEnabled'))!; } @override Future<bool> isMyLocationButtonEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isMyLocationButtonEnabled'))!; } @override Future<bool> isTrafficEnabled({required int mapId}) async { return (await _channelProvider(mapId)! .invokeMethod<bool>('map#isTrafficEnabled'))!; } }
plugins/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_map_inspector_android.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_map_inspector_android.dart", "repo_id": "plugins", "token_count": 1392 }
1,280
// 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 "FLTGoogleMapJSONConversions.h" @implementation FLTGoogleMapJSONConversions + (CLLocationCoordinate2D)locationFromLatLong:(NSArray *)latlong { return CLLocationCoordinate2DMake([latlong[0] doubleValue], [latlong[1] doubleValue]); } + (CGPoint)pointFromArray:(NSArray *)array { return CGPointMake([array[0] doubleValue], [array[1] doubleValue]); } + (NSArray *)arrayFromLocation:(CLLocationCoordinate2D)location { return @[ @(location.latitude), @(location.longitude) ]; } + (UIColor *)colorFromRGBA:(NSNumber *)numberColor { unsigned long value = [numberColor unsignedLongValue]; return [UIColor colorWithRed:((float)((value & 0xFF0000) >> 16)) / 255.0 green:((float)((value & 0xFF00) >> 8)) / 255.0 blue:((float)(value & 0xFF)) / 255.0 alpha:((float)((value & 0xFF000000) >> 24)) / 255.0]; } + (NSArray<CLLocation *> *)pointsFromLatLongs:(NSArray *)data { NSMutableArray *points = [[NSMutableArray alloc] init]; for (unsigned i = 0; i < [data count]; i++) { NSNumber *latitude = data[i][0]; NSNumber *longitude = data[i][1]; CLLocation *point = [[CLLocation alloc] initWithLatitude:[latitude doubleValue] longitude:[longitude doubleValue]]; [points addObject:point]; } return points; } + (NSArray<NSArray<CLLocation *> *> *)holesFromPointsArray:(NSArray *)data { NSMutableArray<NSArray<CLLocation *> *> *holes = [[[NSMutableArray alloc] init] init]; for (unsigned i = 0; i < [data count]; i++) { NSArray<CLLocation *> *points = [FLTGoogleMapJSONConversions pointsFromLatLongs:data[i]]; [holes addObject:points]; } return holes; } + (nullable NSDictionary<NSString *, id> *)dictionaryFromPosition:(GMSCameraPosition *)position { if (!position) { return nil; } return @{ @"target" : [FLTGoogleMapJSONConversions arrayFromLocation:[position target]], @"zoom" : @([position zoom]), @"bearing" : @([position bearing]), @"tilt" : @([position viewingAngle]), }; } + (NSDictionary<NSString *, NSNumber *> *)dictionaryFromPoint:(CGPoint)point { return @{ @"x" : @(lroundf(point.x)), @"y" : @(lroundf(point.y)), }; } + (nullable NSDictionary *)dictionaryFromCoordinateBounds:(GMSCoordinateBounds *)bounds { if (!bounds) { return nil; } return @{ @"southwest" : [FLTGoogleMapJSONConversions arrayFromLocation:[bounds southWest]], @"northeast" : [FLTGoogleMapJSONConversions arrayFromLocation:[bounds northEast]], }; } + (nullable GMSCameraPosition *)cameraPostionFromDictionary:(nullable NSDictionary *)data { if (!data) { return nil; } return [GMSCameraPosition cameraWithTarget:[FLTGoogleMapJSONConversions locationFromLatLong:data[@"target"]] zoom:[data[@"zoom"] floatValue] bearing:[data[@"bearing"] doubleValue] viewingAngle:[data[@"tilt"] doubleValue]]; } + (CGPoint)pointFromDictionary:(NSDictionary *)dictionary { double x = [dictionary[@"x"] doubleValue]; double y = [dictionary[@"y"] doubleValue]; return CGPointMake(x, y); } + (GMSCoordinateBounds *)coordinateBoundsFromLatLongs:(NSArray *)latlongs { return [[GMSCoordinateBounds alloc] initWithCoordinate:[FLTGoogleMapJSONConversions locationFromLatLong:latlongs[0]] coordinate:[FLTGoogleMapJSONConversions locationFromLatLong:latlongs[1]]]; } + (GMSMapViewType)mapViewTypeFromTypeValue:(NSNumber *)typeValue { int value = [typeValue intValue]; return (GMSMapViewType)(value == 0 ? 5 : value); } + (nullable GMSCameraUpdate *)cameraUpdateFromChannelValue:(NSArray *)channelValue { NSString *update = channelValue[0]; if ([update isEqualToString:@"newCameraPosition"]) { return [GMSCameraUpdate setCamera:[FLTGoogleMapJSONConversions cameraPostionFromDictionary:channelValue[1]]]; } else if ([update isEqualToString:@"newLatLng"]) { return [GMSCameraUpdate setTarget:[FLTGoogleMapJSONConversions locationFromLatLong:channelValue[1]]]; } else if ([update isEqualToString:@"newLatLngBounds"]) { return [GMSCameraUpdate fitBounds:[FLTGoogleMapJSONConversions coordinateBoundsFromLatLongs:channelValue[1]] withPadding:[channelValue[2] doubleValue]]; } else if ([update isEqualToString:@"newLatLngZoom"]) { return [GMSCameraUpdate setTarget:[FLTGoogleMapJSONConversions locationFromLatLong:channelValue[1]] zoom:[channelValue[2] floatValue]]; } else if ([update isEqualToString:@"scrollBy"]) { return [GMSCameraUpdate scrollByX:[channelValue[1] doubleValue] Y:[channelValue[2] doubleValue]]; } else if ([update isEqualToString:@"zoomBy"]) { if (channelValue.count == 2) { return [GMSCameraUpdate zoomBy:[channelValue[1] floatValue]]; } else { return [GMSCameraUpdate zoomBy:[channelValue[1] floatValue] atPoint:[FLTGoogleMapJSONConversions pointFromArray:channelValue[2]]]; } } else if ([update isEqualToString:@"zoomIn"]) { return [GMSCameraUpdate zoomIn]; } else if ([update isEqualToString:@"zoomOut"]) { return [GMSCameraUpdate zoomOut]; } else if ([update isEqualToString:@"zoomTo"]) { return [GMSCameraUpdate zoomTo:[channelValue[1] floatValue]]; } return nil; } @end
plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapJSONConversions.m/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapJSONConversions.m", "repo_id": "plugins", "token_count": 2137 }
1,281
// 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:plugin_platform_interface/plugin_platform_interface.dart'; import '../../google_maps_flutter_platform_interface.dart'; /// The interface that platform-specific implementations of /// `google_maps_flutter` can extend to support state inpsection in tests. /// /// Avoid `implements` of this interface. Using `implements` makes adding any /// new methods here a breaking change for end users of your platform! /// /// Do `extends GoogleMapsInspectorPlatform` instead, so new methods /// added here are inherited in your code with the default implementation (that /// throws at runtime), rather than breaking your users at compile time. abstract class GoogleMapsInspectorPlatform extends PlatformInterface { /// Constructs a GoogleMapsFlutterPlatform. GoogleMapsInspectorPlatform() : super(token: _token); static final Object _token = Object(); static GoogleMapsInspectorPlatform? _instance; /// The instance of [GoogleMapsInspectorPlatform], if any. /// /// This is usually populated by calling /// [GoogleMapsFlutterPlatform.enableDebugInspection]. static GoogleMapsInspectorPlatform? get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [GoogleMapsInspectorPlatform] in their /// implementation of [GoogleMapsFlutterPlatform.enableDebugInspection]. static set instance(GoogleMapsInspectorPlatform? instance) { if (instance != null) { PlatformInterface.verify(instance, _token); } _instance = instance; } /// Returns the minimum and maxmimum zoom level settings. Future<MinMaxZoomPreference> getMinMaxZoomLevels({required int mapId}) { throw UnimplementedError('getMinMaxZoomLevels() has not been implemented.'); } /// Returns true if the compass is enabled. Future<bool> isCompassEnabled({required int mapId}) { throw UnimplementedError('isCompassEnabled() has not been implemented.'); } /// Returns true if lite mode is enabled. Future<bool> isLiteModeEnabled({required int mapId}) { throw UnimplementedError('isLiteModeEnabled() has not been implemented.'); } /// Returns true if the map toolbar is enabled. Future<bool> isMapToolbarEnabled({required int mapId}) { throw UnimplementedError('isMapToolbarEnabled() has not been implemented.'); } /// Returns true if the "my location" button is enabled. Future<bool> isMyLocationButtonEnabled({required int mapId}) { throw UnimplementedError( 'isMyLocationButtonEnabled() has not been implemented.'); } /// Returns true if the traffic overlay is enabled. Future<bool> isTrafficEnabled({required int mapId}) { throw UnimplementedError('isTrafficEnabled() has not been implemented.'); } /// Returns true if the building layer is enabled. Future<bool> areBuildingsEnabled({required int mapId}) { throw UnimplementedError('areBuildingsEnabled() has not been implemented.'); } /// Returns true if rotate gestures are enabled. Future<bool> areRotateGesturesEnabled({required int mapId}) { throw UnimplementedError( 'areRotateGesturesEnabled() has not been implemented.'); } /// Returns true if scroll gestures are enabled. Future<bool> areScrollGesturesEnabled({required int mapId}) { throw UnimplementedError( 'areScrollGesturesEnabled() has not been implemented.'); } /// Returns true if tilt gestures are enabled. Future<bool> areTiltGesturesEnabled({required int mapId}) { throw UnimplementedError( 'areTiltGesturesEnabled() has not been implemented.'); } /// Returns true if zoom controls are enabled. Future<bool> areZoomControlsEnabled({required int mapId}) { throw UnimplementedError( 'areZoomControlsEnabled() has not been implemented.'); } /// Returns true if zoom gestures are enabled. Future<bool> areZoomGesturesEnabled({required int mapId}) { throw UnimplementedError( 'areZoomGesturesEnabled() has not been implemented.'); } /// Returns information about the tile overlay with the given ID. /// /// The returned object will be synthesized from platform data, so will not /// be the same Dart object as the original [TileOverlay] provided to the /// platform interface with that ID, and not all fields (e.g., /// [TileOverlay.tileProvider]) will be populated. Future<TileOverlay?> getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) { throw UnimplementedError('getTileOverlayInfo() has not been implemented.'); } }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_inspector_platform.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_inspector_platform.dart", "repo_id": "plugins", "token_count": 1333 }
1,282
// 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; /// Item used in the stroke pattern for a Polyline. @immutable class PatternItem { const PatternItem._(this._json); /// A dot used in the stroke pattern for a [Polyline]. static const PatternItem dot = PatternItem._(<Object>['dot']); /// A dash used in the stroke pattern for a [Polyline]. /// /// [length] has to be non-negative. static PatternItem dash(double length) { assert(length >= 0.0); return PatternItem._(<Object>['dash', length]); } /// A gap used in the stroke pattern for a [Polyline]. /// /// [length] has to be non-negative. static PatternItem gap(double length) { assert(length >= 0.0); return PatternItem._(<Object>['gap', length]); } final Object _json; /// Converts this object to something serializable in JSON. Object toJson() => _json; }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/pattern_item.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/pattern_item.dart", "repo_id": "plugins", "token_count": 311 }
1,283
// 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 Polygons in a Map of PolygonId -> Polygon. Map<PolygonId, Polygon> keyByPolygonId(Iterable<Polygon> polygons) { return keyByMapsObjectId<Polygon>(polygons).cast<PolygonId, Polygon>(); } /// Converts a Set of Polygons into something serializable in JSON. Object serializePolygonSet(Set<Polygon> polygons) { return serializeMapsObjectSet(polygons); }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/polygon.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/polygon.dart", "repo_id": "plugins", "token_count": 190 }
1,284
// 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. const String iconImageBase64 = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAIRlWElmTU' '0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIA' 'AIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQ' 'AAABCgAwAEAAAAAQAAABAAAAAAx28c8QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1M' 'OmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIH' 'g6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8v' 'd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcm' 'lwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFk' 'b2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk' '9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6' 'eG1wbWV0YT4KTMInWQAAAplJREFUOBF1k01ME1EQx2fe7tIPoGgTE6AJgQQSPaiH9oAtkFbsgX' 'jygFcT0XjSkxcTDxtPJh6MR28ePMHBBA8cNLSIony0oBhEMVETP058tE132+7uG3cW24DAXN57' '2fn9/zPz3iIcEdEl0nIxtNLr1IlVeoMadkubKmoL+u2SzAV8IjV5Ekt4GN+A8+VOUPwLarOI2G' 'Vpqq0i4JQorwQxPtWHVZ1IKP8LNGDXGaSyqARFxDGo7MJBy4XVf3AyQ+qTHnTEXoF9cFUy3OkY' '0oWxmWFtD5xNoc1sQ6AOn1+hCNTkkhKow8KFZV77tVs2O9dhFvBm0IA/U0RhZ7/ocEx23oUDlh' 'h8HkNjZIN8Lb3gOU8gOp7AKJHCB2/aNZkTftHumNzzbtl2CBPZHqxw8mHhVZBeoz6w5DvhE2FZ' 'lQYPjKdd2/qRyKZ6KsPv7TEk7EYEk0A0EUmJduHRy1i4oLKqgmC59ZggAdwrC9pFuWy1iUT2rA' 'uv0h2UdNtNqxCBBkgqorjOMOgksN7CxQ90vEb00U3c3LIwyo9o8FXxQVNr8Coqyk+S5EPBXnjt' 'xRmc4TegI7qWbvBkeeUbGMnTCd4nZnYeDOWIEtlC6cKK/JJepY3hZSvN33jovO6L0XFqPKqBTO' 'FuapUoPr1lxDM7cmC2TAOz25cYSGa++feBew/cjpc0V+mNT29/HZp3KDFTNLvuTRPEHy5065lj' 'Xn4y41XM+wP/AlcycRmdc3MUhvLm/J/ceu/3qUVT62oP2EZpjSylHybHSpDUVcjq9gEBVo0+Xt' 'JyN2IWRO+3QUforRoKnZLVsglaMECW+YmMSj9M3SrC6Lg71CMiqWfUrJ6ywzefhnZ+G69BaKdB' 'WhXQAn6wzDUpfUPw7MrmX/WhbfmKblw+AAAAAElFTkSuQmCC';
plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/resources/icon_image_base64.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/resources/icon_image_base64.dart", "repo_id": "plugins", "token_count": 1402 }
1,285
// 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; /// This class manages a set of [MarkerController]s associated to a [GoogleMapController]. class MarkersController extends GeometryController { /// Initialize the cache. The [StreamController] comes from the [GoogleMapController], and is shared with other controllers. MarkersController({ required StreamController<MapEvent<Object?>> stream, }) : _streamController = stream, _markerIdToController = <MarkerId, MarkerController>{}; // A cache of [MarkerController]s indexed by their [MarkerId]. final Map<MarkerId, MarkerController> _markerIdToController; // The stream over which markers broadcast their events final StreamController<MapEvent<Object?>> _streamController; /// Returns the cache of [MarkerController]s. Test only. @visibleForTesting Map<MarkerId, MarkerController> get markers => _markerIdToController; /// Adds a set of [Marker] objects to the cache. /// /// Wraps each [Marker] into its corresponding [MarkerController]. void addMarkers(Set<Marker> markersToAdd) { markersToAdd.forEach(_addMarker); } void _addMarker(Marker marker) { if (marker == null) { return; } final gmaps.InfoWindowOptions? infoWindowOptions = _infoWindowOptionsFromMarker(marker); gmaps.InfoWindow? gmInfoWindow; if (infoWindowOptions != null) { gmInfoWindow = gmaps.InfoWindow(infoWindowOptions); // Google Maps' JS SDK does not have a click event on the InfoWindow, so // we make one... if (infoWindowOptions.content != null && infoWindowOptions.content is HtmlElement) { final HtmlElement content = infoWindowOptions.content! as HtmlElement; content.onClick.listen((_) { _onInfoWindowTap(marker.markerId); }); } } final gmaps.Marker? currentMarker = _markerIdToController[marker.markerId]?.marker; final gmaps.MarkerOptions markerOptions = _markerOptionsFromMarker(marker, currentMarker); final gmaps.Marker gmMarker = gmaps.Marker(markerOptions)..map = googleMap; final MarkerController controller = MarkerController( marker: gmMarker, infoWindow: gmInfoWindow, consumeTapEvents: marker.consumeTapEvents, onTap: () { showMarkerInfoWindow(marker.markerId); _onMarkerTap(marker.markerId); }, onDragStart: (gmaps.LatLng latLng) { _onMarkerDragStart(marker.markerId, latLng); }, onDrag: (gmaps.LatLng latLng) { _onMarkerDrag(marker.markerId, latLng); }, onDragEnd: (gmaps.LatLng latLng) { _onMarkerDragEnd(marker.markerId, latLng); }, ); _markerIdToController[marker.markerId] = controller; } /// Updates a set of [Marker] objects with new options. void changeMarkers(Set<Marker> markersToChange) { markersToChange.forEach(_changeMarker); } void _changeMarker(Marker marker) { final MarkerController? markerController = _markerIdToController[marker.markerId]; if (markerController != null) { final gmaps.MarkerOptions markerOptions = _markerOptionsFromMarker( marker, markerController.marker, ); final gmaps.InfoWindowOptions? infoWindow = _infoWindowOptionsFromMarker(marker); markerController.update( markerOptions, newInfoWindowContent: infoWindow?.content as HtmlElement?, ); } } /// Removes a set of [MarkerId]s from the cache. void removeMarkers(Set<MarkerId> markerIdsToRemove) { markerIdsToRemove.forEach(_removeMarker); } void _removeMarker(MarkerId markerId) { final MarkerController? markerController = _markerIdToController[markerId]; markerController?.remove(); _markerIdToController.remove(markerId); } // InfoWindow... /// Shows the [InfoWindow] of a [MarkerId]. /// /// See also [hideMarkerInfoWindow] and [isInfoWindowShown]. void showMarkerInfoWindow(MarkerId markerId) { _hideAllMarkerInfoWindow(); final MarkerController? markerController = _markerIdToController[markerId]; markerController?.showInfoWindow(); } /// Hides the [InfoWindow] of a [MarkerId]. /// /// See also [showMarkerInfoWindow] and [isInfoWindowShown]. void hideMarkerInfoWindow(MarkerId markerId) { final MarkerController? markerController = _markerIdToController[markerId]; markerController?.hideInfoWindow(); } /// Returns whether or not the [InfoWindow] of a [MarkerId] is shown. /// /// See also [showMarkerInfoWindow] and [hideMarkerInfoWindow]. bool isInfoWindowShown(MarkerId markerId) { final MarkerController? markerController = _markerIdToController[markerId]; return markerController?.infoWindowShown ?? false; } // Handle internal events bool _onMarkerTap(MarkerId markerId) { // Have you ended here on your debugging? Is this wrong? // Comment here: https://github.com/flutter/flutter/issues/64084 _streamController.add(MarkerTapEvent(mapId, markerId)); return _markerIdToController[markerId]?.consumeTapEvents ?? false; } void _onInfoWindowTap(MarkerId markerId) { _streamController.add(InfoWindowTapEvent(mapId, markerId)); } void _onMarkerDragStart(MarkerId markerId, gmaps.LatLng latLng) { _streamController.add(MarkerDragStartEvent( mapId, _gmLatLngToLatLng(latLng), markerId, )); } void _onMarkerDrag(MarkerId markerId, gmaps.LatLng latLng) { _streamController.add(MarkerDragEvent( mapId, _gmLatLngToLatLng(latLng), markerId, )); } void _onMarkerDragEnd(MarkerId markerId, gmaps.LatLng latLng) { _streamController.add(MarkerDragEndEvent( mapId, _gmLatLngToLatLng(latLng), markerId, )); } void _hideAllMarkerInfoWindow() { _markerIdToController.values .where((MarkerController? controller) => controller?.infoWindowShown ?? false) .forEach((MarkerController controller) { controller.hideInfoWindow(); }); } }
plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart", "repo_id": "plugins", "token_count": 2279 }
1,286
## 6.0.0 * **Breaking change** for platform `web`: * Endorses `google_sign_in_web: ^0.11.0` as the web implementation of the plugin. * The web package is now backed by the **Google Identity Services (GIS) SDK**, instead of the **Google Sign-In for Web JS SDK**, which is set to be deprecated after March 31, 2023. * Migration information can be found in the [`google_sign_in_web` package README](https://pub.dev/packages/google_sign_in_web). For every platform other than `web`, this version should be identical to `5.4.4`. ## 5.4.4 * Adds documentation for iOS auth with SERVER_CLIENT_ID * Updates minimum Flutter version to 3.0. ## 5.4.3 * Updates code for stricter lint checks. ## 5.4.2 * Updates minimum Flutter version to 2.10. * Adds override for `GoogleSignInPlatform.initWithParams`. * Fixes tests to recognize new default `forceCodeForRefreshToken` request attribute. ## 5.4.1 * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 5.4.0 * Adds support for configuring `serverClientId` through `GoogleSignIn` constructor. * Adds support for Dart-based configuration as alternative to `GoogleService-Info.plist` for iOS. ## 5.3.3 * Updates references to the obsolete master branch. ## 5.3.2 * Enables mocking models by changing overridden operator == parameter type from `dynamic` to `Object`. * Updates tests to use a mock platform instead of relying on default method channel implementation internals. * Removes example workaround to build for arm64 iOS simulators. ## 5.3.1 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 5.3.0 * Moves Android and iOS implementations to federated packages. ## 5.2.5 * Migrates from `ui.hash*` to `Object.hash*`. * Adds OS version support information to README. ## 5.2.4 * Internal code cleanup for stricter analysis options. ## 5.2.3 * Bumps the Android dependency on `com.google.android.gms:play-services-auth` and therefore removes the need for `jetifier`. ## 5.2.2 * Updates Android compileSdkVersion to 31. * Removes dependency on `meta`. ## 5.2.1 Change the placeholder of the GoogleUserCircleAvatar to a transparent image. ## 5.2.0 * Add `GoogleSignInAccount.serverAuthCode`. Mark `GoogleSignInAuthentication.serverAuthCode` as deprecated. ## 5.1.1 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. ## 5.1.0 * Add reAuthenticate option to signInSilently to allow re-authentication to be requested * Updated Android lint settings. ## 5.0.7 * Mark iOS arm64 simulators as unsupported. ## 5.0.6 * Remove references to the Android V1 embedding. ## 5.0.5 * Add iOS unit and UI integration test targets. * Add iOS unit test module map. * Exclude arm64 simulators in example app. ## 5.0.4 * Migrate maven repo from jcenter to mavenCentral. ## 5.0.3 * Fixed links in `README.md`. * Added documentation for usage on the web. ## 5.0.2 * Fix flutter/flutter#48602 iOS flow shows account selection, if user is signed in to Google on the device. ## 5.0.1 * Update platforms `init` function to prioritize `clientId` property when available; * Updates `google_sign_in_platform_interface` version. ## 5.0.0 * Migrate to null safety. ## 4.5.9 * Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets. ## 4.5.8 * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) ## 4.5.7 * Update Flutter SDK constraint. ## 4.5.6 * Fix deprecated member warning in tests. ## 4.5.5 * Update android compileSdkVersion to 29. ## 4.5.4 * Keep handling deprecated Android v1 classes for backward compatibility. ## 4.5.3 * Update package:e2e -> package:integration_test ## 4.5.2 * Update package:e2e reference to use the local version in the flutter/plugins repository. ## 4.5.1 * Add note on Apple sign in requirement in README. ## 4.5.0 * Add support for getting `serverAuthCode`. ## 4.4.6 * Update lower bound of dart dependency to 2.1.0. ## 4.4.5 * Fix requestScopes to allow subsequent calls on Android. ## 4.4.4 * OCMock module import -> #import, unit tests compile generated as library. * Fix CocoaPods podspec lint warnings. ## 4.4.3 * Upgrade google_sign_in_web to version ^0.9.1 ## 4.4.2 * Android: make the Delegate non-final to allow overriding. ## 4.4.1 * Android: Move `GoogleSignInWrapper` to a separate class. ## 4.4.0 * Migrate to Android v2 embedder. ## 4.3.0 * Add support for method introduced in `google_sign_in_platform_interface` 1.1.0. ## 4.2.0 * Migrate to AndroidX. ## 4.1.5 * Remove unused variable. ## 4.1.4 * Make the pedantic dev_dependency explicit. ## 4.1.3 * Make plugin example meet naming convention. ## 4.1.2 * Added a new error code `network_error`, and return it when a network error occurred. ## 4.1.1 * Support passing `clientId` to the web plugin programmatically. ## 4.1.0 * Support web by default. * Require Flutter SDK `v1.12.13+hotfix.4` or greater. ## 4.0.17 * Add missing documentation and fix an unawaited future in the example app. ## 4.0.16 * Remove the deprecated `author:` field from pubspec.yaml * Migrate the plugin to the pubspec platforms manifest. * Require Flutter SDK 1.10.0 or greater. ## 4.0.15 * Export SignInOption from interface since it is used in the frontend as a type. ## 4.0.14 * Port plugin code to use the federated Platform Interface, instead of a MethodChannel directly. ## 4.0.13 * Fix `GoogleUserCircleAvatar` to handle new style profile image URLs. ## 4.0.12 * Move google_sign_in plugin to google_sign_in/google_sign_in to prepare for federated implementations. ## 4.0.11 * Update iOS CocoaPod dependency to 5.0 to fix deprecated API usage issue. ## 4.0.10 * Remove AndroidX warning. ## 4.0.9 * Update and migrate iOS example project. * Define clang module for iOS. ## 4.0.8 * Get rid of `MethodCompleter` and serialize async actions using chained futures. This prevents a bug when sign in methods are being used in error handling zones. ## 4.0.7 * Switch from using `api` to `implementation` for dependency on `play-services-auth`, preventing version mismatch build failures in some Android configurations. ## 4.0.6 * Fixed the `PlatformException` leaking from `catchError()` in debug mode. ## 4.0.5 * Update README with solution to `APIException` errors. ## 4.0.4 * Revert changes in 4.0.3. ## 4.0.3 * Update guava to `27.0.1-android`. * Add correct @NonNull annotations to reduce compiler warnings. ## 4.0.2 * Add missing template type parameter to `invokeMethod` calls. * Bump minimum Flutter version to 1.5.0. * Replace invokeMethod with invokeMapMethod wherever necessary. ## 4.0.1+3 * Update example to gracefully handle null user information. ## 4.0.1+2 * Fix README.md to correctly spell `GoogleService-Info.plist`. ## 4.0.1+1 * Remove categories. ## 4.0.1 * Log a more detailed warning at build time about the previous AndroidX migration. ## 4.0.0+1 * Added a better error message for iOS when the app is missing necessary URL schemes. ## 4.0.0 * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. This was originally incorrectly pushed in the `3.3.0` update. ## 3.3.0+1 * **Revert the breaking 3.3.0 update**. 3.3.0 was known to be breaking and should have incremented the major version number instead of the minor. This revert is in and of itself breaking for anyone that has already migrated however. Anyone who has already migrated their app to AndroidX should immediately update to `4.0.0` instead. That's the correctly versioned new push of `3.3.0`. ## 3.3.0 * **BAD**. This was a breaking change that was incorrectly published on a minor version upgrade, should never have happened. Reverted by 3.3.0+1. * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. ## 3.2.4 * Increase play-services-auth version to 16.0.1 ## 3.2.3 * Change google-services.json and GoogleService-Info.plist of example. ## 3.2.2 * Don't use the result code when handling signin. This results in better error codes because result code always returns "cancelled". ## 3.2.1 * Set http version to be compatible with flutter_test. ## 3.2.0 * Add support for clearing authentication cache for Android. ## 3.1.0 * Add support to recover authentication for Android. ## 3.0.6 * Remove flaky displayName assertion ## 3.0.5 * Added missing http package dependency. ## 3.0.4 * Updated Gradle tooling to match Android Studio 3.1.2. ## 3.0.3+1 * Added documentation on where to find the list of available scopes. ## 3.0.3 * Added support for games sign in on Android. ## 3.0.2 * Updated Google Play Services dependency to version 15.0.0. ## 3.0.1 * Simplified podspec for Cocoapods 1.5.0, avoiding link issues in app archives. ## 3.0.0 * **Breaking change**. Set SDK constraints to match the Flutter beta release. ## 2.1.2 * Added a Delegate interface (IDelegate) that can be implemented by clients in order to override the functionality (for testing purposes for example). ## 2.1.1 * Fixed Dart 2 type errors. ## 2.1.0 * Enabled use in Swift projects. ## 2.0.1 * Simplified and upgraded Android project template to Android SDK 27. * Updated package description. ## 2.0.0 * **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found [here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1). * Relaxed GMS dependency to [11.4.0,12.0[ ## 1.0.3 * Add FLT prefix to iOS types ## 1.0.2 * Support setting foregroundColor in the avatar. ## 1.0.1 * Change GMS dependency to 11.+ ## 1.0.0 * Make GoogleUserCircleAvatar fade profile image over the top of placeholder * Bump to released version ## 0.3.1 * Updated GMS to always use latest patch version for 11.0.x builds ## 0.3.0 * Add a new `GoogleIdentity` interface, implemented by `GoogleSignInAccount`. * Move `GoogleUserCircleAvatar` to "widgets" library (exported by base library for backwards compatibility) and make it take an instance of `GoogleIdentity`, thus allowing it to be used by other packages that provide implementations of `GoogleIdentity`. ## 0.2.1 * Plugin can (once again) be used in apps that extend `FlutterActivity` * `signInSilently` is guaranteed to never throw * A failed sign-in (caused by a failing `init` step) will no longer block subsequent sign-in attempts ## 0.2.0 * Updated dependencies * **Breaking Change**: You need to add a maven section with the "https://maven.google.com" endpoint to the repository section of your `android/build.gradle`. For example: ```gradle allprojects { repositories { jcenter() maven { // NEW url "https://maven.google.com" // NEW } // NEW } } ``` ## 0.1.0 * Update to use `GoogleSignIn` CocoaPod ## 0.0.6 * Fix crash on iOS when signing in caused by nil uiDelegate ## 0.0.5 * Require the use of `support-v4` library on Android. This is an API change in that plugin users will need their activity class to be an instance of `android.support.v4.app.FragmentActivity`. Flutter framework provides such an activity out of the box: `io.flutter.app.FlutterFragmentActivity` * Ignore "Broken pipe" errors affecting iOS simulator * Update to non-deprecated `application:openURL:options:` on iOS ## 0.0.4 * Prevent race conditions when GoogleSignIn methods are called concurrently (#94) ## 0.0.3 * Fix signOut and disconnect (they were silently ignored) * Fix test (#10050) ## 0.0.2 * Don't try to sign in again if user is already signed in ## 0.0.1 * Initial Release
plugins/packages/google_sign_in/google_sign_in/CHANGELOG.md/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in/CHANGELOG.md", "repo_id": "plugins", "token_count": 3982 }
1,287
// 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:typed_data'; import 'package:flutter/material.dart'; import 'src/common.dart'; import 'src/fife.dart' as fife; /// Builds a CircleAvatar profile image of the appropriate resolution class GoogleUserCircleAvatar extends StatelessWidget { /// Creates a new widget based on the specified [identity]. /// /// If [identity] does not contain a `photoUrl` and [placeholderPhotoUrl] is /// specified, then the given URL will be used as the user's photo URL. The /// URL must be able to handle a [sizeDirective] path segment. /// /// If [identity] does not contain a `photoUrl` and [placeholderPhotoUrl] is /// *not* specified, then the widget will render the user's first initial /// in place of a profile photo, or a default profile photo if the user's /// identity does not specify a `displayName`. const GoogleUserCircleAvatar({ Key? key, required this.identity, this.placeholderPhotoUrl, this.foregroundColor, this.backgroundColor, }) : assert(identity != null), super(key: key); /// A regular expression that matches against the "size directive" path /// segment of Google profile image URLs. /// /// The format is is "`/sNN-c/`", where `NN` is the max width/height of the /// image, and "`c`" indicates we want the image cropped. static final RegExp sizeDirective = fife.sizeDirective; /// The Google user's identity; guaranteed to be non-null. final GoogleIdentity identity; /// The color of the text to be displayed if photo is not available. /// /// If a foreground color is not specified, the theme's text color is used. final Color? foregroundColor; /// The color with which to fill the circle. Changing the background color /// will cause the avatar to animate to the new color. /// /// If a background color is not specified, the theme's primary color is used. final Color? backgroundColor; /// The URL of a photo to use if the user's [identity] does not specify a /// `photoUrl`. /// /// If this is `null` and the user's [identity] does not contain a photo URL, /// then this widget will attempt to display the user's first initial as /// determined from the identity's [displayName] field. If that is `null` a /// default (generic) Google profile photo will be displayed. final String? placeholderPhotoUrl; @override Widget build(BuildContext context) { return CircleAvatar( backgroundColor: backgroundColor, foregroundColor: foregroundColor, child: LayoutBuilder(builder: _buildClippedImage), ); } Widget _buildClippedImage(BuildContext context, BoxConstraints constraints) { assert(constraints.maxWidth == constraints.maxHeight); // Placeholder to use when there is no photo URL, and while the photo is // loading. Uses the first character of the display name (if it has one), // or the first letter of the email address if it does not. final List<String?> placeholderCharSources = <String?>[ identity.displayName, identity.email, '-', ]; final String placeholderChar = placeholderCharSources .firstWhere((String? str) => str != null && str.trimLeft().isNotEmpty)! .trimLeft()[0] .toUpperCase(); final Widget placeholder = Center( child: Text(placeholderChar, textAlign: TextAlign.center), ); final String? photoUrl = identity.photoUrl ?? placeholderPhotoUrl; if (photoUrl == null) { return placeholder; } // Add a sizing directive to the profile photo URL. final double size = MediaQuery.of(context).devicePixelRatio * constraints.maxWidth; final String sizedPhotoUrl = fife.addSizeDirectiveToUrl(photoUrl, size); // Fade the photo in over the top of the placeholder. return SizedBox( width: size, height: size, child: ClipOval( child: Stack(fit: StackFit.expand, children: <Widget>[ placeholder, FadeInImage.memoryNetwork( // This creates a transparent placeholder image, so that // [placeholder] shows through. placeholder: _transparentImage, image: sizedPhotoUrl, ) ]), )); } } /// This is an transparent 1x1 gif image. /// /// Those bytes come from `resources/transparentImage.gif`. final Uint8List _transparentImage = Uint8List.fromList( <int>[ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, // 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x21, 0xf9, 0x04, 0x01, 0x00, // 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, // 0x00, 0x02, 0x01, 0x44, 0x00, 0x3B ], );
plugins/packages/google_sign_in/google_sign_in/lib/widgets.dart/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in/lib/widgets.dart", "repo_id": "plugins", "token_count": 1658 }
1,288
// 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.googlesignin; import android.os.Handler; import android.os.Looper; import java.util.concurrent.Executor; /** * Factory and utility methods for {@code Executor}. * * <p>TODO(jackson): If this class is useful for other plugins, consider including it in a shared * library or in the Flutter engine */ public final class Executors { private static final class UiThreadExecutor implements Executor { private static final Handler UI_THREAD = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable command) { UI_THREAD.post(command); } } /** Returns an {@code Executor} that will post commands to the UI thread. */ public static Executor uiThreadExecutor() { return new UiThreadExecutor(); } // Should never be instantiated. private Executors() {} }
plugins/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/Executors.java/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/Executors.java", "repo_id": "plugins", "token_count": 301 }
1,289
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_sign_in_android/google_sign_in_android.dart'; import 'package:google_sign_in_android/src/utils.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; const Map<String, String> kUserData = <String, String>{ 'email': '[email protected]', 'id': '8162538176523816253123', 'photoUrl': 'https://lh5.googleusercontent.com/photo.jpg', 'displayName': 'John Doe', 'idToken': '123', 'serverAuthCode': '789', }; const Map<dynamic, dynamic> kTokenData = <String, dynamic>{ 'idToken': '123', 'accessToken': '456', 'serverAuthCode': '789', }; const Map<String, dynamic> kDefaultResponses = <String, dynamic>{ 'init': null, 'signInSilently': kUserData, 'signIn': kUserData, 'signOut': null, 'disconnect': null, 'isSignedIn': true, 'getTokens': kTokenData, 'requestScopes': true, }; final GoogleSignInUserData? kUser = getUserDataFromMap(kUserData); final GoogleSignInTokenData kToken = getTokenDataFromMap(kTokenData as Map<String, dynamic>); void main() { TestWidgetsFlutterBinding.ensureInitialized(); final GoogleSignInAndroid googleSignIn = GoogleSignInAndroid(); final MethodChannel channel = googleSignIn.channel; final List<MethodCall> log = <MethodCall>[]; late Map<String, dynamic> responses; // Some tests mutate some kDefaultResponses setUp(() { responses = Map<String, dynamic>.from(kDefaultResponses); _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler( channel, (MethodCall methodCall) { log.add(methodCall); final dynamic response = responses[methodCall.method]; if (response != null && response is Exception) { return Future<dynamic>.error('$response'); } return Future<dynamic>.value(response); }, ); log.clear(); }); test('registered instance', () { GoogleSignInAndroid.registerWith(); expect(GoogleSignInPlatform.instance, isA<GoogleSignInAndroid>()); }); test('signInSilently transforms platform data to GoogleSignInUserData', () async { final dynamic response = await googleSignIn.signInSilently(); expect(response, kUser); }); test('signInSilently Exceptions -> throws', () async { responses['signInSilently'] = Exception('Not a user'); expect(googleSignIn.signInSilently(), throwsA(isInstanceOf<PlatformException>())); }); test('signIn transforms platform data to GoogleSignInUserData', () async { final dynamic response = await googleSignIn.signIn(); expect(response, kUser); }); test('signIn Exceptions -> throws', () async { responses['signIn'] = Exception('Not a user'); expect(googleSignIn.signIn(), throwsA(isInstanceOf<PlatformException>())); }); test('getTokens transforms platform data to GoogleSignInTokenData', () async { final dynamic response = await googleSignIn.getTokens( email: '[email protected]', shouldRecoverAuth: false); expect(response, kToken); expect( log[0], isMethodCall('getTokens', arguments: <String, dynamic>{ 'email': '[email protected]', 'shouldRecoverAuth': false, })); }); test('Other functions pass through arguments to the channel', () async { final Map<void Function(), Matcher> tests = <void Function(), Matcher>{ () { googleSignIn.init( hostedDomain: 'example.com', scopes: <String>['two', 'scopes'], signInOption: SignInOption.games, clientId: 'fakeClientId'); }: isMethodCall('init', arguments: <String, dynamic>{ 'hostedDomain': 'example.com', 'scopes': <String>['two', 'scopes'], 'signInOption': 'SignInOption.games', 'clientId': 'fakeClientId', 'serverClientId': null, 'forceCodeForRefreshToken': false, }), () { googleSignIn.initWithParams(const SignInInitParameters( hostedDomain: 'example.com', scopes: <String>['two', 'scopes'], signInOption: SignInOption.games, clientId: 'fakeClientId', serverClientId: 'fakeServerClientId', forceCodeForRefreshToken: true)); }: isMethodCall('init', arguments: <String, dynamic>{ 'hostedDomain': 'example.com', 'scopes': <String>['two', 'scopes'], 'signInOption': 'SignInOption.games', 'clientId': 'fakeClientId', 'serverClientId': 'fakeServerClientId', 'forceCodeForRefreshToken': true, }), () { googleSignIn.getTokens( email: '[email protected]', shouldRecoverAuth: false); }: isMethodCall('getTokens', arguments: <String, dynamic>{ 'email': '[email protected]', 'shouldRecoverAuth': false, }), () { googleSignIn.clearAuthCache(token: 'abc'); }: isMethodCall('clearAuthCache', arguments: <String, dynamic>{ 'token': 'abc', }), () { googleSignIn.requestScopes(<String>['newScope', 'anotherScope']); }: isMethodCall('requestScopes', arguments: <String, dynamic>{ 'scopes': <String>['newScope', 'anotherScope'], }), googleSignIn.signOut: isMethodCall('signOut', arguments: null), googleSignIn.disconnect: isMethodCall('disconnect', arguments: null), googleSignIn.isSignedIn: isMethodCall('isSignedIn', arguments: null), }; for (final void Function() f in tests.keys) { f(); } expect(log, tests.values); }); } /// This allows a value of type T or T? to be treated as a value of type T?. /// /// We use this so that APIs that have become non-nullable can still be used /// with `!` and `?` on the stable branch. T? _ambiguate<T>(T? value) => value;
plugins/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart", "repo_id": "plugins", "token_count": 2295 }
1,290
// 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 "FLTGoogleSignInPlugin.h" #import "FLTGoogleSignInPlugin_Test.h" #import <GoogleSignIn/GoogleSignIn.h> // The key within `GoogleService-Info.plist` used to hold the application's // client id. See https://developers.google.com/identity/sign-in/ios/start // for more info. static NSString *const kClientIdKey = @"CLIENT_ID"; static NSString *const kServerClientIdKey = @"SERVER_CLIENT_ID"; static NSDictionary<NSString *, id> *loadGoogleServiceInfo() { NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; if (plistPath) { return [[NSDictionary alloc] initWithContentsOfFile:plistPath]; } return nil; } // These error codes must match with ones declared on Android and Dart sides. static NSString *const kErrorReasonSignInRequired = @"sign_in_required"; static NSString *const kErrorReasonSignInCanceled = @"sign_in_canceled"; static NSString *const kErrorReasonNetworkError = @"network_error"; static NSString *const kErrorReasonSignInFailed = @"sign_in_failed"; static FlutterError *getFlutterError(NSError *error) { NSString *errorCode; if (error.code == kGIDSignInErrorCodeHasNoAuthInKeychain) { errorCode = kErrorReasonSignInRequired; } else if (error.code == kGIDSignInErrorCodeCanceled) { errorCode = kErrorReasonSignInCanceled; } else if ([error.domain isEqualToString:NSURLErrorDomain]) { errorCode = kErrorReasonNetworkError; } else { errorCode = kErrorReasonSignInFailed; } return [FlutterError errorWithCode:errorCode message:error.domain details:error.localizedDescription]; } @interface FLTGoogleSignInPlugin () // Configuration wrapping Google Cloud Console, Google Apps, OpenID, // and other initialization metadata. @property(strong) GIDConfiguration *configuration; // Permissions requested during at sign in "init" method call // unioned with scopes requested later with incremental authorization // "requestScopes" method call. // The "email" and "profile" base scopes are always implicitly requested. @property(copy) NSSet<NSString *> *requestedScopes; // Instance used to manage Google Sign In authentication including // sign in, sign out, and requesting additional scopes. @property(strong, readonly) GIDSignIn *signIn; // The contents of GoogleService-Info.plist, if it exists. @property(strong, nullable) NSDictionary<NSString *, id> *googleServiceProperties; // Redeclared as not a designated initializer. - (instancetype)init; @end @implementation FLTGoogleSignInPlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/google_sign_in_ios" binaryMessenger:[registrar messenger]]; FLTGoogleSignInPlugin *instance = [[FLTGoogleSignInPlugin alloc] init]; [registrar addApplicationDelegate:instance]; [registrar addMethodCallDelegate:instance channel:channel]; } - (instancetype)init { return [self initWithSignIn:GIDSignIn.sharedInstance]; } - (instancetype)initWithSignIn:(GIDSignIn *)signIn { return [self initWithSignIn:signIn withGoogleServiceProperties:loadGoogleServiceInfo()]; } - (instancetype)initWithSignIn:(GIDSignIn *)signIn withGoogleServiceProperties:(nullable NSDictionary<NSString *, id> *)googleServiceProperties { self = [super init]; if (self) { _signIn = signIn; _googleServiceProperties = googleServiceProperties; // On the iOS simulator, we get "Broken pipe" errors after sign-in for some // unknown reason. We can avoid crashing the app by ignoring them. signal(SIGPIPE, SIG_IGN); _requestedScopes = [[NSSet alloc] init]; } return self; } #pragma mark - <FlutterPlugin> protocol - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result { if ([call.method isEqualToString:@"init"]) { GIDConfiguration *configuration = [self configurationWithClientIdArgument:call.arguments[@"clientId"] serverClientIdArgument:call.arguments[@"serverClientId"] hostedDomainArgument:call.arguments[@"hostedDomain"]]; if (configuration != nil) { if ([call.arguments[@"scopes"] isKindOfClass:[NSArray class]]) { self.requestedScopes = [NSSet setWithArray:call.arguments[@"scopes"]]; } self.configuration = configuration; result(nil); } else { result([FlutterError errorWithCode:@"missing-config" message:@"GoogleService-Info.plist file not found and clientId " @"was not provided programmatically." details:nil]); } } else if ([call.method isEqualToString:@"signInSilently"]) { [self.signIn restorePreviousSignInWithCallback:^(GIDGoogleUser *user, NSError *error) { [self didSignInForUser:user result:result withError:error]; }]; } else if ([call.method isEqualToString:@"isSignedIn"]) { result(@([self.signIn hasPreviousSignIn])); } else if ([call.method isEqualToString:@"signIn"]) { @try { GIDConfiguration *configuration = self.configuration ?: [self configurationWithClientIdArgument:nil serverClientIdArgument:nil hostedDomainArgument:nil]; [self.signIn signInWithConfiguration:configuration presentingViewController:[self topViewController] hint:nil additionalScopes:self.requestedScopes.allObjects callback:^(GIDGoogleUser *user, NSError *error) { [self didSignInForUser:user result:result withError:error]; }]; } @catch (NSException *e) { result([FlutterError errorWithCode:@"google_sign_in" message:e.reason details:e.name]); [e raise]; } } else if ([call.method isEqualToString:@"getTokens"]) { GIDGoogleUser *currentUser = self.signIn.currentUser; GIDAuthentication *auth = currentUser.authentication; [auth doWithFreshTokens:^void(GIDAuthentication *authentication, NSError *error) { result(error != nil ? getFlutterError(error) : @{ @"idToken" : authentication.idToken, @"accessToken" : authentication.accessToken, }); }]; } else if ([call.method isEqualToString:@"signOut"]) { [self.signIn signOut]; result(nil); } else if ([call.method isEqualToString:@"disconnect"]) { [self.signIn disconnectWithCallback:^(NSError *error) { [self respondWithAccount:@{} result:result error:nil]; }]; } else if ([call.method isEqualToString:@"requestScopes"]) { id scopeArgument = call.arguments[@"scopes"]; if ([scopeArgument isKindOfClass:[NSArray class]]) { self.requestedScopes = [self.requestedScopes setByAddingObjectsFromArray:scopeArgument]; } NSSet<NSString *> *requestedScopes = self.requestedScopes; @try { [self.signIn addScopes:requestedScopes.allObjects presentingViewController:[self topViewController] callback:^(GIDGoogleUser *addedScopeUser, NSError *addedScopeError) { if ([addedScopeError.domain isEqualToString:kGIDSignInErrorDomain] && addedScopeError.code == kGIDSignInErrorCodeNoCurrentUser) { result([FlutterError errorWithCode:@"sign_in_required" message:@"No account to grant scopes." details:nil]); } else if ([addedScopeError.domain isEqualToString:kGIDSignInErrorDomain] && addedScopeError.code == kGIDSignInErrorCodeScopesAlreadyGranted) { // Scopes already granted, report success. result(@YES); } else if (addedScopeUser == nil) { result(@NO); } else { NSSet<NSString *> *grantedScopes = [NSSet setWithArray:addedScopeUser.grantedScopes]; BOOL granted = [requestedScopes isSubsetOfSet:grantedScopes]; result(@(granted)); } }]; } @catch (NSException *e) { result([FlutterError errorWithCode:@"request_scopes" message:e.reason details:e.name]); } } else { result(FlutterMethodNotImplemented); } } - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { return [self.signIn handleURL:url]; } #pragma mark - <GIDSignInUIDelegate> protocol - (void)signIn:(GIDSignIn *)signIn presentViewController:(UIViewController *)viewController { UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController; [rootViewController presentViewController:viewController animated:YES completion:nil]; } - (void)signIn:(GIDSignIn *)signIn dismissViewController:(UIViewController *)viewController { [viewController dismissViewControllerAnimated:YES completion:nil]; } #pragma mark - private methods /// @return @c nil if GoogleService-Info.plist not found and clientId is not provided. - (GIDConfiguration *)configurationWithClientIdArgument:(id)clientIDArg serverClientIdArgument:(id)serverClientIDArg hostedDomainArgument:(id)hostedDomainArg { NSString *clientID; BOOL hasDynamicClientId = [clientIDArg isKindOfClass:[NSString class]]; if (hasDynamicClientId) { clientID = clientIDArg; } else if (self.googleServiceProperties) { clientID = self.googleServiceProperties[kClientIdKey]; } else { // We couldn't resolve a clientId, without which we cannot create a GIDConfiguration. return nil; } BOOL hasDynamicServerClientId = [serverClientIDArg isKindOfClass:[NSString class]]; NSString *serverClientID = hasDynamicServerClientId ? serverClientIDArg : self.googleServiceProperties[kServerClientIdKey]; NSString *hostedDomain = nil; if (hostedDomainArg != [NSNull null]) { hostedDomain = hostedDomainArg; } return [[GIDConfiguration alloc] initWithClientID:clientID serverClientID:serverClientID hostedDomain:hostedDomain openIDRealm:nil]; } - (void)didSignInForUser:(GIDGoogleUser *)user result:(FlutterResult)result withError:(NSError *)error { if (error != nil) { // Forward all errors and let Dart side decide how to handle. [self respondWithAccount:nil result:result error:error]; } else { NSURL *photoUrl; if (user.profile.hasImage) { // Placeholder that will be replaced by on the Dart side based on screen size. photoUrl = [user.profile imageURLWithDimension:1337]; } [self respondWithAccount:@{ @"displayName" : user.profile.name ?: [NSNull null], @"email" : user.profile.email ?: [NSNull null], @"id" : user.userID ?: [NSNull null], @"photoUrl" : [photoUrl absoluteString] ?: [NSNull null], @"serverAuthCode" : user.serverAuthCode ?: [NSNull null] } result:result error:nil]; } } - (void)respondWithAccount:(NSDictionary<NSString *, id> *)account result:(FlutterResult)result error:(NSError *)error { result(error != nil ? getFlutterError(error) : account); } - (UIViewController *)topViewController { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // TODO(stuartmorgan) Provide a non-deprecated codepath. See // https://github.com/flutter/flutter/issues/104117 return [self topViewControllerFromViewController:[UIApplication sharedApplication] .keyWindow.rootViewController]; #pragma clang diagnostic pop } /** * This method recursively iterate through the view hierarchy * to return the top most view controller. * * It supports the following scenarios: * * - The view controller is presenting another view. * - The view controller is a UINavigationController. * - The view controller is a UITabBarController. * * @return The top most view controller. */ - (UIViewController *)topViewControllerFromViewController:(UIViewController *)viewController { if ([viewController isKindOfClass:[UINavigationController class]]) { UINavigationController *navigationController = (UINavigationController *)viewController; return [self topViewControllerFromViewController:[navigationController.viewControllers lastObject]]; } if ([viewController isKindOfClass:[UITabBarController class]]) { UITabBarController *tabController = (UITabBarController *)viewController; return [self topViewControllerFromViewController:tabController.selectedViewController]; } if (viewController.presentedViewController) { return [self topViewControllerFromViewController:viewController.presentedViewController]; } return viewController; } @end
plugins/packages/google_sign_in/google_sign_in_ios/ios/Classes/FLTGoogleSignInPlugin.m/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_ios/ios/Classes/FLTGoogleSignInPlugin.m", "repo_id": "plugins", "token_count": 5726 }
1,291
// 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 '../google_sign_in_platform_interface.dart'; /// Converts user data coming from native code into the proper platform interface type. GoogleSignInUserData? getUserDataFromMap(Map<String, dynamic>? data) { if (data == null) { return null; } return GoogleSignInUserData( email: data['email']! as String, id: data['id']! as String, displayName: data['displayName'] as String?, photoUrl: data['photoUrl'] as String?, idToken: data['idToken'] as String?, serverAuthCode: data['serverAuthCode'] as String?); } /// Converts token data coming from native code into the proper platform interface type. GoogleSignInTokenData getTokenDataFromMap(Map<String, dynamic> data) { return GoogleSignInTokenData( idToken: data['idToken'] as String?, accessToken: data['accessToken'] as String?, serverAuthCode: data['serverAuthCode'] as String?, ); }
plugins/packages/google_sign_in/google_sign_in_platform_interface/lib/src/utils.dart/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_platform_interface/lib/src/utils.dart", "repo_id": "plugins", "token_count": 333 }
1,292
// 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. const String expectedPersonId = '1234567890'; const String expectedPersonName = 'Vincent Adultman'; const String expectedPersonEmail = '[email protected]'; const String expectedPersonPhoto = 'https://thispersondoesnotexist.com/image?x=.jpg'; /// A subset of https://developers.google.com/people/api/rest/v1/people#Person. final Map<String, Object?> person = <String, Object?>{ 'resourceName': 'people/$expectedPersonId', 'emailAddresses': <Object?>[ <String, Object?>{ 'metadata': <String, Object?>{ 'primary': false, }, 'value': '[email protected]', }, <String, Object?>{ 'metadata': <String, Object?>{}, 'value': '[email protected]', }, <String, Object?>{ 'metadata': <String, Object?>{ 'primary': true, }, 'value': expectedPersonEmail, }, ], 'names': <Object?>[ <String, Object?>{ 'metadata': <String, Object?>{ 'primary': true, }, 'displayName': expectedPersonName, }, <String, Object?>{ 'metadata': <String, Object?>{ 'primary': false, }, 'displayName': 'Fakey McFakeface', }, ], 'photos': <Object?>[ <String, Object?>{ 'metadata': <String, Object?>{ 'primary': true, }, 'url': expectedPersonPhoto, }, ], }; /// Returns a copy of [map] without the [keysToRemove]. T mapWithoutKeys<T extends Map<String, Object?>>( T map, Set<String> keysToRemove, ) { return Map<String, Object?>.fromEntries( map.entries.where((MapEntry<String, Object?> entry) { return !keysToRemove.contains(entry.key); }), ) as T; }
plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/src/person.dart/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/src/person.dart", "repo_id": "plugins", "token_count": 715 }
1,293
## 0.8.6+2 * Updates `NSPhotoLibraryUsageDescription` description in README. * Updates minimum Flutter version to 3.0. ## 0.8.6+1 * Updates code for stricter lint checks. ## 0.8.6 * Updates minimum Flutter version to 2.10. * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Adds `requestFullMetadata` option to `pickImage`, so images on iOS can be picked without `Photo Library Usage` permission. ## 0.8.5+3 * Adds argument error assertions to the app-facing package, to ensure consistency across platform implementations. * Updates tests to use a mock platform instead of relying on default method channel implementation internals. ## 0.8.5+2 * Minor fixes for new analysis options. ## 0.8.5+1 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.8.5 * Moves Android and iOS implementations to federated packages. * Adds OS version support information to README. ## 0.8.4+11 * Fixes Activity leak. ## 0.8.4+10 * iOS: allows picking images with WebP format. ## 0.8.4+9 * Internal code cleanup for stricter analysis options. ## 0.8.4+8 * Configures the `UIImagePicker` to default to gallery instead of camera when picking multiple images on pre-iOS 14 devices. ## 0.8.4+7 * Refactors unit test to expose private interface via a separate test header instead of the inline declaration. ## 0.8.4+6 * Fixes minor type issues in iOS implementation. ## 0.8.4+5 * Improves the documentation on handling MainActivity being killed by the Android OS. * Updates Android compileSdkVersion to 31. * Fix iOS RunnerUITests search paths. ## 0.8.4+4 * Fix typos in README.md. ## 0.8.4+3 * Suppress a unchecked cast build warning. ## 0.8.4+2 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. ## 0.8.4+1 * Fix README Example for `ImagePickerCache` to cache multiple files. ## 0.8.4 * Update `ImagePickerCache` to cache multiple files. ## 0.8.3+3 * Fix pickImage not returning a value on iOS when dismissing PHPicker sheet by swiping. * Updated Android lint settings. ## 0.8.3+2 * Fix using Camera as image source on Android 11+ ## 0.8.3+1 * Fixed README Example. ## 0.8.3 * Move `ImagePickerFromLimitedGalleryUITests` to `RunnerUITests` target. * Improved handling of bad image data when applying metadata changes on iOS. ## 0.8.2 * Added new methods that return `package:cross_file` `XFile` instances. [Docs](https://pub.dev/documentation/cross_file/latest/index.html). * Deprecate methods that return `PickedFile` instances: * `getImage`: use **`pickImage`** instead. * `getVideo`: use **`pickVideo`** instead. * `getMultiImage`: use **`pickMultiImage`** instead. * `getLostData`: use **`retrieveLostData`** instead. ## 0.8.1+4 * Fixes an issue where `preferredCameraDevice` option is not working for `getVideo` method. * Refactor unit tests that were device-only before. ## 0.8.1+3 * Fix image picker causing a crash when the cache directory is deleted. ## 0.8.1+2 * Update the example app to support the multi-image feature. ## 0.8.1+1 * Expose errors thrown in `pickImage` and `pickVideo` docs. ## 0.8.1 * Add a new method `getMultiImage` to allow picking multiple images on iOS 14 or higher and Android 4.3 or higher. Returns only 1 image for lower versions of iOS and Android. * Known issue: On Android, `getLostData` will only get the last picked image when picking multiple images, see: [#84634](https://github.com/flutter/flutter/issues/84634). ## 0.8.0+4 * Cleaned up the README example ## 0.8.0+3 * Readded request for camera permissions. ## 0.8.0+2 * Fix a rotation problem where when camera is chosen as a source and additional parameters are added. ## 0.8.0+1 * Removed redundant request for camera permissions. ## 0.8.0 * BREAKING CHANGE: Changed storage location for captured images and videos to internal cache on Android, to comply with new Google Play storage requirements. This means developers are responsible for moving the image or video to a different location in case more permanent storage is required. Other applications will no longer be able to access images or videos captured unless they are moved to a publicly accessible location. * Updated Mockito to fix Android tests. ## 0.7.5+4 * Migrate maven repo from jcenter to mavenCentral. ## 0.7.5+3 * Localize `UIAlertController` strings. ## 0.7.5+2 * Implement `UIAlertController` with a preferredStyle of `UIAlertControllerStyleAlert` since `UIAlertView` is deprecated. ## 0.7.5+1 * Fixes a rotation problem where Select Photos limited access is chosen but the image that is picked is not included selected photos and image is scaled. ## 0.7.5 * Fixes an issue where image rotation is wrong when Select Photos chose and image is scaled. * Migrate to PHPicker for iOS 14 and higher versions to pick image from the photo library. * Implement the limited permission to pick photo from the photo library when Select Photo is chosen. ## 0.7.4 * Update flutter_plugin_android_lifecycle dependency to 2.0.1 to fix an R8 issue on some versions. ## 0.7.3 * Endorse image_picker_for_web. ## 0.7.2+1 * Android: fixes an issue where videos could be wrongly picked with `.jpg` extension. ## 0.7.2 * Run CocoaPods iOS tests in RunnerUITests target. ## 0.7.1 * Update platform_plugin_interface version requirement. ## 0.7.0 * Migrate to nullsafety * Breaking Changes: * Removed the deprecated methods: `ImagePicker.pickImage`, `ImagePicker.pickVideo`, `ImagePicker.retrieveLostData` ## 0.6.7+22 * iOS: update XCUITests to separate each test session. ## 0.6.7+21 * Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets. ## 0.6.7+20 * Updated README.md to show the new Android API requirements. ## 0.6.7+19 * Do not copy static field to another static field. ## 0.6.7+18 * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) ## 0.6.7+17 * iOS: fix `User-facing text should use localized string macro` warning. ## 0.6.7+16 * Update Flutter SDK constraint. ## 0.6.7+15 * Fix element type in XCUITests to look for staticText type when searching for texts. * See https://github.com/flutter/flutter/issues/71927 * Minor update in XCUITests to search for different elements on iOS 14 and above. ## 0.6.7+14 * Set up XCUITests. ## 0.6.7+13 * Update documentation of `getImage()` about HEIC images. ## 0.6.7+12 * Update android compileSdkVersion to 29. ## 0.6.7+11 * Keep handling deprecated Android v1 classes for backward compatibility. ## 0.6.7+10 * Updated documentation with code that does not throw an error when image is not picked. ## 0.6.7+9 * Updated the ExifInterface to the AndroidX version to support more file formats; * Update documentation of `getImage()` regarding compression support for specific image types. ## 0.6.7+8 * Update documentation of getImage() about Android's disability to preference front/rear camera. ## 0.6.7+7 * Updating documentation to use isEmpty check. ## 0.6.7+6 * Update package:e2e -> package:integration_test ## 0.6.7+5 * Update package:e2e reference to use the local version in the flutter/plugins repository. ## 0.6.7+4 * Support iOS simulator x86_64 architecture. ## 0.6.7+3 * Fixes to the example app: * Make videos in web start muted. This allows auto-play across browsers. * Prevent the app from disposing of video controllers too early. ## 0.6.7+2 * iOS: Fixes unpresentable album/image picker if window's root view controller is already presenting other view controller. ## 0.6.7+1 * Add web support to the example app. ## 0.6.7 * Utilize the new platform_interface package. * **This change marks old methods as `deprecated`. Please check the README for migration instructions to the new API.** ## 0.6.6+5 * Pin the version of the platform interface to 1.0.0 until the plugin refactor is ready to go. ## 0.6.6+4 * Fix bug, sometimes double click cancel button will crash. ## 0.6.6+3 * Update README ## 0.6.6+2 * Update lower bound of dart dependency to 2.1.0. ## 0.6.6+1 * Android: always use URI to get image/video data. ## 0.6.6 * Use the new platform_interface package. ## 0.6.5+3 * Move core plugin to a subdirectory to allow for federation. ## 0.6.5+2 * iOS: Fixes crash when an image in the gallery is tapped more than once. ## 0.6.5+1 * Fix CocoaPods podspec lint warnings. ## 0.6.5 * Set maximum duration for video recording. * Fix some existing XCTests. ## 0.6.4 * Add a new parameter to select preferred camera device. ## 0.6.3+4 * Make the pedantic dev_dependency explicit. ## 0.6.3+3 * Android: Fix a crash when `externalFilesDirectory` does not exist. ## 0.6.3+2 * Bump RoboElectric dependency to 4.3.1 and update resource usage. ## 0.6.3+1 * Fix an issue that the example app won't launch the image picker after Android V2 embedding migration. ## 0.6.3 * Support Android V2 embedding. * Migrate to using the new e2e test binding. ## 0.6.2+3 * Remove the deprecated `author:` field from pubspec.yaml * Migrate the plugin to the pubspec platforms manifest. * Require Flutter SDK 1.10.0 or greater. ## 0.6.2+2 * Android: Revert the image file return logic when the image doesn't have to be scaled. Fix a rotation regression caused by 0.6.2+1 * Example App: Add a dialog to enter `maxWidth`, `maxHeight` or `quality` when picking image. ## 0.6.2+1 * Android: Fix a crash when a non-image file is picked. * Android: Fix unwanted bitmap scaling. ## 0.6.2 * iOS: Fixes an issue where picking content from Gallery would result in a crash on iOS 13. ## 0.6.1+11 * Stability and Maintainability: update documentations, add unit tests. ## 0.6.1+10 * iOS: Fix image orientation problems when scaling images. ## 0.6.1+9 * Remove AndroidX warning. ## 0.6.1+8 * Fix iOS build and analyzer warnings. ## 0.6.1+7 * Android: Fix ImagePickerPlugin#onCreate casting context which causes exception. ## 0.6.1+6 * Define clang module for iOS ## 0.6.1+5 * Update and migrate iOS example project. ## 0.6.1+4 * Android: Fix a regression where the `retrieveLostImage` does not work anymore. * Set up Android unit test to test `ImagePickerCache` and added image quality caching tests. ## 0.6.1+3 * Bugfix iOS: Fix orientation of the picked image after scaling. * Remove unnecessary code that tried to normalize the orientation. * Trivial XCTest code fix. ## 0.6.1+2 * Replace dependency on `androidx.legacy:legacy-support-v4:1.0.0` with `androidx.core:core:1.0.2` ## 0.6.1+1 * Add dependency on `androidx.annotation:annotation:1.0.0`. ## 0.6.1 * New feature : Get images with custom quality. While picking images, user can pass `imageQuality` parameter to compress image. ## 0.6.0+20 * Android: Migrated information cache methods to use instance methods. ## 0.6.0+19 * Android: Fix memory leak due not unregistering ActivityLifecycleCallbacks. ## 0.6.0+18 * Fix video play in example and update video_player plugin dependency. ## 0.6.0+17 * iOS: Fix a crash when user captures image from the camera with devices under iOS 11. ## 0.6.0+16 * iOS Simulator: fix hang after trying to take an image from the non-existent camera. ## 0.6.0+15 * Android: throws an exception when permissions denied instead of ignoring. ## 0.6.0+14 * Fix typo in README. ## 0.6.0+13 * Bugfix Android: Fix a crash occurs in some scenarios when user picks up image from gallery. ## 0.6.0+12 * Use class instead of struct for `GIFInfo` in iOS implementation. ## 0.6.0+11 * Don't use module imports. ## 0.6.0+10 * iOS: support picking GIF from gallery. ## 0.6.0+9 * Add missing template type parameter to `invokeMethod` calls. * Bump minimum Flutter version to 1.5.0. * Replace invokeMethod with invokeMapMethod wherever necessary. ## 0.6.0+8 * Bugfix: Add missed return statement into the image_picker example. ## 0.6.0+7 * iOS: Rename objects to follow Objective-C naming convention to avoid conflicts with other iOS library/frameworks. ## 0.6.0+6 * iOS: Picked image now has all the correct meta data from the original image, includes GPS, orientation and etc. ## 0.6.0+5 * iOS: Add missing import. ## 0.6.0+4 * iOS: Using first byte to determine original image type. * iOS: Added XCTest target. * iOS: The picked image now has the correct EXIF data copied from the original image. ## 0.6.0+3 * Android: fixed assertion failures due to reply messages that were sent on the wrong thread. ## 0.6.0+2 * Android: images are saved with their real extension instead of always using `.jpg`. ## 0.6.0+1 * Android: Using correct suffix syntax when picking image from remote url. ## 0.6.0 * Breaking change iOS: Returned `File` objects when picking videos now always holds the correct path. Before this change, the path returned could have `file://` prepended to it. ## 0.5.4+3 * Fix the example app failing to load picked video. ## 0.5.4+2 * Request Camera permission if it present in Manifest on Android >= M. ## 0.5.4+1 * Bugfix iOS: Cancel button not visible in gallery, if camera was accessed first. ## 0.5.4 * Add `retrieveLostData` to retrieve lost data after MainActivity is killed. ## 0.5.3+2 * Android: fix a crash when the MainActivity is destroyed after selecting the image/video. ## 0.5.3+1 * Update minimum deploy iOS version to 8.0. ## 0.5.3 * Fixed incorrect path being returned from Google Photos on Android. ## 0.5.2 * Check iOS camera authorizationStatus and return an error, if the access was denied. ## 0.5.1 * Android: Do not delete original image after scaling if the image is from gallery. ## 0.5.0+9 * Remove unnecessary temp video file path. ## 0.5.0+8 * Fixed wrong GooglePhotos authority of image Uri. ## 0.5.0+7 * Fix a crash when selecting images from yandex.disk and dropbox. ## 0.5.0+6 * Delete the original image if it was scaled. ## 0.5.0+5 * Remove unnecessary camera permission. ## 0.5.0+4 * Preserve transparency when saving images. ## 0.5.0+3 * Fixed an Android crash when Image Picker is registered without an activity. ## 0.5.0+2 * Log a more detailed warning at build time about the previous AndroidX migration. ## 0.5.0+1 * Fix a crash when user calls the plugin in quick succession on Android. ## 0.5.0 * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. ## 0.4.12+1 * Fix a crash when selecting downloaded images from image picker on certain devices. ## 0.4.12 * Fix a crash when user tap the image mutiple times. ## 0.4.11 * Use `api` to define `support-v4` dependency to allow automatic version resolution. ## 0.4.10 * Depend on full `support-v4` library for ease of use (fixes conflicts with Firebase and libraries) ## 0.4.9 * Bugfix: on iOS prevent to appear one pixel white line on resized image. ## 0.4.8 * Replace the full `com.android.support:appcompat-v7` dependency with `com.android.support:support-core-utils`, which results in smaller APK sizes. * Upgrade support library to 27.1.1 ## 0.4.7 * Added missing video_player package dev dependency. ## 0.4.6 * Added support for picking remote images. ## 0.4.5 * Bugfixes, code cleanup, more test coverage. ## 0.4.4 * Updated Gradle tooling to match Android Studio 3.1.2. ## 0.4.3 * Bugfix: on iOS the `pickVideo` method will now return null when the user cancels picking a video. ## 0.4.2 * Added support for picking videos. * Updated example app to show video preview. ## 0.4.1 * Bugfix: the `pickImage` method will now return null when the user cancels picking the image, instead of hanging indefinitely. * Removed the third party library dependency for taking pictures with the camera. ## 0.4.0 * **Breaking change**. The `source` parameter for the `pickImage` is now required. Also, the `ImageSource.any` option doesn't exist anymore. * Use the native Android image gallery for picking images instead of a custom UI. ## 0.3.1 * Bugfix: Android version correctly asks for runtime camera permission when using `ImageSource.camera`. ## 0.3.0 * **Breaking change**. Set SDK constraints to match the Flutter beta release. ## 0.2.1 * Simplified and upgraded Android project template to Android SDK 27. * Updated package description. ## 0.2.0 * **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found [here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1). ## 0.1.5 * Added FLT prefix to iOS types ## 0.1.4 * Bugfix: canceling image picking threw exception. * Bugfix: errors in plugin state management. ## 0.1.3 * Added optional source argument to pickImage for controlling where the image comes from. ## 0.1.2 * Added optional maxWidth and maxHeight arguments to pickImage. ## 0.1.1 * Updated Gradle repositories declaration to avoid the need for manual configuration in the consuming app. ## 0.1.0+1 * Updated readme and description in pubspec.yaml ## 0.1.0 * Updated dependencies * **Breaking Change**: You need to add a maven section with the "https://maven.google.com" endpoint to the repository section of your `android/build.gradle`. For example: ```gradle allprojects { repositories { jcenter() maven { // NEW url "https://maven.google.com" // NEW } // NEW } } ``` ## 0.0.3 * Fix for crash on iPad when showing the Camera/Gallery selection dialog ## 0.0.2+2 * Updated README ## 0.0.2+1 * Updated README ## 0.0.2 * Fix crash when trying to access camera on a device without camera (e.g. the Simulator) ## 0.0.1 * Initial Release
plugins/packages/image_picker/image_picker/CHANGELOG.md/0
{ "file_path": "plugins/packages/image_picker/image_picker/CHANGELOG.md", "repo_id": "plugins", "token_count": 5753 }
1,294
// 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.util.Log; import androidx.exifinterface.media.ExifInterface; import java.util.Arrays; import java.util.List; class ExifDataCopier { void copyExif(String filePathOri, String filePathDest) { try { ExifInterface oldExif = new ExifInterface(filePathOri); ExifInterface newExif = new ExifInterface(filePathDest); List<String> attributes = Arrays.asList( "FNumber", "ExposureTime", "ISOSpeedRatings", "GPSAltitude", "GPSAltitudeRef", "FocalLength", "GPSDateStamp", "WhiteBalance", "GPSProcessingMethod", "GPSTimeStamp", "DateTime", "Flash", "GPSLatitude", "GPSLatitudeRef", "GPSLongitude", "GPSLongitudeRef", "Make", "Model", "Orientation"); for (String attribute : attributes) { setIfNotNull(oldExif, newExif, attribute); } newExif.saveAttributes(); } catch (Exception ex) { Log.e("ExifDataCopier", "Error preserving Exif data on selected image: " + ex); } } private static void setIfNotNull(ExifInterface oldExif, ExifInterface newExif, String property) { if (oldExif.getAttribute(property) != null) { newExif.setAttribute(property, oldExif.getAttribute(property)); } } }
plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ExifDataCopier.java/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ExifDataCopier.java", "repo_id": "plugins", "token_count": 759 }
1,295
// 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/XCTest.h> #import <os/log.h> const int kElementWaitingTime = 30; @interface ImagePickerFromGalleryUITests : XCTestCase @property(nonatomic, strong) XCUIApplication *app; @end @implementation ImagePickerFromGalleryUITests - (void)setUp { [super setUp]; // Delete the app if already exists, to test permission popups self.continueAfterFailure = NO; self.app = [[XCUIApplication alloc] init]; [self.app launch]; __weak typeof(self) weakSelf = self; [self addUIInterruptionMonitorWithDescription:@"Permission popups" handler:^BOOL(XCUIElement *_Nonnull interruptingElement) { if (@available(iOS 14, *)) { XCUIElement *allPhotoPermission = interruptingElement .buttons[@"Allow Access to All Photos"]; if (![allPhotoPermission waitForExistenceWithTimeout: kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", weakSelf.app.debugDescription); XCTFail(@"Failed due to not able to find " @"allPhotoPermission button with %@ seconds", @(kElementWaitingTime)); } [allPhotoPermission tap]; } else { XCUIElement *ok = interruptingElement.buttons[@"OK"]; if (![ok waitForExistenceWithTimeout: kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", weakSelf.app.debugDescription); XCTFail(@"Failed due to not able to find ok button " @"with %@ seconds", @(kElementWaitingTime)); } [ok tap]; } return YES; }]; } - (void)tearDown { [super tearDown]; [self.app terminate]; } - (void)testCancel { // Find and tap on the pick from gallery button. XCUIElement *imageFromGalleryButton = self.app.otherElements[@"image_picker_example_from_gallery"].firstMatch; if (![imageFromGalleryButton waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find image from gallery button with %@ seconds", @(kElementWaitingTime)); } [imageFromGalleryButton tap]; // Find and tap on the `pick` button. XCUIElement *pickButton = self.app.buttons[@"PICK"].firstMatch; if (![pickButton waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find pick button with %@ seconds", @(kElementWaitingTime)); } [pickButton tap]; // There is a known bug where the permission popups interruption won't get fired until a tap // happened in the app. We expect a permission popup so we do a tap here. [self.app tap]; // Find and tap on the `Cancel` button. XCUIElement *cancelButton = self.app.buttons[@"Cancel"].firstMatch; if (![cancelButton waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find Cancel button with %@ seconds", @(kElementWaitingTime)); } [cancelButton tap]; // Find the "not picked image text". XCUIElement *imageNotPickedText = self.app.staticTexts[@"You have not yet picked an image."].firstMatch; if (![imageNotPickedText waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find imageNotPickedText with %@ seconds", @(kElementWaitingTime)); } } - (void)testPickingFromGallery { [self launchPickerAndPickWithMaxWidth:nil maxHeight:nil quality:nil]; } - (void)testPickingWithContraintsFromGallery { [self launchPickerAndPickWithMaxWidth:@200 maxHeight:@100 quality:@50]; } - (void)launchPickerAndPickWithMaxWidth:(NSNumber *)maxWidth maxHeight:(NSNumber *)maxHeight quality:(NSNumber *)quality { // Find and tap on the pick from gallery button. XCUIElement *imageFromGalleryButton = self.app.otherElements[@"image_picker_example_from_gallery"].firstMatch; if (![imageFromGalleryButton waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find image from gallery button with %@ seconds", @(kElementWaitingTime)); } [imageFromGalleryButton tap]; if (maxWidth != nil) { XCUIElement *field = self.app.textFields[@"Enter maxWidth if desired"].firstMatch; [field tap]; [field typeText:maxWidth.stringValue]; } if (maxHeight != nil) { XCUIElement *field = self.app.textFields[@"Enter maxHeight if desired"].firstMatch; [field tap]; [field typeText:maxHeight.stringValue]; } if (quality != nil) { XCUIElement *field = self.app.textFields[@"Enter quality if desired"].firstMatch; [field tap]; [field typeText:quality.stringValue]; } // Find and tap on the `pick` button. XCUIElement *pickButton = self.app.buttons[@"PICK"].firstMatch; if (![pickButton waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find pick button with %@ seconds", @(kElementWaitingTime)); } [pickButton tap]; // There is a known bug where the permission popups interruption won't get fired until a tap // happened in the app. We expect a permission popup so we do a tap here. [self.app tap]; // Find an image and tap on it. (IOS 14 UI, images are showing directly) XCUIElement *aImage; if (@available(iOS 14, *)) { aImage = [self.app.scrollViews.firstMatch.images elementBoundByIndex:1]; } else { XCUIElement *allPhotosCell = self.app.cells[@"All Photos"].firstMatch; if (![allPhotosCell waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find \"All Photos\" cell with %@ seconds", @(kElementWaitingTime)); } [allPhotosCell tap]; aImage = [self.app.collectionViews elementMatchingType:XCUIElementTypeCollectionView identifier:@"PhotosGridView"] .cells.firstMatch; } os_log_error(OS_LOG_DEFAULT, "description before picking image %@", self.app.debugDescription); if (![aImage waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find an image with %@ seconds", @(kElementWaitingTime)); } [aImage tap]; // Find the picked image. XCUIElement *pickedImage = self.app.images[@"image_picker_example_picked_image"].firstMatch; if (![pickedImage waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription); XCTFail(@"Failed due to not able to find pickedImage with %@ seconds", @(kElementWaitingTime)); } } @end
plugins/packages/image_picker/image_picker_ios/example/ios/RunnerUITests/ImagePickerFromGalleryUITests.m/0
{ "file_path": "plugins/packages/image_picker/image_picker_ios/example/ios/RunnerUITests/ImagePickerFromGalleryUITests.m", "repo_id": "plugins", "token_count": 3813 }
1,296
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../../image_picker_platform_interface.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/image_picker'); /// An implementation of [ImagePickerPlatform] that uses method channels. class MethodChannelImagePicker extends ImagePickerPlatform { /// The MethodChannel that is being used by this implementation of the plugin. @visibleForTesting MethodChannel get channel => _channel; @override Future<PickedFile?> pickImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final String? path = await _getImagePath( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ); return path != null ? PickedFile(path) : null; } @override Future<List<PickedFile>?> pickMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { final List<dynamic>? paths = await _getMultiImagePath( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ); if (paths == null) { return null; } return paths.map((dynamic path) => PickedFile(path as String)).toList(); } Future<List<dynamic>?> _getMultiImagePath({ double? maxWidth, double? maxHeight, int? imageQuality, bool requestFullMetadata = true, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } return _channel.invokeMethod<List<dynamic>?>( 'pickMultiImage', <String, dynamic>{ 'maxWidth': maxWidth, 'maxHeight': maxHeight, 'imageQuality': imageQuality, 'requestFullMetadata': requestFullMetadata, }, ); } Future<String?> _getImagePath({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, bool requestFullMetadata = true, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } return _channel.invokeMethod<String>( 'pickImage', <String, dynamic>{ 'source': source.index, 'maxWidth': maxWidth, 'maxHeight': maxHeight, 'imageQuality': imageQuality, 'cameraDevice': preferredCameraDevice.index, 'requestFullMetadata': requestFullMetadata, }, ); } @override Future<PickedFile?> pickVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? path = await _getVideoPath( source: source, maxDuration: maxDuration, preferredCameraDevice: preferredCameraDevice, ); return path != null ? PickedFile(path) : null; } Future<String?> _getVideoPath({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) { return _channel.invokeMethod<String>( 'pickVideo', <String, dynamic>{ 'source': source.index, 'maxDuration': maxDuration?.inSeconds, 'cameraDevice': preferredCameraDevice.index }, ); } @override Future<LostData> retrieveLostData() async { final Map<String, dynamic>? result = await _channel.invokeMapMethod<String, dynamic>('retrieve'); if (result == null) { return LostData.empty(); } assert(result.containsKey('path') != result.containsKey('errorCode')); final String? type = result['type'] as String?; assert(type == kTypeImage || type == kTypeVideo); RetrieveType? retrieveType; if (type == kTypeImage) { retrieveType = RetrieveType.image; } else if (type == kTypeVideo) { retrieveType = RetrieveType.video; } PlatformException? exception; if (result.containsKey('errorCode')) { exception = PlatformException( code: result['errorCode']! as String, message: result['errorMessage'] as String?); } final String? path = result['path'] as String?; return LostData( file: path != null ? PickedFile(path) : null, exception: exception, type: retrieveType, ); } @override Future<XFile?> getImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final String? path = await _getImagePath( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ); return path != null ? XFile(path) : null; } @override Future<XFile?> getImageFromSource({ required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) async { final String? path = await _getImagePath( source: source, maxHeight: options.maxHeight, maxWidth: options.maxWidth, imageQuality: options.imageQuality, preferredCameraDevice: options.preferredCameraDevice, requestFullMetadata: options.requestFullMetadata, ); return path != null ? XFile(path) : null; } @override Future<List<XFile>?> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { final List<dynamic>? paths = await _getMultiImagePath( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ); if (paths == null) { return null; } return paths.map((dynamic path) => XFile(path as String)).toList(); } @override Future<List<XFile>> getMultiImageWithOptions({ MultiImagePickerOptions options = const MultiImagePickerOptions(), }) async { final List<dynamic>? paths = await _getMultiImagePath( maxWidth: options.imageOptions.maxWidth, maxHeight: options.imageOptions.maxHeight, imageQuality: options.imageOptions.imageQuality, requestFullMetadata: options.imageOptions.requestFullMetadata, ); if (paths == null) { return <XFile>[]; } return paths.map((dynamic path) => XFile(path as String)).toList(); } @override Future<XFile?> getVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? path = await _getVideoPath( source: source, maxDuration: maxDuration, preferredCameraDevice: preferredCameraDevice, ); return path != null ? XFile(path) : null; } @override Future<LostDataResponse> getLostData() async { List<XFile>? pickedFileList; final Map<String, dynamic>? result = await _channel.invokeMapMethod<String, dynamic>('retrieve'); if (result == null) { return LostDataResponse.empty(); } assert(result.containsKey('path') != result.containsKey('errorCode')); final String? type = result['type'] as String?; assert(type == kTypeImage || type == kTypeVideo); RetrieveType? retrieveType; if (type == kTypeImage) { retrieveType = RetrieveType.image; } else if (type == kTypeVideo) { retrieveType = RetrieveType.video; } PlatformException? exception; if (result.containsKey('errorCode')) { exception = PlatformException( code: result['errorCode']! as String, message: result['errorMessage'] as String?); } final String? path = result['path'] as String?; final List<String>? pathList = (result['pathList'] as List<dynamic>?)?.cast<String>(); if (pathList != null) { pickedFileList = <XFile>[]; for (final String path in pathList) { pickedFileList.add(XFile(path)); } } return LostDataResponse( file: path != null ? XFile(path) : null, exception: exception, type: retrieveType, files: pickedFileList, ); } }
plugins/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart", "repo_id": "plugins", "token_count": 3275 }
1,297
name: image_picker_platform_interface description: A common platform interface for the image_picker plugin. repository: https://github.com/flutter/plugins/tree/main/packages/image_picker/image_picker_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22 # NOTE: We strongly prefer non-breaking changes, even at the expense of a # less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes version: 2.6.2 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: cross_file: ^0.3.1+1 flutter: sdk: flutter http: ^0.13.0 plugin_platform_interface: ^2.1.0 dev_dependencies: flutter_test: sdk: flutter
plugins/packages/image_picker/image_picker_platform_interface/pubspec.yaml/0
{ "file_path": "plugins/packages/image_picker/image_picker_platform_interface/pubspec.yaml", "repo_id": "plugins", "token_count": 280 }
1,298
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; import 'package:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:in_app_purchase_android/in_app_purchase_android.dart'; import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart'; import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; import 'consumable_store.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(_MyApp()); } // Auto-consume must be true on iOS. // To try without auto-consume on another platform, change `true` to `false` here. final bool _kAutoConsume = Platform.isIOS || true; const String _kConsumableId = 'consumable'; const String _kUpgradeId = 'upgrade'; const String _kSilverSubscriptionId = 'subscription_silver'; const String _kGoldSubscriptionId = 'subscription_gold'; const List<String> _kProductIds = <String>[ _kConsumableId, _kUpgradeId, _kSilverSubscriptionId, _kGoldSubscriptionId, ]; class _MyApp extends StatefulWidget { @override State<_MyApp> createState() => _MyAppState(); } class _MyAppState extends State<_MyApp> { final InAppPurchase _inAppPurchase = InAppPurchase.instance; late StreamSubscription<List<PurchaseDetails>> _subscription; List<String> _notFoundIds = <String>[]; List<ProductDetails> _products = <ProductDetails>[]; List<PurchaseDetails> _purchases = <PurchaseDetails>[]; List<String> _consumables = <String>[]; bool _isAvailable = false; bool _purchasePending = false; bool _loading = true; String? _queryProductError; @override void initState() { final Stream<List<PurchaseDetails>> purchaseUpdated = _inAppPurchase.purchaseStream; _subscription = purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); }, onDone: () { _subscription.cancel(); }, onError: (Object error) { // handle error here. }); initStoreInfo(); super.initState(); } Future<void> initStoreInfo() async { final bool isAvailable = await _inAppPurchase.isAvailable(); if (!isAvailable) { setState(() { _isAvailable = isAvailable; _products = <ProductDetails>[]; _purchases = <PurchaseDetails>[]; _notFoundIds = <String>[]; _consumables = <String>[]; _purchasePending = false; _loading = false; }); return; } if (Platform.isIOS) { final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = _inAppPurchase .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>(); await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate()); } final ProductDetailsResponse productDetailResponse = await _inAppPurchase.queryProductDetails(_kProductIds.toSet()); if (productDetailResponse.error != null) { setState(() { _queryProductError = productDetailResponse.error!.message; _isAvailable = isAvailable; _products = productDetailResponse.productDetails; _purchases = <PurchaseDetails>[]; _notFoundIds = productDetailResponse.notFoundIDs; _consumables = <String>[]; _purchasePending = false; _loading = false; }); return; } if (productDetailResponse.productDetails.isEmpty) { setState(() { _queryProductError = null; _isAvailable = isAvailable; _products = productDetailResponse.productDetails; _purchases = <PurchaseDetails>[]; _notFoundIds = productDetailResponse.notFoundIDs; _consumables = <String>[]; _purchasePending = false; _loading = false; }); return; } final List<String> consumables = await ConsumableStore.load(); setState(() { _isAvailable = isAvailable; _products = productDetailResponse.productDetails; _notFoundIds = productDetailResponse.notFoundIDs; _consumables = consumables; _purchasePending = false; _loading = false; }); } @override void dispose() { if (Platform.isIOS) { final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = _inAppPurchase .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>(); iosPlatformAddition.setDelegate(null); } _subscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { final List<Widget> stack = <Widget>[]; if (_queryProductError == null) { stack.add( ListView( children: <Widget>[ _buildConnectionCheckTile(), _buildProductList(), _buildConsumableBox(), _buildRestoreButton(), ], ), ); } else { stack.add(Center( child: Text(_queryProductError!), )); } if (_purchasePending) { stack.add( // TODO(goderbauer): Make this const when that's available on stable. // ignore: prefer_const_constructors Stack( children: const <Widget>[ Opacity( opacity: 0.3, child: ModalBarrier(dismissible: false, color: Colors.grey), ), Center( child: CircularProgressIndicator(), ), ], ), ); } return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('IAP Example'), ), body: Stack( children: stack, ), ), ); } Card _buildConnectionCheckTile() { if (_loading) { return const Card(child: ListTile(title: Text('Trying to connect...'))); } final Widget storeHeader = ListTile( leading: Icon(_isAvailable ? Icons.check : Icons.block, color: _isAvailable ? Colors.green : ThemeData.light().colorScheme.error), title: Text('The store is ${_isAvailable ? 'available' : 'unavailable'}.'), ); final List<Widget> children = <Widget>[storeHeader]; if (!_isAvailable) { children.addAll(<Widget>[ const Divider(), ListTile( title: Text('Not connected', style: TextStyle(color: ThemeData.light().colorScheme.error)), subtitle: const Text( 'Unable to connect to the payments processor. Has this app been configured correctly? See the example README for instructions.'), ), ]); } return Card(child: Column(children: children)); } Card _buildProductList() { if (_loading) { return const Card( child: ListTile( leading: CircularProgressIndicator(), title: Text('Fetching products...'))); } if (!_isAvailable) { return const Card(); } const ListTile productHeader = ListTile(title: Text('Products for Sale')); final List<ListTile> productList = <ListTile>[]; if (_notFoundIds.isNotEmpty) { productList.add(ListTile( title: Text('[${_notFoundIds.join(", ")}] not found', style: TextStyle(color: ThemeData.light().colorScheme.error)), subtitle: const Text( 'This app needs special configuration to run. Please see example/README.md for instructions.'))); } // This loading previous purchases code is just a demo. Please do not use this as it is. // In your app you should always verify the purchase data using the `verificationData` inside the [PurchaseDetails] object before trusting it. // We recommend that you use your own server to verify the purchase data. final Map<String, PurchaseDetails> purchases = Map<String, PurchaseDetails>.fromEntries( _purchases.map((PurchaseDetails purchase) { if (purchase.pendingCompletePurchase) { _inAppPurchase.completePurchase(purchase); } return MapEntry<String, PurchaseDetails>(purchase.productID, purchase); })); productList.addAll(_products.map( (ProductDetails productDetails) { final PurchaseDetails? previousPurchase = purchases[productDetails.id]; return ListTile( title: Text( productDetails.title, ), subtitle: Text( productDetails.description, ), trailing: previousPurchase != null ? IconButton( onPressed: () => confirmPriceChange(context), icon: const Icon(Icons.upgrade)) : TextButton( style: TextButton.styleFrom( backgroundColor: Colors.green[800], // TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724 // ignore: deprecated_member_use primary: Colors.white, ), onPressed: () { late PurchaseParam purchaseParam; if (Platform.isAndroid) { // NOTE: If you are making a subscription purchase/upgrade/downgrade, we recommend you to // verify the latest status of you your subscription by using server side receipt validation // and update the UI accordingly. The subscription purchase status shown // inside the app may not be accurate. final GooglePlayPurchaseDetails? oldSubscription = _getOldSubscription(productDetails, purchases); purchaseParam = GooglePlayPurchaseParam( productDetails: productDetails, changeSubscriptionParam: (oldSubscription != null) ? ChangeSubscriptionParam( oldPurchaseDetails: oldSubscription, prorationMode: ProrationMode.immediateWithTimeProration, ) : null); } else { purchaseParam = PurchaseParam( productDetails: productDetails, ); } if (productDetails.id == _kConsumableId) { _inAppPurchase.buyConsumable( purchaseParam: purchaseParam, autoConsume: _kAutoConsume); } else { _inAppPurchase.buyNonConsumable( purchaseParam: purchaseParam); } }, child: Text(productDetails.price), ), ); }, )); return Card( child: Column( children: <Widget>[productHeader, const Divider()] + productList)); } Card _buildConsumableBox() { if (_loading) { return const Card( child: ListTile( leading: CircularProgressIndicator(), title: Text('Fetching consumables...'))); } if (!_isAvailable || _notFoundIds.contains(_kConsumableId)) { return const Card(); } const ListTile consumableHeader = ListTile(title: Text('Purchased consumables')); final List<Widget> tokens = _consumables.map((String id) { return GridTile( child: IconButton( icon: const Icon( Icons.stars, size: 42.0, color: Colors.orange, ), splashColor: Colors.yellowAccent, onPressed: () => consume(id), ), ); }).toList(); return Card( child: Column(children: <Widget>[ consumableHeader, const Divider(), GridView.count( crossAxisCount: 5, shrinkWrap: true, padding: const EdgeInsets.all(16.0), children: tokens, ) ])); } Widget _buildRestoreButton() { if (_loading) { return Container(); } return Padding( padding: const EdgeInsets.all(4.0), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ TextButton( style: TextButton.styleFrom( backgroundColor: Theme.of(context).primaryColor, // TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724 // ignore: deprecated_member_use primary: Colors.white, ), onPressed: () => _inAppPurchase.restorePurchases(), child: const Text('Restore purchases'), ), ], ), ); } Future<void> consume(String id) async { await ConsumableStore.consume(id); final List<String> consumables = await ConsumableStore.load(); setState(() { _consumables = consumables; }); } void showPendingUI() { setState(() { _purchasePending = true; }); } Future<void> deliverProduct(PurchaseDetails purchaseDetails) async { // IMPORTANT!! Always verify purchase details before delivering the product. if (purchaseDetails.productID == _kConsumableId) { await ConsumableStore.save(purchaseDetails.purchaseID!); final List<String> consumables = await ConsumableStore.load(); setState(() { _purchasePending = false; _consumables = consumables; }); } else { setState(() { _purchases.add(purchaseDetails); _purchasePending = false; }); } } void handleError(IAPError error) { setState(() { _purchasePending = false; }); } Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) { // IMPORTANT!! Always verify a purchase before delivering the product. // For the purpose of an example, we directly return true. return Future<bool>.value(true); } void _handleInvalidPurchase(PurchaseDetails purchaseDetails) { // handle invalid purchase here if _verifyPurchase` failed. } Future<void> _listenToPurchaseUpdated( List<PurchaseDetails> purchaseDetailsList) async { for (final PurchaseDetails purchaseDetails in purchaseDetailsList) { if (purchaseDetails.status == PurchaseStatus.pending) { showPendingUI(); } else { if (purchaseDetails.status == PurchaseStatus.error) { handleError(purchaseDetails.error!); } else if (purchaseDetails.status == PurchaseStatus.purchased || purchaseDetails.status == PurchaseStatus.restored) { final bool valid = await _verifyPurchase(purchaseDetails); if (valid) { deliverProduct(purchaseDetails); } else { _handleInvalidPurchase(purchaseDetails); return; } } if (Platform.isAndroid) { if (!_kAutoConsume && purchaseDetails.productID == _kConsumableId) { final InAppPurchaseAndroidPlatformAddition androidAddition = _inAppPurchase.getPlatformAddition< InAppPurchaseAndroidPlatformAddition>(); await androidAddition.consumePurchase(purchaseDetails); } } if (purchaseDetails.pendingCompletePurchase) { await _inAppPurchase.completePurchase(purchaseDetails); } } } } Future<void> confirmPriceChange(BuildContext context) async { if (Platform.isAndroid) { final InAppPurchaseAndroidPlatformAddition androidAddition = _inAppPurchase .getPlatformAddition<InAppPurchaseAndroidPlatformAddition>(); final BillingResultWrapper priceChangeConfirmationResult = await androidAddition.launchPriceChangeConfirmationFlow( sku: 'purchaseId', ); if (context.mounted) { if (priceChangeConfirmationResult.responseCode == BillingResponse.ok) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('Price change accepted'), )); } else { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( priceChangeConfirmationResult.debugMessage ?? 'Price change failed with code ${priceChangeConfirmationResult.responseCode}', ), )); } } } if (Platform.isIOS) { final InAppPurchaseStoreKitPlatformAddition iapStoreKitPlatformAddition = _inAppPurchase .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>(); await iapStoreKitPlatformAddition.showPriceConsentIfNeeded(); } } GooglePlayPurchaseDetails? _getOldSubscription( ProductDetails productDetails, Map<String, PurchaseDetails> purchases) { // This is just to demonstrate a subscription upgrade or downgrade. // This method assumes that you have only 2 subscriptions under a group, 'subscription_silver' & 'subscription_gold'. // The 'subscription_silver' subscription can be upgraded to 'subscription_gold' and // the 'subscription_gold' subscription can be downgraded to 'subscription_silver'. // Please remember to replace the logic of finding the old subscription Id as per your app. // The old subscription is only required on Android since Apple handles this internally // by using the subscription group feature in iTunesConnect. GooglePlayPurchaseDetails? oldSubscription; if (productDetails.id == _kSilverSubscriptionId && purchases[_kGoldSubscriptionId] != null) { oldSubscription = purchases[_kGoldSubscriptionId]! as GooglePlayPurchaseDetails; } else if (productDetails.id == _kGoldSubscriptionId && purchases[_kSilverSubscriptionId] != null) { oldSubscription = purchases[_kSilverSubscriptionId]! as GooglePlayPurchaseDetails; } return oldSubscription; } } /// Example implementation of the /// [`SKPaymentQueueDelegate`](https://developer.apple.com/documentation/storekit/skpaymentqueuedelegate?language=objc). /// /// The payment queue delegate can be implementated to provide information /// needed to complete transactions. class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper { @override bool shouldContinueTransaction( SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) { return true; } @override bool shouldShowPriceConsent() { return false; } }
plugins/packages/in_app_purchase/in_app_purchase/example/lib/main.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase/example/lib/main.dart", "repo_id": "plugins", "token_count": 7723 }
1,299
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.inapppurchase; import android.content.Context; import com.android.billingclient.api.BillingClient; import io.flutter.plugin.common.MethodChannel; /** The implementation for {@link BillingClientFactory} for the plugin. */ final class BillingClientFactoryImpl implements BillingClientFactory { @Override public BillingClient createBillingClient(Context context, MethodChannel channel) { BillingClient.Builder builder = BillingClient.newBuilder(context).enablePendingPurchases(); return builder.setListener(new PluginPurchaseListener(channel)).build(); } }
plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/BillingClientFactoryImpl.java/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/BillingClientFactoryImpl.java", "repo_id": "plugins", "token_count": 202 }
1,300
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.inapppurchaseexample"> <!-- The INTERNET permission is required for development. Specifically, flutter needs it to communicate with the running application to allow setting breakpoints, to provide hot reload, etc. --> <uses-permission android:name="android.permission.INTERNET"/> <application android:label="in_app_purchase_example" android:icon="@mipmap/ic_launcher"> <activity android:name="io.flutter.embedding.android.FlutterActivity" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <meta-data android:name="flutterEmbedding" android:value="2"/> </application> </manifest>
plugins/packages/in_app_purchase/in_app_purchase_android/example/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/example/android/app/src/main/AndroidManifest.xml", "repo_id": "plugins", "token_count": 477 }
1,301
// 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: avoid_print import 'dart:async'; import 'package:flutter/material.dart'; import 'package:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:in_app_purchase_android/in_app_purchase_android.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'consumable_store.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); // When using the Android plugin directly it is mandatory to register // the plugin as default instance as part of initializing the app. InAppPurchaseAndroidPlatform.registerPlatform(); runApp(_MyApp()); } // To try without auto-consume, change `true` to `false` here. const bool _kAutoConsume = true; const String _kConsumableId = 'consumable'; const String _kUpgradeId = 'upgrade'; const String _kSilverSubscriptionId = 'subscription_silver1'; const String _kGoldSubscriptionId = 'subscription_gold1'; const List<String> _kProductIds = <String>[ _kConsumableId, _kUpgradeId, _kSilverSubscriptionId, _kGoldSubscriptionId, ]; class _MyApp extends StatefulWidget { @override State<_MyApp> createState() => _MyAppState(); } class _MyAppState extends State<_MyApp> { final InAppPurchasePlatform _inAppPurchasePlatform = InAppPurchasePlatform.instance; late StreamSubscription<List<PurchaseDetails>> _subscription; List<String> _notFoundIds = <String>[]; List<ProductDetails> _products = <ProductDetails>[]; List<PurchaseDetails> _purchases = <PurchaseDetails>[]; List<String> _consumables = <String>[]; bool _isAvailable = false; bool _purchasePending = false; bool _loading = true; String? _queryProductError; @override void initState() { final Stream<List<PurchaseDetails>> purchaseUpdated = _inAppPurchasePlatform.purchaseStream; _subscription = purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); }, onDone: () { _subscription.cancel(); }, onError: (Object error) { // handle error here. }); initStoreInfo(); super.initState(); } Future<void> initStoreInfo() async { final bool isAvailable = await _inAppPurchasePlatform.isAvailable(); if (!isAvailable) { setState(() { _isAvailable = isAvailable; _products = <ProductDetails>[]; _purchases = <PurchaseDetails>[]; _notFoundIds = <String>[]; _consumables = <String>[]; _purchasePending = false; _loading = false; }); return; } final ProductDetailsResponse productDetailResponse = await _inAppPurchasePlatform.queryProductDetails(_kProductIds.toSet()); if (productDetailResponse.error != null) { setState(() { _queryProductError = productDetailResponse.error!.message; _isAvailable = isAvailable; _products = productDetailResponse.productDetails; _purchases = <PurchaseDetails>[]; _notFoundIds = productDetailResponse.notFoundIDs; _consumables = <String>[]; _purchasePending = false; _loading = false; }); return; } if (productDetailResponse.productDetails.isEmpty) { setState(() { _queryProductError = null; _isAvailable = isAvailable; _products = productDetailResponse.productDetails; _purchases = <PurchaseDetails>[]; _notFoundIds = productDetailResponse.notFoundIDs; _consumables = <String>[]; _purchasePending = false; _loading = false; }); return; } await _inAppPurchasePlatform.restorePurchases(); final List<String> consumables = await ConsumableStore.load(); setState(() { _isAvailable = isAvailable; _products = productDetailResponse.productDetails; _notFoundIds = productDetailResponse.notFoundIDs; _consumables = consumables; _purchasePending = false; _loading = false; }); } @override void dispose() { _subscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { final List<Widget> stack = <Widget>[]; if (_queryProductError == null) { stack.add( ListView( children: <Widget>[ _buildConnectionCheckTile(), _buildProductList(), _buildConsumableBox(), _FeatureCard(), ], ), ); } else { stack.add(Center( child: Text(_queryProductError!), )); } if (_purchasePending) { stack.add( // TODO(goderbauer): Make this const when that's available on stable. // ignore: prefer_const_constructors Stack( children: const <Widget>[ Opacity( opacity: 0.3, child: ModalBarrier(dismissible: false, color: Colors.grey), ), Center( child: CircularProgressIndicator(), ), ], ), ); } return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('IAP Example'), ), body: Stack( children: stack, ), ), ); } Card _buildConnectionCheckTile() { if (_loading) { return const Card(child: ListTile(title: Text('Trying to connect...'))); } final Widget storeHeader = ListTile( leading: Icon(_isAvailable ? Icons.check : Icons.block, color: _isAvailable ? Colors.green : ThemeData.light().colorScheme.error), title: Text('The store is ${_isAvailable ? 'available' : 'unavailable'}.'), ); final List<Widget> children = <Widget>[storeHeader]; if (!_isAvailable) { children.addAll(<Widget>[ const Divider(), ListTile( title: Text('Not connected', style: TextStyle(color: ThemeData.light().colorScheme.error)), subtitle: const Text( 'Unable to connect to the payments processor. Has this app been configured correctly? See the example README for instructions.'), ), ]); } return Card(child: Column(children: children)); } Card _buildProductList() { if (_loading) { return const Card( child: ListTile( leading: CircularProgressIndicator(), title: Text('Fetching products...'))); } if (!_isAvailable) { return const Card(); } const ListTile productHeader = ListTile(title: Text('Products for Sale')); final List<ListTile> productList = <ListTile>[]; if (_notFoundIds.isNotEmpty) { productList.add(ListTile( title: Text('[${_notFoundIds.join(", ")}] not found', style: TextStyle(color: ThemeData.light().colorScheme.error)), subtitle: const Text( 'This app needs special configuration to run. Please see example/README.md for instructions.'))); } // This loading previous purchases code is just a demo. Please do not use this as it is. // In your app you should always verify the purchase data using the `verificationData` inside the [PurchaseDetails] object before trusting it. // We recommend that you use your own server to verify the purchase data. final Map<String, PurchaseDetails> purchases = Map<String, PurchaseDetails>.fromEntries( _purchases.map((PurchaseDetails purchase) { if (purchase.pendingCompletePurchase) { _inAppPurchasePlatform.completePurchase(purchase); } return MapEntry<String, PurchaseDetails>(purchase.productID, purchase); })); productList.addAll(_products.map( (ProductDetails productDetails) { final PurchaseDetails? previousPurchase = purchases[productDetails.id]; return ListTile( title: Text( productDetails.title, ), subtitle: Text( productDetails.description, ), trailing: previousPurchase != null ? IconButton( onPressed: () { final InAppPurchaseAndroidPlatformAddition addition = InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; final SkuDetailsWrapper skuDetails = (productDetails as GooglePlayProductDetails) .skuDetails; addition .launchPriceChangeConfirmationFlow( sku: skuDetails.sku) .then((BillingResultWrapper value) => print( 'confirmationResponse: ${value.responseCode}')); }, icon: const Icon(Icons.upgrade)) : TextButton( style: TextButton.styleFrom( backgroundColor: Colors.green[800], // TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724 // ignore: deprecated_member_use primary: Colors.white, ), onPressed: () { // NOTE: If you are making a subscription purchase/upgrade/downgrade, we recommend you to // verify the latest status of you your subscription by using server side receipt validation // and update the UI accordingly. The subscription purchase status shown // inside the app may not be accurate. final GooglePlayPurchaseDetails? oldSubscription = _getOldSubscription( productDetails as GooglePlayProductDetails, purchases); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: productDetails, changeSubscriptionParam: oldSubscription != null ? ChangeSubscriptionParam( oldPurchaseDetails: oldSubscription, prorationMode: ProrationMode .immediateWithTimeProration) : null); if (productDetails.id == _kConsumableId) { _inAppPurchasePlatform.buyConsumable( purchaseParam: purchaseParam, // ignore: avoid_redundant_argument_values autoConsume: _kAutoConsume); } else { _inAppPurchasePlatform.buyNonConsumable( purchaseParam: purchaseParam); } }, child: Text(productDetails.price), )); }, )); return Card( child: Column( children: <Widget>[productHeader, const Divider()] + productList)); } Card _buildConsumableBox() { if (_loading) { return const Card( child: ListTile( leading: CircularProgressIndicator(), title: Text('Fetching consumables...'))); } if (!_isAvailable || _notFoundIds.contains(_kConsumableId)) { return const Card(); } const ListTile consumableHeader = ListTile(title: Text('Purchased consumables')); final List<Widget> tokens = _consumables.map((String id) { return GridTile( child: IconButton( icon: const Icon( Icons.stars, size: 42.0, color: Colors.orange, ), splashColor: Colors.yellowAccent, onPressed: () => consume(id), ), ); }).toList(); return Card( child: Column(children: <Widget>[ consumableHeader, const Divider(), GridView.count( crossAxisCount: 5, shrinkWrap: true, padding: const EdgeInsets.all(16.0), children: tokens, ) ])); } Future<void> consume(String id) async { await ConsumableStore.consume(id); final List<String> consumables = await ConsumableStore.load(); setState(() { _consumables = consumables; }); } void showPendingUI() { setState(() { _purchasePending = true; }); } Future<void> deliverProduct(PurchaseDetails purchaseDetails) async { // IMPORTANT!! Always verify purchase details before delivering the product. if (purchaseDetails.productID == _kConsumableId) { await ConsumableStore.save(purchaseDetails.purchaseID!); final List<String> consumables = await ConsumableStore.load(); setState(() { _purchasePending = false; _consumables = consumables; }); } else { setState(() { _purchases.add(purchaseDetails); _purchasePending = false; }); } } void handleError(IAPError error) { setState(() { _purchasePending = false; }); } Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) { // IMPORTANT!! Always verify a purchase before delivering the product. // For the purpose of an example, we directly return true. return Future<bool>.value(true); } void _handleInvalidPurchase(PurchaseDetails purchaseDetails) { // handle invalid purchase here if _verifyPurchase` failed. } Future<void> _listenToPurchaseUpdated( List<PurchaseDetails> purchaseDetailsList) async { for (final PurchaseDetails purchaseDetails in purchaseDetailsList) { if (purchaseDetails.status == PurchaseStatus.pending) { showPendingUI(); } else { if (purchaseDetails.status == PurchaseStatus.error) { handleError(purchaseDetails.error!); } else if (purchaseDetails.status == PurchaseStatus.purchased || purchaseDetails.status == PurchaseStatus.restored) { final bool valid = await _verifyPurchase(purchaseDetails); if (valid) { deliverProduct(purchaseDetails); } else { _handleInvalidPurchase(purchaseDetails); return; } } if (!_kAutoConsume && purchaseDetails.productID == _kConsumableId) { final InAppPurchaseAndroidPlatformAddition addition = InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; await addition.consumePurchase(purchaseDetails); } if (purchaseDetails.pendingCompletePurchase) { await _inAppPurchasePlatform.completePurchase(purchaseDetails); } } } } GooglePlayPurchaseDetails? _getOldSubscription( GooglePlayProductDetails productDetails, Map<String, PurchaseDetails> purchases) { // This is just to demonstrate a subscription upgrade or downgrade. // This method assumes that you have only 2 subscriptions under a group, 'subscription_silver' & 'subscription_gold'. // The 'subscription_silver' subscription can be upgraded to 'subscription_gold' and // the 'subscription_gold' subscription can be downgraded to 'subscription_silver'. // Please remember to replace the logic of finding the old subscription Id as per your app. // The old subscription is only required on Android since Apple handles this internally // by using the subscription group feature in iTunesConnect. GooglePlayPurchaseDetails? oldSubscription; if (productDetails.id == _kSilverSubscriptionId && purchases[_kGoldSubscriptionId] != null) { oldSubscription = purchases[_kGoldSubscriptionId]! as GooglePlayPurchaseDetails; } else if (productDetails.id == _kGoldSubscriptionId && purchases[_kSilverSubscriptionId] != null) { oldSubscription = purchases[_kSilverSubscriptionId]! as GooglePlayPurchaseDetails; } return oldSubscription; } } class _FeatureCard extends StatelessWidget { _FeatureCard({Key? key}) : super(key: key); final InAppPurchaseAndroidPlatformAddition addition = InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; @override Widget build(BuildContext context) { return Card( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const ListTile(title: Text('Available features')), const Divider(), for (BillingClientFeature feature in BillingClientFeature.values) _buildFeatureWidget(feature), ])); } Widget _buildFeatureWidget(BillingClientFeature feature) { return FutureBuilder<bool>( future: addition.isFeatureSupported(feature), builder: (BuildContext context, AsyncSnapshot<bool> snapshot) { Color color = Colors.grey; final bool? data = snapshot.data; if (data != null) { color = data ? Colors.green : Colors.red; } return Padding( padding: const EdgeInsets.fromLTRB(16.0, 4.0, 16.0, 4.0), child: Text( _featureToString(feature), style: TextStyle(color: color), ), ); }, ); } String _featureToString(BillingClientFeature feature) { switch (feature) { case BillingClientFeature.inAppItemsOnVR: return 'inAppItemsOnVR'; case BillingClientFeature.priceChangeConfirmation: return 'priceChangeConfirmation'; case BillingClientFeature.subscriptions: return 'subscriptions'; case BillingClientFeature.subscriptionsOnVR: return 'subscriptionsOnVR'; case BillingClientFeature.subscriptionsUpdate: return 'subscriptionsUpdate'; } } }
plugins/packages/in_app_purchase/in_app_purchase_android/example/lib/main.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/example/lib/main.dart", "repo_id": "plugins", "token_count": 7581 }
1,302
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import '../../billing_client_wrappers.dart'; /// The class represents the information of a product as registered in at /// Google Play store front. class GooglePlayProductDetails extends ProductDetails { /// Creates a new Google Play specific product details object with the /// provided details. GooglePlayProductDetails({ required String id, required String title, required String description, required String price, required double rawPrice, required String currencyCode, required this.skuDetails, required String currencySymbol, }) : super( id: id, title: title, description: description, price: price, rawPrice: rawPrice, currencyCode: currencyCode, currencySymbol: currencySymbol, ); /// Generate a [GooglePlayProductDetails] object based on an Android /// [SkuDetailsWrapper] object. factory GooglePlayProductDetails.fromSkuDetails( SkuDetailsWrapper skuDetails, ) { return GooglePlayProductDetails( id: skuDetails.sku, title: skuDetails.title, description: skuDetails.description, price: skuDetails.price, rawPrice: skuDetails.priceAmountMicros / 1000000.0, currencyCode: skuDetails.priceCurrencyCode, currencySymbol: skuDetails.priceCurrencySymbol, skuDetails: skuDetails, ); } /// Points back to the [SkuDetailsWrapper] object that was used to generate /// this [GooglePlayProductDetails] object. final SkuDetailsWrapper skuDetails; }
plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_product_details.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_product_details.dart", "repo_id": "plugins", "token_count": 596 }
1,303
# in_app_purchase_platform_interface A common platform interface for the [`in_app_purchase`][1] plugin. This interface allows platform-specific implementations of the `in_app_purchase` plugin, as well as the plugin itself, to ensure they are supporting the same interface. # Usage To implement a new platform-specific implementation of `in_app_purchase`, extend [`InAppPurchasePlatform`][2] with an implementation that performs the platform-specific behavior, and when you register your plugin, set the default `InAppPurchasePlatform` by calling `InAppPurchasePlatform.setInstance(MyPlatformInAppPurchase())`. To implement functionality that is specific to the platform and is not covered by the [`InAppPurchasePlatform`][2] idiomatic API, extend [`InAppPurchasePlatformAddition`][3] with the platform-specific functionality, and when the plugin is registered, set the addition instance by calling `InAppPurchasePlatformAddition.instance = MyPlatformInAppPurchaseAddition()`. # 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]: ../in_app_purchase [2]: lib/in_app_purchase_platform_interface.dart [3]: lib/in_app_purchase_platform_addition.dart
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/README.md/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/README.md", "repo_id": "plugins", "token_count": 368 }
1,304
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'package:mockito/mockito.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$InAppPurchasePlatform', () { test('Cannot be implemented with `implements`', () { expect(() { InAppPurchasePlatform.instance = ImplementsInAppPurchasePlatform(); // In versions of `package:plugin_platform_interface` prior to fixing // https://github.com/flutter/flutter/issues/109339, an attempt to // implement a platform interface using `implements` would sometimes // throw a `NoSuchMethodError` and other times throw an // `AssertionError`. After the issue is fixed, an `AssertionError` will // always be thrown. For the purpose of this test, we don't really care // what exception is thrown, so just allow any exception. }, throwsA(anything)); }); test('Can be extended', () { InAppPurchasePlatform.instance = ExtendsInAppPurchasePlatform(); }); test('Can be mocked with `implements`', () { InAppPurchasePlatform.instance = MockInAppPurchasePlatform(); }); test( // ignore: lines_longer_than_80_chars 'Default implementation of purchaseStream should throw unimplemented error', () { final ExtendsInAppPurchasePlatform inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); expect( () => inAppPurchasePlatform.purchaseStream, throwsUnimplementedError, ); }); test( // ignore: lines_longer_than_80_chars 'Default implementation of isAvailable should throw unimplemented error', () { final ExtendsInAppPurchasePlatform inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); expect( () => inAppPurchasePlatform.isAvailable(), throwsUnimplementedError, ); }); test( // ignore: lines_longer_than_80_chars 'Default implementation of queryProductDetails should throw unimplemented error', () { final ExtendsInAppPurchasePlatform inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); expect( () => inAppPurchasePlatform.queryProductDetails(<String>{''}), throwsUnimplementedError, ); }); test( // ignore: lines_longer_than_80_chars 'Default implementation of buyNonConsumable should throw unimplemented error', () { final ExtendsInAppPurchasePlatform inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); expect( () => inAppPurchasePlatform.buyNonConsumable( purchaseParam: MockPurchaseParam(), ), throwsUnimplementedError, ); }); test( // ignore: lines_longer_than_80_chars 'Default implementation of buyConsumable should throw unimplemented error', () { final ExtendsInAppPurchasePlatform inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); expect( () => inAppPurchasePlatform.buyConsumable( purchaseParam: MockPurchaseParam(), ), throwsUnimplementedError, ); }); test( // ignore: lines_longer_than_80_chars 'Default implementation of completePurchase should throw unimplemented error', () { final ExtendsInAppPurchasePlatform inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); expect( () => inAppPurchasePlatform.completePurchase(MockPurchaseDetails()), throwsUnimplementedError, ); }); test( // ignore: lines_longer_than_80_chars 'Default implementation of restorePurchases should throw unimplemented error', () { final ExtendsInAppPurchasePlatform inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); expect( () => inAppPurchasePlatform.restorePurchases(), throwsUnimplementedError, ); }); }); group('$InAppPurchasePlatformAddition', () { setUp(() { InAppPurchasePlatformAddition.instance = null; }); test('Default instance is null', () { expect(InAppPurchasePlatformAddition.instance, isNull); }); test('Can be implemented.', () { InAppPurchasePlatformAddition.instance = ImplementsInAppPurchasePlatformAddition(); }); test('InAppPurchasePlatformAddition Can be extended', () { InAppPurchasePlatformAddition.instance = ExtendsInAppPurchasePlatformAddition(); }); test('Can not be a `InAppPurchasePlatform`', () { expect( () => InAppPurchasePlatformAddition.instance = ExtendsInAppPurchasePlatformAdditionIsPlatformInterface(), throwsAssertionError); }); test('Provider can provide', () { ImplementsInAppPurchasePlatformAdditionProvider.register(); final ImplementsInAppPurchasePlatformAdditionProvider provider = ImplementsInAppPurchasePlatformAdditionProvider(); final InAppPurchasePlatformAddition? addition = provider.getPlatformAddition(); expect(addition.runtimeType, ExtendsInAppPurchasePlatformAddition); }); test('Provider can provide `null`', () { final ImplementsInAppPurchasePlatformAdditionProvider provider = ImplementsInAppPurchasePlatformAdditionProvider(); final InAppPurchasePlatformAddition? addition = provider.getPlatformAddition(); expect(addition, isNull); }); }); } class ImplementsInAppPurchasePlatform implements InAppPurchasePlatform { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class MockInAppPurchasePlatform extends Mock with // ignore: prefer_mixin MockPlatformInterfaceMixin implements InAppPurchasePlatform {} class ExtendsInAppPurchasePlatform extends InAppPurchasePlatform {} class MockPurchaseParam extends Mock implements PurchaseParam {} class MockPurchaseDetails extends Mock implements PurchaseDetails {} class ImplementsInAppPurchasePlatformAddition implements InAppPurchasePlatformAddition { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class ExtendsInAppPurchasePlatformAddition extends InAppPurchasePlatformAddition {} class ImplementsInAppPurchasePlatformAdditionProvider implements InAppPurchasePlatformAdditionProvider { static void register() { InAppPurchasePlatformAddition.instance = ExtendsInAppPurchasePlatformAddition(); } @override T getPlatformAddition<T extends InAppPurchasePlatformAddition?>() { return InAppPurchasePlatformAddition.instance as T; } } class ExtendsInAppPurchasePlatformAdditionIsPlatformInterface extends InAppPurchasePlatform implements ExtendsInAppPurchasePlatformAddition {}
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart", "repo_id": "plugins", "token_count": 2494 }
1,305
// 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 "FIAPRequestHandler.h" #import <StoreKit/StoreKit.h> #pragma mark - Main Handler @interface FIAPRequestHandler () <SKProductsRequestDelegate> @property(copy, nonatomic) ProductRequestCompletion completion; @property(strong, nonatomic) SKRequest *request; @end @implementation FIAPRequestHandler - (instancetype)initWithRequest:(SKRequest *)request { self = [super init]; if (self) { self.request = request; request.delegate = self; } return self; } - (void)startProductRequestWithCompletionHandler:(ProductRequestCompletion)completion { self.completion = completion; [self.request start]; } - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { if (self.completion) { self.completion(response, nil); // set the completion to nil here so self.completion won't be triggered again in // requestDidFinish for SKProductRequest. self.completion = nil; } } - (void)requestDidFinish:(SKRequest *)request { if (self.completion) { self.completion(nil, nil); } } - (void)request:(SKRequest *)request didFailWithError:(NSError *)error { if (self.completion) { self.completion(nil, error); } } @end
plugins/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAPRequestHandler.m/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAPRequestHandler.m", "repo_id": "plugins", "token_count": 442 }
1,306
// 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/XCTest.h> @import in_app_purchase_storekit; @interface FIATransactionCacheTests : XCTestCase @end @implementation FIATransactionCacheTests - (void)testAddObjectsForNewKey { NSArray *dummyArray = @[ @1, @2, @3 ]; FIATransactionCache *cache = [[FIATransactionCache alloc] init]; [cache addObjects:dummyArray forKey:TransactionCacheKeyUpdatedTransactions]; XCTAssertEqual(dummyArray, [cache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]); } - (void)testAddObjectsForExistingKey { NSArray *dummyArray = @[ @1, @2, @3 ]; FIATransactionCache *cache = [[FIATransactionCache alloc] init]; [cache addObjects:dummyArray forKey:TransactionCacheKeyUpdatedTransactions]; XCTAssertEqual(dummyArray, [cache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]); [cache addObjects:@[ @4, @5, @6 ] forKey:TransactionCacheKeyUpdatedTransactions]; NSArray *expected = @[ @1, @2, @3, @4, @5, @6 ]; XCTAssertEqualObjects(expected, [cache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]); } - (void)testGetObjectsForNonExistingKey { FIATransactionCache *cache = [[FIATransactionCache alloc] init]; XCTAssertNil([cache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]); } - (void)testClear { NSArray *fakeUpdatedTransactions = @[ @1, @2, @3 ]; NSArray *fakeRemovedTransactions = @[ @"Remove 1", @"Remove 2", @"Remove 3" ]; NSArray *fakeUpdatedDownloads = @[ @"Download 1", @"Download 2" ]; FIATransactionCache *cache = [[FIATransactionCache alloc] init]; [cache addObjects:fakeUpdatedTransactions forKey:TransactionCacheKeyUpdatedTransactions]; [cache addObjects:fakeRemovedTransactions forKey:TransactionCacheKeyRemovedTransactions]; [cache addObjects:fakeUpdatedDownloads forKey:TransactionCacheKeyUpdatedDownloads]; XCTAssertEqual(fakeUpdatedTransactions, [cache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]); XCTAssertEqual(fakeRemovedTransactions, [cache getObjectsForKey:TransactionCacheKeyRemovedTransactions]); XCTAssertEqual(fakeUpdatedDownloads, [cache getObjectsForKey:TransactionCacheKeyUpdatedDownloads]); [cache clear]; XCTAssertNil([cache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]); XCTAssertNil([cache getObjectsForKey:TransactionCacheKeyRemovedTransactions]); XCTAssertNil([cache getObjectsForKey:TransactionCacheKeyUpdatedDownloads]); } @end
plugins/packages/in_app_purchase/in_app_purchase_storekit/example/ios/RunnerTests/FIATransactionCacheTests.m/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/example/ios/RunnerTests/FIATransactionCacheTests.m", "repo_id": "plugins", "token_count": 843 }
1,307
// 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 <StoreKit/StoreKit.h> NS_ASSUME_NONNULL_BEGIN @interface FIAObjectTranslator : NSObject // Converts an instance of SKProduct into a dictionary. + (NSDictionary *)getMapFromSKProduct:(SKProduct *)product; // Converts an instance of SKProductSubscriptionPeriod into a dictionary. + (NSDictionary *)getMapFromSKProductSubscriptionPeriod:(SKProductSubscriptionPeriod *)period API_AVAILABLE(ios(11.2)); // Converts an instance of SKProductDiscount into a dictionary. + (NSDictionary *)getMapFromSKProductDiscount:(SKProductDiscount *)discount API_AVAILABLE(ios(11.2)); // Converts an array of SKProductDiscount instances into an array of dictionaries. + (nonnull NSArray *)getMapArrayFromSKProductDiscounts: (nonnull NSArray<SKProductDiscount *> *)productDiscounts API_AVAILABLE(ios(12.2)); // Converts an instance of SKProductsResponse into a dictionary. + (NSDictionary *)getMapFromSKProductsResponse:(SKProductsResponse *)productResponse; // Converts an instance of SKPayment into a dictionary. + (NSDictionary *)getMapFromSKPayment:(SKPayment *)payment; // Converts an instance of NSLocale into a dictionary. + (NSDictionary *)getMapFromNSLocale:(NSLocale *)locale; // Creates an instance of the SKMutablePayment class based on the supplied dictionary. + (SKMutablePayment *)getSKMutablePaymentFromMap:(NSDictionary *)map; // Converts an instance of SKPaymentTransaction into a dictionary. + (NSDictionary *)getMapFromSKPaymentTransaction:(SKPaymentTransaction *)transaction; // Converts an instance of NSError into a dictionary. + (NSDictionary *)getMapFromNSError:(NSError *)error; // Converts an instance of SKStorefront into a dictionary. + (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront API_AVAILABLE(ios(13), macos(10.15), watchos(6.2)); // Converts the supplied instances of SKStorefront and SKPaymentTransaction into a dictionary. + (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront andSKPaymentTransaction:(SKPaymentTransaction *)transaction API_AVAILABLE(ios(13), macos(10.15), watchos(6.2)); // Creates an instance of the SKPaymentDiscount class based on the supplied dictionary. + (nullable SKPaymentDiscount *)getSKPaymentDiscountFromMap:(NSDictionary *)map withError:(NSString *_Nullable *_Nullable)error API_AVAILABLE(ios(12.2)); @end ; NS_ASSUME_NONNULL_END
plugins/packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAObjectTranslator.h/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAObjectTranslator.h", "repo_id": "plugins", "token_count": 849 }
1,308
// 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'; /// Method channel for the plugin's platform<-->Dart calls. const MethodChannel channel = MethodChannel('plugins.flutter.io/in_app_purchase'); /// Method channel used to deliver the payment queue delegate system calls to /// Dart. const MethodChannel paymentQueueDelegateChannel = MethodChannel('plugins.flutter.io/in_app_purchase_payment_queue_delegate');
plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/channel.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/channel.dart", "repo_id": "plugins", "token_count": 155 }
1,309
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'sk_storefront_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** SKStorefrontWrapper _$SKStorefrontWrapperFromJson(Map json) => SKStorefrontWrapper( countryCode: json['countryCode'] as String, identifier: json['identifier'] as String, ); Map<String, dynamic> _$SKStorefrontWrapperToJson( SKStorefrontWrapper instance) => <String, dynamic>{ 'countryCode': instance.countryCode, 'identifier': instance.identifier, };
plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.g.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.g.dart", "repo_id": "plugins", "token_count": 201 }
1,310
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSUInteger, TransactionCacheKey) { TransactionCacheKeyUpdatedDownloads, TransactionCacheKeyUpdatedTransactions, TransactionCacheKeyRemovedTransactions }; @interface FIATransactionCache : NSObject /// Adds objects to the transaction cache. /// /// If the cache already contains an array of objects on the specified key, the supplied /// array will be appended to the existing array. - (void)addObjects:(NSArray *)objects forKey:(TransactionCacheKey)key; /// Gets the array of objects stored at the given key. /// /// If there are no objects associated with the given key nil is returned. - (NSArray *)getObjectsForKey:(TransactionCacheKey)key; /// Removes all objects from the transaction cache. - (void)clear; @end NS_ASSUME_NONNULL_END
plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/FIATransactionCache.h/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/FIATransactionCache.h", "repo_id": "plugins", "token_count": 262 }
1,311
// 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 ios_platform_images; @import XCTest; @interface IosPlatformImagesTests : XCTestCase @end @implementation IosPlatformImagesTests - (void)testPlugin { IosPlatformImagesPlugin *plugin = [[IosPlatformImagesPlugin alloc] init]; XCTAssertNotNil(plugin); } @end
plugins/packages/ios_platform_images/example/ios/RunnerTests/IosPlatformImagesTests.m/0
{ "file_path": "plugins/packages/ios_platform_images/example/ios/RunnerTests/IosPlatformImagesTests.m", "repo_id": "plugins", "token_count": 135 }
1,312
include ':app' def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() def plugins = new Properties() def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') if (pluginsFile.exists()) { pluginsFile.withInputStream { stream -> plugins.load(stream) } } plugins.each { name, path -> def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() include ":$name" project(":$name").projectDir = pluginDirectory }
plugins/packages/local_auth/local_auth/example/android/settings.gradle/0
{ "file_path": "plugins/packages/local_auth/local_auth/example/android/settings.gradle", "repo_id": "plugins", "token_count": 151 }
1,313
rootProject.name = 'local_auth'
plugins/packages/local_auth/local_auth_android/android/settings.gradle/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/android/settings.gradle", "repo_id": "plugins", "token_count": 11 }
1,314
// 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'; /// Options wrapper for [LocalAuthPlatform.authenticate] parameters. @immutable class AuthenticationOptions { /// Constructs a new instance. const AuthenticationOptions({ this.useErrorDialogs = true, this.stickyAuth = false, this.sensitiveTransaction = true, this.biometricOnly = false, }); /// Whether the system will attempt to handle user-fixable issues encountered /// while authenticating. For instance, if a fingerprint reader exists on the /// device but there's no fingerprint registered, the plugin might attempt to /// take the user to settings to add one. Anything that is not user fixable, /// such as no biometric sensor on device, will still result in /// a [PlatformException]. final bool useErrorDialogs; /// Used when the application goes into background for any reason while the /// authentication is in progress. Due to security reasons, the /// authentication has to be stopped at that time. If stickyAuth is set to /// true, authentication resumes when the app is resumed. If it is set to /// false (default), then as soon as app is paused a failure message is sent /// back to Dart and it is up to the client app to restart authentication or /// do something else. final bool stickyAuth; /// Whether platform specific precautions are enabled. For instance, on face /// unlock, Android opens a confirmation dialog after the face is recognized /// to make sure the user meant to unlock their device. final bool sensitiveTransaction; /// Prevent authentications from using non-biometric local authentication /// such as pin, passcode, or pattern. final bool biometricOnly; @override bool operator ==(Object other) => identical(this, other) || other is AuthenticationOptions && runtimeType == other.runtimeType && useErrorDialogs == other.useErrorDialogs && stickyAuth == other.stickyAuth && sensitiveTransaction == other.sensitiveTransaction && biometricOnly == other.biometricOnly; @override int get hashCode => Object.hash( useErrorDialogs, stickyAuth, sensitiveTransaction, biometricOnly, ); }
plugins/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart/0
{ "file_path": "plugins/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart", "repo_id": "plugins", "token_count": 658 }
1,315
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:local_auth_platform_interface/local_auth_platform_interface.dart'; import 'src/messages.g.dart'; export 'package:local_auth_platform_interface/types/auth_messages.dart'; export 'package:local_auth_platform_interface/types/auth_options.dart'; export 'package:local_auth_platform_interface/types/biometric_type.dart'; export 'package:local_auth_windows/types/auth_messages_windows.dart'; /// The implementation of [LocalAuthPlatform] for Windows. class LocalAuthWindows extends LocalAuthPlatform { /// Creates a new plugin implementation instance. LocalAuthWindows({ @visibleForTesting LocalAuthApi? api, }) : _api = api ?? LocalAuthApi(); final LocalAuthApi _api; /// Registers this class as the default instance of [LocalAuthPlatform]. static void registerWith() { LocalAuthPlatform.instance = LocalAuthWindows(); } @override Future<bool> authenticate({ required String localizedReason, required Iterable<AuthMessages> authMessages, AuthenticationOptions options = const AuthenticationOptions(), }) async { assert(localizedReason.isNotEmpty); if (options.biometricOnly) { throw UnsupportedError( "Windows doesn't support the biometricOnly parameter."); } return _api.authenticate(localizedReason); } @override Future<bool> deviceSupportsBiometrics() async { // Biometrics are supported on any supported device. return isDeviceSupported(); } @override Future<List<BiometricType>> getEnrolledBiometrics() async { // Windows doesn't support querying specific biometric types. Since the // OS considers this a strong authentication API, return weak+strong on // any supported device. if (await isDeviceSupported()) { return <BiometricType>[BiometricType.weak, BiometricType.strong]; } return <BiometricType>[]; } @override Future<bool> isDeviceSupported() async => _api.isDeviceSupported(); /// Always returns false as this method is not supported on Windows. @override Future<bool> stopAuthentication() async => false; }
plugins/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart/0
{ "file_path": "plugins/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart", "repo_id": "plugins", "token_count": 678 }
1,316
org.gradle.jvmargs=-Xmx4G android.enableR8=true android.useAndroidX=true android.enableJetifier=true
plugins/packages/path_provider/path_provider/example/android/gradle.properties/0
{ "file_path": "plugins/packages/path_provider/path_provider/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,317
group 'io.flutter.plugins.pathprovider' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.3.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { compileSdkVersion 31 defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } lintOptions { 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.5.0' testImplementation 'junit:junit:4.13.2' }
plugins/packages/path_provider/path_provider_android/android/build.gradle/0
{ "file_path": "plugins/packages/path_provider/path_provider_android/android/build.gradle", "repo_id": "plugins", "token_count": 543 }
1,318
// 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:path_provider_android/messages.g.dart' as messages; import 'package:path_provider_android/path_provider_android.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; import 'messages_test.g.dart'; const String kTemporaryPath = 'temporaryPath'; const String kApplicationSupportPath = 'applicationSupportPath'; const String kLibraryPath = 'libraryPath'; const String kApplicationDocumentsPath = 'applicationDocumentsPath'; const String kExternalCachePaths = 'externalCachePaths'; const String kExternalStoragePaths = 'externalStoragePaths'; const String kDownloadsPath = 'downloadsPath'; class _Api implements TestPathProviderApi { @override String? getApplicationDocumentsPath() => kApplicationDocumentsPath; @override String? getApplicationSupportPath() => kApplicationSupportPath; @override List<String?> getExternalCachePaths() => <String>[kExternalCachePaths]; @override String? getExternalStoragePath() => kExternalStoragePaths; @override List<String?> getExternalStoragePaths(messages.StorageDirectory directory) => <String>[kExternalStoragePaths]; @override String? getTemporaryPath() => kTemporaryPath; } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('PathProviderAndroid', () { late PathProviderAndroid pathProvider; setUp(() async { pathProvider = PathProviderAndroid(); TestPathProviderApi.setup(_Api()); }); test('getTemporaryPath', () async { final String? path = await pathProvider.getTemporaryPath(); expect(path, kTemporaryPath); }); test('getApplicationSupportPath', () async { final String? path = await pathProvider.getApplicationSupportPath(); expect(path, kApplicationSupportPath); }); test('getLibraryPath fails', () async { try { await pathProvider.getLibraryPath(); fail('should throw UnsupportedError'); } catch (e) { expect(e, isUnsupportedError); } }); test('getApplicationDocumentsPath', () async { final String? path = await pathProvider.getApplicationDocumentsPath(); expect(path, kApplicationDocumentsPath); }); test('getExternalCachePaths succeeds', () async { final List<String>? result = await pathProvider.getExternalCachePaths(); expect(result!.length, 1); expect(result.first, kExternalCachePaths); }); for (final StorageDirectory? type in <StorageDirectory?>[ ...StorageDirectory.values ]) { test('getExternalStoragePaths (type: $type) android succeeds', () async { final List<String>? result = await pathProvider.getExternalStoragePaths(type: type); expect(result!.length, 1); expect(result.first, kExternalStoragePaths); }); } // end of for-loop test('getDownloadsPath fails', () async { try { await pathProvider.getDownloadsPath(); fail('should throw UnsupportedError'); } catch (e) { expect(e, isUnsupportedError); } }); }); }
plugins/packages/path_provider/path_provider_android/test/path_provider_android_test.dart/0
{ "file_path": "plugins/packages/path_provider/path_provider_android/test/path_provider_android_test.dart", "repo_id": "plugins", "token_count": 1081 }
1,319
// 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 #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #endif public class PathProviderPlugin: NSObject, FlutterPlugin, PathProviderApi { public static func register(with registrar: FlutterPluginRegistrar) { let instance = PathProviderPlugin() // Workaround for https://github.com/flutter/flutter/issues/118103. #if os(iOS) let messenger = registrar.messenger() #else let messenger = registrar.messenger #endif PathProviderApiSetup.setUp(binaryMessenger: messenger, api: instance) } func getDirectoryPath(type: DirectoryType) -> String? { var path = getDirectory(ofType: fileManagerDirectoryForType(type)) #if os(macOS) // In a non-sandboxed app, this is a shared directory where applications are // expected to use its bundle ID as a subdirectory. (For non-sandboxed apps, // adding the extra path is harmless). // This is not done for iOS, for compatibility with older versions of the // plugin. if type == .applicationSupport { if let basePath = path { let basePathURL = URL.init(fileURLWithPath: basePath) path = basePathURL.appendingPathComponent(Bundle.main.bundleIdentifier!).path } } #endif return path } } /// Returns the FileManager constant corresponding to the given type. private func fileManagerDirectoryForType(_ type: DirectoryType) -> FileManager.SearchPathDirectory { switch type { case .applicationDocuments: return FileManager.SearchPathDirectory.documentDirectory case .applicationSupport: return FileManager.SearchPathDirectory.applicationSupportDirectory case .downloads: return FileManager.SearchPathDirectory.downloadsDirectory case .library: return FileManager.SearchPathDirectory.libraryDirectory case .temp: return FileManager.SearchPathDirectory.cachesDirectory } } /// Returns the user-domain directory of the given type. private func getDirectory(ofType directory: FileManager.SearchPathDirectory) -> String? { let paths = NSSearchPathForDirectoriesInDomains( directory, FileManager.SearchPathDomainMask.userDomainMask, true) return paths.first }
plugins/packages/path_provider/path_provider_foundation/ios/Classes/PathProviderPlugin.swift/0
{ "file_path": "plugins/packages/path_provider/path_provider_foundation/ios/Classes/PathProviderPlugin.swift", "repo_id": "plugins", "token_count": 710 }
1,320
// 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:plugin_platform_interface/plugin_platform_interface.dart'; import 'src/enums.dart'; import 'src/method_channel_path_provider.dart'; export 'src/enums.dart'; /// The interface that implementations of path_provider must implement. /// /// Platform implementations should extend this class rather than implement it as `PathProvider` /// does not consider newly added methods to be breaking changes. Extending this class /// (using `extends`) ensures that the subclass will get the default implementation, while /// platform implementations that `implements` this interface will be broken by newly added /// [PathProviderPlatform] methods. abstract class PathProviderPlatform extends PlatformInterface { /// Constructs a PathProviderPlatform. PathProviderPlatform() : super(token: _token); static final Object _token = Object(); static PathProviderPlatform _instance = MethodChannelPathProvider(); /// The default instance of [PathProviderPlatform] to use. /// /// Defaults to [MethodChannelPathProvider]. static PathProviderPlatform get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [PathProviderPlatform] when they register themselves. static set instance(PathProviderPlatform instance) { PlatformInterface.verify(instance, _token); _instance = instance; } /// Path to the temporary directory on the device that is not backed up and is /// suitable for storing caches of downloaded files. Future<String?> getTemporaryPath() { throw UnimplementedError('getTemporaryPath() has not been implemented.'); } /// Path to a directory where the application may place application support /// files. Future<String?> getApplicationSupportPath() { throw UnimplementedError( 'getApplicationSupportPath() has not been implemented.'); } /// Path to the directory where application can store files that are persistent, /// backed up, and not visible to the user, such as sqlite.db. Future<String?> getLibraryPath() { throw UnimplementedError('getLibraryPath() has not been implemented.'); } /// Path to a directory where the application may place data that is /// user-generated, or that cannot otherwise be recreated by your application. Future<String?> getApplicationDocumentsPath() { throw UnimplementedError( 'getApplicationDocumentsPath() has not been implemented.'); } /// Path to a directory where the application may access top level storage. /// The current operating system should be determined before issuing this /// function call, as this functionality is only available on Android. Future<String?> getExternalStoragePath() { throw UnimplementedError( 'getExternalStoragePath() has not been implemented.'); } /// Paths to directories where application specific external cache data can be /// stored. These paths typically reside on external storage like separate /// partitions or SD cards. Phones may have multiple storage directories /// available. Future<List<String>?> getExternalCachePaths() { throw UnimplementedError( 'getExternalCachePaths() has not been implemented.'); } /// Paths to directories where application specific data can be stored. /// These paths typically reside on external storage like separate partitions /// or SD cards. Phones may have multiple storage directories available. Future<List<String>?> getExternalStoragePaths({ /// Optional parameter. See [StorageDirectory] for more informations on /// how this type translates to Android storage directories. StorageDirectory? type, }) { throw UnimplementedError( 'getExternalStoragePaths() has not been implemented.'); } /// Path to the directory where downloaded files can be stored. /// This is typically only relevant on desktop operating systems. Future<String?> getDownloadsPath() { throw UnimplementedError('getDownloadsPath() has not been implemented.'); } }
plugins/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart/0
{ "file_path": "plugins/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart", "repo_id": "plugins", "token_count": 1057 }
1,321
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. library plugin_platform_interface; import 'package:meta/meta.dart'; /// Base class for platform interfaces. /// /// Provides a static helper method for ensuring that platform interfaces are /// implemented using `extends` instead of `implements`. /// /// Platform interface classes are expected to have a private static token object which will be /// be passed to [verify] along with a platform interface object for verification. /// /// Sample usage: /// /// ```dart /// abstract class UrlLauncherPlatform extends PlatformInterface { /// UrlLauncherPlatform() : super(token: _token); /// /// static UrlLauncherPlatform _instance = MethodChannelUrlLauncher(); /// /// static final Object _token = Object(); /// /// static UrlLauncherPlatform get instance => _instance; /// /// /// Platform-specific plugins should set this with their own platform-specific /// /// class that extends [UrlLauncherPlatform] when they register themselves. /// static set instance(UrlLauncherPlatform instance) { /// PlatformInterface.verify(instance, _token); /// _instance = instance; /// } /// /// } /// ``` /// /// Mockito mocks of platform interfaces will fail the verification, in test code only it is possible /// to include the [MockPlatformInterfaceMixin] for the verification to be temporarily disabled. See /// [MockPlatformInterfaceMixin] for a sample of using Mockito to mock a platform interface. abstract class PlatformInterface { /// Constructs a PlatformInterface, for use only in constructors of abstract /// derived classes. /// /// @param token The same, non-`const` `Object` that will be passed to `verify`. PlatformInterface({required Object token}) { _instanceTokens[this] = token; } /// Expando mapping instances of PlatformInterface to their associated tokens. /// The reason this is not simply a private field of type `Object?` is because /// as of the implementation of field promotion in Dart /// (https://github.com/dart-lang/language/issues/2020), it is a runtime error /// to invoke a private member that is mocked in another library. The expando /// approach prevents [_verify] from triggering this runtime exception when /// encountering an implementation that uses `implements` rather than /// `extends`. This in turn allows [_verify] to throw an [AssertionError] (as /// documented). static final Expando<Object> _instanceTokens = Expando<Object>(); /// Ensures that the platform instance was constructed with a non-`const` token /// that matches the provided token and throws [AssertionError] if not. /// /// This is used to ensure that implementers are using `extends` rather than /// `implements`. /// /// Subclasses of [MockPlatformInterfaceMixin] are assumed to be valid in debug /// builds. /// /// This is implemented as a static method so that it cannot be overridden /// with `noSuchMethod`. static void verify(PlatformInterface instance, Object token) { _verify(instance, token, preventConstObject: true); } /// Performs the same checks as `verify` but without throwing an /// [AssertionError] if `const Object()` is used as the instance token. /// /// This method will be deprecated in a future release. static void verifyToken(PlatformInterface instance, Object token) { _verify(instance, token, preventConstObject: false); } static void _verify( PlatformInterface instance, Object token, { required bool preventConstObject, }) { if (instance is MockPlatformInterfaceMixin) { bool assertionsEnabled = false; assert(() { assertionsEnabled = true; return true; }()); if (!assertionsEnabled) { throw AssertionError( '`MockPlatformInterfaceMixin` is not intended for use in release builds.'); } return; } if (preventConstObject && identical(_instanceTokens[instance], const Object())) { throw AssertionError('`const Object()` cannot be used as the token.'); } if (!identical(token, _instanceTokens[instance])) { throw AssertionError( 'Platform interfaces must not be implemented with `implements`'); } } } /// A [PlatformInterface] mixin that can be combined with fake or mock objects, /// such as test's `Fake` or mockito's `Mock`. /// /// It passes the [PlatformInterface.verify] check even though it isn't /// using `extends`. /// /// This class is intended for use in tests only. /// /// Sample usage (assuming `UrlLauncherPlatform` extends [PlatformInterface]): /// /// ```dart /// class UrlLauncherPlatformMock extends Mock /// with MockPlatformInterfaceMixin /// implements UrlLauncherPlatform {} /// ``` @visibleForTesting abstract class MockPlatformInterfaceMixin implements PlatformInterface {}
plugins/packages/plugin_platform_interface/lib/plugin_platform_interface.dart/0
{ "file_path": "plugins/packages/plugin_platform_interface/lib/plugin_platform_interface.dart", "repo_id": "plugins", "token_count": 1389 }
1,322
// 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:quick_actions_platform_interface/platform_interface/quick_actions_platform.dart'; import 'package:quick_actions_platform_interface/types/types.dart'; export 'package:quick_actions_platform_interface/types/types.dart'; /// Quick actions plugin. class QuickActions { /// Creates a new instance of [QuickActions]. const QuickActions(); /// Initializes this plugin. /// /// Call this once before any further interaction with the plugin. Future<void> initialize(QuickActionHandler handler) async => QuickActionsPlatform.instance.initialize(handler); /// Sets the [ShortcutItem]s to become the app's quick actions. Future<void> setShortcutItems(List<ShortcutItem> items) async => QuickActionsPlatform.instance.setShortcutItems(items); /// Removes all [ShortcutItem]s registered for the app. Future<void> clearShortcutItems() => QuickActionsPlatform.instance.clearShortcutItems(); }
plugins/packages/quick_actions/quick_actions/lib/quick_actions.dart/0
{ "file_path": "plugins/packages/quick_actions/quick_actions/lib/quick_actions.dart", "repo_id": "plugins", "token_count": 320 }
1,323
// 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. @testable import quick_actions_ios final class MockShortcutItemProvider: ShortcutItemProviding { var shortcutItems: [UIApplicationShortcutItem]? = nil }
plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/Mocks/MockShortcutItemProvider.swift/0
{ "file_path": "plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/Mocks/MockShortcutItemProvider.swift", "repo_id": "plugins", "token_count": 88 }
1,324
# Shared preferences plugin [![pub package](https://img.shields.io/pub/v/shared_preferences.svg)](https://pub.dev/packages/shared_preferences) Wraps platform-specific persistent storage for simple data (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc.). Data may be persisted to disk asynchronously, and there is no guarantee that writes will be persisted to disk after returning, so this plugin must not be used for storing critical data. Supported data types are `int`, `double`, `bool`, `String` and `List<String>`. | | Android | iOS | Linux | macOS | Web | Windows | |-------------|---------|------|-------|--------|-----|-------------| | **Support** | SDK 16+ | 9.0+ | Any | 10.11+ | Any | Any | ## Usage To use this plugin, add `shared_preferences` as a [dependency in your pubspec.yaml file](https://flutter.dev/docs/development/platform-integration/platform-channels). ### Examples Here are small examples that show you how to use the API. #### Write data ```dart // Obtain shared preferences. final prefs = await SharedPreferences.getInstance(); // Save an integer value to 'counter' key. await prefs.setInt('counter', 10); // Save an boolean value to 'repeat' key. await prefs.setBool('repeat', true); // Save an double value to 'decimal' key. await prefs.setDouble('decimal', 1.5); // Save an String value to 'action' key. await prefs.setString('action', 'Start'); // Save an list of strings to 'items' key. await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']); ``` #### Read data ```dart // Try reading data from the 'counter' key. If it doesn't exist, returns null. final int? counter = prefs.getInt('counter'); // Try reading data from the 'repeat' key. If it doesn't exist, returns null. final bool? repeat = prefs.getBool('repeat'); // Try reading data from the 'decimal' key. If it doesn't exist, returns null. final double? decimal = prefs.getDouble('decimal'); // Try reading data from the 'action' key. If it doesn't exist, returns null. final String? action = prefs.getString('action'); // Try reading data from the 'items' key. If it doesn't exist, returns null. final List<String>? items = prefs.getStringList('items'); ``` #### Remove an entry ```dart // Remove data for the 'counter' key. final success = await prefs.remove('counter'); ``` ### Testing You can populate `SharedPreferences` with initial values in your tests by running this code: ```dart Map<String, Object> values = <String, Object>{'counter': 1}; SharedPreferences.setMockInitialValues(values); ``` ### Storage location by platform | Platform | Location | | :--- | :--- | | Android | SharedPreferences | | iOS | NSUserDefaults | | Linux | In the XDG_DATA_HOME directory | | macOS | NSUserDefaults | | Web | LocalStorage | | Windows | In the roaming AppData directory |
plugins/packages/shared_preferences/shared_preferences/README.md/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences/README.md", "repo_id": "plugins", "token_count": 863 }
1,325
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
plugins/packages/shared_preferences/shared_preferences/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "plugins", "token_count": 32 }
1,326
name: shared_preferences description: Flutter plugin for reading and writing simple key-value pairs. Wraps NSUserDefaults on iOS and SharedPreferences on Android. repository: https://github.com/flutter/plugins/tree/main/packages/shared_preferences/shared_preferences issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 version: 2.0.17 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: platforms: android: default_package: shared_preferences_android ios: default_package: shared_preferences_foundation linux: default_package: shared_preferences_linux macos: default_package: shared_preferences_foundation web: default_package: shared_preferences_web windows: default_package: shared_preferences_windows dependencies: flutter: sdk: flutter shared_preferences_android: ^2.0.8 shared_preferences_foundation: ^2.1.0 shared_preferences_linux: ^2.0.1 shared_preferences_platform_interface: ^2.0.0 shared_preferences_web: ^2.0.0 shared_preferences_windows: ^2.0.1 dev_dependencies: flutter_driver: sdk: flutter flutter_test: sdk: flutter integration_test: sdk: flutter
plugins/packages/shared_preferences/shared_preferences/pubspec.yaml/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences/pubspec.yaml", "repo_id": "plugins", "token_count": 522 }
1,327
buildscript { ext.kotlin_version = '1.3.50' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.0.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir }
plugins/packages/shared_preferences/shared_preferences_android/example/android/build.gradle/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_android/example/android/build.gradle", "repo_id": "plugins", "token_count": 258 }
1,328
// 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 (v5.0.0), 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 /// Generated class from Pigeon. /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserDefaultsApi { func remove(key: String) func setBool(key: String, value: Bool) func setDouble(key: String, value: Double) func setValue(key: String, value: Any) func getAll() -> [String?: Any?] func clear() } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class UserDefaultsApiSetup { /// The codec used by UserDefaultsApi. /// Sets up an instance of `UserDefaultsApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: UserDefaultsApi?) { let removeChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserDefaultsApi.remove", binaryMessenger: binaryMessenger) if let api = api { removeChannel.setMessageHandler { message, reply in let args = message as! [Any?] let keyArg = args[0] as! String api.remove(key: keyArg) reply(wrapResult(nil)) } } else { removeChannel.setMessageHandler(nil) } let setBoolChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserDefaultsApi.setBool", binaryMessenger: binaryMessenger) if let api = api { setBoolChannel.setMessageHandler { message, reply in let args = message as! [Any?] let keyArg = args[0] as! String let valueArg = args[1] as! Bool api.setBool(key: keyArg, value: valueArg) reply(wrapResult(nil)) } } else { setBoolChannel.setMessageHandler(nil) } let setDoubleChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserDefaultsApi.setDouble", binaryMessenger: binaryMessenger) if let api = api { setDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let keyArg = args[0] as! String let valueArg = args[1] as! Double api.setDouble(key: keyArg, value: valueArg) reply(wrapResult(nil)) } } else { setDoubleChannel.setMessageHandler(nil) } let setValueChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserDefaultsApi.setValue", binaryMessenger: binaryMessenger) if let api = api { setValueChannel.setMessageHandler { message, reply in let args = message as! [Any?] let keyArg = args[0] as! String let valueArg = args[1]! api.setValue(key: keyArg, value: valueArg) reply(wrapResult(nil)) } } else { setValueChannel.setMessageHandler(nil) } let getAllChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserDefaultsApi.getAll", binaryMessenger: binaryMessenger) if let api = api { getAllChannel.setMessageHandler { _, reply in let result = api.getAll() reply(wrapResult(result)) } } else { getAllChannel.setMessageHandler(nil) } let clearChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.UserDefaultsApi.clear", binaryMessenger: binaryMessenger) if let api = api { clearChannel.setMessageHandler { _, reply in api.clear() reply(wrapResult(nil)) } } else { clearChannel.setMessageHandler(nil) } } } private func wrapResult(_ result: Any?) -> [Any?] { return [result] } private func wrapError(_ error: FlutterError) -> [Any?] { return [ error.code, error.message, error.details ] }
plugins/packages/shared_preferences/shared_preferences_foundation/darwin/Classes/messages.g.swift/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/darwin/Classes/messages.g.swift", "repo_id": "plugins", "token_count": 1452 }
1,329
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
plugins/packages/shared_preferences/shared_preferences_foundation/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "plugins", "token_count": 32 }
1,330
name: shared_preferences_web_integration_tests publish_to: none environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter shared_preferences_platform_interface: ^2.0.0 shared_preferences_web: path: ../ dev_dependencies: flutter_driver: sdk: flutter flutter_test: sdk: flutter integration_test: sdk: flutter js: ^0.6.3
plugins/packages/shared_preferences/shared_preferences_web/example/pubspec.yaml/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_web/example/pubspec.yaml", "repo_id": "plugins", "token_count": 179 }
1,331
// 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. // Run this example with: flutter run -t lib/files.dart -d linux // This file is used to extract code samples for the README.md file. // Run update-excerpts if you modify this file. import 'dart:io'; import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; import 'package:url_launcher/url_launcher.dart'; void main() => runApp( const MaterialApp( home: Material( child: Center( child: ElevatedButton( onPressed: _openFile, child: Text('Open File'), ), ), ), ), ); Future<void> _openFile() async { // Prepare a file within tmp final String tempFilePath = p.joinAll(<String>[ ...p.split(Directory.systemTemp.path), 'flutter_url_launcher_example.txt' ]); final File testFile = File(tempFilePath); await testFile.writeAsString('Hello, world!'); // #docregion file final String filePath = testFile.absolute.path; final Uri uri = Uri.file(filePath); if (!File(uri.toFilePath()).existsSync()) { throw Exception('$uri does not exist!'); } if (!await launchUrl(uri)) { throw Exception('Could not launch $uri'); } // #enddocregion file }
plugins/packages/url_launcher/url_launcher/example/lib/files.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher/example/lib/files.dart", "repo_id": "plugins", "token_count": 509 }
1,332
// 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:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'type_conversion.dart'; import 'types.dart'; /// String version of [launchUrl]. /// /// This should be used only in the very rare case of needing to launch a URL /// that is considered valid by the host platform, but not by Dart's [Uri] /// class. In all other cases, use [launchUrl] instead, as that will ensure /// that you are providing a valid URL. /// /// The behavior of this method when passing an invalid URL is entirely /// platform-specific; no effort is made by the plugin to make the URL valid. /// Some platforms may provide best-effort interpretation of an invalid URL, /// others will immediately fail if the URL can't be parsed according to the /// official standards that define URL formats. Future<bool> launchUrlString( String urlString, { LaunchMode mode = LaunchMode.platformDefault, WebViewConfiguration webViewConfiguration = const WebViewConfiguration(), String? webOnlyWindowName, }) async { if (mode == LaunchMode.inAppWebView && !(urlString.startsWith('https:') || urlString.startsWith('http:'))) { throw ArgumentError.value(urlString, 'urlString', 'To use an in-app web view, you must provide an http(s) URL.'); } return UrlLauncherPlatform.instance.launchUrl( urlString, LaunchOptions( mode: convertLaunchMode(mode), webViewConfiguration: convertConfiguration(webViewConfiguration), webOnlyWindowName: webOnlyWindowName, ), ); } /// String version of [canLaunchUrl]. /// /// This should be used only in the very rare case of needing to check a URL /// that is considered valid by the host platform, but not by Dart's [Uri] /// class. In all other cases, use [canLaunchUrl] instead, as that will ensure /// that you are providing a valid URL. /// /// The behavior of this method when passing an invalid URL is entirely /// platform-specific; no effort is made by the plugin to make the URL valid. /// Some platforms may provide best-effort interpretation of an invalid URL, /// others will immediately fail if the URL can't be parsed according to the /// official standards that define URL formats. Future<bool> canLaunchUrlString(String urlString) async { return UrlLauncherPlatform.instance.canLaunch(urlString); }
plugins/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart", "repo_id": "plugins", "token_count": 670 }
1,333
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.urllauncher"> <application> <activity android:name="io.flutter.plugins.urllauncher.WebViewActivity" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:exported="false"/> </application> </manifest>
plugins/packages/url_launcher/url_launcher_android/android/src/main/AndroidManifest.xml/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_android/android/src/main/AndroidManifest.xml", "repo_id": "plugins", "token_count": 120 }
1,334
# url\_launcher\_ios The iOS implementation of [`url_launcher`][1]. ## Usage This package is [endorsed][2], which means you can simply use `url_launcher` normally. This package will be automatically included in your app when you do. [1]: https://pub.dev/packages/url_launcher [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
plugins/packages/url_launcher/url_launcher_ios/README.md/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_ios/README.md", "repo_id": "plugins", "token_count": 123 }
1,335
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('canLaunch', (WidgetTester _) async { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; expect(await launcher.canLaunch('randomstring'), false); // Generally all devices should have some default browser. expect(await launcher.canLaunch('http://flutter.dev'), true); // Generally all devices should have some default SMS app. expect(await launcher.canLaunch('sms:5555555555'), true); }); }
plugins/packages/url_launcher/url_launcher_macos/example/integration_test/url_launcher_test.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_macos/example/integration_test/url_launcher_test.dart", "repo_id": "plugins", "token_count": 262 }
1,336
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import FlutterMacOS import Foundation /// A handler that can launch other apps, check if any app is able to open the URL. public protocol SystemURLHandler { /// Opens the location at the specified URL. /// /// - Parameters: /// - url: A URL specifying the location to open. /// - Returns: true if the location was successfully opened; otherwise, false. func open(_ url: URL) -> Bool /// Returns the URL to the default app that would be opened. /// /// - Parameters: /// - toOpen: The URL of the file to open. /// - Returns: The URL of the default app that would open the specified url. /// Returns nil if no app is able to open the URL, or if the file URL does not exist. func urlForApplication(toOpen: URL) -> URL? } extension NSWorkspace: SystemURLHandler {} public class UrlLauncherPlugin: NSObject, FlutterPlugin { private var workspace: SystemURLHandler public init(_ workspace: SystemURLHandler = NSWorkspace.shared) { self.workspace = workspace } public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel( name: "plugins.flutter.io/url_launcher_macos", binaryMessenger: registrar.messenger) let instance = UrlLauncherPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { let urlString: String? = (call.arguments as? [String: Any])?["url"] as? String switch call.method { case "canLaunch": guard let unwrappedURLString = urlString, let url = URL.init(string: unwrappedURLString) else { result(invalidURLError(urlString)) return } result(workspace.urlForApplication(toOpen: url) != nil) case "launch": guard let unwrappedURLString = urlString, let url = URL.init(string: unwrappedURLString) else { result(invalidURLError(urlString)) return } result(workspace.open(url)) default: result(FlutterMethodNotImplemented) } } } /// Returns an error for the case where a URL string can't be parsed as a URL. private func invalidURLError(_ url: String?) -> FlutterError { return FlutterError( code: "argument_error", message: "Unable to parse URL", details: "Provided URL: \(String(describing: url))") }
plugins/packages/url_launcher/url_launcher_macos/macos/Classes/UrlLauncherPlugin.swift/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_macos/macos/Classes/UrlLauncherPlugin.swift", "repo_id": "plugins", "token_count": 834 }
1,337
// 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:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; class CapturingUrlLauncher extends UrlLauncherPlatform { String? url; bool? useSafariVC; bool? useWebView; bool? enableJavaScript; bool? enableDomStorage; bool? universalLinksOnly; Map<String, String> headers = <String, String>{}; String? webOnlyWindowName; @override final LinkDelegate? linkDelegate = null; @override Future<bool> launch( String url, { required bool useSafariVC, required bool useWebView, required bool enableJavaScript, required bool enableDomStorage, required bool universalLinksOnly, required Map<String, String> headers, String? webOnlyWindowName, }) async { this.url = url; this.useSafariVC = useSafariVC; this.useWebView = useWebView; this.enableJavaScript = enableJavaScript; this.enableDomStorage = enableDomStorage; this.universalLinksOnly = universalLinksOnly; this.headers = headers; this.webOnlyWindowName = webOnlyWindowName; return true; } } void main() { test('launchUrl calls through to launch with default options for web URL', () async { final CapturingUrlLauncher launcher = CapturingUrlLauncher(); await launcher.launchUrl('https://flutter.dev', const LaunchOptions()); expect(launcher.url, 'https://flutter.dev'); expect(launcher.useSafariVC, true); expect(launcher.useWebView, true); expect(launcher.enableJavaScript, true); expect(launcher.enableDomStorage, true); expect(launcher.universalLinksOnly, false); expect(launcher.headers, isEmpty); expect(launcher.webOnlyWindowName, null); }); test('launchUrl calls through to launch with default options for non-web URL', () async { final CapturingUrlLauncher launcher = CapturingUrlLauncher(); await launcher.launchUrl('tel:123456789', const LaunchOptions()); expect(launcher.url, 'tel:123456789'); expect(launcher.useSafariVC, false); expect(launcher.useWebView, false); expect(launcher.enableJavaScript, true); expect(launcher.enableDomStorage, true); expect(launcher.universalLinksOnly, false); expect(launcher.headers, isEmpty); expect(launcher.webOnlyWindowName, null); }); test('launchUrl calls through to launch with universal links', () async { final CapturingUrlLauncher launcher = CapturingUrlLauncher(); await launcher.launchUrl( 'https://flutter.dev', const LaunchOptions( mode: PreferredLaunchMode.externalNonBrowserApplication)); expect(launcher.url, 'https://flutter.dev'); expect(launcher.useSafariVC, false); expect(launcher.useWebView, false); expect(launcher.enableJavaScript, true); expect(launcher.enableDomStorage, true); expect(launcher.universalLinksOnly, true); expect(launcher.headers, isEmpty); expect(launcher.webOnlyWindowName, null); }); test('launchUrl calls through to launch with all non-default options', () async { final CapturingUrlLauncher launcher = CapturingUrlLauncher(); await launcher.launchUrl( 'https://flutter.dev', const LaunchOptions( mode: PreferredLaunchMode.externalApplication, webViewConfiguration: InAppWebViewConfiguration( enableJavaScript: false, enableDomStorage: false, headers: <String, String>{'foo': 'bar'}), webOnlyWindowName: 'a_name', )); expect(launcher.url, 'https://flutter.dev'); expect(launcher.useSafariVC, false); expect(launcher.useWebView, false); expect(launcher.enableJavaScript, false); expect(launcher.enableDomStorage, false); expect(launcher.universalLinksOnly, false); expect(launcher.headers['foo'], 'bar'); expect(launcher.webOnlyWindowName, 'a_name'); }); }
plugins/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart", "repo_id": "plugins", "token_count": 1414 }
1,338