text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// ignore_for_file: prefer_const_constructors import 'dart:ui'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame/game.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/assets_manager/assets_manager.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/more_information/more_information.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball/start_game/start_game.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:share_repository/share_repository.dart'; import '../../helpers/helpers.dart'; class _TestPinballGame extends PinballGame { _TestPinballGame() : super( characterThemeBloc: CharacterThemeCubit(), leaderboardRepository: _MockLeaderboardRepository(), shareRepository: _MockShareRepository(), gameBloc: GameBloc(), l10n: _MockAppLocalizations(), audioPlayer: _MockPinballAudioPlayer(), platformHelper: _MockPlatformHelper(), ); @override Future<void> onLoad() async { images.prefix = ''; final futures = [ ...preLoadAssets(), ...BonusAnimation.loadAssets(), ...SelectedCharacter.loadAssets(), preFetchLeaderboard, ]; await Future.wait<void>( futures.map((loadableBuilder) => loadableBuilder()).toList(), ); return super.onLoad(); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockCharacterThemeCubit extends Mock implements CharacterThemeCubit {} class _MockAssetsManagerCubit extends Mock implements AssetsManagerCubit {} class _MockStartGameBloc extends Mock implements StartGameBloc {} class _MockAppLocalizations extends Mock implements AppLocalizations { @override String get leaderboardErrorMessage => ''; } class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {} class _MockLeaderboardRepository extends Mock implements LeaderboardRepository { } class _MockShareRepository extends Mock implements ShareRepository {} class _MockPlatformHelper extends Mock implements PlatformHelper { @override bool get isMobile => false; } void main() { final game = _TestPinballGame(); group('PinballGamePage', () { late CharacterThemeCubit characterThemeCubit; late GameBloc gameBloc; setUp(() async { await Future.wait<void>( game.preLoadAssets().map((loadableBuilder) => loadableBuilder()), ); characterThemeCubit = _MockCharacterThemeCubit(); gameBloc = _MockGameBloc(); whenListen( characterThemeCubit, const Stream<CharacterThemeState>.empty(), initialState: const CharacterThemeState.initial(), ); whenListen( gameBloc, Stream.value(const GameState.initial()), initialState: const GameState.initial(), ); }); group('renders PinballGameView', () { testWidgets('with debug mode turned on', (tester) async { await tester.pumpApp( PinballGamePage(), characterThemeCubit: characterThemeCubit, gameBloc: gameBloc, ); expect(find.byType(PinballGameView), findsOneWidget); }); testWidgets('with debug mode turned off', (tester) async { await tester.pumpApp( PinballGamePage(isDebugMode: false), characterThemeCubit: characterThemeCubit, gameBloc: gameBloc, ); expect(find.byType(PinballGameView), findsOneWidget); }); }); testWidgets( 'renders the loading indicator while the assets load', (tester) async { final assetsManagerCubit = _MockAssetsManagerCubit(); final initialAssetsState = AssetsManagerState( assetsCount: 1, loaded: 0, ); whenListen( assetsManagerCubit, Stream.value(initialAssetsState), initialState: initialAssetsState, ); await tester.pumpApp( PinballGameView(game), assetsManagerCubit: assetsManagerCubit, characterThemeCubit: characterThemeCubit, ); expect(find.byType(AssetsLoadingPage), findsOneWidget); }, ); testWidgets( 'renders PinballGameLoadedView after resources have been loaded', (tester) async { final assetsManagerCubit = _MockAssetsManagerCubit(); final startGameBloc = _MockStartGameBloc(); final loadedAssetsState = AssetsManagerState( assetsCount: 1, loaded: 1, ); whenListen( assetsManagerCubit, Stream.value(loadedAssetsState), initialState: loadedAssetsState, ); whenListen( startGameBloc, Stream.value(StartGameState.initial()), initialState: StartGameState.initial(), ); await tester.pumpApp( PinballGameView(game), assetsManagerCubit: assetsManagerCubit, characterThemeCubit: characterThemeCubit, gameBloc: gameBloc, startGameBloc: startGameBloc, ); await tester.pump(); expect(find.byType(PinballGameLoadedView), findsOneWidget); }); }); group('PinballGameView', () { final gameBloc = _MockGameBloc(); final startGameBloc = _MockStartGameBloc(); setUp(() async { await Future.wait<void>( game.preLoadAssets().map((loadableBuilder) => loadableBuilder()), ); whenListen( gameBloc, Stream.value(const GameState.initial()), initialState: const GameState.initial(), ); whenListen( startGameBloc, Stream.value(StartGameState.initial()), initialState: StartGameState.initial(), ); }); testWidgets('renders game', (tester) async { await tester.pumpApp( PinballGameView(game), gameBloc: gameBloc, startGameBloc: startGameBloc, ); expect( find.byWidgetPredicate((w) => w is GameWidget<PinballGame>), findsOneWidget, ); expect( find.byType(GameHud), findsNothing, ); }); testWidgets('renders a hud on play state', (tester) async { final startGameState = StartGameState.initial().copyWith( status: StartGameStatus.play, ); whenListen( startGameBloc, Stream.value(startGameState), initialState: startGameState, ); await tester.pumpApp( PinballGameView(game), gameBloc: gameBloc, startGameBloc: startGameBloc, ); expect( find.byType(GameHud), findsOneWidget, ); }); testWidgets('hide a hud on game over', (tester) async { final startGameState = StartGameState.initial().copyWith( status: StartGameStatus.play, ); final gameState = GameState.initial().copyWith( status: GameStatus.gameOver, ); whenListen( startGameBloc, Stream.value(startGameState), initialState: startGameState, ); whenListen( gameBloc, Stream.value(gameState), initialState: gameState, ); await tester.pumpApp( Material(child: PinballGameView(game)), gameBloc: gameBloc, startGameBloc: startGameBloc, ); expect(find.byType(GameHud), findsNothing); }); testWidgets('keep focus on game when mouse hovers over it', (tester) async { final startGameState = StartGameState.initial().copyWith( status: StartGameStatus.play, ); final gameState = GameState.initial().copyWith( status: GameStatus.gameOver, ); whenListen( startGameBloc, Stream.value(startGameState), initialState: startGameState, ); whenListen( gameBloc, Stream.value(gameState), initialState: gameState, ); await tester.pumpApp( Material(child: PinballGameView(game)), gameBloc: gameBloc, startGameBloc: startGameBloc, ); game.focusNode.unfocus(); await tester.pump(); expect(game.focusNode.hasFocus, isFalse); final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); addTearDown(gesture.removePointer); await gesture.moveTo((game.size / 2).toOffset()); await tester.pump(); expect(game.focusNode.hasFocus, isTrue); }); testWidgets('mobile controls when the overlay is added', (tester) async { await tester.pumpApp( PinballGameView(game), gameBloc: gameBloc, startGameBloc: startGameBloc, ); game.overlays.add(PinballGame.mobileControlsOverlay); await tester.pump(); expect(find.byType(MobileControls), findsOneWidget); }); testWidgets( 'ReplayButtonOverlay when the overlay is added', (tester) async { await tester.pumpApp( PinballGameView(game), gameBloc: gameBloc, startGameBloc: startGameBloc, ); game.overlays.add(PinballGame.replayButtonOverlay); await tester.pump(); expect(find.byType(ReplayButtonOverlay), findsOneWidget); }, ); group('info icon', () { testWidgets('renders on game over', (tester) async { final gameState = GameState.initial().copyWith( status: GameStatus.gameOver, ); whenListen( gameBloc, Stream.value(gameState), initialState: gameState, ); await tester.pumpApp( Material(child: PinballGameView(game)), gameBloc: gameBloc, startGameBloc: startGameBloc, ); expect(find.byIcon(Icons.info), findsOneWidget); }); testWidgets('opens MoreInformationDialog when tapped', (tester) async { final gameState = GameState.initial().copyWith( status: GameStatus.gameOver, ); whenListen( gameBloc, Stream.value(gameState), initialState: gameState, ); await tester.pumpApp( Material(child: PinballGameView(game)), gameBloc: gameBloc, startGameBloc: startGameBloc, ); await tester.tap(find.byType(IconButton)); await tester.pump(); expect(find.byType(MoreInformationDialog), findsOneWidget); }); }); }); }
pinball/test/game/view/pinball_game_page_test.dart/0
{ "file_path": "pinball/test/game/view/pinball_game_page_test.dart", "repo_id": "pinball", "token_count": 4477 }
1,212
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball/select_character/select_character.dart'; void main() { group('ThemeState', () { test('can be instantiated', () { expect(const CharacterThemeState.initial(), isNotNull); }); test('supports value equality', () { expect( CharacterThemeState.initial(), equals(const CharacterThemeState.initial()), ); }); }); }
pinball/test/select_character/cubit/character_theme_state_test.dart/0
{ "file_path": "pinball/test/select_character/cubit/character_theme_state_test.dart", "repo_id": "pinball", "token_count": 174 }
1,213
# Describes the targets run in continuous integration environment. # # Flutter infra uses this file to generate a checklist of tasks to be performed # for every commit. # # More information at: # * https://github.com/flutter/cocoon/blob/main/CI_YAML.md enabled_branches: - main platform_properties: linux: properties: dependencies: > [ {"dependency": "curl", "version": "version:7.64.0"} ] device_type: none os: Linux windows: properties: dependencies: > [ {"dependency": "certs", "version": "version:9563bb"} ] device_type: none os: Windows mac_arm64: properties: dependencies: >- [ {"dependency": "xcode", "version": "14a5294e"}, {"dependency": "gems", "version": "v3.3.14"} ] os: Mac-12 device_type: none cpu: arm64 xcode: 14a5294e # xcode 14.0 beta 5 mac_x64: properties: dependencies: >- [ {"dependency": "xcode", "version": "14a5294e"}, {"dependency": "gems", "version": "v3.3.14"} ] os: Mac-12 device_type: none cpu: x86 xcode: 14a5294e # xcode 14.0 beta 5 targets: ### iOS+macOS tasks *** # TODO(stuartmorgan): Move this to ARM once google_maps_flutter has ARM # support. `pod lint` makes a synthetic target that doesn't respect the # pod's arch exclusions, so fails to build. # When moving it, rename the task and file to check_podspecs - name: Mac_x64 lint_podspecs recipe: plugins/plugins timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: macos_lint_podspecs.yaml ### macOS desktop tasks ### # macos_platform_tests builds all the plugins on ARM, so this build is run # on Intel to give us build coverage of both host types. - name: Mac_x64 build_all_plugins master recipe: plugins/plugins timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: macos_build_all_plugins.yaml channel: master - name: Mac_x64 build_all_plugins stable recipe: plugins/plugins timeout: 30 properties: add_recipes_cq: "true" version_file: flutter_stable.version target_file: macos_build_all_plugins.yaml channel: stable - name: Mac_arm64 macos_platform_tests master recipe: plugins/plugins timeout: 60 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: macos_platform_tests.yaml - name: Mac_arm64 macos_platform_tests stable recipe: plugins/plugins presubmit: false timeout: 60 properties: channel: stable add_recipes_cq: "true" version_file: flutter_stable.version target_file: macos_platform_tests.yaml ### iOS tasks ### # ios_platform_tests builds all the plugins on ARM, so this build is run # on Intel to give us build coverage of both host types. - name: Mac_x64 ios_build_all_plugins master recipe: plugins/plugins timeout: 30 properties: channel: master add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_build_all_plugins.yaml - name: Mac_x64 ios_build_all_plugins stable recipe: plugins/plugins timeout: 30 properties: channel: stable add_recipes_cq: "true" version_file: flutter_stable.version target_file: ios_build_all_plugins.yaml # TODO(stuartmorgan): Change all of the ios_platform_tests_* task timeouts # to 60 minutes once https://github.com/flutter/flutter/issues/119750 is # fixed. - name: Mac_arm64 ios_platform_tests_shard_1 master - plugins recipe: plugins/plugins timeout: 120 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 0 --shardCount 5" - name: Mac_arm64 ios_platform_tests_shard_2 master - plugins recipe: plugins/plugins timeout: 120 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 1 --shardCount 5" - name: Mac_arm64 ios_platform_tests_shard_3 master - plugins recipe: plugins/plugins timeout: 120 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 2 --shardCount 5" - name: Mac_arm64 ios_platform_tests_shard_4 master - plugins recipe: plugins/plugins timeout: 120 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 3 --shardCount 5" - name: Mac_arm64 ios_platform_tests_shard_5 master - plugins recipe: plugins/plugins timeout: 120 properties: add_recipes_cq: "true" version_file: flutter_master.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 4 --shardCount 5" # Don't run full platform tests on both channels in pre-submit. - name: Mac_arm64 ios_platform_tests_shard_1 stable - plugins recipe: plugins/plugins presubmit: false timeout: 120 properties: channel: stable add_recipes_cq: "true" version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 0 --shardCount 5" - name: Mac_arm64 ios_platform_tests_shard_2 stable - plugins recipe: plugins/plugins presubmit: false timeout: 120 properties: channel: stable add_recipes_cq: "true" version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 1 --shardCount 5" - name: Mac_arm64 ios_platform_tests_shard_3 stable - plugins recipe: plugins/plugins presubmit: false timeout: 120 properties: channel: stable add_recipes_cq: "true" version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 2 --shardCount 5" - name: Mac_arm64 ios_platform_tests_shard_4 stable - plugins recipe: plugins/plugins presubmit: false timeout: 120 properties: channel: stable add_recipes_cq: "true" version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 3 --shardCount 5" - name: Mac_arm64 ios_platform_tests_shard_5 stable - plugins recipe: plugins/plugins presubmit: false timeout: 120 properties: channel: stable add_recipes_cq: "true" version_file: flutter_stable.version target_file: ios_platform_tests.yaml package_sharding: "--shardIndex 4 --shardCount 5" - name: Windows win32-platform_tests master recipe: plugins/plugins timeout: 60 properties: add_recipes_cq: "true" target_file: windows_build_and_platform_tests.yaml channel: master version_file: flutter_master.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] - name: Windows win32-platform_tests stable recipe: plugins/plugins presubmit: false timeout: 60 properties: add_recipes_cq: "true" target_file: windows_build_and_platform_tests.yaml channel: stable version_file: flutter_stable.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] - name: Windows windows-build_all_plugins master recipe: plugins/plugins timeout: 30 properties: add_recipes_cq: "true" target_file: windows_build_all_plugins.yaml channel: master version_file: flutter_master.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] - name: Windows windows-build_all_plugins stable recipe: plugins/plugins timeout: 30 properties: add_recipes_cq: "true" target_file: windows_build_all_plugins.yaml channel: stable version_file: flutter_stable.version dependencies: > [ {"dependency": "vs_build", "version": "version:vs2019"} ] - name: Linux ci_yaml plugins roller recipe: infra/ci_yaml timeout: 30 runIf: - .ci.yaml
plugins/.ci.yaml/0
{ "file_path": "plugins/.ci.yaml", "repo_id": "plugins", "token_count": 3484 }
1,214
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 Windows debug script: .ci/scripts/build_all_plugins.sh args: ["windows", "debug"] - name: build all_plugins for Windows release script: .ci/scripts/build_all_plugins.sh args: ["windows", "release"]
plugins/.ci/targets/windows_build_all_plugins.yaml/0
{ "file_path": "plugins/.ci/targets/windows_build_all_plugins.yaml", "repo_id": "plugins", "token_count": 142 }
1,215
# camera\_android The Android implementation of [`camera`][1]. ## Usage This package is [endorsed][2], which means you can simply use `camera` normally. This package will be automatically included in your app when you do. [1]: https://pub.dev/packages/camera [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
plugins/packages/camera/camera_android/README.md/0
{ "file_path": "plugins/packages/camera/camera_android/README.md", "repo_id": "plugins", "token_count": 110 }
1,216
// 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; import android.hardware.camera2.CaptureRequest; import androidx.annotation.NonNull; import io.flutter.plugins.camera.CameraProperties; /** * An interface describing a feature in the camera. This holds a setting value of type T and must * implement a means to check if this setting is supported by the current camera properties. It also * must implement a builder update method which will update a given capture request builder for this * feature's current setting value. * * @param <T> */ public abstract class CameraFeature<T> { protected final CameraProperties cameraProperties; protected CameraFeature(@NonNull CameraProperties cameraProperties) { this.cameraProperties = cameraProperties; } /** Debug name for this feature. */ public abstract String getDebugName(); /** * Gets the current value of this feature's setting. * * @return <T> Current value of this feature's setting. */ public abstract T getValue(); /** * Sets a new value for this feature's setting. * * @param value New value for this feature's setting. */ public abstract void setValue(T value); /** * Returns whether or not this feature is supported. * * <p>When the feature is not supported any {@see #value} is simply ignored by the camera plugin. * * @return boolean Whether or not this feature is supported. */ public abstract boolean checkIsSupported(); /** * Updates the setting in a provided {@see android.hardware.camera2.CaptureRequest.Builder}. * * @param requestBuilder A {@see android.hardware.camera2.CaptureRequest.Builder} instance used to * configure the settings and outputs needed to capture a single image from the camera device. */ public abstract void updateBuilder(CaptureRequest.Builder requestBuilder); }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeature.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeature.java", "repo_id": "plugins", "token_count": 537 }
1,217
// 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.noisereduction; /** Only supports fast mode for now. */ public enum NoiseReductionMode { off("off"), fast("fast"), highQuality("highQuality"), minimal("minimal"), zeroShutterLag("zeroShutterLag"); private final String strValue; NoiseReductionMode(String strValue) { this.strValue = strValue; } /** * Tries to convert the supplied string into a {@see NoiseReductionMode} enum value. * * <p>When the supplied string doesn't match a valid {@see NoiseReductionMode} enum value, null is * returned. * * @param modeStr String value to convert into an {@see NoiseReductionMode} enum value. * @return Matching {@see NoiseReductionMode} enum value, or null if no match is found. */ public static NoiseReductionMode getValueForString(String modeStr) { for (NoiseReductionMode value : values()) { if (value.strValue.equals(modeStr)) return value; } return null; } @Override public String toString() { return strValue; } }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/noisereduction/NoiseReductionMode.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/noisereduction/NoiseReductionMode.java", "repo_id": "plugins", "token_count": 377 }
1,218
// 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 static org.mockito.ArgumentMatchers.anyFloat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; 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.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.CaptureResult; import android.hardware.camera2.TotalCaptureResult; import io.flutter.plugins.camera.types.CameraCaptureProperties; import io.flutter.plugins.camera.types.CaptureTimeoutsWrapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class CameraCaptureCallbackTest { private CameraCaptureCallback cameraCaptureCallback; private CameraCaptureProperties mockCaptureProps; @Before public void setUp() { CameraCaptureCallback.CameraCaptureStateListener mockCaptureStateListener = mock(CameraCaptureCallback.CameraCaptureStateListener.class); CaptureTimeoutsWrapper mockCaptureTimeouts = mock(CaptureTimeoutsWrapper.class); mockCaptureProps = mock(CameraCaptureProperties.class); cameraCaptureCallback = CameraCaptureCallback.create( mockCaptureStateListener, mockCaptureTimeouts, mockCaptureProps); } @Test public void onCaptureProgressed_doesNotUpdateCameraCaptureProperties() { CameraCaptureSession mockSession = mock(CameraCaptureSession.class); CaptureRequest mockRequest = mock(CaptureRequest.class); CaptureResult mockResult = mock(CaptureResult.class); cameraCaptureCallback.onCaptureProgressed(mockSession, mockRequest, mockResult); verify(mockCaptureProps, never()).setLastLensAperture(anyFloat()); verify(mockCaptureProps, never()).setLastSensorExposureTime(anyLong()); verify(mockCaptureProps, never()).setLastSensorSensitivity(anyInt()); } @Test public void onCaptureCompleted_updatesCameraCaptureProperties() { CameraCaptureSession mockSession = mock(CameraCaptureSession.class); CaptureRequest mockRequest = mock(CaptureRequest.class); TotalCaptureResult mockResult = mock(TotalCaptureResult.class); when(mockResult.get(CaptureResult.LENS_APERTURE)).thenReturn(1.0f); when(mockResult.get(CaptureResult.SENSOR_EXPOSURE_TIME)).thenReturn(2L); when(mockResult.get(CaptureResult.SENSOR_SENSITIVITY)).thenReturn(3); cameraCaptureCallback.onCaptureCompleted(mockSession, mockRequest, mockResult); verify(mockCaptureProps, times(1)).setLastLensAperture(1.0f); verify(mockCaptureProps, times(1)).setLastSensorExposureTime(2L); verify(mockCaptureProps, times(1)).setLastSensorSensitivity(3); } }
plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraCaptureCallbackTest.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraCaptureCallbackTest.java", "repo_id": "plugins", "token_count": 949 }
1,219
// 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.exposurepoint; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; 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.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.MeteringRectangle; import android.util.Size; 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.Point; import io.flutter.plugins.camera.features.sensororientation.DeviceOrientationManager; import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature; import org.junit.Before; import org.junit.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; public class ExposurePointFeatureTest { Size mockCameraBoundaries; SensorOrientationFeature mockSensorOrientationFeature; DeviceOrientationManager mockDeviceOrientationManager; @Before public void setUp() { this.mockCameraBoundaries = mock(Size.class); when(this.mockCameraBoundaries.getWidth()).thenReturn(100); when(this.mockCameraBoundaries.getHeight()).thenReturn(100); mockSensorOrientationFeature = mock(SensorOrientationFeature.class); mockDeviceOrientationManager = mock(DeviceOrientationManager.class); when(mockSensorOrientationFeature.getDeviceOrientationManager()) .thenReturn(mockDeviceOrientationManager); when(mockDeviceOrientationManager.getLastUIOrientation()) .thenReturn(PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT); } @Test public void getDebugName_shouldReturnTheNameOfTheFeature() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); assertEquals("ExposurePointFeature", exposurePointFeature.getDebugName()); } @Test public void getValue_shouldReturnNullIfNotSet() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); assertNull(exposurePointFeature.getValue()); } @Test public void getValue_shouldEchoTheSetValue() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(this.mockCameraBoundaries); Point expectedPoint = new Point(0.0, 0.0); exposurePointFeature.setValue(expectedPoint); Point actualPoint = exposurePointFeature.getValue(); assertEquals(expectedPoint, actualPoint); } @Test public void setValue_shouldResetPointWhenXCoordIsNull() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(this.mockCameraBoundaries); exposurePointFeature.setValue(new Point(null, 0.0)); assertNull(exposurePointFeature.getValue()); } @Test public void setValue_shouldResetPointWhenYCoordIsNull() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(this.mockCameraBoundaries); exposurePointFeature.setValue(new Point(0.0, null)); assertNull(exposurePointFeature.getValue()); } @Test public void setValue_shouldSetPointWhenValidCoordsAreSupplied() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(this.mockCameraBoundaries); Point point = new Point(0.0, 0.0); exposurePointFeature.setValue(point); assertEquals(point, exposurePointFeature.getValue()); } @Test public void setValue_shouldDetermineMeteringRectangleWhenValidBoundariesAndCoordsAreSupplied() { CameraProperties mockCameraProperties = mock(CameraProperties.class); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(1); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); Size mockedCameraBoundaries = mock(Size.class); exposurePointFeature.setCameraBoundaries(mockedCameraBoundaries); try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils = Mockito.mockStatic(CameraRegionUtils.class)) { exposurePointFeature.setValue(new Point(0.5, 0.5)); mockedCameraRegionUtils.verify( () -> CameraRegionUtils.convertPointToMeteringRectangle( mockedCameraBoundaries, 0.5, 0.5, PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT), times(1)); } } @Test(expected = AssertionError.class) public void setValue_shouldThrowAssertionErrorWhenNoValidBoundariesAreSet() { CameraProperties mockCameraProperties = mock(CameraProperties.class); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(1); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils = Mockito.mockStatic(CameraRegionUtils.class)) { exposurePointFeature.setValue(new Point(0.5, 0.5)); } } @Test public void setValue_shouldNotDetermineMeteringRectangleWhenNullCoordsAreSet() { CameraProperties mockCameraProperties = mock(CameraProperties.class); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(1); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); Size mockedCameraBoundaries = mock(Size.class); exposurePointFeature.setCameraBoundaries(mockedCameraBoundaries); try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils = Mockito.mockStatic(CameraRegionUtils.class)) { exposurePointFeature.setValue(null); exposurePointFeature.setValue(new Point(null, 0.5)); exposurePointFeature.setValue(new Point(0.5, null)); mockedCameraRegionUtils.verifyNoInteractions(); } } @Test public void setCameraBoundaries_shouldDetermineMeteringRectangleWhenValidBoundariesAndCoordsAreSupplied() { CameraProperties mockCameraProperties = mock(CameraProperties.class); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(1); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(this.mockCameraBoundaries); exposurePointFeature.setValue(new Point(0.5, 0.5)); Size mockedCameraBoundaries = mock(Size.class); try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils = Mockito.mockStatic(CameraRegionUtils.class)) { exposurePointFeature.setCameraBoundaries(mockedCameraBoundaries); mockedCameraRegionUtils.verify( () -> CameraRegionUtils.convertPointToMeteringRectangle( mockedCameraBoundaries, 0.5, 0.5, PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT), times(1)); } } @Test public void checkIsSupported_shouldReturnFalseWhenMaxRegionsIsNull() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(new Size(100, 100)); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(null); assertFalse(exposurePointFeature.checkIsSupported()); } @Test public void checkIsSupported_shouldReturnFalseWhenMaxRegionsIsZero() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(new Size(100, 100)); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(0); assertFalse(exposurePointFeature.checkIsSupported()); } @Test public void checkIsSupported_shouldReturnTrueWhenMaxRegionsIsBiggerThenZero() { CameraProperties mockCameraProperties = mock(CameraProperties.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(new Size(100, 100)); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(1); assertTrue(exposurePointFeature.checkIsSupported()); } @Test public void updateBuilder_shouldReturnWhenCheckIsSupportedIsFalse() { CameraProperties mockCameraProperties = mock(CameraProperties.class); CaptureRequest.Builder mockCaptureRequestBuilder = mock(CaptureRequest.Builder.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(0); exposurePointFeature.updateBuilder(mockCaptureRequestBuilder); verify(mockCaptureRequestBuilder, never()).set(any(), any()); } @Test public void updateBuilder_shouldSetMeteringRectangleWhenValidBoundariesAndCoordsAreSupplied() { CameraProperties mockCameraProperties = mock(CameraProperties.class); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(1); CaptureRequest.Builder mockCaptureRequestBuilder = mock(CaptureRequest.Builder.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); Size mockedCameraBoundaries = mock(Size.class); MeteringRectangle mockedMeteringRectangle = mock(MeteringRectangle.class); try (MockedStatic<CameraRegionUtils> mockedCameraRegionUtils = Mockito.mockStatic(CameraRegionUtils.class)) { mockedCameraRegionUtils .when( () -> CameraRegionUtils.convertPointToMeteringRectangle( mockedCameraBoundaries, 0.5, 0.5, PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT)) .thenReturn(mockedMeteringRectangle); exposurePointFeature.setCameraBoundaries(mockedCameraBoundaries); exposurePointFeature.setValue(new Point(0.5, 0.5)); exposurePointFeature.updateBuilder(mockCaptureRequestBuilder); } verify(mockCaptureRequestBuilder, times(1)) .set(CaptureRequest.CONTROL_AE_REGIONS, new MeteringRectangle[] {mockedMeteringRectangle}); } @Test public void updateBuilder_shouldNotSetMeteringRectangleWhenNoValidBoundariesAreSupplied() { CameraProperties mockCameraProperties = mock(CameraProperties.class); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(1); CaptureRequest.Builder mockCaptureRequestBuilder = mock(CaptureRequest.Builder.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.updateBuilder(mockCaptureRequestBuilder); verify(mockCaptureRequestBuilder, times(1)).set(any(), isNull()); } @Test public void updateBuilder_shouldNotSetMeteringRectangleWhenNoValidCoordsAreSupplied() { CameraProperties mockCameraProperties = mock(CameraProperties.class); when(mockCameraProperties.getControlMaxRegionsAutoExposure()).thenReturn(1); CaptureRequest.Builder mockCaptureRequestBuilder = mock(CaptureRequest.Builder.class); ExposurePointFeature exposurePointFeature = new ExposurePointFeature(mockCameraProperties, mockSensorOrientationFeature); exposurePointFeature.setCameraBoundaries(this.mockCameraBoundaries); exposurePointFeature.setValue(null); exposurePointFeature.updateBuilder(mockCaptureRequestBuilder); exposurePointFeature.setValue(new Point(0d, null)); exposurePointFeature.updateBuilder(mockCaptureRequestBuilder); exposurePointFeature.setValue(new Point(null, 0d)); exposurePointFeature.updateBuilder(mockCaptureRequestBuilder); verify(mockCaptureRequestBuilder, times(3)).set(any(), isNull()); } }
plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/exposurepoint/ExposurePointFeatureTest.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/exposurepoint/ExposurePointFeatureTest.java", "repo_id": "plugins", "token_count": 4382 }
1,220
sdk=30
plugins/packages/camera/camera_android/android/src/test/resources/robolectric.properties/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/test/resources/robolectric.properties", "repo_id": "plugins", "token_count": 4 }
1,221
// 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 android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.view.Display; import android.view.Surface; import android.view.WindowManager; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; /** * Support class to help to determine the media orientation based on the orientation of the device. */ public class DeviceOrientationManager { interface DeviceOrientationChangeCallback { void onChange(DeviceOrientation newOrientation); } private static final IntentFilter orientationIntentFilter = new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED); private final Activity activity; private final boolean isFrontFacing; private final int sensorOrientation; private final DeviceOrientationChangeCallback deviceOrientationChangeCallback; private PlatformChannel.DeviceOrientation lastOrientation; private BroadcastReceiver broadcastReceiver; DeviceOrientationManager( @NonNull Activity activity, boolean isFrontFacing, int sensorOrientation, DeviceOrientationChangeCallback callback) { this.activity = activity; this.isFrontFacing = isFrontFacing; this.sensorOrientation = sensorOrientation; this.deviceOrientationChangeCallback = callback; } /** * Starts listening to the device's sensors or UI for orientation updates. * * <p>When orientation information is updated, the callback method of the {@link * DeviceOrientationChangeCallback} is called with the new orientation. This latest value can also * be retrieved through the {@link #getVideoOrientation()} accessor. * * <p>If the device's ACCELEROMETER_ROTATION setting is enabled the {@link * DeviceOrientationManager} will report orientation updates based on the sensor information. If * the ACCELEROMETER_ROTATION is disabled the {@link DeviceOrientationManager} will fallback to * the deliver orientation updates based on the UI orientation. */ public void start() { if (broadcastReceiver != null) { return; } broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { handleUIOrientationChange(); } }; activity.registerReceiver(broadcastReceiver, orientationIntentFilter); broadcastReceiver.onReceive(activity, null); } /** Stops listening for orientation updates. */ public void stop() { if (broadcastReceiver == null) { return; } activity.unregisterReceiver(broadcastReceiver); broadcastReceiver = null; } /** * Returns the device's photo orientation in degrees based on the sensor orientation and the last * known UI orientation. * * <p>Returns one of 0, 90, 180 or 270. * * @return The device's photo orientation in degrees. */ public int getPhotoOrientation() { return this.getPhotoOrientation(this.lastOrientation); } /** * Returns the device's photo orientation in degrees based on the sensor orientation and the * supplied {@link PlatformChannel.DeviceOrientation} value. * * <p>Returns one of 0, 90, 180 or 270. * * @param orientation The {@link PlatformChannel.DeviceOrientation} value that is to be converted * into degrees. * @return The device's photo orientation in degrees. */ public int getPhotoOrientation(PlatformChannel.DeviceOrientation orientation) { int angle = 0; // Fallback to device orientation when the orientation value is null. if (orientation == null) { orientation = getUIOrientation(); } switch (orientation) { case PORTRAIT_UP: angle = 90; break; case PORTRAIT_DOWN: angle = 270; break; case LANDSCAPE_LEFT: angle = isFrontFacing ? 180 : 0; break; case LANDSCAPE_RIGHT: angle = isFrontFacing ? 0 : 180; break; } // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X). // This has to be taken into account so the JPEG is rotated properly. // For devices with orientation of 90, this simply returns the mapping from ORIENTATIONS. // For devices with orientation of 270, the JPEG is rotated 180 degrees instead. return (angle + sensorOrientation + 270) % 360; } /** * Returns the device's video orientation in clockwise degrees based on the sensor orientation and * the last known UI orientation. * * <p>Returns one of 0, 90, 180 or 270. * * @return The device's video orientation in clockwise degrees. */ public int getVideoOrientation() { return this.getVideoOrientation(this.lastOrientation); } /** * Returns the device's video orientation in clockwise degrees based on the sensor orientation and * the supplied {@link PlatformChannel.DeviceOrientation} value. * * <p>Returns one of 0, 90, 180 or 270. * * <p>More details can be found in the official Android documentation: * https://developer.android.com/reference/android/media/MediaRecorder#setOrientationHint(int) * * <p>See also: * https://developer.android.com/training/camera2/camera-preview-large-screens#orientation_calculation * * @param orientation The {@link PlatformChannel.DeviceOrientation} value that is to be converted * into degrees. * @return The device's video orientation in clockwise degrees. */ public int getVideoOrientation(PlatformChannel.DeviceOrientation orientation) { int angle = 0; // Fallback to device orientation when the orientation value is null. if (orientation == null) { orientation = getUIOrientation(); } switch (orientation) { case PORTRAIT_UP: angle = 0; break; case PORTRAIT_DOWN: angle = 180; break; case LANDSCAPE_LEFT: angle = 270; break; case LANDSCAPE_RIGHT: angle = 90; break; } if (isFrontFacing) { angle *= -1; } return (angle + sensorOrientation + 360) % 360; } /** @return the last received UI orientation. */ public PlatformChannel.DeviceOrientation getLastUIOrientation() { return this.lastOrientation; } /** * Handles orientation changes based on change events triggered by the OrientationIntentFilter. * * <p>This method is visible for testing purposes only and should never be used outside this * class. */ @VisibleForTesting void handleUIOrientationChange() { PlatformChannel.DeviceOrientation orientation = getUIOrientation(); handleOrientationChange(orientation, lastOrientation, deviceOrientationChangeCallback); lastOrientation = orientation; } /** * Handles orientation changes coming from either the device's sensors or the * OrientationIntentFilter. * * <p>This method is visible for testing purposes only and should never be used outside this * class. */ @VisibleForTesting static void handleOrientationChange( DeviceOrientation newOrientation, DeviceOrientation previousOrientation, DeviceOrientationChangeCallback callback) { if (!newOrientation.equals(previousOrientation)) { callback.onChange(newOrientation); } } /** * Gets the current user interface orientation. * * <p>This method is visible for testing purposes only and should never be used outside this * class. * * @return The current user interface orientation. */ @VisibleForTesting PlatformChannel.DeviceOrientation getUIOrientation() { final int rotation = getDisplay().getRotation(); final int orientation = activity.getResources().getConfiguration().orientation; switch (orientation) { case Configuration.ORIENTATION_PORTRAIT: if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) { return PlatformChannel.DeviceOrientation.PORTRAIT_UP; } else { return PlatformChannel.DeviceOrientation.PORTRAIT_DOWN; } case Configuration.ORIENTATION_LANDSCAPE: if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) { return PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT; } else { return PlatformChannel.DeviceOrientation.LANDSCAPE_RIGHT; } default: return PlatformChannel.DeviceOrientation.PORTRAIT_UP; } } /** * Calculates the sensor orientation based on the supplied angle. * * <p>This method is visible for testing purposes only and should never be used outside this * class. * * @param angle Orientation angle. * @return The sensor orientation based on the supplied angle. */ @VisibleForTesting PlatformChannel.DeviceOrientation calculateSensorOrientation(int angle) { final int tolerance = 45; angle += tolerance; // Orientation is 0 in the default orientation mode. This is portrait-mode for phones // and landscape for tablets. We have to compensate for this by calculating the default // orientation, and apply an offset accordingly. int defaultDeviceOrientation = getDeviceDefaultOrientation(); if (defaultDeviceOrientation == Configuration.ORIENTATION_LANDSCAPE) { angle += 90; } // Determine the orientation angle = angle % 360; return new PlatformChannel.DeviceOrientation[] { PlatformChannel.DeviceOrientation.PORTRAIT_UP, PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT, PlatformChannel.DeviceOrientation.PORTRAIT_DOWN, PlatformChannel.DeviceOrientation.LANDSCAPE_RIGHT, } [angle / 90]; } /** * Gets the default orientation of the device. * * <p>This method is visible for testing purposes only and should never be used outside this * class. * * @return The default orientation of the device. */ @VisibleForTesting int getDeviceDefaultOrientation() { Configuration config = activity.getResources().getConfiguration(); int rotation = getDisplay().getRotation(); if (((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE) || ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)) { return Configuration.ORIENTATION_LANDSCAPE; } else { return Configuration.ORIENTATION_PORTRAIT; } } /** * Gets an instance of the Android {@link android.view.Display}. * * <p>This method is visible for testing purposes only and should never be used outside this * class. * * @return An instance of the Android {@link android.view.Display}. */ @SuppressWarnings("deprecation") @VisibleForTesting Display getDisplay() { return ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); } }
plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManager.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManager.java", "repo_id": "plugins", "token_count": 3733 }
1,222
// 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.Mockito.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.graphics.SurfaceTexture; import android.util.Size; import android.view.Surface; import androidx.camera.core.Preview; import androidx.camera.core.SurfaceRequest; import androidx.core.util.Consumer; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesFlutterApi.Reply; import io.flutter.view.TextureRegistry; import java.util.concurrent.Executor; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class PreviewTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public Preview mockPreview; @Mock public BinaryMessenger mockBinaryMessenger; @Mock public TextureRegistry mockTextureRegistry; @Mock public CameraXProxy mockCameraXProxy; InstanceManager testInstanceManager; @Before public void setUp() { testInstanceManager = spy(InstanceManager.open(identifier -> {})); } @After public void tearDown() { testInstanceManager.close(); } @Test public void create_createsPreviewWithCorrectConfiguration() { final PreviewHostApiImpl previewHostApi = new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); final Preview.Builder mockPreviewBuilder = mock(Preview.Builder.class); final int targetRotation = 90; final int targetResolutionWidth = 10; final int targetResolutionHeight = 50; final Long previewIdentifier = 3L; final GeneratedCameraXLibrary.ResolutionInfo resolutionInfo = new GeneratedCameraXLibrary.ResolutionInfo.Builder() .setWidth(Long.valueOf(targetResolutionWidth)) .setHeight(Long.valueOf(targetResolutionHeight)) .build(); previewHostApi.cameraXProxy = mockCameraXProxy; when(mockCameraXProxy.createPreviewBuilder()).thenReturn(mockPreviewBuilder); when(mockPreviewBuilder.build()).thenReturn(mockPreview); final ArgumentCaptor<Size> sizeCaptor = ArgumentCaptor.forClass(Size.class); previewHostApi.create(previewIdentifier, Long.valueOf(targetRotation), resolutionInfo); verify(mockPreviewBuilder).setTargetRotation(targetRotation); verify(mockPreviewBuilder).setTargetResolution(sizeCaptor.capture()); assertEquals(sizeCaptor.getValue().getWidth(), targetResolutionWidth); assertEquals(sizeCaptor.getValue().getHeight(), targetResolutionHeight); verify(mockPreviewBuilder).build(); verify(testInstanceManager).addDartCreatedInstance(mockPreview, previewIdentifier); } @Test public void setSurfaceProviderTest_createsSurfaceProviderAndReturnsTextureEntryId() { final PreviewHostApiImpl previewHostApi = spy(new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry)); final TextureRegistry.SurfaceTextureEntry mockSurfaceTextureEntry = mock(TextureRegistry.SurfaceTextureEntry.class); final SurfaceTexture mockSurfaceTexture = mock(SurfaceTexture.class); final Long previewIdentifier = 5L; final Long surfaceTextureEntryId = 120L; previewHostApi.cameraXProxy = mockCameraXProxy; testInstanceManager.addDartCreatedInstance(mockPreview, previewIdentifier); when(mockTextureRegistry.createSurfaceTexture()).thenReturn(mockSurfaceTextureEntry); when(mockSurfaceTextureEntry.surfaceTexture()).thenReturn(mockSurfaceTexture); when(mockSurfaceTextureEntry.id()).thenReturn(surfaceTextureEntryId); final ArgumentCaptor<Preview.SurfaceProvider> surfaceProviderCaptor = ArgumentCaptor.forClass(Preview.SurfaceProvider.class); final ArgumentCaptor<Surface> surfaceCaptor = ArgumentCaptor.forClass(Surface.class); final ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class); // Test that surface provider was set and the surface texture ID was returned. assertEquals(previewHostApi.setSurfaceProvider(previewIdentifier), surfaceTextureEntryId); verify(mockPreview).setSurfaceProvider(surfaceProviderCaptor.capture()); verify(previewHostApi).createSurfaceProvider(mockSurfaceTexture); } @Test public void createSurfaceProvider_createsExpectedPreviewSurfaceProvider() { final PreviewHostApiImpl previewHostApi = new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); final SurfaceTexture mockSurfaceTexture = mock(SurfaceTexture.class); final Surface mockSurface = mock(Surface.class); final SurfaceRequest mockSurfaceRequest = mock(SurfaceRequest.class); final SurfaceRequest.Result mockSurfaceRequestResult = mock(SurfaceRequest.Result.class); final SystemServicesFlutterApiImpl mockSystemServicesFlutterApi = mock(SystemServicesFlutterApiImpl.class); final int resolutionWidth = 200; final int resolutionHeight = 500; previewHostApi.cameraXProxy = mockCameraXProxy; when(mockCameraXProxy.createSurface(mockSurfaceTexture)).thenReturn(mockSurface); when(mockSurfaceRequest.getResolution()) .thenReturn(new Size(resolutionWidth, resolutionHeight)); when(mockCameraXProxy.createSystemServicesFlutterApiImpl(mockBinaryMessenger)) .thenReturn(mockSystemServicesFlutterApi); final ArgumentCaptor<Surface> surfaceCaptor = ArgumentCaptor.forClass(Surface.class); final ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class); Preview.SurfaceProvider previewSurfaceProvider = previewHostApi.createSurfaceProvider(mockSurfaceTexture); previewSurfaceProvider.onSurfaceRequested(mockSurfaceRequest); verify(mockSurfaceTexture).setDefaultBufferSize(resolutionWidth, resolutionHeight); verify(mockSurfaceRequest) .provideSurface(surfaceCaptor.capture(), any(Executor.class), consumerCaptor.capture()); // Test that the surface derived from the surface texture entry will be provided to the surface request. assertEquals(surfaceCaptor.getValue(), mockSurface); // Test that the Consumer used to handle surface request result releases Flutter surface texture appropriately // and sends camera errors appropriately. Consumer<SurfaceRequest.Result> capturedConsumer = consumerCaptor.getValue(); // Case where Surface should be released. when(mockSurfaceRequestResult.getResultCode()) .thenReturn(SurfaceRequest.Result.RESULT_REQUEST_CANCELLED); capturedConsumer.accept(mockSurfaceRequestResult); verify(mockSurface).release(); reset(mockSurface); when(mockSurfaceRequestResult.getResultCode()) .thenReturn(SurfaceRequest.Result.RESULT_REQUEST_CANCELLED); capturedConsumer.accept(mockSurfaceRequestResult); verify(mockSurface).release(); reset(mockSurface); when(mockSurfaceRequestResult.getResultCode()) .thenReturn(SurfaceRequest.Result.RESULT_WILL_NOT_PROVIDE_SURFACE); capturedConsumer.accept(mockSurfaceRequestResult); verify(mockSurface).release(); reset(mockSurface); when(mockSurfaceRequestResult.getResultCode()) .thenReturn(SurfaceRequest.Result.RESULT_SURFACE_USED_SUCCESSFULLY); capturedConsumer.accept(mockSurfaceRequestResult); verify(mockSurface).release(); reset(mockSurface); // Case where error must be sent. when(mockSurfaceRequestResult.getResultCode()) .thenReturn(SurfaceRequest.Result.RESULT_INVALID_SURFACE); capturedConsumer.accept(mockSurfaceRequestResult); verify(mockSurface).release(); verify(mockSystemServicesFlutterApi).sendCameraError(anyString(), any(Reply.class)); } @Test public void releaseFlutterSurfaceTexture_makesCallToReleaseFlutterSurfaceTexture() { final PreviewHostApiImpl previewHostApi = new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); final TextureRegistry.SurfaceTextureEntry mockSurfaceTextureEntry = mock(TextureRegistry.SurfaceTextureEntry.class); previewHostApi.flutterSurfaceTexture = mockSurfaceTextureEntry; previewHostApi.releaseFlutterSurfaceTexture(); verify(mockSurfaceTextureEntry).release(); } @Test public void getResolutionInfo_makesCallToRetrievePreviewResolutionInfo() { final PreviewHostApiImpl previewHostApi = new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); final androidx.camera.core.ResolutionInfo mockResolutionInfo = mock(androidx.camera.core.ResolutionInfo.class); final Long previewIdentifier = 23L; final int resolutionWidth = 500; final int resolutionHeight = 200; testInstanceManager.addDartCreatedInstance(mockPreview, previewIdentifier); when(mockPreview.getResolutionInfo()).thenReturn(mockResolutionInfo); when(mockResolutionInfo.getResolution()) .thenReturn(new Size(resolutionWidth, resolutionHeight)); ResolutionInfo resolutionInfo = previewHostApi.getResolutionInfo(previewIdentifier); assertEquals(resolutionInfo.getWidth(), Long.valueOf(resolutionWidth)); assertEquals(resolutionInfo.getHeight(), Long.valueOf(resolutionHeight)); } }
plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PreviewTest.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PreviewTest.java", "repo_id": "plugins", "token_count": 3162 }
1,223
// 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_android_camerax/camera_android_camerax.dart'; import 'package:camera_android_camerax/src/camera.dart'; import 'package:camera_android_camerax/src/camera_info.dart'; import 'package:camera_android_camerax/src/camera_selector.dart'; import 'package:camera_android_camerax/src/camerax_library.g.dart'; import 'package:camera_android_camerax/src/preview.dart'; import 'package:camera_android_camerax/src/process_camera_provider.dart'; import 'package:camera_android_camerax/src/system_services.dart'; import 'package:camera_android_camerax/src/use_case.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart' show DeviceOrientation; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'android_camera_camerax_test.mocks.dart'; @GenerateNiceMocks(<MockSpec<Object>>[ MockSpec<Camera>(), MockSpec<CameraInfo>(), MockSpec<CameraSelector>(), MockSpec<Preview>(), MockSpec<ProcessCameraProvider>(), ]) @GenerateMocks(<Type>[BuildContext]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('Should fetch CameraDescription instances for available cameras', () async { // Arrange final MockAndroidCameraCamerax camera = MockAndroidCameraCamerax(); camera.processCameraProvider = MockProcessCameraProvider(); final List<dynamic> returnData = <dynamic>[ <String, dynamic>{ 'name': 'Camera 0', 'lensFacing': 'back', 'sensorOrientation': 0 }, <String, dynamic>{ 'name': 'Camera 1', 'lensFacing': 'front', 'sensorOrientation': 90 } ]; // Create mocks to use final MockCameraInfo mockFrontCameraInfo = MockCameraInfo(); final MockCameraInfo mockBackCameraInfo = MockCameraInfo(); // Mock calls to native platform when(camera.processCameraProvider!.getAvailableCameraInfos()).thenAnswer( (_) async => <MockCameraInfo>[mockBackCameraInfo, mockFrontCameraInfo]); when(camera.mockBackCameraSelector .filter(<MockCameraInfo>[mockFrontCameraInfo])) .thenAnswer((_) async => <MockCameraInfo>[]); when(camera.mockBackCameraSelector .filter(<MockCameraInfo>[mockBackCameraInfo])) .thenAnswer((_) async => <MockCameraInfo>[mockBackCameraInfo]); when(camera.mockFrontCameraSelector .filter(<MockCameraInfo>[mockBackCameraInfo])) .thenAnswer((_) async => <MockCameraInfo>[]); when(camera.mockFrontCameraSelector .filter(<MockCameraInfo>[mockFrontCameraInfo])) .thenAnswer((_) async => <MockCameraInfo>[mockFrontCameraInfo]); when(mockBackCameraInfo.getSensorRotationDegrees()) .thenAnswer((_) async => 0); when(mockFrontCameraInfo.getSensorRotationDegrees()) .thenAnswer((_) async => 90); final List<CameraDescription> cameraDescriptions = await camera.availableCameras(); expect(cameraDescriptions.length, returnData.length); for (int i = 0; i < returnData.length; i++) { final Map<String, Object?> typedData = (returnData[i] as Map<dynamic, dynamic>).cast<String, Object?>(); final CameraDescription cameraDescription = CameraDescription( name: typedData['name']! as String, lensDirection: (typedData['lensFacing']! as String) == 'front' ? CameraLensDirection.front : CameraLensDirection.back, sensorOrientation: typedData['sensorOrientation']! as int, ); expect(cameraDescriptions[i], cameraDescription); } }); test( 'createCamera requests permissions, starts listening for device orientation changes, and returns flutter surface texture ID', () async { final MockAndroidCameraCamerax camera = MockAndroidCameraCamerax(); camera.processCameraProvider = MockProcessCameraProvider(); const CameraLensDirection testLensDirection = CameraLensDirection.back; const int testSensorOrientation = 90; const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation); const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; const bool enableAudio = true; const int testSurfaceTextureId = 6; when(camera.testPreview.setSurfaceProvider()) .thenAnswer((_) async => testSurfaceTextureId); expect( await camera.createCamera(testCameraDescription, testResolutionPreset, enableAudio: enableAudio), equals(testSurfaceTextureId)); // Verify permissions are requested and the camera starts listening for device orientation changes. expect(camera.cameraPermissionsRequested, isTrue); expect(camera.startedListeningForDeviceOrientationChanges, isTrue); // Verify CameraSelector is set with appropriate lens direction. expect(camera.cameraSelector, equals(camera.mockBackCameraSelector)); // Verify the camera's Preview instance is instantiated properly. expect(camera.preview, equals(camera.testPreview)); // Verify the camera's Preview instance has its surface provider set. verify(camera.preview!.setSurfaceProvider()); }); test( 'initializeCamera throws AssertionError when createCamera has not been called before initializedCamera', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); expect(() => camera.initializeCamera(3), throwsAssertionError); }); test('initializeCamera sends expected CameraInitializedEvent', () async { final MockAndroidCameraCamerax camera = MockAndroidCameraCamerax(); camera.processCameraProvider = MockProcessCameraProvider(); const int cameraId = 10; const CameraLensDirection testLensDirection = CameraLensDirection.back; const int testSensorOrientation = 90; const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation); const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; const bool enableAudio = true; const int resolutionWidth = 350; const int resolutionHeight = 750; final Camera mockCamera = MockCamera(); final ResolutionInfo testResolutionInfo = ResolutionInfo(width: resolutionWidth, height: resolutionHeight); // TODO(camsim99): Modify this when camera configuration is supported and // defualt values no longer being used. // https://github.com/flutter/flutter/issues/120468 // https://github.com/flutter/flutter/issues/120467 final CameraInitializedEvent testCameraInitializedEvent = CameraInitializedEvent( cameraId, resolutionWidth.toDouble(), resolutionHeight.toDouble(), ExposureMode.auto, false, FocusMode.auto, false); // Call createCamera. when(camera.testPreview.setSurfaceProvider()) .thenAnswer((_) async => cameraId); await camera.createCamera(testCameraDescription, testResolutionPreset, enableAudio: enableAudio); when(camera.processCameraProvider!.bindToLifecycle( camera.cameraSelector!, <UseCase>[camera.testPreview])) .thenAnswer((_) async => mockCamera); when(camera.testPreview.getResolutionInfo()) .thenAnswer((_) async => testResolutionInfo); // Start listening to camera events stream to verify the proper CameraInitializedEvent is sent. camera.cameraEventStreamController.stream.listen((CameraEvent event) { expect(event, const TypeMatcher<CameraInitializedEvent>()); expect(event, equals(testCameraInitializedEvent)); }); await camera.initializeCamera(cameraId); // Verify preview was bound and unbound to get preview resolution information. verify(camera.processCameraProvider!.bindToLifecycle( camera.cameraSelector!, <UseCase>[camera.testPreview])); verify(camera.processCameraProvider!.unbind(<UseCase>[camera.testPreview])); // Check camera instance was received, but preview is no longer bound. expect(camera.camera, equals(mockCamera)); expect(camera.previewIsBound, isFalse); }); test('dispose releases Flutter surface texture and unbinds all use cases', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); camera.preview = MockPreview(); camera.processCameraProvider = MockProcessCameraProvider(); camera.dispose(3); verify(camera.preview!.releaseFlutterSurfaceTexture()); verify(camera.processCameraProvider!.unbindAll()); }); test('onCameraInitialized stream emits CameraInitializedEvents', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); const int cameraId = 16; final Stream<CameraInitializedEvent> eventStream = camera.onCameraInitialized(cameraId); final StreamQueue<CameraInitializedEvent> streamQueue = StreamQueue<CameraInitializedEvent>(eventStream); const CameraInitializedEvent testEvent = CameraInitializedEvent( cameraId, 320, 80, ExposureMode.auto, false, FocusMode.auto, false); camera.cameraEventStreamController.add(testEvent); expect(await streamQueue.next, testEvent); await streamQueue.cancel(); }); test('onCameraError stream emits errors caught by system services', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); const int cameraId = 27; const String testErrorDescription = 'Test error description!'; final Stream<CameraErrorEvent> eventStream = camera.onCameraError(cameraId); final StreamQueue<CameraErrorEvent> streamQueue = StreamQueue<CameraErrorEvent>(eventStream); SystemServices.cameraErrorStreamController.add(testErrorDescription); expect(await streamQueue.next, equals(const CameraErrorEvent(cameraId, testErrorDescription))); await streamQueue.cancel(); }); test( 'onDeviceOrientationChanged stream emits changes in device oreintation detected by system services', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); final Stream<DeviceOrientationChangedEvent> eventStream = camera.onDeviceOrientationChanged(); final StreamQueue<DeviceOrientationChangedEvent> streamQueue = StreamQueue<DeviceOrientationChangedEvent>(eventStream); const DeviceOrientationChangedEvent testEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitDown); SystemServices.deviceOrientationChangedStreamController.add(testEvent); expect(await streamQueue.next, testEvent); await streamQueue.cancel(); }); test( 'pausePreview unbinds preview from lifecycle when preview is nonnull and has been bound to lifecycle', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); camera.processCameraProvider = MockProcessCameraProvider(); camera.preview = MockPreview(); camera.previewIsBound = true; await camera.pausePreview(579); verify(camera.processCameraProvider!.unbind(<UseCase>[camera.preview!])); expect(camera.previewIsBound, isFalse); }); test( 'pausePreview does not unbind preview from lifecycle when preview has not been bound to lifecycle', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); camera.processCameraProvider = MockProcessCameraProvider(); camera.preview = MockPreview(); await camera.pausePreview(632); verifyNever( camera.processCameraProvider!.unbind(<UseCase>[camera.preview!])); }); test('resumePreview does not bind preview to lifecycle if already bound', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); camera.processCameraProvider = MockProcessCameraProvider(); camera.cameraSelector = MockCameraSelector(); camera.preview = MockPreview(); camera.previewIsBound = true; await camera.resumePreview(78); verifyNever(camera.processCameraProvider! .bindToLifecycle(camera.cameraSelector!, <UseCase>[camera.preview!])); }); test('resumePreview binds preview to lifecycle if not already bound', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); camera.processCameraProvider = MockProcessCameraProvider(); camera.cameraSelector = MockCameraSelector(); camera.preview = MockPreview(); await camera.resumePreview(78); verify(camera.processCameraProvider! .bindToLifecycle(camera.cameraSelector!, <UseCase>[camera.preview!])); }); test( 'buildPreview returns a FutureBuilder that does not return a Texture until the preview is bound to the lifecycle', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); const int textureId = 75; camera.processCameraProvider = MockProcessCameraProvider(); camera.cameraSelector = MockCameraSelector(); camera.preview = MockPreview(); final FutureBuilder<void> previewWidget = camera.buildPreview(textureId) as FutureBuilder<void>; expect( previewWidget.builder( MockBuildContext(), const AsyncSnapshot<void>.nothing()), isA<SizedBox>()); expect( previewWidget.builder( MockBuildContext(), const AsyncSnapshot<void>.waiting()), isA<SizedBox>()); expect( previewWidget.builder(MockBuildContext(), const AsyncSnapshot<void>.withData(ConnectionState.active, null)), isA<SizedBox>()); }); test( 'buildPreview returns a FutureBuilder that returns a Texture once the preview is bound to the lifecycle', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); const int textureId = 75; camera.processCameraProvider = MockProcessCameraProvider(); camera.cameraSelector = MockCameraSelector(); camera.preview = MockPreview(); final FutureBuilder<void> previewWidget = camera.buildPreview(textureId) as FutureBuilder<void>; final Texture previewTexture = previewWidget.builder(MockBuildContext(), const AsyncSnapshot<void>.withData(ConnectionState.done, null)) as Texture; expect(previewTexture.textureId, equals(textureId)); }); } /// Mock of [AndroidCameraCameraX] that stubs behavior of some methods for /// testing. class MockAndroidCameraCamerax extends AndroidCameraCameraX { bool cameraPermissionsRequested = false; bool startedListeningForDeviceOrientationChanges = false; final MockPreview testPreview = MockPreview(); final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); @override Future<void> requestCameraPermissions(bool enableAudio) async { cameraPermissionsRequested = true; } @override void startListeningForDeviceOrientationChange( bool cameraIsFrontFacing, int sensorOrientation) { startedListeningForDeviceOrientationChanges = true; return; } @override CameraSelector createCameraSelector(int cameraSelectorLensDirection) { switch (cameraSelectorLensDirection) { case CameraSelector.lensFacingFront: return mockFrontCameraSelector; case CameraSelector.lensFacingBack: default: return mockBackCameraSelector; } } @override Preview createPreview(int targetRotation, ResolutionInfo? targetResolution) { return testPreview; } }
plugins/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart", "repo_id": "plugins", "token_count": 5154 }
1,224
## 0.9.11 * Adds back use of Optional type. * Updates minimum Flutter version to 3.0. ## 0.9.10+2 * Updates code for stricter lint checks. ## 0.9.10+1 * Updates code for stricter lint checks. ## 0.9.10 * Remove usage of deprecated quiver Optional type. ## 0.9.9 * Implements option to also stream when recording a video. ## 0.9.8+6 * Updates code for `no_leading_underscores_for_local_identifiers` lint. * Updates minimum Flutter version to 2.10. ## 0.9.8+5 * Fixes a regression introduced in 0.9.8+4 where the stream handler is not set. ## 0.9.8+4 * Fixes a crash due to sending orientation change events when the engine is torn down. ## 0.9.8+3 * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Ignores missing return warnings in preparation for [upcoming analysis changes](https://github.com/flutter/flutter/issues/105750). ## 0.9.8+2 * Fixes exception in registerWith caused by the switch to an in-package method channel. ## 0.9.8+1 * Ignores deprecation warnings for upcoming styleFrom button API changes. ## 0.9.8 * Switches to internal method channel implementation. ## 0.9.7+1 * Splits from `camera` as a federated implementation.
plugins/packages/camera/camera_avfoundation/CHANGELOG.md/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/CHANGELOG.md", "repo_id": "plugins", "token_count": 391 }
1,225
// 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; NS_ASSUME_NONNULL_BEGIN /// Creates an `FLTCam` that runs its capture session operations on a given queue. /// @param captureSessionQueue the capture session queue /// @return an FLTCam object. extern FLTCam *FLTCreateCamWithCaptureSessionQueue(dispatch_queue_t captureSessionQueue); /// Creates a test sample buffer. /// @return a test sample buffer. extern CMSampleBufferRef FLTCreateTestSampleBuffer(void); NS_ASSUME_NONNULL_END
plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.h/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.h", "repo_id": "plugins", "token_count": 181 }
1,226
// 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/material.dart'; import 'package:flutter/services.dart'; import 'camera_controller.dart'; /// A widget showing a live camera preview. class CameraPreview extends StatelessWidget { /// Creates a preview widget for the given camera controller. const CameraPreview(this.controller, {Key? key, this.child}) : super(key: key); /// The controller for the camera that the preview is shown for. final CameraController controller; /// A widget to overlay on top of the camera preview final Widget? child; @override Widget build(BuildContext context) { return controller.value.isInitialized ? ValueListenableBuilder<CameraValue>( valueListenable: controller, builder: (BuildContext context, Object? value, Widget? child) { final double cameraAspectRatio = controller.value.previewSize!.width / controller.value.previewSize!.height; return AspectRatio( aspectRatio: _isLandscape() ? cameraAspectRatio : (1 / cameraAspectRatio), child: Stack( fit: StackFit.expand, children: <Widget>[ _wrapInRotatedBox(child: controller.buildPreview()), child ?? Container(), ], ), ); }, child: child, ) : Container(); } Widget _wrapInRotatedBox({required Widget child}) { if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) { return child; } return RotatedBox( quarterTurns: _getQuarterTurns(), child: child, ); } bool _isLandscape() { return <DeviceOrientation>[ DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight ].contains(_getApplicableOrientation()); } int _getQuarterTurns() { final Map<DeviceOrientation, int> turns = <DeviceOrientation, int>{ DeviceOrientation.portraitUp: 0, DeviceOrientation.landscapeRight: 1, DeviceOrientation.portraitDown: 2, DeviceOrientation.landscapeLeft: 3, }; return turns[_getApplicableOrientation()]!; } DeviceOrientation _getApplicableOrientation() { return controller.value.isRecordingVideo ? controller.value.recordingOrientation! : (controller.value.previewPauseOrientation ?? controller.value.lockedCaptureOrientation ?? controller.value.deviceOrientation); } }
plugins/packages/camera/camera_avfoundation/example/lib/camera_preview.dart/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/lib/camera_preview.dart", "repo_id": "plugins", "token_count": 1115 }
1,227
// 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 "FLTThreadSafeFlutterResult.h" NS_ASSUME_NONNULL_BEGIN /// The completion handler block for save photo operations. /// Can be called from either main queue or IO queue. /// If success, `error` will be present and `path` will be nil. Otherewise, `error` will be nil and /// `path` will be present. /// @param path the path for successfully saved photo file. /// @param error photo capture error or IO error. typedef void (^FLTSavePhotoDelegateCompletionHandler)(NSString *_Nullable path, NSError *_Nullable error); /** Delegate object that handles photo capture results. */ @interface FLTSavePhotoDelegate : NSObject <AVCapturePhotoCaptureDelegate> /** * Initialize a photo capture delegate. * @param path the path for captured photo file. * @param ioQueue the queue on which captured photos are written to disk. * @param completionHandler The completion handler block for save photo operations. Can * be called from either main queue or IO queue. */ - (instancetype)initWithPath:(NSString *)path ioQueue:(dispatch_queue_t)ioQueue completionHandler:(FLTSavePhotoDelegateCompletionHandler)completionHandler; @end NS_ASSUME_NONNULL_END
plugins/packages/camera/camera_avfoundation/ios/Classes/FLTSavePhotoDelegate.h/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTSavePhotoDelegate.h", "repo_id": "plugins", "token_count": 459 }
1,228
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('DeviceOrientationChangedEvent tests', () { test('Constructor should initialize all properties', () { const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); expect(event.orientation, DeviceOrientation.portraitUp); }); test('fromJson should initialize all properties', () { final DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent.fromJson(const <String, dynamic>{ 'orientation': 'portraitUp', }); expect(event.orientation, DeviceOrientation.portraitUp); }); test('toJson should return a map with all fields', () { const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); final Map<String, dynamic> jsonMap = event.toJson(); expect(jsonMap.length, 1); expect(jsonMap['orientation'], 'portraitUp'); }); test('equals should return true if objects are the same', () { const DeviceOrientationChangedEvent firstEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); const DeviceOrientationChangedEvent secondEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); expect(firstEvent == secondEvent, true); }); test('equals should return false if orientation is different', () { const DeviceOrientationChangedEvent firstEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); const DeviceOrientationChangedEvent secondEvent = DeviceOrientationChangedEvent(DeviceOrientation.landscapeLeft); expect(firstEvent == secondEvent, false); }); test('hashCode should match hashCode of all properties', () { const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); final int expectedHashCode = event.orientation.hashCode; expect(event.hashCode, expectedHashCode); }); }); }
plugins/packages/camera/camera_platform_interface/test/events/device_event_test.dart/0
{ "file_path": "plugins/packages/camera/camera_platform_interface/test/events/device_event_test.dart", "repo_id": "plugins", "token_count": 796 }
1,229
# Camera Web Plugin The web implementation of [`camera`][camera]. *Note*: This plugin is under development. See [missing implementation](#missing-implementation). ## Usage ### Depend on the package This package is [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin), which means you can simply use `camera` normally. This package will be automatically included in your app when you do. ## Example Find the example in the [`camera` package](https://pub.dev/packages/camera#example). ## Limitations on the web platform ### Camera devices The camera devices are accessed with [Stream Web API](https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API) with the following [browser support](https://caniuse.com/stream): ![Data on support for the Stream feature across the major browsers from caniuse.com](https://caniuse.bitsofco.de/image/stream.png) Accessing camera devices requires a [secure browsing context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts). Broadly speaking, this means that you need to serve your web application over HTTPS (or `localhost` for local development). For insecure contexts `CameraPlatform.availableCameras` might throw a `CameraException` with the `permissionDenied` error code. ### Device orientation The device orientation implementation is backed by [`Screen Orientation Web API`](https://www.w3.org/TR/screen-orientation/) with the following [browser support](https://caniuse.com/screen-orientation): ![Data on support for the Screen Orientation feature across the major browsers from caniuse.com](https://caniuse.bitsofco.de/image/screen-orientation.png) For the browsers that do not support the device orientation: - `CameraPlatform.onDeviceOrientationChanged` returns an empty stream. - `CameraPlatform.lockCaptureOrientation` and `CameraPlatform.unlockCaptureOrientation` throw a `PlatformException` with the `orientationNotSupported` error code. ### Flash mode and zoom level The flash mode and zoom level implementation is backed by [Image Capture Web API](https://w3c.github.io/mediacapture-image/) with the following [browser support](https://caniuse.com/mdn-api_imagecapture): ![Data on support for the Image Capture feature across the major browsers from caniuse.com](https://caniuse.bitsofco.de/static/v1/mdn-api__ImageCapture-1628778966589.png) For the browsers that do not support the flash mode: - `CameraPlatform.setFlashMode` throws a `PlatformException` with the `torchModeNotSupported` error code. For the browsers that do not support the zoom level: - `CameraPlatform.getMaxZoomLevel`, `CameraPlatform.getMinZoomLevel` and `CameraPlatform.setZoomLevel` throw a `PlatformException` with the `zoomLevelNotSupported` error code. ### Taking a picture The image capturing implementation is backed by [`URL.createObjectUrl` Web API](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) with the following [browser support](https://caniuse.com/bloburls): ![Data on support for the Blob URLs feature across the major browsers from caniuse.com](https://caniuse.bitsofco.de/image/bloburls.png) The web platform does not support `dart:io`. Attempts to display a captured image using `Image.file` will throw an error. The capture image contains a network-accessible URL pointing to a location within the browser (blob) and can be displayed using `Image.network` or `Image.memory` after loading the image bytes to memory. See the example below: ```dart if (kIsWeb) { Image.network(capturedImage.path); } else { Image.file(File(capturedImage.path)); } ``` ### Video recording The video recording implementation is backed by [MediaRecorder Web API](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder) with the following [browser support](https://caniuse.com/mdn-api_mediarecorder): ![Data on support for the MediaRecorder feature across the major browsers from caniuse.com](https://caniuse.bitsofco.de/image/mediarecorder.png). A video is recorded in one of the following video MIME types: - video/webm (e.g. on Chrome or Firefox) - video/mp4 (e.g. on Safari) Pausing, resuming or stopping the video recording throws a `PlatformException` with the `videoRecordingNotStarted` error code if the video recording was not started. For the browsers that do not support the video recording: - `CameraPlatform.startVideoRecording` throws a `PlatformException` with the `notSupported` error code. ## Missing implementation The web implementation of [`camera`][camera] is missing the following features: - Exposure mode, point and offset - Focus mode and point - Sensor orientation - Image format group - Streaming of frames <!-- Links --> [camera]: https://pub.dev/packages/camera
plugins/packages/camera/camera_web/README.md/0
{ "file_path": "plugins/packages/camera/camera_web/README.md", "repo_id": "plugins", "token_count": 1340 }
1,230
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:html' as html; import 'package:flutter/foundation.dart'; /// The possible range of values for the zoom level configurable /// on the camera video track. @immutable class ZoomLevelCapability { /// Creates a new instance of [ZoomLevelCapability] with the given /// zoom level range of [minimum] to [maximum] configurable /// on the [videoTrack]. const ZoomLevelCapability({ required this.minimum, required this.maximum, required this.videoTrack, }); /// The zoom level constraint name. /// See: https://w3c.github.io/mediacapture-image/#dom-mediatracksupportedconstraints-zoom static const String constraintName = 'zoom'; /// The minimum zoom level. final double minimum; /// The maximum zoom level. final double maximum; /// The video track capable of configuring the zoom level. final html.MediaStreamTrack videoTrack; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is ZoomLevelCapability && other.minimum == minimum && other.maximum == maximum && other.videoTrack == videoTrack; } @override int get hashCode => Object.hash(minimum, maximum, videoTrack); }
plugins/packages/camera/camera_web/lib/src/types/zoom_level_capability.dart/0
{ "file_path": "plugins/packages/camera/camera_web/lib/src/types/zoom_level_capability.dart", "repo_id": "plugins", "token_count": 418 }
1,231
// 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_DEVICE_INFO_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_DEVICE_INFO_H_ #include <string> namespace camera_windows { // Name and device ID information for a capture device. class CaptureDeviceInfo { public: CaptureDeviceInfo() {} virtual ~CaptureDeviceInfo() = default; // Disallow copy and move. CaptureDeviceInfo(const CaptureDeviceInfo&) = delete; CaptureDeviceInfo& operator=(const CaptureDeviceInfo&) = delete; // Build unique device name from display name and device id. // Format: "display_name <device_id>". std::string GetUniqueDeviceName() const; // Parses display name and device id from unique device name format. // Format: "display_name <device_id>". bool CaptureDeviceInfo::ParseDeviceInfoFromCameraName( const std::string& camera_name); // Updates display name. void SetDisplayName(const std::string& display_name) { display_name_ = display_name; } // Updates device id. void SetDeviceID(const std::string& device_id) { device_id_ = device_id; } // Returns device id. std::string GetDeviceId() const { return device_id_; } private: std::string display_name_; std::string device_id_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_DEVICE_INFO_H_
plugins/packages/camera/camera_windows/windows/capture_device_info.h/0
{ "file_path": "plugins/packages/camera/camera_windows/windows/capture_device_info.h", "repo_id": "plugins", "token_count": 465 }
1,232
// 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_TEST_MOCKS_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEST_MOCKS_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 <mfcaptureengine.h> #include "camera.h" #include "camera_plugin.h" #include "capture_controller.h" #include "capture_controller_listener.h" #include "capture_engine_listener.h" namespace camera_windows { namespace test { namespace { using flutter::EncodableMap; using flutter::EncodableValue; using ::testing::_; class MockMethodResult : public flutter::MethodResult<> { public: ~MockMethodResult() = default; MOCK_METHOD(void, SuccessInternal, (const EncodableValue* result), (override)); MOCK_METHOD(void, ErrorInternal, (const std::string& error_code, const std::string& error_message, const EncodableValue* details), (override)); MOCK_METHOD(void, NotImplementedInternal, (), (override)); }; class MockBinaryMessenger : public flutter::BinaryMessenger { public: ~MockBinaryMessenger() = default; MOCK_METHOD(void, Send, (const std::string& channel, const uint8_t* message, size_t message_size, flutter::BinaryReply reply), (const)); MOCK_METHOD(void, SetMessageHandler, (const std::string& channel, flutter::BinaryMessageHandler handler), ()); }; class MockTextureRegistrar : public flutter::TextureRegistrar { public: MockTextureRegistrar() { ON_CALL(*this, RegisterTexture) .WillByDefault([this](flutter::TextureVariant* texture) -> int64_t { EXPECT_TRUE(texture); this->texture_ = texture; this->texture_id_ = 1000; return this->texture_id_; }); // Deprecated pre-Flutter-3.4 version. ON_CALL(*this, UnregisterTexture(_)) .WillByDefault([this](int64_t tid) -> bool { if (tid == this->texture_id_) { texture_ = nullptr; this->texture_id_ = -1; return true; } return false; }); // Flutter 3.4+ version. ON_CALL(*this, UnregisterTexture(_, _)) .WillByDefault( [this](int64_t tid, std::function<void()> callback) -> void { // Forward to the pre-3.4 implementation so that expectations can // be the same for all versions. this->UnregisterTexture(tid); if (callback) { callback(); } }); ON_CALL(*this, MarkTextureFrameAvailable) .WillByDefault([this](int64_t tid) -> bool { if (tid == this->texture_id_) { return true; } return false; }); } ~MockTextureRegistrar() { texture_ = nullptr; } MOCK_METHOD(int64_t, RegisterTexture, (flutter::TextureVariant * texture), (override)); // Pre-Flutter-3.4 version. MOCK_METHOD(bool, UnregisterTexture, (int64_t), (override)); // Flutter 3.4+ version. // TODO(cbracken): Add an override annotation to this once 3.4+ is the // minimum version tested in CI. MOCK_METHOD(void, UnregisterTexture, (int64_t, std::function<void()> callback), ()); MOCK_METHOD(bool, MarkTextureFrameAvailable, (int64_t), (override)); int64_t texture_id_ = -1; flutter::TextureVariant* texture_ = nullptr; }; class MockCameraFactory : public CameraFactory { public: MockCameraFactory() { ON_CALL(*this, CreateCamera).WillByDefault([this]() { assert(this->pending_camera_); return std::move(this->pending_camera_); }); } ~MockCameraFactory() = default; // Disallow copy and move. MockCameraFactory(const MockCameraFactory&) = delete; MockCameraFactory& operator=(const MockCameraFactory&) = delete; MOCK_METHOD(std::unique_ptr<Camera>, CreateCamera, (const std::string& device_id), (override)); std::unique_ptr<Camera> pending_camera_; }; class MockCamera : public Camera { public: MockCamera(const std::string& device_id) : device_id_(device_id), Camera(device_id){}; ~MockCamera() = default; // Disallow copy and move. MockCamera(const MockCamera&) = delete; MockCamera& operator=(const MockCamera&) = delete; MOCK_METHOD(void, OnCreateCaptureEngineSucceeded, (int64_t texture_id), (override)); MOCK_METHOD(std::unique_ptr<flutter::MethodResult<>>, GetPendingResultByType, (PendingResultType type)); MOCK_METHOD(void, OnCreateCaptureEngineFailed, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(void, OnStartPreviewSucceeded, (int32_t width, int32_t height), (override)); MOCK_METHOD(void, OnStartPreviewFailed, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(void, OnResumePreviewSucceeded, (), (override)); MOCK_METHOD(void, OnResumePreviewFailed, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(void, OnPausePreviewSucceeded, (), (override)); MOCK_METHOD(void, OnPausePreviewFailed, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(void, OnStartRecordSucceeded, (), (override)); MOCK_METHOD(void, OnStartRecordFailed, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(void, OnStopRecordSucceeded, (const std::string& file_path), (override)); MOCK_METHOD(void, OnStopRecordFailed, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(void, OnTakePictureSucceeded, (const std::string& file_path), (override)); MOCK_METHOD(void, OnTakePictureFailed, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(void, OnVideoRecordSucceeded, (const std::string& file_path, int64_t video_duration), (override)); MOCK_METHOD(void, OnVideoRecordFailed, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(void, OnCaptureError, (CameraResult result, const std::string& error), (override)); MOCK_METHOD(bool, HasDeviceId, (std::string & device_id), (const override)); MOCK_METHOD(bool, HasCameraId, (int64_t camera_id), (const override)); MOCK_METHOD(bool, AddPendingResult, (PendingResultType type, std::unique_ptr<MethodResult<>> result), (override)); MOCK_METHOD(bool, HasPendingResultByType, (PendingResultType type), (const override)); MOCK_METHOD(camera_windows::CaptureController*, GetCaptureController, (), (override)); MOCK_METHOD(bool, InitCamera, (flutter::TextureRegistrar * texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset), (override)); std::unique_ptr<CaptureController> capture_controller_; std::unique_ptr<MethodResult<>> pending_result_; std::string device_id_; int64_t camera_id_ = -1; }; class MockCaptureControllerFactory : public CaptureControllerFactory { public: MockCaptureControllerFactory(){}; virtual ~MockCaptureControllerFactory() = default; // Disallow copy and move. MockCaptureControllerFactory(const MockCaptureControllerFactory&) = delete; MockCaptureControllerFactory& operator=(const MockCaptureControllerFactory&) = delete; MOCK_METHOD(std::unique_ptr<CaptureController>, CreateCaptureController, (CaptureControllerListener * listener), (override)); }; class MockCaptureController : public CaptureController { public: ~MockCaptureController() = default; MOCK_METHOD(bool, InitCaptureDevice, (flutter::TextureRegistrar * texture_registrar, const std::string& device_id, bool record_audio, ResolutionPreset resolution_preset), (override)); MOCK_METHOD(uint32_t, GetPreviewWidth, (), (const override)); MOCK_METHOD(uint32_t, GetPreviewHeight, (), (const override)); // Actions MOCK_METHOD(void, StartPreview, (), (override)); MOCK_METHOD(void, ResumePreview, (), (override)); MOCK_METHOD(void, PausePreview, (), (override)); MOCK_METHOD(void, StartRecord, (const std::string& file_path, int64_t max_video_duration_ms), (override)); MOCK_METHOD(void, StopRecord, (), (override)); MOCK_METHOD(void, TakePicture, (const std::string& file_path), (override)); }; // MockCameraPlugin extends CameraPlugin behaviour a bit to allow adding cameras // without creating them first with create message handler and mocking static // system calls class MockCameraPlugin : public CameraPlugin { public: MockCameraPlugin(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger) : CameraPlugin(texture_registrar, messenger){}; // Creates a plugin instance with the given CameraFactory instance. // Exists for unit testing with mock implementations. MockCameraPlugin(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, std::unique_ptr<CameraFactory> camera_factory) : CameraPlugin(texture_registrar, messenger, std::move(camera_factory)){}; ~MockCameraPlugin() = default; // Disallow copy and move. MockCameraPlugin(const MockCameraPlugin&) = delete; MockCameraPlugin& operator=(const MockCameraPlugin&) = delete; MOCK_METHOD(bool, EnumerateVideoCaptureDeviceSources, (IMFActivate * **devices, UINT32* count), (override)); // Helper to add camera without creating it via CameraFactory for testing // purposes void AddCamera(std::unique_ptr<Camera> camera) { cameras_.push_back(std::move(camera)); } }; class MockCaptureSource : public IMFCaptureSource { public: MockCaptureSource(){}; ~MockCaptureSource() = default; // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCaptureSource) { *ppv = static_cast<IMFCaptureSource*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } MOCK_METHOD(HRESULT, GetCaptureDeviceSource, (MF_CAPTURE_ENGINE_DEVICE_TYPE mfCaptureEngineDeviceType, IMFMediaSource** ppMediaSource)); MOCK_METHOD(HRESULT, GetCaptureDeviceActivate, (MF_CAPTURE_ENGINE_DEVICE_TYPE mfCaptureEngineDeviceType, IMFActivate** ppActivate)); MOCK_METHOD(HRESULT, GetService, (REFIID rguidService, REFIID riid, IUnknown** ppUnknown)); MOCK_METHOD(HRESULT, AddEffect, (DWORD dwSourceStreamIndex, IUnknown* pUnknown)); MOCK_METHOD(HRESULT, RemoveEffect, (DWORD dwSourceStreamIndex, IUnknown* pUnknown)); MOCK_METHOD(HRESULT, RemoveAllEffects, (DWORD dwSourceStreamIndex)); MOCK_METHOD(HRESULT, GetAvailableDeviceMediaType, (DWORD dwSourceStreamIndex, DWORD dwMediaTypeIndex, IMFMediaType** ppMediaType)); MOCK_METHOD(HRESULT, SetCurrentDeviceMediaType, (DWORD dwSourceStreamIndex, IMFMediaType* pMediaType)); MOCK_METHOD(HRESULT, GetCurrentDeviceMediaType, (DWORD dwSourceStreamIndex, IMFMediaType** ppMediaType)); MOCK_METHOD(HRESULT, GetDeviceStreamCount, (DWORD * pdwStreamCount)); MOCK_METHOD(HRESULT, GetDeviceStreamCategory, (DWORD dwSourceStreamIndex, MF_CAPTURE_ENGINE_STREAM_CATEGORY* pStreamCategory)); MOCK_METHOD(HRESULT, GetMirrorState, (DWORD dwStreamIndex, BOOL* pfMirrorState)); MOCK_METHOD(HRESULT, SetMirrorState, (DWORD dwStreamIndex, BOOL fMirrorState)); MOCK_METHOD(HRESULT, GetStreamIndexFromFriendlyName, (UINT32 uifriendlyName, DWORD* pdwActualStreamIndex)); private: volatile ULONG ref_ = 0; }; // Uses IMFMediaSourceEx which has SetD3DManager method. class MockMediaSource : public IMFMediaSourceEx { public: MockMediaSource(){}; ~MockMediaSource() = default; // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFMediaSource) { *ppv = static_cast<IMFMediaSource*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } // IMFMediaSource HRESULT GetCharacteristics(DWORD* dwCharacteristics) override { return E_NOTIMPL; } // IMFMediaSource HRESULT CreatePresentationDescriptor( IMFPresentationDescriptor** presentationDescriptor) override { return E_NOTIMPL; } // IMFMediaSource HRESULT Start(IMFPresentationDescriptor* presentationDescriptor, const GUID* guidTimeFormat, const PROPVARIANT* varStartPosition) override { return E_NOTIMPL; } // IMFMediaSource HRESULT Stop(void) override { return E_NOTIMPL; } // IMFMediaSource HRESULT Pause(void) override { return E_NOTIMPL; } // IMFMediaSource HRESULT Shutdown(void) override { return E_NOTIMPL; } // IMFMediaEventGenerator HRESULT GetEvent(DWORD dwFlags, IMFMediaEvent** event) override { return E_NOTIMPL; } // IMFMediaEventGenerator HRESULT BeginGetEvent(IMFAsyncCallback* callback, IUnknown* unkState) override { return E_NOTIMPL; } // IMFMediaEventGenerator HRESULT EndGetEvent(IMFAsyncResult* result, IMFMediaEvent** event) override { return E_NOTIMPL; } // IMFMediaEventGenerator HRESULT QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT* value) override { return E_NOTIMPL; } // IMFMediaSourceEx HRESULT GetSourceAttributes(IMFAttributes** attributes) { return E_NOTIMPL; } // IMFMediaSourceEx HRESULT GetStreamAttributes(DWORD stream_id, IMFAttributes** attributes) { return E_NOTIMPL; } // IMFMediaSourceEx HRESULT SetD3DManager(IUnknown* manager) { return S_OK; } private: volatile ULONG ref_ = 0; }; class MockCapturePreviewSink : public IMFCapturePreviewSink { public: // IMFCaptureSink MOCK_METHOD(HRESULT, GetOutputMediaType, (DWORD dwSinkStreamIndex, IMFMediaType** ppMediaType)); // IMFCaptureSink MOCK_METHOD(HRESULT, GetService, (DWORD dwSinkStreamIndex, REFGUID rguidService, REFIID riid, IUnknown** ppUnknown)); // IMFCaptureSink MOCK_METHOD(HRESULT, AddStream, (DWORD dwSourceStreamIndex, IMFMediaType* pMediaType, IMFAttributes* pAttributes, DWORD* pdwSinkStreamIndex)); // IMFCaptureSink MOCK_METHOD(HRESULT, Prepare, ()); // IMFCaptureSink MOCK_METHOD(HRESULT, RemoveAllStreams, ()); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetRenderHandle, (HANDLE handle)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetRenderSurface, (IUnknown * pSurface)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, UpdateVideo, (const MFVideoNormalizedRect* pSrc, const RECT* pDst, const COLORREF* pBorderClr)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetSampleCallback, (DWORD dwStreamSinkIndex, IMFCaptureEngineOnSampleCallback* pCallback)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, GetMirrorState, (BOOL * pfMirrorState)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetMirrorState, (BOOL fMirrorState)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, GetRotation, (DWORD dwStreamIndex, DWORD* pdwRotationValue)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetRotation, (DWORD dwStreamIndex, DWORD dwRotationValue)); // IMFCapturePreviewSink MOCK_METHOD(HRESULT, SetCustomSink, (IMFMediaSink * pMediaSink)); // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCapturePreviewSink) { *ppv = static_cast<IMFCapturePreviewSink*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } void SendFakeSample(uint8_t* src_buffer, uint32_t size) { assert(sample_callback_); ComPtr<IMFSample> sample; ComPtr<IMFMediaBuffer> buffer; HRESULT hr = MFCreateSample(&sample); if (SUCCEEDED(hr)) { hr = MFCreateMemoryBuffer(size, &buffer); } if (SUCCEEDED(hr)) { uint8_t* target_data; if (SUCCEEDED(buffer->Lock(&target_data, nullptr, nullptr))) { std::copy(src_buffer, src_buffer + size, target_data); } hr = buffer->Unlock(); } if (SUCCEEDED(hr)) { hr = buffer->SetCurrentLength(size); } if (SUCCEEDED(hr)) { hr = sample->AddBuffer(buffer.Get()); } if (SUCCEEDED(hr)) { sample_callback_->OnSample(sample.Get()); } } ComPtr<IMFCaptureEngineOnSampleCallback> sample_callback_; private: ~MockCapturePreviewSink() = default; volatile ULONG ref_ = 0; }; class MockCaptureRecordSink : public IMFCaptureRecordSink { public: // IMFCaptureSink MOCK_METHOD(HRESULT, GetOutputMediaType, (DWORD dwSinkStreamIndex, IMFMediaType** ppMediaType)); // IMFCaptureSink MOCK_METHOD(HRESULT, GetService, (DWORD dwSinkStreamIndex, REFGUID rguidService, REFIID riid, IUnknown** ppUnknown)); // IMFCaptureSink MOCK_METHOD(HRESULT, AddStream, (DWORD dwSourceStreamIndex, IMFMediaType* pMediaType, IMFAttributes* pAttributes, DWORD* pdwSinkStreamIndex)); // IMFCaptureSink MOCK_METHOD(HRESULT, Prepare, ()); // IMFCaptureSink MOCK_METHOD(HRESULT, RemoveAllStreams, ()); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetOutputByteStream, (IMFByteStream * pByteStream, REFGUID guidContainerType)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetOutputFileName, (LPCWSTR fileName)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetSampleCallback, (DWORD dwStreamSinkIndex, IMFCaptureEngineOnSampleCallback* pCallback)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetCustomSink, (IMFMediaSink * pMediaSink)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, GetRotation, (DWORD dwStreamIndex, DWORD* pdwRotationValue)); // IMFCaptureRecordSink MOCK_METHOD(HRESULT, SetRotation, (DWORD dwStreamIndex, DWORD dwRotationValue)); // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCaptureRecordSink) { *ppv = static_cast<IMFCaptureRecordSink*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } private: ~MockCaptureRecordSink() = default; volatile ULONG ref_ = 0; }; class MockCapturePhotoSink : public IMFCapturePhotoSink { public: // IMFCaptureSink MOCK_METHOD(HRESULT, GetOutputMediaType, (DWORD dwSinkStreamIndex, IMFMediaType** ppMediaType)); // IMFCaptureSink MOCK_METHOD(HRESULT, GetService, (DWORD dwSinkStreamIndex, REFGUID rguidService, REFIID riid, IUnknown** ppUnknown)); // IMFCaptureSink MOCK_METHOD(HRESULT, AddStream, (DWORD dwSourceStreamIndex, IMFMediaType* pMediaType, IMFAttributes* pAttributes, DWORD* pdwSinkStreamIndex)); // IMFCaptureSink MOCK_METHOD(HRESULT, Prepare, ()); // IMFCaptureSink MOCK_METHOD(HRESULT, RemoveAllStreams, ()); // IMFCapturePhotoSink MOCK_METHOD(HRESULT, SetOutputFileName, (LPCWSTR fileName)); // IMFCapturePhotoSink MOCK_METHOD(HRESULT, SetSampleCallback, (IMFCaptureEngineOnSampleCallback * pCallback)); // IMFCapturePhotoSink MOCK_METHOD(HRESULT, SetOutputByteStream, (IMFByteStream * pByteStream)); // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCapturePhotoSink) { *ppv = static_cast<IMFCapturePhotoSink*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } private: ~MockCapturePhotoSink() = default; volatile ULONG ref_ = 0; }; template <class T> class FakeIMFAttributesBase : public T { static_assert(std::is_base_of<IMFAttributes, T>::value, "I must inherit from IMFAttributes"); // IIMFAttributes HRESULT GetItem(REFGUID guidKey, PROPVARIANT* pValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE* pType) override { return E_NOTIMPL; } // IIMFAttributes HRESULT CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL* pbResult) override { return E_NOTIMPL; } // IIMFAttributes HRESULT Compare(IMFAttributes* pTheirs, MF_ATTRIBUTES_MATCH_TYPE MatchType, BOOL* pbResult) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetUINT32(REFGUID guidKey, UINT32* punValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetUINT64(REFGUID guidKey, UINT64* punValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetDouble(REFGUID guidKey, double* pfValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetGUID(REFGUID guidKey, GUID* pguidValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetStringLength(REFGUID guidKey, UINT32* pcchLength) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32* pcchLength) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetAllocatedString(REFGUID guidKey, LPWSTR* ppwszValue, UINT32* pcchLength) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetBlobSize(REFGUID guidKey, UINT32* pcbBlobSize) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetBlob(REFGUID guidKey, UINT8* pBuf, UINT32 cbBufSize, UINT32* pcbBlobSize) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetAllocatedBlob(REFGUID guidKey, UINT8** ppBuf, UINT32* pcbSize) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetUnknown(REFGUID guidKey, REFIID riid, __RPC__deref_out_opt LPVOID* ppv) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetItem(REFGUID guidKey, REFPROPVARIANT Value) override { return E_NOTIMPL; } // IIMFAttributes HRESULT DeleteItem(REFGUID guidKey) override { return E_NOTIMPL; } // IIMFAttributes HRESULT DeleteAllItems(void) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetUINT32(REFGUID guidKey, UINT32 unValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetUINT64(REFGUID guidKey, UINT64 unValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetDouble(REFGUID guidKey, double fValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetGUID(REFGUID guidKey, REFGUID guidValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetString(REFGUID guidKey, LPCWSTR wszValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetBlob(REFGUID guidKey, const UINT8* pBuf, UINT32 cbBufSize) override { return E_NOTIMPL; } // IIMFAttributes HRESULT SetUnknown(REFGUID guidKey, IUnknown* pUnknown) override { return E_NOTIMPL; } // IIMFAttributes HRESULT LockStore(void) override { return E_NOTIMPL; } // IIMFAttributes HRESULT UnlockStore(void) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetCount(UINT32* pcItems) override { return E_NOTIMPL; } // IIMFAttributes HRESULT GetItemByIndex(UINT32 unIndex, GUID* pguidKey, PROPVARIANT* pValue) override { return E_NOTIMPL; } // IIMFAttributes HRESULT CopyAllItems(IMFAttributes* pDest) override { return E_NOTIMPL; } }; class FakeMediaType : public FakeIMFAttributesBase<IMFMediaType> { public: FakeMediaType(GUID major_type, GUID sub_type, int width, int height) : major_type_(major_type), sub_type_(sub_type), width_(width), height_(height){}; // IMFAttributes HRESULT GetUINT64(REFGUID key, UINT64* value) override { if (key == MF_MT_FRAME_SIZE) { *value = (int64_t)width_ << 32 | (int64_t)height_; return S_OK; } else if (key == MF_MT_FRAME_RATE) { *value = (int64_t)frame_rate_ << 32 | 1; return S_OK; } return E_FAIL; }; // IMFAttributes HRESULT GetGUID(REFGUID key, GUID* value) override { if (key == MF_MT_MAJOR_TYPE) { *value = major_type_; return S_OK; } else if (key == MF_MT_SUBTYPE) { *value = sub_type_; return S_OK; } return E_FAIL; } // IIMFAttributes HRESULT CopyAllItems(IMFAttributes* pDest) override { pDest->SetUINT64(MF_MT_FRAME_SIZE, (int64_t)width_ << 32 | (int64_t)height_); pDest->SetUINT64(MF_MT_FRAME_RATE, (int64_t)frame_rate_ << 32 | 1); pDest->SetGUID(MF_MT_MAJOR_TYPE, major_type_); pDest->SetGUID(MF_MT_SUBTYPE, sub_type_); return S_OK; } // IMFMediaType HRESULT STDMETHODCALLTYPE GetMajorType(GUID* pguidMajorType) override { return E_NOTIMPL; }; // IMFMediaType HRESULT STDMETHODCALLTYPE IsCompressedFormat(BOOL* pfCompressed) override { return E_NOTIMPL; } // IMFMediaType HRESULT STDMETHODCALLTYPE IsEqual(IMFMediaType* pIMediaType, DWORD* pdwFlags) override { return E_NOTIMPL; } // IMFMediaType HRESULT STDMETHODCALLTYPE GetRepresentation( GUID guidRepresentation, LPVOID* ppvRepresentation) override { return E_NOTIMPL; } // IMFMediaType HRESULT STDMETHODCALLTYPE FreeRepresentation( GUID guidRepresentation, LPVOID pvRepresentation) override { return E_NOTIMPL; } // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFMediaType) { *ppv = static_cast<IMFMediaType*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } private: ~FakeMediaType() = default; volatile ULONG ref_ = 0; const GUID major_type_; const GUID sub_type_; const int width_; const int height_; const int frame_rate_ = 30; }; class MockCaptureEngine : public IMFCaptureEngine { public: MockCaptureEngine() { ON_CALL(*this, Initialize) .WillByDefault([this](IMFCaptureEngineOnEventCallback* callback, IMFAttributes* attributes, IUnknown* audioSource, IUnknown* videoSource) -> HRESULT { EXPECT_TRUE(callback); EXPECT_TRUE(attributes); EXPECT_TRUE(videoSource); // audioSource is allowed to be nullptr; callback_ = callback; videoSource_ = reinterpret_cast<IMFMediaSource*>(videoSource); audioSource_ = reinterpret_cast<IMFMediaSource*>(audioSource); initialized_ = true; return S_OK; }); }; virtual ~MockCaptureEngine() = default; MOCK_METHOD(HRESULT, Initialize, (IMFCaptureEngineOnEventCallback * callback, IMFAttributes* attributes, IUnknown* audioSource, IUnknown* videoSource)); MOCK_METHOD(HRESULT, StartPreview, ()); MOCK_METHOD(HRESULT, StopPreview, ()); MOCK_METHOD(HRESULT, StartRecord, ()); MOCK_METHOD(HRESULT, StopRecord, (BOOL finalize, BOOL flushUnprocessedSamples)); MOCK_METHOD(HRESULT, TakePhoto, ()); MOCK_METHOD(HRESULT, GetSink, (MF_CAPTURE_ENGINE_SINK_TYPE type, IMFCaptureSink** sink)); MOCK_METHOD(HRESULT, GetSource, (IMFCaptureSource * *ppSource)); // IUnknown STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCaptureEngine) { *ppv = static_cast<IMFCaptureEngine*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } void CreateFakeEvent(HRESULT hrStatus, GUID event_type) { EXPECT_TRUE(initialized_); ComPtr<IMFMediaEvent> event; MFCreateMediaEvent(MEExtendedType, event_type, hrStatus, nullptr, &event); if (callback_) { callback_->OnEvent(event.Get()); } } ComPtr<IMFCaptureEngineOnEventCallback> callback_; ComPtr<IMFMediaSource> videoSource_; ComPtr<IMFMediaSource> audioSource_; volatile ULONG ref_ = 0; bool initialized_ = false; }; #define MOCK_DEVICE_ID "mock_device_id" #define MOCK_CAMERA_NAME "mock_camera_name <" MOCK_DEVICE_ID ">" #define MOCK_INVALID_CAMERA_NAME "invalid_camera_name" } // namespace } // namespace test } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_TEST_MOCKS_H_
plugins/packages/camera/camera_windows/windows/test/mocks.h/0
{ "file_path": "plugins/packages/camera/camera_windows/windows/test/mocks.h", "repo_id": "plugins", "token_count": 12733 }
1,233
// 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.action; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import android.os.Looper; import androidx.test.espresso.IdlingRegistry; import androidx.test.espresso.IdlingResource; import androidx.test.espresso.UiController; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; /** Utils for the Flutter actions. */ final class ActionUtil { /** * Loops the main thread until the given future task has been done. Users could use this method to * "synchronize" between the main thread and {@code Future} instances running on its own thread * (e.g. methods of the {@code FlutterTestingProtocol}), without blocking the main thread. * * <p>Usage: * * <pre>{@code * Future<T> fooFuture = flutterTestingProtocol.callFoo(); * T fooResult = loopUntilCompletion("fooTask", androidUiController, fooFuture, executor); * // Then consumes the fooResult on main thread. * }</pre> * * @param taskName the name that shall be used when registering the task as an {@link * IdlingResource}. Espresso ignores {@link IdlingResource} with the same name, so always uses * a unique name if you don't want Espresso to ignore your task. * @param androidUiController the controller to use to interact with the Android UI. * @param futureTask the future task that main thread should wait for a completion signal. * @param executor the executor to use for running async tasks within the method. * @param <T> the return value type. * @return the result of the future task. * @throws ExecutionException if any error occurs during executing the future task. * @throws InterruptedException when any internal thread is interrupted. */ public static <T> T loopUntilCompletion( String taskName, UiController androidUiController, Future<T> futureTask, ExecutorService executor) throws ExecutionException, InterruptedException { checkState(Looper.myLooper() == Looper.getMainLooper(), "Expecting to be on main thread!"); FutureIdlingResource<T> idlingResourceFuture = new FutureIdlingResource<>(taskName, futureTask); IdlingRegistry.getInstance().register(idlingResourceFuture); try { // It's fine to ignore this {@code Future} handler, since {@code idlingResourceFuture} should // give us the result/error any way. @SuppressWarnings("unused") Future<?> possiblyIgnoredError = executor.submit(idlingResourceFuture); androidUiController.loopMainThreadUntilIdle(); checkState(idlingResourceFuture.isDone(), "Future task signaled - but it wasn't done."); return idlingResourceFuture.get(); } finally { IdlingRegistry.getInstance().unregister(idlingResourceFuture); } } /** * An {@code IdlingResource} implementation that takes in a {@code Future}, and sends the idle * signal to the main thread when the given {@code Future} is done. * * @param <T> the return value type of this {@code FutureTask}. */ private static class FutureIdlingResource<T> extends FutureTask<T> implements IdlingResource { private final String taskName; // Written from main thread, read from any thread. private volatile ResourceCallback resourceCallback; public FutureIdlingResource(String taskName, final Future<T> future) { super( new Callable<T>() { @Override public T call() throws Exception { return future.get(); } }); this.taskName = checkNotNull(taskName); } @Override public String getName() { return taskName; } @Override public void done() { resourceCallback.onTransitionToIdle(); } @Override public boolean isIdleNow() { return isDone(); } @Override public void registerIdleTransitionCallback(ResourceCallback callback) { this.resourceCallback = callback; } } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/ActionUtil.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/ActionUtil.java", "repo_id": "plugins", "token_count": 1393 }
1,234
// 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.assertion; import static com.google.common.base.Preconditions.checkNotNull; import static org.hamcrest.MatcherAssert.assertThat; import android.view.View; import androidx.test.espresso.flutter.api.WidgetAssertion; import androidx.test.espresso.flutter.model.WidgetInfo; import javax.annotation.Nonnull; import org.hamcrest.Matcher; /** Collection of common {@link WidgetAssertion} instances. */ public final class FlutterAssertions { /** * Returns a generic {@link WidgetAssertion} that asserts that a Flutter widget exists and is * matched by the given widget matcher. */ public static WidgetAssertion matches(@Nonnull Matcher<WidgetInfo> widgetMatcher) { return new MatchesWidgetAssertion(checkNotNull(widgetMatcher, "Matcher cannot be null.")); } /** A widget assertion that checks whether a widget is matched by the given matcher. */ static class MatchesWidgetAssertion implements WidgetAssertion { private final Matcher<WidgetInfo> widgetMatcher; private MatchesWidgetAssertion(Matcher<WidgetInfo> widgetMatcher) { this.widgetMatcher = checkNotNull(widgetMatcher); } @Override public void check(View flutterView, WidgetInfo widgetInfo) { assertThat(widgetInfo, widgetMatcher); } } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/assertion/FlutterAssertions.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/assertion/FlutterAssertions.java", "repo_id": "plugins", "token_count": 448 }
1,235
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package androidx.test.espresso.flutter.internal.protocol.impl; /** Represents an exception/error relevant to Dart VM service. */ public final class FlutterProtocolException extends RuntimeException { public FlutterProtocolException(String message) { super(message); } public FlutterProtocolException(Throwable t) { super(t); } public FlutterProtocolException(String message, Throwable t) { super(message, t); } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/FlutterProtocolException.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/FlutterProtocolException.java", "repo_id": "plugins", "token_count": 172 }
1,236
// 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.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 tooltip. */ public final class WithTooltipMatcher extends WidgetMatcher { @Expose @SerializedName("text") private final String tooltip; /** * Constructs the matcher with the given {@code tooltip} to be matched with. * * @param tooltip the tooltip to be matched with. */ public WithTooltipMatcher(@Nonnull String tooltip) { super("ByTooltipMessage"); this.tooltip = checkNotNull(tooltip); } /** Returns the tooltip string that shall be matched for the widget. */ public String getTooltip() { return tooltip; } @Override public String toString() { return "with tooltip: " + tooltip; } @Override protected boolean matchesSafely(WidgetInfo widget) { return tooltip.equals(widget.getTooltip()); } @Override public void describeTo(Description description) { description.appendText("with tooltip: ").appendText(tooltip); } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/WithTooltipMatcher.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/WithTooltipMatcher.java", "repo_id": "plugins", "token_count": 455 }
1,237
## NEXT * Updates example code for `use_build_context_synchronously` lint. * Updates minimum Flutter version to 3.0. ## 0.9.2+2 * Improves API docs and examples. * Changes XTypeGroup initialization from final to const. * Updates minimum Flutter version to 2.10. ## 0.9.2 * Adds an endorsed iOS implementation. ## 0.9.1 * Adds an endorsed Linux implementation. ## 0.9.0 * **BREAKING CHANGE**: The following methods: * `openFile` * `openFiles` * `getSavePath` can throw `ArgumentError`s if called with any `XTypeGroup`s that do not contain appropriate filters for the current platform. For example, an `XTypeGroup` that only specifies `webWildCards` will throw on non-web platforms. To avoid runtime errors, ensure that all `XTypeGroup`s (other than wildcards) set filters that cover every platform your application targets. See the README for details. ## 0.8.4+3 * Improves API docs and examples. * Minor fixes for new analysis options. ## 0.8.4+2 * Removes unnecessary imports. * Adds OS version support information to README. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.8.4+1 * Adds README information about macOS entitlements. * Adds necessary entitlement to macOS example. ## 0.8.4 * Adds an endorsed macOS implementation. ## 0.8.3 * Adds an endorsed Windows implementation. ## 0.8.2+1 * Minor code cleanup for new analysis rules. * Updated package description. ## 0.8.2 * Update `platform_plugin_interface` version requirement. ## 0.8.1 Endorse the web implementation. ## 0.8.0 Migrate to null safety. ## 0.7.0+2 * Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets. ## 0.7.0+1 * Update Flutter SDK constraint. ## 0.7.0 * Initial Open Source release.
plugins/packages/file_selector/file_selector/CHANGELOG.md/0
{ "file_path": "plugins/packages/file_selector/file_selector/CHANGELOG.md", "repo_id": "plugins", "token_count": 582 }
1,238
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector/file_selector.dart'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; void main() { late FakeFileSelector fakePlatformImplementation; const String initialDirectory = '/home/flutteruser'; const String confirmButtonText = 'Use this profile picture'; const String suggestedName = 'suggested_name'; const List<XTypeGroup> acceptedTypeGroups = <XTypeGroup>[ XTypeGroup(label: 'documents', mimeTypes: <String>[ 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessing', ]), XTypeGroup(label: 'images', extensions: <String>[ 'jpg', 'png', ]), ]; setUp(() { fakePlatformImplementation = FakeFileSelector(); FileSelectorPlatform.instance = fakePlatformImplementation; }); group('openFile', () { final XFile expectedFile = XFile('path'); test('works', () async { fakePlatformImplementation ..setExpectations( initialDirectory: initialDirectory, confirmButtonText: confirmButtonText, acceptedTypeGroups: acceptedTypeGroups) ..setFileResponse(<XFile>[expectedFile]); final XFile? file = await openFile( initialDirectory: initialDirectory, confirmButtonText: confirmButtonText, acceptedTypeGroups: acceptedTypeGroups, ); expect(file, expectedFile); }); test('works with no arguments', () async { fakePlatformImplementation.setFileResponse(<XFile>[expectedFile]); final XFile? file = await openFile(); expect(file, expectedFile); }); test('sets the initial directory', () async { fakePlatformImplementation ..setExpectations(initialDirectory: initialDirectory) ..setFileResponse(<XFile>[expectedFile]); final XFile? file = await openFile(initialDirectory: initialDirectory); expect(file, expectedFile); }); test('sets the button confirmation label', () async { fakePlatformImplementation ..setExpectations(confirmButtonText: confirmButtonText) ..setFileResponse(<XFile>[expectedFile]); final XFile? file = await openFile(confirmButtonText: confirmButtonText); expect(file, expectedFile); }); test('sets the accepted type groups', () async { fakePlatformImplementation ..setExpectations(acceptedTypeGroups: acceptedTypeGroups) ..setFileResponse(<XFile>[expectedFile]); final XFile? file = await openFile(acceptedTypeGroups: acceptedTypeGroups); expect(file, expectedFile); }); }); group('openFiles', () { final List<XFile> expectedFiles = <XFile>[XFile('path')]; test('works', () async { fakePlatformImplementation ..setExpectations( initialDirectory: initialDirectory, confirmButtonText: confirmButtonText, acceptedTypeGroups: acceptedTypeGroups) ..setFileResponse(expectedFiles); final List<XFile> files = await openFiles( initialDirectory: initialDirectory, confirmButtonText: confirmButtonText, acceptedTypeGroups: acceptedTypeGroups, ); expect(files, expectedFiles); }); test('works with no arguments', () async { fakePlatformImplementation.setFileResponse(expectedFiles); final List<XFile> files = await openFiles(); expect(files, expectedFiles); }); test('sets the initial directory', () async { fakePlatformImplementation ..setExpectations(initialDirectory: initialDirectory) ..setFileResponse(expectedFiles); final List<XFile> files = await openFiles(initialDirectory: initialDirectory); expect(files, expectedFiles); }); test('sets the button confirmation label', () async { fakePlatformImplementation ..setExpectations(confirmButtonText: confirmButtonText) ..setFileResponse(expectedFiles); final List<XFile> files = await openFiles(confirmButtonText: confirmButtonText); expect(files, expectedFiles); }); test('sets the accepted type groups', () async { fakePlatformImplementation ..setExpectations(acceptedTypeGroups: acceptedTypeGroups) ..setFileResponse(expectedFiles); final List<XFile> files = await openFiles(acceptedTypeGroups: acceptedTypeGroups); expect(files, expectedFiles); }); }); group('getSavePath', () { const String expectedSavePath = '/example/path'; test('works', () async { fakePlatformImplementation ..setExpectations( initialDirectory: initialDirectory, confirmButtonText: confirmButtonText, acceptedTypeGroups: acceptedTypeGroups, suggestedName: suggestedName) ..setPathResponse(expectedSavePath); final String? savePath = await getSavePath( initialDirectory: initialDirectory, confirmButtonText: confirmButtonText, acceptedTypeGroups: acceptedTypeGroups, suggestedName: suggestedName, ); expect(savePath, expectedSavePath); }); test('works with no arguments', () async { fakePlatformImplementation.setPathResponse(expectedSavePath); final String? savePath = await getSavePath(); expect(savePath, expectedSavePath); }); test('sets the initial directory', () async { fakePlatformImplementation ..setExpectations(initialDirectory: initialDirectory) ..setPathResponse(expectedSavePath); final String? savePath = await getSavePath(initialDirectory: initialDirectory); expect(savePath, expectedSavePath); }); test('sets the button confirmation label', () async { fakePlatformImplementation ..setExpectations(confirmButtonText: confirmButtonText) ..setPathResponse(expectedSavePath); final String? savePath = await getSavePath(confirmButtonText: confirmButtonText); expect(savePath, expectedSavePath); }); test('sets the accepted type groups', () async { fakePlatformImplementation ..setExpectations(acceptedTypeGroups: acceptedTypeGroups) ..setPathResponse(expectedSavePath); final String? savePath = await getSavePath(acceptedTypeGroups: acceptedTypeGroups); expect(savePath, expectedSavePath); }); test('sets the suggested name', () async { fakePlatformImplementation ..setExpectations(suggestedName: suggestedName) ..setPathResponse(expectedSavePath); final String? savePath = await getSavePath(suggestedName: suggestedName); expect(savePath, expectedSavePath); }); }); group('getDirectoryPath', () { const String expectedDirectoryPath = '/example/path'; test('works', () async { fakePlatformImplementation ..setExpectations( initialDirectory: initialDirectory, confirmButtonText: confirmButtonText) ..setPathResponse(expectedDirectoryPath); final String? directoryPath = await getDirectoryPath( initialDirectory: initialDirectory, confirmButtonText: confirmButtonText, ); expect(directoryPath, expectedDirectoryPath); }); test('works with no arguments', () async { fakePlatformImplementation.setPathResponse(expectedDirectoryPath); final String? directoryPath = await getDirectoryPath(); expect(directoryPath, expectedDirectoryPath); }); test('sets the initial directory', () async { fakePlatformImplementation ..setExpectations(initialDirectory: initialDirectory) ..setPathResponse(expectedDirectoryPath); final String? directoryPath = await getDirectoryPath(initialDirectory: initialDirectory); expect(directoryPath, expectedDirectoryPath); }); test('sets the button confirmation label', () async { fakePlatformImplementation ..setExpectations(confirmButtonText: confirmButtonText) ..setPathResponse(expectedDirectoryPath); final String? directoryPath = await getDirectoryPath(confirmButtonText: confirmButtonText); expect(directoryPath, expectedDirectoryPath); }); }); } class FakeFileSelector extends Fake with MockPlatformInterfaceMixin implements FileSelectorPlatform { // Expectations. List<XTypeGroup>? acceptedTypeGroups = const <XTypeGroup>[]; String? initialDirectory; String? confirmButtonText; String? suggestedName; // Return values. List<XFile>? files; String? path; void setExpectations({ List<XTypeGroup> acceptedTypeGroups = const <XTypeGroup>[], String? initialDirectory, String? suggestedName, String? confirmButtonText, }) { this.acceptedTypeGroups = acceptedTypeGroups; this.initialDirectory = initialDirectory; this.suggestedName = suggestedName; this.confirmButtonText = confirmButtonText; } // ignore: use_setters_to_change_properties void setFileResponse(List<XFile> files) { this.files = files; } // ignore: use_setters_to_change_properties void setPathResponse(String path) { this.path = path; } @override Future<XFile?> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { expect(acceptedTypeGroups, this.acceptedTypeGroups); expect(initialDirectory, this.initialDirectory); expect(suggestedName, suggestedName); return files?[0]; } @override Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { expect(acceptedTypeGroups, this.acceptedTypeGroups); expect(initialDirectory, this.initialDirectory); expect(suggestedName, suggestedName); return files!; } @override Future<String?> getSavePath({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? suggestedName, String? confirmButtonText, }) async { expect(acceptedTypeGroups, this.acceptedTypeGroups); expect(initialDirectory, this.initialDirectory); expect(suggestedName, this.suggestedName); expect(confirmButtonText, this.confirmButtonText); return path; } @override Future<String?> getDirectoryPath({ String? initialDirectory, String? confirmButtonText, }) async { expect(initialDirectory, this.initialDirectory); expect(confirmButtonText, this.confirmButtonText); return path; } }
plugins/packages/file_selector/file_selector/test/file_selector_test.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector/test/file_selector_test.dart", "repo_id": "plugins", "token_count": 3711 }
1,239
// 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 (v3.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon #import <Foundation/Foundation.h> @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @class FlutterStandardTypedData; NS_ASSUME_NONNULL_BEGIN @class FFSFileSelectorConfig; @interface FFSFileSelectorConfig : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithUtis:(NSArray<NSString *> *)utis allowMultiSelection:(NSNumber *)allowMultiSelection; @property(nonatomic, strong) NSArray<NSString *> *utis; @property(nonatomic, strong) NSNumber *allowMultiSelection; @end /// The codec used by FFSFileSelectorApi. NSObject<FlutterMessageCodec> *FFSFileSelectorApiGetCodec(void); @protocol FFSFileSelectorApi - (void)openFileSelectorWithConfig:(FFSFileSelectorConfig *)config completion:(void (^)(NSArray<NSString *> *_Nullable, FlutterError *_Nullable))completion; @end extern void FFSFileSelectorApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FFSFileSelectorApi> *_Nullable api); NS_ASSUME_NONNULL_END
plugins/packages/file_selector/file_selector_ios/ios/Classes/messages.g.h/0
{ "file_path": "plugins/packages/file_selector/file_selector_ios/ios/Classes/messages.g.h", "repo_id": "plugins", "token_count": 553 }
1,240
## NEXT * Updates example code for `use_build_context_synchronously` lint. * Updates minimum Flutter version to 3.0. ## 0.9.0+4 * Converts platform channel to Pigeon. ## 0.9.0+3 * Changes XTypeGroup initialization from final to const. ## 0.9.0+2 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. ## 0.9.0+1 * Updates README for endorsement. * Updates `flutter_test` to be a `dev_dependencies` entry. ## 0.9.0 * **BREAKING CHANGE**: Methods that take `XTypeGroup`s now throw an `ArgumentError` if any group is not a wildcard (all filter types null or empty), but doesn't include any of the filter types supported by macOS. * Ignores deprecation warnings for upcoming styleFrom button API changes. ## 0.8.2+2 * Updates references to the obsolete master branch. ## 0.8.2+1 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.8.2 * Moves source to flutter/plugins. * Adds native unit tests. * Converts native implementation to Swift. * Switches to an internal method channel implementation. ## 0.0.4+1 * Update README ## 0.0.4 * Treat empty filter lists the same as null. ## 0.0.3 * Fix README ## 0.0.2 * Update SDK constraint to signal compatibility with null safety. ## 0.0.1 * Initial macOS implementation of `file_selector`.
plugins/packages/file_selector/file_selector_macos/CHANGELOG.md/0
{ "file_path": "plugins/packages/file_selector/file_selector_macos/CHANGELOG.md", "repo_id": "plugins", "token_count": 457 }
1,241
name: file_selector_platform_interface description: A common platform interface for the file_selector plugin. repository: https://github.com/flutter/plugins/tree/main/packages/file_selector/file_selector_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%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.0 flutter: sdk: flutter http: ^0.13.0 plugin_platform_interface: ^2.1.0 dev_dependencies: flutter_test: sdk: flutter test: ^1.16.3
plugins/packages/file_selector/file_selector_platform_interface/pubspec.yaml/0
{ "file_path": "plugins/packages/file_selector/file_selector_platform_interface/pubspec.yaml", "repo_id": "plugins", "token_count": 288 }
1,242
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'src/dom_helper.dart'; import 'src/utils.dart'; /// The web implementation of [FileSelectorPlatform]. /// /// This class implements the `package:file_selector` functionality for the web. class FileSelectorWeb extends FileSelectorPlatform { /// Default constructor, initializes _domHelper that we can use /// to interact with the DOM. /// overrides parameter allows for testing to override functions FileSelectorWeb({@visibleForTesting DomHelper? domHelper}) : _domHelper = domHelper ?? DomHelper(); final DomHelper _domHelper; /// Registers this class as the default instance of [FileSelectorPlatform]. static void registerWith(Registrar registrar) { FileSelectorPlatform.instance = FileSelectorWeb(); } @override Future<XFile> openFile({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { final List<XFile> files = await _openFiles(acceptedTypeGroups: acceptedTypeGroups); return files.first; } @override Future<List<XFile>> openFiles({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, }) async { return _openFiles(acceptedTypeGroups: acceptedTypeGroups, multiple: true); } // This is intended to be passed to XFile, which ignores the path, but 'null' // indicates a canceled save on other platforms, so provide a non-null dummy // value. @override Future<String?> getSavePath({ List<XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? suggestedName, String? confirmButtonText, }) async => ''; @override Future<String?> getDirectoryPath({ String? initialDirectory, String? confirmButtonText, }) async => null; Future<List<XFile>> _openFiles({ List<XTypeGroup>? acceptedTypeGroups, bool multiple = false, }) async { final String accept = acceptedTypesToString(acceptedTypeGroups); return _domHelper.getFiles( accept: accept, multiple: multiple, ); } }
plugins/packages/file_selector/file_selector_web/lib/file_selector_web.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector_web/lib/file_selector_web.dart", "repo_id": "plugins", "token_count": 775 }
1,243
// 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_UTILS_H_ #define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_UTILS_H_ #include <comdef.h> #include <comip.h> #include <shlobj.h> #include <shobjidl.h> #include <windows.h> #include <memory> #include <string> #include <type_traits> #include <variant> #include "file_dialog_controller.h" _COM_SMARTPTR_TYPEDEF(IShellItem, IID_IShellItem); _COM_SMARTPTR_TYPEDEF(IShellItemArray, IID_IShellItemArray); namespace file_selector_windows { namespace test { // Creates a temp file, managed as an IShellItem, which will be deleted when // the instance goes out of scope. // // This creates a file on the filesystem since creating IShellItem instances for // files that don't exist is non-trivial. class ScopedTestShellItem { public: ScopedTestShellItem(); ~ScopedTestShellItem(); // Disallow copy and assign. ScopedTestShellItem(const ScopedTestShellItem&) = delete; ScopedTestShellItem& operator=(const ScopedTestShellItem&) = delete; // Returns the file's IShellItem reference. IShellItemPtr file() { return item_; } // Returns the file's path. const std::wstring& path() { return path_; } private: IShellItemPtr item_; std::wstring path_; }; // Creates a temp file, managed as an ITEMIDLIST, which will be deleted when // the instance goes out of scope. // // This creates a file on the filesystem since creating IShellItem instances for // files that don't exist is non-trivial, and this is intended for use in // creating IShellItemArray instances. class ScopedTestFileIdList { public: ScopedTestFileIdList(); ~ScopedTestFileIdList(); // Disallow copy and assign. ScopedTestFileIdList(const ScopedTestFileIdList&) = delete; ScopedTestFileIdList& operator=(const ScopedTestFileIdList&) = delete; // Returns the file's ITEMIDLIST reference. PIDLIST_ABSOLUTE file() { return item_.get(); } // Returns the file's path. const std::wstring& path() { return path_; } private: // Smart pointer for managing ITEMIDLIST instances. struct ItemIdListDeleter { void operator()(LPITEMIDLIST item) { if (item) { ::ILFree(item); } } }; using ItemIdListPtr = std::unique_ptr<std::remove_pointer_t<PIDLIST_ABSOLUTE>, ItemIdListDeleter>; ItemIdListPtr item_; std::wstring path_; }; } // namespace test } // namespace file_selector_windows #endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_TEST_TEST_UTILS_H_
plugins/packages/file_selector/file_selector_windows/windows/test/test_utils.h/0
{ "file_path": "plugins/packages/file_selector/file_selector_windows/windows/test/test_utils.h", "repo_id": "plugins", "token_count": 930 }
1,244
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.googlemaps"> </manifest>
plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/AndroidManifest.xml/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/AndroidManifest.xml", "repo_id": "plugins", "token_count": 45 }
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. @import google_maps_flutter_ios; @import google_maps_flutter_ios.Test; @import XCTest; @import MapKit; @import GoogleMaps; #import <OCMock/OCMock.h> #import "PartiallyMockedMapView.h" @interface FLTGoogleMapJSONConversionsTests : XCTestCase @end @implementation FLTGoogleMapJSONConversionsTests - (void)testLocationFromLatLong { NSArray<NSNumber *> *latlong = @[ @1, @2 ]; CLLocationCoordinate2D location = [FLTGoogleMapJSONConversions locationFromLatLong:latlong]; XCTAssertEqual(location.latitude, 1); XCTAssertEqual(location.longitude, 2); } - (void)testPointFromArray { NSArray<NSNumber *> *array = @[ @1, @2 ]; CGPoint point = [FLTGoogleMapJSONConversions pointFromArray:array]; XCTAssertEqual(point.x, 1); XCTAssertEqual(point.y, 2); } - (void)testArrayFromLocation { CLLocationCoordinate2D location = CLLocationCoordinate2DMake(1, 2); NSArray<NSNumber *> *array = [FLTGoogleMapJSONConversions arrayFromLocation:location]; XCTAssertEqual([array[0] integerValue], 1); XCTAssertEqual([array[1] integerValue], 2); } - (void)testColorFromRGBA { NSNumber *rgba = @(0x01020304); UIColor *color = [FLTGoogleMapJSONConversions colorFromRGBA:rgba]; CGFloat red, green, blue, alpha; BOOL success = [color getRed:&red green:&green blue:&blue alpha:&alpha]; XCTAssertTrue(success); const CGFloat accuracy = 0.0001; XCTAssertEqualWithAccuracy(red, 2 / 255.0, accuracy); XCTAssertEqualWithAccuracy(green, 3 / 255.0, accuracy); XCTAssertEqualWithAccuracy(blue, 4 / 255.0, accuracy); XCTAssertEqualWithAccuracy(alpha, 1 / 255.0, accuracy); } - (void)testPointsFromLatLongs { NSArray<NSArray *> *latlongs = @[ @[ @1, @2 ], @[ @(3), @(4) ] ]; NSArray<CLLocation *> *locations = [FLTGoogleMapJSONConversions pointsFromLatLongs:latlongs]; XCTAssertEqual(locations.count, 2); XCTAssertEqual(locations[0].coordinate.latitude, 1); XCTAssertEqual(locations[0].coordinate.longitude, 2); XCTAssertEqual(locations[1].coordinate.latitude, 3); XCTAssertEqual(locations[1].coordinate.longitude, 4); } - (void)testHolesFromPointsArray { NSArray<NSArray *> *pointsArray = @[ @[ @[ @1, @2 ], @[ @(3), @(4) ] ], @[ @[ @(5), @(6) ], @[ @(7), @(8) ] ] ]; NSArray<NSArray<CLLocation *> *> *holes = [FLTGoogleMapJSONConversions holesFromPointsArray:pointsArray]; XCTAssertEqual(holes.count, 2); XCTAssertEqual(holes[0][0].coordinate.latitude, 1); XCTAssertEqual(holes[0][0].coordinate.longitude, 2); XCTAssertEqual(holes[0][1].coordinate.latitude, 3); XCTAssertEqual(holes[0][1].coordinate.longitude, 4); XCTAssertEqual(holes[1][0].coordinate.latitude, 5); XCTAssertEqual(holes[1][0].coordinate.longitude, 6); XCTAssertEqual(holes[1][1].coordinate.latitude, 7); XCTAssertEqual(holes[1][1].coordinate.longitude, 8); } - (void)testDictionaryFromPosition { id mockPosition = OCMClassMock([GMSCameraPosition class]); NSValue *locationValue = [NSValue valueWithMKCoordinate:CLLocationCoordinate2DMake(1, 2)]; [(GMSCameraPosition *)[[mockPosition stub] andReturnValue:locationValue] target]; [[[mockPosition stub] andReturnValue:@(2.0)] zoom]; [[[mockPosition stub] andReturnValue:@(3.0)] bearing]; [[[mockPosition stub] andReturnValue:@(75.0)] viewingAngle]; NSDictionary *dictionary = [FLTGoogleMapJSONConversions dictionaryFromPosition:mockPosition]; NSArray *targetArray = @[ @1, @2 ]; XCTAssertEqualObjects(dictionary[@"target"], targetArray); XCTAssertEqualObjects(dictionary[@"zoom"], @2.0); XCTAssertEqualObjects(dictionary[@"bearing"], @3.0); XCTAssertEqualObjects(dictionary[@"tilt"], @75.0); } - (void)testDictionaryFromPoint { CGPoint point = CGPointMake(10, 20); NSDictionary *dictionary = [FLTGoogleMapJSONConversions dictionaryFromPoint:point]; const CGFloat accuracy = 0.0001; XCTAssertEqualWithAccuracy([dictionary[@"x"] floatValue], point.x, accuracy); XCTAssertEqualWithAccuracy([dictionary[@"y"] floatValue], point.y, accuracy); } - (void)testDictionaryFromCoordinateBounds { XCTAssertNil([FLTGoogleMapJSONConversions dictionaryFromCoordinateBounds:nil]); GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:CLLocationCoordinate2DMake(10, 20) coordinate:CLLocationCoordinate2DMake(30, 40)]; NSDictionary *dictionary = [FLTGoogleMapJSONConversions dictionaryFromCoordinateBounds:bounds]; NSArray *southwest = @[ @10, @20 ]; NSArray *northeast = @[ @30, @40 ]; XCTAssertEqualObjects(dictionary[@"southwest"], southwest); XCTAssertEqualObjects(dictionary[@"northeast"], northeast); } - (void)testCameraPostionFromDictionary { XCTAssertNil([FLTGoogleMapJSONConversions cameraPostionFromDictionary:nil]); NSDictionary *channelValue = @{@"target" : @[ @1, @2 ], @"zoom" : @3, @"bearing" : @4, @"tilt" : @5}; GMSCameraPosition *cameraPosition = [FLTGoogleMapJSONConversions cameraPostionFromDictionary:channelValue]; const CGFloat accuracy = 0.001; XCTAssertEqualWithAccuracy(cameraPosition.target.latitude, 1, accuracy); XCTAssertEqualWithAccuracy(cameraPosition.target.longitude, 2, accuracy); XCTAssertEqualWithAccuracy(cameraPosition.zoom, 3, accuracy); XCTAssertEqualWithAccuracy(cameraPosition.bearing, 4, accuracy); XCTAssertEqualWithAccuracy(cameraPosition.viewingAngle, 5, accuracy); } - (void)testPointFromDictionary { XCTAssertNil([FLTGoogleMapJSONConversions cameraPostionFromDictionary:nil]); NSDictionary *dictionary = @{ @"x" : @1, @"y" : @2, }; CGPoint point = [FLTGoogleMapJSONConversions pointFromDictionary:dictionary]; const CGFloat accuracy = 0.001; XCTAssertEqualWithAccuracy(point.x, 1, accuracy); XCTAssertEqualWithAccuracy(point.y, 2, accuracy); } - (void)testCoordinateBoundsFromLatLongs { NSArray<NSNumber *> *latlong1 = @[ @1, @2 ]; NSArray<NSNumber *> *latlong2 = @[ @(3), @(4) ]; GMSCoordinateBounds *bounds = [FLTGoogleMapJSONConversions coordinateBoundsFromLatLongs:@[ latlong1, latlong2 ]]; const CGFloat accuracy = 0.001; XCTAssertEqualWithAccuracy(bounds.southWest.latitude, 1, accuracy); XCTAssertEqualWithAccuracy(bounds.southWest.longitude, 2, accuracy); XCTAssertEqualWithAccuracy(bounds.northEast.latitude, 3, accuracy); XCTAssertEqualWithAccuracy(bounds.northEast.longitude, 4, accuracy); } - (void)testMapViewTypeFromTypeValue { XCTAssertEqual(kGMSTypeNormal, [FLTGoogleMapJSONConversions mapViewTypeFromTypeValue:@1]); XCTAssertEqual(kGMSTypeSatellite, [FLTGoogleMapJSONConversions mapViewTypeFromTypeValue:@2]); XCTAssertEqual(kGMSTypeTerrain, [FLTGoogleMapJSONConversions mapViewTypeFromTypeValue:@3]); XCTAssertEqual(kGMSTypeHybrid, [FLTGoogleMapJSONConversions mapViewTypeFromTypeValue:@4]); XCTAssertEqual(kGMSTypeNone, [FLTGoogleMapJSONConversions mapViewTypeFromTypeValue:@5]); } - (void)testCameraUpdateFromChannelValueNewCameraPosition { NSArray *channelValue = @[ @"newCameraPosition", @{@"target" : @[ @1, @2 ], @"zoom" : @3, @"bearing" : @4, @"tilt" : @5} ]; id classMockCameraUpdate = OCMClassMock([GMSCameraUpdate class]); [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValue]; [[classMockCameraUpdate expect] setCamera:[FLTGoogleMapJSONConversions cameraPostionFromDictionary:channelValue[1]]]; [classMockCameraUpdate stopMocking]; } // TODO(cyanglaz): Fix the test for CameraUpdateFromChannelValue with the "NewLatlng" key. // 2 approaches have been tried and neither worked for the tests. // // 1. Use OCMock to vefiry that [GMSCameraUpdate setTarget:] is triggered with the correct value. // This class method conflicts with certain category method in OCMock, causing OCMock not able to // disambigious them. // // 2. Directly verify the GMSCameraUpdate object returned by the method. // The GMSCameraUpdate object returned from the method doesn't have any accessors to the "target" // property. It can be used to update the "camera" property in GMSMapView. However, [GMSMapView // moveCamera:] doesn't update the camera immediately. Thus the GMSCameraUpdate object cannot be // verified. // // The code in below test uses the 2nd approach. - (void)skip_testCameraUpdateFromChannelValueNewLatLong { NSArray *channelValue = @[ @"newLatLng", @[ @1, @2 ] ]; GMSCameraUpdate *update = [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValue]; GMSMapView *mapView = [[GMSMapView alloc] initWithFrame:CGRectZero camera:[GMSCameraPosition cameraWithTarget:CLLocationCoordinate2DMake(5, 6) zoom:1]]; [mapView moveCamera:update]; const CGFloat accuracy = 0.001; XCTAssertEqualWithAccuracy(mapView.camera.target.latitude, 1, accuracy); // mapView.camera.target.latitude is still 5. XCTAssertEqualWithAccuracy(mapView.camera.target.longitude, 2, accuracy); // mapView.camera.target.longitude is still 6. } - (void)testCameraUpdateFromChannelValueNewLatLngBounds { NSArray<NSNumber *> *latlong1 = @[ @1, @2 ]; NSArray<NSNumber *> *latlong2 = @[ @(3), @(4) ]; GMSCoordinateBounds *bounds = [FLTGoogleMapJSONConversions coordinateBoundsFromLatLongs:@[ latlong1, latlong2 ]]; NSArray *channelValue = @[ @"newLatLngBounds", @[ latlong1, latlong2 ], @20 ]; id classMockCameraUpdate = OCMClassMock([GMSCameraUpdate class]); [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValue]; [[classMockCameraUpdate expect] fitBounds:bounds withPadding:20]; [classMockCameraUpdate stopMocking]; } - (void)testCameraUpdateFromChannelValueNewLatLngZoom { NSArray *channelValue = @[ @"newLatLngZoom", @[ @1, @2 ], @3 ]; id classMockCameraUpdate = OCMClassMock([GMSCameraUpdate class]); [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValue]; [[classMockCameraUpdate expect] setTarget:CLLocationCoordinate2DMake(1, 2) zoom:3]; [classMockCameraUpdate stopMocking]; } - (void)testCameraUpdateFromChannelValueScrollBy { NSArray *channelValue = @[ @"scrollBy", @1, @2 ]; id classMockCameraUpdate = OCMClassMock([GMSCameraUpdate class]); [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValue]; [[classMockCameraUpdate expect] scrollByX:1 Y:2]; [classMockCameraUpdate stopMocking]; } - (void)testCameraUpdateFromChannelValueZoomBy { NSArray *channelValueNoPoint = @[ @"zoomBy", @1 ]; id classMockCameraUpdate = OCMClassMock([GMSCameraUpdate class]); [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValueNoPoint]; [[classMockCameraUpdate expect] zoomBy:1]; NSArray *channelValueWithPoint = @[ @"zoomBy", @1, @[ @2, @3 ] ]; [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValueWithPoint]; [[classMockCameraUpdate expect] zoomBy:1 atPoint:CGPointMake(2, 3)]; [classMockCameraUpdate stopMocking]; } - (void)testCameraUpdateFromChannelValueZoomIn { NSArray *channelValueNoPoint = @[ @"zoomIn" ]; id classMockCameraUpdate = OCMClassMock([GMSCameraUpdate class]); [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValueNoPoint]; [[classMockCameraUpdate expect] zoomIn]; [classMockCameraUpdate stopMocking]; } - (void)testCameraUpdateFromChannelValueZoomOut { NSArray *channelValueNoPoint = @[ @"zoomOut" ]; id classMockCameraUpdate = OCMClassMock([GMSCameraUpdate class]); [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValueNoPoint]; [[classMockCameraUpdate expect] zoomOut]; [classMockCameraUpdate stopMocking]; } - (void)testCameraUpdateFromChannelValueZoomTo { NSArray *channelValueNoPoint = @[ @"zoomTo", @1 ]; id classMockCameraUpdate = OCMClassMock([GMSCameraUpdate class]); [FLTGoogleMapJSONConversions cameraUpdateFromChannelValue:channelValueNoPoint]; [[classMockCameraUpdate expect] zoomTo:1]; [classMockCameraUpdate stopMocking]; } @end
plugins/packages/google_maps_flutter/google_maps_flutter_ios/example/ios/RunnerTests/FLTGoogleMapJSONConversionsConversionTests.m/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/example/ios/RunnerTests/FLTGoogleMapJSONConversionsConversionTests.m", "repo_id": "plugins", "token_count": 4271 }
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. #import <Flutter/Flutter.h> #import <GoogleMaps/GoogleMaps.h> #import "GoogleMapCircleController.h" #import "GoogleMapController.h" #import "GoogleMapMarkerController.h" #import "GoogleMapPolygonController.h" #import "GoogleMapPolylineController.h" NS_ASSUME_NONNULL_BEGIN @interface FLTGoogleMapsPlugin : NSObject <FlutterPlugin> @end NS_ASSUME_NONNULL_END
plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapsPlugin.h/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapsPlugin.h", "repo_id": "plugins", "token_count": 169 }
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. import 'dart:ui' show Offset; import 'package:flutter/foundation.dart'; import 'types.dart'; /// The position of the map "camera", the view point from which the world is shown in the map view. /// /// Aggregates the camera's [target] geographical location, its [zoom] level, /// [tilt] angle, and [bearing]. @immutable class CameraPosition { /// Creates a immutable representation of the [GoogleMap] camera. /// /// [AssertionError] is thrown if [bearing], [target], [tilt], or [zoom] are /// null. const CameraPosition({ this.bearing = 0.0, required this.target, this.tilt = 0.0, this.zoom = 0.0, }) : assert(bearing != null), assert(target != null), assert(tilt != null), assert(zoom != null); /// The camera's bearing in degrees, measured clockwise from north. /// /// A bearing of 0.0, the default, means the camera points north. /// A bearing of 90.0 means the camera points east. final double bearing; /// The geographical location that the camera is pointing at. final LatLng target; /// The angle, in degrees, of the camera angle from the nadir. /// /// A tilt of 0.0, the default and minimum supported value, means the camera /// is directly facing the Earth. /// /// The maximum tilt value depends on the current zoom level. Values beyond /// the supported range are allowed, but on applying them to a map they will /// be silently clamped to the supported range. final double tilt; /// The zoom level of the camera. /// /// A zoom of 0.0, the default, means the screen width of the world is 256. /// Adding 1.0 to the zoom level doubles the screen width of the map. So at /// zoom level 3.0, the screen width of the world is 2³x256=2048. /// /// Larger zoom levels thus means the camera is placed closer to the surface /// of the Earth, revealing more detail in a narrower geographical region. /// /// The supported zoom level range depends on the map data and device. Values /// beyond the supported range are allowed, but on applying them to a map they /// will be silently clamped to the supported range. final double zoom; /// Serializes [CameraPosition]. /// /// Mainly for internal use when calling [CameraUpdate.newCameraPosition]. Object toMap() => <String, Object>{ 'bearing': bearing, 'target': target.toJson(), 'tilt': tilt, 'zoom': zoom, }; /// Deserializes [CameraPosition] from a map. /// /// Mainly for internal use. static CameraPosition? fromMap(Object? json) { if (json == null || json is! Map<dynamic, dynamic>) { return null; } final LatLng? target = LatLng.fromJson(json['target']); if (target == null) { return null; } return CameraPosition( bearing: json['bearing'] as double, target: target, tilt: json['tilt'] as double, zoom: json['zoom'] as double, ); } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (runtimeType != other.runtimeType) { return false; } return other is CameraPosition && bearing == other.bearing && target == other.target && tilt == other.tilt && zoom == other.zoom; } @override int get hashCode => Object.hash(bearing, target, tilt, zoom); @override String toString() => 'CameraPosition(bearing: $bearing, target: $target, tilt: $tilt, zoom: $zoom)'; } /// Defines a camera move, supporting absolute moves as well as moves relative /// the current position. class CameraUpdate { const CameraUpdate._(this._json); /// Returns a camera update that moves the camera to the specified position. static CameraUpdate newCameraPosition(CameraPosition cameraPosition) { return CameraUpdate._( <Object>['newCameraPosition', cameraPosition.toMap()], ); } /// Returns a camera update that moves the camera target to the specified /// geographical location. static CameraUpdate newLatLng(LatLng latLng) { return CameraUpdate._(<Object>['newLatLng', latLng.toJson()]); } /// Returns a camera update that transforms the camera so that the specified /// geographical bounding box is centered in the map view at the greatest /// possible zoom level. A non-zero [padding] insets the bounding box from the /// map view's edges. The camera's new tilt and bearing will both be 0.0. static CameraUpdate newLatLngBounds(LatLngBounds bounds, double padding) { return CameraUpdate._(<Object>[ 'newLatLngBounds', bounds.toJson(), padding, ]); } /// Returns a camera update that moves the camera target to the specified /// geographical location and zoom level. static CameraUpdate newLatLngZoom(LatLng latLng, double zoom) { return CameraUpdate._( <Object>['newLatLngZoom', latLng.toJson(), zoom], ); } /// Returns a camera update that moves the camera target the specified screen /// distance. /// /// For a camera with bearing 0.0 (pointing north), scrolling by 50,75 moves /// the camera's target to a geographical location that is 50 to the east and /// 75 to the south of the current location, measured in screen coordinates. static CameraUpdate scrollBy(double dx, double dy) { return CameraUpdate._( <Object>['scrollBy', dx, dy], ); } /// Returns a camera update that modifies the camera zoom level by the /// specified amount. The optional [focus] is a screen point whose underlying /// geographical location should be invariant, if possible, by the movement. static CameraUpdate zoomBy(double amount, [Offset? focus]) { if (focus == null) { return CameraUpdate._(<Object>['zoomBy', amount]); } else { return CameraUpdate._(<Object>[ 'zoomBy', amount, <double>[focus.dx, focus.dy], ]); } } /// Returns a camera update that zooms the camera in, bringing the camera /// closer to the surface of the Earth. /// /// Equivalent to the result of calling `zoomBy(1.0)`. static CameraUpdate zoomIn() { return const CameraUpdate._(<Object>['zoomIn']); } /// Returns a camera update that zooms the camera out, bringing the camera /// further away from the surface of the Earth. /// /// Equivalent to the result of calling `zoomBy(-1.0)`. static CameraUpdate zoomOut() { return const CameraUpdate._(<Object>['zoomOut']); } /// Returns a camera update that sets the camera zoom level. static CameraUpdate zoomTo(double zoom) { return CameraUpdate._(<Object>['zoomTo', zoom]); } 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/camera.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart", "repo_id": "plugins", "token_count": 2161 }
1,248
name: google_maps_flutter_platform_interface description: A common platform interface for the google_maps_flutter plugin. repository: https://github.com/flutter/plugins/tree/main/packages/google_maps_flutter/google_maps_flutter_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%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.2.5 environment: sdk: '>=2.12.0 <3.0.0' flutter: ">=3.0.0" dependencies: collection: ^1.15.0 flutter: sdk: flutter plugin_platform_interface: ^2.1.0 stream_transform: ^2.0.0 dev_dependencies: async: ^2.5.0 flutter_test: sdk: flutter mockito: ^5.0.0
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/pubspec.yaml/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/pubspec.yaml", "repo_id": "plugins", "token_count": 304 }
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. part of google_maps_flutter_web; /// The `PolygonController` class wraps a [gmaps.Polyline] and its `onTap` behavior. class PolylineController { /// Creates a `PolylineController` that wraps a [gmaps.Polyline] object and its `onTap` behavior. PolylineController({ required gmaps.Polyline polyline, bool consumeTapEvents = false, ui.VoidCallback? onTap, }) : _polyline = polyline, _consumeTapEvents = consumeTapEvents { if (onTap != null) { polyline.onClick.listen((gmaps.PolyMouseEvent event) { onTap.call(); }); } } gmaps.Polyline? _polyline; final bool _consumeTapEvents; /// Returns the wrapped [gmaps.Polyline]. Only used for testing. @visibleForTesting gmaps.Polyline? get line => _polyline; /// Returns `true` if this Controller will use its own `onTap` handler to consume events. bool get consumeTapEvents => _consumeTapEvents; /// Updates the options of the wrapped [gmaps.Polyline] object. /// /// This cannot be called after [remove]. void update(gmaps.PolylineOptions options) { assert( _polyline != null, 'Cannot `update` Polyline after calling `remove`.'); _polyline!.options = options; } /// Disposes of the currently wrapped [gmaps.Polyline]. void remove() { if (_polyline != null) { _polyline!.visible = false; _polyline!.map = null; _polyline = null; } } }
plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polyline.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polyline.dart", "repo_id": "plugins", "token_count": 533 }
1,250
# google_sign_in_example Demonstrates how to use the google_sign_in plugin.
plugins/packages/google_sign_in/google_sign_in/example/README.md/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in/example/README.md", "repo_id": "plugins", "token_count": 25 }
1,251
// 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 static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; 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.Intent; import android.content.res.Resources; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.common.api.Status; import com.google.android.gms.tasks.Task; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.PluginRegistry; import java.util.Collections; import java.util.HashMap; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; public class GoogleSignInTest { @Mock Context mockContext; @Mock Resources mockResources; @Mock Activity mockActivity; @Mock PluginRegistry.Registrar mockRegistrar; @Mock BinaryMessenger mockMessenger; @Spy MethodChannel.Result result; @Mock GoogleSignInWrapper mockGoogleSignIn; @Mock GoogleSignInAccount account; @Mock GoogleSignInClient mockClient; @Mock Task<GoogleSignInAccount> mockSignInTask; private GoogleSignInPlugin plugin; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(mockRegistrar.messenger()).thenReturn(mockMessenger); when(mockRegistrar.context()).thenReturn(mockContext); when(mockRegistrar.activity()).thenReturn(mockActivity); when(mockContext.getResources()).thenReturn(mockResources); plugin = new GoogleSignInPlugin(); plugin.initInstance(mockRegistrar.messenger(), mockRegistrar.context(), mockGoogleSignIn); plugin.setUpRegistrar(mockRegistrar); } @Test public void requestScopes_ResultErrorIfAccountIsNull() { MethodCall methodCall = new MethodCall("requestScopes", null); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(null); plugin.onMethodCall(methodCall, result); verify(result).error("sign_in_required", "No account to grant scopes.", null); } @Test public void requestScopes_ResultTrueIfAlreadyGranted() { HashMap<String, List<String>> arguments = new HashMap<>(); arguments.put("scopes", Collections.singletonList("requestedScope")); MethodCall methodCall = new MethodCall("requestScopes", arguments); Scope requestedScope = new Scope("requestedScope"); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(true); plugin.onMethodCall(methodCall, result); verify(result).success(true); } @Test public void requestScopes_RequestsPermissionIfNotGranted() { HashMap<String, List<String>> arguments = new HashMap<>(); arguments.put("scopes", Collections.singletonList("requestedScope")); MethodCall methodCall = new MethodCall("requestScopes", arguments); Scope requestedScope = new Scope("requestedScope"); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(false); plugin.onMethodCall(methodCall, result); verify(mockGoogleSignIn) .requestPermissions(mockActivity, 53295, account, new Scope[] {requestedScope}); } @Test public void requestScopes_ReturnsFalseIfPermissionDenied() { HashMap<String, List<String>> arguments = new HashMap<>(); arguments.put("scopes", Collections.singletonList("requestedScope")); MethodCall methodCall = new MethodCall("requestScopes", arguments); Scope requestedScope = new Scope("requestedScope"); ArgumentCaptor<PluginRegistry.ActivityResultListener> captor = ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class); verify(mockRegistrar).addActivityResultListener(captor.capture()); PluginRegistry.ActivityResultListener listener = captor.getValue(); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(false); plugin.onMethodCall(methodCall, result); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_CANCELED, new Intent()); verify(result).success(false); } @Test public void requestScopes_ReturnsTrueIfPermissionGranted() { HashMap<String, List<String>> arguments = new HashMap<>(); arguments.put("scopes", Collections.singletonList("requestedScope")); MethodCall methodCall = new MethodCall("requestScopes", arguments); Scope requestedScope = new Scope("requestedScope"); ArgumentCaptor<PluginRegistry.ActivityResultListener> captor = ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class); verify(mockRegistrar).addActivityResultListener(captor.capture()); PluginRegistry.ActivityResultListener listener = captor.getValue(); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(false); plugin.onMethodCall(methodCall, result); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); verify(result).success(true); } @Test public void requestScopes_mayBeCalledRepeatedly_ifAlreadyGranted() { HashMap<String, List<String>> arguments = new HashMap<>(); arguments.put("scopes", Collections.singletonList("requestedScope")); MethodCall methodCall = new MethodCall("requestScopes", arguments); Scope requestedScope = new Scope("requestedScope"); ArgumentCaptor<PluginRegistry.ActivityResultListener> captor = ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class); verify(mockRegistrar).addActivityResultListener(captor.capture()); PluginRegistry.ActivityResultListener listener = captor.getValue(); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(account); when(account.getGrantedScopes()).thenReturn(Collections.singleton(requestedScope)); when(mockGoogleSignIn.hasPermissions(account, requestedScope)).thenReturn(false); plugin.onMethodCall(methodCall, result); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); plugin.onMethodCall(methodCall, result); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); verify(result, times(2)).success(true); } @Test public void requestScopes_mayBeCalledRepeatedly_ifNotSignedIn() { HashMap<String, List<String>> arguments = new HashMap<>(); arguments.put("scopes", Collections.singletonList("requestedScope")); MethodCall methodCall = new MethodCall("requestScopes", arguments); Scope requestedScope = new Scope("requestedScope"); ArgumentCaptor<PluginRegistry.ActivityResultListener> captor = ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class); verify(mockRegistrar).addActivityResultListener(captor.capture()); PluginRegistry.ActivityResultListener listener = captor.getValue(); when(mockGoogleSignIn.getLastSignedInAccount(mockContext)).thenReturn(null); plugin.onMethodCall(methodCall, result); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); plugin.onMethodCall(methodCall, result); listener.onActivityResult( GoogleSignInPlugin.Delegate.REQUEST_CODE_REQUEST_SCOPE, Activity.RESULT_OK, new Intent()); verify(result, times(2)).error("sign_in_required", "No account to grant scopes.", null); } @Test(expected = IllegalStateException.class) public void signInThrowsWithoutActivity() { final GoogleSignInPlugin plugin = new GoogleSignInPlugin(); plugin.initInstance( mock(BinaryMessenger.class), mock(Context.class), mock(GoogleSignInWrapper.class)); plugin.onMethodCall(new MethodCall("signIn", null), null); } @Test public void signInSilentlyThatImmediatelyCompletesWithoutResultFinishesWithError() throws ApiException { final String clientId = "fakeClientId"; MethodCall methodCall = buildInitMethodCall(clientId, null); initAndAssertServerClientId(methodCall, clientId); ApiException exception = new ApiException(new Status(CommonStatusCodes.SIGN_IN_REQUIRED, "Error text")); when(mockClient.silentSignIn()).thenReturn(mockSignInTask); when(mockSignInTask.isComplete()).thenReturn(true); when(mockSignInTask.getResult(ApiException.class)).thenThrow(exception); plugin.onMethodCall(new MethodCall("signInSilently", null), result); verify(result) .error( "sign_in_required", "com.google.android.gms.common.api.ApiException: 4: Error text", null); } @Test public void init_LoadsServerClientIdFromResources() { final String packageName = "fakePackageName"; final String serverClientId = "fakeServerClientId"; final int resourceId = 1; MethodCall methodCall = buildInitMethodCall(null, null); when(mockContext.getPackageName()).thenReturn(packageName); when(mockResources.getIdentifier("default_web_client_id", "string", packageName)) .thenReturn(resourceId); when(mockContext.getString(resourceId)).thenReturn(serverClientId); initAndAssertServerClientId(methodCall, serverClientId); } @Test public void init_InterpretsClientIdAsServerClientId() { final String clientId = "fakeClientId"; MethodCall methodCall = buildInitMethodCall(clientId, null); initAndAssertServerClientId(methodCall, clientId); } @Test public void init_ForwardsServerClientId() { final String serverClientId = "fakeServerClientId"; MethodCall methodCall = buildInitMethodCall(null, serverClientId); initAndAssertServerClientId(methodCall, serverClientId); } @Test public void init_IgnoresClientIdIfServerClientIdIsProvided() { final String clientId = "fakeClientId"; final String serverClientId = "fakeServerClientId"; MethodCall methodCall = buildInitMethodCall(clientId, serverClientId); initAndAssertServerClientId(methodCall, serverClientId); } @Test public void init_PassesForceCodeForRefreshTokenFalseWithServerClientIdParameter() { MethodCall methodCall = buildInitMethodCall("fakeClientId", "fakeServerClientId", false); initAndAssertForceCodeForRefreshToken(methodCall, false); } @Test public void init_PassesForceCodeForRefreshTokenTrueWithServerClientIdParameter() { MethodCall methodCall = buildInitMethodCall("fakeClientId", "fakeServerClientId", true); initAndAssertForceCodeForRefreshToken(methodCall, true); } @Test public void init_PassesForceCodeForRefreshTokenFalseWithServerClientIdFromResources() { final String packageName = "fakePackageName"; final String serverClientId = "fakeServerClientId"; final int resourceId = 1; MethodCall methodCall = buildInitMethodCall(null, null, false); when(mockContext.getPackageName()).thenReturn(packageName); when(mockResources.getIdentifier("default_web_client_id", "string", packageName)) .thenReturn(resourceId); when(mockContext.getString(resourceId)).thenReturn(serverClientId); initAndAssertForceCodeForRefreshToken(methodCall, false); } @Test public void init_PassesForceCodeForRefreshTokenTrueWithServerClientIdFromResources() { final String packageName = "fakePackageName"; final String serverClientId = "fakeServerClientId"; final int resourceId = 1; MethodCall methodCall = buildInitMethodCall(null, null, true); when(mockContext.getPackageName()).thenReturn(packageName); when(mockResources.getIdentifier("default_web_client_id", "string", packageName)) .thenReturn(resourceId); when(mockContext.getString(resourceId)).thenReturn(serverClientId); initAndAssertForceCodeForRefreshToken(methodCall, true); } public void initAndAssertServerClientId(MethodCall methodCall, String serverClientId) { ArgumentCaptor<GoogleSignInOptions> optionsCaptor = ArgumentCaptor.forClass(GoogleSignInOptions.class); when(mockGoogleSignIn.getClient(any(Context.class), optionsCaptor.capture())) .thenReturn(mockClient); plugin.onMethodCall(methodCall, result); verify(result).success(null); Assert.assertEquals(serverClientId, optionsCaptor.getValue().getServerClientId()); } public void initAndAssertForceCodeForRefreshToken( MethodCall methodCall, boolean forceCodeForRefreshToken) { ArgumentCaptor<GoogleSignInOptions> optionsCaptor = ArgumentCaptor.forClass(GoogleSignInOptions.class); when(mockGoogleSignIn.getClient(any(Context.class), optionsCaptor.capture())) .thenReturn(mockClient); plugin.onMethodCall(methodCall, result); verify(result).success(null); Assert.assertEquals( forceCodeForRefreshToken, optionsCaptor.getValue().isForceCodeForRefreshToken()); } private static MethodCall buildInitMethodCall(String clientId, String serverClientId) { return buildInitMethodCall( "SignInOption.standard", Collections.<String>emptyList(), clientId, serverClientId, false); } private static MethodCall buildInitMethodCall( String clientId, String serverClientId, boolean forceCodeForRefreshToken) { return buildInitMethodCall( "SignInOption.standard", Collections.<String>emptyList(), clientId, serverClientId, forceCodeForRefreshToken); } private static MethodCall buildInitMethodCall( String signInOption, List<String> scopes, String clientId, String serverClientId, boolean forceCodeForRefreshToken) { HashMap<String, Object> arguments = new HashMap<>(); arguments.put("signInOption", signInOption); arguments.put("scopes", scopes); if (clientId != null) { arguments.put("clientId", clientId); } if (serverClientId != null) { arguments.put("serverClientId", serverClientId); } arguments.put("forceCodeForRefreshToken", forceCodeForRefreshToken); return new MethodCall("init", arguments); } }
plugins/packages/google_sign_in/google_sign_in_android/android/src/test/java/io/flutter/plugins/googlesignin/GoogleSignInTest.java/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_android/android/src/test/java/io/flutter/plugins/googlesignin/GoogleSignInTest.java", "repo_id": "plugins", "token_count": 5039 }
1,252
name: google_sign_in_web_integration_tests publish_to: none environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter google_sign_in_web: path: ../ dev_dependencies: build_runner: ^2.1.1 flutter_driver: sdk: flutter flutter_test: sdk: flutter google_identity_services_web: ^0.2.0 google_sign_in_platform_interface: ^2.2.0 http: ^0.13.0 integration_test: sdk: flutter js: ^0.6.3 mockito: ^5.3.2
plugins/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_web/example/pubspec.yaml", "repo_id": "plugins", "token_count": 229 }
1,253
# image_picker_example Demonstrates how to use the image_picker plugin.
plugins/packages/image_picker/image_picker/example/README.md/0
{ "file_path": "plugins/packages/image_picker/image_picker/example/README.md", "repo_id": "plugins", "token_count": 23 }
1,254
{ "name": "image_picker example", "short_name": "image_picker", "start_url": ".", "display": "minimal-ui", "background_color": "#0175C2", "theme_color": "#0175C2", "description": "An example of the image_picker on the web.", "orientation": "portrait-primary", "prefer_related_applications": false, "icons": [ { "src": "icons/Icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/Icon-512.png", "sizes": "512x512", "type": "image/png" } ] }
plugins/packages/image_picker/image_picker/example/web/manifest.json/0
{ "file_path": "plugins/packages/image_picker/image_picker/example/web/manifest.json", "repo_id": "plugins", "token_count": 316 }
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. package io.flutter.plugins.imagepicker; import android.Manifest; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.hardware.camera2.CameraCharacteristics; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.core.app.ActivityCompat; import androidx.core.content.FileProvider; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.PluginRegistry; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; enum CameraDevice { REAR, FRONT } /** * A delegate class doing the heavy lifting for the plugin. * * <p>When invoked, both the {@link #chooseImageFromGallery} and {@link #takeImageWithCamera} * methods go through the same steps: * * <p>1. Check for an existing {@link #pendingResult}. If a previous pendingResult exists, this * means that the chooseImageFromGallery() or takeImageWithCamera() method was called at least * twice. In this case, stop executing and finish with an error. * * <p>2. Check that a required runtime permission has been granted. The takeImageWithCamera() method * checks that {@link Manifest.permission#CAMERA} has been granted. * * <p>The permission check can end up in two different outcomes: * * <p>A) If the permission has already been granted, continue with picking the image from gallery or * camera. * * <p>B) If the permission hasn't already been granted, ask for the permission from the user. If the * user grants the permission, proceed with step #3. If the user denies the permission, stop doing * anything else and finish with a null result. * * <p>3. Launch the gallery or camera for picking the image, depending on whether * chooseImageFromGallery() or takeImageWithCamera() was called. * * <p>This can end up in three different outcomes: * * <p>A) User picks an image. No maxWidth or maxHeight was specified when calling {@code * pickImage()} method in the Dart side of this plugin. Finish with full path for the picked image * as the result. * * <p>B) User picks an image. A maxWidth and/or maxHeight was provided when calling {@code * pickImage()} method in the Dart side of this plugin. A scaled copy of the image is created. * Finish with full path for the scaled image as the result. * * <p>C) User cancels picking an image. Finish with null result. */ public class ImagePickerDelegate implements PluginRegistry.ActivityResultListener, PluginRegistry.RequestPermissionsResultListener { @VisibleForTesting static final int REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY = 2342; @VisibleForTesting static final int REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA = 2343; @VisibleForTesting static final int REQUEST_CAMERA_IMAGE_PERMISSION = 2345; @VisibleForTesting static final int REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY = 2346; @VisibleForTesting static final int REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY = 2352; @VisibleForTesting static final int REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA = 2353; @VisibleForTesting static final int REQUEST_CAMERA_VIDEO_PERMISSION = 2355; @VisibleForTesting final String fileProviderName; private final Activity activity; @VisibleForTesting final File externalFilesDirectory; private final ImageResizer imageResizer; private final ImagePickerCache cache; private final PermissionManager permissionManager; private final FileUriResolver fileUriResolver; private final FileUtils fileUtils; private CameraDevice cameraDevice; interface PermissionManager { boolean isPermissionGranted(String permissionName); void askForPermission(String permissionName, int requestCode); boolean needRequestCameraPermission(); } interface FileUriResolver { Uri resolveFileProviderUriForFile(String fileProviderName, File imageFile); void getFullImagePath(Uri imageUri, OnPathReadyListener listener); } interface OnPathReadyListener { void onPathReady(String path); } private Uri pendingCameraMediaUri; private MethodChannel.Result pendingResult; private MethodCall methodCall; public ImagePickerDelegate( final Activity activity, final File externalFilesDirectory, final ImageResizer imageResizer, final ImagePickerCache cache) { this( activity, externalFilesDirectory, imageResizer, null, null, cache, new PermissionManager() { @Override public boolean isPermissionGranted(String permissionName) { return ActivityCompat.checkSelfPermission(activity, permissionName) == PackageManager.PERMISSION_GRANTED; } @Override public void askForPermission(String permissionName, int requestCode) { ActivityCompat.requestPermissions(activity, new String[] {permissionName}, requestCode); } @Override public boolean needRequestCameraPermission() { return ImagePickerUtils.needRequestCameraPermission(activity); } }, new FileUriResolver() { @Override public Uri resolveFileProviderUriForFile(String fileProviderName, File file) { return FileProvider.getUriForFile(activity, fileProviderName, file); } @Override public void getFullImagePath(final Uri imageUri, final OnPathReadyListener listener) { MediaScannerConnection.scanFile( activity, new String[] {(imageUri != null) ? imageUri.getPath() : ""}, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { listener.onPathReady(path); } }); } }, new FileUtils()); } /** * This constructor is used exclusively for testing; it can be used to provide mocks to final * fields of this class. Otherwise those fields would have to be mutable and visible. */ @VisibleForTesting ImagePickerDelegate( final Activity activity, final File externalFilesDirectory, final ImageResizer imageResizer, final MethodChannel.Result result, final MethodCall methodCall, final ImagePickerCache cache, final PermissionManager permissionManager, final FileUriResolver fileUriResolver, final FileUtils fileUtils) { this.activity = activity; this.externalFilesDirectory = externalFilesDirectory; this.imageResizer = imageResizer; this.fileProviderName = activity.getPackageName() + ".flutter.image_provider"; this.pendingResult = result; this.methodCall = methodCall; this.permissionManager = permissionManager; this.fileUriResolver = fileUriResolver; this.fileUtils = fileUtils; this.cache = cache; } void setCameraDevice(CameraDevice device) { cameraDevice = device; } CameraDevice getCameraDevice() { return cameraDevice; } // Save the state of the image picker so it can be retrieved with `retrieveLostImage`. void saveStateBeforeResult() { if (methodCall == null) { return; } cache.saveTypeWithMethodCallName(methodCall.method); cache.saveDimensionWithMethodCall(methodCall); if (pendingCameraMediaUri != null) { cache.savePendingCameraMediaUriPath(pendingCameraMediaUri); } } void retrieveLostImage(MethodChannel.Result result) { Map<String, Object> resultMap = cache.getCacheMap(); @SuppressWarnings("unchecked") ArrayList<String> pathList = (ArrayList<String>) resultMap.get(cache.MAP_KEY_PATH_LIST); ArrayList<String> newPathList = new ArrayList<>(); if (pathList != null) { for (String path : pathList) { Double maxWidth = (Double) resultMap.get(cache.MAP_KEY_MAX_WIDTH); Double maxHeight = (Double) resultMap.get(cache.MAP_KEY_MAX_HEIGHT); int imageQuality = resultMap.get(cache.MAP_KEY_IMAGE_QUALITY) == null ? 100 : (int) resultMap.get(cache.MAP_KEY_IMAGE_QUALITY); newPathList.add(imageResizer.resizeImageIfNeeded(path, maxWidth, maxHeight, imageQuality)); } resultMap.put(cache.MAP_KEY_PATH_LIST, newPathList); resultMap.put(cache.MAP_KEY_PATH, newPathList.get(newPathList.size() - 1)); } if (resultMap.isEmpty()) { result.success(null); } else { result.success(resultMap); } cache.clear(); } public void chooseVideoFromGallery(MethodCall methodCall, MethodChannel.Result result) { if (!setPendingMethodCallAndResult(methodCall, result)) { finishWithAlreadyActiveError(result); return; } launchPickVideoFromGalleryIntent(); } private void launchPickVideoFromGalleryIntent() { Intent pickVideoIntent = new Intent(Intent.ACTION_GET_CONTENT); pickVideoIntent.setType("video/*"); activity.startActivityForResult(pickVideoIntent, REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY); } public void takeVideoWithCamera(MethodCall methodCall, MethodChannel.Result result) { if (!setPendingMethodCallAndResult(methodCall, result)) { finishWithAlreadyActiveError(result); return; } if (needRequestCameraPermission() && !permissionManager.isPermissionGranted(Manifest.permission.CAMERA)) { permissionManager.askForPermission( Manifest.permission.CAMERA, REQUEST_CAMERA_VIDEO_PERMISSION); return; } launchTakeVideoWithCameraIntent(); } private void launchTakeVideoWithCameraIntent() { Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); if (this.methodCall != null && this.methodCall.argument("maxDuration") != null) { int maxSeconds = this.methodCall.argument("maxDuration"); intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, maxSeconds); } if (cameraDevice == CameraDevice.FRONT) { useFrontCamera(intent); } File videoFile = createTemporaryWritableVideoFile(); pendingCameraMediaUri = Uri.parse("file:" + videoFile.getAbsolutePath()); Uri videoUri = fileUriResolver.resolveFileProviderUriForFile(fileProviderName, videoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri); grantUriPermissions(intent, videoUri); try { activity.startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA); } catch (ActivityNotFoundException e) { try { // If we can't delete the file again here, there's not really anything we can do about it. //noinspection ResultOfMethodCallIgnored videoFile.delete(); } catch (SecurityException exception) { exception.printStackTrace(); } finishWithError("no_available_camera", "No cameras available for taking pictures."); } } public void chooseImageFromGallery(MethodCall methodCall, MethodChannel.Result result) { if (!setPendingMethodCallAndResult(methodCall, result)) { finishWithAlreadyActiveError(result); return; } launchPickImageFromGalleryIntent(); } public void chooseMultiImageFromGallery(MethodCall methodCall, MethodChannel.Result result) { if (!setPendingMethodCallAndResult(methodCall, result)) { finishWithAlreadyActiveError(result); return; } launchMultiPickImageFromGalleryIntent(); } private void launchPickImageFromGalleryIntent() { Intent pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT); pickImageIntent.setType("image/*"); activity.startActivityForResult(pickImageIntent, REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY); } private void launchMultiPickImageFromGalleryIntent() { Intent pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { pickImageIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } pickImageIntent.setType("image/*"); activity.startActivityForResult(pickImageIntent, REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY); } public void takeImageWithCamera(MethodCall methodCall, MethodChannel.Result result) { if (!setPendingMethodCallAndResult(methodCall, result)) { finishWithAlreadyActiveError(result); return; } if (needRequestCameraPermission() && !permissionManager.isPermissionGranted(Manifest.permission.CAMERA)) { permissionManager.askForPermission( Manifest.permission.CAMERA, REQUEST_CAMERA_IMAGE_PERMISSION); return; } launchTakeImageWithCameraIntent(); } private boolean needRequestCameraPermission() { if (permissionManager == null) { return false; } return permissionManager.needRequestCameraPermission(); } private void launchTakeImageWithCameraIntent() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraDevice == CameraDevice.FRONT) { useFrontCamera(intent); } File imageFile = createTemporaryWritableImageFile(); pendingCameraMediaUri = Uri.parse("file:" + imageFile.getAbsolutePath()); Uri imageUri = fileUriResolver.resolveFileProviderUriForFile(fileProviderName, imageFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); grantUriPermissions(intent, imageUri); try { activity.startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA); } catch (ActivityNotFoundException e) { try { // If we can't delete the file again here, there's not really anything we can do about it. //noinspection ResultOfMethodCallIgnored imageFile.delete(); } catch (SecurityException exception) { exception.printStackTrace(); } finishWithError("no_available_camera", "No cameras available for taking pictures."); } } private File createTemporaryWritableImageFile() { return createTemporaryWritableFile(".jpg"); } private File createTemporaryWritableVideoFile() { return createTemporaryWritableFile(".mp4"); } private File createTemporaryWritableFile(String suffix) { String filename = UUID.randomUUID().toString(); File image; try { externalFilesDirectory.mkdirs(); image = File.createTempFile(filename, suffix, externalFilesDirectory); } catch (IOException e) { throw new RuntimeException(e); } return image; } private void grantUriPermissions(Intent intent, Uri imageUri) { PackageManager packageManager = activity.getPackageManager(); List<ResolveInfo> compatibleActivities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : compatibleActivities) { activity.grantUriPermission( info.activityInfo.packageName, imageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } } @Override public boolean onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults) { boolean permissionGranted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED; switch (requestCode) { case REQUEST_CAMERA_IMAGE_PERMISSION: if (permissionGranted) { launchTakeImageWithCameraIntent(); } break; case REQUEST_CAMERA_VIDEO_PERMISSION: if (permissionGranted) { launchTakeVideoWithCameraIntent(); } break; default: return false; } if (!permissionGranted) { switch (requestCode) { case REQUEST_CAMERA_IMAGE_PERMISSION: case REQUEST_CAMERA_VIDEO_PERMISSION: finishWithError("camera_access_denied", "The user did not allow camera access."); break; } } return true; } @Override public boolean onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY: handleChooseImageResult(resultCode, data); break; case REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY: handleChooseMultiImageResult(resultCode, data); break; case REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA: handleCaptureImageResult(resultCode); break; case REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY: handleChooseVideoResult(resultCode, data); break; case REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA: handleCaptureVideoResult(resultCode); break; default: return false; } return true; } private void handleChooseImageResult(int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && data != null) { String path = fileUtils.getPathFromUri(activity, data.getData()); handleImageResult(path, false); return; } // User cancelled choosing a picture. finishWithSuccess(null); } private void handleChooseMultiImageResult(int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK && intent != null) { ArrayList<String> paths = new ArrayList<>(); if (intent.getClipData() != null) { for (int i = 0; i < intent.getClipData().getItemCount(); i++) { paths.add(fileUtils.getPathFromUri(activity, intent.getClipData().getItemAt(i).getUri())); } } else { paths.add(fileUtils.getPathFromUri(activity, intent.getData())); } handleMultiImageResult(paths, false); return; } // User cancelled choosing a picture. finishWithSuccess(null); } private void handleChooseVideoResult(int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && data != null) { String path = fileUtils.getPathFromUri(activity, data.getData()); handleVideoResult(path); return; } // User cancelled choosing a picture. finishWithSuccess(null); } private void handleCaptureImageResult(int resultCode) { if (resultCode == Activity.RESULT_OK) { fileUriResolver.getFullImagePath( pendingCameraMediaUri != null ? pendingCameraMediaUri : Uri.parse(cache.retrievePendingCameraMediaUriPath()), new OnPathReadyListener() { @Override public void onPathReady(String path) { handleImageResult(path, true); } }); return; } // User cancelled taking a picture. finishWithSuccess(null); } private void handleCaptureVideoResult(int resultCode) { if (resultCode == Activity.RESULT_OK) { fileUriResolver.getFullImagePath( pendingCameraMediaUri != null ? pendingCameraMediaUri : Uri.parse(cache.retrievePendingCameraMediaUriPath()), new OnPathReadyListener() { @Override public void onPathReady(String path) { handleVideoResult(path); } }); return; } // User cancelled taking a picture. finishWithSuccess(null); } private void handleMultiImageResult( ArrayList<String> paths, boolean shouldDeleteOriginalIfScaled) { if (methodCall != null) { ArrayList<String> finalPath = new ArrayList<>(); for (int i = 0; i < paths.size(); i++) { String finalImagePath = getResizedImagePath(paths.get(i)); //delete original file if scaled if (finalImagePath != null && !finalImagePath.equals(paths.get(i)) && shouldDeleteOriginalIfScaled) { new File(paths.get(i)).delete(); } finalPath.add(i, finalImagePath); } finishWithListSuccess(finalPath); } else { finishWithListSuccess(paths); } } private void handleImageResult(String path, boolean shouldDeleteOriginalIfScaled) { if (methodCall != null) { String finalImagePath = getResizedImagePath(path); //delete original file if scaled if (finalImagePath != null && !finalImagePath.equals(path) && shouldDeleteOriginalIfScaled) { new File(path).delete(); } finishWithSuccess(finalImagePath); } else { finishWithSuccess(path); } } private String getResizedImagePath(String path) { Double maxWidth = methodCall.argument("maxWidth"); Double maxHeight = methodCall.argument("maxHeight"); Integer imageQuality = methodCall.argument("imageQuality"); return imageResizer.resizeImageIfNeeded(path, maxWidth, maxHeight, imageQuality); } private void handleVideoResult(String path) { finishWithSuccess(path); } private boolean setPendingMethodCallAndResult( MethodCall methodCall, MethodChannel.Result result) { if (pendingResult != null) { return false; } this.methodCall = methodCall; pendingResult = result; // Clean up cache if a new image picker is launched. cache.clear(); return true; } // Handles completion of selection with a single result. // // A null imagePath indicates that the image picker was cancelled without // selection. private void finishWithSuccess(@Nullable String imagePath) { if (pendingResult == null) { // Only save data for later retrieval if something was actually selected. if (imagePath != null) { ArrayList<String> pathList = new ArrayList<>(); pathList.add(imagePath); cache.saveResult(pathList, null, null); } return; } pendingResult.success(imagePath); clearMethodCallAndResult(); } private void finishWithListSuccess(ArrayList<String> imagePaths) { if (pendingResult == null) { cache.saveResult(imagePaths, null, null); return; } pendingResult.success(imagePaths); clearMethodCallAndResult(); } private void finishWithAlreadyActiveError(MethodChannel.Result result) { result.error("already_active", "Image picker is already active", null); } private void finishWithError(String errorCode, String errorMessage) { if (pendingResult == null) { cache.saveResult(null, errorCode, errorMessage); return; } pendingResult.error(errorCode, errorMessage, null); clearMethodCallAndResult(); } private void clearMethodCallAndResult() { methodCall = null; pendingResult = null; } private void useFrontCamera(Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { intent.putExtra( "android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true); } } else { intent.putExtra("android.intent.extras.CAMERA_FACING", 1); } } }
plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerDelegate.java/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerDelegate.java", "repo_id": "plugins", "token_count": 8380 }
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 'dart:convert'; import 'dart:html' as html; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_for_web/image_picker_for_web.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'package:integration_test/integration_test.dart'; const String expectedStringContents = 'Hello, world!'; const String otherStringContents = 'Hello again, world!'; final Uint8List bytes = utf8.encode(expectedStringContents) as Uint8List; final Uint8List otherBytes = utf8.encode(otherStringContents) as Uint8List; final Map<String, dynamic> options = <String, dynamic>{ 'type': 'text/plain', 'lastModified': DateTime.utc(2017, 12, 13).millisecondsSinceEpoch, }; final html.File textFile = html.File(<Uint8List>[bytes], 'hello.txt', options); final html.File secondTextFile = html.File(<Uint8List>[otherBytes], 'secondFile.txt'); void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); // Under test... late ImagePickerPlugin plugin; setUp(() { plugin = ImagePickerPlugin(); }); testWidgets('Can select a file (Deprecated)', (WidgetTester tester) async { final html.FileUploadInputElement mockInput = html.FileUploadInputElement(); final ImagePickerPluginTestOverrides overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) ..getMultipleFilesFromInput = ((_) => <html.File>[textFile]); final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides); // Init the pick file dialog... final Future<PickedFile> file = plugin.pickFile(); // Mock the browser behavior of selecting a file... mockInput.dispatchEvent(html.Event('change')); // Now the file should be available expect(file, completes); // And readable expect((await file).readAsBytes(), completion(isNotEmpty)); }); testWidgets('Can select a file', (WidgetTester tester) async { final html.FileUploadInputElement mockInput = html.FileUploadInputElement(); final ImagePickerPluginTestOverrides overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) ..getMultipleFilesFromInput = ((_) => <html.File>[textFile]); final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides); // Init the pick file dialog... final Future<XFile> image = plugin.getImage(source: ImageSource.camera); // Mock the browser behavior of selecting a file... mockInput.dispatchEvent(html.Event('change')); // Now the file should be available expect(image, completes); // And readable final XFile file = await image; expect(file.readAsBytes(), completion(isNotEmpty)); expect(file.name, textFile.name); expect(file.length(), completion(textFile.size)); expect(file.mimeType, textFile.type); expect( file.lastModified(), completion( DateTime.fromMillisecondsSinceEpoch(textFile.lastModified!), )); }); testWidgets('Can select multiple files', (WidgetTester tester) async { final html.FileUploadInputElement mockInput = html.FileUploadInputElement(); final ImagePickerPluginTestOverrides overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) ..getMultipleFilesFromInput = ((_) => <html.File>[textFile, secondTextFile]); final ImagePickerPlugin plugin = ImagePickerPlugin(overrides: overrides); // Init the pick file dialog... final Future<List<XFile>> files = plugin.getMultiImage(); // Mock the browser behavior of selecting a file... mockInput.dispatchEvent(html.Event('change')); // Now the file should be available expect(files, completes); // And readable expect((await files).first.readAsBytes(), completion(isNotEmpty)); // Peek into the second file... final XFile secondFile = (await files).elementAt(1); expect(secondFile.readAsBytes(), completion(isNotEmpty)); expect(secondFile.name, secondTextFile.name); expect(secondFile.length(), completion(secondTextFile.size)); }); // There's no good way of detecting when the user has "aborted" the selection. testWidgets('computeCaptureAttribute', (WidgetTester tester) async { expect( plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.front), isNull, ); expect( plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.rear), isNull, ); expect( plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.front), 'user', ); expect( plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.rear), 'environment', ); }); group('createInputElement', () { testWidgets('accept: any, capture: null', (WidgetTester tester) async { final html.Element input = plugin.createInputElement('any', null); expect(input.attributes, containsPair('accept', 'any')); expect(input.attributes, isNot(contains('capture'))); expect(input.attributes, isNot(contains('multiple'))); }); testWidgets('accept: any, capture: something', (WidgetTester tester) async { final html.Element input = plugin.createInputElement('any', 'something'); expect(input.attributes, containsPair('accept', 'any')); expect(input.attributes, containsPair('capture', 'something')); expect(input.attributes, isNot(contains('multiple'))); }); testWidgets('accept: any, capture: null, multi: true', (WidgetTester tester) async { final html.Element input = plugin.createInputElement('any', null, multiple: true); expect(input.attributes, containsPair('accept', 'any')); expect(input.attributes, isNot(contains('capture'))); expect(input.attributes, contains('multiple')); }); testWidgets('accept: any, capture: something, multi: true', (WidgetTester tester) async { final html.Element input = plugin.createInputElement('any', 'something', multiple: true); expect(input.attributes, containsPair('accept', 'any')); expect(input.attributes, containsPair('capture', 'something')); expect(input.attributes, contains('multiple')); }); }); }
plugins/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart", "repo_id": "plugins", "token_count": 2216 }
1,257
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'image_picker_ios' s.version = '0.0.1' s.summary = 'Flutter plugin that shows an image picker.' s.description = <<-DESC A Flutter plugin for picking images from the image library, and taking new pictures with the camera. Downloaded by pub (not CocoaPods). DESC s.homepage = 'https://github.com/flutter/plugins' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/image_picker_ios' } s.documentation_url = 'https://pub.dev/packages/image_picker_ios' s.source_files = 'Classes/**/*.{h,m}' s.public_header_files = 'Classes/**/*.h' s.module_map = 'Classes/ImagePickerPlugin.modulemap' s.dependency 'Flutter' s.platform = :ios, '9.0' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } end
plugins/packages/image_picker/image_picker_ios/ios/image_picker_ios.podspec/0
{ "file_path": "plugins/packages/image_picker/image_picker_ios/ios/image_picker_ios.podspec", "repo_id": "plugins", "token_count": 491 }
1,258
// 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. /// Specifies image-specific options for picking. class ImageOptions { /// Creates an instance with the given [maxHeight], [maxWidth], [imageQuality] /// and [requestFullMetadata]. const ImageOptions({ this.maxHeight, this.maxWidth, this.imageQuality, this.requestFullMetadata = true, }); /// The maximum width of the image, in pixels. /// /// If null, the image will only be resized if [maxHeight] is specified. final double? maxWidth; /// The maximum height of the image, in pixels. /// /// If null, the image will only be resized if [maxWidth] is specified. final double? maxHeight; /// Modifies the quality of the image, ranging from 0-100 where 100 is the /// original/max quality. /// /// Compression is only supported for certain image types such as JPEG. If /// compression is not supported for the image that is picked, a warning /// message will be logged. /// /// If null, the image will be returned with the original quality. final int? imageQuality; /// If true, requests full image metadata, which may require extra permissions /// on some platforms, (e.g., NSPhotoLibraryUsageDescription on iOS). // // Defaults to true. final bool requestFullMetadata; }
plugins/packages/image_picker/image_picker_platform_interface/lib/src/types/image_options.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_platform_interface/lib/src/types/image_options.dart", "repo_id": "plugins", "token_count": 386 }
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. /// Captures an error from the underlying purchase platform. /// /// The error can happen during the purchase, restoring a purchase, or querying product. /// Errors from restoring a purchase are not indicative of any errors during the original purchase. /// See also: /// * [ProductDetailsResponse] for error when querying product details. /// * [PurchaseDetails] for error happened in purchase. class IAPError { /// Creates a new IAP error object with the given error details. IAPError( {required this.source, required this.code, required this.message, this.details}); /// Which source is the error on. final String source; /// The error code. final String code; /// A human-readable error message. final String message; /// Error details, possibly null. final dynamic details; @override String toString() { return 'IAPError(code: $code, source: $source, message: $message, details: $details)'; } }
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_error.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_error.dart", "repo_id": "plugins", "token_count": 308 }
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 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; void main() { group('Constructor Tests', () { test( 'fromSkProduct should correctly parse data from a SKProductWrapper instance.', () { final ProductDetails productDetails = ProductDetails( id: 'id', title: 'title', description: 'description', price: '13.37', currencyCode: 'USD', currencySymbol: r'$', rawPrice: 13.37); expect(productDetails.id, 'id'); expect(productDetails.title, 'title'); expect(productDetails.description, 'description'); expect(productDetails.rawPrice, 13.37); expect(productDetails.currencyCode, 'USD'); expect(productDetails.currencySymbol, r'$'); }); }); group('PurchaseStatus Tests', () { test('PurchaseStatus should contain 5 options', () { const List<PurchaseStatus> values = PurchaseStatus.values; expect(values.length, 5); }); test('PurchaseStatus enum should have items in correct index', () { const List<PurchaseStatus> values = PurchaseStatus.values; expect(values[0], PurchaseStatus.pending); expect(values[1], PurchaseStatus.purchased); expect(values[2], PurchaseStatus.error); expect(values[3], PurchaseStatus.restored); expect(values[4], PurchaseStatus.canceled); }); }); }
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/types/product_details_test.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/types/product_details_test.dart", "repo_id": "plugins", "token_count": 586 }
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. #import "FIAPPaymentQueueDelegate.h" #import "FIAObjectTranslator.h" @interface FIAPPaymentQueueDelegate () @property(strong, nonatomic, readonly) FlutterMethodChannel *callbackChannel; @end @implementation FIAPPaymentQueueDelegate - (id)initWithMethodChannel:(FlutterMethodChannel *)methodChannel { self = [super init]; if (self) { _callbackChannel = methodChannel; } return self; } - (BOOL)paymentQueue:(SKPaymentQueue *)paymentQueue shouldContinueTransaction:(SKPaymentTransaction *)transaction inStorefront:(SKStorefront *)newStorefront { // Default return value for this method is true (see // https://developer.apple.com/documentation/storekit/skpaymentqueuedelegate/3521328-paymentqueueshouldshowpriceconse?language=objc) __block BOOL shouldContinue = YES; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); [self.callbackChannel invokeMethod:@"shouldContinueTransaction" arguments:[FIAObjectTranslator getMapFromSKStorefront:newStorefront andSKPaymentTransaction:transaction] result:^(id _Nullable result) { // When result is a valid instance of NSNumber use it to determine // if the transaction should continue. Otherwise use the default // value. if (result && [result isKindOfClass:[NSNumber class]]) { shouldContinue = [(NSNumber *)result boolValue]; } dispatch_semaphore_signal(semaphore); }]; // The client should respond within 1 second otherwise continue // with default value. dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC)); return shouldContinue; } #if TARGET_OS_IOS - (BOOL)paymentQueueShouldShowPriceConsent:(SKPaymentQueue *)paymentQueue { // Default return value for this method is true (see // https://developer.apple.com/documentation/storekit/skpaymentqueuedelegate/3521328-paymentqueueshouldshowpriceconse?language=objc) __block BOOL shouldShowPriceConsent = YES; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); [self.callbackChannel invokeMethod:@"shouldShowPriceConsent" arguments:nil result:^(id _Nullable result) { // When result is a valid instance of NSNumber use it to determine // if the transaction should continue. Otherwise use the default // value. if (result && [result isKindOfClass:[NSNumber class]]) { shouldShowPriceConsent = [(NSNumber *)result boolValue]; } dispatch_semaphore_signal(semaphore); }]; // The client should respond within 1 second otherwise continue // with default value. dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC)); return shouldShowPriceConsent; } #endif @end
plugins/packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAPPaymentQueueDelegate.m/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAPPaymentQueueDelegate.m", "repo_id": "plugins", "token_count": 1496 }
1,262
# store_kit_wrappers This exposes Dart endpoints through to the [StoreKit](https://developer.apple.com/documentation/storekit) APIs. Can be used as an alternative to [in_app_purchase](../in_app_purchase/README.md).
plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/README.md/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/README.md", "repo_id": "plugins", "token_count": 68 }
1,263
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import '../../store_kit_wrappers.dart'; /// Apple AppStore specific parameter object for generating a purchase. class AppStorePurchaseParam extends PurchaseParam { /// Creates a new [AppStorePurchaseParam] object with the given data. AppStorePurchaseParam({ required super.productDetails, super.applicationUserName, this.quantity = 1, this.simulatesAskToBuyInSandbox = false, this.discount, }); /// Set it to `true` to produce an "ask to buy" flow for this payment in the /// sandbox. /// /// If you want to test [simulatesAskToBuyInSandbox], you should ensure that /// you create an instance of the [AppStorePurchaseParam] class and set its /// [simulateAskToBuyInSandbox] field to `true` and use it with the /// `buyNonConsumable` or `buyConsumable` methods. /// /// See also [SKPaymentWrapper.simulatesAskToBuyInSandbox]. final bool simulatesAskToBuyInSandbox; /// Quantity of the product user requested to buy. final int quantity; /// Discount applied to the product. The value is `null` when the product does not have a discount. final SKPaymentDiscountWrapper? discount; }
plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/app_store_purchase_param.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/app_store_purchase_param.dart", "repo_id": "plugins", "token_count": 406 }
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. #import "InAppPurchasePlugin.h" #import <StoreKit/StoreKit.h> #import "FIAObjectTranslator.h" #import "FIAPPaymentQueueDelegate.h" #import "FIAPReceiptManager.h" #import "FIAPRequestHandler.h" #import "FIAPaymentQueueHandler.h" @interface InAppPurchasePlugin () // Holding strong references to FIAPRequestHandlers. Remove the handlers from the set after // the request is finished. @property(strong, nonatomic, readonly) NSMutableSet *requestHandlers; // After querying the product, the available products will be saved in the map to be used // for purchase. @property(strong, nonatomic, readonly) NSMutableDictionary *productsCache; // Callback channel to dart used for when a function from the transaction observer is triggered. @property(strong, nonatomic, readonly) FlutterMethodChannel *transactionObserverCallbackChannel; // Callback channel to dart used for when a function from the payment queue delegate is triggered. @property(strong, nonatomic, readonly) FlutterMethodChannel *paymentQueueDelegateCallbackChannel; @property(strong, nonatomic, readonly) NSObject<FlutterPluginRegistrar> *registrar; @property(strong, nonatomic, readonly) FIAPReceiptManager *receiptManager; @property(strong, nonatomic, readonly) FIAPPaymentQueueDelegate *paymentQueueDelegate API_AVAILABLE(ios(13)) API_UNAVAILABLE(tvos, macos, watchos); @end @implementation InAppPurchasePlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/in_app_purchase" binaryMessenger:[registrar messenger]]; InAppPurchasePlugin *instance = [[InAppPurchasePlugin alloc] initWithRegistrar:registrar]; [registrar addMethodCallDelegate:instance channel:channel]; } - (instancetype)initWithReceiptManager:(FIAPReceiptManager *)receiptManager { self = [super init]; _receiptManager = receiptManager; _requestHandlers = [NSMutableSet new]; _productsCache = [NSMutableDictionary new]; return self; } - (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { self = [self initWithReceiptManager:[FIAPReceiptManager new]]; _registrar = registrar; __weak typeof(self) weakSelf = self; _paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:[SKPaymentQueue defaultQueue] transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) { [weakSelf handleTransactionsUpdated:transactions]; } transactionRemoved:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) { [weakSelf handleTransactionsRemoved:transactions]; } restoreTransactionFailed:^(NSError *_Nonnull error) { [weakSelf handleTransactionRestoreFailed:error]; } restoreCompletedTransactionsFinished:^{ [weakSelf restoreCompletedTransactionsFinished]; } shouldAddStorePayment:^BOOL(SKPayment *payment, SKProduct *product) { return [weakSelf shouldAddStorePayment:payment product:product]; } updatedDownloads:^void(NSArray<SKDownload *> *_Nonnull downloads) { [weakSelf updatedDownloads:downloads]; } transactionCache:[[FIATransactionCache alloc] init]]; _transactionObserverCallbackChannel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/in_app_purchase" binaryMessenger:[registrar messenger]]; return self; } - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result { if ([@"-[SKPaymentQueue canMakePayments:]" isEqualToString:call.method]) { [self canMakePayments:result]; } else if ([@"-[SKPaymentQueue transactions]" isEqualToString:call.method]) { [self getPendingTransactions:result]; } else if ([@"-[InAppPurchasePlugin startProductRequest:result:]" isEqualToString:call.method]) { [self handleProductRequestMethodCall:call result:result]; } else if ([@"-[InAppPurchasePlugin addPayment:result:]" isEqualToString:call.method]) { [self addPayment:call result:result]; } else if ([@"-[InAppPurchasePlugin finishTransaction:result:]" isEqualToString:call.method]) { [self finishTransaction:call result:result]; } else if ([@"-[InAppPurchasePlugin restoreTransactions:result:]" isEqualToString:call.method]) { [self restoreTransactions:call result:result]; #if TARGET_OS_IOS } else if ([@"-[InAppPurchasePlugin presentCodeRedemptionSheet:result:]" isEqualToString:call.method]) { [self presentCodeRedemptionSheet:call result:result]; #endif } else if ([@"-[InAppPurchasePlugin retrieveReceiptData:result:]" isEqualToString:call.method]) { [self retrieveReceiptData:call result:result]; } else if ([@"-[InAppPurchasePlugin refreshReceipt:result:]" isEqualToString:call.method]) { [self refreshReceipt:call result:result]; } else if ([@"-[SKPaymentQueue startObservingTransactionQueue]" isEqualToString:call.method]) { [self startObservingPaymentQueue:result]; } else if ([@"-[SKPaymentQueue stopObservingTransactionQueue]" isEqualToString:call.method]) { [self stopObservingPaymentQueue:result]; #if TARGET_OS_IOS } else if ([@"-[SKPaymentQueue registerDelegate]" isEqualToString:call.method]) { [self registerPaymentQueueDelegate:result]; #endif } else if ([@"-[SKPaymentQueue removeDelegate]" isEqualToString:call.method]) { [self removePaymentQueueDelegate:result]; #if TARGET_OS_IOS } else if ([@"-[SKPaymentQueue showPriceConsentIfNeeded]" isEqualToString:call.method]) { [self showPriceConsentIfNeeded:result]; #endif } else { result(FlutterMethodNotImplemented); } } - (void)canMakePayments:(FlutterResult)result { result(@([SKPaymentQueue canMakePayments])); } - (void)getPendingTransactions:(FlutterResult)result { NSArray<SKPaymentTransaction *> *transactions = [self.paymentQueueHandler getUnfinishedTransactions]; NSMutableArray *transactionMaps = [[NSMutableArray alloc] init]; for (SKPaymentTransaction *transaction in transactions) { [transactionMaps addObject:[FIAObjectTranslator getMapFromSKPaymentTransaction:transaction]]; } result(transactionMaps); } - (void)handleProductRequestMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result { if (![call.arguments isKindOfClass:[NSArray class]]) { result([FlutterError errorWithCode:@"storekit_invalid_argument" message:@"Argument type of startRequest is not array" details:call.arguments]); return; } NSArray *productIdentifiers = (NSArray *)call.arguments; SKProductsRequest *request = [self getProductRequestWithIdentifiers:[NSSet setWithArray:productIdentifiers]]; FIAPRequestHandler *handler = [[FIAPRequestHandler alloc] initWithRequest:request]; [self.requestHandlers addObject:handler]; __weak typeof(self) weakSelf = self; [handler startProductRequestWithCompletionHandler:^(SKProductsResponse *_Nullable response, NSError *_Nullable error) { if (error) { result([FlutterError errorWithCode:@"storekit_getproductrequest_platform_error" message:error.localizedDescription details:error.description]); return; } if (!response) { result([FlutterError errorWithCode:@"storekit_platform_no_response" message:@"Failed to get SKProductResponse in startRequest " @"call. Error occured on iOS platform" details:call.arguments]); return; } for (SKProduct *product in response.products) { [self.productsCache setObject:product forKey:product.productIdentifier]; } result([FIAObjectTranslator getMapFromSKProductsResponse:response]); [weakSelf.requestHandlers removeObject:handler]; }]; } - (void)addPayment:(FlutterMethodCall *)call result:(FlutterResult)result { if (![call.arguments isKindOfClass:[NSDictionary class]]) { result([FlutterError errorWithCode:@"storekit_invalid_argument" message:@"Argument type of addPayment is not a Dictionary" details:call.arguments]); return; } NSDictionary *paymentMap = (NSDictionary *)call.arguments; NSString *productID = [paymentMap objectForKey:@"productIdentifier"]; // When a product is already fetched, we create a payment object with // the product to process the payment. SKProduct *product = [self getProduct:productID]; if (!product) { result([FlutterError errorWithCode:@"storekit_invalid_payment_object" message: @"You have requested a payment for an invalid product. Either the " @"`productIdentifier` of the payment is not valid or the product has not been " @"fetched before adding the payment to the payment queue." details:call.arguments]); return; } SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:product]; payment.applicationUsername = [paymentMap objectForKey:@"applicationUsername"]; NSNumber *quantity = [paymentMap objectForKey:@"quantity"]; payment.quantity = (quantity != nil) ? quantity.integerValue : 1; NSNumber *simulatesAskToBuyInSandbox = [paymentMap objectForKey:@"simulatesAskToBuyInSandbox"]; payment.simulatesAskToBuyInSandbox = (id)simulatesAskToBuyInSandbox == (id)[NSNull null] ? NO : [simulatesAskToBuyInSandbox boolValue]; if (@available(iOS 12.2, *)) { NSDictionary *paymentDiscountMap = [self getNonNullValueFromDictionary:paymentMap forKey:@"paymentDiscount"]; NSString *error = nil; SKPaymentDiscount *paymentDiscount = [FIAObjectTranslator getSKPaymentDiscountFromMap:paymentDiscountMap withError:&error]; if (error) { result([FlutterError errorWithCode:@"storekit_invalid_payment_discount_object" message:[NSString stringWithFormat:@"You have requested a payment and specified a " @"payment discount with invalid properties. %@", error] details:call.arguments]); return; } payment.paymentDiscount = paymentDiscount; } if (![self.paymentQueueHandler addPayment:payment]) { result([FlutterError errorWithCode:@"storekit_duplicate_product_object" message:@"There is a pending transaction for the same product identifier. Please " @"either wait for it to be finished or finish it manually using " @"`completePurchase` to avoid edge cases." details:call.arguments]); return; } result(nil); } - (void)finishTransaction:(FlutterMethodCall *)call result:(FlutterResult)result { if (![call.arguments isKindOfClass:[NSDictionary class]]) { result([FlutterError errorWithCode:@"storekit_invalid_argument" message:@"Argument type of finishTransaction is not a Dictionary" details:call.arguments]); return; } NSDictionary *paymentMap = (NSDictionary *)call.arguments; NSString *transactionIdentifier = [paymentMap objectForKey:@"transactionIdentifier"]; NSString *productIdentifier = [paymentMap objectForKey:@"productIdentifier"]; NSArray<SKPaymentTransaction *> *pendingTransactions = [self.paymentQueueHandler getUnfinishedTransactions]; for (SKPaymentTransaction *transaction in pendingTransactions) { // If the user cancels the purchase dialog we won't have a transactionIdentifier. // So if it is null AND a transaction in the pendingTransactions list has // also a null transactionIdentifier we check for equal product identifiers. if ([transaction.transactionIdentifier isEqualToString:transactionIdentifier] || ([transactionIdentifier isEqual:[NSNull null]] && transaction.transactionIdentifier == nil && [transaction.payment.productIdentifier isEqualToString:productIdentifier])) { @try { [self.paymentQueueHandler finishTransaction:transaction]; } @catch (NSException *e) { result([FlutterError errorWithCode:@"storekit_finish_transaction_exception" message:e.name details:e.description]); return; } } } result(nil); } - (void)restoreTransactions:(FlutterMethodCall *)call result:(FlutterResult)result { if (call.arguments && ![call.arguments isKindOfClass:[NSString class]]) { result([FlutterError errorWithCode:@"storekit_invalid_argument" message:@"Argument is not nil and the type of finishTransaction is not a string." details:call.arguments]); return; } [self.paymentQueueHandler restoreTransactions:call.arguments]; result(nil); } #if TARGET_OS_IOS - (void)presentCodeRedemptionSheet:(FlutterMethodCall *)call result:(FlutterResult)result { [self.paymentQueueHandler presentCodeRedemptionSheet]; result(nil); } #endif - (void)retrieveReceiptData:(FlutterMethodCall *)call result:(FlutterResult)result { FlutterError *error = nil; NSString *receiptData = [self.receiptManager retrieveReceiptWithError:&error]; if (error) { result(error); return; } result(receiptData); } - (void)refreshReceipt:(FlutterMethodCall *)call result:(FlutterResult)result { NSDictionary *arguments = call.arguments; SKReceiptRefreshRequest *request; if (arguments) { if (![arguments isKindOfClass:[NSDictionary class]]) { result([FlutterError errorWithCode:@"storekit_invalid_argument" message:@"Argument type of startRequest is not array" details:call.arguments]); return; } NSMutableDictionary *properties = [NSMutableDictionary new]; properties[SKReceiptPropertyIsExpired] = arguments[@"isExpired"]; properties[SKReceiptPropertyIsRevoked] = arguments[@"isRevoked"]; properties[SKReceiptPropertyIsVolumePurchase] = arguments[@"isVolumePurchase"]; request = [self getRefreshReceiptRequest:properties]; } else { request = [self getRefreshReceiptRequest:nil]; } FIAPRequestHandler *handler = [[FIAPRequestHandler alloc] initWithRequest:request]; [self.requestHandlers addObject:handler]; __weak typeof(self) weakSelf = self; [handler startProductRequestWithCompletionHandler:^(SKProductsResponse *_Nullable response, NSError *_Nullable error) { if (error) { result([FlutterError errorWithCode:@"storekit_refreshreceiptrequest_platform_error" message:error.localizedDescription details:error.description]); return; } result(nil); [weakSelf.requestHandlers removeObject:handler]; }]; } - (void)startObservingPaymentQueue:(FlutterResult)result { [_paymentQueueHandler startObservingPaymentQueue]; result(nil); } - (void)stopObservingPaymentQueue:(FlutterResult)result { [_paymentQueueHandler stopObservingPaymentQueue]; result(nil); } #if TARGET_OS_IOS - (void)registerPaymentQueueDelegate:(FlutterResult)result { if (@available(iOS 13.0, *)) { _paymentQueueDelegateCallbackChannel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/in_app_purchase_payment_queue_delegate" binaryMessenger:[_registrar messenger]]; _paymentQueueDelegate = [[FIAPPaymentQueueDelegate alloc] initWithMethodChannel:_paymentQueueDelegateCallbackChannel]; _paymentQueueHandler.delegate = _paymentQueueDelegate; } result(nil); } #endif - (void)removePaymentQueueDelegate:(FlutterResult)result { if (@available(iOS 13.0, *)) { _paymentQueueHandler.delegate = nil; } _paymentQueueDelegate = nil; _paymentQueueDelegateCallbackChannel = nil; result(nil); } #if TARGET_OS_IOS - (void)showPriceConsentIfNeeded:(FlutterResult)result { if (@available(iOS 13.4, *)) { [_paymentQueueHandler showPriceConsentIfNeeded]; } result(nil); } #endif - (id)getNonNullValueFromDictionary:(NSDictionary *)dictionary forKey:(NSString *)key { id value = dictionary[key]; return [value isKindOfClass:[NSNull class]] ? nil : value; } #pragma mark - transaction observer: - (void)handleTransactionsUpdated:(NSArray<SKPaymentTransaction *> *)transactions { NSMutableArray *maps = [NSMutableArray new]; for (SKPaymentTransaction *transaction in transactions) { [maps addObject:[FIAObjectTranslator getMapFromSKPaymentTransaction:transaction]]; } [self.transactionObserverCallbackChannel invokeMethod:@"updatedTransactions" arguments:maps]; } - (void)handleTransactionsRemoved:(NSArray<SKPaymentTransaction *> *)transactions { NSMutableArray *maps = [NSMutableArray new]; for (SKPaymentTransaction *transaction in transactions) { [maps addObject:[FIAObjectTranslator getMapFromSKPaymentTransaction:transaction]]; } [self.transactionObserverCallbackChannel invokeMethod:@"removedTransactions" arguments:maps]; } - (void)handleTransactionRestoreFailed:(NSError *)error { [self.transactionObserverCallbackChannel invokeMethod:@"restoreCompletedTransactionsFailed" arguments:[FIAObjectTranslator getMapFromNSError:error]]; } - (void)restoreCompletedTransactionsFinished { [self.transactionObserverCallbackChannel invokeMethod:@"paymentQueueRestoreCompletedTransactionsFinished" arguments:nil]; } - (void)updatedDownloads:(NSArray<SKDownload *> *)downloads { NSLog(@"Received an updatedDownloads callback, but downloads are not supported."); } - (BOOL)shouldAddStorePayment:(SKPayment *)payment product:(SKProduct *)product { // We always return NO here. And we send the message to dart to process the payment; and we will // have a interception method that deciding if the payment should be processed (implemented by the // programmer). [self.productsCache setObject:product forKey:product.productIdentifier]; [self.transactionObserverCallbackChannel invokeMethod:@"shouldAddStorePayment" arguments:@{ @"payment" : [FIAObjectTranslator getMapFromSKPayment:payment], @"product" : [FIAObjectTranslator getMapFromSKProduct:product] }]; return NO; } #pragma mark - dependency injection (for unit testing) - (SKProductsRequest *)getProductRequestWithIdentifiers:(NSSet *)identifiers { return [[SKProductsRequest alloc] initWithProductIdentifiers:identifiers]; } - (SKProduct *)getProduct:(NSString *)productID { return [self.productsCache objectForKey:productID]; } - (SKReceiptRefreshRequest *)getRefreshReceiptRequest:(NSDictionary *)properties { return [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:properties]; } @end
plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/InAppPurchasePlugin.m/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/InAppPurchasePlugin.m", "repo_id": "plugins", "token_count": 7041 }
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. // This file exists solely to host compiled excerpts for README.md, and is not // intended for use as an actual example application. // ignore_for_file: public_member_api_docs, avoid_print import 'package:flutter/material.dart'; // #docregion ErrorHandling import 'package:flutter/services.dart'; // #docregion NoErrorDialogs import 'package:local_auth/error_codes.dart' as auth_error; // #enddocregion NoErrorDialogs // #docregion CanCheck import 'package:local_auth/local_auth.dart'; // #enddocregion CanCheck // #enddocregion ErrorHandling // #docregion CustomMessages import 'package:local_auth_android/local_auth_android.dart'; import 'package:local_auth_ios/local_auth_ios.dart'; // #enddocregion CustomMessages void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { // #docregion CanCheck // #docregion ErrorHandling final LocalAuthentication auth = LocalAuthentication(); // #enddocregion CanCheck // #enddocregion ErrorHandling @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('README example app'), ), body: const Text('See example in main.dart'), ), ); } Future<void> checkSupport() async { // #docregion CanCheck final bool canAuthenticateWithBiometrics = await auth.canCheckBiometrics; final bool canAuthenticate = canAuthenticateWithBiometrics || await auth.isDeviceSupported(); // #enddocregion CanCheck print('Can authenticate: $canAuthenticate'); print('Can authenticate with biometrics: $canAuthenticateWithBiometrics'); } Future<void> getEnrolledBiometrics() async { // #docregion Enrolled final List<BiometricType> availableBiometrics = await auth.getAvailableBiometrics(); if (availableBiometrics.isNotEmpty) { // Some biometrics are enrolled. } if (availableBiometrics.contains(BiometricType.strong) || availableBiometrics.contains(BiometricType.face)) { // Specific types of biometrics are available. // Use checks like this with caution! } // #enddocregion Enrolled } Future<void> authenticate() async { // #docregion AuthAny try { final bool didAuthenticate = await auth.authenticate( localizedReason: 'Please authenticate to show account balance'); // #enddocregion AuthAny print(didAuthenticate); // #docregion AuthAny } on PlatformException { // ... } // #enddocregion AuthAny } Future<void> authenticateWithBiometrics() async { // #docregion AuthBioOnly final bool didAuthenticate = await auth.authenticate( localizedReason: 'Please authenticate to show account balance', options: const AuthenticationOptions(biometricOnly: true)); // #enddocregion AuthBioOnly print(didAuthenticate); } Future<void> authenticateWithoutDialogs() async { // #docregion NoErrorDialogs try { final bool didAuthenticate = await auth.authenticate( localizedReason: 'Please authenticate to show account balance', options: const AuthenticationOptions(useErrorDialogs: false)); // #enddocregion NoErrorDialogs print(didAuthenticate ? 'Success!' : 'Failure'); // #docregion NoErrorDialogs } on PlatformException catch (e) { if (e.code == auth_error.notAvailable) { // Add handling of no hardware here. } else if (e.code == auth_error.notEnrolled) { // ... } else { // ... } } // #enddocregion NoErrorDialogs } Future<void> authenticateWithErrorHandling() async { // #docregion ErrorHandling try { final bool didAuthenticate = await auth.authenticate( localizedReason: 'Please authenticate to show account balance', options: const AuthenticationOptions(useErrorDialogs: false)); // #enddocregion ErrorHandling print(didAuthenticate ? 'Success!' : 'Failure'); // #docregion ErrorHandling } on PlatformException catch (e) { if (e.code == auth_error.notEnrolled) { // Add handling of no hardware here. } else if (e.code == auth_error.lockedOut || e.code == auth_error.permanentlyLockedOut) { // ... } else { // ... } } // #enddocregion ErrorHandling } Future<void> authenticateWithCustomDialogMessages() async { // #docregion CustomMessages final bool didAuthenticate = await auth.authenticate( localizedReason: 'Please authenticate to show account balance', authMessages: const <AuthMessages>[ AndroidAuthMessages( signInTitle: 'Oops! Biometric authentication required!', cancelButton: 'No thanks', ), IOSAuthMessages( cancelButton: 'No thanks', ), ]); // #enddocregion CustomMessages print(didAuthenticate ? 'Success!' : 'Failure'); } }
plugins/packages/local_auth/local_auth/example/lib/readme_excerpts.dart/0
{ "file_path": "plugins/packages/local_auth/local_auth/example/lib/readme_excerpts.dart", "repo_id": "plugins", "token_count": 1879 }
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 io.flutter.plugins.localauth; import static android.app.Activity.RESULT_OK; import static android.content.Context.KEYGUARD_SERVICE; import android.app.Activity; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.biometric.BiometricManager; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Lifecycle; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.embedding.engine.plugins.lifecycle.FlutterLifecycleAdapter; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugin.common.PluginRegistry.Registrar; import io.flutter.plugins.localauth.AuthenticationHelper.AuthCompletionHandler; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicBoolean; /** * Flutter plugin providing access to local authentication. * * <p>Instantiate this in an add to app scenario to gracefully handle activity and context changes. */ @SuppressWarnings("deprecation") public class LocalAuthPlugin implements MethodCallHandler, FlutterPlugin, ActivityAware { private static final String CHANNEL_NAME = "plugins.flutter.io/local_auth_android"; private static final int LOCK_REQUEST_CODE = 221; private Activity activity; private AuthenticationHelper authHelper; @VisibleForTesting final AtomicBoolean authInProgress = new AtomicBoolean(false); // These are null when not using v2 embedding. private MethodChannel channel; private Lifecycle lifecycle; private BiometricManager biometricManager; private KeyguardManager keyguardManager; private Result lockRequestResult; private final PluginRegistry.ActivityResultListener resultListener = new PluginRegistry.ActivityResultListener() { @Override public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == LOCK_REQUEST_CODE) { if (resultCode == RESULT_OK && lockRequestResult != null) { authenticateSuccess(lockRequestResult); } else { authenticateFail(lockRequestResult); } lockRequestResult = null; } return false; } }; /** * Registers a plugin with the v1 embedding api {@code io.flutter.plugin.common}. * * <p>Calling this will register the plugin with the passed registrar. However, plugins * initialized this way won't react to changes in activity or context. * * @param registrar attaches this plugin's {@link * io.flutter.plugin.common.MethodChannel.MethodCallHandler} to the registrar's {@link * io.flutter.plugin.common.BinaryMessenger}. */ @SuppressWarnings("deprecation") public static void registerWith(Registrar registrar) { final MethodChannel channel = new MethodChannel(registrar.messenger(), CHANNEL_NAME); final LocalAuthPlugin plugin = new LocalAuthPlugin(); plugin.activity = registrar.activity(); channel.setMethodCallHandler(plugin); registrar.addActivityResultListener(plugin.resultListener); } /** * Default constructor for LocalAuthPlugin. * * <p>Use this constructor when adding this plugin to an app with v2 embedding. */ public LocalAuthPlugin() {} @Override public void onMethodCall(MethodCall call, @NonNull final Result result) { switch (call.method) { case "authenticate": authenticate(call, result); break; case "getEnrolledBiometrics": getEnrolledBiometrics(result); break; case "isDeviceSupported": isDeviceSupported(result); break; case "stopAuthentication": stopAuthentication(result); break; case "deviceSupportsBiometrics": deviceSupportsBiometrics(result); break; default: result.notImplemented(); break; } } /* * Starts authentication process */ private void authenticate(MethodCall call, final Result result) { if (authInProgress.get()) { result.error("auth_in_progress", "Authentication in progress", null); return; } if (activity == null || activity.isFinishing()) { result.error("no_activity", "local_auth plugin requires a foreground activity", null); return; } if (!(activity instanceof FragmentActivity)) { result.error( "no_fragment_activity", "local_auth plugin requires activity to be a FragmentActivity.", null); return; } if (!isDeviceSupported()) { authInProgress.set(false); result.error("NotAvailable", "Required security features not enabled", null); return; } authInProgress.set(true); AuthCompletionHandler completionHandler = createAuthCompletionHandler(result); boolean isBiometricOnly = call.argument("biometricOnly"); boolean allowCredentials = !isBiometricOnly && canAuthenticateWithDeviceCredential(); sendAuthenticationRequest(call, completionHandler, allowCredentials); return; } @VisibleForTesting public AuthCompletionHandler createAuthCompletionHandler(final Result result) { return new AuthCompletionHandler() { @Override public void onSuccess() { authenticateSuccess(result); } @Override public void onFailure() { authenticateFail(result); } @Override public void onError(String code, String error) { if (authInProgress.compareAndSet(true, false)) { result.error(code, error, null); } } }; } @VisibleForTesting public void sendAuthenticationRequest( MethodCall call, AuthCompletionHandler completionHandler, boolean allowCredentials) { authHelper = new AuthenticationHelper( lifecycle, (FragmentActivity) activity, call, completionHandler, allowCredentials); authHelper.authenticate(); } private void authenticateSuccess(Result result) { if (authInProgress.compareAndSet(true, false)) { result.success(true); } } private void authenticateFail(Result result) { if (authInProgress.compareAndSet(true, false)) { result.success(false); } } /* * Stops the authentication if in progress. */ private void stopAuthentication(Result result) { try { if (authHelper != null && authInProgress.get()) { authHelper.stopAuthentication(); authHelper = null; } authInProgress.set(false); result.success(true); } catch (Exception e) { result.success(false); } } private void deviceSupportsBiometrics(final Result result) { result.success(hasBiometricHardware()); } /* * Returns enrolled biometric types available on device. */ private void getEnrolledBiometrics(final Result result) { try { if (activity == null || activity.isFinishing()) { result.error("no_activity", "local_auth plugin requires a foreground activity", null); return; } ArrayList<String> biometrics = getEnrolledBiometrics(); result.success(biometrics); } catch (Exception e) { result.error("no_biometrics_available", e.getMessage(), null); } } @VisibleForTesting public ArrayList<String> getEnrolledBiometrics() { ArrayList<String> biometrics = new ArrayList<>(); if (activity == null || activity.isFinishing()) { return biometrics; } if (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS) { biometrics.add("weak"); } if (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS) { biometrics.add("strong"); } return biometrics; } @VisibleForTesting public boolean isDeviceSecure() { if (keyguardManager == null) return false; return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && keyguardManager.isDeviceSecure()); } @VisibleForTesting public boolean isDeviceSupported() { return isDeviceSecure() || canAuthenticateWithBiometrics(); } private boolean canAuthenticateWithBiometrics() { if (biometricManager == null) return false; return biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS; } private boolean hasBiometricHardware() { if (biometricManager == null) return false; return biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) != BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE; } @VisibleForTesting public boolean canAuthenticateWithDeviceCredential() { if (Build.VERSION.SDK_INT < 30) { // Checking for device credential only authentication via the BiometricManager // is not allowed before API level 30, so we check for presence of PIN, pattern, // or password instead. return isDeviceSecure(); } if (biometricManager == null) return false; return biometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL) == BiometricManager.BIOMETRIC_SUCCESS; } private void isDeviceSupported(Result result) { result.success(isDeviceSupported()); } @Override public void onAttachedToEngine(FlutterPluginBinding binding) { channel = new MethodChannel(binding.getFlutterEngine().getDartExecutor(), CHANNEL_NAME); channel.setMethodCallHandler(this); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {} private void setServicesFromActivity(Activity activity) { if (activity == null) return; this.activity = activity; Context context = activity.getBaseContext(); biometricManager = BiometricManager.from(activity); keyguardManager = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE); } @Override public void onAttachedToActivity(ActivityPluginBinding binding) { binding.addActivityResultListener(resultListener); setServicesFromActivity(binding.getActivity()); lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding); channel.setMethodCallHandler(this); } @Override public void onDetachedFromActivityForConfigChanges() { lifecycle = null; activity = null; } @Override public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) { binding.addActivityResultListener(resultListener); setServicesFromActivity(binding.getActivity()); lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding); } @Override public void onDetachedFromActivity() { lifecycle = null; channel.setMethodCallHandler(null); activity = null; } @VisibleForTesting final Activity getActivity() { return activity; } @VisibleForTesting void setBiometricManager(BiometricManager biometricManager) { this.biometricManager = biometricManager; } @VisibleForTesting void setKeyguardManager(KeyguardManager keyguardManager) { this.keyguardManager = keyguardManager; } }
plugins/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/LocalAuthPlugin.java/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/LocalAuthPlugin.java", "repo_id": "plugins", "token_count": 3883 }
1,267
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <LocalAuthentication/LocalAuthentication.h> #import "FLTLocalAuthPlugin.h" @interface FLTLocalAuthPlugin () @property(nonatomic, copy, nullable) NSDictionary<NSString *, NSNumber *> *lastCallArgs; @property(nonatomic, nullable) FlutterResult lastResult; // For unit tests to inject dummy LAContext instances that will be used when a new context would // normally be created. Each call to createAuthContext will remove the current first element from // the array. - (void)setAuthContextOverrides:(NSArray<LAContext *> *)authContexts; @end @implementation FLTLocalAuthPlugin { NSMutableArray<LAContext *> *_authContextOverrides; } + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/local_auth_ios" binaryMessenger:[registrar messenger]]; FLTLocalAuthPlugin *instance = [[FLTLocalAuthPlugin alloc] init]; [registrar addMethodCallDelegate:instance channel:channel]; [registrar addApplicationDelegate:instance]; } - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result { if ([@"authenticate" isEqualToString:call.method]) { bool isBiometricOnly = [call.arguments[@"biometricOnly"] boolValue]; if (isBiometricOnly) { [self authenticateWithBiometrics:call.arguments withFlutterResult:result]; } else { [self authenticate:call.arguments withFlutterResult:result]; } } else if ([@"getEnrolledBiometrics" isEqualToString:call.method]) { [self getEnrolledBiometrics:result]; } else if ([@"deviceSupportsBiometrics" isEqualToString:call.method]) { [self deviceSupportsBiometrics:result]; } else if ([@"isDeviceSupported" isEqualToString:call.method]) { result(@YES); } else { result(FlutterMethodNotImplemented); } } #pragma mark Private Methods - (void)setAuthContextOverrides:(NSArray<LAContext *> *)authContexts { _authContextOverrides = [authContexts mutableCopy]; } - (LAContext *)createAuthContext { if ([_authContextOverrides count] > 0) { LAContext *context = [_authContextOverrides firstObject]; [_authContextOverrides removeObjectAtIndex:0]; return context; } return [[LAContext alloc] init]; } - (void)alertMessage:(NSString *)message firstButton:(NSString *)firstButton flutterResult:(FlutterResult)result additionalButton:(NSString *)secondButton { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:firstButton style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { result(@NO); }]; [alert addAction:defaultAction]; if (secondButton != nil) { UIAlertAction *additionalAction = [UIAlertAction actionWithTitle:secondButton style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { if (UIApplicationOpenSettingsURLString != NULL) { NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if (@available(iOS 10, *)) { [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:NULL]; } else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" [[UIApplication sharedApplication] openURL:url]; #pragma clang diagnostic pop } result(@NO); } }]; [alert addAction:additionalAction]; } [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:alert animated:YES completion:nil]; } - (void)deviceSupportsBiometrics:(FlutterResult)result { LAContext *context = self.createAuthContext; NSError *authError = nil; // Check if authentication with biometrics is possible. if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) { if (authError == nil) { result(@YES); return; } } // If not, check if it is because no biometrics are enrolled (but still present). if (authError != nil) { if (@available(iOS 11, *)) { if (authError.code == LAErrorBiometryNotEnrolled) { result(@YES); return; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" } else if (authError.code == LAErrorTouchIDNotEnrolled) { result(@YES); return; #pragma clang diagnostic pop } } result(@NO); } - (void)getEnrolledBiometrics:(FlutterResult)result { LAContext *context = self.createAuthContext; NSError *authError = nil; NSMutableArray<NSString *> *biometrics = [[NSMutableArray<NSString *> alloc] init]; if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) { if (authError == nil) { if (@available(iOS 11, *)) { if (context.biometryType == LABiometryTypeFaceID) { [biometrics addObject:@"face"]; } else if (context.biometryType == LABiometryTypeTouchID) { [biometrics addObject:@"fingerprint"]; } } else { [biometrics addObject:@"fingerprint"]; } } } result(biometrics); } - (void)authenticateWithBiometrics:(NSDictionary *)arguments withFlutterResult:(FlutterResult)result { LAContext *context = self.createAuthContext; NSError *authError = nil; self.lastCallArgs = nil; self.lastResult = nil; context.localizedFallbackTitle = arguments[@"localizedFallbackTitle"] == [NSNull null] ? nil : arguments[@"localizedFallbackTitle"]; if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) { [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:arguments[@"localizedReason"] reply:^(BOOL success, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ [self handleAuthReplyWithSuccess:success error:error flutterArguments:arguments flutterResult:result]; }); }]; } else { [self handleErrors:authError flutterArguments:arguments withFlutterResult:result]; } } - (void)authenticate:(NSDictionary *)arguments withFlutterResult:(FlutterResult)result { LAContext *context = self.createAuthContext; NSError *authError = nil; _lastCallArgs = nil; _lastResult = nil; context.localizedFallbackTitle = arguments[@"localizedFallbackTitle"] == [NSNull null] ? nil : arguments[@"localizedFallbackTitle"]; if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&authError]) { [context evaluatePolicy:kLAPolicyDeviceOwnerAuthentication localizedReason:arguments[@"localizedReason"] reply:^(BOOL success, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ [self handleAuthReplyWithSuccess:success error:error flutterArguments:arguments flutterResult:result]; }); }]; } else { [self handleErrors:authError flutterArguments:arguments withFlutterResult:result]; } } - (void)handleAuthReplyWithSuccess:(BOOL)success error:(NSError *)error flutterArguments:(NSDictionary *)arguments flutterResult:(FlutterResult)result { NSAssert([NSThread isMainThread], @"Response handling must be done on the main thread."); if (success) { result(@YES); } else { switch (error.code) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // TODO(stuartmorgan): Remove the pragma and s/TouchID/Biometry/ in these constants when // iOS 10 support is dropped. The values are the same, only the names have changed. case LAErrorTouchIDNotAvailable: case LAErrorTouchIDNotEnrolled: case LAErrorTouchIDLockout: #pragma clang diagnostic pop case LAErrorUserFallback: case LAErrorPasscodeNotSet: case LAErrorAuthenticationFailed: [self handleErrors:error flutterArguments:arguments withFlutterResult:result]; return; case LAErrorSystemCancel: if ([arguments[@"stickyAuth"] boolValue]) { self->_lastCallArgs = arguments; self->_lastResult = result; } else { result(@NO); } return; } [self handleErrors:error flutterArguments:arguments withFlutterResult:result]; } } - (void)handleErrors:(NSError *)authError flutterArguments:(NSDictionary *)arguments withFlutterResult:(FlutterResult)result { NSString *errorCode = @"NotAvailable"; switch (authError.code) { case LAErrorPasscodeNotSet: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // TODO(stuartmorgan): Remove the pragma and s/TouchID/Biometry/ in this constant when // iOS 10 support is dropped. The values are the same, only the names have changed. case LAErrorTouchIDNotEnrolled: #pragma clang diagnostic pop if ([arguments[@"useErrorDialogs"] boolValue]) { [self alertMessage:arguments[@"goToSettingDescriptionIOS"] firstButton:arguments[@"okButton"] flutterResult:result additionalButton:arguments[@"goToSetting"]]; return; } errorCode = authError.code == LAErrorPasscodeNotSet ? @"PasscodeNotSet" : @"NotEnrolled"; break; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // TODO(stuartmorgan): Remove the pragma and s/TouchID/Biometry/ in this constant when // iOS 10 support is dropped. The values are the same, only the names have changed. case LAErrorTouchIDLockout: #pragma clang diagnostic pop [self alertMessage:arguments[@"lockOut"] firstButton:arguments[@"okButton"] flutterResult:result additionalButton:nil]; return; } result([FlutterError errorWithCode:errorCode message:authError.localizedDescription details:authError.domain]); } #pragma mark - AppDelegate - (void)applicationDidBecomeActive:(UIApplication *)application { if (self.lastCallArgs != nil && self.lastResult != nil) { [self authenticateWithBiometrics:_lastCallArgs withFlutterResult:self.lastResult]; } } @end
plugins/packages/local_auth/local_auth_ios/ios/Classes/FLTLocalAuthPlugin.m/0
{ "file_path": "plugins/packages/local_auth/local_auth_ios/ios/Classes/FLTLocalAuthPlugin.m", "repo_id": "plugins", "token_count": 5227 }
1,268
name: local_auth_platform_interface description: A common platform interface for the local_auth plugin. repository: https://github.com/flutter/plugins/tree/main/packages/local_auth/local_auth_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%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: 1.0.6 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter plugin_platform_interface: ^2.1.2 dev_dependencies: flutter_test: sdk: flutter mockito: ^5.0.0
plugins/packages/local_auth/local_auth_platform_interface/pubspec.yaml/0
{ "file_path": "plugins/packages/local_auth/local_auth_platform_interface/pubspec.yaml", "repo_id": "plugins", "token_count": 262 }
1,269
# path_provider [![pub package](https://img.shields.io/pub/v/path_provider.svg)](https://pub.dev/packages/path_provider) A Flutter plugin for finding commonly used locations on the filesystem. Supports Android, iOS, Linux, macOS and Windows. Not all methods are supported on all platforms. | | Android | iOS | Linux | macOS | Windows | |-------------|---------|------|-------|--------|-------------| | **Support** | SDK 16+ | 9.0+ | Any | 10.11+ | Windows 10+ | ## Usage To use this plugin, add `path_provider` as a [dependency in your pubspec.yaml file](https://flutter.dev/docs/development/platform-integration/platform-channels). ## Example ```dart Directory tempDir = await getTemporaryDirectory(); String tempPath = tempDir.path; Directory appDocDir = await getApplicationDocumentsDirectory(); String appDocPath = appDocDir.path; ``` ## Supported platforms and paths Directories support by platform: | Directory | Android | iOS | Linux | macOS | Windows | | :--- | :---: | :---: | :---: | :---: | :---: | | Temporary | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | Application Support | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | Application Library | ❌️ | ✔️ | ❌️ | ✔️ | ❌️ | | Application Documents | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | External Storage | ✔️ | ❌ | ❌ | ❌️ | ❌️ | | External Cache Directories | ✔️ | ❌ | ❌ | ❌️ | ❌️ | | External Storage Directories | ✔️ | ❌ | ❌ | ❌️ | ❌️ | | Downloads | ❌ | ✔️ | ✔️ | ✔️ | ✔️ | ## Testing `path_provider` now uses a `PlatformInterface`, meaning that not all platforms share a single `PlatformChannel`-based implementation. With that change, tests should be updated to mock `PathProviderPlatform` rather than `PlatformChannel`. See this `path_provider` [test](https://github.com/flutter/plugins/blob/main/packages/path_provider/path_provider/test/path_provider_test.dart) for an example.
plugins/packages/path_provider/path_provider/README.md/0
{ "file_path": "plugins/packages/path_provider/path_provider/README.md", "repo_id": "plugins", "token_count": 612 }
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 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path_provider/path_provider.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('getTemporaryDirectory', (WidgetTester tester) async { final Directory result = await getTemporaryDirectory(); _verifySampleFile(result, 'temporaryDirectory'); }); testWidgets('getApplicationDocumentsDirectory', (WidgetTester tester) async { final Directory result = await getApplicationDocumentsDirectory(); _verifySampleFile(result, 'applicationDocuments'); }); testWidgets('getApplicationSupportDirectory', (WidgetTester tester) async { final Directory result = await getApplicationSupportDirectory(); _verifySampleFile(result, 'applicationSupport'); }); testWidgets('getLibraryDirectory', (WidgetTester tester) async { if (Platform.isIOS) { final Directory result = await getLibraryDirectory(); _verifySampleFile(result, 'library'); } else if (Platform.isAndroid) { final Future<Directory?> result = getLibraryDirectory(); expect(result, throwsA(isInstanceOf<UnsupportedError>())); } }); testWidgets('getExternalStorageDirectory', (WidgetTester tester) async { if (Platform.isIOS) { final Future<Directory?> result = getExternalStorageDirectory(); expect(result, throwsA(isInstanceOf<UnsupportedError>())); } else if (Platform.isAndroid) { final Directory? result = await getExternalStorageDirectory(); _verifySampleFile(result, 'externalStorage'); } }); testWidgets('getExternalCacheDirectories', (WidgetTester tester) async { if (Platform.isIOS) { final Future<List<Directory>?> result = getExternalCacheDirectories(); expect(result, throwsA(isInstanceOf<UnsupportedError>())); } else if (Platform.isAndroid) { final List<Directory>? directories = await getExternalCacheDirectories(); expect(directories, isNotNull); for (final Directory result in directories!) { _verifySampleFile(result, 'externalCache'); } } }); final List<StorageDirectory?> allDirs = <StorageDirectory?>[ null, StorageDirectory.music, StorageDirectory.podcasts, StorageDirectory.ringtones, StorageDirectory.alarms, StorageDirectory.notifications, StorageDirectory.pictures, StorageDirectory.movies, ]; for (final StorageDirectory? type in allDirs) { testWidgets('getExternalStorageDirectories (type: $type)', (WidgetTester tester) async { if (Platform.isIOS) { final Future<List<Directory>?> result = getExternalStorageDirectories(); expect(result, throwsA(isInstanceOf<UnsupportedError>())); } else if (Platform.isAndroid) { final List<Directory>? directories = await getExternalStorageDirectories(type: type); expect(directories, isNotNull); for (final Directory result in directories!) { _verifySampleFile(result, '$type'); } } }); } testWidgets('getDownloadsDirectory', (WidgetTester tester) async { if (Platform.isAndroid) { final Future<Directory?> result = getDownloadsDirectory(); expect(result, throwsA(isInstanceOf<UnsupportedError>())); } else { final Directory? result = await getDownloadsDirectory(); // On recent versions of macOS, actually using the downloads directory // requires a user prompt (so will fail on CI), and on some platforms the // directory may not exist. Instead of verifying that it exists, just // check that it returned a path. expect(result?.path, isNotEmpty); } }); } /// Verify a file called [name] in [directory] by recreating it with test /// contents when necessary. void _verifySampleFile(Directory? directory, String name) { expect(directory, isNotNull); if (directory == null) { return; } final File file = File('${directory.path}/$name'); if (file.existsSync()) { file.deleteSync(); expect(file.existsSync(), isFalse); } file.writeAsStringSync('Hello world!'); expect(file.readAsStringSync(), 'Hello world!'); expect(directory.listSync(), isNotEmpty); file.deleteSync(); }
plugins/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart/0
{ "file_path": "plugins/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart", "repo_id": "plugins", "token_count": 1456 }
1,271
// 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 (v3.2.0), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.pathprovider; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"}) public class Messages { public enum StorageDirectory { root(0), music(1), podcasts(2), ringtones(3), alarms(4), notifications(5), pictures(6), movies(7), downloads(8), dcim(9), documents(10); private int index; private StorageDirectory(final int index) { this.index = index; } } private static class PathProviderApiCodec extends StandardMessageCodec { public static final PathProviderApiCodec INSTANCE = new PathProviderApiCodec(); private PathProviderApiCodec() {} } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface PathProviderApi { @Nullable String getTemporaryPath(); @Nullable String getApplicationSupportPath(); @Nullable String getApplicationDocumentsPath(); @Nullable String getExternalStoragePath(); @NonNull List<String> getExternalCachePaths(); @NonNull List<String> getExternalStoragePaths(@NonNull StorageDirectory directory); /** The codec used by PathProviderApi. */ static MessageCodec<Object> getCodec() { return PathProviderApiCodec.INSTANCE; } /** * Sets up an instance of `PathProviderApi` to handle messages through the `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, PathProviderApi api) { { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PathProviderApi.getTemporaryPath", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { String output = api.getTemporaryPath(); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PathProviderApi.getApplicationSupportPath", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { String output = api.getApplicationSupportPath(); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PathProviderApi.getApplicationDocumentsPath", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { String output = api.getApplicationDocumentsPath(); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PathProviderApi.getExternalStoragePath", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { String output = api.getExternalStoragePath(); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PathProviderApi.getExternalCachePaths", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { List<String> output = api.getExternalCachePaths(); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue(); BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PathProviderApi.getExternalStoragePaths", getCodec(), taskQueue); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; StorageDirectory directoryArg = args.get(0) == null ? null : StorageDirectory.values()[(int) args.get(0)]; if (directoryArg == null) { throw new NullPointerException("directoryArg unexpectedly null."); } List<String> output = api.getExternalStoragePaths(directoryArg); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static Map<String, Object> wrapError(Throwable exception) { Map<String, Object> errorMap = new HashMap<>(); errorMap.put("message", exception.toString()); errorMap.put("code", exception.getClass().getSimpleName()); errorMap.put( "details", "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); return errorMap; } }
plugins/packages/path_provider/path_provider_android/android/src/main/java/io/flutter/plugins/pathprovider/Messages.java/0
{ "file_path": "plugins/packages/path_provider/path_provider_android/android/src/main/java/io/flutter/plugins/pathprovider/Messages.java", "repo_id": "plugins", "token_count": 3903 }
1,272
org.gradle.jvmargs=-Xmx4G android.enableR8=true android.useAndroidX=true android.enableJetifier=true
plugins/packages/path_provider/path_provider_android/example/android/gradle.properties/0
{ "file_path": "plugins/packages/path_provider/path_provider_android/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,273
## NEXT * Updates minimum supported Flutter version to 3.0. ## 2.1.1 * Fixes a regression in the path retured by `getApplicationSupportDirectory` on iOS. ## 2.1.0 * Renames the package previously published as [`path_provider_macos`](https://pub.dev/packages/path_provider_macos) * Adds iOS support.
plugins/packages/path_provider/path_provider_foundation/CHANGELOG.md/0
{ "file_path": "plugins/packages/path_provider/path_provider_foundation/CHANGELOG.md", "repo_id": "plugins", "token_count": 99 }
1,274
// 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:path_provider_platform_interface/path_provider_platform_interface.dart'; void main() { runApp(const MyApp()); } /// Sample app class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String? _tempDirectory = 'Unknown'; String? _downloadsDirectory = 'Unknown'; String? _libraryDirectory = 'Unknown'; String? _appSupportDirectory = 'Unknown'; String? _documentsDirectory = 'Unknown'; @override void initState() { super.initState(); initDirectories(); } // Platform messages are asynchronous, so we initialize in an async method. Future<void> initDirectories() async { String? tempDirectory; String? downloadsDirectory; String? appSupportDirectory; String? libraryDirectory; String? documentsDirectory; final PathProviderPlatform provider = PathProviderPlatform.instance; try { tempDirectory = await provider.getTemporaryPath(); } catch (exception) { tempDirectory = 'Failed to get temp directory: $exception'; } try { downloadsDirectory = await provider.getDownloadsPath(); } catch (exception) { downloadsDirectory = 'Failed to get downloads directory: $exception'; } try { documentsDirectory = await provider.getApplicationDocumentsPath(); } catch (exception) { documentsDirectory = 'Failed to get documents directory: $exception'; } try { libraryDirectory = await provider.getLibraryPath(); } catch (exception) { libraryDirectory = 'Failed to get library directory: $exception'; } try { appSupportDirectory = await provider.getApplicationSupportPath(); } catch (exception) { appSupportDirectory = 'Failed to get app support directory: $exception'; } setState(() { _tempDirectory = tempDirectory; _downloadsDirectory = downloadsDirectory; _libraryDirectory = libraryDirectory; _appSupportDirectory = appSupportDirectory; _documentsDirectory = documentsDirectory; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Path Provider example app'), ), body: Center( child: Column( children: <Widget>[ Text('Temp Directory: $_tempDirectory\n'), Text('Documents Directory: $_documentsDirectory\n'), Text('Downloads Directory: $_downloadsDirectory\n'), Text('Library Directory: $_libraryDirectory\n'), Text('Application Support Directory: $_appSupportDirectory\n'), ], ), ), ), ); } }
plugins/packages/path_provider/path_provider_foundation/example/lib/main.dart/0
{ "file_path": "plugins/packages/path_provider/path_provider_foundation/example/lib/main.dart", "repo_id": "plugins", "token_count": 1052 }
1,275
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'path_provider_foundation' s.version = '0.0.1' s.summary = 'An iOS and macOS implementation of the path_provider plugin.' s.description = <<-DESC An iOS and macOS implementation of the Flutter plugin for getting commonly used locations on the filesystem. DESC s.homepage = 'https://github.com/flutter/plugins/tree/main/packages/path_provider/path_provider_foundation' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/path_provider/path_provider_foundation' } s.source_files = 'Classes/**/*' s.ios.dependency 'Flutter' s.osx.dependency 'FlutterMacOS' s.ios.deployment_target = '9.0' s.osx.deployment_target = '10.11' s.ios.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift', 'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift', } s.swift_version = '5.0' end
plugins/packages/path_provider/path_provider_foundation/ios/path_provider_foundation.podspec/0
{ "file_path": "plugins/packages/path_provider/path_provider_foundation/ios/path_provider_foundation.podspec", "repo_id": "plugins", "token_count": 535 }
1,276
## 2.1.8 * Adds compatibility with `xdg_directories` 1.0. * Updates minimum Flutter version to 3.0. ## 2.1.7 * Bumps ffi dependency to match path_provider_windows. ## 2.1.6 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.1.5 * Removes dependency on `meta`. ## 2.1.4 * Fixes `getApplicationSupportPath` handling of applications where the application ID is not set. ## 2.1.3 * Change getApplicationSupportPath from using executable name to application ID (if provided). * If the executable name based directory exists, continue to use that so existing applications continue with the same behaviour. ## 2.1.2 * Fixes link in README. ## 2.1.1 * Removed obsolete `pluginClass: none` from pubpsec. ## 2.1.0 * Now `getTemporaryPath` returns the value of the `TMPDIR` environment variable primarily. If `TMPDIR` is not set, `/tmp` is returned. ## 2.0.2 * Updated installation instructions in README. ## 2.0.1 * Add `implements` to pubspec.yaml. * Add `registerWith` method to the main Dart class. ## 2.0.0 * Migrate to null safety. ## 0.1.1+3 * Update Flutter SDK constraint. ## 0.1.1+2 * Log errors in the example when calls to the `path_provider` fail. ## 0.1.1+1 * Check in linux/ directory for example/ ## 0.1.1 - NOT PUBLISHED * Reverts changes on 0.1.0, which broke the tree. ## 0.1.0 - NOT PUBLISHED * This release updates getApplicationSupportPath to use the application ID instead of the executable name. * No migration is provided, so any older apps that were using this path will now have a different directory. ## 0.0.1+2 * This release updates the example to depend on the endorsed plugin rather than relative path ## 0.0.1+1 * This updates the readme and pubspec and example to reflect the endorsement of this implementation of `path_provider` ## 0.0.1 * The initial implementation of path\_provider for Linux * Implements getApplicationSupportPath, getApplicationDocumentsPath, getDownloadsPath, and getTemporaryPath
plugins/packages/path_provider/path_provider_linux/CHANGELOG.md/0
{ "file_path": "plugins/packages/path_provider/path_provider_linux/CHANGELOG.md", "repo_id": "plugins", "token_count": 646 }
1,277
name: path_provider_platform_interface description: A common platform interface for the path_provider plugin. repository: https://github.com/flutter/plugins/tree/main/packages/path_provider/path_provider_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%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.0.5 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter platform: ^3.0.0 plugin_platform_interface: ^2.1.0 dev_dependencies: flutter_test: sdk: flutter
plugins/packages/path_provider/path_provider_platform_interface/pubspec.yaml/0
{ "file_path": "plugins/packages/path_provider/path_provider_platform_interface/pubspec.yaml", "repo_id": "plugins", "token_count": 266 }
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. import XCTest private let elementWaitingTime: TimeInterval = 30 class RunnerUITests: XCTestCase { private var exampleApp: XCUIApplication! override func setUp() { super.setUp() self.continueAfterFailure = false exampleApp = XCUIApplication() } override func tearDown() { super.tearDown() exampleApp.terminate() exampleApp = nil } func testQuickActionWithFreshStart() { let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") let quickActionsAppIcon = springboard.icons["quick_actions_example"] if !quickActionsAppIcon.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the example app from springboard with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } quickActionsAppIcon.press(forDuration: 2) let actionTwo = springboard.buttons["Action two"] if !actionTwo.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the actionTwo button from springboard with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } actionTwo.tap() let actionTwoConfirmation = exampleApp.otherElements["action_two"] if !actionTwoConfirmation.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the actionTwoConfirmation in the app with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } XCTAssert(actionTwoConfirmation.exists) } func testQuickActionWhenAppIsInBackground() { exampleApp.launch() let actionsReady = exampleApp.otherElements["actions ready"] if !actionsReady.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the actionsReady in the app with \(elementWaitingTime) seconds. App debug description: \(exampleApp.debugDescription)" ) } XCUIDevice.shared.press(.home) let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") let quickActionsAppIcon = springboard.icons["quick_actions_example"] if !quickActionsAppIcon.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the example app from springboard with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } quickActionsAppIcon.press(forDuration: 2) let actionOne = springboard.buttons["Action one"] if !actionOne.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the actionOne button from springboard with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } actionOne.tap() let actionOneConfirmation = exampleApp.otherElements["action_one"] if !actionOneConfirmation.waitForExistence(timeout: elementWaitingTime) { XCTFail( "Failed due to not able to find the actionOneConfirmation in the app with \(elementWaitingTime) seconds. Springboard debug description: \(springboard.debugDescription)" ) } XCTAssert(actionOneConfirmation.exists) } }
plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerUITests/RunnerUITests.swift/0
{ "file_path": "plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerUITests/RunnerUITests.swift", "repo_id": "plugins", "token_count": 1137 }
1,279
# quick_actions_platform_interface A common platform interface for the [`quick_actions`][1] plugin. This interface allows platform-specific implementations of the `quick_actions` plugin, as well as the plugin itself, to ensure they are supporting the same interface. # Usage To implement a new platform-specific implementation of `quick_actions`, extend [`QuickActionsPlatform`][2] with an implementation that performs the platform-specific behavior, and when you register your plugin, set the default `QuickActionsPlatform` by calling `QuickActionsPlatform.instance = MyPlatformQuickActions()`. # 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]: ../quick_actions [2]: lib/quick_actions_platform_interface.dart
plugins/packages/quick_actions/quick_actions_platform_interface/README.md/0
{ "file_path": "plugins/packages/quick_actions/quick_actions_platform_interface/README.md", "repo_id": "plugins", "token_count": 240 }
1,280
# shared_preferences_example Demonstrates how to use the shared_preferences plugin.
plugins/packages/shared_preferences/shared_preferences/example/README.md/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences/example/README.md", "repo_id": "plugins", "token_count": 25 }
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. // ignore_for_file: public_member_api_docs import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( title: 'SharedPreferences Demo', home: SharedPreferencesDemo(), ); } } class SharedPreferencesDemo extends StatefulWidget { const SharedPreferencesDemo({Key? key}) : super(key: key); @override SharedPreferencesDemoState createState() => SharedPreferencesDemoState(); } class SharedPreferencesDemoState extends State<SharedPreferencesDemo> { final Future<SharedPreferences> _prefs = SharedPreferences.getInstance(); late Future<int> _counter; Future<void> _incrementCounter() async { final SharedPreferences prefs = await _prefs; final int counter = (prefs.getInt('counter') ?? 0) + 1; setState(() { _counter = prefs.setInt('counter', counter).then((bool success) { return counter; }); }); } @override void initState() { super.initState(); _counter = _prefs.then((SharedPreferences prefs) { return prefs.getInt('counter') ?? 0; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('SharedPreferences Demo'), ), body: Center( child: FutureBuilder<int>( future: _counter, builder: (BuildContext context, AsyncSnapshot<int> snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: return const CircularProgressIndicator(); case ConnectionState.active: case ConnectionState.done: if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return Text( 'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n' 'This should persist across restarts.', ); } } })), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
plugins/packages/shared_preferences/shared_preferences/example/lib/main.dart/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences/example/lib/main.dart", "repo_id": "plugins", "token_count": 1143 }
1,282
## NEXT * Updates minimum Flutter version to 3.0. ## 2.0.15 * Updates code for stricter lint checks. ## 2.0.14 * Fixes typo in `SharedPreferencesAndroid` docs. * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 2.0.13 * Updates gradle to 7.2.2. * Updates minimum Flutter version to 2.10. ## 2.0.12 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.0.11 * Switches to an in-package method channel implementation. ## 2.0.10 * Removes dependency on `meta`. ## 2.0.9 * Updates compileSdkVersion to 31. ## 2.0.8 * Split from `shared_preferences` as a federated implementation.
plugins/packages/shared_preferences/shared_preferences_android/CHANGELOG.md/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_android/CHANGELOG.md", "repo_id": "plugins", "token_count": 248 }
1,283
# shared_preferences_platform_interface A common platform interface for the [`shared_preferences`][1] plugin. This interface allows platform-specific implementations of the `shared_preferences` plugin, as well as the plugin itself, to ensure they are supporting the same interface. # Usage To implement a new platform-specific implementation of `shared_preferences`, extend [`SharedPreferencesPlatform`][2] with an implementation that performs the platform-specific behavior, and when you register your plugin, set the default `SharedPreferencesLoader` by calling the `SharedPreferencesPlatform.loader` setter. # 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]: ../shared_preferences [2]: lib/shared_preferences_platform_interface.dart
plugins/packages/shared_preferences/shared_preferences_platform_interface/README.md/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_platform_interface/README.md", "repo_id": "plugins", "token_count": 251 }
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. // Provides a String-based alterantive to the Uri-based primary API. // // This is provided as a separate import because it's much easier to use // incorrectly, so should require explicit opt-in (to avoid issues such as // IDE auto-complete to the more error-prone APIs just by importing the // main API). export 'src/types.dart'; export 'src/url_launcher_string.dart';
plugins/packages/url_launcher/url_launcher/lib/url_launcher_string.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher/lib/url_launcher_string.dart", "repo_id": "plugins", "token_count": 143 }
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. package io.flutter.plugins.urllauncher; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; /** * Plugin implementation that uses the new {@code io.flutter.embedding} package. * * <p>Instantiate this in an add to app scenario to gracefully handle activity and context changes. */ public final class UrlLauncherPlugin implements FlutterPlugin, ActivityAware { private static final String TAG = "UrlLauncherPlugin"; @Nullable private MethodCallHandlerImpl methodCallHandler; @Nullable private UrlLauncher urlLauncher; /** * Registers a plugin implementation that uses the stable {@code io.flutter.plugin.common} * package. * * <p>Calling this automatically initializes the plugin. However plugins initialized this way * won't react to changes in activity or context, unlike {@link UrlLauncherPlugin}. */ @SuppressWarnings("deprecation") public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) { MethodCallHandlerImpl handler = new MethodCallHandlerImpl(new UrlLauncher(registrar.context(), registrar.activity())); handler.startListening(registrar.messenger()); } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { urlLauncher = new UrlLauncher(binding.getApplicationContext(), /*activity=*/ null); methodCallHandler = new MethodCallHandlerImpl(urlLauncher); methodCallHandler.startListening(binding.getBinaryMessenger()); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { if (methodCallHandler == null) { Log.wtf(TAG, "Already detached from the engine."); return; } methodCallHandler.stopListening(); methodCallHandler = null; urlLauncher = null; } @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { if (methodCallHandler == null) { Log.wtf(TAG, "urlLauncher was never set."); return; } urlLauncher.setActivity(binding.getActivity()); } @Override public void onDetachedFromActivity() { if (methodCallHandler == null) { Log.wtf(TAG, "urlLauncher was never set."); return; } urlLauncher.setActivity(null); } @Override public void onDetachedFromActivityForConfigChanges() { onDetachedFromActivity(); } @Override public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { onAttachedToActivity(binding); } }
plugins/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/UrlLauncherPlugin.java/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/UrlLauncherPlugin.java", "repo_id": "plugins", "token_count": 891 }
1,286
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true android.enableR8=true
plugins/packages/url_launcher/url_launcher_android/example/android/gradle.properties/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_android/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
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:async'; import 'package:flutter/services.dart'; import 'package:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/url_launcher_linux'); /// An implementation of [UrlLauncherPlatform] for Linux. class UrlLauncherLinux extends UrlLauncherPlatform { /// Registers this class as the default instance of [UrlLauncherPlatform]. static void registerWith() { UrlLauncherPlatform.instance = UrlLauncherLinux(); } @override final LinkDelegate? linkDelegate = null; @override Future<bool> canLaunch(String url) { return _channel.invokeMethod<bool>( 'canLaunch', <String, Object>{'url': url}, ).then((bool? value) => value ?? false); } @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, }) { return _channel.invokeMethod<bool>( 'launch', <String, Object>{ 'url': url, 'enableJavaScript': enableJavaScript, 'enableDomStorage': enableDomStorage, 'universalLinksOnly': universalLinksOnly, 'headers': headers, }, ).then((bool? value) => value ?? false); } }
plugins/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart", "repo_id": "plugins", "token_count": 550 }
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. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher_macos/url_launcher_macos.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$UrlLauncherMacOS', () { const MethodChannel channel = MethodChannel('plugins.flutter.io/url_launcher_macos'); final List<MethodCall> log = <MethodCall>[]; _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { log.add(methodCall); // Return null explicitly instead of relying on the implicit null // returned by the method channel if no return statement is specified. return null; }); tearDown(() { log.clear(); }); test('registers instance', () { UrlLauncherMacOS.registerWith(); expect(UrlLauncherPlatform.instance, isA<UrlLauncherMacOS>()); }); test('canLaunch', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(); await launcher.canLaunch('http://example.com/'); expect( log, <Matcher>[ isMethodCall('canLaunch', arguments: <String, Object>{ 'url': 'http://example.com/', }) ], ); }); test('canLaunch should return false if platform returns null', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(); final bool canLaunch = await launcher.canLaunch('http://example.com/'); expect(canLaunch, false); }); test('launch', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'enableJavaScript': false, 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': <String, String>{}, }) ], ); }); test('launch with headers', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{'key': 'value'}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'enableJavaScript': false, 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': <String, String>{'key': 'value'}, }) ], ); }); test('launch universal links only', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(); await launcher.launch( 'http://example.com/', useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: true, headers: const <String, String>{}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'enableJavaScript': false, 'enableDomStorage': false, 'universalLinksOnly': true, 'headers': <String, String>{}, }) ], ); }); test('launch should return false if platform returns null', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(); final bool launched = await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect(launched, false); }); }); } /// 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/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart", "repo_id": "plugins", "token_count": 1980 }
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. // Autogenerated from Pigeon (v5.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon #undef _HAS_EXCEPTIONS #include "messages.g.h" #include <flutter/basic_message_channel.h> #include <flutter/binary_messenger.h> #include <flutter/encodable_value.h> #include <flutter/standard_message_codec.h> #include <map> #include <optional> #include <string> namespace url_launcher_windows { /// The codec used by UrlLauncherApi. const flutter::StandardMessageCodec& UrlLauncherApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &flutter::StandardCodecSerializer::GetInstance()); } // Sets up an instance of `UrlLauncherApi` to handle messages through the // `binary_messenger`. void UrlLauncherApi::SetUp(flutter::BinaryMessenger* binary_messenger, UrlLauncherApi* api) { { auto channel = std::make_unique<flutter::BasicMessageChannel<flutter::EncodableValue>>( binary_messenger, "dev.flutter.pigeon.UrlLauncherApi.canLaunchUrl", &GetCodec()); if (api != nullptr) { channel->SetMessageHandler( [api](const flutter::EncodableValue& message, const flutter::MessageReply<flutter::EncodableValue>& reply) { try { const auto& args = std::get<flutter::EncodableList>(message); const auto& encodable_url_arg = args.at(0); if (encodable_url_arg.IsNull()) { reply(WrapError("url_arg unexpectedly null.")); return; } const auto& url_arg = std::get<std::string>(encodable_url_arg); ErrorOr<bool> output = api->CanLaunchUrl(url_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } flutter::EncodableList wrapped; wrapped.push_back( flutter::EncodableValue(std::move(output).TakeValue())); reply(flutter::EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel->SetMessageHandler(nullptr); } } { auto channel = std::make_unique<flutter::BasicMessageChannel<flutter::EncodableValue>>( binary_messenger, "dev.flutter.pigeon.UrlLauncherApi.launchUrl", &GetCodec()); if (api != nullptr) { channel->SetMessageHandler( [api](const flutter::EncodableValue& message, const flutter::MessageReply<flutter::EncodableValue>& reply) { try { const auto& args = std::get<flutter::EncodableList>(message); const auto& encodable_url_arg = args.at(0); if (encodable_url_arg.IsNull()) { reply(WrapError("url_arg unexpectedly null.")); return; } const auto& url_arg = std::get<std::string>(encodable_url_arg); std::optional<FlutterError> output = api->LaunchUrl(url_arg); if (output.has_value()) { reply(WrapError(output.value())); return; } flutter::EncodableList wrapped; wrapped.push_back(flutter::EncodableValue()); reply(flutter::EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel->SetMessageHandler(nullptr); } } } flutter::EncodableValue UrlLauncherApi::WrapError( std::string_view error_message) { return flutter::EncodableValue(flutter::EncodableList{ flutter::EncodableValue(std::string(error_message)), flutter::EncodableValue("Error"), flutter::EncodableValue()}); } flutter::EncodableValue UrlLauncherApi::WrapError(const FlutterError& error) { return flutter::EncodableValue(flutter::EncodableList{ flutter::EncodableValue(error.message()), flutter::EncodableValue(error.code()), error.details()}); } } // namespace url_launcher_windows
plugins/packages/url_launcher/url_launcher_windows/windows/messages.g.cpp/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_windows/windows/messages.g.cpp", "repo_id": "plugins", "token_count": 1958 }
1,290
## Updating pigeon-generated files If you update files in the pigeons/ directory, run the following command in this directory: ```bash flutter pub upgrade flutter pub run pigeon --input pigeons/messages.dart # git commit your changes so that your working environment is clean (cd ../../../; ./script/tool_runner.sh format --clang-format=clang-format-7) ``` If you update pigeon itself and want to test the changes here, temporarily update the pubspec.yaml by adding the following to the `dependency_overrides` section, assuming you have checked out the `flutter/packages` repo in a sibling directory to the `plugins` repo: ```yaml pigeon: path: ../../../../packages/packages/pigeon/ ``` Then, run the commands above. When you run `pub get` it should warn you that you're using an override. If you do this, you will need to publish pigeon before you can land the updates to this package, since the CI tests run the analysis using latest published version of pigeon, not your version or the version on `main`. In either case, the configuration will be obtained automatically from the `pigeons/messages.dart` file (see `ConfigurePigeon` at the top of that file).
plugins/packages/video_player/video_player_android/CONTRIBUTING.md/0
{ "file_path": "plugins/packages/video_player/video_player_android/CONTRIBUTING.md", "repo_id": "plugins", "token_count": 330 }
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 AVFoundation; @import video_player_avfoundation; @import XCTest; #import <OCMock/OCMock.h> #import <video_player_avfoundation/AVAssetTrackUtils.h> @interface FLTVideoPlayer : NSObject <FlutterStreamHandler> @property(readonly, nonatomic) AVPlayer *player; @property(readonly, nonatomic) AVPlayerLayer *playerLayer; @end @interface FLTVideoPlayerPlugin (Test) <FLTAVFoundationVideoPlayerApi> @property(readonly, strong, nonatomic) NSMutableDictionary<NSNumber *, FLTVideoPlayer *> *playersByTextureId; @end @interface FakeAVAssetTrack : AVAssetTrack @property(readonly, nonatomic) CGAffineTransform preferredTransform; @property(readonly, nonatomic) CGSize naturalSize; @property(readonly, nonatomic) UIImageOrientation orientation; - (instancetype)initWithOrientation:(UIImageOrientation)orientation; @end @implementation FakeAVAssetTrack - (instancetype)initWithOrientation:(UIImageOrientation)orientation { _orientation = orientation; _naturalSize = CGSizeMake(800, 600); return self; } - (CGAffineTransform)preferredTransform { switch (_orientation) { case UIImageOrientationUp: return CGAffineTransformMake(1, 0, 0, 1, 0, 0); case UIImageOrientationDown: return CGAffineTransformMake(-1, 0, 0, -1, 0, 0); case UIImageOrientationLeft: return CGAffineTransformMake(0, -1, 1, 0, 0, 0); case UIImageOrientationRight: return CGAffineTransformMake(0, 1, -1, 0, 0, 0); case UIImageOrientationUpMirrored: return CGAffineTransformMake(-1, 0, 0, 1, 0, 0); case UIImageOrientationDownMirrored: return CGAffineTransformMake(1, 0, 0, -1, 0, 0); case UIImageOrientationLeftMirrored: return CGAffineTransformMake(0, -1, -1, 0, 0, 0); case UIImageOrientationRightMirrored: return CGAffineTransformMake(0, 1, 1, 0, 0, 0); } } @end @interface VideoPlayerTests : XCTestCase @end @implementation VideoPlayerTests - (void)testBlankVideoBugWithEncryptedVideoStreamAndInvertedAspectRatioBugForSomeVideoStream { // This is to fix 2 bugs: 1. blank video for encrypted video streams on iOS 16 // (https://github.com/flutter/flutter/issues/111457) and 2. swapped width and height for some // video streams (not just iOS 16). (https://github.com/flutter/flutter/issues/109116). An // invisible AVPlayerLayer is used to overwrite the protection of pixel buffers in those streams // for issue #1, and restore the correct width and height for issue #2. NSObject<FlutterPluginRegistry> *registry = (NSObject<FlutterPluginRegistry> *)[[UIApplication sharedApplication] delegate]; NSObject<FlutterPluginRegistrar> *registrar = [registry registrarForPlugin:@"testPlayerLayerWorkaround"]; FLTVideoPlayerPlugin *videoPlayerPlugin = [[FLTVideoPlayerPlugin alloc] initWithRegistrar:registrar]; FlutterError *error; [videoPlayerPlugin initialize:&error]; XCTAssertNil(error); FLTCreateMessage *create = [FLTCreateMessage makeWithAsset:nil uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4" packageName:nil formatHint:nil httpHeaders:@{}]; FLTTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error]; XCTAssertNil(error); XCTAssertNotNil(textureMessage); FLTVideoPlayer *player = videoPlayerPlugin.playersByTextureId[textureMessage.textureId]; XCTAssertNotNil(player); XCTAssertNotNil(player.playerLayer, @"AVPlayerLayer should be present."); XCTAssertNotNil(player.playerLayer.superlayer, @"AVPlayerLayer should be added on screen."); } - (void)testSeekToInvokesTextureFrameAvailableOnTextureRegistry { NSObject<FlutterTextureRegistry> *mockTextureRegistry = OCMProtocolMock(@protocol(FlutterTextureRegistry)); NSObject<FlutterPluginRegistry> *registry = (NSObject<FlutterPluginRegistry> *)[[UIApplication sharedApplication] delegate]; NSObject<FlutterPluginRegistrar> *registrar = [registry registrarForPlugin:@"SeekToInvokestextureFrameAvailable"]; NSObject<FlutterPluginRegistrar> *partialRegistrar = OCMPartialMock(registrar); OCMStub([partialRegistrar textures]).andReturn(mockTextureRegistry); FLTVideoPlayerPlugin *videoPlayerPlugin = (FLTVideoPlayerPlugin *)[[FLTVideoPlayerPlugin alloc] initWithRegistrar:partialRegistrar]; FLTPositionMessage *message = [FLTPositionMessage makeWithTextureId:@101 position:@0]; FlutterError *error; [videoPlayerPlugin seekTo:message error:&error]; OCMVerify([mockTextureRegistry textureFrameAvailable:message.textureId.intValue]); } - (void)testDeregistersFromPlayer { NSObject<FlutterPluginRegistry> *registry = (NSObject<FlutterPluginRegistry> *)[[UIApplication sharedApplication] delegate]; NSObject<FlutterPluginRegistrar> *registrar = [registry registrarForPlugin:@"testDeregistersFromPlayer"]; FLTVideoPlayerPlugin *videoPlayerPlugin = (FLTVideoPlayerPlugin *)[[FLTVideoPlayerPlugin alloc] initWithRegistrar:registrar]; FlutterError *error; [videoPlayerPlugin initialize:&error]; XCTAssertNil(error); FLTCreateMessage *create = [FLTCreateMessage makeWithAsset:nil uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4" packageName:nil formatHint:nil httpHeaders:@{}]; FLTTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error]; XCTAssertNil(error); XCTAssertNotNil(textureMessage); FLTVideoPlayer *player = videoPlayerPlugin.playersByTextureId[textureMessage.textureId]; XCTAssertNotNil(player); AVPlayer *avPlayer = player.player; [videoPlayerPlugin dispose:textureMessage error:&error]; XCTAssertEqual(videoPlayerPlugin.playersByTextureId.count, 0); XCTAssertNil(error); [self keyValueObservingExpectationForObject:avPlayer keyPath:@"currentItem" expectedValue:nil]; [self waitForExpectationsWithTimeout:30.0 handler:nil]; } - (void)testVideoControls { NSObject<FlutterPluginRegistry> *registry = (NSObject<FlutterPluginRegistry> *)[[UIApplication sharedApplication] delegate]; NSObject<FlutterPluginRegistrar> *registrar = [registry registrarForPlugin:@"TestVideoControls"]; FLTVideoPlayerPlugin *videoPlayerPlugin = (FLTVideoPlayerPlugin *)[[FLTVideoPlayerPlugin alloc] initWithRegistrar:registrar]; NSDictionary<NSString *, id> *videoInitialization = [self testPlugin:videoPlayerPlugin uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"]; XCTAssertEqualObjects(videoInitialization[@"height"], @720); XCTAssertEqualObjects(videoInitialization[@"width"], @1280); XCTAssertEqualWithAccuracy([videoInitialization[@"duration"] intValue], 4000, 200); } - (void)testAudioControls { NSObject<FlutterPluginRegistry> *registry = (NSObject<FlutterPluginRegistry> *)[[UIApplication sharedApplication] delegate]; NSObject<FlutterPluginRegistrar> *registrar = [registry registrarForPlugin:@"TestAudioControls"]; FLTVideoPlayerPlugin *videoPlayerPlugin = (FLTVideoPlayerPlugin *)[[FLTVideoPlayerPlugin alloc] initWithRegistrar:registrar]; NSDictionary<NSString *, id> *audioInitialization = [self testPlugin:videoPlayerPlugin uri:@"https://flutter.github.io/assets-for-api-docs/assets/audio/rooster.mp3"]; XCTAssertEqualObjects(audioInitialization[@"height"], @0); XCTAssertEqualObjects(audioInitialization[@"width"], @0); // Perfect precision not guaranteed. XCTAssertEqualWithAccuracy([audioInitialization[@"duration"] intValue], 5400, 200); } - (void)testHLSControls { NSObject<FlutterPluginRegistry> *registry = (NSObject<FlutterPluginRegistry> *)[[UIApplication sharedApplication] delegate]; NSObject<FlutterPluginRegistrar> *registrar = [registry registrarForPlugin:@"TestHLSControls"]; FLTVideoPlayerPlugin *videoPlayerPlugin = (FLTVideoPlayerPlugin *)[[FLTVideoPlayerPlugin alloc] initWithRegistrar:registrar]; NSDictionary<NSString *, id> *videoInitialization = [self testPlugin:videoPlayerPlugin uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8"]; XCTAssertEqualObjects(videoInitialization[@"height"], @720); XCTAssertEqualObjects(videoInitialization[@"width"], @1280); XCTAssertEqualWithAccuracy([videoInitialization[@"duration"] intValue], 4000, 200); } - (void)testTransformFix { [self validateTransformFixForOrientation:UIImageOrientationUp]; [self validateTransformFixForOrientation:UIImageOrientationDown]; [self validateTransformFixForOrientation:UIImageOrientationLeft]; [self validateTransformFixForOrientation:UIImageOrientationRight]; [self validateTransformFixForOrientation:UIImageOrientationUpMirrored]; [self validateTransformFixForOrientation:UIImageOrientationDownMirrored]; [self validateTransformFixForOrientation:UIImageOrientationLeftMirrored]; [self validateTransformFixForOrientation:UIImageOrientationRightMirrored]; } - (NSDictionary<NSString *, id> *)testPlugin:(FLTVideoPlayerPlugin *)videoPlayerPlugin uri:(NSString *)uri { FlutterError *error; [videoPlayerPlugin initialize:&error]; XCTAssertNil(error); FLTCreateMessage *create = [FLTCreateMessage makeWithAsset:nil uri:uri packageName:nil formatHint:nil httpHeaders:@{}]; FLTTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error]; NSNumber *textureId = textureMessage.textureId; FLTVideoPlayer *player = videoPlayerPlugin.playersByTextureId[textureId]; XCTAssertNotNil(player); XCTestExpectation *initializedExpectation = [self expectationWithDescription:@"initialized"]; __block NSDictionary<NSString *, id> *initializationEvent; [player onListenWithArguments:nil eventSink:^(NSDictionary<NSString *, id> *event) { if ([event[@"event"] isEqualToString:@"initialized"]) { initializationEvent = event; XCTAssertEqual(event.count, 4); [initializedExpectation fulfill]; } }]; [self waitForExpectationsWithTimeout:30.0 handler:nil]; // Starts paused. AVPlayer *avPlayer = player.player; XCTAssertEqual(avPlayer.rate, 0); XCTAssertEqual(avPlayer.volume, 1); XCTAssertEqual(avPlayer.timeControlStatus, AVPlayerTimeControlStatusPaused); // Change playback speed. FLTPlaybackSpeedMessage *playback = [FLTPlaybackSpeedMessage makeWithTextureId:textureId speed:@2]; [videoPlayerPlugin setPlaybackSpeed:playback error:&error]; XCTAssertNil(error); XCTAssertEqual(avPlayer.rate, 2); XCTAssertEqual(avPlayer.timeControlStatus, AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate); // Volume FLTVolumeMessage *volume = [FLTVolumeMessage makeWithTextureId:textureId volume:@0.1]; [videoPlayerPlugin setVolume:volume error:&error]; XCTAssertNil(error); XCTAssertEqual(avPlayer.volume, 0.1f); [player onCancelWithArguments:nil]; return initializationEvent; } - (void)validateTransformFixForOrientation:(UIImageOrientation)orientation { AVAssetTrack *track = [[FakeAVAssetTrack alloc] initWithOrientation:orientation]; CGAffineTransform t = FLTGetStandardizedTransformForTrack(track); CGSize size = track.naturalSize; CGFloat expectX, expectY; switch (orientation) { case UIImageOrientationUp: expectX = 0; expectY = 0; break; case UIImageOrientationDown: expectX = size.width; expectY = size.height; break; case UIImageOrientationLeft: expectX = 0; expectY = size.width; break; case UIImageOrientationRight: expectX = size.height; expectY = 0; break; case UIImageOrientationUpMirrored: expectX = size.width; expectY = 0; break; case UIImageOrientationDownMirrored: expectX = 0; expectY = size.height; break; case UIImageOrientationLeftMirrored: expectX = size.height; expectY = size.width; break; case UIImageOrientationRightMirrored: expectX = 0; expectY = 0; break; } XCTAssertEqual(t.tx, expectX); XCTAssertEqual(t.ty, expectY); } @end
plugins/packages/video_player/video_player_avfoundation/example/ios/RunnerTests/VideoPlayerTests.m/0
{ "file_path": "plugins/packages/video_player/video_player_avfoundation/example/ios/RunnerTests/VideoPlayerTests.m", "repo_id": "plugins", "token_count": 4730 }
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. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; import 'messages.g.dart'; /// An iOS implementation of [VideoPlayerPlatform] that uses the /// Pigeon-generated [VideoPlayerApi]. class AVFoundationVideoPlayer extends VideoPlayerPlatform { final AVFoundationVideoPlayerApi _api = AVFoundationVideoPlayerApi(); /// Registers this class as the default instance of [VideoPlayerPlatform]. static void registerWith() { VideoPlayerPlatform.instance = AVFoundationVideoPlayer(); } @override Future<void> init() { return _api.initialize(); } @override Future<void> dispose(int textureId) { return _api.dispose(TextureMessage(textureId: textureId)); } @override Future<int?> create(DataSource dataSource) async { String? asset; String? packageName; String? uri; String? formatHint; Map<String, String> httpHeaders = <String, String>{}; switch (dataSource.sourceType) { case DataSourceType.asset: asset = dataSource.asset; packageName = dataSource.package; break; case DataSourceType.network: uri = dataSource.uri; formatHint = _videoFormatStringMap[dataSource.formatHint]; httpHeaders = dataSource.httpHeaders; break; case DataSourceType.file: uri = dataSource.uri; break; case DataSourceType.contentUri: uri = dataSource.uri; break; } final CreateMessage message = CreateMessage( asset: asset, packageName: packageName, uri: uri, httpHeaders: httpHeaders, formatHint: formatHint, ); final TextureMessage response = await _api.create(message); return response.textureId; } @override Future<void> setLooping(int textureId, bool looping) { return _api.setLooping(LoopingMessage( textureId: textureId, isLooping: looping, )); } @override Future<void> play(int textureId) { return _api.play(TextureMessage(textureId: textureId)); } @override Future<void> pause(int textureId) { return _api.pause(TextureMessage(textureId: textureId)); } @override Future<void> setVolume(int textureId, double volume) { return _api.setVolume(VolumeMessage( textureId: textureId, volume: volume, )); } @override Future<void> setPlaybackSpeed(int textureId, double speed) { assert(speed > 0); return _api.setPlaybackSpeed(PlaybackSpeedMessage( textureId: textureId, speed: speed, )); } @override Future<void> seekTo(int textureId, Duration position) { return _api.seekTo(PositionMessage( textureId: textureId, position: position.inMilliseconds, )); } @override Future<Duration> getPosition(int textureId) async { final PositionMessage response = await _api.position(TextureMessage(textureId: textureId)); return Duration(milliseconds: response.position); } @override Stream<VideoEvent> videoEventsFor(int textureId) { return _eventChannelFor(textureId) .receiveBroadcastStream() .map((dynamic event) { final Map<dynamic, dynamic> map = event as Map<dynamic, dynamic>; switch (map['event']) { case 'initialized': return VideoEvent( eventType: VideoEventType.initialized, duration: Duration(milliseconds: map['duration'] as int), size: Size((map['width'] as num?)?.toDouble() ?? 0.0, (map['height'] as num?)?.toDouble() ?? 0.0), ); case 'completed': return VideoEvent( eventType: VideoEventType.completed, ); case 'bufferingUpdate': final List<dynamic> values = map['values'] as List<dynamic>; return VideoEvent( buffered: values.map<DurationRange>(_toDurationRange).toList(), eventType: VideoEventType.bufferingUpdate, ); case 'bufferingStart': return VideoEvent(eventType: VideoEventType.bufferingStart); case 'bufferingEnd': return VideoEvent(eventType: VideoEventType.bufferingEnd); default: return VideoEvent(eventType: VideoEventType.unknown); } }); } @override Widget buildView(int textureId) { return Texture(textureId: textureId); } @override Future<void> setMixWithOthers(bool mixWithOthers) { return _api .setMixWithOthers(MixWithOthersMessage(mixWithOthers: mixWithOthers)); } EventChannel _eventChannelFor(int textureId) { return EventChannel('flutter.io/videoPlayer/videoEvents$textureId'); } static const Map<VideoFormat, String> _videoFormatStringMap = <VideoFormat, String>{ VideoFormat.ss: 'ss', VideoFormat.hls: 'hls', VideoFormat.dash: 'dash', VideoFormat.other: 'other', }; DurationRange _toDurationRange(dynamic value) { final List<dynamic> pair = value as List<dynamic>; return DurationRange( Duration(milliseconds: pair[0] as int), Duration(milliseconds: pair[1] as int), ); } }
plugins/packages/video_player/video_player_avfoundation/lib/src/avfoundation_video_player.dart/0
{ "file_path": "plugins/packages/video_player/video_player_avfoundation/lib/src/avfoundation_video_player.dart", "repo_id": "plugins", "token_count": 2023 }
1,293
// 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:webview_flutter/webview_flutter.dart'; void main() => runApp(const MaterialApp(home: WebViewExample())); class WebViewExample extends StatefulWidget { const WebViewExample({super.key}); @override State<WebViewExample> createState() => _WebViewExampleState(); } class _WebViewExampleState extends State<WebViewExample> { late final WebViewController controller; @override void initState() { super.initState(); // #docregion webview_controller controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setBackgroundColor(const Color(0x00000000)) ..setNavigationDelegate( NavigationDelegate( onProgress: (int progress) { // Update loading bar. }, onPageStarted: (String url) {}, onPageFinished: (String url) {}, onWebResourceError: (WebResourceError error) {}, onNavigationRequest: (NavigationRequest request) { if (request.url.startsWith('https://www.youtube.com/')) { return NavigationDecision.prevent; } return NavigationDecision.navigate; }, ), ) ..loadRequest(Uri.parse('https://flutter.dev')); // #enddocregion webview_controller } // #docregion webview_widget @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Flutter Simple Example')), body: WebViewWidget(controller: controller), ); } // #enddocregion webview_widget }
plugins/packages/webview_flutter/webview_flutter/example/lib/simple_example.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter/example/lib/simple_example.dart", "repo_id": "plugins", "token_count": 670 }
1,294
// Mocks generated by Mockito 5.3.2 from annotations // in webview_flutter/test/navigation_delegate_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i8; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_platform_interface/src/platform_navigation_delegate.dart' as _i3; import 'package:webview_flutter_platform_interface/src/platform_webview_controller.dart' as _i4; import 'package:webview_flutter_platform_interface/src/platform_webview_cookie_manager.dart' as _i2; import 'package:webview_flutter_platform_interface/src/platform_webview_widget.dart' as _i5; import 'package:webview_flutter_platform_interface/src/types/types.dart' as _i6; import 'package:webview_flutter_platform_interface/src/webview_platform.dart' as _i7; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakePlatformWebViewCookieManager_0 extends _i1.SmartFake implements _i2.PlatformWebViewCookieManager { _FakePlatformWebViewCookieManager_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformNavigationDelegate_1 extends _i1.SmartFake implements _i3.PlatformNavigationDelegate { _FakePlatformNavigationDelegate_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformWebViewController_2 extends _i1.SmartFake implements _i4.PlatformWebViewController { _FakePlatformWebViewController_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformWebViewWidget_3 extends _i1.SmartFake implements _i5.PlatformWebViewWidget { _FakePlatformWebViewWidget_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformNavigationDelegateCreationParams_4 extends _i1.SmartFake implements _i6.PlatformNavigationDelegateCreationParams { _FakePlatformNavigationDelegateCreationParams_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [WebViewPlatform]. /// /// See the documentation for Mockito's code generation for more information. class MockWebViewPlatform extends _i1.Mock implements _i7.WebViewPlatform { MockWebViewPlatform() { _i1.throwOnMissingStub(this); } @override _i2.PlatformWebViewCookieManager createPlatformCookieManager( _i6.PlatformWebViewCookieManagerCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformCookieManager, [params], ), returnValue: _FakePlatformWebViewCookieManager_0( this, Invocation.method( #createPlatformCookieManager, [params], ), ), ) as _i2.PlatformWebViewCookieManager); @override _i3.PlatformNavigationDelegate createPlatformNavigationDelegate( _i6.PlatformNavigationDelegateCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformNavigationDelegate, [params], ), returnValue: _FakePlatformNavigationDelegate_1( this, Invocation.method( #createPlatformNavigationDelegate, [params], ), ), ) as _i3.PlatformNavigationDelegate); @override _i4.PlatformWebViewController createPlatformWebViewController( _i6.PlatformWebViewControllerCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformWebViewController, [params], ), returnValue: _FakePlatformWebViewController_2( this, Invocation.method( #createPlatformWebViewController, [params], ), ), ) as _i4.PlatformWebViewController); @override _i5.PlatformWebViewWidget createPlatformWebViewWidget( _i6.PlatformWebViewWidgetCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformWebViewWidget, [params], ), returnValue: _FakePlatformWebViewWidget_3( this, Invocation.method( #createPlatformWebViewWidget, [params], ), ), ) as _i5.PlatformWebViewWidget); } /// A class which mocks [PlatformNavigationDelegate]. /// /// See the documentation for Mockito's code generation for more information. class MockPlatformNavigationDelegate extends _i1.Mock implements _i3.PlatformNavigationDelegate { MockPlatformNavigationDelegate() { _i1.throwOnMissingStub(this); } @override _i6.PlatformNavigationDelegateCreationParams get params => (super.noSuchMethod( Invocation.getter(#params), returnValue: _FakePlatformNavigationDelegateCreationParams_4( this, Invocation.getter(#params), ), ) as _i6.PlatformNavigationDelegateCreationParams); @override _i8.Future<void> setOnNavigationRequest( _i3.NavigationRequestCallback? onNavigationRequest) => (super.noSuchMethod( Invocation.method( #setOnNavigationRequest, [onNavigationRequest], ), returnValue: _i8.Future<void>.value(), returnValueForMissingStub: _i8.Future<void>.value(), ) as _i8.Future<void>); @override _i8.Future<void> setOnPageStarted(_i3.PageEventCallback? onPageStarted) => (super.noSuchMethod( Invocation.method( #setOnPageStarted, [onPageStarted], ), returnValue: _i8.Future<void>.value(), returnValueForMissingStub: _i8.Future<void>.value(), ) as _i8.Future<void>); @override _i8.Future<void> setOnPageFinished(_i3.PageEventCallback? onPageFinished) => (super.noSuchMethod( Invocation.method( #setOnPageFinished, [onPageFinished], ), returnValue: _i8.Future<void>.value(), returnValueForMissingStub: _i8.Future<void>.value(), ) as _i8.Future<void>); @override _i8.Future<void> setOnProgress(_i3.ProgressCallback? onProgress) => (super.noSuchMethod( Invocation.method( #setOnProgress, [onProgress], ), returnValue: _i8.Future<void>.value(), returnValueForMissingStub: _i8.Future<void>.value(), ) as _i8.Future<void>); @override _i8.Future<void> setOnWebResourceError( _i3.WebResourceErrorCallback? onWebResourceError) => (super.noSuchMethod( Invocation.method( #setOnWebResourceError, [onWebResourceError], ), returnValue: _i8.Future<void>.value(), returnValueForMissingStub: _i8.Future<void>.value(), ) as _i8.Future<void>); }
plugins/packages/webview_flutter/webview_flutter/test/navigation_delegate_test.mocks.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter/test/navigation_delegate_test.mocks.dart", "repo_id": "plugins", "token_count": 3091 }
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. package io.flutter.plugins.webviewflutter; import static android.hardware.display.DisplayManager.DisplayListener; import android.annotation.TargetApi; import android.hardware.display.DisplayManager; import android.os.Build; import android.util.Log; import java.lang.reflect.Field; import java.util.ArrayList; /** * Works around an Android WebView bug by filtering some DisplayListener invocations. * * <p>Older Android WebView versions had assumed that when {@link DisplayListener#onDisplayChanged} * is invoked, the display ID it is provided is of a valid display. However it turns out that when a * display is removed Android may call onDisplayChanged with the ID of the removed display, in this * case the Android WebView code tries to fetch and use the display with this ID and crashes with an * NPE. * * <p>This issue was fixed in the Android WebView code in * https://chromium-review.googlesource.com/517913 which is available starting WebView version * 58.0.3029.125 however older webviews in the wild still have this issue. * * <p>Since Flutter removes virtual displays whenever a platform view is resized the webview crash * is more likely to happen than other apps. And users were reporting this issue see: * https://github.com/flutter/flutter/issues/30420 * * <p>This class works around the webview bug by unregistering the WebView's DisplayListener, and * instead registering its own DisplayListener which delegates the callbacks to the WebView's * listener unless it's a onDisplayChanged for an invalid display. * * <p>I did not find a clean way to get a handle of the WebView's DisplayListener so I'm using * reflection to fetch all registered listeners before and after initializing a webview. In the * first initialization of a webview within the process the difference between the lists is the * webview's display listener. */ @TargetApi(Build.VERSION_CODES.KITKAT) class DisplayListenerProxy { private static final String TAG = "DisplayListenerProxy"; private ArrayList<DisplayListener> listenersBeforeWebView; /** Should be called prior to the webview's initialization. */ void onPreWebViewInitialization(DisplayManager displayManager) { listenersBeforeWebView = yoinkDisplayListeners(displayManager); } /** Should be called after the webview's initialization. */ void onPostWebViewInitialization(final DisplayManager displayManager) { final ArrayList<DisplayListener> webViewListeners = yoinkDisplayListeners(displayManager); // We recorded the list of listeners prior to initializing webview, any new listeners we see // after initializing the webview are listeners added by the webview. webViewListeners.removeAll(listenersBeforeWebView); if (webViewListeners.isEmpty()) { // The Android WebView registers a single display listener per process (even if there // are multiple WebView instances) so this list is expected to be non-empty only the // first time a webview is initialized. // Note that in an add2app scenario if the application had instantiated a non Flutter // WebView prior to instantiating the Flutter WebView we are not able to get a reference // to the WebView's display listener and can't work around the bug. // // This means that webview resizes in add2app Flutter apps with a non Flutter WebView // running on a system with a webview prior to 58.0.3029.125 may crash (the Android's // behavior seems to be racy so it doesn't always happen). return; } for (DisplayListener webViewListener : webViewListeners) { // Note that while DisplayManager.unregisterDisplayListener throws when given an // unregistered listener, this isn't an issue as the WebView code never calls // unregisterDisplayListener. displayManager.unregisterDisplayListener(webViewListener); // We never explicitly unregister this listener as the webview's listener is never // unregistered (it's released when the process is terminated). displayManager.registerDisplayListener( new DisplayListener() { @Override public void onDisplayAdded(int displayId) { for (DisplayListener webViewListener : webViewListeners) { webViewListener.onDisplayAdded(displayId); } } @Override public void onDisplayRemoved(int displayId) { for (DisplayListener webViewListener : webViewListeners) { webViewListener.onDisplayRemoved(displayId); } } @Override public void onDisplayChanged(int displayId) { if (displayManager.getDisplay(displayId) == null) { return; } for (DisplayListener webViewListener : webViewListeners) { webViewListener.onDisplayChanged(displayId); } } }, null); } } @SuppressWarnings({"unchecked", "PrivateApi"}) private static ArrayList<DisplayListener> yoinkDisplayListeners(DisplayManager displayManager) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { // We cannot use reflection on Android P, but it shouldn't matter as it shipped // with WebView 66.0.3359.158 and the WebView version the bug this code is working around was // fixed in 61.0.3116.0. return new ArrayList<>(); } try { Field displayManagerGlobalField = DisplayManager.class.getDeclaredField("mGlobal"); displayManagerGlobalField.setAccessible(true); Object displayManagerGlobal = displayManagerGlobalField.get(displayManager); Field displayListenersField = displayManagerGlobal.getClass().getDeclaredField("mDisplayListeners"); displayListenersField.setAccessible(true); ArrayList<Object> delegates = (ArrayList<Object>) displayListenersField.get(displayManagerGlobal); Field listenerField = null; ArrayList<DisplayManager.DisplayListener> listeners = new ArrayList<>(); for (Object delegate : delegates) { if (listenerField == null) { listenerField = delegate.getClass().getField("mListener"); listenerField.setAccessible(true); } DisplayManager.DisplayListener listener = (DisplayManager.DisplayListener) listenerField.get(delegate); listeners.add(listener); } return listeners; } catch (NoSuchFieldException | IllegalAccessException e) { Log.w(TAG, "Could not extract WebView's display listeners. " + e); return new ArrayList<>(); } } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DisplayListenerProxy.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/DisplayListenerProxy.java", "repo_id": "plugins", "token_count": 2177 }
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. package io.flutter.plugins.webviewflutter; import android.net.Uri; import android.os.Build; import android.os.Message; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.VisibleForTesting; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebChromeClientHostApi; import java.util.Objects; /** * Host api implementation for {@link WebChromeClient}. * * <p>Handles creating {@link WebChromeClient}s that intercommunicate with a paired Dart object. */ public class WebChromeClientHostApiImpl implements WebChromeClientHostApi { private final InstanceManager instanceManager; private final WebChromeClientCreator webChromeClientCreator; private final WebChromeClientFlutterApiImpl flutterApi; /** * Implementation of {@link WebChromeClient} that passes arguments of callback methods to Dart. */ public static class WebChromeClientImpl extends SecureWebChromeClient { private final WebChromeClientFlutterApiImpl flutterApi; private boolean returnValueForOnShowFileChooser = false; /** * Creates a {@link WebChromeClient} that passes arguments of callbacks methods to Dart. * * @param flutterApi handles sending messages to Dart */ public WebChromeClientImpl(@NonNull WebChromeClientFlutterApiImpl flutterApi) { this.flutterApi = flutterApi; } @Override public void onProgressChanged(WebView view, int progress) { flutterApi.onProgressChanged(this, view, (long) progress, reply -> {}); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean onShowFileChooser( WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { final boolean currentReturnValueForOnShowFileChooser = returnValueForOnShowFileChooser; flutterApi.onShowFileChooser( this, webView, fileChooserParams, reply -> { // The returned list of file paths can only be passed to `filePathCallback` if the // `onShowFileChooser` method returned true. if (currentReturnValueForOnShowFileChooser) { final Uri[] filePaths = new Uri[reply.size()]; for (int i = 0; i < reply.size(); i++) { filePaths[i] = Uri.parse(reply.get(i)); } filePathCallback.onReceiveValue(filePaths); } }); return currentReturnValueForOnShowFileChooser; } /** Sets return value for {@link #onShowFileChooser}. */ public void setReturnValueForOnShowFileChooser(boolean value) { returnValueForOnShowFileChooser = value; } } /** * Implementation of {@link WebChromeClient} that only allows secure urls when opening a new * window. */ public static class SecureWebChromeClient extends WebChromeClient { @Nullable private WebViewClient webViewClient; @Override public boolean onCreateWindow( final WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { return onCreateWindow(view, resultMsg, new WebView(view.getContext())); } /** * Verifies that a url opened by `Window.open` has a secure url. * * @param view the WebView from which the request for a new window originated. * @param resultMsg the message to send when once a new WebView has been created. resultMsg.obj * is a {@link WebView.WebViewTransport} object. This should be used to transport the new * WebView, by calling WebView.WebViewTransport.setWebView(WebView) * @param onCreateWindowWebView the temporary WebView used to verify the url is secure * @return this method should return true if the host application will create a new window, in * which case resultMsg should be sent to its target. Otherwise, this method should return * false. Returning false from this method but also sending resultMsg will result in * undefined behavior */ @VisibleForTesting boolean onCreateWindow( final WebView view, Message resultMsg, @Nullable WebView onCreateWindowWebView) { // WebChromeClient requires a WebViewClient because of a bug fix that makes // calls to WebViewClient.requestLoading/WebViewClient.urlLoading when a new // window is opened. This is to make sure a url opened by `Window.open` has // a secure url. if (webViewClient == null) { return false; } final WebViewClient windowWebViewClient = new WebViewClient() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public boolean shouldOverrideUrlLoading( @NonNull WebView windowWebView, @NonNull WebResourceRequest request) { if (!webViewClient.shouldOverrideUrlLoading(view, request)) { view.loadUrl(request.getUrl().toString()); } return true; } @Override public boolean shouldOverrideUrlLoading(WebView windowWebView, String url) { if (!webViewClient.shouldOverrideUrlLoading(view, url)) { view.loadUrl(url); } return true; } }; if (onCreateWindowWebView == null) { onCreateWindowWebView = new WebView(view.getContext()); } onCreateWindowWebView.setWebViewClient(windowWebViewClient); final WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(onCreateWindowWebView); resultMsg.sendToTarget(); return true; } /** * Set the {@link WebViewClient} that calls to {@link WebChromeClient#onCreateWindow} are passed * to. * * @param webViewClient the forwarding {@link WebViewClient} */ public void setWebViewClient(@NonNull WebViewClient webViewClient) { this.webViewClient = webViewClient; } } /** Handles creating {@link WebChromeClient}s for a {@link WebChromeClientHostApiImpl}. */ public static class WebChromeClientCreator { /** * Creates a {@link DownloadListenerHostApiImpl.DownloadListenerImpl}. * * @param flutterApi handles sending messages to Dart * @return the created {@link WebChromeClientHostApiImpl.WebChromeClientImpl} */ public WebChromeClientImpl createWebChromeClient(WebChromeClientFlutterApiImpl flutterApi) { return new WebChromeClientImpl(flutterApi); } } /** * Creates a host API that handles creating {@link WebChromeClient}s. * * @param instanceManager maintains instances stored to communicate with Dart objects * @param webChromeClientCreator handles creating {@link WebChromeClient}s * @param flutterApi handles sending messages to Dart */ public WebChromeClientHostApiImpl( InstanceManager instanceManager, WebChromeClientCreator webChromeClientCreator, WebChromeClientFlutterApiImpl flutterApi) { this.instanceManager = instanceManager; this.webChromeClientCreator = webChromeClientCreator; this.flutterApi = flutterApi; } @Override public void create(Long instanceId) { final WebChromeClient webChromeClient = webChromeClientCreator.createWebChromeClient(flutterApi); instanceManager.addDartCreatedInstance(webChromeClient, instanceId); } @Override public void setSynchronousReturnValueForOnShowFileChooser( @NonNull Long instanceId, @NonNull Boolean value) { final WebChromeClientImpl webChromeClient = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webChromeClient.setReturnValueForOnShowFileChooser(value); } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebChromeClientHostApiImpl.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebChromeClientHostApiImpl.java", "repo_id": "plugins", "token_count": 2894 }
1,297
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import android.os.Handler; import io.flutter.plugins.webviewflutter.JavaScriptChannelHostApiImpl.JavaScriptChannelCreator; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class JavaScriptChannelTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public JavaScriptChannelFlutterApiImpl mockFlutterApi; InstanceManager instanceManager; JavaScriptChannelHostApiImpl hostApiImpl; JavaScriptChannel javaScriptChannel; @Before public void setUp() { instanceManager = InstanceManager.open(identifier -> {}); final JavaScriptChannelCreator javaScriptChannelCreator = new JavaScriptChannelCreator() { @Override public JavaScriptChannel createJavaScriptChannel( JavaScriptChannelFlutterApiImpl javaScriptChannelFlutterApi, String channelName, Handler platformThreadHandler) { javaScriptChannel = super.createJavaScriptChannel( javaScriptChannelFlutterApi, channelName, platformThreadHandler); return javaScriptChannel; } }; hostApiImpl = new JavaScriptChannelHostApiImpl( instanceManager, javaScriptChannelCreator, mockFlutterApi, new Handler()); hostApiImpl.create(0L, "aChannelName"); } @After public void tearDown() { instanceManager.close(); } @Test public void postMessage() { javaScriptChannel.postMessage("A message post."); verify(mockFlutterApi).postMessage(eq(javaScriptChannel), eq("A message post."), any()); } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/JavaScriptChannelTest.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/JavaScriptChannelTest.java", "repo_id": "plugins", "token_count": 730 }
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. // TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#106316) // ignore: unnecessary_import import 'dart:typed_data'; import 'dart:ui'; import 'package:flutter/services.dart' show BinaryMessenger; import 'android_webview.dart'; import 'android_webview.g.dart'; import 'instance_manager.dart'; export 'android_webview.g.dart' show FileChooserMode; /// Converts [WebResourceRequestData] to [WebResourceRequest] WebResourceRequest _toWebResourceRequest(WebResourceRequestData data) { return WebResourceRequest( url: data.url, isForMainFrame: data.isForMainFrame, isRedirect: data.isRedirect, hasGesture: data.hasGesture, method: data.method, requestHeaders: data.requestHeaders.cast<String, String>(), ); } /// Converts [WebResourceErrorData] to [WebResourceError]. WebResourceError _toWebResourceError(WebResourceErrorData data) { return WebResourceError( errorCode: data.errorCode, description: data.description, ); } /// Handles initialization of Flutter APIs for Android WebView. class AndroidWebViewFlutterApis { /// Creates a [AndroidWebViewFlutterApis]. AndroidWebViewFlutterApis({ JavaObjectFlutterApiImpl? javaObjectFlutterApi, DownloadListenerFlutterApiImpl? downloadListenerFlutterApi, WebViewClientFlutterApiImpl? webViewClientFlutterApi, WebChromeClientFlutterApiImpl? webChromeClientFlutterApi, JavaScriptChannelFlutterApiImpl? javaScriptChannelFlutterApi, FileChooserParamsFlutterApiImpl? fileChooserParamsFlutterApi, }) { this.javaObjectFlutterApi = javaObjectFlutterApi ?? JavaObjectFlutterApiImpl(); this.downloadListenerFlutterApi = downloadListenerFlutterApi ?? DownloadListenerFlutterApiImpl(); this.webViewClientFlutterApi = webViewClientFlutterApi ?? WebViewClientFlutterApiImpl(); this.webChromeClientFlutterApi = webChromeClientFlutterApi ?? WebChromeClientFlutterApiImpl(); this.javaScriptChannelFlutterApi = javaScriptChannelFlutterApi ?? JavaScriptChannelFlutterApiImpl(); this.fileChooserParamsFlutterApi = fileChooserParamsFlutterApi ?? FileChooserParamsFlutterApiImpl(); } static bool _haveBeenSetUp = false; /// Mutable instance containing all Flutter Apis for Android WebView. /// /// This should only be changed for testing purposes. static AndroidWebViewFlutterApis instance = AndroidWebViewFlutterApis(); /// Handles callbacks methods for the native Java Object class. late final JavaObjectFlutterApi javaObjectFlutterApi; /// Flutter Api for [DownloadListener]. late final DownloadListenerFlutterApiImpl downloadListenerFlutterApi; /// Flutter Api for [WebViewClient]. late final WebViewClientFlutterApiImpl webViewClientFlutterApi; /// Flutter Api for [WebChromeClient]. late final WebChromeClientFlutterApiImpl webChromeClientFlutterApi; /// Flutter Api for [JavaScriptChannel]. late final JavaScriptChannelFlutterApiImpl javaScriptChannelFlutterApi; /// Flutter Api for [FileChooserParams]. late final FileChooserParamsFlutterApiImpl fileChooserParamsFlutterApi; /// Ensures all the Flutter APIs have been setup to receive calls from native code. void ensureSetUp() { if (!_haveBeenSetUp) { JavaObjectFlutterApi.setup(javaObjectFlutterApi); DownloadListenerFlutterApi.setup(downloadListenerFlutterApi); WebViewClientFlutterApi.setup(webViewClientFlutterApi); WebChromeClientFlutterApi.setup(webChromeClientFlutterApi); JavaScriptChannelFlutterApi.setup(javaScriptChannelFlutterApi); FileChooserParamsFlutterApi.setup(fileChooserParamsFlutterApi); _haveBeenSetUp = true; } } } /// Handles methods calls to the native Java Object class. class JavaObjectHostApiImpl extends JavaObjectHostApi { /// Constructs a [JavaObjectHostApiImpl]. JavaObjectHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; } /// Handles callbacks methods for the native Java Object class. class JavaObjectFlutterApiImpl implements JavaObjectFlutterApi { /// Constructs a [JavaObjectFlutterApiImpl]. JavaObjectFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; @override void dispose(int identifier) { instanceManager.remove(identifier); } } /// Host api implementation for [WebView]. class WebViewHostApiImpl extends WebViewHostApi { /// Constructs a [WebViewHostApiImpl]. WebViewHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebView instance) { return create( instanceManager.addDartCreatedInstance(instance), instance.useHybridComposition, ); } /// Helper method to convert the instances ids to objects. Future<void> loadDataFromInstance( WebView instance, String data, String? mimeType, String? encoding, ) { return loadData( instanceManager.getIdentifier(instance)!, data, mimeType, encoding, ); } /// Helper method to convert instances ids to objects. Future<void> loadDataWithBaseUrlFromInstance( WebView instance, String? baseUrl, String data, String? mimeType, String? encoding, String? historyUrl, ) { return loadDataWithBaseUrl( instanceManager.getIdentifier(instance)!, baseUrl, data, mimeType, encoding, historyUrl, ); } /// Helper method to convert instances ids to objects. Future<void> loadUrlFromInstance( WebView instance, String url, Map<String, String> headers, ) { return loadUrl(instanceManager.getIdentifier(instance)!, url, headers); } /// Helper method to convert instances ids to objects. Future<void> postUrlFromInstance( WebView instance, String url, Uint8List data, ) { return postUrl(instanceManager.getIdentifier(instance)!, url, data); } /// Helper method to convert instances ids to objects. Future<String?> getUrlFromInstance(WebView instance) { return getUrl(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<bool> canGoBackFromInstance(WebView instance) { return canGoBack(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<bool> canGoForwardFromInstance(WebView instance) { return canGoForward(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> goBackFromInstance(WebView instance) { return goBack(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> goForwardFromInstance(WebView instance) { return goForward(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> reloadFromInstance(WebView instance) { return reload(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> clearCacheFromInstance(WebView instance, bool includeDiskFiles) { return clearCache( instanceManager.getIdentifier(instance)!, includeDiskFiles, ); } /// Helper method to convert instances ids to objects. Future<String?> evaluateJavascriptFromInstance( WebView instance, String javascriptString, ) { return evaluateJavascript( instanceManager.getIdentifier(instance)!, javascriptString, ); } /// Helper method to convert instances ids to objects. Future<String?> getTitleFromInstance(WebView instance) { return getTitle(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> scrollToFromInstance(WebView instance, int x, int y) { return scrollTo(instanceManager.getIdentifier(instance)!, x, y); } /// Helper method to convert instances ids to objects. Future<void> scrollByFromInstance(WebView instance, int x, int y) { return scrollBy(instanceManager.getIdentifier(instance)!, x, y); } /// Helper method to convert instances ids to objects. Future<int> getScrollXFromInstance(WebView instance) { return getScrollX(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<int> getScrollYFromInstance(WebView instance) { return getScrollY(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<Offset> getScrollPositionFromInstance(WebView instance) async { final WebViewPoint position = await getScrollPosition(instanceManager.getIdentifier(instance)!); return Offset(position.x.toDouble(), position.y.toDouble()); } /// Helper method to convert instances ids to objects. Future<void> setWebViewClientFromInstance( WebView instance, WebViewClient webViewClient, ) { return setWebViewClient( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(webViewClient)!, ); } /// Helper method to convert instances ids to objects. Future<void> addJavaScriptChannelFromInstance( WebView instance, JavaScriptChannel javaScriptChannel, ) { return addJavaScriptChannel( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(javaScriptChannel)!, ); } /// Helper method to convert instances ids to objects. Future<void> removeJavaScriptChannelFromInstance( WebView instance, JavaScriptChannel javaScriptChannel, ) { return removeJavaScriptChannel( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(javaScriptChannel)!, ); } /// Helper method to convert instances ids to objects. Future<void> setDownloadListenerFromInstance( WebView instance, DownloadListener? listener, ) { return setDownloadListener( instanceManager.getIdentifier(instance)!, listener != null ? instanceManager.getIdentifier(listener) : null, ); } /// Helper method to convert instances ids to objects. Future<void> setWebChromeClientFromInstance( WebView instance, WebChromeClient? client, ) { return setWebChromeClient( instanceManager.getIdentifier(instance)!, client != null ? instanceManager.getIdentifier(client) : null, ); } /// Helper method to convert instances ids to objects. Future<void> setBackgroundColorFromInstance(WebView instance, int color) { return setBackgroundColor(instanceManager.getIdentifier(instance)!, color); } } /// Host api implementation for [WebSettings]. class WebSettingsHostApiImpl extends WebSettingsHostApi { /// Constructs a [WebSettingsHostApiImpl]. WebSettingsHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebSettings instance, WebView webView) { return create( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(webView)!, ); } /// Helper method to convert instances ids to objects. Future<void> setDomStorageEnabledFromInstance( WebSettings instance, bool flag, ) { return setDomStorageEnabled(instanceManager.getIdentifier(instance)!, flag); } /// Helper method to convert instances ids to objects. Future<void> setJavaScriptCanOpenWindowsAutomaticallyFromInstance( WebSettings instance, bool flag, ) { return setJavaScriptCanOpenWindowsAutomatically( instanceManager.getIdentifier(instance)!, flag, ); } /// Helper method to convert instances ids to objects. Future<void> setSupportMultipleWindowsFromInstance( WebSettings instance, bool support, ) { return setSupportMultipleWindows( instanceManager.getIdentifier(instance)!, support); } /// Helper method to convert instances ids to objects. Future<void> setJavaScriptEnabledFromInstance( WebSettings instance, bool flag, ) { return setJavaScriptEnabled( instanceManager.getIdentifier(instance)!, flag, ); } /// Helper method to convert instances ids to objects. Future<void> setUserAgentStringFromInstance( WebSettings instance, String? userAgentString, ) { return setUserAgentString( instanceManager.getIdentifier(instance)!, userAgentString, ); } /// Helper method to convert instances ids to objects. Future<void> setMediaPlaybackRequiresUserGestureFromInstance( WebSettings instance, bool require, ) { return setMediaPlaybackRequiresUserGesture( instanceManager.getIdentifier(instance)!, require, ); } /// Helper method to convert instances ids to objects. Future<void> setSupportZoomFromInstance( WebSettings instance, bool support, ) { return setSupportZoom(instanceManager.getIdentifier(instance)!, support); } /// Helper method to convert instances ids to objects. Future<void> setLoadWithOverviewModeFromInstance( WebSettings instance, bool overview, ) { return setLoadWithOverviewMode( instanceManager.getIdentifier(instance)!, overview, ); } /// Helper method to convert instances ids to objects. Future<void> setUseWideViewPortFromInstance( WebSettings instance, bool use, ) { return setUseWideViewPort(instanceManager.getIdentifier(instance)!, use); } /// Helper method to convert instances ids to objects. Future<void> setDisplayZoomControlsFromInstance( WebSettings instance, bool enabled, ) { return setDisplayZoomControls( instanceManager.getIdentifier(instance)!, enabled, ); } /// Helper method to convert instances ids to objects. Future<void> setBuiltInZoomControlsFromInstance( WebSettings instance, bool enabled, ) { return setBuiltInZoomControls( instanceManager.getIdentifier(instance)!, enabled, ); } /// Helper method to convert instances ids to objects. Future<void> setAllowFileAccessFromInstance( WebSettings instance, bool enabled, ) { return setAllowFileAccess( instanceManager.getIdentifier(instance)!, enabled, ); } } /// Host api implementation for [JavaScriptChannel]. class JavaScriptChannelHostApiImpl extends JavaScriptChannelHostApi { /// Constructs a [JavaScriptChannelHostApiImpl]. JavaScriptChannelHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(JavaScriptChannel instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); await create( identifier, instance.channelName, ); } } } /// Flutter api implementation for [JavaScriptChannel]. class JavaScriptChannelFlutterApiImpl extends JavaScriptChannelFlutterApi { /// Constructs a [JavaScriptChannelFlutterApiImpl]. JavaScriptChannelFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void postMessage(int instanceId, String message) { final JavaScriptChannel? instance = instanceManager .getInstanceWithWeakReference(instanceId) as JavaScriptChannel?; assert( instance != null, 'InstanceManager does not contain an JavaScriptChannel with instanceId: $instanceId', ); instance!.postMessage(message); } } /// Host api implementation for [WebViewClient]. class WebViewClientHostApiImpl extends WebViewClientHostApi { /// Constructs a [WebViewClientHostApiImpl]. WebViewClientHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebViewClient instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); return create(identifier); } } /// Helper method to convert instances ids to objects. Future<void> setShouldOverrideUrlLoadingReturnValueFromInstance( WebViewClient instance, bool value, ) { return setSynchronousReturnValueForShouldOverrideUrlLoading( instanceManager.getIdentifier(instance)!, value, ); } } /// Flutter api implementation for [WebViewClient]. class WebViewClientFlutterApiImpl extends WebViewClientFlutterApi { /// Constructs a [WebViewClientFlutterApiImpl]. WebViewClientFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void onPageFinished(int instanceId, int webViewInstanceId, String url) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain an WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId', ); if (instance!.onPageFinished != null) { instance.onPageFinished!(webViewInstance!, url); } } @override void onPageStarted(int instanceId, int webViewInstanceId, String url) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain an WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId', ); if (instance!.onPageStarted != null) { instance.onPageStarted!(webViewInstance!, url); } } @override void onReceivedError( int instanceId, int webViewInstanceId, int errorCode, String description, String failingUrl, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain an WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId', ); // ignore: deprecated_member_use_from_same_package if (instance!.onReceivedError != null) { instance.onReceivedError!( webViewInstance!, errorCode, description, failingUrl, ); } } @override void onReceivedRequestError( int instanceId, int webViewInstanceId, WebResourceRequestData request, WebResourceErrorData error, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain an WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId', ); if (instance!.onReceivedRequestError != null) { instance.onReceivedRequestError!( webViewInstance!, _toWebResourceRequest(request), _toWebResourceError(error), ); } } @override void requestLoading( int instanceId, int webViewInstanceId, WebResourceRequestData request, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain an WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId', ); if (instance!.requestLoading != null) { instance.requestLoading!( webViewInstance!, _toWebResourceRequest(request), ); } } @override void urlLoading( int instanceId, int webViewInstanceId, String url, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain an WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId', ); if (instance!.urlLoading != null) { instance.urlLoading!(webViewInstance!, url); } } } /// Host api implementation for [DownloadListener]. class DownloadListenerHostApiImpl extends DownloadListenerHostApi { /// Constructs a [DownloadListenerHostApiImpl]. DownloadListenerHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(DownloadListener instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); return create(identifier); } } } /// Flutter api implementation for [DownloadListener]. class DownloadListenerFlutterApiImpl extends DownloadListenerFlutterApi { /// Constructs a [DownloadListenerFlutterApiImpl]. DownloadListenerFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void onDownloadStart( int instanceId, String url, String userAgent, String contentDisposition, String mimetype, int contentLength, ) { final DownloadListener? instance = instanceManager .getInstanceWithWeakReference(instanceId) as DownloadListener?; assert( instance != null, 'InstanceManager does not contain an DownloadListener with instanceId: $instanceId', ); instance!.onDownloadStart( url, userAgent, contentDisposition, mimetype, contentLength, ); } } /// Host api implementation for [DownloadListener]. class WebChromeClientHostApiImpl extends WebChromeClientHostApi { /// Constructs a [WebChromeClientHostApiImpl]. WebChromeClientHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebChromeClient instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); return create(identifier); } } /// Helper method to convert instances ids to objects. Future<void> setSynchronousReturnValueForOnShowFileChooserFromInstance( WebChromeClient instance, bool value, ) { return setSynchronousReturnValueForOnShowFileChooser( instanceManager.getIdentifier(instance)!, value, ); } } /// Flutter api implementation for [DownloadListener]. class WebChromeClientFlutterApiImpl extends WebChromeClientFlutterApi { /// Constructs a [DownloadListenerFlutterApiImpl]. WebChromeClientFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void onProgressChanged(int instanceId, int webViewInstanceId, int progress) { final WebChromeClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebChromeClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain an WebChromeClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId', ); if (instance!.onProgressChanged != null) { instance.onProgressChanged!(webViewInstance!, progress); } } @override Future<List<String?>> onShowFileChooser( int instanceId, int webViewInstanceId, int paramsInstanceId, ) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; if (instance.onShowFileChooser != null) { return instance.onShowFileChooser!( instanceManager.getInstanceWithWeakReference(webViewInstanceId)! as WebView, instanceManager.getInstanceWithWeakReference(paramsInstanceId)! as FileChooserParams, ); } return Future<List<String>>.value(const <String>[]); } } /// Host api implementation for [WebStorage]. class WebStorageHostApiImpl extends WebStorageHostApi { /// Constructs a [WebStorageHostApiImpl]. WebStorageHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebStorage instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); return create(identifier); } } /// Helper method to convert instances ids to objects. Future<void> deleteAllDataFromInstance(WebStorage instance) { return deleteAllData(instanceManager.getIdentifier(instance)!); } } /// Flutter api implementation for [FileChooserParams]. class FileChooserParamsFlutterApiImpl extends FileChooserParamsFlutterApi { /// Constructs a [FileChooserParamsFlutterApiImpl]. FileChooserParamsFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void create( int instanceId, bool isCaptureEnabled, List<String?> acceptTypes, FileChooserModeEnumData mode, String? filenameHint, ) { instanceManager.addHostCreatedInstance( FileChooserParams.detached( isCaptureEnabled: isCaptureEnabled, acceptTypes: acceptTypes.cast(), mode: mode.value, filenameHint: filenameHint, ), instanceId, ); } }
plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_api_impls.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_api_impls.dart", "repo_id": "plugins", "token_count": 9371 }
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. // TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231) // ignore: unnecessary_import import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_android/src/android_proxy.dart'; import 'package:webview_flutter_android/src/android_webview.dart' as android_webview; import 'package:webview_flutter_android/src/android_webview_api_impls.dart'; import 'package:webview_flutter_android/src/instance_manager.dart'; import 'package:webview_flutter_android/src/platform_views_service_proxy.dart'; import 'package:webview_flutter_android/webview_flutter_android.dart'; import 'package:webview_flutter_platform_interface/src/webview_platform.dart'; import 'android_navigation_delegate_test.dart'; import 'android_webview_controller_test.mocks.dart'; @GenerateNiceMocks(<MockSpec<Object>>[ MockSpec<AndroidNavigationDelegate>(), MockSpec<AndroidWebViewController>(), MockSpec<AndroidWebViewProxy>(), MockSpec<AndroidWebViewWidgetCreationParams>(), MockSpec<ExpensiveAndroidViewController>(), MockSpec<android_webview.FlutterAssetManager>(), MockSpec<android_webview.JavaScriptChannel>(), MockSpec<PlatformViewsServiceProxy>(), MockSpec<SurfaceAndroidViewController>(), MockSpec<android_webview.WebChromeClient>(), MockSpec<android_webview.WebSettings>(), MockSpec<android_webview.WebView>(), MockSpec<android_webview.WebViewClient>(), MockSpec<android_webview.WebStorage>(), MockSpec<InstanceManager>(), ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); AndroidWebViewController createControllerWithMocks({ android_webview.FlutterAssetManager? mockFlutterAssetManager, android_webview.JavaScriptChannel? mockJavaScriptChannel, android_webview.WebChromeClient Function({ void Function(android_webview.WebView webView, int progress)? onProgressChanged, Future<List<String>> Function( android_webview.WebView webView, android_webview.FileChooserParams params, )? onShowFileChooser, })? createWebChromeClient, android_webview.WebView? mockWebView, android_webview.WebViewClient? mockWebViewClient, android_webview.WebStorage? mockWebStorage, android_webview.WebSettings? mockSettings, }) { final android_webview.WebView nonNullMockWebView = mockWebView ?? MockWebView(); final AndroidWebViewControllerCreationParams creationParams = AndroidWebViewControllerCreationParams( androidWebStorage: mockWebStorage ?? MockWebStorage(), androidWebViewProxy: AndroidWebViewProxy( createAndroidWebChromeClient: createWebChromeClient ?? ({ void Function(android_webview.WebView, int)? onProgressChanged, Future<List<String>> Function( android_webview.WebView webView, android_webview.FileChooserParams params, )? onShowFileChooser, }) => MockWebChromeClient(), createAndroidWebView: ({required bool useHybridComposition}) => nonNullMockWebView, createAndroidWebViewClient: ({ void Function(android_webview.WebView webView, String url)? onPageFinished, void Function(android_webview.WebView webView, String url)? onPageStarted, @Deprecated('Only called on Android version < 23.') void Function( android_webview.WebView webView, int errorCode, String description, String failingUrl, )? onReceivedError, void Function( android_webview.WebView webView, android_webview.WebResourceRequest request, android_webview.WebResourceError error, )? onReceivedRequestError, void Function( android_webview.WebView webView, android_webview.WebResourceRequest request, )? requestLoading, void Function(android_webview.WebView webView, String url)? urlLoading, }) => mockWebViewClient ?? MockWebViewClient(), createFlutterAssetManager: () => mockFlutterAssetManager ?? MockFlutterAssetManager(), createJavaScriptChannel: ( String channelName, { required void Function(String) postMessage, }) => mockJavaScriptChannel ?? MockJavaScriptChannel(), )); when(nonNullMockWebView.settings) .thenReturn(mockSettings ?? MockWebSettings()); return AndroidWebViewController(creationParams); } group('AndroidWebViewController', () { AndroidJavaScriptChannelParams createAndroidJavaScriptChannelParamsWithMocks({ String? name, MockJavaScriptChannel? mockJavaScriptChannel, }) { return AndroidJavaScriptChannelParams( name: name ?? 'test', onMessageReceived: (JavaScriptMessage message) {}, webViewProxy: AndroidWebViewProxy( createJavaScriptChannel: ( String channelName, { required void Function(String) postMessage, }) => mockJavaScriptChannel ?? MockJavaScriptChannel(), )); } test('loadFile without file prefix', () async { final MockWebView mockWebView = MockWebView(); final MockWebSettings mockWebSettings = MockWebSettings(); createControllerWithMocks( mockWebView: mockWebView, mockSettings: mockWebSettings, ); verify(mockWebSettings.setBuiltInZoomControls(true)).called(1); verify(mockWebSettings.setDisplayZoomControls(false)).called(1); verify(mockWebSettings.setDomStorageEnabled(true)).called(1); verify(mockWebSettings.setJavaScriptCanOpenWindowsAutomatically(true)) .called(1); verify(mockWebSettings.setLoadWithOverviewMode(true)).called(1); verify(mockWebSettings.setSupportMultipleWindows(true)).called(1); verify(mockWebSettings.setUseWideViewPort(true)).called(1); }); test('loadFile without file prefix', () async { final MockWebView mockWebView = MockWebView(); final MockWebSettings mockWebSettings = MockWebSettings(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, mockSettings: mockWebSettings, ); await controller.loadFile('/path/to/file.html'); verify(mockWebSettings.setAllowFileAccess(true)).called(1); verify(mockWebView.loadUrl( 'file:///path/to/file.html', <String, String>{}, )).called(1); }); test('loadFile without file prefix and characters to be escaped', () async { final MockWebView mockWebView = MockWebView(); final MockWebSettings mockWebSettings = MockWebSettings(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, mockSettings: mockWebSettings, ); await controller.loadFile('/path/to/?_<_>_.html'); verify(mockWebSettings.setAllowFileAccess(true)).called(1); verify(mockWebView.loadUrl( 'file:///path/to/%3F_%3C_%3E_.html', <String, String>{}, )).called(1); }); test('loadFile with file prefix', () async { final MockWebView mockWebView = MockWebView(); final MockWebSettings mockWebSettings = MockWebSettings(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); when(mockWebView.settings).thenReturn(mockWebSettings); await controller.loadFile('file:///path/to/file.html'); verify(mockWebSettings.setAllowFileAccess(true)).called(1); verify(mockWebView.loadUrl( 'file:///path/to/file.html', <String, String>{}, )).called(1); }); test('loadFlutterAsset when asset does not exists', () async { final MockWebView mockWebView = MockWebView(); final MockFlutterAssetManager mockAssetManager = MockFlutterAssetManager(); final AndroidWebViewController controller = createControllerWithMocks( mockFlutterAssetManager: mockAssetManager, mockWebView: mockWebView, ); when(mockAssetManager.getAssetFilePathByName('mock_key')) .thenAnswer((_) => Future<String>.value('')); when(mockAssetManager.list('')) .thenAnswer((_) => Future<List<String>>.value(<String>[])); try { await controller.loadFlutterAsset('mock_key'); fail('Expected an `ArgumentError`.'); } on ArgumentError catch (e) { expect(e.message, 'Asset for key "mock_key" not found.'); expect(e.name, 'key'); } on Error { fail('Expect an `ArgumentError`.'); } verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1); verify(mockAssetManager.list('')).called(1); verifyNever(mockWebView.loadUrl(any, any)); }); test('loadFlutterAsset when asset does exists', () async { final MockWebView mockWebView = MockWebView(); final MockFlutterAssetManager mockAssetManager = MockFlutterAssetManager(); final AndroidWebViewController controller = createControllerWithMocks( mockFlutterAssetManager: mockAssetManager, mockWebView: mockWebView, ); when(mockAssetManager.getAssetFilePathByName('mock_key')) .thenAnswer((_) => Future<String>.value('www/mock_file.html')); when(mockAssetManager.list('www')).thenAnswer( (_) => Future<List<String>>.value(<String>['mock_file.html'])); await controller.loadFlutterAsset('mock_key'); verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1); verify(mockAssetManager.list('www')).called(1); verify(mockWebView.loadUrl( 'file:///android_asset/www/mock_file.html', <String, String>{})); }); test( 'loadFlutterAsset when asset name contains characters that should be escaped', () async { final MockWebView mockWebView = MockWebView(); final MockFlutterAssetManager mockAssetManager = MockFlutterAssetManager(); final AndroidWebViewController controller = createControllerWithMocks( mockFlutterAssetManager: mockAssetManager, mockWebView: mockWebView, ); when(mockAssetManager.getAssetFilePathByName('mock_key')) .thenAnswer((_) => Future<String>.value('www/?_<_>_.html')); when(mockAssetManager.list('www')).thenAnswer( (_) => Future<List<String>>.value(<String>['?_<_>_.html'])); await controller.loadFlutterAsset('mock_key'); verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1); verify(mockAssetManager.list('www')).called(1); verify(mockWebView.loadUrl( 'file:///android_asset/www/%3F_%3C_%3E_.html', <String, String>{})); }); test('loadHtmlString without baseUrl', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.loadHtmlString('<p>Hello Test!</p>'); verify(mockWebView.loadDataWithBaseUrl( data: '<p>Hello Test!</p>', mimeType: 'text/html', )).called(1); }); test('loadHtmlString with baseUrl', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.loadHtmlString('<p>Hello Test!</p>', baseUrl: 'https://flutter.dev'); verify(mockWebView.loadDataWithBaseUrl( data: '<p>Hello Test!</p>', baseUrl: 'https://flutter.dev', mimeType: 'text/html', )).called(1); }); test('loadRequest without URI scheme', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final LoadRequestParams requestParams = LoadRequestParams( uri: Uri.parse('flutter.dev'), ); try { await controller.loadRequest(requestParams); fail('Expect an `ArgumentError`.'); } on ArgumentError catch (e) { expect(e.message, 'WebViewRequest#uri is required to have a scheme.'); } on Error { fail('Expect a `ArgumentError`.'); } verifyNever(mockWebView.loadUrl(any, any)); verifyNever(mockWebView.postUrl(any, any)); }); test('loadRequest using the GET method', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final LoadRequestParams requestParams = LoadRequestParams( uri: Uri.parse('https://flutter.dev'), headers: const <String, String>{'X-Test': 'Testing'}, ); await controller.loadRequest(requestParams); verify(mockWebView.loadUrl( 'https://flutter.dev', <String, String>{'X-Test': 'Testing'}, )); verifyNever(mockWebView.postUrl(any, any)); }); test('loadRequest using the POST method without body', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final LoadRequestParams requestParams = LoadRequestParams( uri: Uri.parse('https://flutter.dev'), method: LoadRequestMethod.post, headers: const <String, String>{'X-Test': 'Testing'}, ); await controller.loadRequest(requestParams); verify(mockWebView.postUrl( 'https://flutter.dev', Uint8List(0), )); verifyNever(mockWebView.loadUrl(any, any)); }); test('loadRequest using the POST method with body', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final LoadRequestParams requestParams = LoadRequestParams( uri: Uri.parse('https://flutter.dev'), method: LoadRequestMethod.post, headers: const <String, String>{'X-Test': 'Testing'}, body: Uint8List.fromList('{"message": "Hello World!"}'.codeUnits), ); await controller.loadRequest(requestParams); verify(mockWebView.postUrl( 'https://flutter.dev', Uint8List.fromList('{"message": "Hello World!"}'.codeUnits), )); verifyNever(mockWebView.loadUrl(any, any)); }); test('currentUrl', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.currentUrl(); verify(mockWebView.getUrl()).called(1); }); test('canGoBack', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.canGoBack(); verify(mockWebView.canGoBack()).called(1); }); test('canGoForward', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.canGoForward(); verify(mockWebView.canGoForward()).called(1); }); test('goBack', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.goBack(); verify(mockWebView.goBack()).called(1); }); test('goForward', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.goForward(); verify(mockWebView.goForward()).called(1); }); test('reload', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.reload(); verify(mockWebView.reload()).called(1); }); test('clearCache', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.clearCache(); verify(mockWebView.clearCache(true)).called(1); }); test('clearLocalStorage', () async { final MockWebStorage mockWebStorage = MockWebStorage(); final AndroidWebViewController controller = createControllerWithMocks( mockWebStorage: mockWebStorage, ); await controller.clearLocalStorage(); verify(mockWebStorage.deleteAllData()).called(1); }); test('setPlatformNavigationDelegate', () async { final MockAndroidNavigationDelegate mockNavigationDelegate = MockAndroidNavigationDelegate(); final MockWebView mockWebView = MockWebView(); final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); final MockWebViewClient mockWebViewClient = MockWebViewClient(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); when(mockNavigationDelegate.androidWebChromeClient) .thenReturn(mockWebChromeClient); when(mockNavigationDelegate.androidWebViewClient) .thenReturn(mockWebViewClient); await controller.setPlatformNavigationDelegate(mockNavigationDelegate); verify(mockWebView.setWebViewClient(mockWebViewClient)); verifyNever(mockWebView.setWebChromeClient(mockWebChromeClient)); }); test('onProgress', () { final AndroidNavigationDelegate androidNavigationDelegate = AndroidNavigationDelegate( AndroidNavigationDelegateCreationParams .fromPlatformNavigationDelegateCreationParams( const PlatformNavigationDelegateCreationParams(), androidWebViewProxy: const AndroidWebViewProxy( createAndroidWebViewClient: android_webview.WebViewClient.detached, createAndroidWebChromeClient: android_webview.WebChromeClient.detached, createDownloadListener: android_webview.DownloadListener.detached, ), ), ); late final int callbackProgress; androidNavigationDelegate .setOnProgress((int progress) => callbackProgress = progress); final AndroidWebViewController controller = createControllerWithMocks( createWebChromeClient: CapturingWebChromeClient.new, ); controller.setPlatformNavigationDelegate(androidNavigationDelegate); CapturingWebChromeClient.lastCreatedDelegate.onProgressChanged!( android_webview.WebView.detached(), 42, ); expect(callbackProgress, 42); }); test('onProgress does not cause LateInitializationError', () { // ignore: unused_local_variable final AndroidWebViewController controller = createControllerWithMocks( createWebChromeClient: CapturingWebChromeClient.new, ); // Should not cause LateInitializationError CapturingWebChromeClient.lastCreatedDelegate.onProgressChanged!( android_webview.WebView.detached(), 42, ); }); test('setOnShowFileSelector', () async { late final Future<List<String>> Function( android_webview.WebView webView, android_webview.FileChooserParams params, ) onShowFileChooserCallback; final MockWebChromeClient mockWebChromeClient = MockWebChromeClient(); final AndroidWebViewController controller = createControllerWithMocks( createWebChromeClient: ({ dynamic onProgressChanged, Future<List<String>> Function( android_webview.WebView webView, android_webview.FileChooserParams params, )? onShowFileChooser, }) { onShowFileChooserCallback = onShowFileChooser!; return mockWebChromeClient; }, ); late final FileSelectorParams fileSelectorParams; await controller.setOnShowFileSelector( (FileSelectorParams params) async { fileSelectorParams = params; return <String>[]; }, ); verify( mockWebChromeClient.setSynchronousReturnValueForOnShowFileChooser(true), ); onShowFileChooserCallback( android_webview.WebView.detached(), android_webview.FileChooserParams.detached( isCaptureEnabled: false, acceptTypes: <String>['png'], filenameHint: 'filenameHint', mode: android_webview.FileChooserMode.open, ), ); expect(fileSelectorParams.isCaptureEnabled, isFalse); expect(fileSelectorParams.acceptTypes, <String>['png']); expect(fileSelectorParams.filenameHint, 'filenameHint'); expect(fileSelectorParams.mode, FileSelectorMode.open); }); test('runJavaScript', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.runJavaScript('alert("This is a test.");'); verify(mockWebView.evaluateJavascript('alert("This is a test.");')) .called(1); }); test('runJavaScriptReturningResult with return value', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); when(mockWebView.evaluateJavascript('return "Hello" + " World!";')) .thenAnswer((_) => Future<String>.value('Hello World!')); final String message = await controller.runJavaScriptReturningResult( 'return "Hello" + " World!";') as String; expect(message, 'Hello World!'); }); test('runJavaScriptReturningResult returning null', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); when(mockWebView.evaluateJavascript('alert("This is a test.");')) .thenAnswer((_) => Future<String?>.value()); final String message = await controller .runJavaScriptReturningResult('alert("This is a test.");') as String; expect(message, ''); }); test('runJavaScriptReturningResult parses num', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); when(mockWebView.evaluateJavascript('alert("This is a test.");')) .thenAnswer((_) => Future<String?>.value('3.14')); final num message = await controller .runJavaScriptReturningResult('alert("This is a test.");') as num; expect(message, 3.14); }); test('runJavaScriptReturningResult parses true', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); when(mockWebView.evaluateJavascript('alert("This is a test.");')) .thenAnswer((_) => Future<String?>.value('true')); final bool message = await controller .runJavaScriptReturningResult('alert("This is a test.");') as bool; expect(message, true); }); test('runJavaScriptReturningResult parses false', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); when(mockWebView.evaluateJavascript('alert("This is a test.");')) .thenAnswer((_) => Future<String?>.value('false')); final bool message = await controller .runJavaScriptReturningResult('alert("This is a test.");') as bool; expect(message, false); }); test('addJavaScriptChannel', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final AndroidJavaScriptChannelParams paramsWithMock = createAndroidJavaScriptChannelParamsWithMocks(name: 'test'); await controller.addJavaScriptChannel(paramsWithMock); verify(mockWebView.addJavaScriptChannel( argThat(isA<android_webview.JavaScriptChannel>()))) .called(1); }); test( 'addJavaScriptChannel add channel with same name should remove existing channel', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final AndroidJavaScriptChannelParams paramsWithMock = createAndroidJavaScriptChannelParamsWithMocks(name: 'test'); await controller.addJavaScriptChannel(paramsWithMock); verify(mockWebView.addJavaScriptChannel( argThat(isA<android_webview.JavaScriptChannel>()))) .called(1); await controller.addJavaScriptChannel(paramsWithMock); verifyInOrder(<Object>[ mockWebView.removeJavaScriptChannel( argThat(isA<android_webview.JavaScriptChannel>())), mockWebView.addJavaScriptChannel( argThat(isA<android_webview.JavaScriptChannel>())), ]); }); test('removeJavaScriptChannel when channel is not registered', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.removeJavaScriptChannel('test'); verifyNever(mockWebView.removeJavaScriptChannel(any)); }); test('removeJavaScriptChannel when channel exists', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); final AndroidJavaScriptChannelParams paramsWithMock = createAndroidJavaScriptChannelParamsWithMocks(name: 'test'); // Make sure channel exists before removing it. await controller.addJavaScriptChannel(paramsWithMock); verify(mockWebView.addJavaScriptChannel( argThat(isA<android_webview.JavaScriptChannel>()))) .called(1); await controller.removeJavaScriptChannel('test'); verify(mockWebView.removeJavaScriptChannel( argThat(isA<android_webview.JavaScriptChannel>()))) .called(1); }); test('getTitle', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.getTitle(); verify(mockWebView.getTitle()).called(1); }); test('scrollTo', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.scrollTo(4, 2); verify(mockWebView.scrollTo(4, 2)).called(1); }); test('scrollBy', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.scrollBy(4, 2); verify(mockWebView.scrollBy(4, 2)).called(1); }); test('getScrollPosition', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); when(mockWebView.getScrollPosition()) .thenAnswer((_) => Future<Offset>.value(const Offset(4, 2))); final Offset position = await controller.getScrollPosition(); verify(mockWebView.getScrollPosition()).called(1); expect(position.dx, 4); expect(position.dy, 2); }); test('enableDebugging', () async { final MockAndroidWebViewProxy mockProxy = MockAndroidWebViewProxy(); await AndroidWebViewController.enableDebugging( true, webViewProxy: mockProxy, ); verify(mockProxy.setWebContentsDebuggingEnabled(true)).called(1); }); test('enableZoom', () async { final MockWebView mockWebView = MockWebView(); final MockWebSettings mockSettings = MockWebSettings(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, mockSettings: mockSettings, ); clearInteractions(mockWebView); await controller.enableZoom(true); verify(mockWebView.settings).called(1); verify(mockSettings.setSupportZoom(true)).called(1); }); test('setBackgroundColor', () async { final MockWebView mockWebView = MockWebView(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); await controller.setBackgroundColor(Colors.blue); verify(mockWebView.setBackgroundColor(Colors.blue)).called(1); }); test('setJavaScriptMode', () async { final MockWebView mockWebView = MockWebView(); final MockWebSettings mockSettings = MockWebSettings(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, mockSettings: mockSettings, ); clearInteractions(mockWebView); await controller.setJavaScriptMode(JavaScriptMode.disabled); verify(mockWebView.settings).called(1); verify(mockSettings.setJavaScriptEnabled(false)).called(1); }); test('setUserAgent', () async { final MockWebView mockWebView = MockWebView(); final MockWebSettings mockSettings = MockWebSettings(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, mockSettings: mockSettings, ); clearInteractions(mockWebView); await controller.setUserAgent('Test Framework'); verify(mockWebView.settings).called(1); verify(mockSettings.setUserAgentString('Test Framework')).called(1); }); }); test('setMediaPlaybackRequiresUserGesture', () async { final MockWebView mockWebView = MockWebView(); final MockWebSettings mockSettings = MockWebSettings(); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, mockSettings: mockSettings, ); await controller.setMediaPlaybackRequiresUserGesture(true); verify(mockSettings.setMediaPlaybackRequiresUserGesture(true)).called(1); }); test('webViewIdentifier', () { final MockWebView mockWebView = MockWebView(); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); instanceManager.addHostCreatedInstance(mockWebView, 0); android_webview.WebView.api = WebViewHostApiImpl( instanceManager: instanceManager, ); final AndroidWebViewController controller = createControllerWithMocks( mockWebView: mockWebView, ); expect( controller.webViewIdentifier, 0, ); android_webview.WebView.api = WebViewHostApiImpl(); }); group('AndroidWebViewWidget', () { testWidgets('Builds Android view using supplied parameters', (WidgetTester tester) async { final AndroidWebViewController controller = createControllerWithMocks(); final AndroidWebViewWidget webViewWidget = AndroidWebViewWidget( AndroidWebViewWidgetCreationParams( key: const Key('test_web_view'), controller: controller, ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) => webViewWidget.build(context), )); expect(find.byType(PlatformViewLink), findsOneWidget); expect(find.byKey(const Key('test_web_view')), findsOneWidget); }); testWidgets('displayWithHybridComposition is false', (WidgetTester tester) async { final AndroidWebViewController controller = createControllerWithMocks(); final MockPlatformViewsServiceProxy mockPlatformViewsService = MockPlatformViewsServiceProxy(); when( mockPlatformViewsService.initSurfaceAndroidView( id: anyNamed('id'), viewType: anyNamed('viewType'), layoutDirection: anyNamed('layoutDirection'), creationParams: anyNamed('creationParams'), creationParamsCodec: anyNamed('creationParamsCodec'), onFocus: anyNamed('onFocus'), ), ).thenReturn(MockSurfaceAndroidViewController()); final AndroidWebViewWidget webViewWidget = AndroidWebViewWidget( AndroidWebViewWidgetCreationParams( key: const Key('test_web_view'), controller: controller, platformViewsServiceProxy: mockPlatformViewsService, ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) => webViewWidget.build(context), )); await tester.pumpAndSettle(); verify( mockPlatformViewsService.initSurfaceAndroidView( id: anyNamed('id'), viewType: anyNamed('viewType'), layoutDirection: anyNamed('layoutDirection'), creationParams: anyNamed('creationParams'), creationParamsCodec: anyNamed('creationParamsCodec'), onFocus: anyNamed('onFocus'), ), ); }); testWidgets('displayWithHybridComposition is true', (WidgetTester tester) async { final AndroidWebViewController controller = createControllerWithMocks(); final MockPlatformViewsServiceProxy mockPlatformViewsService = MockPlatformViewsServiceProxy(); when( mockPlatformViewsService.initExpensiveAndroidView( id: anyNamed('id'), viewType: anyNamed('viewType'), layoutDirection: anyNamed('layoutDirection'), creationParams: anyNamed('creationParams'), creationParamsCodec: anyNamed('creationParamsCodec'), onFocus: anyNamed('onFocus'), ), ).thenReturn(MockExpensiveAndroidViewController()); final AndroidWebViewWidget webViewWidget = AndroidWebViewWidget( AndroidWebViewWidgetCreationParams( key: const Key('test_web_view'), controller: controller, platformViewsServiceProxy: mockPlatformViewsService, displayWithHybridComposition: true, ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) => webViewWidget.build(context), )); await tester.pumpAndSettle(); verify( mockPlatformViewsService.initExpensiveAndroidView( id: anyNamed('id'), viewType: anyNamed('viewType'), layoutDirection: anyNamed('layoutDirection'), creationParams: anyNamed('creationParams'), creationParamsCodec: anyNamed('creationParamsCodec'), onFocus: anyNamed('onFocus'), ), ); }); }); }
plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart", "repo_id": "plugins", "token_count": 14096 }
1,300
// 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 cookie that can be set globally for all web views /// using [WebViewCookieManagerPlatform]. class WebViewCookie { /// Constructs a new [WebViewCookie]. const WebViewCookie( {required this.name, required this.value, required this.domain, this.path = '/'}); /// The cookie-name of the cookie. /// /// Its value should match "cookie-name" in RFC6265bis: /// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1 final String name; /// The cookie-value of the cookie. /// /// Its value should match "cookie-value" in RFC6265bis: /// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1 final String value; /// The domain-value of the cookie. /// /// Its value should match "domain-value" in RFC6265bis: /// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1 final String domain; /// The path-value of the cookie. /// Is set to `/` in the constructor by default. /// /// Its value should match "path-value" in RFC6265bis: /// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-02#section-4.1.1 final String path; /// Serializes the [WebViewCookie] to a Map<String, String>. Map<String, String> toJson() { return <String, String>{ 'name': name, 'value': value, 'domain': domain, 'path': path }; } }
plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_cookie.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/webview_cookie.dart", "repo_id": "plugins", "token_count": 573 }
1,301
// Mocks generated by Mockito 5.3.2 from annotations // in webview_flutter_platform_interface/test/webview_platform_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_platform_interface/src/platform_navigation_delegate.dart' as _i3; import 'package:webview_flutter_platform_interface/src/platform_webview_controller.dart' as _i4; import 'package:webview_flutter_platform_interface/src/platform_webview_cookie_manager.dart' as _i2; import 'package:webview_flutter_platform_interface/src/platform_webview_widget.dart' as _i5; import 'package:webview_flutter_platform_interface/src/types/types.dart' as _i7; import 'package:webview_flutter_platform_interface/src/webview_platform.dart' as _i6; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakePlatformWebViewCookieManager_0 extends _i1.SmartFake implements _i2.PlatformWebViewCookieManager { _FakePlatformWebViewCookieManager_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformNavigationDelegate_1 extends _i1.SmartFake implements _i3.PlatformNavigationDelegate { _FakePlatformNavigationDelegate_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformWebViewController_2 extends _i1.SmartFake implements _i4.PlatformWebViewController { _FakePlatformWebViewController_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePlatformWebViewWidget_3 extends _i1.SmartFake implements _i5.PlatformWebViewWidget { _FakePlatformWebViewWidget_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [WebViewPlatform]. /// /// See the documentation for Mockito's code generation for more information. class MockWebViewPlatform extends _i1.Mock implements _i6.WebViewPlatform { MockWebViewPlatform() { _i1.throwOnMissingStub(this); } @override _i2.PlatformWebViewCookieManager createPlatformCookieManager( _i7.PlatformWebViewCookieManagerCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformCookieManager, [params], ), returnValue: _FakePlatformWebViewCookieManager_0( this, Invocation.method( #createPlatformCookieManager, [params], ), ), ) as _i2.PlatformWebViewCookieManager); @override _i3.PlatformNavigationDelegate createPlatformNavigationDelegate( _i7.PlatformNavigationDelegateCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformNavigationDelegate, [params], ), returnValue: _FakePlatformNavigationDelegate_1( this, Invocation.method( #createPlatformNavigationDelegate, [params], ), ), ) as _i3.PlatformNavigationDelegate); @override _i4.PlatformWebViewController createPlatformWebViewController( _i7.PlatformWebViewControllerCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformWebViewController, [params], ), returnValue: _FakePlatformWebViewController_2( this, Invocation.method( #createPlatformWebViewController, [params], ), ), ) as _i4.PlatformWebViewController); @override _i5.PlatformWebViewWidget createPlatformWebViewWidget( _i7.PlatformWebViewWidgetCreationParams? params) => (super.noSuchMethod( Invocation.method( #createPlatformWebViewWidget, [params], ), returnValue: _FakePlatformWebViewWidget_3( this, Invocation.method( #createPlatformWebViewWidget, [params], ), ), ) as _i5.PlatformWebViewWidget); }
plugins/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.mocks.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/test/webview_platform_test.mocks.dart", "repo_id": "plugins", "token_count": 1888 }
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 Flutter; @import XCTest; @import webview_flutter_wkwebview; #import <OCMock/OCMock.h> @interface FWFUserContentControllerHostApiTests : XCTestCase @end @implementation FWFUserContentControllerHostApiTests - (void)testCreateFromWebViewConfigurationWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFUserContentControllerHostApiImpl *hostAPI = [[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]; [instanceManager addDartCreatedInstance:[[WKWebViewConfiguration alloc] init] withIdentifier:0]; FlutterError *error; [hostAPI createFromWebViewConfigurationWithIdentifier:@1 configurationIdentifier:@0 error:&error]; WKUserContentController *userContentController = (WKUserContentController *)[instanceManager instanceForIdentifier:1]; XCTAssertTrue([userContentController isKindOfClass:[WKUserContentController class]]); XCTAssertNil(error); } - (void)testAddScriptMessageHandler { WKUserContentController *mockUserContentController = OCMClassMock([WKUserContentController class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockUserContentController withIdentifier:0]; FWFUserContentControllerHostApiImpl *hostAPI = [[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]; id<WKScriptMessageHandler> mockMessageHandler = OCMProtocolMock(@protocol(WKScriptMessageHandler)); [instanceManager addDartCreatedInstance:mockMessageHandler withIdentifier:1]; FlutterError *error; [hostAPI addScriptMessageHandlerForControllerWithIdentifier:@0 handlerIdentifier:@1 ofName:@"apple" error:&error]; OCMVerify([mockUserContentController addScriptMessageHandler:mockMessageHandler name:@"apple"]); XCTAssertNil(error); } - (void)testRemoveScriptMessageHandler { WKUserContentController *mockUserContentController = OCMClassMock([WKUserContentController class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockUserContentController withIdentifier:0]; FWFUserContentControllerHostApiImpl *hostAPI = [[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]; FlutterError *error; [hostAPI removeScriptMessageHandlerForControllerWithIdentifier:@0 name:@"apple" error:&error]; OCMVerify([mockUserContentController removeScriptMessageHandlerForName:@"apple"]); XCTAssertNil(error); } - (void)testRemoveAllScriptMessageHandlers API_AVAILABLE(ios(14.0)) { WKUserContentController *mockUserContentController = OCMClassMock([WKUserContentController class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockUserContentController withIdentifier:0]; FWFUserContentControllerHostApiImpl *hostAPI = [[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]; FlutterError *error; [hostAPI removeAllScriptMessageHandlersForControllerWithIdentifier:@0 error:&error]; OCMVerify([mockUserContentController removeAllScriptMessageHandlers]); XCTAssertNil(error); } - (void)testAddUserScript { WKUserContentController *mockUserContentController = OCMClassMock([WKUserContentController class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockUserContentController withIdentifier:0]; FWFUserContentControllerHostApiImpl *hostAPI = [[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]; FlutterError *error; [hostAPI addUserScriptForControllerWithIdentifier:@0 userScript: [FWFWKUserScriptData makeWithSource:@"runAScript" injectionTime: [FWFWKUserScriptInjectionTimeEnumData makeWithValue: FWFWKUserScriptInjectionTimeEnumAtDocumentEnd] isMainFrameOnly:@YES] error:&error]; OCMVerify([mockUserContentController addUserScript:[OCMArg isKindOfClass:[WKUserScript class]]]); XCTAssertNil(error); } - (void)testRemoveAllUserScripts { WKUserContentController *mockUserContentController = OCMClassMock([WKUserContentController class]); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockUserContentController withIdentifier:0]; FWFUserContentControllerHostApiImpl *hostAPI = [[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]; FlutterError *error; [hostAPI removeAllUserScriptsForControllerWithIdentifier:@0 error:&error]; OCMVerify([mockUserContentController removeAllUserScripts]); XCTAssertNil(error); } @end
plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFUserContentControllerHostApiTests.m/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFUserContentControllerHostApiTests.m", "repo_id": "plugins", "token_count": 2032 }
1,303
// 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 "FLTWebViewFlutterPlugin.h" #import "FWFGeneratedWebKitApis.h" #import "FWFHTTPCookieStoreHostApi.h" #import "FWFInstanceManager.h" #import "FWFNavigationDelegateHostApi.h" #import "FWFObjectHostApi.h" #import "FWFPreferencesHostApi.h" #import "FWFScriptMessageHandlerHostApi.h" #import "FWFScrollViewHostApi.h" #import "FWFUIDelegateHostApi.h" #import "FWFUIViewHostApi.h" #import "FWFUserContentControllerHostApi.h" #import "FWFWebViewConfigurationHostApi.h" #import "FWFWebViewHostApi.h" #import "FWFWebsiteDataStoreHostApi.h" @interface FWFWebViewFactory : NSObject <FlutterPlatformViewFactory> @property(nonatomic, weak) FWFInstanceManager *instanceManager; - (instancetype)initWithManager:(FWFInstanceManager *)manager; @end @implementation FWFWebViewFactory - (instancetype)initWithManager:(FWFInstanceManager *)manager { self = [self init]; if (self) { _instanceManager = manager; } return self; } - (NSObject<FlutterMessageCodec> *)createArgsCodec { return [FlutterStandardMessageCodec sharedInstance]; } - (NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args { NSNumber *identifier = (NSNumber *)args; FWFWebView *webView = (FWFWebView *)[self.instanceManager instanceForIdentifier:identifier.longValue]; webView.frame = frame; return webView; } @end @implementation FLTWebViewFlutterPlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] initWithDeallocCallback:^(long identifier) { FWFObjectFlutterApiImpl *objectApi = [[FWFObjectFlutterApiImpl alloc] initWithBinaryMessenger:registrar.messenger instanceManager:[[FWFInstanceManager alloc] init]]; dispatch_async(dispatch_get_main_queue(), ^{ [objectApi disposeObjectWithIdentifier:@(identifier) completion:^(NSError *error) { NSAssert(!error, @"%@", error); }]; }); }]; FWFWKHttpCookieStoreHostApiSetup( registrar.messenger, [[FWFHTTPCookieStoreHostApiImpl alloc] initWithInstanceManager:instanceManager]); FWFWKNavigationDelegateHostApiSetup( registrar.messenger, [[FWFNavigationDelegateHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger instanceManager:instanceManager]); FWFNSObjectHostApiSetup(registrar.messenger, [[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager]); FWFWKPreferencesHostApiSetup(registrar.messenger, [[FWFPreferencesHostApiImpl alloc] initWithInstanceManager:instanceManager]); FWFWKScriptMessageHandlerHostApiSetup( registrar.messenger, [[FWFScriptMessageHandlerHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger instanceManager:instanceManager]); FWFUIScrollViewHostApiSetup(registrar.messenger, [[FWFScrollViewHostApiImpl alloc] initWithInstanceManager:instanceManager]); FWFWKUIDelegateHostApiSetup(registrar.messenger, [[FWFUIDelegateHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger instanceManager:instanceManager]); FWFUIViewHostApiSetup(registrar.messenger, [[FWFUIViewHostApiImpl alloc] initWithInstanceManager:instanceManager]); FWFWKUserContentControllerHostApiSetup( registrar.messenger, [[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]); FWFWKWebsiteDataStoreHostApiSetup( registrar.messenger, [[FWFWebsiteDataStoreHostApiImpl alloc] initWithInstanceManager:instanceManager]); FWFWKWebViewConfigurationHostApiSetup( registrar.messenger, [[FWFWebViewConfigurationHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger instanceManager:instanceManager]); FWFWKWebViewHostApiSetup(registrar.messenger, [[FWFWebViewHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger instanceManager:instanceManager]); FWFWebViewFactory *webviewFactory = [[FWFWebViewFactory alloc] initWithManager:instanceManager]; [registrar registerViewFactory:webviewFactory withId:@"plugins.flutter.io/webview"]; // InstanceManager is published so that a strong reference is maintained. [registrar publish:instanceManager]; } - (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { [registrar publish:[NSNull null]]; } @end
plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FLTWebViewFlutterPlugin.m/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FLTWebViewFlutterPlugin.m", "repo_id": "plugins", "token_count": 2272 }
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 <Flutter/Flutter.h> #import <WebKit/WebKit.h> #import "FWFGeneratedWebKitApis.h" #import "FWFInstanceManager.h" #import "FWFObjectHostApi.h" NS_ASSUME_NONNULL_BEGIN /** * Flutter api implementation for WKScriptMessageHandler. * * Handles making callbacks to Dart for a WKScriptMessageHandler. */ @interface FWFScriptMessageHandlerFlutterApiImpl : FWFWKScriptMessageHandlerFlutterApi - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; @end /** * Implementation of WKScriptMessageHandler for FWFScriptMessageHandlerHostApiImpl. */ @interface FWFScriptMessageHandler : FWFObject <WKScriptMessageHandler> @property(readonly, nonnull, nonatomic) FWFScriptMessageHandlerFlutterApiImpl *scriptMessageHandlerAPI; - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; @end /** * Host api implementation for WKScriptMessageHandler. * * Handles creating WKScriptMessageHandler that intercommunicate with a paired Dart object. */ @interface FWFScriptMessageHandlerHostApiImpl : NSObject <FWFWKScriptMessageHandlerHostApi> - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager; @end NS_ASSUME_NONNULL_END
plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScriptMessageHandlerHostApi.h/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScriptMessageHandlerHostApi.h", "repo_id": "plugins", "token_count": 530 }
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 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../common/instance_manager.dart'; import '../common/web_kit.g.dart'; import '../foundation/foundation.dart'; import 'web_kit.dart'; export '../common/web_kit.g.dart' show WKNavigationType; Iterable<WKWebsiteDataTypeEnumData> _toWKWebsiteDataTypeEnumData( Iterable<WKWebsiteDataType> types) { return types.map<WKWebsiteDataTypeEnumData>((WKWebsiteDataType type) { late final WKWebsiteDataTypeEnum value; switch (type) { case WKWebsiteDataType.cookies: value = WKWebsiteDataTypeEnum.cookies; break; case WKWebsiteDataType.memoryCache: value = WKWebsiteDataTypeEnum.memoryCache; break; case WKWebsiteDataType.diskCache: value = WKWebsiteDataTypeEnum.diskCache; break; case WKWebsiteDataType.offlineWebApplicationCache: value = WKWebsiteDataTypeEnum.offlineWebApplicationCache; break; case WKWebsiteDataType.localStorage: value = WKWebsiteDataTypeEnum.localStorage; break; case WKWebsiteDataType.sessionStorage: value = WKWebsiteDataTypeEnum.sessionStorage; break; case WKWebsiteDataType.webSQLDatabases: value = WKWebsiteDataTypeEnum.webSQLDatabases; break; case WKWebsiteDataType.indexedDBDatabases: value = WKWebsiteDataTypeEnum.indexedDBDatabases; break; } return WKWebsiteDataTypeEnumData(value: value); }); } extension _NSHttpCookieConverter on NSHttpCookie { NSHttpCookieData toNSHttpCookieData() { final Iterable<NSHttpCookiePropertyKey> keys = properties.keys; return NSHttpCookieData( propertyKeys: keys.map<NSHttpCookiePropertyKeyEnumData>( (NSHttpCookiePropertyKey key) { return key.toNSHttpCookiePropertyKeyEnumData(); }, ).toList(), propertyValues: keys .map<Object>((NSHttpCookiePropertyKey key) => properties[key]!) .toList(), ); } } extension _WKNavigationActionPolicyConverter on WKNavigationActionPolicy { WKNavigationActionPolicyEnumData toWKNavigationActionPolicyEnumData() { return WKNavigationActionPolicyEnumData( value: WKNavigationActionPolicyEnum.values.firstWhere( (WKNavigationActionPolicyEnum element) => element.name == name, ), ); } } extension _NSHttpCookiePropertyKeyConverter on NSHttpCookiePropertyKey { NSHttpCookiePropertyKeyEnumData toNSHttpCookiePropertyKeyEnumData() { late final NSHttpCookiePropertyKeyEnum value; switch (this) { case NSHttpCookiePropertyKey.comment: value = NSHttpCookiePropertyKeyEnum.comment; break; case NSHttpCookiePropertyKey.commentUrl: value = NSHttpCookiePropertyKeyEnum.commentUrl; break; case NSHttpCookiePropertyKey.discard: value = NSHttpCookiePropertyKeyEnum.discard; break; case NSHttpCookiePropertyKey.domain: value = NSHttpCookiePropertyKeyEnum.domain; break; case NSHttpCookiePropertyKey.expires: value = NSHttpCookiePropertyKeyEnum.expires; break; case NSHttpCookiePropertyKey.maximumAge: value = NSHttpCookiePropertyKeyEnum.maximumAge; break; case NSHttpCookiePropertyKey.name: value = NSHttpCookiePropertyKeyEnum.name; break; case NSHttpCookiePropertyKey.originUrl: value = NSHttpCookiePropertyKeyEnum.originUrl; break; case NSHttpCookiePropertyKey.path: value = NSHttpCookiePropertyKeyEnum.path; break; case NSHttpCookiePropertyKey.port: value = NSHttpCookiePropertyKeyEnum.port; break; case NSHttpCookiePropertyKey.sameSitePolicy: value = NSHttpCookiePropertyKeyEnum.sameSitePolicy; break; case NSHttpCookiePropertyKey.secure: value = NSHttpCookiePropertyKeyEnum.secure; break; case NSHttpCookiePropertyKey.value: value = NSHttpCookiePropertyKeyEnum.value; break; case NSHttpCookiePropertyKey.version: value = NSHttpCookiePropertyKeyEnum.version; break; } return NSHttpCookiePropertyKeyEnumData(value: value); } } extension _WKUserScriptInjectionTimeConverter on WKUserScriptInjectionTime { WKUserScriptInjectionTimeEnumData toWKUserScriptInjectionTimeEnumData() { late final WKUserScriptInjectionTimeEnum value; switch (this) { case WKUserScriptInjectionTime.atDocumentStart: value = WKUserScriptInjectionTimeEnum.atDocumentStart; break; case WKUserScriptInjectionTime.atDocumentEnd: value = WKUserScriptInjectionTimeEnum.atDocumentEnd; break; } return WKUserScriptInjectionTimeEnumData(value: value); } } Iterable<WKAudiovisualMediaTypeEnumData> _toWKAudiovisualMediaTypeEnumData( Iterable<WKAudiovisualMediaType> types, ) { return types .map<WKAudiovisualMediaTypeEnumData>((WKAudiovisualMediaType type) { late final WKAudiovisualMediaTypeEnum value; switch (type) { case WKAudiovisualMediaType.none: value = WKAudiovisualMediaTypeEnum.none; break; case WKAudiovisualMediaType.audio: value = WKAudiovisualMediaTypeEnum.audio; break; case WKAudiovisualMediaType.video: value = WKAudiovisualMediaTypeEnum.video; break; case WKAudiovisualMediaType.all: value = WKAudiovisualMediaTypeEnum.all; break; } return WKAudiovisualMediaTypeEnumData(value: value); }); } extension _NavigationActionDataConverter on WKNavigationActionData { WKNavigationAction toNavigationAction() { return WKNavigationAction( request: request.toNSUrlRequest(), targetFrame: targetFrame.toWKFrameInfo(), navigationType: navigationType, ); } } extension _WKFrameInfoDataConverter on WKFrameInfoData { WKFrameInfo toWKFrameInfo() { return WKFrameInfo(isMainFrame: isMainFrame); } } extension _NSUrlRequestDataConverter on NSUrlRequestData { NSUrlRequest toNSUrlRequest() { return NSUrlRequest( url: url, httpBody: httpBody, httpMethod: httpMethod, allHttpHeaderFields: allHttpHeaderFields.cast(), ); } } extension _WKNSErrorDataConverter on NSErrorData { NSError toNSError() { return NSError( domain: domain, code: code, localizedDescription: localizedDescription, ); } } extension _WKScriptMessageDataConverter on WKScriptMessageData { WKScriptMessage toWKScriptMessage() { return WKScriptMessage(name: name, body: body); } } extension _WKUserScriptConverter on WKUserScript { WKUserScriptData toWKUserScriptData() { return WKUserScriptData( source: source, injectionTime: injectionTime.toWKUserScriptInjectionTimeEnumData(), isMainFrameOnly: isMainFrameOnly, ); } } extension _NSUrlRequestConverter on NSUrlRequest { NSUrlRequestData toNSUrlRequestData() { return NSUrlRequestData( url: url, httpMethod: httpMethod, httpBody: httpBody, allHttpHeaderFields: allHttpHeaderFields, ); } } /// Handles initialization of Flutter APIs for WebKit. class WebKitFlutterApis { /// Constructs a [WebKitFlutterApis]. @visibleForTesting WebKitFlutterApis({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _binaryMessenger = binaryMessenger, navigationDelegate = WKNavigationDelegateFlutterApiImpl( instanceManager: instanceManager, ), scriptMessageHandler = WKScriptMessageHandlerFlutterApiImpl( instanceManager: instanceManager, ), uiDelegate = WKUIDelegateFlutterApiImpl( instanceManager: instanceManager, ), webViewConfiguration = WKWebViewConfigurationFlutterApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ); static WebKitFlutterApis _instance = WebKitFlutterApis(); /// Sets the global instance containing the Flutter Apis for the WebKit library. @visibleForTesting static set instance(WebKitFlutterApis instance) { _instance = instance; } /// Global instance containing the Flutter Apis for the WebKit library. static WebKitFlutterApis get instance { return _instance; } final BinaryMessenger? _binaryMessenger; bool _hasBeenSetUp = false; /// Flutter Api for [WKNavigationDelegate]. @visibleForTesting final WKNavigationDelegateFlutterApiImpl navigationDelegate; /// Flutter Api for [WKScriptMessageHandler]. @visibleForTesting final WKScriptMessageHandlerFlutterApiImpl scriptMessageHandler; /// Flutter Api for [WKUIDelegate]. @visibleForTesting final WKUIDelegateFlutterApiImpl uiDelegate; /// Flutter Api for [WKWebViewConfiguration]. @visibleForTesting final WKWebViewConfigurationFlutterApiImpl webViewConfiguration; /// Ensures all the Flutter APIs have been set up to receive calls from native code. void ensureSetUp() { if (!_hasBeenSetUp) { WKNavigationDelegateFlutterApi.setup( navigationDelegate, binaryMessenger: _binaryMessenger, ); WKScriptMessageHandlerFlutterApi.setup( scriptMessageHandler, binaryMessenger: _binaryMessenger, ); WKUIDelegateFlutterApi.setup( uiDelegate, binaryMessenger: _binaryMessenger, ); WKWebViewConfigurationFlutterApi.setup( webViewConfiguration, binaryMessenger: _binaryMessenger, ); _hasBeenSetUp = true; } } } /// Host api implementation for [WKWebSiteDataStore]. class WKWebsiteDataStoreHostApiImpl extends WKWebsiteDataStoreHostApi { /// Constructs a [WebsiteDataStoreHostApiImpl]. WKWebsiteDataStoreHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebViewConfiguration] with the ids of the provided object instances. Future<void> createFromWebViewConfigurationForInstances( WKWebsiteDataStore instance, WKWebViewConfiguration configuration, ) { return createFromWebViewConfiguration( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(configuration)!, ); } /// Calls [createDefaultDataStore] with the ids of the provided object instances. Future<void> createDefaultDataStoreForInstances( WKWebsiteDataStore instance, ) { return createDefaultDataStore( instanceManager.addDartCreatedInstance(instance), ); } /// Calls [removeDataOfTypes] with the ids of the provided object instances. Future<bool> removeDataOfTypesForInstances( WKWebsiteDataStore instance, Set<WKWebsiteDataType> dataTypes, { required double secondsModifiedSinceEpoch, }) { return removeDataOfTypes( instanceManager.getIdentifier(instance)!, _toWKWebsiteDataTypeEnumData(dataTypes).toList(), secondsModifiedSinceEpoch, ); } } /// Host api implementation for [WKScriptMessageHandler]. class WKScriptMessageHandlerHostApiImpl extends WKScriptMessageHandlerHostApi { /// Constructs a [WKScriptMessageHandlerHostApiImpl]. WKScriptMessageHandlerHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances(WKScriptMessageHandler instance) { return create(instanceManager.addDartCreatedInstance(instance)); } } /// Flutter api implementation for [WKScriptMessageHandler]. class WKScriptMessageHandlerFlutterApiImpl extends WKScriptMessageHandlerFlutterApi { /// Constructs a [WKScriptMessageHandlerFlutterApiImpl]. WKScriptMessageHandlerFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; WKScriptMessageHandler _getHandler(int identifier) { return instanceManager.getInstanceWithWeakReference(identifier)!; } @override void didReceiveScriptMessage( int identifier, int userContentControllerIdentifier, WKScriptMessageData message, ) { _getHandler(identifier).didReceiveScriptMessage( instanceManager.getInstanceWithWeakReference( userContentControllerIdentifier, )! as WKUserContentController, message.toWKScriptMessage(), ); } } /// Host api implementation for [WKPreferences]. class WKPreferencesHostApiImpl extends WKPreferencesHostApi { /// Constructs a [WKPreferencesHostApiImpl]. WKPreferencesHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebViewConfiguration] with the ids of the provided object instances. Future<void> createFromWebViewConfigurationForInstances( WKPreferences instance, WKWebViewConfiguration configuration, ) { return createFromWebViewConfiguration( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(configuration)!, ); } /// Calls [setJavaScriptEnabled] with the ids of the provided object instances. Future<void> setJavaScriptEnabledForInstances( WKPreferences instance, bool enabled, ) { return setJavaScriptEnabled( instanceManager.getIdentifier(instance)!, enabled, ); } } /// Host api implementation for [WKHttpCookieStore]. class WKHttpCookieStoreHostApiImpl extends WKHttpCookieStoreHostApi { /// Constructs a [WKHttpCookieStoreHostApiImpl]. WKHttpCookieStoreHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebsiteDataStore] with the ids of the provided object instances. Future<void> createFromWebsiteDataStoreForInstances( WKHttpCookieStore instance, WKWebsiteDataStore dataStore, ) { return createFromWebsiteDataStore( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(dataStore)!, ); } /// Calls [setCookie] with the ids of the provided object instances. Future<void> setCookieForInstances( WKHttpCookieStore instance, NSHttpCookie cookie, ) { return setCookie( instanceManager.getIdentifier(instance)!, cookie.toNSHttpCookieData(), ); } } /// Host api implementation for [WKUserContentController]. class WKUserContentControllerHostApiImpl extends WKUserContentControllerHostApi { /// Constructs a [WKUserContentControllerHostApiImpl]. WKUserContentControllerHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebViewConfiguration] with the ids of the provided object instances. Future<void> createFromWebViewConfigurationForInstances( WKUserContentController instance, WKWebViewConfiguration configuration, ) { return createFromWebViewConfiguration( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(configuration)!, ); } /// Calls [addScriptMessageHandler] with the ids of the provided object instances. Future<void> addScriptMessageHandlerForInstances( WKUserContentController instance, WKScriptMessageHandler handler, String name, ) { return addScriptMessageHandler( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(handler)!, name, ); } /// Calls [removeScriptMessageHandler] with the ids of the provided object instances. Future<void> removeScriptMessageHandlerForInstances( WKUserContentController instance, String name, ) { return removeScriptMessageHandler( instanceManager.getIdentifier(instance)!, name, ); } /// Calls [removeAllScriptMessageHandlers] with the ids of the provided object instances. Future<void> removeAllScriptMessageHandlersForInstances( WKUserContentController instance, ) { return removeAllScriptMessageHandlers( instanceManager.getIdentifier(instance)!, ); } /// Calls [addUserScript] with the ids of the provided object instances. Future<void> addUserScriptForInstances( WKUserContentController instance, WKUserScript userScript, ) { return addUserScript( instanceManager.getIdentifier(instance)!, userScript.toWKUserScriptData(), ); } /// Calls [removeAllUserScripts] with the ids of the provided object instances. Future<void> removeAllUserScriptsForInstances( WKUserContentController instance, ) { return removeAllUserScripts(instanceManager.getIdentifier(instance)!); } } /// Host api implementation for [WKWebViewConfiguration]. class WKWebViewConfigurationHostApiImpl extends WKWebViewConfigurationHostApi { /// Constructs a [WKWebViewConfigurationHostApiImpl]. WKWebViewConfigurationHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances(WKWebViewConfiguration instance) { return create(instanceManager.addDartCreatedInstance(instance)); } /// Calls [createFromWebView] with the ids of the provided object instances. Future<void> createFromWebViewForInstances( WKWebViewConfiguration instance, WKWebView webView, ) { return createFromWebView( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(webView)!, ); } /// Calls [setAllowsInlineMediaPlayback] with the ids of the provided object instances. Future<void> setAllowsInlineMediaPlaybackForInstances( WKWebViewConfiguration instance, bool allow, ) { return setAllowsInlineMediaPlayback( instanceManager.getIdentifier(instance)!, allow, ); } /// Calls [setMediaTypesRequiringUserActionForPlayback] with the ids of the provided object instances. Future<void> setMediaTypesRequiringUserActionForPlaybackForInstances( WKWebViewConfiguration instance, Set<WKAudiovisualMediaType> types, ) { return setMediaTypesRequiringUserActionForPlayback( instanceManager.getIdentifier(instance)!, _toWKAudiovisualMediaTypeEnumData(types).toList(), ); } } /// Flutter api implementation for [WKWebViewConfiguration]. @immutable class WKWebViewConfigurationFlutterApiImpl extends WKWebViewConfigurationFlutterApi { /// Constructs a [WKWebViewConfigurationFlutterApiImpl]. WKWebViewConfigurationFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; @override void create(int identifier) { instanceManager.addHostCreatedInstance( WKWebViewConfiguration.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), identifier, ); } } /// Host api implementation for [WKUIDelegate]. class WKUIDelegateHostApiImpl extends WKUIDelegateHostApi { /// Constructs a [WKUIDelegateHostApiImpl]. WKUIDelegateHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances(WKUIDelegate instance) async { return create(instanceManager.addDartCreatedInstance(instance)); } } /// Flutter api implementation for [WKUIDelegate]. class WKUIDelegateFlutterApiImpl extends WKUIDelegateFlutterApi { /// Constructs a [WKUIDelegateFlutterApiImpl]. WKUIDelegateFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; WKUIDelegate _getDelegate(int identifier) { return instanceManager.getInstanceWithWeakReference(identifier)!; } @override void onCreateWebView( int identifier, int webViewIdentifier, int configurationIdentifier, WKNavigationActionData navigationAction, ) { final void Function(WKWebView, WKWebViewConfiguration, WKNavigationAction)? function = _getDelegate(identifier).onCreateWebView; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, instanceManager.getInstanceWithWeakReference(configurationIdentifier)! as WKWebViewConfiguration, navigationAction.toNavigationAction(), ); } } /// Host api implementation for [WKNavigationDelegate]. class WKNavigationDelegateHostApiImpl extends WKNavigationDelegateHostApi { /// Constructs a [WKNavigationDelegateHostApiImpl]. WKNavigationDelegateHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances(WKNavigationDelegate instance) async { return create(instanceManager.addDartCreatedInstance(instance)); } } /// Flutter api implementation for [WKNavigationDelegate]. class WKNavigationDelegateFlutterApiImpl extends WKNavigationDelegateFlutterApi { /// Constructs a [WKNavigationDelegateFlutterApiImpl]. WKNavigationDelegateFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; WKNavigationDelegate _getDelegate(int identifier) { return instanceManager.getInstanceWithWeakReference(identifier)!; } @override void didFinishNavigation( int identifier, int webViewIdentifier, String? url, ) { final void Function(WKWebView, String?)? function = _getDelegate(identifier).didFinishNavigation; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, url, ); } @override Future<WKNavigationActionPolicyEnumData> decidePolicyForNavigationAction( int identifier, int webViewIdentifier, WKNavigationActionData navigationAction, ) async { final Future<WKNavigationActionPolicy> Function( WKWebView, WKNavigationAction navigationAction, )? function = _getDelegate(identifier).decidePolicyForNavigationAction; if (function == null) { return WKNavigationActionPolicyEnumData( value: WKNavigationActionPolicyEnum.allow, ); } final WKNavigationActionPolicy policy = await function( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, navigationAction.toNavigationAction(), ); return policy.toWKNavigationActionPolicyEnumData(); } @override void didFailNavigation( int identifier, int webViewIdentifier, NSErrorData error, ) { final void Function(WKWebView, NSError)? function = _getDelegate(identifier).didFailNavigation; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, error.toNSError(), ); } @override void didFailProvisionalNavigation( int identifier, int webViewIdentifier, NSErrorData error, ) { final void Function(WKWebView, NSError)? function = _getDelegate(identifier).didFailProvisionalNavigation; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, error.toNSError(), ); } @override void didStartProvisionalNavigation( int identifier, int webViewIdentifier, String? url, ) { final void Function(WKWebView, String?)? function = _getDelegate(identifier).didStartProvisionalNavigation; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, url, ); } @override void webViewWebContentProcessDidTerminate( int identifier, int webViewIdentifier, ) { final void Function(WKWebView)? function = _getDelegate(identifier).webViewWebContentProcessDidTerminate; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, ); } } /// Host api implementation for [WKWebView]. class WKWebViewHostApiImpl extends WKWebViewHostApi { /// Constructs a [WKWebViewHostApiImpl]. WKWebViewHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances( WKWebView instance, WKWebViewConfiguration configuration, ) { return create( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(configuration)!, ); } /// Calls [loadRequest] with the ids of the provided object instances. Future<void> loadRequestForInstances( WKWebView webView, NSUrlRequest request, ) { return loadRequest( instanceManager.getIdentifier(webView)!, request.toNSUrlRequestData(), ); } /// Calls [loadHtmlString] with the ids of the provided object instances. Future<void> loadHtmlStringForInstances( WKWebView instance, String string, String? baseUrl, ) { return loadHtmlString( instanceManager.getIdentifier(instance)!, string, baseUrl, ); } /// Calls [loadFileUrl] with the ids of the provided object instances. Future<void> loadFileUrlForInstances( WKWebView instance, String url, String readAccessUrl, ) { return loadFileUrl( instanceManager.getIdentifier(instance)!, url, readAccessUrl, ); } /// Calls [loadFlutterAsset] with the ids of the provided object instances. Future<void> loadFlutterAssetForInstances(WKWebView instance, String key) { return loadFlutterAsset( instanceManager.getIdentifier(instance)!, key, ); } /// Calls [canGoBack] with the ids of the provided object instances. Future<bool> canGoBackForInstances(WKWebView instance) { return canGoBack(instanceManager.getIdentifier(instance)!); } /// Calls [canGoForward] with the ids of the provided object instances. Future<bool> canGoForwardForInstances(WKWebView instance) { return canGoForward(instanceManager.getIdentifier(instance)!); } /// Calls [goBack] with the ids of the provided object instances. Future<void> goBackForInstances(WKWebView instance) { return goBack(instanceManager.getIdentifier(instance)!); } /// Calls [goForward] with the ids of the provided object instances. Future<void> goForwardForInstances(WKWebView instance) { return goForward(instanceManager.getIdentifier(instance)!); } /// Calls [reload] with the ids of the provided object instances. Future<void> reloadForInstances(WKWebView instance) { return reload(instanceManager.getIdentifier(instance)!); } /// Calls [getUrl] with the ids of the provided object instances. Future<String?> getUrlForInstances(WKWebView instance) { return getUrl(instanceManager.getIdentifier(instance)!); } /// Calls [getTitle] with the ids of the provided object instances. Future<String?> getTitleForInstances(WKWebView instance) { return getTitle(instanceManager.getIdentifier(instance)!); } /// Calls [getEstimatedProgress] with the ids of the provided object instances. Future<double> getEstimatedProgressForInstances(WKWebView instance) { return getEstimatedProgress(instanceManager.getIdentifier(instance)!); } /// Calls [setAllowsBackForwardNavigationGestures] with the ids of the provided object instances. Future<void> setAllowsBackForwardNavigationGesturesForInstances( WKWebView instance, bool allow, ) { return setAllowsBackForwardNavigationGestures( instanceManager.getIdentifier(instance)!, allow, ); } /// Calls [setCustomUserAgent] with the ids of the provided object instances. Future<void> setCustomUserAgentForInstances( WKWebView instance, String? userAgent, ) { return setCustomUserAgent( instanceManager.getIdentifier(instance)!, userAgent, ); } /// Calls [evaluateJavaScript] with the ids of the provided object instances. Future<Object?> evaluateJavaScriptForInstances( WKWebView instance, String javaScriptString, ) async { try { final Object? result = await evaluateJavaScript( instanceManager.getIdentifier(instance)!, javaScriptString, ); return result; } on PlatformException catch (exception) { if (exception.details is! NSErrorData) { rethrow; } throw PlatformException( code: exception.code, message: exception.message, stacktrace: exception.stacktrace, details: (exception.details as NSErrorData).toNSError(), ); } } /// Calls [setNavigationDelegate] with the ids of the provided object instances. Future<void> setNavigationDelegateForInstances( WKWebView instance, WKNavigationDelegate? delegate, ) { return setNavigationDelegate( instanceManager.getIdentifier(instance)!, delegate != null ? instanceManager.getIdentifier(delegate)! : null, ); } /// Calls [setUIDelegate] with the ids of the provided object instances. Future<void> setUIDelegateForInstances( WKWebView instance, WKUIDelegate? delegate, ) { return setUIDelegate( instanceManager.getIdentifier(instance)!, delegate != null ? instanceManager.getIdentifier(delegate)! : null, ); } }
plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/web_kit/web_kit_api_impls.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/web_kit/web_kit_api_impls.dart", "repo_id": "plugins", "token_count": 11485 }
1,306
// Mocks generated by Mockito 5.3.2 from annotations // in webview_flutter_wkwebview/test/src/foundation/foundation_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart' as _i3; import '../common/test_web_kit.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 [TestNSObjectHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestNSObjectHostApi extends _i1.Mock implements _i2.TestNSObjectHostApi { MockTestNSObjectHostApi() { _i1.throwOnMissingStub(this); } @override void dispose(int? identifier) => super.noSuchMethod( Invocation.method( #dispose, [identifier], ), returnValueForMissingStub: null, ); @override void addObserver( int? identifier, int? observerIdentifier, String? keyPath, List<_i3.NSKeyValueObservingOptionsEnumData?>? options, ) => super.noSuchMethod( Invocation.method( #addObserver, [ identifier, observerIdentifier, keyPath, options, ], ), returnValueForMissingStub: null, ); @override void removeObserver( int? identifier, int? observerIdentifier, String? keyPath, ) => super.noSuchMethod( Invocation.method( #removeObserver, [ identifier, observerIdentifier, keyPath, ], ), returnValueForMissingStub: null, ); }
plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/foundation/foundation_test.mocks.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/src/foundation/foundation_test.mocks.dart", "repo_id": "plugins", "token_count": 894 }
1,307
# No integration tests to run: - espresso
plugins/script/configs/exclude_integration_android.yaml/0
{ "file_path": "plugins/script/configs/exclude_integration_android.yaml", "repo_id": "plugins", "token_count": 11 }
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 'dart:io' as io; import 'package:git/git.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:yaml/yaml.dart'; /// Finding diffs based on `baseGitDir` and `baseSha`. class GitVersionFinder { /// Constructor GitVersionFinder(this.baseGitDir, String? baseSha) : _baseSha = baseSha; /// The top level directory of the git repo. /// /// That is where the .git/ folder exists. final GitDir baseGitDir; /// The base sha used to get diff. String? _baseSha; static bool _isPubspec(String file) { return file.trim().endsWith('pubspec.yaml'); } /// Get a list of all the pubspec.yaml file that is changed. Future<List<String>> getChangedPubSpecs() async { return (await getChangedFiles()).where(_isPubspec).toList(); } /// Get a list of all the changed files. Future<List<String>> getChangedFiles( {bool includeUncommitted = false}) async { final String baseSha = await getBaseSha(); final io.ProcessResult changedFilesCommand = await baseGitDir .runCommand(<String>[ 'diff', '--name-only', baseSha, if (!includeUncommitted) 'HEAD' ]); final String changedFilesStdout = changedFilesCommand.stdout.toString(); if (changedFilesStdout.isEmpty) { return <String>[]; } final List<String> changedFiles = changedFilesStdout.split('\n') ..removeWhere((String element) => element.isEmpty); return changedFiles.toList(); } /// Get a list of all the changed files. Future<List<String>> getDiffContents({ String? targetPath, bool includeUncommitted = false, }) async { final String baseSha = await getBaseSha(); final io.ProcessResult diffCommand = await baseGitDir.runCommand(<String>[ 'diff', baseSha, if (!includeUncommitted) 'HEAD', if (targetPath != null) ...<String>['--', targetPath], ]); final String diffStdout = diffCommand.stdout.toString(); if (diffStdout.isEmpty) { return <String>[]; } final List<String> changedFiles = diffStdout.split('\n') ..removeWhere((String element) => element.isEmpty); return changedFiles.toList(); } /// Get the package version specified in the pubspec file in `pubspecPath` and /// at the revision of `gitRef` (defaulting to the base if not provided). Future<Version?> getPackageVersion(String pubspecPath, {String? gitRef}) async { final String ref = gitRef ?? (await getBaseSha()); io.ProcessResult gitShow; try { gitShow = await baseGitDir.runCommand(<String>['show', '$ref:$pubspecPath']); } on io.ProcessException { return null; } final String fileContent = gitShow.stdout as String; if (fileContent.trim().isEmpty) { return null; } final YamlMap fileYaml = loadYaml(fileContent) as YamlMap; final String? versionString = fileYaml['version'] as String?; return versionString == null ? null : Version.parse(versionString); } /// Returns the base used to diff against. Future<String> getBaseSha() async { String? baseSha = _baseSha; if (baseSha != null && baseSha.isNotEmpty) { return baseSha; } io.ProcessResult baseShaFromMergeBase = await baseGitDir.runCommand( <String>['merge-base', '--fork-point', 'FETCH_HEAD', 'HEAD'], throwOnError: false); final String stdout = (baseShaFromMergeBase.stdout as String? ?? '').trim(); final String stderr = (baseShaFromMergeBase.stderr as String? ?? '').trim(); if (stderr.isNotEmpty || stdout.isEmpty) { baseShaFromMergeBase = await baseGitDir .runCommand(<String>['merge-base', 'FETCH_HEAD', 'HEAD']); } baseSha = (baseShaFromMergeBase.stdout as String).trim(); _baseSha = baseSha; return baseSha; } }
plugins/script/tool/lib/src/common/git_version_finder.dart/0
{ "file_path": "plugins/script/tool/lib/src/common/git_version_finder.dart", "repo_id": "plugins", "token_count": 1456 }
1,309
# Flutter samples [![Build Status](https://github.com/flutter/samples/workflows/Main%20Branch%20CI/badge.svg)](https://github.com/flutter/samples/actions?workflow=Main%20Branch%20CI) A collection of open source samples that illustrate best practices for [Flutter](https://flutter.dev). ## Visual samples index The easiest way to browse through the samples in this repo (as well as a few others!) is the [visual samples index](https://flutter.github.io/samples). ## Tip: minimize download size As this repository is quite big, you can use svn to download a single example. For example: ``` svn co https://github.com/flutter/samples/trunk/provider_shopper ``` You can also use a [partial clone](https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/) to skip blob objects that aren't currently checked out, while including the full commit history: ``` git clone --filter=blob:none https://github.com/flutter/samples.git ``` ## Interested in contributing? See the [contributor's guide](CONTRIBUTING.md)! ## Questions or issues? If you have a general question about one of these samples or how to adapt its techniques for one of your own apps, try one of these resources: * [The FlutterDev Discord](https://discord.gg/rflutterdev) * [StackOverflow](https://stackoverflow.com/questions/tagged/flutter) If you run into a bug in one of the samples, please file an issue in the [`flutter/samples` issue tracker](https://github.com/flutter/samples/issues).
samples/README.md/0
{ "file_path": "samples/README.md", "repo_id": "samples", "token_count": 461 }
1,310
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="#FF000000" android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" /> </vector>
samples/add_to_app/android_view/android_view/app/src/main/res/drawable/ic_notifications_black_24dp.xml/0
{ "file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/drawable/ic_notifications_black_24dp.xml", "repo_id": "samples", "token_count": 266 }
1,311