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 'package:share_repository/share_repository.dart';
import 'package:test/test.dart';
void main() {
group('ShareRepository', () {
const appUrl = 'https://fakeurl.com/';
late ShareRepository shareRepository;
setUp(() {
shareRepository = ShareRepository(appUrl: appUrl);
});
test('can be instantiated', () {
expect(ShareRepository(appUrl: appUrl), isNotNull);
});
group('shareText', () {
const value = 'hello world!';
test('returns the correct share url for twitter', () async {
const shareTextUrl =
'https://twitter.com/intent/tweet?url=https%3A%2F%2Ffakeurl.com%2F&text=hello%20world!';
final shareTextResult = shareRepository.shareText(
value: value,
platform: SharePlatform.twitter,
);
expect(shareTextResult, equals(shareTextUrl));
});
test('returns the correct share url for facebook', () async {
const shareTextUrl =
'https://www.facebook.com/sharer.php?u=https%3A%2F%2Ffakeurl.com%2F"e=hello%20world!';
final shareTextResult = shareRepository.shareText(
value: value,
platform: SharePlatform.facebook,
);
expect(shareTextResult, equals(shareTextUrl));
});
});
});
}
| pinball/packages/share_repository/test/src/share_repository_test.dart/0 | {
"file_path": "pinball/packages/share_repository/test/src/share_repository_test.dart",
"repo_id": "pinball",
"token_count": 546
} | 1,125 |
// ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
Future<void> pump(
_TestBodyComponent child, {
required PinballAudioPlayer audioPlayer,
}) {
return ensureAdd(
FlameProvider<PinballAudioPlayer>.value(
audioPlayer,
children: [child],
),
);
}
}
class _TestBodyComponent extends BodyComponent {
@override
Body createBody() => world.createBody(BodyDef());
}
class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('RolloverNoiseBehavior', () {
late PinballAudioPlayer audioPlayer;
final flameTester = FlameTester(_TestGame.new);
setUp(() {
audioPlayer = _MockPinballAudioPlayer();
});
flameTester.testGameWidget(
'plays rollover sound on contact',
setUp: (game, _) async {
final behavior = RolloverNoiseBehavior();
final parent = _TestBodyComponent();
await game.pump(parent, audioPlayer: audioPlayer);
await parent.ensureAdd(behavior);
behavior.beginContact(Object(), _MockContact());
},
verify: (_, __) async {
verify(() => audioPlayer.play(PinballAudio.rollover)).called(1);
},
);
});
}
| pinball/test/game/behaviors/rollover_noise_behavior_test.dart/0 | {
"file_path": "pinball/test/game/behaviors/rollover_noise_behavior_test.dart",
"repo_id": "pinball",
"token_count": 608
} | 1,126 |
// ignore_for_file: cascade_invocations
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/bloc/game_bloc.dart';
import 'package:pinball/game/components/backbox/displays/game_over_info_display.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_ui/pinball_ui.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:share_repository/share_repository.dart';
class _TestGame extends Forge2DGame with HasTappables {
@override
Future<void> onLoad() async {
await super.onLoad();
images.prefix = '';
await images.loadAll(
[
Assets.images.backbox.displayTitleDecoration.keyName,
],
);
}
Future<void> pump(GameOverInfoDisplay component) {
return ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: GameBloc(),
children: [
FlameProvider.value(
_MockAppLocalizations(),
children: [component],
),
],
),
);
}
}
class _MockAppLocalizations extends Mock implements AppLocalizations {
@override
String get shareYourScore => '';
@override
String get andChallengeYourFriends => '';
@override
String get share => '';
@override
String get gotoIO => '';
@override
String get learnMore => '';
@override
String get firebaseOr => '';
@override
String get openSourceCode => '';
}
class _MockTapDownInfo extends Mock implements TapDownInfo {}
class _MockTapUpInfo extends Mock implements TapUpInfo {}
class _MockUrlLauncher extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
late UrlLauncherPlatform urlLauncher;
setUp(() async {
urlLauncher = _MockUrlLauncher();
UrlLauncherPlatform.instance = urlLauncher;
});
group('InfoDisplay', () {
flameTester.test(
'loads correctly',
(game) async {
final component = GameOverInfoDisplay();
await game.pump(component);
expect(game.descendants(), contains(component));
},
);
flameTester.test(
'calls onShare when Share link is tapped',
(game) async {
var tapped = false;
final tapDownInfo = _MockTapDownInfo();
final component = GameOverInfoDisplay(
onShare: () => tapped = true,
);
await game.pump(component);
final shareLink =
component.descendants().whereType<ShareLinkComponent>().first;
shareLink.onTapDown(tapDownInfo);
expect(tapped, isTrue);
},
);
flameTester.test(
'open Google IO Event url when navigating',
(game) async {
when(() => urlLauncher.canLaunch(any())).thenAnswer((_) async => true);
when(
() => urlLauncher.launch(
any(),
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
).thenAnswer((_) async => true);
final component = GameOverInfoDisplay();
await game.pump(component);
final googleLink =
component.descendants().whereType<GoogleIOLinkComponent>().first;
googleLink.onTapUp(_MockTapUpInfo());
await game.ready();
verify(
() => urlLauncher.launch(
ShareRepository.googleIOEvent,
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
);
},
);
flameTester.test(
'open OpenSource url when navigating',
(game) async {
when(() => urlLauncher.canLaunch(any())).thenAnswer((_) async => true);
when(
() => urlLauncher.launch(
any(),
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
).thenAnswer((_) async => true);
final component = GameOverInfoDisplay();
await game.pump(component);
final openSourceLink =
component.descendants().whereType<OpenSourceTextComponent>().first;
openSourceLink.onTapUp(_MockTapUpInfo());
await game.ready();
verify(
() => urlLauncher.launch(
ShareRepository.openSourceCode,
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
);
},
);
});
}
| pinball/test/game/components/backbox/displays/game_over_info_display_test.dart/0 | {
"file_path": "pinball/test/game/components/backbox/displays/game_over_info_display_test.dart",
"repo_id": "pinball",
"token_count": 2406
} | 1,127 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/start_game/bloc/start_game_bloc.dart';
import '../../../helpers/helpers.dart';
class _MockStartGameBloc extends Mock implements StartGameBloc {}
void main() {
group('PlayButtonOverlay', () {
late StartGameBloc startGameBloc;
setUp(() async {
await mockFlameImages();
startGameBloc = _MockStartGameBloc();
whenListen(
startGameBloc,
Stream.value(const StartGameState.initial()),
initialState: const StartGameState.initial(),
);
});
testWidgets('renders correctly', (tester) async {
await tester.pumpApp(const PlayButtonOverlay());
expect(find.text('Play'), findsOneWidget);
});
testWidgets('adds PlayTapped event to StartGameBloc when tapped',
(tester) async {
await tester.pumpApp(
const PlayButtonOverlay(),
startGameBloc: startGameBloc,
);
await tester.tap(find.text('Play'));
await tester.pump();
verify(() => startGameBloc.add(const PlayTapped())).called(1);
});
});
}
| pinball/test/game/view/widgets/play_button_overlay_test.dart/0 | {
"file_path": "pinball/test/game/view/widgets/play_button_overlay_test.dart",
"repo_id": "pinball",
"token_count": 491
} | 1,128 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/how_to_play/how_to_play.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 '../../helpers/helpers.dart';
class _MockStartGameBloc extends Mock implements StartGameBloc {}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockCharacterThemeCubit extends Mock implements CharacterThemeCubit {}
class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {}
class _MockPlatformHelper extends Mock implements PlatformHelper {
@override
bool get isMobile => false;
}
void main() {
late StartGameBloc startGameBloc;
late PinballAudioPlayer pinballAudioPlayer;
late CharacterThemeCubit characterThemeCubit;
late PlatformHelper platformHelper;
group('StartGameListener', () {
setUp(() async {
await mockFlameImages();
startGameBloc = _MockStartGameBloc();
pinballAudioPlayer = _MockPinballAudioPlayer();
characterThemeCubit = _MockCharacterThemeCubit();
platformHelper = _MockPlatformHelper();
});
group('on selectCharacter status', () {
late GameBloc gameBloc;
setUp(() {
gameBloc = _MockGameBloc();
whenListen(
gameBloc,
const Stream<GameState>.empty(),
initialState: const GameState.initial(),
);
});
testWidgets(
'calls GameStarted event',
(tester) async {
whenListen(
startGameBloc,
Stream.value(
const StartGameState(
status: StartGameStatus.selectCharacter,
),
),
initialState: const StartGameState.initial(),
);
await tester.pumpApp(
const StartGameListener(
child: SizedBox.shrink(),
),
gameBloc: gameBloc,
startGameBloc: startGameBloc,
);
verify(() => gameBloc.add(const GameStarted())).called(1);
},
);
testWidgets(
'shows SelectCharacter dialog',
(tester) async {
whenListen(
startGameBloc,
Stream.value(
const StartGameState(status: StartGameStatus.selectCharacter),
),
initialState: const StartGameState.initial(),
);
whenListen(
characterThemeCubit,
Stream.value(const CharacterThemeState.initial()),
initialState: const CharacterThemeState.initial(),
);
await tester.pumpApp(
const StartGameListener(
child: SizedBox.shrink(),
),
gameBloc: gameBloc,
startGameBloc: startGameBloc,
characterThemeCubit: characterThemeCubit,
);
await tester.pump(kThemeAnimationDuration);
expect(
find.byType(CharacterSelectionDialog),
findsOneWidget,
);
},
);
});
testWidgets(
'on howToPlay status shows HowToPlay dialog',
(tester) async {
whenListen(
startGameBloc,
Stream.value(
const StartGameState(status: StartGameStatus.howToPlay),
),
initialState: const StartGameState.initial(),
);
await tester.pumpApp(
const StartGameListener(
child: SizedBox.shrink(),
),
startGameBloc: startGameBloc,
platformHelper: platformHelper,
);
await tester.pumpAndSettle();
expect(
find.byType(HowToPlayDialog),
findsOneWidget,
);
},
);
testWidgets(
'do nothing on play status',
(tester) async {
whenListen(
startGameBloc,
Stream.value(
const StartGameState(status: StartGameStatus.play),
),
initialState: const StartGameState.initial(),
);
await tester.pumpApp(
const StartGameListener(
child: SizedBox.shrink(),
),
startGameBloc: startGameBloc,
);
await tester.pumpAndSettle();
expect(
find.byType(HowToPlayDialog),
findsNothing,
);
expect(
find.byType(CharacterSelectionDialog),
findsNothing,
);
},
);
testWidgets(
'do nothing on initial status',
(tester) async {
whenListen(
startGameBloc,
Stream.value(
const StartGameState(status: StartGameStatus.initial),
),
initialState: const StartGameState.initial(),
);
await tester.pumpApp(
const StartGameListener(
child: SizedBox.shrink(),
),
startGameBloc: startGameBloc,
);
await tester.pumpAndSettle();
expect(
find.byType(HowToPlayDialog),
findsNothing,
);
expect(
find.byType(CharacterSelectionDialog),
findsNothing,
);
},
);
group('on dismiss HowToPlayDialog', () {
setUp(() {
whenListen(
startGameBloc,
Stream.value(
const StartGameState(status: StartGameStatus.howToPlay),
),
initialState: const StartGameState.initial(),
);
});
testWidgets(
'adds HowToPlayFinished event',
(tester) async {
await tester.pumpApp(
const StartGameListener(
child: SizedBox.shrink(),
),
startGameBloc: startGameBloc,
platformHelper: platformHelper,
);
await tester.pumpAndSettle();
expect(
find.byType(HowToPlayDialog),
findsOneWidget,
);
await tester.tapAt(const Offset(1, 1));
await tester.pumpAndSettle();
expect(
find.byType(HowToPlayDialog),
findsNothing,
);
await tester.pumpAndSettle();
verify(
() => startGameBloc.add(const HowToPlayFinished()),
).called(1);
},
);
testWidgets(
'plays the I/O Pinball voice over audio',
(tester) async {
await tester.pumpApp(
const StartGameListener(
child: SizedBox.shrink(),
),
startGameBloc: startGameBloc,
pinballAudioPlayer: pinballAudioPlayer,
platformHelper: platformHelper,
);
await tester.pumpAndSettle();
expect(
find.byType(HowToPlayDialog),
findsOneWidget,
);
await tester.tapAt(const Offset(1, 1));
await tester.pumpAndSettle();
expect(
find.byType(HowToPlayDialog),
findsNothing,
);
await tester.pumpAndSettle();
verify(() => pinballAudioPlayer.play(PinballAudio.ioPinballVoiceOver))
.called(1);
},
);
});
});
}
| pinball/test/start_game/widgets/start_game_listener_test.dart/0 | {
"file_path": "pinball/test/start_game/widgets/start_game_listener_test.dart",
"repo_id": "pinball",
"token_count": 3562
} | 1,129 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.OutputConfiguration;
import android.hardware.camera2.params.SessionConfiguration;
import android.media.CamcorderProfile;
import android.media.EncoderProfiles;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import android.util.Size;
import android.view.Display;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.camera.features.CameraFeature;
import io.flutter.plugins.camera.features.CameraFeatureFactory;
import io.flutter.plugins.camera.features.CameraFeatures;
import io.flutter.plugins.camera.features.Point;
import io.flutter.plugins.camera.features.autofocus.AutoFocusFeature;
import io.flutter.plugins.camera.features.autofocus.FocusMode;
import io.flutter.plugins.camera.features.exposurelock.ExposureLockFeature;
import io.flutter.plugins.camera.features.exposurelock.ExposureMode;
import io.flutter.plugins.camera.features.exposureoffset.ExposureOffsetFeature;
import io.flutter.plugins.camera.features.exposurepoint.ExposurePointFeature;
import io.flutter.plugins.camera.features.flash.FlashFeature;
import io.flutter.plugins.camera.features.flash.FlashMode;
import io.flutter.plugins.camera.features.focuspoint.FocusPointFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionPreset;
import io.flutter.plugins.camera.features.sensororientation.DeviceOrientationManager;
import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature;
import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature;
import io.flutter.plugins.camera.media.MediaRecorderBuilder;
import io.flutter.plugins.camera.types.CameraCaptureProperties;
import io.flutter.plugins.camera.types.CaptureTimeoutsWrapper;
import io.flutter.view.TextureRegistry.SurfaceTextureEntry;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executors;
@FunctionalInterface
interface ErrorCallback {
void onError(String errorCode, String errorMessage);
}
/** A mockable wrapper for CameraDevice calls. */
interface CameraDeviceWrapper {
@NonNull
CaptureRequest.Builder createCaptureRequest(int templateType) throws CameraAccessException;
@TargetApi(VERSION_CODES.P)
void createCaptureSession(SessionConfiguration config) throws CameraAccessException;
@TargetApi(VERSION_CODES.LOLLIPOP)
void createCaptureSession(
@NonNull List<Surface> outputs,
@NonNull CameraCaptureSession.StateCallback callback,
@Nullable Handler handler)
throws CameraAccessException;
void close();
}
class Camera
implements CameraCaptureCallback.CameraCaptureStateListener,
ImageReader.OnImageAvailableListener {
private static final String TAG = "Camera";
private static final HashMap<String, Integer> supportedImageFormats;
// Current supported outputs.
static {
supportedImageFormats = new HashMap<>();
supportedImageFormats.put("yuv420", ImageFormat.YUV_420_888);
supportedImageFormats.put("jpeg", ImageFormat.JPEG);
}
/**
* Holds all of the camera features/settings and will be used to update the request builder when
* one changes.
*/
private final CameraFeatures cameraFeatures;
private final SurfaceTextureEntry flutterTexture;
private final boolean enableAudio;
private final Context applicationContext;
private final DartMessenger dartMessenger;
private final CameraProperties cameraProperties;
private final CameraFeatureFactory cameraFeatureFactory;
private final Activity activity;
/** A {@link CameraCaptureSession.CaptureCallback} that handles events related to JPEG capture. */
private final CameraCaptureCallback cameraCaptureCallback;
/** A {@link Handler} for running tasks in the background. */
private Handler backgroundHandler;
/** An additional thread for running tasks that shouldn't block the UI. */
private HandlerThread backgroundHandlerThread;
private CameraDeviceWrapper cameraDevice;
private CameraCaptureSession captureSession;
private ImageReader pictureImageReader;
private ImageReader imageStreamReader;
/** {@link CaptureRequest.Builder} for the camera preview */
private CaptureRequest.Builder previewRequestBuilder;
private MediaRecorder mediaRecorder;
/** True when recording video. */
private boolean recordingVideo;
/** True when the preview is paused. */
private boolean pausedPreview;
private File captureFile;
/** Holds the current capture timeouts */
private CaptureTimeoutsWrapper captureTimeouts;
/** Holds the last known capture properties */
private CameraCaptureProperties captureProps;
private MethodChannel.Result flutterResult;
/** A CameraDeviceWrapper implementation that forwards calls to a CameraDevice. */
private class DefaultCameraDeviceWrapper implements CameraDeviceWrapper {
private final CameraDevice cameraDevice;
private DefaultCameraDeviceWrapper(CameraDevice cameraDevice) {
this.cameraDevice = cameraDevice;
}
@NonNull
@Override
public CaptureRequest.Builder createCaptureRequest(int templateType)
throws CameraAccessException {
return cameraDevice.createCaptureRequest(templateType);
}
@TargetApi(VERSION_CODES.P)
@Override
public void createCaptureSession(SessionConfiguration config) throws CameraAccessException {
cameraDevice.createCaptureSession(config);
}
@TargetApi(VERSION_CODES.LOLLIPOP)
@SuppressWarnings("deprecation")
@Override
public void createCaptureSession(
@NonNull List<Surface> outputs,
@NonNull CameraCaptureSession.StateCallback callback,
@Nullable Handler handler)
throws CameraAccessException {
cameraDevice.createCaptureSession(outputs, callback, backgroundHandler);
}
@Override
public void close() {
cameraDevice.close();
}
}
public Camera(
final Activity activity,
final SurfaceTextureEntry flutterTexture,
final CameraFeatureFactory cameraFeatureFactory,
final DartMessenger dartMessenger,
final CameraProperties cameraProperties,
final ResolutionPreset resolutionPreset,
final boolean enableAudio) {
if (activity == null) {
throw new IllegalStateException("No activity available!");
}
this.activity = activity;
this.enableAudio = enableAudio;
this.flutterTexture = flutterTexture;
this.dartMessenger = dartMessenger;
this.applicationContext = activity.getApplicationContext();
this.cameraProperties = cameraProperties;
this.cameraFeatureFactory = cameraFeatureFactory;
this.cameraFeatures =
CameraFeatures.init(
cameraFeatureFactory, cameraProperties, activity, dartMessenger, resolutionPreset);
// Create capture callback.
captureTimeouts = new CaptureTimeoutsWrapper(3000, 3000);
captureProps = new CameraCaptureProperties();
cameraCaptureCallback = CameraCaptureCallback.create(this, captureTimeouts, captureProps);
startBackgroundThread();
}
@Override
public void onConverged() {
takePictureAfterPrecapture();
}
@Override
public void onPrecapture() {
runPrecaptureSequence();
}
/**
* Updates the builder settings with all of the available features.
*
* @param requestBuilder request builder to update.
*/
private void updateBuilderSettings(CaptureRequest.Builder requestBuilder) {
for (CameraFeature feature : cameraFeatures.getAllFeatures()) {
Log.d(TAG, "Updating builder with feature: " + feature.getDebugName());
feature.updateBuilder(requestBuilder);
}
}
private void prepareMediaRecorder(String outputFilePath) throws IOException {
Log.i(TAG, "prepareMediaRecorder");
if (mediaRecorder != null) {
mediaRecorder.release();
}
final PlatformChannel.DeviceOrientation lockedOrientation =
((SensorOrientationFeature) cameraFeatures.getSensorOrientation())
.getLockedCaptureOrientation();
MediaRecorderBuilder mediaRecorderBuilder;
// TODO(camsim99): Revert changes that allow legacy code to be used when recordingProfile is null
// once this has largely been fixed on the Android side. https://github.com/flutter/flutter/issues/119668
EncoderProfiles recordingProfile = getRecordingProfile();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && recordingProfile != null) {
mediaRecorderBuilder = new MediaRecorderBuilder(recordingProfile, outputFilePath);
} else {
mediaRecorderBuilder = new MediaRecorderBuilder(getRecordingProfileLegacy(), outputFilePath);
}
mediaRecorder =
mediaRecorderBuilder
.setEnableAudio(enableAudio)
.setMediaOrientation(
lockedOrientation == null
? getDeviceOrientationManager().getVideoOrientation()
: getDeviceOrientationManager().getVideoOrientation(lockedOrientation))
.build();
}
@SuppressLint("MissingPermission")
public void open(String imageFormatGroup) throws CameraAccessException {
final ResolutionFeature resolutionFeature = cameraFeatures.getResolution();
if (!resolutionFeature.checkIsSupported()) {
// Tell the user that the camera they are trying to open is not supported,
// as its {@link android.media.CamcorderProfile} cannot be fetched due to the name
// not being a valid parsable integer.
dartMessenger.sendCameraErrorEvent(
"Camera with name \""
+ cameraProperties.getCameraName()
+ "\" is not supported by this plugin.");
return;
}
// Always capture using JPEG format.
pictureImageReader =
ImageReader.newInstance(
resolutionFeature.getCaptureSize().getWidth(),
resolutionFeature.getCaptureSize().getHeight(),
ImageFormat.JPEG,
1);
// For image streaming, use the provided image format or fall back to YUV420.
Integer imageFormat = supportedImageFormats.get(imageFormatGroup);
if (imageFormat == null) {
Log.w(TAG, "The selected imageFormatGroup is not supported by Android. Defaulting to yuv420");
imageFormat = ImageFormat.YUV_420_888;
}
imageStreamReader =
ImageReader.newInstance(
resolutionFeature.getPreviewSize().getWidth(),
resolutionFeature.getPreviewSize().getHeight(),
imageFormat,
1);
// Open the camera.
CameraManager cameraManager = CameraUtils.getCameraManager(activity);
cameraManager.openCamera(
cameraProperties.getCameraName(),
new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice device) {
cameraDevice = new DefaultCameraDeviceWrapper(device);
try {
startPreview();
dartMessenger.sendCameraInitializedEvent(
resolutionFeature.getPreviewSize().getWidth(),
resolutionFeature.getPreviewSize().getHeight(),
cameraFeatures.getExposureLock().getValue(),
cameraFeatures.getAutoFocus().getValue(),
cameraFeatures.getExposurePoint().checkIsSupported(),
cameraFeatures.getFocusPoint().checkIsSupported());
} catch (CameraAccessException e) {
dartMessenger.sendCameraErrorEvent(e.getMessage());
close();
}
}
@Override
public void onClosed(@NonNull CameraDevice camera) {
Log.i(TAG, "open | onClosed");
// Prevents calls to methods that would otherwise result in IllegalStateException exceptions.
cameraDevice = null;
closeCaptureSession();
dartMessenger.sendCameraClosingEvent();
}
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
Log.i(TAG, "open | onDisconnected");
close();
dartMessenger.sendCameraErrorEvent("The camera was disconnected.");
}
@Override
public void onError(@NonNull CameraDevice cameraDevice, int errorCode) {
Log.i(TAG, "open | onError");
close();
String errorDescription;
switch (errorCode) {
case ERROR_CAMERA_IN_USE:
errorDescription = "The camera device is in use already.";
break;
case ERROR_MAX_CAMERAS_IN_USE:
errorDescription = "Max cameras in use";
break;
case ERROR_CAMERA_DISABLED:
errorDescription = "The camera device could not be opened due to a device policy.";
break;
case ERROR_CAMERA_DEVICE:
errorDescription = "The camera device has encountered a fatal error";
break;
case ERROR_CAMERA_SERVICE:
errorDescription = "The camera service has encountered a fatal error.";
break;
default:
errorDescription = "Unknown camera error";
}
dartMessenger.sendCameraErrorEvent(errorDescription);
}
},
backgroundHandler);
}
@VisibleForTesting
void createCaptureSession(int templateType, Surface... surfaces) throws CameraAccessException {
createCaptureSession(templateType, null, surfaces);
}
private void createCaptureSession(
int templateType, Runnable onSuccessCallback, Surface... surfaces)
throws CameraAccessException {
// Close any existing capture session.
captureSession = null;
// Create a new capture builder.
previewRequestBuilder = cameraDevice.createCaptureRequest(templateType);
// Build Flutter surface to render to.
ResolutionFeature resolutionFeature = cameraFeatures.getResolution();
SurfaceTexture surfaceTexture = flutterTexture.surfaceTexture();
surfaceTexture.setDefaultBufferSize(
resolutionFeature.getPreviewSize().getWidth(),
resolutionFeature.getPreviewSize().getHeight());
Surface flutterSurface = new Surface(surfaceTexture);
previewRequestBuilder.addTarget(flutterSurface);
List<Surface> remainingSurfaces = Arrays.asList(surfaces);
if (templateType != CameraDevice.TEMPLATE_PREVIEW) {
// If it is not preview mode, add all surfaces as targets.
for (Surface surface : remainingSurfaces) {
previewRequestBuilder.addTarget(surface);
}
}
// Update camera regions.
Size cameraBoundaries =
CameraRegionUtils.getCameraBoundaries(cameraProperties, previewRequestBuilder);
cameraFeatures.getExposurePoint().setCameraBoundaries(cameraBoundaries);
cameraFeatures.getFocusPoint().setCameraBoundaries(cameraBoundaries);
// Prepare the callback.
CameraCaptureSession.StateCallback callback =
new CameraCaptureSession.StateCallback() {
boolean captureSessionClosed = false;
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
Log.i(TAG, "CameraCaptureSession onConfigured");
// Camera was already closed.
if (cameraDevice == null || captureSessionClosed) {
dartMessenger.sendCameraErrorEvent("The camera was closed during configuration.");
return;
}
captureSession = session;
Log.i(TAG, "Updating builder settings");
updateBuilderSettings(previewRequestBuilder);
refreshPreviewCaptureSession(
onSuccessCallback, (code, message) -> dartMessenger.sendCameraErrorEvent(message));
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Log.i(TAG, "CameraCaptureSession onConfigureFailed");
dartMessenger.sendCameraErrorEvent("Failed to configure camera session.");
}
@Override
public void onClosed(@NonNull CameraCaptureSession session) {
Log.i(TAG, "CameraCaptureSession onClosed");
captureSessionClosed = true;
}
};
// Start the session.
if (VERSION.SDK_INT >= VERSION_CODES.P) {
// Collect all surfaces to render to.
List<OutputConfiguration> configs = new ArrayList<>();
configs.add(new OutputConfiguration(flutterSurface));
for (Surface surface : remainingSurfaces) {
configs.add(new OutputConfiguration(surface));
}
createCaptureSessionWithSessionConfig(configs, callback);
} else {
// Collect all surfaces to render to.
List<Surface> surfaceList = new ArrayList<>();
surfaceList.add(flutterSurface);
surfaceList.addAll(remainingSurfaces);
createCaptureSession(surfaceList, callback);
}
}
@TargetApi(VERSION_CODES.P)
private void createCaptureSessionWithSessionConfig(
List<OutputConfiguration> outputConfigs, CameraCaptureSession.StateCallback callback)
throws CameraAccessException {
cameraDevice.createCaptureSession(
new SessionConfiguration(
SessionConfiguration.SESSION_REGULAR,
outputConfigs,
Executors.newSingleThreadExecutor(),
callback));
}
@TargetApi(VERSION_CODES.LOLLIPOP)
@SuppressWarnings("deprecation")
private void createCaptureSession(
List<Surface> surfaces, CameraCaptureSession.StateCallback callback)
throws CameraAccessException {
cameraDevice.createCaptureSession(surfaces, callback, backgroundHandler);
}
// Send a repeating request to refresh capture session.
private void refreshPreviewCaptureSession(
@Nullable Runnable onSuccessCallback, @NonNull ErrorCallback onErrorCallback) {
Log.i(TAG, "refreshPreviewCaptureSession");
if (captureSession == null) {
Log.i(
TAG,
"refreshPreviewCaptureSession: captureSession not yet initialized, "
+ "skipping preview capture session refresh.");
return;
}
try {
if (!pausedPreview) {
captureSession.setRepeatingRequest(
previewRequestBuilder.build(), cameraCaptureCallback, backgroundHandler);
}
if (onSuccessCallback != null) {
onSuccessCallback.run();
}
} catch (IllegalStateException e) {
onErrorCallback.onError("cameraAccess", "Camera is closed: " + e.getMessage());
} catch (CameraAccessException e) {
onErrorCallback.onError("cameraAccess", e.getMessage());
}
}
private void startCapture(boolean record, boolean stream) throws CameraAccessException {
List<Surface> surfaces = new ArrayList<>();
Runnable successCallback = null;
if (record) {
surfaces.add(mediaRecorder.getSurface());
successCallback = () -> mediaRecorder.start();
}
if (stream) {
surfaces.add(imageStreamReader.getSurface());
}
createCaptureSession(
CameraDevice.TEMPLATE_RECORD, successCallback, surfaces.toArray(new Surface[0]));
}
public void takePicture(@NonNull final Result result) {
// Only take one picture at a time.
if (cameraCaptureCallback.getCameraState() != CameraState.STATE_PREVIEW) {
result.error("captureAlreadyActive", "Picture is currently already being captured", null);
return;
}
flutterResult = result;
// Create temporary file.
final File outputDir = applicationContext.getCacheDir();
try {
captureFile = File.createTempFile("CAP", ".jpg", outputDir);
captureTimeouts.reset();
} catch (IOException | SecurityException e) {
dartMessenger.error(flutterResult, "cannotCreateFile", e.getMessage(), null);
return;
}
// Listen for picture being taken.
pictureImageReader.setOnImageAvailableListener(this, backgroundHandler);
final AutoFocusFeature autoFocusFeature = cameraFeatures.getAutoFocus();
final boolean isAutoFocusSupported = autoFocusFeature.checkIsSupported();
if (isAutoFocusSupported && autoFocusFeature.getValue() == FocusMode.auto) {
runPictureAutoFocus();
} else {
runPrecaptureSequence();
}
}
/**
* Run the precapture sequence for capturing a still image. This method should be called when a
* response is received in {@link #cameraCaptureCallback} from lockFocus().
*/
private void runPrecaptureSequence() {
Log.i(TAG, "runPrecaptureSequence");
try {
// First set precapture state to idle or else it can hang in STATE_WAITING_PRECAPTURE_START.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_IDLE);
captureSession.capture(
previewRequestBuilder.build(), cameraCaptureCallback, backgroundHandler);
// Repeating request to refresh preview session.
refreshPreviewCaptureSession(
null,
(code, message) -> dartMessenger.error(flutterResult, "cameraAccess", message, null));
// Start precapture.
cameraCaptureCallback.setCameraState(CameraState.STATE_WAITING_PRECAPTURE_START);
previewRequestBuilder.set(
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
// Trigger one capture to start AE sequence.
captureSession.capture(
previewRequestBuilder.build(), cameraCaptureCallback, backgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Capture a still picture. This method should be called when a response is received {@link
* #cameraCaptureCallback} from both lockFocus().
*/
private void takePictureAfterPrecapture() {
Log.i(TAG, "captureStillPicture");
cameraCaptureCallback.setCameraState(CameraState.STATE_CAPTURING);
if (cameraDevice == null) {
return;
}
// This is the CaptureRequest.Builder that is used to take a picture.
CaptureRequest.Builder stillBuilder;
try {
stillBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
} catch (CameraAccessException e) {
dartMessenger.error(flutterResult, "cameraAccess", e.getMessage(), null);
return;
}
stillBuilder.addTarget(pictureImageReader.getSurface());
// Zoom.
stillBuilder.set(
CaptureRequest.SCALER_CROP_REGION,
previewRequestBuilder.get(CaptureRequest.SCALER_CROP_REGION));
// Have all features update the builder.
updateBuilderSettings(stillBuilder);
// Orientation.
final PlatformChannel.DeviceOrientation lockedOrientation =
((SensorOrientationFeature) cameraFeatures.getSensorOrientation())
.getLockedCaptureOrientation();
stillBuilder.set(
CaptureRequest.JPEG_ORIENTATION,
lockedOrientation == null
? getDeviceOrientationManager().getPhotoOrientation()
: getDeviceOrientationManager().getPhotoOrientation(lockedOrientation));
CameraCaptureSession.CaptureCallback captureCallback =
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(
@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull TotalCaptureResult result) {
unlockAutoFocus();
}
};
try {
captureSession.stopRepeating();
Log.i(TAG, "sending capture request");
captureSession.capture(stillBuilder.build(), captureCallback, backgroundHandler);
} catch (CameraAccessException e) {
dartMessenger.error(flutterResult, "cameraAccess", e.getMessage(), null);
}
}
@SuppressWarnings("deprecation")
private Display getDefaultDisplay() {
return activity.getWindowManager().getDefaultDisplay();
}
/** Starts a background thread and its {@link Handler}. */
public void startBackgroundThread() {
if (backgroundHandlerThread != null) {
return;
}
backgroundHandlerThread = HandlerThreadFactory.create("CameraBackground");
try {
backgroundHandlerThread.start();
} catch (IllegalThreadStateException e) {
// Ignore exception in case the thread has already started.
}
backgroundHandler = HandlerFactory.create(backgroundHandlerThread.getLooper());
}
/** Stops the background thread and its {@link Handler}. */
public void stopBackgroundThread() {
if (backgroundHandlerThread != null) {
backgroundHandlerThread.quitSafely();
}
backgroundHandlerThread = null;
backgroundHandler = null;
}
/** Start capturing a picture, doing autofocus first. */
private void runPictureAutoFocus() {
Log.i(TAG, "runPictureAutoFocus");
cameraCaptureCallback.setCameraState(CameraState.STATE_WAITING_FOCUS);
lockAutoFocus();
}
private void lockAutoFocus() {
Log.i(TAG, "lockAutoFocus");
if (captureSession == null) {
Log.i(TAG, "[unlockAutoFocus] captureSession null, returning");
return;
}
// Trigger AF to start.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);
try {
captureSession.capture(previewRequestBuilder.build(), null, backgroundHandler);
} catch (CameraAccessException e) {
dartMessenger.sendCameraErrorEvent(e.getMessage());
}
}
/** Cancel and reset auto focus state and refresh the preview session. */
private void unlockAutoFocus() {
Log.i(TAG, "unlockAutoFocus");
if (captureSession == null) {
Log.i(TAG, "[unlockAutoFocus] captureSession null, returning");
return;
}
try {
// Cancel existing AF state.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
captureSession.capture(previewRequestBuilder.build(), null, backgroundHandler);
// Set AF state to idle again.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_IDLE);
captureSession.capture(previewRequestBuilder.build(), null, backgroundHandler);
} catch (CameraAccessException e) {
dartMessenger.sendCameraErrorEvent(e.getMessage());
return;
}
refreshPreviewCaptureSession(
null,
(errorCode, errorMessage) ->
dartMessenger.error(flutterResult, errorCode, errorMessage, null));
}
public void startVideoRecording(
@NonNull Result result, @Nullable EventChannel imageStreamChannel) {
prepareRecording(result);
if (imageStreamChannel != null) {
setStreamHandler(imageStreamChannel);
}
recordingVideo = true;
try {
startCapture(true, imageStreamChannel != null);
result.success(null);
} catch (CameraAccessException e) {
recordingVideo = false;
captureFile = null;
result.error("videoRecordingFailed", e.getMessage(), null);
}
}
public void stopVideoRecording(@NonNull final Result result) {
if (!recordingVideo) {
result.success(null);
return;
}
// Re-create autofocus feature so it's using continuous capture focus mode now.
cameraFeatures.setAutoFocus(
cameraFeatureFactory.createAutoFocusFeature(cameraProperties, false));
recordingVideo = false;
try {
captureSession.abortCaptures();
mediaRecorder.stop();
} catch (CameraAccessException | IllegalStateException e) {
// Ignore exceptions and try to continue (changes are camera session already aborted capture).
}
mediaRecorder.reset();
try {
startPreview();
} catch (CameraAccessException | IllegalStateException e) {
result.error("videoRecordingFailed", e.getMessage(), null);
return;
}
result.success(captureFile.getAbsolutePath());
captureFile = null;
}
public void pauseVideoRecording(@NonNull final Result result) {
if (!recordingVideo) {
result.success(null);
return;
}
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mediaRecorder.pause();
} else {
result.error("videoRecordingFailed", "pauseVideoRecording requires Android API +24.", null);
return;
}
} catch (IllegalStateException e) {
result.error("videoRecordingFailed", e.getMessage(), null);
return;
}
result.success(null);
}
public void resumeVideoRecording(@NonNull final Result result) {
if (!recordingVideo) {
result.success(null);
return;
}
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mediaRecorder.resume();
} else {
result.error(
"videoRecordingFailed", "resumeVideoRecording requires Android API +24.", null);
return;
}
} catch (IllegalStateException e) {
result.error("videoRecordingFailed", e.getMessage(), null);
return;
}
result.success(null);
}
/**
* Method handler for setting new flash modes.
*
* @param result Flutter result.
* @param newMode new mode.
*/
public void setFlashMode(@NonNull final Result result, @NonNull FlashMode newMode) {
// Save the new flash mode setting.
final FlashFeature flashFeature = cameraFeatures.getFlash();
flashFeature.setValue(newMode);
flashFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) -> result.error("setFlashModeFailed", "Could not set flash mode.", null));
}
/**
* Method handler for setting new exposure modes.
*
* @param result Flutter result.
* @param newMode new mode.
*/
public void setExposureMode(@NonNull final Result result, @NonNull ExposureMode newMode) {
final ExposureLockFeature exposureLockFeature = cameraFeatures.getExposureLock();
exposureLockFeature.setValue(newMode);
exposureLockFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) ->
result.error("setExposureModeFailed", "Could not set exposure mode.", null));
}
/**
* Sets new exposure point from dart.
*
* @param result Flutter result.
* @param point The exposure point.
*/
public void setExposurePoint(@NonNull final Result result, @Nullable Point point) {
final ExposurePointFeature exposurePointFeature = cameraFeatures.getExposurePoint();
exposurePointFeature.setValue(point);
exposurePointFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) ->
result.error("setExposurePointFailed", "Could not set exposure point.", null));
}
/** Return the max exposure offset value supported by the camera to dart. */
public double getMaxExposureOffset() {
return cameraFeatures.getExposureOffset().getMaxExposureOffset();
}
/** Return the min exposure offset value supported by the camera to dart. */
public double getMinExposureOffset() {
return cameraFeatures.getExposureOffset().getMinExposureOffset();
}
/** Return the exposure offset step size to dart. */
public double getExposureOffsetStepSize() {
return cameraFeatures.getExposureOffset().getExposureOffsetStepSize();
}
/**
* Sets new focus mode from dart.
*
* @param result Flutter result.
* @param newMode New mode.
*/
public void setFocusMode(final Result result, @NonNull FocusMode newMode) {
final AutoFocusFeature autoFocusFeature = cameraFeatures.getAutoFocus();
autoFocusFeature.setValue(newMode);
autoFocusFeature.updateBuilder(previewRequestBuilder);
/*
* For focus mode an extra step of actually locking/unlocking the
* focus has to be done, in order to ensure it goes into the correct state.
*/
if (!pausedPreview) {
switch (newMode) {
case locked:
// Perform a single focus trigger.
if (captureSession == null) {
Log.i(TAG, "[unlockAutoFocus] captureSession null, returning");
return;
}
lockAutoFocus();
// Set AF state to idle again.
previewRequestBuilder.set(
CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_IDLE);
try {
captureSession.setRepeatingRequest(
previewRequestBuilder.build(), null, backgroundHandler);
} catch (CameraAccessException e) {
if (result != null) {
result.error(
"setFocusModeFailed", "Error setting focus mode: " + e.getMessage(), null);
}
return;
}
break;
case auto:
// Cancel current AF trigger and set AF to idle again.
unlockAutoFocus();
break;
}
}
if (result != null) {
result.success(null);
}
}
/**
* Sets new focus point from dart.
*
* @param result Flutter result.
* @param point the new coordinates.
*/
public void setFocusPoint(@NonNull final Result result, @Nullable Point point) {
final FocusPointFeature focusPointFeature = cameraFeatures.getFocusPoint();
focusPointFeature.setValue(point);
focusPointFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) -> result.error("setFocusPointFailed", "Could not set focus point.", null));
this.setFocusMode(null, cameraFeatures.getAutoFocus().getValue());
}
/**
* Sets a new exposure offset from dart. From dart the offset comes as a double, like +1.3 or
* -1.3.
*
* @param result flutter result.
* @param offset new value.
*/
public void setExposureOffset(@NonNull final Result result, double offset) {
final ExposureOffsetFeature exposureOffsetFeature = cameraFeatures.getExposureOffset();
exposureOffsetFeature.setValue(offset);
exposureOffsetFeature.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(exposureOffsetFeature.getValue()),
(code, message) ->
result.error("setExposureOffsetFailed", "Could not set exposure offset.", null));
}
public float getMaxZoomLevel() {
return cameraFeatures.getZoomLevel().getMaximumZoomLevel();
}
public float getMinZoomLevel() {
return cameraFeatures.getZoomLevel().getMinimumZoomLevel();
}
/** Shortcut to get current recording profile. Legacy method provides support for SDK < 31. */
CamcorderProfile getRecordingProfileLegacy() {
return cameraFeatures.getResolution().getRecordingProfileLegacy();
}
EncoderProfiles getRecordingProfile() {
return cameraFeatures.getResolution().getRecordingProfile();
}
/** Shortut to get deviceOrientationListener. */
DeviceOrientationManager getDeviceOrientationManager() {
return cameraFeatures.getSensorOrientation().getDeviceOrientationManager();
}
/**
* Sets zoom level from dart.
*
* @param result Flutter result.
* @param zoom new value.
*/
public void setZoomLevel(@NonNull final Result result, float zoom) throws CameraAccessException {
final ZoomLevelFeature zoomLevel = cameraFeatures.getZoomLevel();
float maxZoom = zoomLevel.getMaximumZoomLevel();
float minZoom = zoomLevel.getMinimumZoomLevel();
if (zoom > maxZoom || zoom < minZoom) {
String errorMessage =
String.format(
Locale.ENGLISH,
"Zoom level out of bounds (zoom level should be between %f and %f).",
minZoom,
maxZoom);
result.error("ZOOM_ERROR", errorMessage, null);
return;
}
zoomLevel.setValue(zoom);
zoomLevel.updateBuilder(previewRequestBuilder);
refreshPreviewCaptureSession(
() -> result.success(null),
(code, message) -> result.error("setZoomLevelFailed", "Could not set zoom level.", null));
}
/**
* Lock capture orientation from dart.
*
* @param orientation new orientation.
*/
public void lockCaptureOrientation(PlatformChannel.DeviceOrientation orientation) {
cameraFeatures.getSensorOrientation().lockCaptureOrientation(orientation);
}
/** Unlock capture orientation from dart. */
public void unlockCaptureOrientation() {
cameraFeatures.getSensorOrientation().unlockCaptureOrientation();
}
/** Pause the preview from dart. */
public void pausePreview() throws CameraAccessException {
this.pausedPreview = true;
this.captureSession.stopRepeating();
}
/** Resume the preview from dart. */
public void resumePreview() {
this.pausedPreview = false;
this.refreshPreviewCaptureSession(
null, (code, message) -> dartMessenger.sendCameraErrorEvent(message));
}
public void startPreview() throws CameraAccessException {
if (pictureImageReader == null || pictureImageReader.getSurface() == null) return;
Log.i(TAG, "startPreview");
createCaptureSession(CameraDevice.TEMPLATE_PREVIEW, pictureImageReader.getSurface());
}
public void startPreviewWithImageStream(EventChannel imageStreamChannel)
throws CameraAccessException {
setStreamHandler(imageStreamChannel);
startCapture(false, true);
Log.i(TAG, "startPreviewWithImageStream");
}
/**
* This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
* still image is ready to be saved.
*/
@Override
public void onImageAvailable(ImageReader reader) {
Log.i(TAG, "onImageAvailable");
backgroundHandler.post(
new ImageSaver(
// Use acquireNextImage since image reader is only for one image.
reader.acquireNextImage(),
captureFile,
new ImageSaver.Callback() {
@Override
public void onComplete(String absolutePath) {
dartMessenger.finish(flutterResult, absolutePath);
}
@Override
public void onError(String errorCode, String errorMessage) {
dartMessenger.error(flutterResult, errorCode, errorMessage, null);
}
}));
cameraCaptureCallback.setCameraState(CameraState.STATE_PREVIEW);
}
private void prepareRecording(@NonNull Result result) {
final File outputDir = applicationContext.getCacheDir();
try {
captureFile = File.createTempFile("REC", ".mp4", outputDir);
} catch (IOException | SecurityException e) {
result.error("cannotCreateFile", e.getMessage(), null);
return;
}
try {
prepareMediaRecorder(captureFile.getAbsolutePath());
} catch (IOException e) {
recordingVideo = false;
captureFile = null;
result.error("videoRecordingFailed", e.getMessage(), null);
return;
}
// Re-create autofocus feature so it's using video focus mode now.
cameraFeatures.setAutoFocus(
cameraFeatureFactory.createAutoFocusFeature(cameraProperties, true));
}
private void setStreamHandler(EventChannel imageStreamChannel) {
imageStreamChannel.setStreamHandler(
new EventChannel.StreamHandler() {
@Override
public void onListen(Object o, EventChannel.EventSink imageStreamSink) {
setImageStreamImageAvailableListener(imageStreamSink);
}
@Override
public void onCancel(Object o) {
imageStreamReader.setOnImageAvailableListener(null, backgroundHandler);
}
});
}
private void setImageStreamImageAvailableListener(final EventChannel.EventSink imageStreamSink) {
imageStreamReader.setOnImageAvailableListener(
reader -> {
Image img = reader.acquireNextImage();
// Use acquireNextImage since image reader is only for one image.
if (img == null) return;
List<Map<String, Object>> planes = new ArrayList<>();
for (Image.Plane plane : img.getPlanes()) {
ByteBuffer buffer = plane.getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes, 0, bytes.length);
Map<String, Object> planeBuffer = new HashMap<>();
planeBuffer.put("bytesPerRow", plane.getRowStride());
planeBuffer.put("bytesPerPixel", plane.getPixelStride());
planeBuffer.put("bytes", bytes);
planes.add(planeBuffer);
}
Map<String, Object> imageBuffer = new HashMap<>();
imageBuffer.put("width", img.getWidth());
imageBuffer.put("height", img.getHeight());
imageBuffer.put("format", img.getFormat());
imageBuffer.put("planes", planes);
imageBuffer.put("lensAperture", this.captureProps.getLastLensAperture());
imageBuffer.put("sensorExposureTime", this.captureProps.getLastSensorExposureTime());
Integer sensorSensitivity = this.captureProps.getLastSensorSensitivity();
imageBuffer.put(
"sensorSensitivity", sensorSensitivity == null ? null : (double) sensorSensitivity);
final Handler handler = new Handler(Looper.getMainLooper());
handler.post(() -> imageStreamSink.success(imageBuffer));
img.close();
},
backgroundHandler);
}
private void closeCaptureSession() {
if (captureSession != null) {
Log.i(TAG, "closeCaptureSession");
captureSession.close();
captureSession = null;
}
}
public void close() {
Log.i(TAG, "close");
if (cameraDevice != null) {
cameraDevice.close();
cameraDevice = null;
// Closing the CameraDevice without closing the CameraCaptureSession is recommended
// for quickly closing the camera:
// https://developer.android.com/reference/android/hardware/camera2/CameraCaptureSession#close()
captureSession = null;
} else {
closeCaptureSession();
}
if (pictureImageReader != null) {
pictureImageReader.close();
pictureImageReader = null;
}
if (imageStreamReader != null) {
imageStreamReader.close();
imageStreamReader = null;
}
if (mediaRecorder != null) {
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
}
stopBackgroundThread();
}
public void dispose() {
Log.i(TAG, "dispose");
close();
flutterTexture.release();
getDeviceOrientationManager().stop();
}
/** Factory class that assists in creating a {@link HandlerThread} instance. */
static class HandlerThreadFactory {
/**
* Creates a new instance of the {@link HandlerThread} class.
*
* <p>This method is visible for testing purposes only and should never be used outside this *
* class.
*
* @param name to give to the HandlerThread.
* @return new instance of the {@link HandlerThread} class.
*/
@VisibleForTesting
public static HandlerThread create(String name) {
return new HandlerThread(name);
}
}
/** Factory class that assists in creating a {@link Handler} instance. */
static class HandlerFactory {
/**
* Creates a new instance of the {@link Handler} class.
*
* <p>This method is visible for testing purposes only and should never be used outside this *
* class.
*
* @param looper to give to the Handler.
* @return new instance of the {@link Handler} class.
*/
@VisibleForTesting
public static Handler create(Looper looper) {
return new Handler(looper);
}
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/Camera.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/Camera.java",
"repo_id": "plugins",
"token_count": 15624
} | 1,130 |
// Copyright 2013 The Flutter 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.autofocus;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CaptureRequest;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.features.CameraFeature;
/** Controls the auto focus configuration on the {@see anddroid.hardware.camera2} API. */
public class AutoFocusFeature extends CameraFeature<FocusMode> {
private FocusMode currentSetting = FocusMode.auto;
// When switching recording modes this feature is re-created with the appropriate setting here.
private final boolean recordingVideo;
/**
* Creates a new instance of the {@see AutoFocusFeature}.
*
* @param cameraProperties Collection of the characteristics for the current camera device.
* @param recordingVideo Indicates whether the camera is currently recording video.
*/
public AutoFocusFeature(CameraProperties cameraProperties, boolean recordingVideo) {
super(cameraProperties);
this.recordingVideo = recordingVideo;
}
@Override
public String getDebugName() {
return "AutoFocusFeature";
}
@Override
public FocusMode getValue() {
return currentSetting;
}
@Override
public void setValue(FocusMode value) {
this.currentSetting = value;
}
@Override
public boolean checkIsSupported() {
int[] modes = cameraProperties.getControlAutoFocusAvailableModes();
final Float minFocus = cameraProperties.getLensInfoMinimumFocusDistance();
// Check if the focal length of the lens is fixed. If the minimum focus distance == 0, then the
// focal length is fixed. The minimum focus distance can be null on some devices: https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics#LENS_INFO_MINIMUM_FOCUS_DISTANCE
boolean isFixedLength = minFocus == null || minFocus == 0;
return !isFixedLength
&& !(modes.length == 0
|| (modes.length == 1 && modes[0] == CameraCharacteristics.CONTROL_AF_MODE_OFF));
}
@Override
public void updateBuilder(CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
switch (currentSetting) {
case locked:
// When locking the auto-focus the camera device should do a one-time focus and afterwards
// set the auto-focus to idle. This is accomplished by setting the CONTROL_AF_MODE to
// CONTROL_AF_MODE_AUTO.
requestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
break;
case auto:
requestBuilder.set(
CaptureRequest.CONTROL_AF_MODE,
recordingVideo
? CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO
: CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
default:
break;
}
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/autofocus/AutoFocusFeature.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/autofocus/AutoFocusFeature.java",
"repo_id": "plugins",
"token_count": 959
} | 1,131 |
// Copyright 2013 The Flutter 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.zoomlevel;
import android.graphics.Rect;
import android.hardware.camera2.CaptureRequest;
import android.os.Build;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.features.CameraFeature;
/** Controls the zoom configuration on the {@link android.hardware.camera2} API. */
public class ZoomLevelFeature extends CameraFeature<Float> {
private static final Float DEFAULT_ZOOM_LEVEL = 1.0f;
private final boolean hasSupport;
private final Rect sensorArraySize;
private Float currentSetting = DEFAULT_ZOOM_LEVEL;
private Float minimumZoomLevel = currentSetting;
private Float maximumZoomLevel;
/**
* Creates a new instance of the {@link ZoomLevelFeature}.
*
* @param cameraProperties Collection of characteristics for the current camera device.
*/
public ZoomLevelFeature(CameraProperties cameraProperties) {
super(cameraProperties);
sensorArraySize = cameraProperties.getSensorInfoActiveArraySize();
if (sensorArraySize == null) {
maximumZoomLevel = minimumZoomLevel;
hasSupport = false;
return;
}
// On Android 11+ CONTROL_ZOOM_RATIO_RANGE should be use to get the zoom ratio directly as minimum zoom does not have to be 1.0f.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
minimumZoomLevel = cameraProperties.getScalerMinZoomRatio();
maximumZoomLevel = cameraProperties.getScalerMaxZoomRatio();
} else {
minimumZoomLevel = DEFAULT_ZOOM_LEVEL;
Float maxDigitalZoom = cameraProperties.getScalerAvailableMaxDigitalZoom();
maximumZoomLevel =
((maxDigitalZoom == null) || (maxDigitalZoom < minimumZoomLevel))
? minimumZoomLevel
: maxDigitalZoom;
}
hasSupport = (Float.compare(maximumZoomLevel, minimumZoomLevel) > 0);
}
@Override
public String getDebugName() {
return "ZoomLevelFeature";
}
@Override
public Float getValue() {
return currentSetting;
}
@Override
public void setValue(Float value) {
currentSetting = value;
}
@Override
public boolean checkIsSupported() {
return hasSupport;
}
@Override
public void updateBuilder(CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
// On Android 11+ CONTROL_ZOOM_RATIO can be set to a zoom ratio and the camera feed will compute
// how to zoom on its own accounting for multiple logical cameras.
// Prior the image cropping window must be calculated and set manually.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
requestBuilder.set(
CaptureRequest.CONTROL_ZOOM_RATIO,
ZoomUtils.computeZoomRatio(currentSetting, minimumZoomLevel, maximumZoomLevel));
} else {
final Rect computedZoom =
ZoomUtils.computeZoomRect(
currentSetting, sensorArraySize, minimumZoomLevel, maximumZoomLevel);
requestBuilder.set(CaptureRequest.SCALER_CROP_REGION, computedZoom);
}
}
/**
* Gets the minimum supported zoom level.
*
* @return The minimum zoom level.
*/
public float getMinimumZoomLevel() {
return minimumZoomLevel;
}
/**
* Gets the maximum supported zoom level.
*
* @return The maximum zoom level.
*/
public float getMaximumZoomLevel() {
return maximumZoomLevel;
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/zoomlevel/ZoomLevelFeature.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/zoomlevel/ZoomLevelFeature.java",
"repo_id": "plugins",
"token_count": 1190
} | 1,132 |
// Copyright 2013 The Flutter 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.SessionConfiguration;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Size;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleObserver;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.camera.features.CameraFeatureFactory;
import io.flutter.plugins.camera.features.CameraFeatures;
import io.flutter.plugins.camera.features.Point;
import io.flutter.plugins.camera.features.autofocus.AutoFocusFeature;
import io.flutter.plugins.camera.features.autofocus.FocusMode;
import io.flutter.plugins.camera.features.exposurelock.ExposureLockFeature;
import io.flutter.plugins.camera.features.exposurelock.ExposureMode;
import io.flutter.plugins.camera.features.exposureoffset.ExposureOffsetFeature;
import io.flutter.plugins.camera.features.exposurepoint.ExposurePointFeature;
import io.flutter.plugins.camera.features.flash.FlashFeature;
import io.flutter.plugins.camera.features.flash.FlashMode;
import io.flutter.plugins.camera.features.focuspoint.FocusPointFeature;
import io.flutter.plugins.camera.features.fpsrange.FpsRangeFeature;
import io.flutter.plugins.camera.features.noisereduction.NoiseReductionFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionPreset;
import io.flutter.plugins.camera.features.sensororientation.DeviceOrientationManager;
import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature;
import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature;
import io.flutter.plugins.camera.utils.TestUtils;
import io.flutter.view.TextureRegistry;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
class FakeCameraDeviceWrapper implements CameraDeviceWrapper {
final List<CaptureRequest.Builder> captureRequests;
FakeCameraDeviceWrapper(List<CaptureRequest.Builder> captureRequests) {
this.captureRequests = captureRequests;
}
@NonNull
@Override
public CaptureRequest.Builder createCaptureRequest(int var1) {
return captureRequests.remove(0);
}
@Override
public void createCaptureSession(SessionConfiguration config) {}
@Override
public void createCaptureSession(
@NonNull List<Surface> outputs,
@NonNull CameraCaptureSession.StateCallback callback,
@Nullable Handler handler) {}
@Override
public void close() {}
}
public class CameraTest {
private CameraProperties mockCameraProperties;
private CameraFeatureFactory mockCameraFeatureFactory;
private DartMessenger mockDartMessenger;
private Camera camera;
private CameraCaptureSession mockCaptureSession;
private CaptureRequest.Builder mockPreviewRequestBuilder;
private MockedStatic<Camera.HandlerThreadFactory> mockHandlerThreadFactory;
private HandlerThread mockHandlerThread;
private MockedStatic<Camera.HandlerFactory> mockHandlerFactory;
private Handler mockHandler;
@Before
public void before() {
mockCameraProperties = mock(CameraProperties.class);
mockCameraFeatureFactory = new TestCameraFeatureFactory();
mockDartMessenger = mock(DartMessenger.class);
mockCaptureSession = mock(CameraCaptureSession.class);
mockPreviewRequestBuilder = mock(CaptureRequest.Builder.class);
mockHandlerThreadFactory = mockStatic(Camera.HandlerThreadFactory.class);
mockHandlerThread = mock(HandlerThread.class);
mockHandlerFactory = mockStatic(Camera.HandlerFactory.class);
mockHandler = mock(Handler.class);
final Activity mockActivity = mock(Activity.class);
final TextureRegistry.SurfaceTextureEntry mockFlutterTexture =
mock(TextureRegistry.SurfaceTextureEntry.class);
final String cameraName = "1";
final ResolutionPreset resolutionPreset = ResolutionPreset.high;
final boolean enableAudio = false;
when(mockCameraProperties.getCameraName()).thenReturn(cameraName);
mockHandlerFactory.when(() -> Camera.HandlerFactory.create(any())).thenReturn(mockHandler);
mockHandlerThreadFactory
.when(() -> Camera.HandlerThreadFactory.create(any()))
.thenReturn(mockHandlerThread);
camera =
new Camera(
mockActivity,
mockFlutterTexture,
mockCameraFeatureFactory,
mockDartMessenger,
mockCameraProperties,
resolutionPreset,
enableAudio);
TestUtils.setPrivateField(camera, "captureSession", mockCaptureSession);
TestUtils.setPrivateField(camera, "previewRequestBuilder", mockPreviewRequestBuilder);
}
@After
public void after() {
TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", 0);
mockHandlerThreadFactory.close();
mockHandlerFactory.close();
}
@Test
public void shouldNotImplementLifecycleObserverInterface() {
Class<Camera> cameraClass = Camera.class;
assertFalse(LifecycleObserver.class.isAssignableFrom(cameraClass));
}
@Test
public void shouldCreateCameraPluginAndSetAllFeatures() {
final Activity mockActivity = mock(Activity.class);
final TextureRegistry.SurfaceTextureEntry mockFlutterTexture =
mock(TextureRegistry.SurfaceTextureEntry.class);
final CameraFeatureFactory mockCameraFeatureFactory = mock(CameraFeatureFactory.class);
final String cameraName = "1";
final ResolutionPreset resolutionPreset = ResolutionPreset.high;
final boolean enableAudio = false;
when(mockCameraProperties.getCameraName()).thenReturn(cameraName);
SensorOrientationFeature mockSensorOrientationFeature = mock(SensorOrientationFeature.class);
when(mockCameraFeatureFactory.createSensorOrientationFeature(any(), any(), any()))
.thenReturn(mockSensorOrientationFeature);
Camera camera =
new Camera(
mockActivity,
mockFlutterTexture,
mockCameraFeatureFactory,
mockDartMessenger,
mockCameraProperties,
resolutionPreset,
enableAudio);
verify(mockCameraFeatureFactory, times(1))
.createSensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger);
verify(mockCameraFeatureFactory, times(1)).createAutoFocusFeature(mockCameraProperties, false);
verify(mockCameraFeatureFactory, times(1)).createExposureLockFeature(mockCameraProperties);
verify(mockCameraFeatureFactory, times(1))
.createExposurePointFeature(eq(mockCameraProperties), eq(mockSensorOrientationFeature));
verify(mockCameraFeatureFactory, times(1)).createExposureOffsetFeature(mockCameraProperties);
verify(mockCameraFeatureFactory, times(1)).createFlashFeature(mockCameraProperties);
verify(mockCameraFeatureFactory, times(1))
.createFocusPointFeature(eq(mockCameraProperties), eq(mockSensorOrientationFeature));
verify(mockCameraFeatureFactory, times(1)).createFpsRangeFeature(mockCameraProperties);
verify(mockCameraFeatureFactory, times(1)).createNoiseReductionFeature(mockCameraProperties);
verify(mockCameraFeatureFactory, times(1))
.createResolutionFeature(mockCameraProperties, resolutionPreset, cameraName);
verify(mockCameraFeatureFactory, times(1)).createZoomLevelFeature(mockCameraProperties);
assertNotNull("should create a camera", camera);
}
@Test
public void getDeviceOrientationManager() {
SensorOrientationFeature mockSensorOrientationFeature =
mockCameraFeatureFactory.createSensorOrientationFeature(mockCameraProperties, null, null);
DeviceOrientationManager mockDeviceOrientationManager = mock(DeviceOrientationManager.class);
when(mockSensorOrientationFeature.getDeviceOrientationManager())
.thenReturn(mockDeviceOrientationManager);
DeviceOrientationManager actualDeviceOrientationManager = camera.getDeviceOrientationManager();
verify(mockSensorOrientationFeature, times(1)).getDeviceOrientationManager();
assertEquals(mockDeviceOrientationManager, actualDeviceOrientationManager);
}
@Test
public void getExposureOffsetStepSize() {
ExposureOffsetFeature mockExposureOffsetFeature =
mockCameraFeatureFactory.createExposureOffsetFeature(mockCameraProperties);
double stepSize = 2.3;
when(mockExposureOffsetFeature.getExposureOffsetStepSize()).thenReturn(stepSize);
double actualSize = camera.getExposureOffsetStepSize();
verify(mockExposureOffsetFeature, times(1)).getExposureOffsetStepSize();
assertEquals(stepSize, actualSize, 0);
}
@Test
public void getMaxExposureOffset() {
ExposureOffsetFeature mockExposureOffsetFeature =
mockCameraFeatureFactory.createExposureOffsetFeature(mockCameraProperties);
double expectedMaxOffset = 42.0;
when(mockExposureOffsetFeature.getMaxExposureOffset()).thenReturn(expectedMaxOffset);
double actualMaxOffset = camera.getMaxExposureOffset();
verify(mockExposureOffsetFeature, times(1)).getMaxExposureOffset();
assertEquals(expectedMaxOffset, actualMaxOffset, 0);
}
@Test
public void getMinExposureOffset() {
ExposureOffsetFeature mockExposureOffsetFeature =
mockCameraFeatureFactory.createExposureOffsetFeature(mockCameraProperties);
double expectedMinOffset = 21.5;
when(mockExposureOffsetFeature.getMinExposureOffset()).thenReturn(21.5);
double actualMinOffset = camera.getMinExposureOffset();
verify(mockExposureOffsetFeature, times(1)).getMinExposureOffset();
assertEquals(expectedMinOffset, actualMinOffset, 0);
}
@Test
public void getMaxZoomLevel() {
ZoomLevelFeature mockZoomLevelFeature =
mockCameraFeatureFactory.createZoomLevelFeature(mockCameraProperties);
float expectedMaxZoomLevel = 4.2f;
when(mockZoomLevelFeature.getMaximumZoomLevel()).thenReturn(expectedMaxZoomLevel);
float actualMaxZoomLevel = camera.getMaxZoomLevel();
verify(mockZoomLevelFeature, times(1)).getMaximumZoomLevel();
assertEquals(expectedMaxZoomLevel, actualMaxZoomLevel, 0);
}
@Test
public void getMinZoomLevel() {
ZoomLevelFeature mockZoomLevelFeature =
mockCameraFeatureFactory.createZoomLevelFeature(mockCameraProperties);
float expectedMinZoomLevel = 4.2f;
when(mockZoomLevelFeature.getMinimumZoomLevel()).thenReturn(expectedMinZoomLevel);
float actualMinZoomLevel = camera.getMinZoomLevel();
verify(mockZoomLevelFeature, times(1)).getMinimumZoomLevel();
assertEquals(expectedMinZoomLevel, actualMinZoomLevel, 0);
}
@Test
public void setExposureMode_shouldUpdateExposureLockFeature() {
ExposureLockFeature mockExposureLockFeature =
mockCameraFeatureFactory.createExposureLockFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
ExposureMode exposureMode = ExposureMode.locked;
camera.setExposureMode(mockResult, exposureMode);
verify(mockExposureLockFeature, times(1)).setValue(exposureMode);
verify(mockResult, never()).error(any(), any(), any());
verify(mockResult, times(1)).success(null);
}
@Test
public void setExposureMode_shouldUpdateBuilder() {
ExposureLockFeature mockExposureLockFeature =
mockCameraFeatureFactory.createExposureLockFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
ExposureMode exposureMode = ExposureMode.locked;
camera.setExposureMode(mockResult, exposureMode);
verify(mockExposureLockFeature, times(1)).updateBuilder(any());
}
@Test
public void setExposureMode_shouldCallErrorOnResultOnCameraAccessException()
throws CameraAccessException {
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
ExposureMode exposureMode = ExposureMode.locked;
when(mockCaptureSession.setRepeatingRequest(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setExposureMode(mockResult, exposureMode);
verify(mockResult, never()).success(any());
verify(mockResult, times(1))
.error("setExposureModeFailed", "Could not set exposure mode.", null);
}
@Test
public void setExposurePoint_shouldUpdateExposurePointFeature() {
SensorOrientationFeature mockSensorOrientationFeature = mock(SensorOrientationFeature.class);
ExposurePointFeature mockExposurePointFeature =
mockCameraFeatureFactory.createExposurePointFeature(
mockCameraProperties, mockSensorOrientationFeature);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
Point point = new Point(42d, 42d);
camera.setExposurePoint(mockResult, point);
verify(mockExposurePointFeature, times(1)).setValue(point);
verify(mockResult, never()).error(any(), any(), any());
verify(mockResult, times(1)).success(null);
}
@Test
public void setExposurePoint_shouldUpdateBuilder() {
SensorOrientationFeature mockSensorOrientationFeature = mock(SensorOrientationFeature.class);
ExposurePointFeature mockExposurePointFeature =
mockCameraFeatureFactory.createExposurePointFeature(
mockCameraProperties, mockSensorOrientationFeature);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
Point point = new Point(42d, 42d);
camera.setExposurePoint(mockResult, point);
verify(mockExposurePointFeature, times(1)).updateBuilder(any());
}
@Test
public void setExposurePoint_shouldCallErrorOnResultOnCameraAccessException()
throws CameraAccessException {
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
Point point = new Point(42d, 42d);
when(mockCaptureSession.setRepeatingRequest(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setExposurePoint(mockResult, point);
verify(mockResult, never()).success(any());
verify(mockResult, times(1))
.error("setExposurePointFailed", "Could not set exposure point.", null);
}
@Test
public void setFlashMode_shouldUpdateFlashFeature() {
FlashFeature mockFlashFeature =
mockCameraFeatureFactory.createFlashFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
FlashMode flashMode = FlashMode.always;
camera.setFlashMode(mockResult, flashMode);
verify(mockFlashFeature, times(1)).setValue(flashMode);
verify(mockResult, never()).error(any(), any(), any());
verify(mockResult, times(1)).success(null);
}
@Test
public void setFlashMode_shouldUpdateBuilder() {
FlashFeature mockFlashFeature =
mockCameraFeatureFactory.createFlashFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
FlashMode flashMode = FlashMode.always;
camera.setFlashMode(mockResult, flashMode);
verify(mockFlashFeature, times(1)).updateBuilder(any());
}
@Test
public void setFlashMode_shouldCallErrorOnResultOnCameraAccessException()
throws CameraAccessException {
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
FlashMode flashMode = FlashMode.always;
when(mockCaptureSession.setRepeatingRequest(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setFlashMode(mockResult, flashMode);
verify(mockResult, never()).success(any());
verify(mockResult, times(1)).error("setFlashModeFailed", "Could not set flash mode.", null);
}
@Test
public void setFocusPoint_shouldUpdateFocusPointFeature() {
SensorOrientationFeature mockSensorOrientationFeature = mock(SensorOrientationFeature.class);
FocusPointFeature mockFocusPointFeature =
mockCameraFeatureFactory.createFocusPointFeature(
mockCameraProperties, mockSensorOrientationFeature);
AutoFocusFeature mockAutoFocusFeature =
mockCameraFeatureFactory.createAutoFocusFeature(mockCameraProperties, false);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
Point point = new Point(42d, 42d);
when(mockAutoFocusFeature.getValue()).thenReturn(FocusMode.auto);
camera.setFocusPoint(mockResult, point);
verify(mockFocusPointFeature, times(1)).setValue(point);
verify(mockResult, never()).error(any(), any(), any());
verify(mockResult, times(1)).success(null);
}
@Test
public void setFocusPoint_shouldUpdateBuilder() {
SensorOrientationFeature mockSensorOrientationFeature = mock(SensorOrientationFeature.class);
FocusPointFeature mockFocusPointFeature =
mockCameraFeatureFactory.createFocusPointFeature(
mockCameraProperties, mockSensorOrientationFeature);
AutoFocusFeature mockAutoFocusFeature =
mockCameraFeatureFactory.createAutoFocusFeature(mockCameraProperties, false);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
Point point = new Point(42d, 42d);
when(mockAutoFocusFeature.getValue()).thenReturn(FocusMode.auto);
camera.setFocusPoint(mockResult, point);
verify(mockFocusPointFeature, times(1)).updateBuilder(any());
}
@Test
public void setFocusPoint_shouldCallErrorOnResultOnCameraAccessException()
throws CameraAccessException {
AutoFocusFeature mockAutoFocusFeature =
mockCameraFeatureFactory.createAutoFocusFeature(mockCameraProperties, false);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
Point point = new Point(42d, 42d);
when(mockAutoFocusFeature.getValue()).thenReturn(FocusMode.auto);
when(mockCaptureSession.setRepeatingRequest(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setFocusPoint(mockResult, point);
verify(mockResult, never()).success(any());
verify(mockResult, times(1)).error("setFocusPointFailed", "Could not set focus point.", null);
}
@Test
public void setZoomLevel_shouldUpdateZoomLevelFeature() throws CameraAccessException {
ZoomLevelFeature mockZoomLevelFeature =
mockCameraFeatureFactory.createZoomLevelFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
float zoomLevel = 1.0f;
when(mockZoomLevelFeature.getValue()).thenReturn(zoomLevel);
when(mockZoomLevelFeature.getMinimumZoomLevel()).thenReturn(0f);
when(mockZoomLevelFeature.getMaximumZoomLevel()).thenReturn(2f);
camera.setZoomLevel(mockResult, zoomLevel);
verify(mockZoomLevelFeature, times(1)).setValue(zoomLevel);
verify(mockResult, never()).error(any(), any(), any());
verify(mockResult, times(1)).success(null);
}
@Test
public void setZoomLevel_shouldUpdateBuilder() throws CameraAccessException {
ZoomLevelFeature mockZoomLevelFeature =
mockCameraFeatureFactory.createZoomLevelFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
float zoomLevel = 1.0f;
when(mockZoomLevelFeature.getValue()).thenReturn(zoomLevel);
when(mockZoomLevelFeature.getMinimumZoomLevel()).thenReturn(0f);
when(mockZoomLevelFeature.getMaximumZoomLevel()).thenReturn(2f);
camera.setZoomLevel(mockResult, zoomLevel);
verify(mockZoomLevelFeature, times(1)).updateBuilder(any());
}
@Test
public void setZoomLevel_shouldCallErrorOnResultOnCameraAccessException()
throws CameraAccessException {
ZoomLevelFeature mockZoomLevelFeature =
mockCameraFeatureFactory.createZoomLevelFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
float zoomLevel = 1.0f;
when(mockZoomLevelFeature.getValue()).thenReturn(zoomLevel);
when(mockZoomLevelFeature.getMinimumZoomLevel()).thenReturn(0f);
when(mockZoomLevelFeature.getMaximumZoomLevel()).thenReturn(2f);
when(mockCaptureSession.setRepeatingRequest(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setZoomLevel(mockResult, zoomLevel);
verify(mockResult, never()).success(any());
verify(mockResult, times(1)).error("setZoomLevelFailed", "Could not set zoom level.", null);
}
@Test
public void pauseVideoRecording_shouldSendNullResultWhenNotRecording() {
TestUtils.setPrivateField(camera, "recordingVideo", false);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
camera.pauseVideoRecording(mockResult);
verify(mockResult, times(1)).success(null);
verify(mockResult, never()).error(any(), any(), any());
}
@Test
public void pauseVideoRecording_shouldCallPauseWhenRecordingAndOnAPIN() {
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
MediaRecorder mockMediaRecorder = mock(MediaRecorder.class);
TestUtils.setPrivateField(camera, "mediaRecorder", mockMediaRecorder);
TestUtils.setPrivateField(camera, "recordingVideo", true);
TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", 24);
camera.pauseVideoRecording(mockResult);
verify(mockMediaRecorder, times(1)).pause();
verify(mockResult, times(1)).success(null);
verify(mockResult, never()).error(any(), any(), any());
}
@Test
public void pauseVideoRecording_shouldSendVideoRecordingFailedErrorWhenVersionCodeSmallerThenN() {
TestUtils.setPrivateField(camera, "recordingVideo", true);
TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", 23);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
camera.pauseVideoRecording(mockResult);
verify(mockResult, times(1))
.error("videoRecordingFailed", "pauseVideoRecording requires Android API +24.", null);
verify(mockResult, never()).success(any());
}
@Test
public void
pauseVideoRecording_shouldSendVideoRecordingFailedErrorWhenMediaRecorderPauseThrowsIllegalStateException() {
MediaRecorder mockMediaRecorder = mock(MediaRecorder.class);
TestUtils.setPrivateField(camera, "mediaRecorder", mockMediaRecorder);
TestUtils.setPrivateField(camera, "recordingVideo", true);
TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", 24);
IllegalStateException expectedException = new IllegalStateException("Test error message");
doThrow(expectedException).when(mockMediaRecorder).pause();
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
camera.pauseVideoRecording(mockResult);
verify(mockResult, times(1)).error("videoRecordingFailed", "Test error message", null);
verify(mockResult, never()).success(any());
}
@Test
public void resumeVideoRecording_shouldSendNullResultWhenNotRecording() {
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
TestUtils.setPrivateField(camera, "recordingVideo", false);
camera.resumeVideoRecording(mockResult);
verify(mockResult, times(1)).success(null);
verify(mockResult, never()).error(any(), any(), any());
}
@Test
public void resumeVideoRecording_shouldCallPauseWhenRecordingAndOnAPIN() {
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
MediaRecorder mockMediaRecorder = mock(MediaRecorder.class);
TestUtils.setPrivateField(camera, "mediaRecorder", mockMediaRecorder);
TestUtils.setPrivateField(camera, "recordingVideo", true);
TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", 24);
camera.resumeVideoRecording(mockResult);
verify(mockMediaRecorder, times(1)).resume();
verify(mockResult, times(1)).success(null);
verify(mockResult, never()).error(any(), any(), any());
}
@Test
public void
resumeVideoRecording_shouldSendVideoRecordingFailedErrorWhenVersionCodeSmallerThanN() {
TestUtils.setPrivateField(camera, "recordingVideo", true);
TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", 23);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
camera.resumeVideoRecording(mockResult);
verify(mockResult, times(1))
.error("videoRecordingFailed", "resumeVideoRecording requires Android API +24.", null);
verify(mockResult, never()).success(any());
}
@Test
public void
resumeVideoRecording_shouldSendVideoRecordingFailedErrorWhenMediaRecorderPauseThrowsIllegalStateException() {
MediaRecorder mockMediaRecorder = mock(MediaRecorder.class);
TestUtils.setPrivateField(camera, "mediaRecorder", mockMediaRecorder);
TestUtils.setPrivateField(camera, "recordingVideo", true);
TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", 24);
IllegalStateException expectedException = new IllegalStateException("Test error message");
doThrow(expectedException).when(mockMediaRecorder).resume();
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
camera.resumeVideoRecording(mockResult);
verify(mockResult, times(1)).error("videoRecordingFailed", "Test error message", null);
verify(mockResult, never()).success(any());
}
@Test
public void setFocusMode_shouldUpdateAutoFocusFeature() {
AutoFocusFeature mockAutoFocusFeature =
mockCameraFeatureFactory.createAutoFocusFeature(mockCameraProperties, false);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
camera.setFocusMode(mockResult, FocusMode.auto);
verify(mockAutoFocusFeature, times(1)).setValue(FocusMode.auto);
verify(mockResult, never()).error(any(), any(), any());
verify(mockResult, times(1)).success(null);
}
@Test
public void setFocusMode_shouldUpdateBuilder() {
AutoFocusFeature mockAutoFocusFeature =
mockCameraFeatureFactory.createAutoFocusFeature(mockCameraProperties, false);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
camera.setFocusMode(mockResult, FocusMode.auto);
verify(mockAutoFocusFeature, times(1)).updateBuilder(any());
}
@Test
public void setFocusMode_shouldUnlockAutoFocusForAutoMode() {
camera.setFocusMode(mock(MethodChannel.Result.class), FocusMode.auto);
verify(mockPreviewRequestBuilder, times(1))
.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
verify(mockPreviewRequestBuilder, times(1))
.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_IDLE);
}
@Test
public void setFocusMode_shouldSkipUnlockAutoFocusWhenNullCaptureSession() {
TestUtils.setPrivateField(camera, "captureSession", null);
camera.setFocusMode(mock(MethodChannel.Result.class), FocusMode.auto);
verify(mockPreviewRequestBuilder, never())
.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
verify(mockPreviewRequestBuilder, never())
.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_IDLE);
}
@Test
public void setFocusMode_shouldSendErrorEventOnUnlockAutoFocusCameraAccessException()
throws CameraAccessException {
when(mockCaptureSession.capture(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setFocusMode(mock(MethodChannel.Result.class), FocusMode.auto);
verify(mockDartMessenger, times(1)).sendCameraErrorEvent(any());
}
@Test
public void setFocusMode_shouldLockAutoFocusForLockedMode() throws CameraAccessException {
camera.setFocusMode(mock(MethodChannel.Result.class), FocusMode.locked);
verify(mockPreviewRequestBuilder, times(1))
.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);
verify(mockCaptureSession, times(1)).capture(any(), any(), any());
verify(mockCaptureSession, times(1)).setRepeatingRequest(any(), any(), any());
}
@Test
public void setFocusMode_shouldSkipLockAutoFocusWhenNullCaptureSession() {
TestUtils.setPrivateField(camera, "captureSession", null);
camera.setFocusMode(mock(MethodChannel.Result.class), FocusMode.locked);
verify(mockPreviewRequestBuilder, never())
.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);
}
@Test
public void setFocusMode_shouldSendErrorEventOnLockAutoFocusCameraAccessException()
throws CameraAccessException {
when(mockCaptureSession.capture(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setFocusMode(mock(MethodChannel.Result.class), FocusMode.locked);
verify(mockDartMessenger, times(1)).sendCameraErrorEvent(any());
}
@Test
public void setFocusMode_shouldCallErrorOnResultOnCameraAccessException()
throws CameraAccessException {
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
when(mockCaptureSession.setRepeatingRequest(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setFocusMode(mockResult, FocusMode.locked);
verify(mockResult, never()).success(any());
verify(mockResult, times(1))
.error("setFocusModeFailed", "Error setting focus mode: null", null);
}
@Test
public void setExposureOffset_shouldUpdateExposureOffsetFeature() {
ExposureOffsetFeature mockExposureOffsetFeature =
mockCameraFeatureFactory.createExposureOffsetFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
when(mockExposureOffsetFeature.getValue()).thenReturn(1.0);
camera.setExposureOffset(mockResult, 1.0);
verify(mockExposureOffsetFeature, times(1)).setValue(1.0);
verify(mockResult, never()).error(any(), any(), any());
verify(mockResult, times(1)).success(1.0);
}
@Test
public void setExposureOffset_shouldAndUpdateBuilder() {
ExposureOffsetFeature mockExposureOffsetFeature =
mockCameraFeatureFactory.createExposureOffsetFeature(mockCameraProperties);
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
camera.setExposureOffset(mockResult, 1.0);
verify(mockExposureOffsetFeature, times(1)).updateBuilder(any());
}
@Test
public void setExposureOffset_shouldCallErrorOnResultOnCameraAccessException()
throws CameraAccessException {
MethodChannel.Result mockResult = mock(MethodChannel.Result.class);
when(mockCaptureSession.setRepeatingRequest(any(), any(), any()))
.thenThrow(new CameraAccessException(0, ""));
camera.setExposureOffset(mockResult, 1.0);
verify(mockResult, never()).success(any());
verify(mockResult, times(1))
.error("setExposureOffsetFailed", "Could not set exposure offset.", null);
}
@Test
public void lockCaptureOrientation_shouldLockCaptureOrientation() {
final Activity mockActivity = mock(Activity.class);
SensorOrientationFeature mockSensorOrientationFeature =
mockCameraFeatureFactory.createSensorOrientationFeature(
mockCameraProperties, mockActivity, mockDartMessenger);
camera.lockCaptureOrientation(PlatformChannel.DeviceOrientation.PORTRAIT_UP);
verify(mockSensorOrientationFeature, times(1))
.lockCaptureOrientation(PlatformChannel.DeviceOrientation.PORTRAIT_UP);
}
@Test
public void unlockCaptureOrientation_shouldUnlockCaptureOrientation() {
final Activity mockActivity = mock(Activity.class);
SensorOrientationFeature mockSensorOrientationFeature =
mockCameraFeatureFactory.createSensorOrientationFeature(
mockCameraProperties, mockActivity, mockDartMessenger);
camera.unlockCaptureOrientation();
verify(mockSensorOrientationFeature, times(1)).unlockCaptureOrientation();
}
@Test
public void pausePreview_shouldPausePreview() throws CameraAccessException {
camera.pausePreview();
assertEquals(TestUtils.getPrivateField(camera, "pausedPreview"), true);
verify(mockCaptureSession, times(1)).stopRepeating();
}
@Test
public void resumePreview_shouldResumePreview() throws CameraAccessException {
camera.resumePreview();
assertEquals(TestUtils.getPrivateField(camera, "pausedPreview"), false);
verify(mockCaptureSession, times(1)).setRepeatingRequest(any(), any(), any());
}
@Test
public void resumePreview_shouldSendErrorEventOnCameraAccessException()
throws CameraAccessException {
when(mockCaptureSession.setRepeatingRequest(any(), any(), any()))
.thenThrow(new CameraAccessException(0));
camera.resumePreview();
verify(mockDartMessenger, times(1)).sendCameraErrorEvent(any());
}
@Test
public void startBackgroundThread_shouldStartNewThread() {
camera.startBackgroundThread();
verify(mockHandlerThread, times(1)).start();
assertEquals(mockHandler, TestUtils.getPrivateField(camera, "backgroundHandler"));
}
@Test
public void startBackgroundThread_shouldNotStartNewThreadWhenAlreadyCreated() {
camera.startBackgroundThread();
camera.startBackgroundThread();
verify(mockHandlerThread, times(1)).start();
}
@Test
public void stopBackgroundThread_quitsSafely() throws InterruptedException {
camera.startBackgroundThread();
camera.stopBackgroundThread();
verify(mockHandlerThread).quitSafely();
verify(mockHandlerThread, never()).join();
}
@Test
public void onConverge_shouldTakePictureWithoutAbortingSession() throws CameraAccessException {
ArrayList<CaptureRequest.Builder> mockRequestBuilders = new ArrayList<>();
mockRequestBuilders.add(mock(CaptureRequest.Builder.class));
CameraDeviceWrapper fakeCamera = new FakeCameraDeviceWrapper(mockRequestBuilders);
// Stub out other features used by the flow.
TestUtils.setPrivateField(camera, "cameraDevice", fakeCamera);
TestUtils.setPrivateField(camera, "pictureImageReader", mock(ImageReader.class));
SensorOrientationFeature mockSensorOrientationFeature =
mockCameraFeatureFactory.createSensorOrientationFeature(mockCameraProperties, null, null);
DeviceOrientationManager mockDeviceOrientationManager = mock(DeviceOrientationManager.class);
when(mockSensorOrientationFeature.getDeviceOrientationManager())
.thenReturn(mockDeviceOrientationManager);
// Simulate a post-precapture flow.
camera.onConverged();
// A picture should be taken.
verify(mockCaptureSession, times(1)).capture(any(), any(), any());
// The session shuold not be aborted as part of this flow, as this breaks capture on some
// devices, and causes delays on others.
verify(mockCaptureSession, never()).abortCaptures();
}
@Test
public void createCaptureSession_doesNotCloseCaptureSession() throws CameraAccessException {
Surface mockSurface = mock(Surface.class);
SurfaceTexture mockSurfaceTexture = mock(SurfaceTexture.class);
ResolutionFeature mockResolutionFeature = mock(ResolutionFeature.class);
Size mockSize = mock(Size.class);
ArrayList<CaptureRequest.Builder> mockRequestBuilders = new ArrayList<>();
mockRequestBuilders.add(mock(CaptureRequest.Builder.class));
CameraDeviceWrapper fakeCamera = new FakeCameraDeviceWrapper(mockRequestBuilders);
TestUtils.setPrivateField(camera, "cameraDevice", fakeCamera);
TextureRegistry.SurfaceTextureEntry cameraFlutterTexture =
(TextureRegistry.SurfaceTextureEntry) TestUtils.getPrivateField(camera, "flutterTexture");
CameraFeatures cameraFeatures =
(CameraFeatures) TestUtils.getPrivateField(camera, "cameraFeatures");
ResolutionFeature resolutionFeature =
(ResolutionFeature)
TestUtils.getPrivateField(mockCameraFeatureFactory, "mockResolutionFeature");
when(cameraFlutterTexture.surfaceTexture()).thenReturn(mockSurfaceTexture);
when(resolutionFeature.getPreviewSize()).thenReturn(mockSize);
camera.createCaptureSession(CameraDevice.TEMPLATE_PREVIEW, mockSurface);
verify(mockCaptureSession, never()).close();
}
@Test
public void close_doesCloseCaptureSessionWhenCameraDeviceNull() {
camera.close();
verify(mockCaptureSession).close();
}
@Test
public void close_doesNotCloseCaptureSessionWhenCameraDeviceNonNull() {
ArrayList<CaptureRequest.Builder> mockRequestBuilders = new ArrayList<>();
mockRequestBuilders.add(mock(CaptureRequest.Builder.class));
CameraDeviceWrapper fakeCamera = new FakeCameraDeviceWrapper(mockRequestBuilders);
TestUtils.setPrivateField(camera, "cameraDevice", fakeCamera);
camera.close();
verify(mockCaptureSession, never()).close();
}
private static class TestCameraFeatureFactory implements CameraFeatureFactory {
private final AutoFocusFeature mockAutoFocusFeature;
private final ExposureLockFeature mockExposureLockFeature;
private final ExposureOffsetFeature mockExposureOffsetFeature;
private final ExposurePointFeature mockExposurePointFeature;
private final FlashFeature mockFlashFeature;
private final FocusPointFeature mockFocusPointFeature;
private final FpsRangeFeature mockFpsRangeFeature;
private final NoiseReductionFeature mockNoiseReductionFeature;
private final ResolutionFeature mockResolutionFeature;
private final SensorOrientationFeature mockSensorOrientationFeature;
private final ZoomLevelFeature mockZoomLevelFeature;
public TestCameraFeatureFactory() {
this.mockAutoFocusFeature = mock(AutoFocusFeature.class);
this.mockExposureLockFeature = mock(ExposureLockFeature.class);
this.mockExposureOffsetFeature = mock(ExposureOffsetFeature.class);
this.mockExposurePointFeature = mock(ExposurePointFeature.class);
this.mockFlashFeature = mock(FlashFeature.class);
this.mockFocusPointFeature = mock(FocusPointFeature.class);
this.mockFpsRangeFeature = mock(FpsRangeFeature.class);
this.mockNoiseReductionFeature = mock(NoiseReductionFeature.class);
this.mockResolutionFeature = mock(ResolutionFeature.class);
this.mockSensorOrientationFeature = mock(SensorOrientationFeature.class);
this.mockZoomLevelFeature = mock(ZoomLevelFeature.class);
}
@Override
public AutoFocusFeature createAutoFocusFeature(
@NonNull CameraProperties cameraProperties, boolean recordingVideo) {
return mockAutoFocusFeature;
}
@Override
public ExposureLockFeature createExposureLockFeature(
@NonNull CameraProperties cameraProperties) {
return mockExposureLockFeature;
}
@Override
public ExposureOffsetFeature createExposureOffsetFeature(
@NonNull CameraProperties cameraProperties) {
return mockExposureOffsetFeature;
}
@Override
public FlashFeature createFlashFeature(@NonNull CameraProperties cameraProperties) {
return mockFlashFeature;
}
@Override
public ResolutionFeature createResolutionFeature(
@NonNull CameraProperties cameraProperties,
ResolutionPreset initialSetting,
String cameraName) {
return mockResolutionFeature;
}
@Override
public FocusPointFeature createFocusPointFeature(
@NonNull CameraProperties cameraProperties,
@NonNull SensorOrientationFeature sensorOrienttionFeature) {
return mockFocusPointFeature;
}
@Override
public FpsRangeFeature createFpsRangeFeature(@NonNull CameraProperties cameraProperties) {
return mockFpsRangeFeature;
}
@Override
public SensorOrientationFeature createSensorOrientationFeature(
@NonNull CameraProperties cameraProperties,
@NonNull Activity activity,
@NonNull DartMessenger dartMessenger) {
return mockSensorOrientationFeature;
}
@Override
public ZoomLevelFeature createZoomLevelFeature(@NonNull CameraProperties cameraProperties) {
return mockZoomLevelFeature;
}
@Override
public ExposurePointFeature createExposurePointFeature(
@NonNull CameraProperties cameraProperties,
@NonNull SensorOrientationFeature sensorOrientationFeature) {
return mockExposurePointFeature;
}
@Override
public NoiseReductionFeature createNoiseReductionFeature(
@NonNull CameraProperties cameraProperties) {
return mockNoiseReductionFeature;
}
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraTest.java",
"repo_id": "plugins",
"token_count": 13087
} | 1,133 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.noisereduction;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
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.os.Build.VERSION;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.utils.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NoiseReductionFeatureTest {
@Before
public void before() {
// Make sure the VERSION.SDK_INT field returns 23, to allow using all available
// noise reduction modes in tests.
TestUtils.setFinalStatic(VERSION.class, "SDK_INT", 23);
}
@After
public void after() {
// Make sure we reset the VERSION.SDK_INT field to it's original value.
TestUtils.setFinalStatic(VERSION.class, "SDK_INT", 0);
}
@Test
public void getDebugName_shouldReturnTheNameOfTheFeature() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
NoiseReductionFeature noiseReductionFeature = new NoiseReductionFeature(mockCameraProperties);
assertEquals("NoiseReductionFeature", noiseReductionFeature.getDebugName());
}
@Test
public void getValue_shouldReturnFastIfNotSet() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
NoiseReductionFeature noiseReductionFeature = new NoiseReductionFeature(mockCameraProperties);
assertEquals(NoiseReductionMode.fast, noiseReductionFeature.getValue());
}
@Test
public void getValue_shouldEchoTheSetValue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
NoiseReductionFeature noiseReductionFeature = new NoiseReductionFeature(mockCameraProperties);
NoiseReductionMode expectedValue = NoiseReductionMode.fast;
noiseReductionFeature.setValue(expectedValue);
NoiseReductionMode actualValue = noiseReductionFeature.getValue();
assertEquals(expectedValue, actualValue);
}
@Test
public void checkIsSupported_shouldReturnFalseWhenAvailableNoiseReductionModesIsNull() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
NoiseReductionFeature noiseReductionFeature = new NoiseReductionFeature(mockCameraProperties);
when(mockCameraProperties.getAvailableNoiseReductionModes()).thenReturn(null);
assertFalse(noiseReductionFeature.checkIsSupported());
}
@Test
public void
checkIsSupported_shouldReturnFalseWhenAvailableNoiseReductionModesReturnsAnEmptyArray() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
NoiseReductionFeature noiseReductionFeature = new NoiseReductionFeature(mockCameraProperties);
when(mockCameraProperties.getAvailableNoiseReductionModes()).thenReturn(new int[] {});
assertFalse(noiseReductionFeature.checkIsSupported());
}
@Test
public void
checkIsSupported_shouldReturnTrueWhenAvailableNoiseReductionModesReturnsAtLeastOneItem() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
NoiseReductionFeature noiseReductionFeature = new NoiseReductionFeature(mockCameraProperties);
when(mockCameraProperties.getAvailableNoiseReductionModes()).thenReturn(new int[] {1});
assertTrue(noiseReductionFeature.checkIsSupported());
}
@Test
public void updateBuilder_shouldReturnWhenCheckIsSupportedIsFalse() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
NoiseReductionFeature noiseReductionFeature = new NoiseReductionFeature(mockCameraProperties);
when(mockCameraProperties.getAvailableNoiseReductionModes()).thenReturn(new int[] {});
noiseReductionFeature.updateBuilder(mockBuilder);
verify(mockBuilder, never()).set(any(), any());
}
@Test
public void updateBuilder_shouldSetNoiseReductionModeOffWhenOff() {
testUpdateBuilderWith(NoiseReductionMode.off, CaptureRequest.NOISE_REDUCTION_MODE_OFF);
}
@Test
public void updateBuilder_shouldSetNoiseReductionModeFastWhenFast() {
testUpdateBuilderWith(NoiseReductionMode.fast, CaptureRequest.NOISE_REDUCTION_MODE_FAST);
}
@Test
public void updateBuilder_shouldSetNoiseReductionModeHighQualityWhenHighQuality() {
testUpdateBuilderWith(
NoiseReductionMode.highQuality, CaptureRequest.NOISE_REDUCTION_MODE_HIGH_QUALITY);
}
@Test
public void updateBuilder_shouldSetNoiseReductionModeMinimalWhenMinimal() {
testUpdateBuilderWith(NoiseReductionMode.minimal, CaptureRequest.NOISE_REDUCTION_MODE_MINIMAL);
}
@Test
public void updateBuilder_shouldSetNoiseReductionModeZeroShutterLagWhenZeroShutterLag() {
testUpdateBuilderWith(
NoiseReductionMode.zeroShutterLag, CaptureRequest.NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG);
}
private static void testUpdateBuilderWith(NoiseReductionMode mode, int expectedResult) {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
NoiseReductionFeature noiseReductionFeature = new NoiseReductionFeature(mockCameraProperties);
when(mockCameraProperties.getAvailableNoiseReductionModes()).thenReturn(new int[] {1});
noiseReductionFeature.setValue(mode);
noiseReductionFeature.updateBuilder(mockBuilder);
verify(mockBuilder, times(1)).set(CaptureRequest.NOISE_REDUCTION_MODE, expectedResult);
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/noisereduction/NoiseReductionFeatureTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/noisereduction/NoiseReductionFeatureTest.java",
"repo_id": "plugins",
"token_count": 1794
} | 1,134 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.cameraexample">
<application
android:icon="@mipmap/ic_launcher"
android:label="camera_example">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:launchMode="singleTop"
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/LaunchTheme"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
<uses-feature
android:name="android.hardware.camera"
android:required="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
</manifest>
| plugins/packages/camera/camera_android/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/camera/camera_android/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 379
} | 1,135 |
group 'io.flutter.plugins.camerax'
version '1.0'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
// CameraX dependencies require compilation against version 33 or later.
compileSdkVersion 33
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
// Many of the CameraX APIs require API 21.
minSdkVersion 21
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
lintOptions {
disable 'AndroidGradlePluginVersion'
disable 'GradleDependency'
}
}
dependencies {
// CameraX core library using the camera2 implementation must use same version number.
def camerax_version = "1.3.0-alpha03"
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"
implementation "androidx.camera:camera-lifecycle:${camerax_version}"
implementation 'com.google.guava:guava:31.1-android'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-inline:5.0.0'
testImplementation 'androidx.test:core:1.4.0'
testImplementation 'org.robolectric:robolectric:4.8'
}
| plugins/packages/camera/camera_android_camerax/android/build.gradle/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/build.gradle",
"repo_id": "plugins",
"token_count": 757
} | 1,136 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.camera.lifecycle.ProcessCameraProvider;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ProcessCameraProviderFlutterApi;
public class ProcessCameraProviderFlutterApiImpl extends ProcessCameraProviderFlutterApi {
public ProcessCameraProviderFlutterApiImpl(
BinaryMessenger binaryMessenger, InstanceManager instanceManager) {
super(binaryMessenger);
this.instanceManager = instanceManager;
}
private final InstanceManager instanceManager;
void create(ProcessCameraProvider processCameraProvider, Reply<Void> reply) {
create(instanceManager.addHostCreatedInstance(processCameraProvider), reply);
}
}
| plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderFlutterApiImpl.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderFlutterApiImpl.java",
"repo_id": "plugins",
"token_count": 246
} | 1,137 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| plugins/packages/camera/camera_android_camerax/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 30
} | 1,138 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camera_info.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// Selects a camera for use.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector.
class CameraSelector extends JavaObject {
/// Creates a [CameraSelector].
CameraSelector(
{BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
this.lensFacing})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = CameraSelectorHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
_api.createFromInstance(this, lensFacing);
}
/// Creates a detached [CameraSelector].
CameraSelector.detached(
{BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
this.lensFacing})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = CameraSelectorHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final CameraSelectorHostApiImpl _api;
/// ID for front facing lens.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_FRONT().
static const int lensFacingFront = 0;
/// ID for back facing lens.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_BACK().
static const int lensFacingBack = 1;
/// ID for external lens.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_EXTERNAL().
static const int lensFacingExternal = 2;
/// ID for unknown lens.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_UNKNOWN().
static const int lensFacingUnknown = -1;
/// Selector for default front facing camera.
static CameraSelector getDefaultFrontCamera({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) {
return CameraSelector(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
lensFacing: lensFacingFront,
);
}
/// Selector for default back facing camera.
static CameraSelector getDefaultBackCamera({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) {
return CameraSelector(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
lensFacing: lensFacingBack,
);
}
/// Lens direction of this selector.
final int? lensFacing;
/// Filters available cameras based on provided [CameraInfo]s.
Future<List<CameraInfo>> filter(List<CameraInfo> cameraInfos) {
return _api.filterFromInstance(this, cameraInfos);
}
}
/// Host API implementation of [CameraSelector].
class CameraSelectorHostApiImpl extends CameraSelectorHostApi {
/// Constructs a [CameraSelectorHostApiImpl].
CameraSelectorHostApiImpl(
{this.binaryMessenger, InstanceManager? instanceManager})
: super(binaryMessenger: binaryMessenger) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Creates a [CameraSelector] with the lens direction provided if specified.
void createFromInstance(CameraSelector instance, int? lensFacing) {
int? identifier = instanceManager.getIdentifier(instance);
identifier ??= instanceManager.addDartCreatedInstance(instance,
onCopy: (CameraSelector original) {
return CameraSelector.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
lensFacing: original.lensFacing);
});
create(identifier, lensFacing);
}
/// Filters a list of [CameraInfo]s based on the [CameraSelector].
Future<List<CameraInfo>> filterFromInstance(
CameraSelector instance,
List<CameraInfo> cameraInfos,
) async {
int? identifier = instanceManager.getIdentifier(instance);
identifier ??= instanceManager.addDartCreatedInstance(instance,
onCopy: (CameraSelector original) {
return CameraSelector.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
lensFacing: original.lensFacing);
});
final List<int> cameraInfoIds = cameraInfos
.map<int>((CameraInfo info) => instanceManager.getIdentifier(info)!)
.toList();
final List<int?> filteredCameraInfoIds =
await filter(identifier, cameraInfoIds);
if (filteredCameraInfoIds.isEmpty) {
return <CameraInfo>[];
}
return filteredCameraInfoIds
.map<CameraInfo>((int? id) =>
instanceManager.getInstanceWithWeakReference(id!)! as CameraInfo)
.toList();
}
}
/// Flutter API implementation of [CameraSelector].
class CameraSelectorFlutterApiImpl implements CameraSelectorFlutterApi {
/// Constructs a [CameraSelectorFlutterApiImpl].
CameraSelectorFlutterApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void create(int identifier, int? lensFacing) {
instanceManager.addHostCreatedInstance(
CameraSelector.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
lensFacing: lensFacing),
identifier,
onCopy: (CameraSelector original) {
return CameraSelector.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
lensFacing: original.lensFacing);
},
);
}
}
| plugins/packages/camera/camera_android_camerax/lib/src/camera_selector.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/lib/src/camera_selector.dart",
"repo_id": "plugins",
"token_count": 2228
} | 1,139 |
// Mocks generated by Mockito 5.3.2 from annotations
// in camera_android_camerax/test/camera_selector_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 'test_camerax_library.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestCameraSelectorHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestCameraSelectorHostApi extends _i1.Mock
implements _i2.TestCameraSelectorHostApi {
MockTestCameraSelectorHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? lensFacing,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
lensFacing,
],
),
returnValueForMissingStub: null,
);
@override
List<int?> filter(
int? identifier,
List<int?>? cameraInfoIds,
) =>
(super.noSuchMethod(
Invocation.method(
#filter,
[
identifier,
cameraInfoIds,
],
),
returnValue: <int?>[],
) as List<int?>);
}
| plugins/packages/camera/camera_android_camerax/test/camera_selector_test.mocks.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/test/camera_selector_test.mocks.dart",
"repo_id": "plugins",
"token_count": 689
} | 1,140 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import camera_avfoundation;
@import camera_avfoundation.Test;
@import AVFoundation;
@import XCTest;
#import <OCMock/OCMock.h>
@interface FLTSavePhotoDelegateTests : XCTestCase
@end
@implementation FLTSavePhotoDelegateTests
- (void)testHandlePhotoCaptureResult_mustCompleteWithErrorIfFailedToCapture {
XCTestExpectation *completionExpectation =
[self expectationWithDescription:@"Must complete with error if failed to capture photo."];
NSError *captureError = [NSError errorWithDomain:@"test" code:0 userInfo:nil];
dispatch_queue_t ioQueue = dispatch_queue_create("test", NULL);
FLTSavePhotoDelegate *delegate = [[FLTSavePhotoDelegate alloc]
initWithPath:@"test"
ioQueue:ioQueue
completionHandler:^(NSString *_Nullable path, NSError *_Nullable error) {
XCTAssertEqualObjects(captureError, error);
XCTAssertNil(path);
[completionExpectation fulfill];
}];
[delegate handlePhotoCaptureResultWithError:captureError
photoDataProvider:^NSData * {
return nil;
}];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testHandlePhotoCaptureResult_mustCompleteWithErrorIfFailedToWrite {
XCTestExpectation *completionExpectation =
[self expectationWithDescription:@"Must complete with error if failed to write file."];
dispatch_queue_t ioQueue = dispatch_queue_create("test", NULL);
NSError *ioError = [NSError errorWithDomain:@"IOError"
code:0
userInfo:@{NSLocalizedDescriptionKey : @"Localized IO Error"}];
FLTSavePhotoDelegate *delegate = [[FLTSavePhotoDelegate alloc]
initWithPath:@"test"
ioQueue:ioQueue
completionHandler:^(NSString *_Nullable path, NSError *_Nullable error) {
XCTAssertEqualObjects(ioError, error);
XCTAssertNil(path);
[completionExpectation fulfill];
}];
// Do not use OCMClassMock for NSData because some XCTest APIs uses NSData (e.g.
// `XCTRunnerIDESession::logDebugMessage:`) on a private queue.
id mockData = OCMPartialMock([NSData data]);
OCMStub([mockData writeToFile:OCMOCK_ANY
options:NSDataWritingAtomic
error:[OCMArg setTo:ioError]])
.andReturn(NO);
[delegate handlePhotoCaptureResultWithError:nil
photoDataProvider:^NSData * {
return mockData;
}];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testHandlePhotoCaptureResult_mustCompleteWithFilePathIfSuccessToWrite {
XCTestExpectation *completionExpectation =
[self expectationWithDescription:@"Must complete with file path if success to write file."];
dispatch_queue_t ioQueue = dispatch_queue_create("test", NULL);
NSString *filePath = @"test";
FLTSavePhotoDelegate *delegate = [[FLTSavePhotoDelegate alloc]
initWithPath:filePath
ioQueue:ioQueue
completionHandler:^(NSString *_Nullable path, NSError *_Nullable error) {
XCTAssertNil(error);
XCTAssertEqualObjects(filePath, path);
[completionExpectation fulfill];
}];
// Do not use OCMClassMock for NSData because some XCTest APIs uses NSData (e.g.
// `XCTRunnerIDESession::logDebugMessage:`) on a private queue.
id mockData = OCMPartialMock([NSData data]);
OCMStub([mockData writeToFile:filePath options:NSDataWritingAtomic error:[OCMArg setTo:nil]])
.andReturn(YES);
[delegate handlePhotoCaptureResultWithError:nil
photoDataProvider:^NSData * {
return mockData;
}];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testHandlePhotoCaptureResult_bothProvideDataAndSaveFileMustRunOnIOQueue {
XCTestExpectation *dataProviderQueueExpectation =
[self expectationWithDescription:@"Data provider must run on io queue."];
XCTestExpectation *writeFileQueueExpectation =
[self expectationWithDescription:@"File writing must run on io queue"];
XCTestExpectation *completionExpectation =
[self expectationWithDescription:@"Must complete with file path if success to write file."];
dispatch_queue_t ioQueue = dispatch_queue_create("test", NULL);
const char *ioQueueSpecific = "io_queue_specific";
dispatch_queue_set_specific(ioQueue, ioQueueSpecific, (void *)ioQueueSpecific, NULL);
// Do not use OCMClassMock for NSData because some XCTest APIs uses NSData (e.g.
// `XCTRunnerIDESession::logDebugMessage:`) on a private queue.
id mockData = OCMPartialMock([NSData data]);
OCMStub([mockData writeToFile:OCMOCK_ANY options:NSDataWritingAtomic error:[OCMArg setTo:nil]])
.andDo(^(NSInvocation *invocation) {
if (dispatch_get_specific(ioQueueSpecific)) {
[writeFileQueueExpectation fulfill];
}
})
.andReturn(YES);
NSString *filePath = @"test";
FLTSavePhotoDelegate *delegate = [[FLTSavePhotoDelegate alloc]
initWithPath:filePath
ioQueue:ioQueue
completionHandler:^(NSString *_Nullable path, NSError *_Nullable error) {
[completionExpectation fulfill];
}];
[delegate handlePhotoCaptureResultWithError:nil
photoDataProvider:^NSData * {
if (dispatch_get_specific(ioQueueSpecific)) {
[dataProviderQueueExpectation fulfill];
}
return mockData;
}];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTSavePhotoDelegateTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTSavePhotoDelegateTests.m",
"repo_id": "plugins",
"token_count": 2452
} | 1,141 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Foundation;
#import <Flutter/Flutter.h>
typedef void (^FLTCameraPermissionRequestCompletionHandler)(FlutterError *);
/// Requests camera access permission.
///
/// If it is the first time requesting camera access, a permission dialog will show up on the
/// screen. Otherwise AVFoundation simply returns the user's previous choice, and in this case the
/// user will have to update the choice in Settings app.
///
/// @param handler if access permission is (or was previously) granted, completion handler will be
/// called without error; Otherwise completion handler will be called with error. Handler can be
/// called on an arbitrary dispatch queue.
extern void FLTRequestCameraPermissionWithCompletionHandler(
FLTCameraPermissionRequestCompletionHandler handler);
/// Requests audio access permission.
///
/// If it is the first time requesting audio access, a permission dialog will show up on the
/// screen. Otherwise AVFoundation simply returns the user's previous choice, and in this case the
/// user will have to update the choice in Settings app.
///
/// @param handler if access permission is (or was previously) granted, completion handler will be
/// called without error; Otherwise completion handler will be called with error. Handler can be
/// called on an arbitrary dispatch queue.
extern void FLTRequestAudioPermissionWithCompletionHandler(
FLTCameraPermissionRequestCompletionHandler handler);
| plugins/packages/camera/camera_avfoundation/ios/Classes/CameraPermissionUtils.h/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/CameraPermissionUtils.h",
"repo_id": "plugins",
"token_count": 370
} | 1,142 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
NS_ASSUME_NONNULL_BEGIN
/**
* A thread safe wrapper for FlutterResult that can be called from any thread, by dispatching its
* underlying engine calls to the main thread.
*/
@interface FLTThreadSafeFlutterResult : NSObject
/**
* Gets the original FlutterResult object wrapped by this FLTThreadSafeFlutterResult instance.
*/
@property(readonly, nonatomic) FlutterResult flutterResult;
/**
* Initializes with a FlutterResult object.
* @param result The FlutterResult object that the result will be given to.
*/
- (instancetype)initWithResult:(FlutterResult)result;
/**
* Sends a successful result on the main thread without any data.
*/
- (void)sendSuccess;
/**
* Sends a successful result on the main thread with data.
* @param data Result data that is send to the Flutter Dart side.
*/
- (void)sendSuccessWithData:(id)data;
/**
* Sends an NSError as result on the main thread.
* @param error Error that will be send as FlutterError.
*/
- (void)sendError:(NSError *)error;
/**
* Sends a FlutterError as result on the main thread.
* @param flutterError FlutterError that will be sent to the Flutter Dart side.
*/
- (void)sendFlutterError:(FlutterError *)flutterError;
/**
* Sends a FlutterError as result on the main thread.
*/
- (void)sendErrorWithCode:(NSString *)code
message:(nullable NSString *)message
details:(nullable id)details;
/**
* Sends FlutterMethodNotImplemented as result on the main thread.
*/
- (void)sendNotImplemented;
@end
NS_ASSUME_NONNULL_END
| plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeFlutterResult.h/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeFlutterResult.h",
"repo_id": "plugins",
"token_count": 535
} | 1,143 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// The possible exposure modes that can be set for a camera.
enum ExposureMode {
/// Automatically determine exposure settings.
auto,
/// Lock the currently determined exposure settings.
locked,
}
/// Returns the exposure mode as a String.
String serializeExposureMode(ExposureMode exposureMode) {
switch (exposureMode) {
case ExposureMode.locked:
return 'locked';
case ExposureMode.auto:
return 'auto';
}
}
/// Returns the exposure mode for a given String.
ExposureMode deserializeExposureMode(String str) {
switch (str) {
case 'locked':
return ExposureMode.locked;
case 'auto':
return ExposureMode.auto;
default:
throw ArgumentError('"$str" is not a valid ExposureMode value');
}
}
| plugins/packages/camera/camera_platform_interface/lib/src/types/exposure_mode.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/lib/src/types/exposure_mode.dart",
"repo_id": "plugins",
"token_count": 277
} | 1,144 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// 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:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('CameraImageData can be created', () {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
final CameraImageData cameraImage = CameraImageData(
format: const CameraImageFormat(ImageFormatGroup.jpeg, raw: 42),
height: 100,
width: 200,
lensAperture: 1.8,
sensorExposureTime: 11,
sensorSensitivity: 92.0,
planes: <CameraImagePlane>[
CameraImagePlane(
bytes: Uint8List.fromList(<int>[1, 2, 3, 4]),
bytesPerRow: 4,
bytesPerPixel: 2,
height: 100,
width: 200)
],
);
expect(cameraImage.format.group, ImageFormatGroup.jpeg);
expect(cameraImage.lensAperture, 1.8);
expect(cameraImage.sensorExposureTime, 11);
expect(cameraImage.sensorSensitivity, 92.0);
expect(cameraImage.height, 100);
expect(cameraImage.width, 200);
expect(cameraImage.planes.length, 1);
});
}
| plugins/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart",
"repo_id": "plugins",
"token_count": 538
} | 1,145 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html';
import 'dart:js_util' as js_util;
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#106316)
// ignore: unnecessary_import
import 'dart:ui';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_web/src/camera.dart';
import 'package:camera_web/src/camera_service.dart';
import 'package:camera_web/src/shims/dart_js_util.dart';
import 'package:camera_web/src/types/types.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:mocktail/mocktail.dart';
import 'helpers/helpers.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('CameraService', () {
const int cameraId = 1;
late Window window;
late Navigator navigator;
late MediaDevices mediaDevices;
late CameraService cameraService;
late JsUtil jsUtil;
setUp(() async {
window = MockWindow();
navigator = MockNavigator();
mediaDevices = MockMediaDevices();
jsUtil = MockJsUtil();
when(() => window.navigator).thenReturn(navigator);
when(() => navigator.mediaDevices).thenReturn(mediaDevices);
// Mock JsUtil to return the real getProperty from dart:js_util.
when<dynamic>(() => jsUtil.getProperty(any(), any())).thenAnswer(
(Invocation invocation) => js_util.getProperty<dynamic>(
invocation.positionalArguments[0] as Object,
invocation.positionalArguments[1] as Object,
),
);
cameraService = CameraService()..window = window;
});
group('getMediaStreamForOptions', () {
testWidgets(
'calls MediaDevices.getUserMedia '
'with provided options', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenAnswer((_) async => FakeMediaStream(<MediaStreamTrack>[]));
final CameraOptions options = CameraOptions(
video: VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.user),
width: const VideoSizeConstraint(ideal: 200),
),
);
await cameraService.getMediaStreamForOptions(options);
verify(
() => mediaDevices.getUserMedia(options.toJson()),
).called(1);
});
testWidgets(
'throws PlatformException '
'with notSupported error '
'when there are no media devices', (WidgetTester tester) async {
when(() => navigator.mediaDevices).thenReturn(null);
expect(
() => cameraService.getMediaStreamForOptions(const CameraOptions()),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notSupported.toString(),
),
),
);
});
group('throws CameraWebException', () {
testWidgets(
'with notFound error '
'when MediaDevices.getUserMedia throws DomException '
'with NotFoundError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('NotFoundError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.notFound),
),
);
});
testWidgets(
'with notFound error '
'when MediaDevices.getUserMedia throws DomException '
'with DevicesNotFoundError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('DevicesNotFoundError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.notFound),
),
);
});
testWidgets(
'with notReadable error '
'when MediaDevices.getUserMedia throws DomException '
'with NotReadableError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('NotReadableError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.notReadable),
),
);
});
testWidgets(
'with notReadable error '
'when MediaDevices.getUserMedia throws DomException '
'with TrackStartError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('TrackStartError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.notReadable),
),
);
});
testWidgets(
'with overconstrained error '
'when MediaDevices.getUserMedia throws DomException '
'with OverconstrainedError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('OverconstrainedError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.overconstrained),
),
);
});
testWidgets(
'with overconstrained error '
'when MediaDevices.getUserMedia throws DomException '
'with ConstraintNotSatisfiedError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('ConstraintNotSatisfiedError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.overconstrained),
),
);
});
testWidgets(
'with permissionDenied error '
'when MediaDevices.getUserMedia throws DomException '
'with NotAllowedError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('NotAllowedError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.permissionDenied),
),
);
});
testWidgets(
'with permissionDenied error '
'when MediaDevices.getUserMedia throws DomException '
'with PermissionDeniedError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('PermissionDeniedError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.permissionDenied),
),
);
});
testWidgets(
'with type error '
'when MediaDevices.getUserMedia throws DomException '
'with TypeError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('TypeError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.type),
),
);
});
testWidgets(
'with abort error '
'when MediaDevices.getUserMedia throws DomException '
'with AbortError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('AbortError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.abort),
),
);
});
testWidgets(
'with security error '
'when MediaDevices.getUserMedia throws DomException '
'with SecurityError', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('SecurityError'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.security),
),
);
});
testWidgets(
'with unknown error '
'when MediaDevices.getUserMedia throws DomException '
'with an unknown error', (WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any()))
.thenThrow(FakeDomException('Unknown'));
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.unknown),
),
);
});
testWidgets(
'with unknown error '
'when MediaDevices.getUserMedia throws an unknown exception',
(WidgetTester tester) async {
when(() => mediaDevices.getUserMedia(any())).thenThrow(Exception());
expect(
() => cameraService.getMediaStreamForOptions(
const CameraOptions(),
cameraId: cameraId,
),
throwsA(
isA<CameraWebException>()
.having((CameraWebException e) => e.cameraId, 'cameraId',
cameraId)
.having((CameraWebException e) => e.code, 'code',
CameraErrorCode.unknown),
),
);
});
});
});
group('getZoomLevelCapabilityForCamera', () {
late Camera camera;
late List<MediaStreamTrack> videoTracks;
setUp(() {
camera = MockCamera();
videoTracks = <MediaStreamTrack>[
MockMediaStreamTrack(),
MockMediaStreamTrack()
];
when(() => camera.textureId).thenReturn(0);
when(() => camera.stream).thenReturn(FakeMediaStream(videoTracks));
cameraService.jsUtil = jsUtil;
});
testWidgets(
'returns the zoom level capability '
'based on the first video track', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'zoom': true,
});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'zoom': js_util.jsify(<dynamic, dynamic>{
'min': 100,
'max': 400,
'step': 2,
}),
});
final ZoomLevelCapability zoomLevelCapability =
cameraService.getZoomLevelCapabilityForCamera(camera);
expect(zoomLevelCapability.minimum, equals(100.0));
expect(zoomLevelCapability.maximum, equals(400.0));
expect(zoomLevelCapability.videoTrack, equals(videoTracks.first));
});
group('throws CameraWebException', () {
testWidgets(
'with zoomLevelNotSupported error '
'when there are no media devices', (WidgetTester tester) async {
when(() => navigator.mediaDevices).thenReturn(null);
expect(
() => cameraService.getZoomLevelCapabilityForCamera(camera),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
camera.textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.zoomLevelNotSupported,
),
),
);
});
testWidgets(
'with zoomLevelNotSupported error '
'when the zoom level is not supported '
'in the browser', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'zoom': false,
});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'zoom': <dynamic, dynamic>{
'min': 100,
'max': 400,
'step': 2,
},
});
expect(
() => cameraService.getZoomLevelCapabilityForCamera(camera),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
camera.textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.zoomLevelNotSupported,
),
),
);
});
testWidgets(
'with zoomLevelNotSupported error '
'when the zoom level is not supported '
'by the camera', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'zoom': true,
});
when(videoTracks.first.getCapabilities)
.thenReturn(<dynamic, dynamic>{});
expect(
() => cameraService.getZoomLevelCapabilityForCamera(camera),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
camera.textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.zoomLevelNotSupported,
),
),
);
});
testWidgets(
'with notStarted error '
'when the camera stream has not been initialized',
(WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'zoom': true,
});
// Create a camera stream with no video tracks.
when(() => camera.stream)
.thenReturn(FakeMediaStream(<MediaStreamTrack>[]));
expect(
() => cameraService.getZoomLevelCapabilityForCamera(camera),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
camera.textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.notStarted,
),
),
);
});
});
});
group('getFacingModeForVideoTrack', () {
setUp(() {
cameraService.jsUtil = jsUtil;
});
testWidgets(
'throws PlatformException '
'with notSupported error '
'when there are no media devices', (WidgetTester tester) async {
when(() => navigator.mediaDevices).thenReturn(null);
expect(
() =>
cameraService.getFacingModeForVideoTrack(MockMediaStreamTrack()),
throwsA(
isA<PlatformException>().having(
(PlatformException e) => e.code,
'code',
CameraErrorCode.notSupported.toString(),
),
),
);
});
testWidgets(
'returns null '
'when the facing mode is not supported', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'facingMode': false,
});
final String? facingMode =
cameraService.getFacingModeForVideoTrack(MockMediaStreamTrack());
expect(facingMode, isNull);
});
group('when the facing mode is supported', () {
late MediaStreamTrack videoTrack;
setUp(() {
videoTrack = MockMediaStreamTrack();
when(() => jsUtil.hasProperty(videoTrack, 'getCapabilities'))
.thenReturn(true);
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'facingMode': true,
});
});
testWidgets(
'returns an appropriate facing mode '
'based on the video track settings', (WidgetTester tester) async {
when(videoTrack.getSettings)
.thenReturn(<dynamic, dynamic>{'facingMode': 'user'});
final String? facingMode =
cameraService.getFacingModeForVideoTrack(videoTrack);
expect(facingMode, equals('user'));
});
testWidgets(
'returns an appropriate facing mode '
'based on the video track capabilities '
'when the facing mode setting is empty',
(WidgetTester tester) async {
when(videoTrack.getSettings).thenReturn(<dynamic, dynamic>{});
when(videoTrack.getCapabilities).thenReturn(<dynamic, dynamic>{
'facingMode': <dynamic>['environment', 'left']
});
when(() => jsUtil.hasProperty(videoTrack, 'getCapabilities'))
.thenReturn(true);
final String? facingMode =
cameraService.getFacingModeForVideoTrack(videoTrack);
expect(facingMode, equals('environment'));
});
testWidgets(
'returns null '
'when the facing mode setting '
'and capabilities are empty', (WidgetTester tester) async {
when(videoTrack.getSettings).thenReturn(<dynamic, dynamic>{});
when(videoTrack.getCapabilities)
.thenReturn(<dynamic, dynamic>{'facingMode': <dynamic>[]});
final String? facingMode =
cameraService.getFacingModeForVideoTrack(videoTrack);
expect(facingMode, isNull);
});
testWidgets(
'returns null '
'when the facing mode setting is empty and '
'the video track capabilities are not supported',
(WidgetTester tester) async {
when(videoTrack.getSettings).thenReturn(<dynamic, dynamic>{});
when(() => jsUtil.hasProperty(videoTrack, 'getCapabilities'))
.thenReturn(false);
final String? facingMode =
cameraService.getFacingModeForVideoTrack(videoTrack);
expect(facingMode, isNull);
});
});
});
group('mapFacingModeToLensDirection', () {
testWidgets(
'returns front '
'when the facing mode is user', (WidgetTester tester) async {
expect(
cameraService.mapFacingModeToLensDirection('user'),
equals(CameraLensDirection.front),
);
});
testWidgets(
'returns back '
'when the facing mode is environment', (WidgetTester tester) async {
expect(
cameraService.mapFacingModeToLensDirection('environment'),
equals(CameraLensDirection.back),
);
});
testWidgets(
'returns external '
'when the facing mode is left', (WidgetTester tester) async {
expect(
cameraService.mapFacingModeToLensDirection('left'),
equals(CameraLensDirection.external),
);
});
testWidgets(
'returns external '
'when the facing mode is right', (WidgetTester tester) async {
expect(
cameraService.mapFacingModeToLensDirection('right'),
equals(CameraLensDirection.external),
);
});
});
group('mapFacingModeToCameraType', () {
testWidgets(
'returns user '
'when the facing mode is user', (WidgetTester tester) async {
expect(
cameraService.mapFacingModeToCameraType('user'),
equals(CameraType.user),
);
});
testWidgets(
'returns environment '
'when the facing mode is environment', (WidgetTester tester) async {
expect(
cameraService.mapFacingModeToCameraType('environment'),
equals(CameraType.environment),
);
});
testWidgets(
'returns user '
'when the facing mode is left', (WidgetTester tester) async {
expect(
cameraService.mapFacingModeToCameraType('left'),
equals(CameraType.user),
);
});
testWidgets(
'returns user '
'when the facing mode is right', (WidgetTester tester) async {
expect(
cameraService.mapFacingModeToCameraType('right'),
equals(CameraType.user),
);
});
});
group('mapResolutionPresetToSize', () {
testWidgets(
'returns 4096x2160 '
'when the resolution preset is max', (WidgetTester tester) async {
expect(
cameraService.mapResolutionPresetToSize(ResolutionPreset.max),
equals(const Size(4096, 2160)),
);
});
testWidgets(
'returns 4096x2160 '
'when the resolution preset is ultraHigh',
(WidgetTester tester) async {
expect(
cameraService.mapResolutionPresetToSize(ResolutionPreset.ultraHigh),
equals(const Size(4096, 2160)),
);
});
testWidgets(
'returns 1920x1080 '
'when the resolution preset is veryHigh',
(WidgetTester tester) async {
expect(
cameraService.mapResolutionPresetToSize(ResolutionPreset.veryHigh),
equals(const Size(1920, 1080)),
);
});
testWidgets(
'returns 1280x720 '
'when the resolution preset is high', (WidgetTester tester) async {
expect(
cameraService.mapResolutionPresetToSize(ResolutionPreset.high),
equals(const Size(1280, 720)),
);
});
testWidgets(
'returns 720x480 '
'when the resolution preset is medium', (WidgetTester tester) async {
expect(
cameraService.mapResolutionPresetToSize(ResolutionPreset.medium),
equals(const Size(720, 480)),
);
});
testWidgets(
'returns 320x240 '
'when the resolution preset is low', (WidgetTester tester) async {
expect(
cameraService.mapResolutionPresetToSize(ResolutionPreset.low),
equals(const Size(320, 240)),
);
});
});
group('mapDeviceOrientationToOrientationType', () {
testWidgets(
'returns portraitPrimary '
'when the device orientation is portraitUp',
(WidgetTester tester) async {
expect(
cameraService.mapDeviceOrientationToOrientationType(
DeviceOrientation.portraitUp,
),
equals(OrientationType.portraitPrimary),
);
});
testWidgets(
'returns landscapePrimary '
'when the device orientation is landscapeLeft',
(WidgetTester tester) async {
expect(
cameraService.mapDeviceOrientationToOrientationType(
DeviceOrientation.landscapeLeft,
),
equals(OrientationType.landscapePrimary),
);
});
testWidgets(
'returns portraitSecondary '
'when the device orientation is portraitDown',
(WidgetTester tester) async {
expect(
cameraService.mapDeviceOrientationToOrientationType(
DeviceOrientation.portraitDown,
),
equals(OrientationType.portraitSecondary),
);
});
testWidgets(
'returns landscapeSecondary '
'when the device orientation is landscapeRight',
(WidgetTester tester) async {
expect(
cameraService.mapDeviceOrientationToOrientationType(
DeviceOrientation.landscapeRight,
),
equals(OrientationType.landscapeSecondary),
);
});
});
group('mapOrientationTypeToDeviceOrientation', () {
testWidgets(
'returns portraitUp '
'when the orientation type is portraitPrimary',
(WidgetTester tester) async {
expect(
cameraService.mapOrientationTypeToDeviceOrientation(
OrientationType.portraitPrimary,
),
equals(DeviceOrientation.portraitUp),
);
});
testWidgets(
'returns landscapeLeft '
'when the orientation type is landscapePrimary',
(WidgetTester tester) async {
expect(
cameraService.mapOrientationTypeToDeviceOrientation(
OrientationType.landscapePrimary,
),
equals(DeviceOrientation.landscapeLeft),
);
});
testWidgets(
'returns portraitDown '
'when the orientation type is portraitSecondary',
(WidgetTester tester) async {
expect(
cameraService.mapOrientationTypeToDeviceOrientation(
OrientationType.portraitSecondary,
),
equals(DeviceOrientation.portraitDown),
);
});
testWidgets(
'returns portraitDown '
'when the orientation type is portraitSecondary',
(WidgetTester tester) async {
expect(
cameraService.mapOrientationTypeToDeviceOrientation(
OrientationType.portraitSecondary,
),
equals(DeviceOrientation.portraitDown),
);
});
testWidgets(
'returns landscapeRight '
'when the orientation type is landscapeSecondary',
(WidgetTester tester) async {
expect(
cameraService.mapOrientationTypeToDeviceOrientation(
OrientationType.landscapeSecondary,
),
equals(DeviceOrientation.landscapeRight),
);
});
testWidgets(
'returns portraitUp '
'for an unknown orientation type', (WidgetTester tester) async {
expect(
cameraService.mapOrientationTypeToDeviceOrientation(
'unknown',
),
equals(DeviceOrientation.portraitUp),
);
});
});
});
}
class JSNoSuchMethodError implements Exception {}
| plugins/packages/camera/camera_web/example/integration_test/camera_service_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/example/integration_test/camera_service_test.dart",
"repo_id": "plugins",
"token_count": 14752
} | 1,146 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:js_util' as js_util;
/// A utility that shims dart:js_util to manipulate JavaScript interop objects.
class JsUtil {
/// Returns true if the object [o] has the property [name].
bool hasProperty(Object o, Object name) => js_util.hasProperty(o, name);
/// Returns the value of the property [name] in the object [o].
dynamic getProperty(Object o, Object name) =>
js_util.getProperty<dynamic>(o, name);
}
| plugins/packages/camera/camera_web/lib/src/shims/dart_js_util.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/lib/src/shims/dart_js_util.dart",
"repo_id": "plugins",
"token_count": 178
} | 1,147 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "photo_handler.h"
#include <mfapi.h>
#include <mfcaptureengine.h>
#include <wincodec.h>
#include <cassert>
#include "capture_engine_listener.h"
#include "string_utils.h"
namespace camera_windows {
using Microsoft::WRL::ComPtr;
// Initializes media type for photo capture for jpeg images.
HRESULT BuildMediaTypeForPhotoCapture(IMFMediaType* src_media_type,
IMFMediaType** photo_media_type,
GUID image_format) {
assert(src_media_type);
ComPtr<IMFMediaType> new_media_type;
HRESULT hr = MFCreateMediaType(&new_media_type);
if (FAILED(hr)) {
return hr;
}
// Clones everything from original media type.
hr = src_media_type->CopyAllItems(new_media_type.Get());
if (FAILED(hr)) {
return hr;
}
hr = new_media_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Image);
if (FAILED(hr)) {
return hr;
}
hr = new_media_type->SetGUID(MF_MT_SUBTYPE, image_format);
if (FAILED(hr)) {
return hr;
}
new_media_type.CopyTo(photo_media_type);
return hr;
}
HRESULT PhotoHandler::InitPhotoSink(IMFCaptureEngine* capture_engine,
IMFMediaType* base_media_type) {
assert(capture_engine);
assert(base_media_type);
HRESULT hr = S_OK;
if (photo_sink_) {
// If photo sink already exists, only update output filename.
hr = photo_sink_->SetOutputFileName(Utf16FromUtf8(file_path_).c_str());
if (FAILED(hr)) {
photo_sink_ = nullptr;
}
return hr;
}
ComPtr<IMFMediaType> photo_media_type;
ComPtr<IMFCaptureSink> capture_sink;
// Get sink with photo type.
hr =
capture_engine->GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_PHOTO, &capture_sink);
if (FAILED(hr)) {
return hr;
}
hr = capture_sink.As(&photo_sink_);
if (FAILED(hr)) {
photo_sink_ = nullptr;
return hr;
}
hr = photo_sink_->RemoveAllStreams();
if (FAILED(hr)) {
photo_sink_ = nullptr;
return hr;
}
hr = BuildMediaTypeForPhotoCapture(base_media_type,
photo_media_type.GetAddressOf(),
GUID_ContainerFormatJpeg);
if (FAILED(hr)) {
photo_sink_ = nullptr;
return hr;
}
DWORD photo_sink_stream_index;
hr = photo_sink_->AddStream(
(DWORD)MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_PHOTO,
photo_media_type.Get(), nullptr, &photo_sink_stream_index);
if (FAILED(hr)) {
photo_sink_ = nullptr;
return hr;
}
hr = photo_sink_->SetOutputFileName(Utf16FromUtf8(file_path_).c_str());
if (FAILED(hr)) {
photo_sink_ = nullptr;
return hr;
}
return hr;
}
HRESULT PhotoHandler::TakePhoto(const std::string& file_path,
IMFCaptureEngine* capture_engine,
IMFMediaType* base_media_type) {
assert(!file_path.empty());
assert(capture_engine);
assert(base_media_type);
file_path_ = file_path;
HRESULT hr = InitPhotoSink(capture_engine, base_media_type);
if (FAILED(hr)) {
return hr;
}
photo_state_ = PhotoState::kTakingPhoto;
return capture_engine->TakePhoto();
}
void PhotoHandler::OnPhotoTaken() {
assert(photo_state_ == PhotoState::kTakingPhoto);
photo_state_ = PhotoState::kIdle;
}
} // namespace camera_windows
| plugins/packages/camera/camera_windows/windows/photo_handler.cpp/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/photo_handler.cpp",
"repo_id": "plugins",
"token_count": 1525
} | 1,148 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(tarrinneal): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
/// Page for showing an example of saving with file_selector
class SaveTextPage extends StatelessWidget {
/// Default Constructor
SaveTextPage({Key? key}) : super(key: key);
final bool _isIOS = !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS;
final TextEditingController _nameController = TextEditingController();
final TextEditingController _contentController = TextEditingController();
Future<void> _saveFile() async {
final String fileName = _nameController.text;
// This demonstrates using an initial directory for the prompt, which should
// only be done in cases where the application can likely predict where the
// file will be saved. In most cases, this parameter should not be provided.
final String initialDirectory =
(await getApplicationDocumentsDirectory()).path;
final String? path = await getSavePath(
initialDirectory: initialDirectory,
suggestedName: fileName,
);
if (path == null) {
// Operation was canceled by the user.
return;
}
final String text = _contentController.text;
final Uint8List fileData = Uint8List.fromList(text.codeUnits);
const String fileMimeType = 'text/plain';
final XFile textFile =
XFile.fromData(fileData, mimeType: fileMimeType, name: fileName);
await textFile.saveTo(path);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Save text into a file'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 300,
child: TextField(
minLines: 1,
maxLines: 12,
controller: _nameController,
decoration: const InputDecoration(
hintText: '(Optional) Suggest File Name',
),
),
),
SizedBox(
width: 300,
child: TextField(
minLines: 1,
maxLines: 12,
controller: _contentController,
decoration: const InputDecoration(
hintText: 'Enter File Contents',
),
),
),
const SizedBox(height: 10),
ElevatedButton(
style: ElevatedButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: Colors.blue,
// ignore: deprecated_member_use
onPrimary: Colors.white,
),
onPressed: _isIOS ? null : () => _saveFile(),
child: const Text(
'Press to save a text file (not supported on iOS).',
),
),
],
),
),
);
}
}
| plugins/packages/file_selector/file_selector/example/lib/save_text_page.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector/example/lib/save_text_page.dart",
"repo_id": "plugins",
"token_count": 1485
} | 1,149 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 0.9.0+2
* Changes XTypeGroup initialization from final to const.
## 0.9.0+1
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 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 web.
## 0.8.1+5
* Minor fixes for new analysis options.
## 0.8.1+4
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.8.1+3
* Minor code cleanup for new analysis rules.
* Removes dependency on `meta`.
## 0.8.1+2
* Add `implements` to pubspec.
# 0.8.1+1
- Updated installation instructions in README.
# 0.8.1
- Return a non-null value from `getSavePath` for consistency with
API expectations that null indicates canceling.
# 0.8.0
- Migrated to null-safety
# 0.7.0+1
- Add dummy `ios` dir, so flutter sdk can be lower than 1.20
# 0.7.0
- Initial open-source release.
| plugins/packages/file_selector/file_selector_web/CHANGELOG.md/0 | {
"file_path": "plugins/packages/file_selector/file_selector_web/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 409
} | 1,150 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
// 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/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:stream_transform/stream_transform.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late TestGoogleMapsFlutterPlatform platform;
setUp(() {
// Use a mock platform so we never need to hit the MethodChannel code.
platform = TestGoogleMapsFlutterPlatform();
GoogleMapsFlutterPlatform.instance = platform;
});
testWidgets('_webOnlyMapCreationId increments with each GoogleMap widget', (
WidgetTester tester,
) async {
// Inject two map widgets...
await tester.pumpWidget(
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
Directionality(
textDirection: TextDirection.ltr,
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
child: Column(
children: const <Widget>[
GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(43.362, -5.849),
),
),
GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(47.649, -122.350),
),
),
],
),
),
);
// Verify that each one was created with a different _webOnlyMapCreationId.
expect(platform.createdIds.length, 2);
expect(platform.createdIds[0], 0);
expect(platform.createdIds[1], 1);
});
testWidgets('Calls platform.dispose when GoogleMap is disposed of', (
WidgetTester tester,
) async {
await tester.pumpWidget(const GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(43.3608, -5.8702),
),
));
// Now dispose of the map...
await tester.pumpWidget(Container());
expect(platform.disposed, true);
});
}
// A dummy implementation of the platform interface for tests.
class TestGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform {
TestGoogleMapsFlutterPlatform();
// The IDs passed to each call to buildView, in call order.
List<int> createdIds = <int>[];
// Whether `dispose` has been called.
bool disposed = false;
// Stream controller to inject events for testing.
final StreamController<MapEvent<dynamic>> mapEventStreamController =
StreamController<MapEvent<dynamic>>.broadcast();
@override
Future<void> init(int mapId) async {}
@override
Future<void> updateMapConfiguration(
MapConfiguration update, {
required int mapId,
}) async {}
@override
Future<void> updateMarkers(
MarkerUpdates markerUpdates, {
required int mapId,
}) async {}
@override
Future<void> updatePolygons(
PolygonUpdates polygonUpdates, {
required int mapId,
}) async {}
@override
Future<void> updatePolylines(
PolylineUpdates polylineUpdates, {
required int mapId,
}) async {}
@override
Future<void> updateCircles(
CircleUpdates circleUpdates, {
required int mapId,
}) async {}
@override
Future<void> updateTileOverlays({
required Set<TileOverlay> newTileOverlays,
required int mapId,
}) async {}
@override
Future<void> clearTileCache(
TileOverlayId tileOverlayId, {
required int mapId,
}) async {}
@override
Future<void> animateCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) async {}
@override
Future<void> moveCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) async {}
@override
Future<void> setMapStyle(
String? mapStyle, {
required int mapId,
}) async {}
@override
Future<LatLngBounds> getVisibleRegion({
required int mapId,
}) async {
return LatLngBounds(
southwest: const LatLng(0, 0), northeast: const LatLng(0, 0));
}
@override
Future<ScreenCoordinate> getScreenCoordinate(
LatLng latLng, {
required int mapId,
}) async {
return const ScreenCoordinate(x: 0, y: 0);
}
@override
Future<LatLng> getLatLng(
ScreenCoordinate screenCoordinate, {
required int mapId,
}) async {
return const LatLng(0, 0);
}
@override
Future<void> showMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) async {}
@override
Future<void> hideMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) async {}
@override
Future<bool> isMarkerInfoWindowShown(
MarkerId markerId, {
required int mapId,
}) async {
return false;
}
@override
Future<double> getZoomLevel({
required int mapId,
}) async {
return 0.0;
}
@override
Future<Uint8List?> takeSnapshot({
required int mapId,
}) async {
return null;
}
@override
Stream<CameraMoveStartedEvent> onCameraMoveStarted({required int mapId}) {
return mapEventStreamController.stream.whereType<CameraMoveStartedEvent>();
}
@override
Stream<CameraMoveEvent> onCameraMove({required int mapId}) {
return mapEventStreamController.stream.whereType<CameraMoveEvent>();
}
@override
Stream<CameraIdleEvent> onCameraIdle({required int mapId}) {
return mapEventStreamController.stream.whereType<CameraIdleEvent>();
}
@override
Stream<MarkerTapEvent> onMarkerTap({required int mapId}) {
return mapEventStreamController.stream.whereType<MarkerTapEvent>();
}
@override
Stream<InfoWindowTapEvent> onInfoWindowTap({required int mapId}) {
return mapEventStreamController.stream.whereType<InfoWindowTapEvent>();
}
@override
Stream<MarkerDragStartEvent> onMarkerDragStart({required int mapId}) {
return mapEventStreamController.stream.whereType<MarkerDragStartEvent>();
}
@override
Stream<MarkerDragEvent> onMarkerDrag({required int mapId}) {
return mapEventStreamController.stream.whereType<MarkerDragEvent>();
}
@override
Stream<MarkerDragEndEvent> onMarkerDragEnd({required int mapId}) {
return mapEventStreamController.stream.whereType<MarkerDragEndEvent>();
}
@override
Stream<PolylineTapEvent> onPolylineTap({required int mapId}) {
return mapEventStreamController.stream.whereType<PolylineTapEvent>();
}
@override
Stream<PolygonTapEvent> onPolygonTap({required int mapId}) {
return mapEventStreamController.stream.whereType<PolygonTapEvent>();
}
@override
Stream<CircleTapEvent> onCircleTap({required int mapId}) {
return mapEventStreamController.stream.whereType<CircleTapEvent>();
}
@override
Stream<MapTapEvent> onTap({required int mapId}) {
return mapEventStreamController.stream.whereType<MapTapEvent>();
}
@override
Stream<MapLongPressEvent> onLongPress({required int mapId}) {
return mapEventStreamController.stream.whereType<MapLongPressEvent>();
}
@override
void dispose({required int mapId}) {
disposed = true;
}
@override
Widget buildViewWithConfiguration(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required MapWidgetConfiguration widgetConfiguration,
MapObjects mapObjects = const MapObjects(),
MapConfiguration mapConfiguration = const MapConfiguration(),
}) {
onPlatformViewCreated(0);
createdIds.add(creationId);
return Container();
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter/test/map_creation_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/test/map_creation_test.dart",
"repo_id": "plugins",
"token_count": 2734
} | 1,151 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import CoreLocation;
@import XCTest;
@import os.log;
@interface GoogleMapsUITests : XCTestCase
@property(nonatomic, strong) XCUIApplication *app;
@end
@implementation GoogleMapsUITests
- (void)setUp {
self.continueAfterFailure = NO;
self.app = [[XCUIApplication alloc] init];
[self.app launch];
[self
addUIInterruptionMonitorWithDescription:@"Permission popups"
handler:^BOOL(XCUIElement *_Nonnull interruptingElement) {
if (@available(iOS 14, *)) {
XCUIElement *locationPermission =
interruptingElement.buttons[@"Allow While Using App"];
if (![locationPermission
waitForExistenceWithTimeout:30.0]) {
XCTFail(@"Failed due to not able to find "
@"locationPermission button");
}
[locationPermission tap];
} else {
XCUIElement *allow =
interruptingElement.buttons[@"Allow"];
if (![allow waitForExistenceWithTimeout:30.0]) {
XCTFail(@"Failed due to not able to find Allow button");
}
[allow tap];
}
return YES;
}];
}
- (void)testUserInterface {
XCUIApplication *app = self.app;
XCUIElement *userInteface = app.staticTexts[@"User interface"];
if (![userInteface waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find User interface");
}
[userInteface tap];
XCUIElement *platformView = app.otherElements[@"platform_view[0]"];
if (![platformView waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find platform view");
}
// There is a known bug where the permission popups interruption won't get fired until a tap
// happened in the app. We expect a permission popup so we do a tap here.
// iOS 16 has a bug where if the app itself is directly tapped: [app tap], the first button
// (disable compass) in the app is also tapped, so instead we tap a arbitrary location in the app
// instead.
XCUICoordinate *coordinate = [app coordinateWithNormalizedOffset:CGVectorMake(0, 0)];
[coordinate tap];
XCUIElement *compass = app.buttons[@"disable compass"];
if (![compass waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find disable compass button");
}
[self forceTap:compass];
}
- (void)testMapCoordinatesPage {
XCUIApplication *app = self.app;
XCUIElement *mapCoordinates = app.staticTexts[@"Map coordinates"];
if (![mapCoordinates waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find 'Map coordinates''");
}
[mapCoordinates tap];
XCUIElement *platformView = app.otherElements[@"platform_view[0]"];
if (![platformView waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find platform view");
}
XCUIElement *titleBar = app.otherElements[@"Map coordinates"];
if (![titleBar waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find title bar");
}
NSPredicate *visibleRegionPredicate =
[NSPredicate predicateWithFormat:@"label BEGINSWITH 'VisibleRegion'"];
XCUIElement *visibleRegionText =
[app.staticTexts elementMatchingPredicate:visibleRegionPredicate];
if (![visibleRegionText waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find Visible Region label'");
}
// Validate visible region does not change when scrolled under safe areas.
// https://github.com/flutter/flutter/issues/107913
// Example -33.79495661816674, 151.313996873796
CLLocationCoordinate2D originalNortheast;
// Example -33.90900557679571, 151.10800322145224
CLLocationCoordinate2D originalSouthwest;
[self validateVisibleRegion:visibleRegionText.label
northeast:&originalNortheast
southwest:&originalSouthwest];
XCTAssertGreaterThan(originalNortheast.latitude, originalSouthwest.latitude);
XCTAssertGreaterThan(originalNortheast.longitude, originalSouthwest.longitude);
XCTAssertLessThan(originalNortheast.latitude, 0);
XCTAssertLessThan(originalSouthwest.latitude, 0);
XCTAssertGreaterThan(originalNortheast.longitude, 0);
XCTAssertGreaterThan(originalSouthwest.longitude, 0);
// Drag the map upward to under the title bar.
[platformView pressForDuration:0 thenDragToElement:titleBar];
CLLocationCoordinate2D draggedNortheast;
CLLocationCoordinate2D draggedSouthwest;
[self validateVisibleRegion:visibleRegionText.label
northeast:&draggedNortheast
southwest:&draggedSouthwest];
XCTAssertEqual(originalNortheast.latitude, draggedNortheast.latitude);
XCTAssertEqual(originalNortheast.longitude, draggedNortheast.longitude);
XCTAssertEqual(originalSouthwest.latitude, draggedSouthwest.latitude);
XCTAssertEqual(originalSouthwest.latitude, draggedSouthwest.latitude);
}
- (void)validateVisibleRegion:(NSString *)label
northeast:(CLLocationCoordinate2D *)northeast
southwest:(CLLocationCoordinate2D *)southwest {
// String will be "VisibleRegion:\nnortheast: LatLng(-33.79495661816674,
// 151.313996873796),\nsouthwest: LatLng(-33.90900557679571, 151.10800322145224)"
NSScanner *scan = [NSScanner scannerWithString:label];
// northeast
[scan scanString:@"VisibleRegion:\nnortheast: LatLng(" intoString:NULL];
double northeastLatitude;
[scan scanDouble:&northeastLatitude];
[scan scanString:@", " intoString:NULL];
XCTAssertNotEqual(northeastLatitude, 0);
double northeastLongitude;
[scan scanDouble:&northeastLongitude];
XCTAssertNotEqual(northeastLongitude, 0);
[scan scanString:@"),\nsouthwest: LatLng(" intoString:NULL];
double southwestLatitude;
[scan scanDouble:&southwestLatitude];
XCTAssertNotEqual(southwestLatitude, 0);
[scan scanString:@", " intoString:NULL];
double southwestLongitude;
[scan scanDouble:&southwestLongitude];
XCTAssertNotEqual(southwestLongitude, 0);
*northeast = CLLocationCoordinate2DMake(northeastLatitude, northeastLongitude);
*southwest = CLLocationCoordinate2DMake(southwestLatitude, southwestLongitude);
}
- (void)testMapClickPage {
XCUIApplication *app = self.app;
XCUIElement *mapClick = app.staticTexts[@"Map click"];
if (![mapClick waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find 'Map click''");
}
[mapClick tap];
XCUIElement *platformView = app.otherElements[@"platform_view[0]"];
if (![platformView waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find platform view");
}
[platformView tap];
XCUIElement *tapped = app.staticTexts[@"Tapped"];
if (![tapped waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find 'tapped''");
}
[platformView pressForDuration:5.0];
XCUIElement *longPressed = app.staticTexts[@"Long pressed"];
if (![longPressed waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find 'longPressed''");
}
}
- (void)forceTap:(XCUIElement *)button {
// iOS 16 introduced a bug where hittable is NO for buttons. We force hit the location of the
// button if that is the case. It is likely similar to
// https://github.com/flutter/flutter/issues/113377.
if (button.isHittable) {
[button tap];
return;
}
XCUICoordinate *coordinate = [button coordinateWithNormalizedOffset:CGVectorMake(0, 0)];
[coordinate tap];
}
@end
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/example/ios/RunnerUITests/GoogleMapsUITests.m/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/example/ios/RunnerUITests/GoogleMapsUITests.m",
"repo_id": "plugins",
"token_count": 3672
} | 1,152 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs, avoid_print
import 'dart:async';
import 'dart:convert' show json;
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:http/http.dart' as http;
GoogleSignIn _googleSignIn = GoogleSignIn(
// Optional clientId
// clientId: '479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com',
scopes: <String>[
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
void main() {
runApp(
const MaterialApp(
title: 'Google Sign In',
home: SignInDemo(),
),
);
}
class SignInDemo extends StatefulWidget {
const SignInDemo({Key? key}) : super(key: key);
@override
State createState() => SignInDemoState();
}
class SignInDemoState extends State<SignInDemo> {
GoogleSignInAccount? _currentUser;
String _contactText = '';
@override
void initState() {
super.initState();
_googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account) {
setState(() {
_currentUser = account;
});
if (_currentUser != null) {
_handleGetContact(_currentUser!);
}
});
_googleSignIn.signInSilently();
}
Future<void> _handleGetContact(GoogleSignInAccount user) async {
setState(() {
_contactText = 'Loading contact info...';
});
final http.Response response = await http.get(
Uri.parse('https://people.googleapis.com/v1/people/me/connections'
'?requestMask.includeField=person.names'),
headers: await user.authHeaders,
);
if (response.statusCode != 200) {
setState(() {
_contactText = 'People API gave a ${response.statusCode} '
'response. Check logs for details.';
});
print('People API ${response.statusCode} response: ${response.body}');
return;
}
final Map<String, dynamic> data =
json.decode(response.body) as Map<String, dynamic>;
final String? namedContact = _pickFirstNamedContact(data);
setState(() {
if (namedContact != null) {
_contactText = 'I see you know $namedContact!';
} else {
_contactText = 'No contacts to display.';
}
});
}
String? _pickFirstNamedContact(Map<String, dynamic> data) {
final List<dynamic>? connections = data['connections'] as List<dynamic>?;
final Map<String, dynamic>? contact = connections?.firstWhere(
(dynamic contact) => (contact as Map<Object?, dynamic>)['names'] != null,
orElse: () => null,
) as Map<String, dynamic>?;
if (contact != null) {
final List<dynamic> names = contact['names'] as List<dynamic>;
final Map<String, dynamic>? name = names.firstWhere(
(dynamic name) =>
(name as Map<Object?, dynamic>)['displayName'] != null,
orElse: () => null,
) as Map<String, dynamic>?;
if (name != null) {
return name['displayName'] as String?;
}
}
return null;
}
Future<void> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print(error);
}
}
Future<void> _handleSignOut() => _googleSignIn.disconnect();
Widget _buildBody() {
final GoogleSignInAccount? user = _currentUser;
if (user != null) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ListTile(
leading: GoogleUserCircleAvatar(
identity: user,
),
title: Text(user.displayName ?? ''),
subtitle: Text(user.email),
),
const Text('Signed in successfully.'),
Text(_contactText),
ElevatedButton(
onPressed: _handleSignOut,
child: const Text('SIGN OUT'),
),
ElevatedButton(
child: const Text('REFRESH'),
onPressed: () => _handleGetContact(user),
),
],
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
const Text('You are not currently signed in.'),
ElevatedButton(
onPressed: _handleSignIn,
child: const Text('SIGN IN'),
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Google Sign In'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: _buildBody(),
));
}
}
| plugins/packages/google_sign_in/google_sign_in/example/lib/main.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 1986
} | 1,153 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:html' as html;
import 'package:flutter/foundation.dart' show visibleForTesting, kDebugMode;
import 'package:flutter/services.dart' show PlatformException;
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:google_identity_services_web/loader.dart' as loader;
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'src/gis_client.dart';
/// The `name` of the meta-tag to define a ClientID in HTML.
const String clientIdMetaName = 'google-signin-client_id';
/// The selector used to find the meta-tag that defines a ClientID in HTML.
const String clientIdMetaSelector = 'meta[name=$clientIdMetaName]';
/// The attribute name that stores the Client ID in the meta-tag that defines a Client ID in HTML.
const String clientIdAttributeName = 'content';
/// Implementation of the google_sign_in plugin for Web.
class GoogleSignInPlugin extends GoogleSignInPlatform {
/// Constructs the plugin immediately and begins initializing it in the
/// background.
///
/// The plugin is completely initialized when [initialized] completed.
GoogleSignInPlugin({@visibleForTesting bool debugOverrideLoader = false}) {
autoDetectedClientId = html
.querySelector(clientIdMetaSelector)
?.getAttribute(clientIdAttributeName);
if (debugOverrideLoader) {
_jsSdkLoadedFuture = Future<bool>.value(true);
} else {
_jsSdkLoadedFuture = loader.loadWebSdk();
}
}
late Future<void> _jsSdkLoadedFuture;
bool _isInitCalled = false;
// The instance of [GisSdkClient] backing the plugin.
late GisSdkClient _gisClient;
// This method throws if init or initWithParams hasn't been called at some
// point in the past. It is used by the [initialized] getter to ensure that
// users can't await on a Future that will never resolve.
void _assertIsInitCalled() {
if (!_isInitCalled) {
throw StateError(
'GoogleSignInPlugin::init() or GoogleSignInPlugin::initWithParams() '
'must be called before any other method in this plugin.',
);
}
}
/// A future that resolves when the SDK has been correctly loaded.
@visibleForTesting
Future<void> get initialized {
_assertIsInitCalled();
return _jsSdkLoadedFuture;
}
/// Stores the client ID if it was set in a meta-tag of the page.
@visibleForTesting
late String? autoDetectedClientId;
/// Factory method that initializes the plugin with [GoogleSignInPlatform].
static void registerWith(Registrar registrar) {
GoogleSignInPlatform.instance = GoogleSignInPlugin();
}
@override
Future<void> init({
List<String> scopes = const <String>[],
SignInOption signInOption = SignInOption.standard,
String? hostedDomain,
String? clientId,
}) {
return initWithParams(SignInInitParameters(
scopes: scopes,
signInOption: signInOption,
hostedDomain: hostedDomain,
clientId: clientId,
));
}
@override
Future<void> initWithParams(
SignInInitParameters params, {
@visibleForTesting GisSdkClient? overrideClient,
}) async {
final String? appClientId = params.clientId ?? autoDetectedClientId;
assert(
appClientId != null,
'ClientID not set. Either set it on a '
'<meta name="google-signin-client_id" content="CLIENT_ID" /> tag,'
' or pass clientId when initializing GoogleSignIn');
assert(params.serverClientId == null,
'serverClientId is not supported on Web.');
assert(
!params.scopes.any((String scope) => scope.contains(' ')),
"OAuth 2.0 Scopes for Google APIs can't contain spaces. "
'Check https://developers.google.com/identity/protocols/googlescopes '
'for a list of valid OAuth 2.0 scopes.');
await _jsSdkLoadedFuture;
_gisClient = overrideClient ??
GisSdkClient(
clientId: appClientId!,
hostedDomain: params.hostedDomain,
initialScopes: List<String>.from(params.scopes),
loggingEnabled: kDebugMode,
);
_isInitCalled = true;
}
@override
Future<GoogleSignInUserData?> signInSilently() async {
await initialized;
// Since the new GIS SDK does *not* perform authorization at the same time as
// authentication (and every one of our users expects that), we need to tell
// the plugin that this failed regardless of the actual result.
//
// However, if this succeeds, we'll save a People API request later.
return _gisClient.signInSilently().then((_) => null);
}
@override
Future<GoogleSignInUserData?> signIn() async {
await initialized;
// This method mainly does oauth2 authorization, which happens to also do
// authentication if needed. However, the authentication information is not
// returned anymore.
//
// This method will synthesize authentication information from the People API
// if needed (or use the last identity seen from signInSilently).
try {
return _gisClient.signIn();
} catch (reason) {
throw PlatformException(
code: reason.toString(),
message: 'Exception raised from signIn',
details:
'https://developers.google.com/identity/oauth2/web/guides/error',
);
}
}
@override
Future<GoogleSignInTokenData> getTokens({
required String email,
bool? shouldRecoverAuth,
}) async {
await initialized;
return _gisClient.getTokens();
}
@override
Future<void> signOut() async {
await initialized;
_gisClient.signOut();
}
@override
Future<void> disconnect() async {
await initialized;
_gisClient.disconnect();
}
@override
Future<bool> isSignedIn() async {
await initialized;
return _gisClient.isSignedIn();
}
@override
Future<void> clearAuthCache({required String token}) async {
await initialized;
_gisClient.clearAuthCache();
}
@override
Future<bool> requestScopes(List<String> scopes) async {
await initialized;
return _gisClient.requestScopes(scopes);
}
}
| plugins/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart",
"repo_id": "plugins",
"token_count": 2109
} | 1,154 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.imagepickerexample">
<!-- Flutter needs internet permission to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:usesCleartextTraffic="true">
<activity
android:name=".ImagePickerTestActivity"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
</activity>
</application>
</manifest>
| plugins/packages/image_picker/image_picker/example/android/app/src/debug/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/image_picker/image_picker/example/android/app/src/debug/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 329
} | 1,155 |
// Mocks generated by Mockito 5.1.0 from annotations
// in image_picker/test/image_picker_test.dart.
// Do not manually edit this file.
import 'dart:async' as _i4;
import 'package:cross_file/cross_file.dart' as _i5;
import 'package:image_picker_platform_interface/src/platform_interface/image_picker_platform.dart'
as _i3;
import 'package:image_picker_platform_interface/src/types/types.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: 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
class _FakeLostData_0 extends _i1.Fake implements _i2.LostData {}
class _FakeLostDataResponse_1 extends _i1.Fake
implements _i2.LostDataResponse {}
/// A class which mocks [ImagePickerPlatform].
///
/// See the documentation for Mockito's code generation for more information.
class MockImagePickerPlatform extends _i1.Mock
implements _i3.ImagePickerPlatform {
MockImagePickerPlatform() {
_i1.throwOnMissingStub(this);
}
@override
_i4.Future<_i2.PickedFile?> pickImage(
{_i2.ImageSource? source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
_i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear}) =>
(super.noSuchMethod(
Invocation.method(#pickImage, [], {
#source: source,
#maxWidth: maxWidth,
#maxHeight: maxHeight,
#imageQuality: imageQuality,
#preferredCameraDevice: preferredCameraDevice
}),
returnValue: Future<_i2.PickedFile?>.value())
as _i4.Future<_i2.PickedFile?>);
@override
_i4.Future<List<_i2.PickedFile>?> pickMultiImage(
{double? maxWidth, double? maxHeight, int? imageQuality}) =>
(super.noSuchMethod(
Invocation.method(#pickMultiImage, [], {
#maxWidth: maxWidth,
#maxHeight: maxHeight,
#imageQuality: imageQuality
}),
returnValue: Future<List<_i2.PickedFile>?>.value())
as _i4.Future<List<_i2.PickedFile>?>);
@override
_i4.Future<_i2.PickedFile?> pickVideo(
{_i2.ImageSource? source,
_i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear,
Duration? maxDuration}) =>
(super.noSuchMethod(
Invocation.method(#pickVideo, [], {
#source: source,
#preferredCameraDevice: preferredCameraDevice,
#maxDuration: maxDuration
}),
returnValue: Future<_i2.PickedFile?>.value())
as _i4.Future<_i2.PickedFile?>);
@override
_i4.Future<_i2.LostData> retrieveLostData() =>
(super.noSuchMethod(Invocation.method(#retrieveLostData, []),
returnValue: Future<_i2.LostData>.value(_FakeLostData_0()))
as _i4.Future<_i2.LostData>);
@override
_i4.Future<_i5.XFile?> getImage(
{_i2.ImageSource? source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
_i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear}) =>
(super.noSuchMethod(
Invocation.method(#getImage, [], {
#source: source,
#maxWidth: maxWidth,
#maxHeight: maxHeight,
#imageQuality: imageQuality,
#preferredCameraDevice: preferredCameraDevice
}),
returnValue: Future<_i5.XFile?>.value()) as _i4.Future<_i5.XFile?>);
@override
_i4.Future<List<_i5.XFile>?> getMultiImage(
{double? maxWidth, double? maxHeight, int? imageQuality}) =>
(super.noSuchMethod(
Invocation.method(#getMultiImage, [], {
#maxWidth: maxWidth,
#maxHeight: maxHeight,
#imageQuality: imageQuality
}),
returnValue: Future<List<_i5.XFile>?>.value())
as _i4.Future<List<_i5.XFile>?>);
@override
_i4.Future<_i5.XFile?> getVideo(
{_i2.ImageSource? source,
_i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear,
Duration? maxDuration}) =>
(super.noSuchMethod(
Invocation.method(#getVideo, [], {
#source: source,
#preferredCameraDevice: preferredCameraDevice,
#maxDuration: maxDuration
}),
returnValue: Future<_i5.XFile?>.value()) as _i4.Future<_i5.XFile?>);
@override
_i4.Future<_i2.LostDataResponse> getLostData() =>
(super.noSuchMethod(Invocation.method(#getLostData, []),
returnValue:
Future<_i2.LostDataResponse>.value(_FakeLostDataResponse_1()))
as _i4.Future<_i2.LostDataResponse>);
@override
_i4.Future<_i5.XFile?> getImageFromSource(
{_i2.ImageSource? source,
_i2.ImagePickerOptions? options = const _i2.ImagePickerOptions()}) =>
(super.noSuchMethod(
Invocation.method(
#getImageFromSource, [], {#source: source, #options: options}),
returnValue: Future<_i5.XFile?>.value()) as _i4.Future<_i5.XFile?>);
@override
_i4.Future<List<_i5.XFile>> getMultiImageWithOptions(
{_i2.MultiImagePickerOptions? options =
const _i2.MultiImagePickerOptions()}) =>
(super.noSuchMethod(
Invocation.method(#getMultiImageWithOptions, [], {#options: options}),
returnValue:
Future<List<_i5.XFile>>.value(<_i5.XFile>[])) as _i4
.Future<List<_i5.XFile>>);
}
| plugins/packages/image_picker/image_picker/test/image_picker_test.mocks.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker/test/image_picker_test.mocks.dart",
"repo_id": "plugins",
"token_count": 2711
} | 1,156 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.imagepickerexample">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="Image Picker Example" android:icon="@mipmap/ic_launcher">
<activity android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="flutterEmbedding" android:value="2"/>
</application>
</manifest>
| plugins/packages/image_picker/image_picker_android/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 406
} | 1,157 |
name: image_picker_ios
description: iOS implementation of the image_picker plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/image_picker/image_picker_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22
version: 0.8.6+8
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: image_picker
platforms:
ios:
dartPluginClass: ImagePickerIOS
pluginClass: FLTImagePickerPlugin
dependencies:
flutter:
sdk: flutter
image_picker_platform_interface: ^2.6.1
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.0
pigeon: ^3.0.2
| plugins/packages/image_picker/image_picker_ios/pubspec.yaml/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/pubspec.yaml",
"repo_id": "plugins",
"token_count": 302
} | 1,158 |
# image\_picker\_windows
A Windows implementation of [`image_picker`][1].
### pickImage()
The arguments `source`, `maxWidth`, `maxHeight`, `imageQuality`, and `preferredCameraDevice` are not supported on Windows.
### pickVideo()
The arguments `source`, `preferredCameraDevice`, and `maxDuration` are not supported on Windows.
## Usage
### Import the package
This package is not yet [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin), which means you need to add
not only the `image_picker`, as well as the `image_picker_windows`. | plugins/packages/image_picker/image_picker_windows/README.md/0 | {
"file_path": "plugins/packages/image_picker/image_picker_windows/README.md",
"repo_id": "plugins",
"token_count": 174
} | 1,159 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.inapppurchase;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.ACKNOWLEDGE_PURCHASE;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.CONSUME_PURCHASE_ASYNC;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.END_CONNECTION;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.IS_FEATURE_SUPPORTED;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.IS_READY;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.LAUNCH_BILLING_FLOW;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.LAUNCH_PRICE_CHANGE_CONFIRMATION_FLOW;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.ON_DISCONNECT;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.ON_PURCHASES_UPDATED;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.QUERY_PURCHASES_ASYNC;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.QUERY_PURCHASE_HISTORY_ASYNC;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.QUERY_SKU_DETAILS;
import static io.flutter.plugins.inapppurchase.InAppPurchasePlugin.MethodNames.START_CONNECTION;
import static io.flutter.plugins.inapppurchase.Translator.fromBillingResult;
import static io.flutter.plugins.inapppurchase.Translator.fromPurchaseHistoryRecordList;
import static io.flutter.plugins.inapppurchase.Translator.fromPurchasesList;
import static io.flutter.plugins.inapppurchase.Translator.fromSkuDetailsList;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.refEq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
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.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClient.SkuType;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.PriceChangeConfirmationListener;
import com.android.billingclient.api.PriceChangeFlowParams;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.PurchaseHistoryResponseListener;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.QueryPurchaseHistoryParams;
import com.android.billingclient.api.QueryPurchasesParams;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class MethodCallHandlerTest {
private MethodCallHandlerImpl methodChannelHandler;
private BillingClientFactory factory;
@Mock BillingClient mockBillingClient;
@Mock MethodChannel mockMethodChannel;
@Spy Result result;
@Mock Activity activity;
@Mock Context context;
@Mock ActivityPluginBinding mockActivityPluginBinding;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
factory = (@NonNull Context context, @NonNull MethodChannel channel) -> mockBillingClient;
methodChannelHandler = new MethodCallHandlerImpl(activity, context, mockMethodChannel, factory);
when(mockActivityPluginBinding.getActivity()).thenReturn(activity);
}
@Test
public void invalidMethod() {
MethodCall call = new MethodCall("invalid", null);
methodChannelHandler.onMethodCall(call, result);
verify(result, times(1)).notImplemented();
}
@Test
public void isReady_true() {
mockStartConnection();
MethodCall call = new MethodCall(IS_READY, null);
when(mockBillingClient.isReady()).thenReturn(true);
methodChannelHandler.onMethodCall(call, result);
verify(result).success(true);
}
@Test
public void isReady_false() {
mockStartConnection();
MethodCall call = new MethodCall(IS_READY, null);
when(mockBillingClient.isReady()).thenReturn(false);
methodChannelHandler.onMethodCall(call, result);
verify(result).success(false);
}
@Test
public void isReady_clientDisconnected() {
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, mock(Result.class));
MethodCall isReadyCall = new MethodCall(IS_READY, null);
methodChannelHandler.onMethodCall(isReadyCall, result);
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
@Test
public void startConnection() {
ArgumentCaptor<BillingClientStateListener> captor = mockStartConnection();
verify(result, never()).success(any());
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
captor.getValue().onBillingSetupFinished(billingResult);
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void startConnection_multipleCalls() {
Map<String, Object> arguments = new HashMap<>();
arguments.put("handle", 1);
MethodCall call = new MethodCall(START_CONNECTION, arguments);
ArgumentCaptor<BillingClientStateListener> captor =
ArgumentCaptor.forClass(BillingClientStateListener.class);
doNothing().when(mockBillingClient).startConnection(captor.capture());
methodChannelHandler.onMethodCall(call, result);
verify(result, never()).success(any());
BillingResult billingResult1 =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
BillingResult billingResult2 =
BillingResult.newBuilder()
.setResponseCode(200)
.setDebugMessage("dummy debug message")
.build();
BillingResult billingResult3 =
BillingResult.newBuilder()
.setResponseCode(300)
.setDebugMessage("dummy debug message")
.build();
captor.getValue().onBillingSetupFinished(billingResult1);
captor.getValue().onBillingSetupFinished(billingResult2);
captor.getValue().onBillingSetupFinished(billingResult3);
verify(result, times(1)).success(fromBillingResult(billingResult1));
verify(result, times(1)).success(any());
}
@Test
public void endConnection() {
// Set up a connected BillingClient instance
final int disconnectCallbackHandle = 22;
Map<String, Object> arguments = new HashMap<>();
arguments.put("handle", disconnectCallbackHandle);
MethodCall connectCall = new MethodCall(START_CONNECTION, arguments);
ArgumentCaptor<BillingClientStateListener> captor =
ArgumentCaptor.forClass(BillingClientStateListener.class);
doNothing().when(mockBillingClient).startConnection(captor.capture());
methodChannelHandler.onMethodCall(connectCall, mock(Result.class));
final BillingClientStateListener stateListener = captor.getValue();
// Disconnect the connected client
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, result);
// Verify that the client is disconnected and that the OnDisconnect callback has
// been triggered
verify(result, times(1)).success(any());
verify(mockBillingClient, times(1)).endConnection();
stateListener.onBillingServiceDisconnected();
Map<String, Integer> expectedInvocation = new HashMap<>();
expectedInvocation.put("handle", disconnectCallbackHandle);
verify(mockMethodChannel, times(1)).invokeMethod(ON_DISCONNECT, expectedInvocation);
}
@Test
public void querySkuDetailsAsync() {
// Connect a billing client and set up the SKU query listeners
establishConnectedBillingClient(/* arguments= */ null, /* result= */ null);
String skuType = BillingClient.SkuType.INAPP;
List<String> skusList = asList("id1", "id2");
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("skuType", skuType);
arguments.put("skusList", skusList);
MethodCall queryCall = new MethodCall(QUERY_SKU_DETAILS, arguments);
// Query for SKU details
methodChannelHandler.onMethodCall(queryCall, result);
// Assert the arguments were forwarded correctly to BillingClient
ArgumentCaptor<SkuDetailsParams> paramCaptor = ArgumentCaptor.forClass(SkuDetailsParams.class);
ArgumentCaptor<SkuDetailsResponseListener> listenerCaptor =
ArgumentCaptor.forClass(SkuDetailsResponseListener.class);
verify(mockBillingClient).querySkuDetailsAsync(paramCaptor.capture(), listenerCaptor.capture());
assertEquals(paramCaptor.getValue().getSkuType(), skuType);
assertEquals(paramCaptor.getValue().getSkusList(), skusList);
// Assert that we handed result BillingClient's response
int responseCode = 200;
List<SkuDetails> skuDetailsResponse = asList(buildSkuDetails("foo"));
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
listenerCaptor.getValue().onSkuDetailsResponse(billingResult, skuDetailsResponse);
ArgumentCaptor<HashMap<String, Object>> resultCaptor = ArgumentCaptor.forClass(HashMap.class);
verify(result).success(resultCaptor.capture());
HashMap<String, Object> resultData = resultCaptor.getValue();
assertEquals(resultData.get("billingResult"), fromBillingResult(billingResult));
assertEquals(resultData.get("skuDetailsList"), fromSkuDetailsList(skuDetailsResponse));
}
@Test
public void querySkuDetailsAsync_clientDisconnected() {
// Disconnect the Billing client and prepare a querySkuDetails call
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, mock(Result.class));
String skuType = BillingClient.SkuType.INAPP;
List<String> skusList = asList("id1", "id2");
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("skuType", skuType);
arguments.put("skusList", skusList);
MethodCall queryCall = new MethodCall(QUERY_SKU_DETAILS, arguments);
// Query for SKU details
methodChannelHandler.onMethodCall(queryCall, result);
// Assert that we sent an error back.
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
// Test launchBillingFlow not crash if `accountId` is `null`
// Ideally, we should check if the `accountId` is null in the parameter; however,
// since PBL 3.0, the `accountId` variable is not public.
@Test
public void launchBillingFlow_null_AccountId_do_not_crash() {
// Fetch the sku details first and then prepare the launch billing flow call
String skuId = "foo";
queryForSkus(singletonList(skuId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", null);
arguments.put("obfuscatedProfileId", null);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_ok_null_OldSku() {
// Fetch the sku details first and then prepare the launch billing flow call
String skuId = "foo";
String accountId = "account";
queryForSkus(singletonList(skuId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
arguments.put("oldSku", null);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_ok_null_Activity() {
methodChannelHandler.setActivity(null);
// Fetch the sku details first and then prepare the launch billing flow call
String skuId = "foo";
String accountId = "account";
queryForSkus(singletonList(skuId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the response code to result
verify(result).error(contains("ACTIVITY_UNAVAILABLE"), contains("foreground"), any());
verify(result, never()).success(any());
}
@Test
public void launchBillingFlow_ok_oldSku() {
// Fetch the sku details first and query the method call
String skuId = "foo";
String accountId = "account";
String oldSkuId = "oldFoo";
queryForSkus(unmodifiableList(asList(skuId, oldSkuId)));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
arguments.put("oldSku", oldSkuId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_ok_AccountId() {
// Fetch the sku details first and query the method call
String skuId = "foo";
String accountId = "account";
queryForSkus(singletonList(skuId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_ok_Proration() {
// Fetch the sku details first and query the method call
String skuId = "foo";
String oldSkuId = "oldFoo";
String purchaseToken = "purchaseTokenFoo";
String accountId = "account";
int prorationMode = BillingFlowParams.ProrationMode.IMMEDIATE_AND_CHARGE_PRORATED_PRICE;
queryForSkus(unmodifiableList(asList(skuId, oldSkuId)));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
arguments.put("oldSku", oldSkuId);
arguments.put("purchaseToken", purchaseToken);
arguments.put("prorationMode", prorationMode);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_ok_Proration_with_null_OldSku() {
// Fetch the sku details first and query the method call
String skuId = "foo";
String accountId = "account";
String queryOldSkuId = "oldFoo";
String oldSkuId = null;
int prorationMode = BillingFlowParams.ProrationMode.IMMEDIATE_AND_CHARGE_PRORATED_PRICE;
queryForSkus(unmodifiableList(asList(skuId, queryOldSkuId)));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
arguments.put("oldSku", oldSkuId);
arguments.put("prorationMode", prorationMode);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Assert that we sent an error back.
verify(result)
.error(
contains("IN_APP_PURCHASE_REQUIRE_OLD_SKU"),
contains("launchBillingFlow failed because oldSku is null"),
any());
verify(result, never()).success(any());
}
@Test
public void launchBillingFlow_ok_Full() {
// Fetch the sku details first and query the method call
String skuId = "foo";
String oldSkuId = "oldFoo";
String purchaseToken = "purchaseTokenFoo";
String accountId = "account";
int prorationMode = BillingFlowParams.ProrationMode.IMMEDIATE_AND_CHARGE_FULL_PRICE;
queryForSkus(unmodifiableList(asList(skuId, oldSkuId)));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
arguments.put("oldSku", oldSkuId);
arguments.put("purchaseToken", purchaseToken);
arguments.put("prorationMode", prorationMode);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
// Launch the billing flow
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
when(mockBillingClient.launchBillingFlow(any(), any())).thenReturn(billingResult);
methodChannelHandler.onMethodCall(launchCall, result);
// Verify we pass the arguments to the billing flow
ArgumentCaptor<BillingFlowParams> billingFlowParamsCaptor =
ArgumentCaptor.forClass(BillingFlowParams.class);
verify(mockBillingClient).launchBillingFlow(any(), billingFlowParamsCaptor.capture());
BillingFlowParams params = billingFlowParamsCaptor.getValue();
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void launchBillingFlow_clientDisconnected() {
// Prepare the launch call after disconnecting the client
MethodCall disconnectCall = new MethodCall(END_CONNECTION, null);
methodChannelHandler.onMethodCall(disconnectCall, mock(Result.class));
String skuId = "foo";
String accountId = "account";
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
methodChannelHandler.onMethodCall(launchCall, result);
// Assert that we sent an error back.
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
@Test
public void launchBillingFlow_skuNotFound() {
// Try to launch the billing flow for a random sku ID
establishConnectedBillingClient(null, null);
String skuId = "foo";
String accountId = "account";
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
methodChannelHandler.onMethodCall(launchCall, result);
// Assert that we sent an error back.
verify(result).error(contains("NOT_FOUND"), contains(skuId), any());
verify(result, never()).success(any());
}
@Test
public void launchBillingFlow_oldSkuNotFound() {
// Try to launch the billing flow for a random sku ID
establishConnectedBillingClient(null, null);
String skuId = "foo";
String accountId = "account";
String oldSkuId = "oldSku";
queryForSkus(singletonList(skuId));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
arguments.put("accountId", accountId);
arguments.put("oldSku", oldSkuId);
MethodCall launchCall = new MethodCall(LAUNCH_BILLING_FLOW, arguments);
methodChannelHandler.onMethodCall(launchCall, result);
// Assert that we sent an error back.
verify(result).error(contains("IN_APP_PURCHASE_INVALID_OLD_SKU"), contains(oldSkuId), any());
verify(result, never()).success(any());
}
@Test
public void queryPurchases_clientDisconnected() {
// Prepare the launch call after disconnecting the client
methodChannelHandler.onMethodCall(new MethodCall(END_CONNECTION, null), mock(Result.class));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("skuType", SkuType.INAPP);
methodChannelHandler.onMethodCall(new MethodCall(QUERY_PURCHASES_ASYNC, arguments), result);
// Assert that we sent an error back.
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
@Test
public void queryPurchases_returns_success() throws Exception {
establishConnectedBillingClient(null, null);
CountDownLatch lock = new CountDownLatch(1);
doAnswer(
new Answer() {
public Object answer(InvocationOnMock invocation) {
lock.countDown();
return null;
}
})
.when(result)
.success(any(HashMap.class));
ArgumentCaptor<PurchasesResponseListener> purchasesResponseListenerArgumentCaptor =
ArgumentCaptor.forClass(PurchasesResponseListener.class);
doAnswer(
new Answer() {
public Object answer(InvocationOnMock invocation) {
BillingResult.Builder resultBuilder =
BillingResult.newBuilder()
.setResponseCode(BillingClient.BillingResponseCode.OK)
.setDebugMessage("hello message");
purchasesResponseListenerArgumentCaptor
.getValue()
.onQueryPurchasesResponse(resultBuilder.build(), new ArrayList<Purchase>());
return null;
}
})
.when(mockBillingClient)
.queryPurchasesAsync(
any(QueryPurchasesParams.class), purchasesResponseListenerArgumentCaptor.capture());
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("skuType", SkuType.INAPP);
methodChannelHandler.onMethodCall(new MethodCall(QUERY_PURCHASES_ASYNC, arguments), result);
lock.await(5000, TimeUnit.MILLISECONDS);
verify(result, never()).error(any(), any(), any());
ArgumentCaptor<HashMap> hashMapCaptor = ArgumentCaptor.forClass(HashMap.class);
verify(result, times(1)).success(hashMapCaptor.capture());
HashMap<String, Object> map = hashMapCaptor.getValue();
assert (map.containsKey("responseCode"));
assert (map.containsKey("billingResult"));
assert (map.containsKey("purchasesList"));
assert ((int) map.get("responseCode") == 0);
}
@Test
public void queryPurchaseHistoryAsync() {
// Set up an established billing client and all our mocked responses
establishConnectedBillingClient(null, null);
ArgumentCaptor<HashMap<String, Object>> resultCaptor = ArgumentCaptor.forClass(HashMap.class);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
List<PurchaseHistoryRecord> purchasesList = asList(buildPurchaseHistoryRecord("foo"));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("skuType", SkuType.INAPP);
ArgumentCaptor<PurchaseHistoryResponseListener> listenerCaptor =
ArgumentCaptor.forClass(PurchaseHistoryResponseListener.class);
methodChannelHandler.onMethodCall(
new MethodCall(QUERY_PURCHASE_HISTORY_ASYNC, arguments), result);
// Verify we pass the data to result
verify(mockBillingClient)
.queryPurchaseHistoryAsync(any(QueryPurchaseHistoryParams.class), listenerCaptor.capture());
listenerCaptor.getValue().onPurchaseHistoryResponse(billingResult, purchasesList);
verify(result).success(resultCaptor.capture());
HashMap<String, Object> resultData = resultCaptor.getValue();
assertEquals(fromBillingResult(billingResult), resultData.get("billingResult"));
assertEquals(
fromPurchaseHistoryRecordList(purchasesList), resultData.get("purchaseHistoryRecordList"));
}
@Test
public void queryPurchaseHistoryAsync_clientDisconnected() {
// Prepare the launch call after disconnecting the client
methodChannelHandler.onMethodCall(new MethodCall(END_CONNECTION, null), mock(Result.class));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("skuType", SkuType.INAPP);
methodChannelHandler.onMethodCall(
new MethodCall(QUERY_PURCHASE_HISTORY_ASYNC, arguments), result);
// Assert that we sent an error back.
verify(result).error(contains("UNAVAILABLE"), contains("BillingClient"), any());
verify(result, never()).success(any());
}
@Test
public void onPurchasesUpdatedListener() {
PluginPurchaseListener listener = new PluginPurchaseListener(mockMethodChannel);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
List<Purchase> purchasesList = asList(buildPurchase("foo"));
ArgumentCaptor<HashMap<String, Object>> resultCaptor = ArgumentCaptor.forClass(HashMap.class);
doNothing()
.when(mockMethodChannel)
.invokeMethod(eq(ON_PURCHASES_UPDATED), resultCaptor.capture());
listener.onPurchasesUpdated(billingResult, purchasesList);
HashMap<String, Object> resultData = resultCaptor.getValue();
assertEquals(fromBillingResult(billingResult), resultData.get("billingResult"));
assertEquals(fromPurchasesList(purchasesList), resultData.get("purchasesList"));
}
@Test
public void consumeAsync() {
establishConnectedBillingClient(null, null);
ArgumentCaptor<BillingResult> resultCaptor = ArgumentCaptor.forClass(BillingResult.class);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("purchaseToken", "mockToken");
arguments.put("developerPayload", "mockPayload");
ArgumentCaptor<ConsumeResponseListener> listenerCaptor =
ArgumentCaptor.forClass(ConsumeResponseListener.class);
methodChannelHandler.onMethodCall(new MethodCall(CONSUME_PURCHASE_ASYNC, arguments), result);
ConsumeParams params = ConsumeParams.newBuilder().setPurchaseToken("mockToken").build();
// Verify we pass the data to result
verify(mockBillingClient).consumeAsync(refEq(params), listenerCaptor.capture());
listenerCaptor.getValue().onConsumeResponse(billingResult, "mockToken");
verify(result).success(resultCaptor.capture());
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void acknowledgePurchase() {
establishConnectedBillingClient(null, null);
ArgumentCaptor<BillingResult> resultCaptor = ArgumentCaptor.forClass(BillingResult.class);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("purchaseToken", "mockToken");
arguments.put("developerPayload", "mockPayload");
ArgumentCaptor<AcknowledgePurchaseResponseListener> listenerCaptor =
ArgumentCaptor.forClass(AcknowledgePurchaseResponseListener.class);
methodChannelHandler.onMethodCall(new MethodCall(ACKNOWLEDGE_PURCHASE, arguments), result);
AcknowledgePurchaseParams params =
AcknowledgePurchaseParams.newBuilder().setPurchaseToken("mockToken").build();
// Verify we pass the data to result
verify(mockBillingClient).acknowledgePurchase(refEq(params), listenerCaptor.capture());
listenerCaptor.getValue().onAcknowledgePurchaseResponse(billingResult);
verify(result).success(resultCaptor.capture());
// Verify we pass the response code to result
verify(result, never()).error(any(), any(), any());
verify(result, times(1)).success(fromBillingResult(billingResult));
}
@Test
public void endConnection_if_activity_detached() {
InAppPurchasePlugin plugin = new InAppPurchasePlugin();
plugin.setMethodCallHandler(methodChannelHandler);
mockStartConnection();
plugin.onDetachedFromActivity();
verify(mockBillingClient).endConnection();
}
@Test
public void isFutureSupported_true() {
mockStartConnection();
final String feature = "subscriptions";
Map<String, Object> arguments = new HashMap<>();
arguments.put("feature", feature);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(BillingClient.BillingResponseCode.OK)
.setDebugMessage("dummy debug message")
.build();
MethodCall call = new MethodCall(IS_FEATURE_SUPPORTED, arguments);
when(mockBillingClient.isFeatureSupported(feature)).thenReturn(billingResult);
methodChannelHandler.onMethodCall(call, result);
verify(result).success(true);
}
@Test
public void isFutureSupported_false() {
mockStartConnection();
final String feature = "subscriptions";
Map<String, Object> arguments = new HashMap<>();
arguments.put("feature", feature);
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED)
.setDebugMessage("dummy debug message")
.build();
MethodCall call = new MethodCall(IS_FEATURE_SUPPORTED, arguments);
when(mockBillingClient.isFeatureSupported(feature)).thenReturn(billingResult);
methodChannelHandler.onMethodCall(call, result);
verify(result).success(false);
}
@Test
public void launchPriceChangeConfirmationFlow() {
// Set up the sku details
establishConnectedBillingClient(null, null);
String skuId = "foo";
queryForSkus(singletonList(skuId));
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(BillingClient.BillingResponseCode.OK)
.setDebugMessage("dummy debug message")
.build();
// Set up the mock billing client
ArgumentCaptor<PriceChangeConfirmationListener> priceChangeConfirmationListenerArgumentCaptor =
ArgumentCaptor.forClass(PriceChangeConfirmationListener.class);
ArgumentCaptor<PriceChangeFlowParams> priceChangeFlowParamsArgumentCaptor =
ArgumentCaptor.forClass(PriceChangeFlowParams.class);
doNothing()
.when(mockBillingClient)
.launchPriceChangeConfirmationFlow(
any(),
priceChangeFlowParamsArgumentCaptor.capture(),
priceChangeConfirmationListenerArgumentCaptor.capture());
// Call the methodChannelHandler
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
methodChannelHandler.onMethodCall(
new MethodCall(LAUNCH_PRICE_CHANGE_CONFIRMATION_FLOW, arguments), result);
// Verify the price change params.
PriceChangeFlowParams priceChangeFlowParams = priceChangeFlowParamsArgumentCaptor.getValue();
assertEquals(skuId, priceChangeFlowParams.getSkuDetails().getSku());
// Set the response in the callback
PriceChangeConfirmationListener priceChangeConfirmationListener =
priceChangeConfirmationListenerArgumentCaptor.getValue();
priceChangeConfirmationListener.onPriceChangeConfirmationResult(billingResult);
// Verify we pass the response to result
verify(result, never()).error(any(), any(), any());
ArgumentCaptor<HashMap> resultCaptor = ArgumentCaptor.forClass(HashMap.class);
verify(result, times(1)).success(resultCaptor.capture());
assertEquals(fromBillingResult(billingResult), resultCaptor.getValue());
}
@Test
public void launchPriceChangeConfirmationFlow_withoutActivity_returnsActivityUnavailableError() {
// Set up the sku details
establishConnectedBillingClient(null, null);
String skuId = "foo";
queryForSkus(singletonList(skuId));
methodChannelHandler.setActivity(null);
// Call the methodChannelHandler
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
methodChannelHandler.onMethodCall(
new MethodCall(LAUNCH_PRICE_CHANGE_CONFIRMATION_FLOW, arguments), result);
verify(result, times(1)).error(eq("ACTIVITY_UNAVAILABLE"), any(), any());
}
@Test
public void launchPriceChangeConfirmationFlow_withoutSkuQuery_returnsNotFoundError() {
// Set up the sku details
establishConnectedBillingClient(null, null);
String skuId = "foo";
// Call the methodChannelHandler
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
methodChannelHandler.onMethodCall(
new MethodCall(LAUNCH_PRICE_CHANGE_CONFIRMATION_FLOW, arguments), result);
verify(result, times(1)).error(eq("NOT_FOUND"), contains("sku"), any());
}
@Test
public void launchPriceChangeConfirmationFlow_withoutBillingClient_returnsUnavailableError() {
// Set up the sku details
String skuId = "foo";
// Call the methodChannelHandler
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("sku", skuId);
methodChannelHandler.onMethodCall(
new MethodCall(LAUNCH_PRICE_CHANGE_CONFIRMATION_FLOW, arguments), result);
verify(result, times(1)).error(eq("UNAVAILABLE"), contains("BillingClient"), any());
}
private ArgumentCaptor<BillingClientStateListener> mockStartConnection() {
Map<String, Object> arguments = new HashMap<>();
arguments.put("handle", 1);
MethodCall call = new MethodCall(START_CONNECTION, arguments);
ArgumentCaptor<BillingClientStateListener> captor =
ArgumentCaptor.forClass(BillingClientStateListener.class);
doNothing().when(mockBillingClient).startConnection(captor.capture());
methodChannelHandler.onMethodCall(call, result);
return captor;
}
private void establishConnectedBillingClient(
@Nullable Map<String, Object> arguments, @Nullable Result result) {
if (arguments == null) {
arguments = new HashMap<>();
arguments.put("handle", 1);
}
if (result == null) {
result = mock(Result.class);
}
MethodCall connectCall = new MethodCall(START_CONNECTION, arguments);
methodChannelHandler.onMethodCall(connectCall, result);
}
private void queryForSkus(List<String> skusList) {
// Set up the query method call
establishConnectedBillingClient(/* arguments= */ null, /* result= */ null);
HashMap<String, Object> arguments = new HashMap<>();
String skuType = SkuType.INAPP;
arguments.put("skuType", skuType);
arguments.put("skusList", skusList);
MethodCall queryCall = new MethodCall(QUERY_SKU_DETAILS, arguments);
// Call the method.
methodChannelHandler.onMethodCall(queryCall, mock(Result.class));
// Respond to the call with a matching set of Sku details.
ArgumentCaptor<SkuDetailsResponseListener> listenerCaptor =
ArgumentCaptor.forClass(SkuDetailsResponseListener.class);
verify(mockBillingClient).querySkuDetailsAsync(any(), listenerCaptor.capture());
List<SkuDetails> skuDetailsResponse =
skusList.stream().map(this::buildSkuDetails).collect(toList());
BillingResult billingResult =
BillingResult.newBuilder()
.setResponseCode(100)
.setDebugMessage("dummy debug message")
.build();
listenerCaptor.getValue().onSkuDetailsResponse(billingResult, skuDetailsResponse);
}
private SkuDetails buildSkuDetails(String id) {
String json =
String.format(
"{\"packageName\": \"dummyPackageName\",\"productId\":\"%s\",\"type\":\"inapp\",\"price\":\"$0.99\",\"price_amount_micros\":990000,\"price_currency_code\":\"USD\",\"title\":\"Example title\",\"description\":\"Example description.\",\"original_price\":\"$0.99\",\"original_price_micros\":990000}",
id);
SkuDetails details = null;
try {
details = new SkuDetails(json);
} catch (JSONException e) {
fail("buildSkuDetails failed with JSONException " + e.toString());
}
return details;
}
private Purchase buildPurchase(String orderId) {
Purchase purchase = mock(Purchase.class);
when(purchase.getOrderId()).thenReturn(orderId);
return purchase;
}
private PurchaseHistoryRecord buildPurchaseHistoryRecord(String purchaseToken) {
PurchaseHistoryRecord purchase = mock(PurchaseHistoryRecord.class);
when(purchase.getPurchaseToken()).thenReturn(purchaseToken);
return purchase;
}
}
| plugins/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/MethodCallHandlerTest.java/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/MethodCallHandlerTest.java",
"repo_id": "plugins",
"token_count": 14540
} | 1,160 |
mock-maker-inline
| plugins/packages/in_app_purchase/in_app_purchase_android/example/android/app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/example/android/app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker",
"repo_id": "plugins",
"token_count": 7
} | 1,161 |
// Copyright 2013 The Flutter 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(mvanbeusekom): Remove this file when the deprecated
// `SkuDetailsWrapper.introductoryPriceMicros` field is
// removed.
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_android/billing_client_wrappers.dart';
void main() {
test(
'Deprecated `introductoryPriceMicros` field reflects parameter from constructor',
() {
const SkuDetailsWrapper skuDetails = SkuDetailsWrapper(
description: 'description',
freeTrialPeriod: 'freeTrialPeriod',
introductoryPrice: 'introductoryPrice',
// ignore: deprecated_member_use_from_same_package
introductoryPriceMicros: '990000',
introductoryPriceCycles: 1,
introductoryPricePeriod: 'introductoryPricePeriod',
price: 'price',
priceAmountMicros: 1000,
priceCurrencyCode: 'priceCurrencyCode',
priceCurrencySymbol: r'$',
sku: 'sku',
subscriptionPeriod: 'subscriptionPeriod',
title: 'title',
type: SkuType.inapp,
originalPrice: 'originalPrice',
originalPriceAmountMicros: 1000,
);
expect(skuDetails, isNotNull);
expect(skuDetails.introductoryPriceAmountMicros, 0);
// ignore: deprecated_member_use_from_same_package
expect(skuDetails.introductoryPriceMicros, '990000');
});
test(
'`introductoryPriceAmoutMicros` constructor parameter is reflected by deprecated `introductoryPriceMicros` and `introductoryPriceAmountMicros` fields',
() {
const SkuDetailsWrapper skuDetails = SkuDetailsWrapper(
description: 'description',
freeTrialPeriod: 'freeTrialPeriod',
introductoryPrice: 'introductoryPrice',
introductoryPriceAmountMicros: 990000,
introductoryPriceCycles: 1,
introductoryPricePeriod: 'introductoryPricePeriod',
price: 'price',
priceAmountMicros: 1000,
priceCurrencyCode: 'priceCurrencyCode',
priceCurrencySymbol: r'$',
sku: 'sku',
subscriptionPeriod: 'subscriptionPeriod',
title: 'title',
type: SkuType.inapp,
originalPrice: 'originalPrice',
originalPriceAmountMicros: 1000,
);
expect(skuDetails, isNotNull);
expect(skuDetails.introductoryPriceAmountMicros, 990000);
// ignore: deprecated_member_use_from_same_package
expect(skuDetails.introductoryPriceMicros, '990000');
});
}
| plugins/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/sku_details_wrapper_deprecated_test.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/sku_details_wrapper_deprecated_test.dart",
"repo_id": "plugins",
"token_count": 936
} | 1,162 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// The class represents the information of a product.
class ProductDetails {
/// Creates a new product details object with the provided details.
ProductDetails({
required this.id,
required this.title,
required this.description,
required this.price,
required this.rawPrice,
required this.currencyCode,
this.currencySymbol = '',
});
/// The identifier of the product.
///
/// For example, on iOS it is specified in App Store Connect; on Android, it is specified in Google Play Console.
final String id;
/// The title of the product.
///
/// For example, on iOS it is specified in App Store Connect; on Android, it is specified in Google Play Console.
final String title;
/// The description of the product.
///
/// For example, on iOS it is specified in App Store Connect; on Android, it is specified in Google Play Console.
final String description;
/// The price of the product, formatted with currency symbol ("$0.99").
///
/// For example, on iOS it is specified in App Store Connect; on Android, it is specified in Google Play Console.
final String price;
/// The unformatted price of the product, specified in the App Store Connect or Sku in Google Play console based on the platform.
/// The currency unit for this value can be found in the [currencyCode] property.
/// The value always describes full units of the currency. (e.g. 2.45 in the case of $2.45)
final double rawPrice;
/// The currency code for the price of the product.
/// Based on the price specified in the App Store Connect or Sku in Google Play console based on the platform.
final String currencyCode;
/// The currency symbol for the locale, e.g. $ for US locale.
///
/// When the currency symbol cannot be determined, the ISO 4217 currency code is returned.
final String currencySymbol;
}
| plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/product_details.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/product_details.dart",
"repo_id": "plugins",
"token_count": 523
} | 1,163 |
// Copyright 2013 The Flutter 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_test/flutter_test.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/src/store_kit_wrappers/enum_converters.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'fakes/fake_storekit_platform.dart';
import 'store_kit_wrappers/sk_test_stub_objects.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform();
late InAppPurchaseStoreKitPlatform iapStoreKitPlatform;
setUpAll(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform, fakeStoreKitPlatform.onMethodCall);
});
setUp(() {
InAppPurchaseStoreKitPlatform.registerPlatform();
iapStoreKitPlatform =
InAppPurchasePlatform.instance as InAppPurchaseStoreKitPlatform;
fakeStoreKitPlatform.reset();
});
tearDown(() => fakeStoreKitPlatform.reset());
group('isAvailable', () {
test('true', () async {
expect(await iapStoreKitPlatform.isAvailable(), isTrue);
});
});
group('query product list', () {
test('should get product list and correct invalid identifiers', () async {
final InAppPurchaseStoreKitPlatform connection =
InAppPurchaseStoreKitPlatform();
final ProductDetailsResponse response =
await connection.queryProductDetails(<String>{'123', '456', '789'});
final List<ProductDetails> products = response.productDetails;
expect(products.first.id, '123');
expect(products[1].id, '456');
expect(response.notFoundIDs, <String>['789']);
expect(response.error, isNull);
expect(response.productDetails.first.currencySymbol, r'$');
expect(response.productDetails[1].currencySymbol, 'EUR');
});
test(
'if query products throws error, should get error object in the response',
() async {
fakeStoreKitPlatform.queryProductException = PlatformException(
code: 'error_code',
message: 'error_message',
details: <Object, Object>{'info': 'error_info'});
final InAppPurchaseStoreKitPlatform connection =
InAppPurchaseStoreKitPlatform();
final ProductDetailsResponse response =
await connection.queryProductDetails(<String>{'123', '456', '789'});
expect(response.productDetails, <ProductDetails>[]);
expect(response.notFoundIDs, <String>['123', '456', '789']);
expect(response.error, isNotNull);
expect(response.error!.source, kIAPSource);
expect(response.error!.code, 'error_code');
expect(response.error!.message, 'error_message');
expect(response.error!.details, <Object, Object>{'info': 'error_info'});
});
});
group('restore purchases', () {
test('should emit restored transactions on purchase stream', () async {
fakeStoreKitPlatform.transactions.insert(
0, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT1'));
fakeStoreKitPlatform.transactions.insert(
1, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'));
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
if (purchaseDetailsList.first.status == PurchaseStatus.restored) {
subscription.cancel();
completer.complete(purchaseDetailsList);
}
});
await iapStoreKitPlatform.restorePurchases();
final List<PurchaseDetails> details = await completer.future;
expect(details.length, 2);
for (int i = 0; i < fakeStoreKitPlatform.transactions.length; i++) {
final SKPaymentTransactionWrapper expected =
fakeStoreKitPlatform.transactions[i];
final PurchaseDetails actual = details[i];
expect(actual.purchaseID, expected.transactionIdentifier);
expect(actual.verificationData, isNotNull);
expect(actual.status, PurchaseStatus.restored);
expect(actual.verificationData.localVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.verificationData.serverVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.pendingCompletePurchase, true);
}
});
test(
'should emit empty transaction list on purchase stream when there is nothing to restore',
() async {
fakeStoreKitPlatform.testRestoredTransactionsNull = true;
final Completer<List<PurchaseDetails>?> completer =
Completer<List<PurchaseDetails>?>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
expect(purchaseDetailsList.isEmpty, true);
subscription.cancel();
completer.complete();
});
await iapStoreKitPlatform.restorePurchases();
await completer.future;
});
test('should not block transaction updates', () async {
fakeStoreKitPlatform.transactions.insert(
0, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT1'));
fakeStoreKitPlatform.transactions.insert(
1, fakeStoreKitPlatform.createPurchasedTransaction('foo', 'bar'));
fakeStoreKitPlatform.transactions.insert(
2, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'));
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
if (purchaseDetailsList[1].status == PurchaseStatus.purchased) {
completer.complete(purchaseDetailsList);
subscription.cancel();
}
});
await iapStoreKitPlatform.restorePurchases();
final List<PurchaseDetails> details = await completer.future;
expect(details.length, 3);
for (int i = 0; i < fakeStoreKitPlatform.transactions.length; i++) {
final SKPaymentTransactionWrapper expected =
fakeStoreKitPlatform.transactions[i];
final PurchaseDetails actual = details[i];
expect(actual.purchaseID, expected.transactionIdentifier);
expect(actual.verificationData, isNotNull);
expect(
actual.status,
const SKTransactionStatusConverter()
.toPurchaseStatus(expected.transactionState, expected.error),
);
expect(actual.verificationData.localVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.verificationData.serverVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.pendingCompletePurchase, true);
}
});
test(
'should emit empty transaction if transactions array does not contain a transaction with PurchaseStatus.restored status.',
() async {
fakeStoreKitPlatform.transactions.insert(
0, fakeStoreKitPlatform.createPurchasedTransaction('foo', 'bar'));
final Completer<List<List<PurchaseDetails>>> completer =
Completer<List<List<PurchaseDetails>>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
final List<List<PurchaseDetails>> purchaseDetails =
<List<PurchaseDetails>>[];
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
purchaseDetails.add(purchaseDetailsList);
if (purchaseDetails.length == 2) {
completer.complete(purchaseDetails);
subscription.cancel();
}
});
await iapStoreKitPlatform.restorePurchases();
final List<List<PurchaseDetails>> details = await completer.future;
expect(details.length, 2);
expect(details[0], <List<PurchaseDetails>>[]);
for (int i = 0; i < fakeStoreKitPlatform.transactions.length; i++) {
final SKPaymentTransactionWrapper expected =
fakeStoreKitPlatform.transactions[i];
final PurchaseDetails actual = details[1][i];
expect(actual.purchaseID, expected.transactionIdentifier);
expect(actual.verificationData, isNotNull);
expect(
actual.status,
const SKTransactionStatusConverter()
.toPurchaseStatus(expected.transactionState, expected.error),
);
expect(actual.verificationData.localVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.verificationData.serverVerificationData,
fakeStoreKitPlatform.receiptData);
expect(actual.pendingCompletePurchase, true);
}
});
test('receipt error should populate null to verificationData.data',
() async {
fakeStoreKitPlatform.transactions.insert(
0, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT1'));
fakeStoreKitPlatform.transactions.insert(
1, fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'));
fakeStoreKitPlatform.receiptData = null;
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
if (purchaseDetailsList.first.status == PurchaseStatus.restored) {
completer.complete(purchaseDetailsList);
subscription.cancel();
}
});
await iapStoreKitPlatform.restorePurchases();
final List<PurchaseDetails> details = await completer.future;
for (final PurchaseDetails purchase in details) {
expect(purchase.verificationData.localVerificationData, isEmpty);
expect(purchase.verificationData.serverVerificationData, isEmpty);
}
});
test('test restore error', () {
fakeStoreKitPlatform.testRestoredError = const SKError(
code: 123,
domain: 'error_test',
userInfo: <String, dynamic>{'message': 'errorMessage'});
expect(
() => iapStoreKitPlatform.restorePurchases(),
throwsA(
isA<SKError>()
.having((SKError error) => error.code, 'code', 123)
.having((SKError error) => error.domain, 'domain', 'error_test')
.having((SKError error) => error.userInfo, 'userInfo',
<String, dynamic>{'message': 'errorMessage'}),
));
});
});
group('make payment', () {
test(
'buying non consumable, should get purchase objects in the purchase update callback',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
if (purchaseDetailsList.first.status == PurchaseStatus.purchased) {
completer.complete(details);
subscription.cancel();
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final List<PurchaseDetails> result = await completer.future;
expect(result.length, 2);
expect(result.first.productID, dummyProductWrapper.productIdentifier);
});
test(
'buying consumable, should get purchase objects in the purchase update callback',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
if (purchaseDetailsList.first.status == PurchaseStatus.purchased) {
completer.complete(details);
subscription.cancel();
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam);
final List<PurchaseDetails> result = await completer.future;
expect(result.length, 2);
expect(result.first.productID, dummyProductWrapper.productIdentifier);
});
test('buying consumable, should throw when autoConsume is false', () async {
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
expect(
() => iapStoreKitPlatform.buyConsumable(
purchaseParam: purchaseParam, autoConsume: false),
throwsA(isInstanceOf<AssertionError>()));
});
test('should get failed purchase status', () async {
fakeStoreKitPlatform.testTransactionFail = true;
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<IAPError> completer = Completer<IAPError>();
late IAPError error;
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.status == PurchaseStatus.error) {
error = purchaseDetails.error!;
completer.complete(error);
subscription.cancel();
}
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final IAPError completerError = await completer.future;
expect(completerError.code, 'purchase_error');
expect(completerError.source, kIAPSource);
expect(completerError.message, 'ios_domain');
expect(completerError.details,
<Object, Object>{'message': 'an error message'});
});
test(
'should get canceled purchase status when error code is SKErrorPaymentCancelled',
() async {
fakeStoreKitPlatform.testTransactionCancel = 2;
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<PurchaseStatus> completer = Completer<PurchaseStatus>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.status == PurchaseStatus.canceled) {
completer.complete(purchaseDetails.status);
subscription.cancel();
}
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final PurchaseStatus purchaseStatus = await completer.future;
expect(purchaseStatus, PurchaseStatus.canceled);
});
test(
'should get canceled purchase status when error code is SKErrorOverlayCancelled',
() async {
fakeStoreKitPlatform.testTransactionCancel = 15;
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<PurchaseStatus> completer = Completer<PurchaseStatus>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.status == PurchaseStatus.canceled) {
completer.complete(purchaseDetails.status);
subscription.cancel();
}
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final PurchaseStatus purchaseStatus = await completer.future;
expect(purchaseStatus, PurchaseStatus.canceled);
});
test(
'buying non consumable, should be able to purchase multiple quantity of one product',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.pendingCompletePurchase) {
iapStoreKitPlatform.completePurchase(purchaseDetails);
completer.complete(details);
subscription.cancel();
}
}
});
final AppStoreProductDetails productDetails =
AppStoreProductDetails.fromSKProduct(dummyProductWrapper);
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails: productDetails,
quantity: 5,
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
await completer.future;
expect(
fakeStoreKitPlatform.finishedTransactions.first.payment.quantity, 5);
});
test(
'buying consumable, should be able to purchase multiple quantity of one product',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.pendingCompletePurchase) {
iapStoreKitPlatform.completePurchase(purchaseDetails);
completer.complete(details);
subscription.cancel();
}
}
});
final AppStoreProductDetails productDetails =
AppStoreProductDetails.fromSKProduct(dummyProductWrapper);
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails: productDetails,
quantity: 5,
applicationUserName: 'appName');
await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam);
await completer.future;
expect(
fakeStoreKitPlatform.finishedTransactions.first.payment.quantity, 5);
});
test(
'buying non consumable with discount, should get purchase objects in the purchase update callback',
() async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
if (purchaseDetailsList.first.status == PurchaseStatus.purchased) {
completer.complete(details);
subscription.cancel();
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'userWithDiscount',
discount: dummyPaymentDiscountWrapper,
);
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final List<PurchaseDetails> result = await completer.future;
expect(result.length, 2);
expect(result.first.productID, dummyProductWrapper.productIdentifier);
expect(fakeStoreKitPlatform.discountReceived,
dummyPaymentDiscountWrapper.toMap());
});
});
group('complete purchase', () {
test('should complete purchase', () async {
final List<PurchaseDetails> details = <PurchaseDetails>[];
final Completer<List<PurchaseDetails>> completer =
Completer<List<PurchaseDetails>>();
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
late StreamSubscription<List<PurchaseDetails>> subscription;
subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) {
details.addAll(purchaseDetailsList);
for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.pendingCompletePurchase) {
iapStoreKitPlatform.completePurchase(purchaseDetails);
completer.complete(details);
subscription.cancel();
}
}
});
final AppStorePurchaseParam purchaseParam = AppStorePurchaseParam(
productDetails:
AppStoreProductDetails.fromSKProduct(dummyProductWrapper),
applicationUserName: 'appName');
await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam);
final List<PurchaseDetails> result = await completer.future;
expect(result.length, 2);
expect(result.first.productID, dummyProductWrapper.productIdentifier);
expect(fakeStoreKitPlatform.finishedTransactions.length, 1);
});
});
group('purchase stream', () {
test('Should only have active queue when purchaseStream has listeners', () {
final Stream<List<PurchaseDetails>> stream =
iapStoreKitPlatform.purchaseStream;
expect(fakeStoreKitPlatform.queueIsActive, false);
final StreamSubscription<List<PurchaseDetails>> subscription1 =
stream.listen((List<PurchaseDetails> event) {});
expect(fakeStoreKitPlatform.queueIsActive, true);
final StreamSubscription<List<PurchaseDetails>> subscription2 =
stream.listen((List<PurchaseDetails> event) {});
expect(fakeStoreKitPlatform.queueIsActive, true);
subscription1.cancel();
expect(fakeStoreKitPlatform.queueIsActive, true);
subscription2.cancel();
expect(fakeStoreKitPlatform.queueIsActive, 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/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_test.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_test.dart",
"repo_id": "plugins",
"token_count": 9145
} | 1,164 |
// Copyright 2013 The Flutter 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 <UIKit/UIKit.h>
@interface UIImage (ios_platform_images)
/// Loads a UIImage from the embedded Flutter project's assets.
///
/// This method loads the Flutter asset that is appropriate for the current
/// screen. If you are on a 2x retina device where usually `UIImage` would be
/// loading `@2x` assets, it will attempt to load the `2.0x` variant. It will
/// load the standard image if it can't find the `2.0x` variant.
///
/// For example, if your Flutter project's `pubspec.yaml` lists "assets/foo.png"
/// and "assets/2.0x/foo.png", calling
/// `[UIImage flutterImageWithName:@"assets/foo.png"]` will load
/// "assets/2.0x/foo.png".
///
/// See also https://flutter.dev/docs/development/ui/assets-and-images
///
/// Note: We don't yet support images from package dependencies (ex.
/// `AssetImage('icons/heart.png', package: 'my_icons')`).
+ (UIImage *)flutterImageWithName:(NSString *)name;
@end
| plugins/packages/ios_platform_images/ios/Classes/UIImage+ios_platform_images.h/0 | {
"file_path": "plugins/packages/ios_platform_images/ios/Classes/UIImage+ios_platform_images.h",
"repo_id": "plugins",
"token_count": 335
} | 1,165 |
name: local_auth
description: Flutter plugin for Android and iOS devices to allow local
authentication via fingerprint, touch ID, face ID, passcode, pin, or pattern.
repository: https://github.com/flutter/plugins/tree/main/packages/local_auth/local_auth
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22
version: 2.1.4
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
default_package: local_auth_android
ios:
default_package: local_auth_ios
windows:
default_package: local_auth_windows
dependencies:
flutter:
sdk: flutter
local_auth_android: ^1.0.0
local_auth_ios: ^1.0.1
local_auth_platform_interface: ^1.0.1
local_auth_windows: ^1.0.0
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: ^5.1.0
plugin_platform_interface: ^2.1.2
| plugins/packages/local_auth/local_auth/pubspec.yaml/0 | {
"file_path": "plugins/packages/local_auth/local_auth/pubspec.yaml",
"repo_id": "plugins",
"token_count": 412
} | 1,166 |
// Copyright 2013 The Flutter 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:local_auth_ios/local_auth_ios.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('LocalAuth', () {
const MethodChannel channel = MethodChannel(
'plugins.flutter.io/local_auth_ios',
);
final List<MethodCall> log = <MethodCall>[];
late LocalAuthIOS localAuthentication;
setUp(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) {
log.add(methodCall);
switch (methodCall.method) {
case 'getEnrolledBiometrics':
return Future<List<String>>.value(
<String>['face', 'fingerprint', 'iris', 'undefined']);
default:
return Future<dynamic>.value(true);
}
});
localAuthentication = LocalAuthIOS();
log.clear();
});
test('deviceSupportsBiometrics calls platform', () async {
final bool result = await localAuthentication.deviceSupportsBiometrics();
expect(
log,
<Matcher>[
isMethodCall('deviceSupportsBiometrics', arguments: null),
],
);
expect(result, true);
});
test('getEnrolledBiometrics calls platform', () async {
final List<BiometricType> result =
await localAuthentication.getEnrolledBiometrics();
expect(
log,
<Matcher>[
isMethodCall('getEnrolledBiometrics', arguments: null),
],
);
expect(result, <BiometricType>[
BiometricType.face,
BiometricType.fingerprint,
BiometricType.iris
]);
});
test('isDeviceSupported calls platform', () async {
await localAuthentication.isDeviceSupported();
expect(
log,
<Matcher>[
isMethodCall('isDeviceSupported', arguments: null),
],
);
});
test('stopAuthentication returns false', () async {
final bool result = await localAuthentication.stopAuthentication();
expect(result, false);
});
group('With device auth fail over', () {
test('authenticate with no args.', () async {
await localAuthentication.authenticate(
authMessages: <AuthMessages>[const IOSAuthMessages()],
localizedReason: 'Needs secure',
options: const AuthenticationOptions(biometricOnly: true),
);
expect(
log,
<Matcher>[
isMethodCall('authenticate',
arguments: <String, dynamic>{
'localizedReason': 'Needs secure',
'useErrorDialogs': true,
'stickyAuth': false,
'sensitiveTransaction': true,
'biometricOnly': true,
}..addAll(const IOSAuthMessages().args)),
],
);
});
test('authenticate with no localizedReason.', () async {
await expectLater(
localAuthentication.authenticate(
authMessages: <AuthMessages>[const IOSAuthMessages()],
localizedReason: '',
options: const AuthenticationOptions(biometricOnly: true),
),
throwsAssertionError,
);
});
});
group('With biometrics only', () {
test('authenticate with no args.', () async {
await localAuthentication.authenticate(
authMessages: <AuthMessages>[const IOSAuthMessages()],
localizedReason: 'Needs secure',
);
expect(
log,
<Matcher>[
isMethodCall('authenticate',
arguments: <String, dynamic>{
'localizedReason': 'Needs secure',
'useErrorDialogs': true,
'stickyAuth': false,
'sensitiveTransaction': true,
'biometricOnly': false,
}..addAll(const IOSAuthMessages().args)),
],
);
});
test('authenticate with `localizedFallbackTitle`', () async {
await localAuthentication.authenticate(
authMessages: <AuthMessages>[
const IOSAuthMessages(localizedFallbackTitle: 'Enter PIN'),
],
localizedReason: 'Needs secure',
);
expect(
log,
<Matcher>[
isMethodCall('authenticate',
arguments: <String, dynamic>{
'localizedReason': 'Needs secure',
'useErrorDialogs': true,
'stickyAuth': false,
'sensitiveTransaction': true,
'biometricOnly': false,
'localizedFallbackTitle': 'Enter PIN',
}..addAll(const IOSAuthMessages().args)),
],
);
});
test('authenticate with no sensitive transaction.', () async {
await localAuthentication.authenticate(
authMessages: <AuthMessages>[const IOSAuthMessages()],
localizedReason: 'Insecure',
options: const AuthenticationOptions(
sensitiveTransaction: false,
useErrorDialogs: false,
),
);
expect(
log,
<Matcher>[
isMethodCall('authenticate',
arguments: <String, dynamic>{
'localizedReason': 'Insecure',
'useErrorDialogs': false,
'stickyAuth': false,
'sensitiveTransaction': false,
'biometricOnly': false,
}..addAll(const IOSAuthMessages().args)),
],
);
});
});
});
}
/// 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/local_auth/local_auth_ios/test/local_auth_test.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth_ios/test/local_auth_test.dart",
"repo_id": "plugins",
"token_count": 2766
} | 1,167 |
# local\_auth\_windows
The Windows implementation of [`local_auth`][1].
## Usage
This package is [endorsed][2], which means you can simply use `local_auth`
normally. This package will be automatically included in your app when you do.
[1]: https://pub.dev/packages/local_auth
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin | plugins/packages/local_auth/local_auth_windows/README.md/0 | {
"file_path": "plugins/packages/local_auth/local_auth_windows/README.md",
"repo_id": "plugins",
"token_count": 118
} | 1,168 |
// Copyright 2013 The Flutter 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
@testable import path_provider_foundation
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#endif
class RunnerTests: XCTestCase {
func testGetTemporaryDirectory() throws {
let plugin = PathProviderPlugin()
let path = plugin.getDirectoryPath(type: .temp)
XCTAssertEqual(
path,
NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.cachesDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true
).first)
}
func testGetApplicationDocumentsDirectory() throws {
let plugin = PathProviderPlugin()
let path = plugin.getDirectoryPath(type: .applicationDocuments)
XCTAssertEqual(
path,
NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.documentDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true
).first)
}
func testGetApplicationSupportDirectory() throws {
let plugin = PathProviderPlugin()
let path = plugin.getDirectoryPath(type: .applicationSupport)
#if os(iOS)
// On iOS, the application support directory path should be just the system application
// support path.
XCTAssertEqual(
path,
NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.applicationSupportDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true
).first)
#else
// On macOS, the application support directory path should be the system application
// support path with an added subdirectory based on the app name.
XCTAssert(
path!.hasPrefix(
NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.applicationSupportDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true
).first!))
XCTAssert(path!.hasSuffix("Example"))
#endif
}
func testGetLibraryDirectory() throws {
let plugin = PathProviderPlugin()
let path = plugin.getDirectoryPath(type: .library)
XCTAssertEqual(
path,
NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.libraryDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true
).first)
}
func testGetDownloadsDirectory() throws {
let plugin = PathProviderPlugin()
let path = plugin.getDirectoryPath(type: .downloads)
XCTAssertEqual(
path,
NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.downloadsDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true
).first)
}
}
| plugins/packages/path_provider/path_provider_foundation/darwin/RunnerTests/RunnerTests.swift/0 | {
"file_path": "plugins/packages/path_provider/path_provider_foundation/darwin/RunnerTests/RunnerTests.swift",
"repo_id": "plugins",
"token_count": 982
} | 1,169 |
name: path_provider_windows
description: Windows implementation of the path_provider plugin
repository: https://github.com/flutter/plugins/tree/main/packages/path_provider/path_provider_windows
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22
version: 2.1.3
environment:
sdk: ">=2.17.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: path_provider
platforms:
windows:
dartPluginClass: PathProviderWindows
dependencies:
ffi: ^2.0.0
flutter:
sdk: flutter
path: ^1.8.0
path_provider_platform_interface: ^2.0.0
win32: ">=2.1.0 <4.0.0"
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/path_provider/path_provider_windows/pubspec.yaml/0 | {
"file_path": "plugins/packages/path_provider/path_provider_windows/pubspec.yaml",
"repo_id": "plugins",
"token_count": 299
} | 1,170 |
rootProject.name = 'quick_actions'
| plugins/packages/quick_actions/quick_actions_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 11
} | 1,171 |
// Copyright 2013 The Flutter 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
/// A channel for platform code to communicate with the Dart code.
protocol MethodChannel {
/// Invokes a method in Dart code.
/// - Parameter method the method name.
/// - Parameter arguments the method arguments.
func invokeMethod(_ method: String, arguments: Any?)
}
/// A default implementation of the `MethodChannel` protocol.
extension FlutterMethodChannel: MethodChannel {}
| plugins/packages/quick_actions/quick_actions_ios/ios/Classes/MethodChannel.swift/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/ios/Classes/MethodChannel.swift",
"repo_id": "plugins",
"token_count": 141
} | 1,172 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Home screen quick-action shortcut item.
class ShortcutItem {
/// Constructs an instance with the given [type], [localizedTitle], and
/// [icon].
///
/// Only [icon] should be nullable. It will remain `null` if unset.
const ShortcutItem({
required this.type,
required this.localizedTitle,
this.icon,
});
/// The identifier of this item; should be unique within the app.
final String type;
/// Localized title of the item.
final String localizedTitle;
/// Name of native resource (xcassets etc; NOT a Flutter asset) to be
/// displayed as the icon for this item.
final String? icon;
}
| plugins/packages/quick_actions/quick_actions_platform_interface/lib/types/shortcut_item.dart/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_platform_interface/lib/types/shortcut_item.dart",
"repo_id": "plugins",
"token_count": 225
} | 1,173 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('$SharedPreferences', () {
const String testString = 'hello world';
const bool testBool = true;
const int testInt = 42;
const double testDouble = 3.14159;
const List<String> testList = <String>['foo', 'bar'];
const String testString2 = 'goodbye world';
const bool testBool2 = false;
const int testInt2 = 1337;
const double testDouble2 = 2.71828;
const List<String> testList2 = <String>['baz', 'quox'];
late SharedPreferences preferences;
setUp(() async {
preferences = await SharedPreferences.getInstance();
});
tearDown(() {
preferences.clear();
});
testWidgets('reading', (WidgetTester _) async {
expect(preferences.get('String'), isNull);
expect(preferences.get('bool'), isNull);
expect(preferences.get('int'), isNull);
expect(preferences.get('double'), isNull);
expect(preferences.get('List'), isNull);
expect(preferences.getString('String'), isNull);
expect(preferences.getBool('bool'), isNull);
expect(preferences.getInt('int'), isNull);
expect(preferences.getDouble('double'), isNull);
expect(preferences.getStringList('List'), isNull);
});
testWidgets('writing', (WidgetTester _) async {
await Future.wait(<Future<bool>>[
preferences.setString('String', testString2),
preferences.setBool('bool', testBool2),
preferences.setInt('int', testInt2),
preferences.setDouble('double', testDouble2),
preferences.setStringList('List', testList2)
]);
expect(preferences.getString('String'), testString2);
expect(preferences.getBool('bool'), testBool2);
expect(preferences.getInt('int'), testInt2);
expect(preferences.getDouble('double'), testDouble2);
expect(preferences.getStringList('List'), testList2);
});
testWidgets('removing', (WidgetTester _) async {
const String key = 'testKey';
await preferences.setString(key, testString);
await preferences.setBool(key, testBool);
await preferences.setInt(key, testInt);
await preferences.setDouble(key, testDouble);
await preferences.setStringList(key, testList);
await preferences.remove(key);
expect(preferences.get('testKey'), isNull);
});
testWidgets('clearing', (WidgetTester _) async {
await preferences.setString('String', testString);
await preferences.setBool('bool', testBool);
await preferences.setInt('int', testInt);
await preferences.setDouble('double', testDouble);
await preferences.setStringList('List', testList);
await preferences.clear();
expect(preferences.getString('String'), null);
expect(preferences.getBool('bool'), null);
expect(preferences.getInt('int'), null);
expect(preferences.getDouble('double'), null);
expect(preferences.getStringList('List'), null);
});
testWidgets('simultaneous writes', (WidgetTester _) async {
final List<Future<bool>> writes = <Future<bool>>[];
const int writeCount = 100;
for (int i = 1; i <= writeCount; i++) {
writes.add(preferences.setInt('int', i));
}
final List<bool> result = await Future.wait(writes, eagerError: true);
// All writes should succeed.
expect(result.where((bool element) => !element), isEmpty);
// The last write should win.
expect(preferences.getInt('int'), writeCount);
});
});
}
| plugins/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart",
"repo_id": "plugins",
"token_count": 1418
} | 1,174 |
rootProject.name = 'shared_preferences_android'
| plugins/packages/shared_preferences/shared_preferences_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 15
} | 1,175 |
// Copyright 2013 The Flutter 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:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
const MethodChannel _kChannel =
MethodChannel('plugins.flutter.io/shared_preferences_android');
/// The Android implementation of [SharedPreferencesStorePlatform].
///
/// This class implements the `package:shared_preferences` functionality for Android.
class SharedPreferencesAndroid extends SharedPreferencesStorePlatform {
/// Registers this class as the default instance of [SharedPreferencesStorePlatform].
static void registerWith() {
SharedPreferencesStorePlatform.instance = SharedPreferencesAndroid();
}
@override
Future<bool> remove(String key) async {
return (await _kChannel.invokeMethod<bool>(
'remove',
<String, dynamic>{'key': key},
))!;
}
@override
Future<bool> setValue(String valueType, String key, Object value) async {
return (await _kChannel.invokeMethod<bool>(
'set$valueType',
<String, dynamic>{'key': key, 'value': value},
))!;
}
@override
Future<bool> clear() async {
return (await _kChannel.invokeMethod<bool>('clear'))!;
}
@override
Future<Map<String, Object>> getAll() async {
final Map<String, Object>? preferences =
await _kChannel.invokeMapMethod<String, Object>('getAll');
if (preferences == null) {
return <String, Object>{};
}
return preferences;
}
}
| plugins/packages/shared_preferences/shared_preferences_android/lib/shared_preferences_android.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/lib/shared_preferences_android.dart",
"repo_id": "plugins",
"token_count": 523
} | 1,176 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v5.0.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import
// ignore_for_file: avoid_relative_lib_imports
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_foundation/messages.g.dart';
abstract class TestUserDefaultsApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
void remove(String key);
void setBool(String key, bool value);
void setDouble(String key, double value);
void setValue(String key, Object value);
Map<String?, Object?> getAll();
void clear();
static void setup(TestUserDefaultsApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.UserDefaultsApi.remove', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.remove was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_key = (args[0] as String?);
assert(arg_key != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.remove was null, expected non-null String.');
api.remove(arg_key!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.UserDefaultsApi.setBool', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setBool was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_key = (args[0] as String?);
assert(arg_key != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setBool was null, expected non-null String.');
final bool? arg_value = (args[1] as bool?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setBool was null, expected non-null bool.');
api.setBool(arg_key!, arg_value!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.UserDefaultsApi.setDouble', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setDouble was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_key = (args[0] as String?);
assert(arg_key != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setDouble was null, expected non-null String.');
final double? arg_value = (args[1] as double?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setDouble was null, expected non-null double.');
api.setDouble(arg_key!, arg_value!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.UserDefaultsApi.setValue', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setValue was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_key = (args[0] as String?);
assert(arg_key != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setValue was null, expected non-null String.');
final Object? arg_value = (args[1] as Object?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.UserDefaultsApi.setValue was null, expected non-null Object.');
api.setValue(arg_key!, arg_value!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.UserDefaultsApi.getAll', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
final Map<String?, Object?> output = api.getAll();
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.UserDefaultsApi.clear', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
api.clear();
return <Object?>[];
});
}
}
}
}
| plugins/packages/shared_preferences/shared_preferences_foundation/test/test_api.g.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/test/test_api.g.dart",
"repo_id": "plugins",
"token_count": 2551
} | 1,177 |
// Copyright 2013 The Flutter 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:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group(SharedPreferencesStorePlatform, () {
test('disallows implementing interface', () {
expect(() {
SharedPreferencesStorePlatform.instance = IllegalImplementation();
},
// In versions of `package:plugin_platform_interface` prior to fixing
// https://github.com/flutter/flutter/issues/109339, an attempt to
// implement a platform interface using `implements` would sometimes
// throw a `NoSuchMethodError` and other times throw an
// `AssertionError`. After the issue is fixed, an `AssertionError` will
// always be thrown. For the purpose of this test, we don't really care
// what exception is thrown, so just allow any exception.
throwsA(anything));
});
test('supports MockPlatformInterfaceMixin', () {
SharedPreferencesStorePlatform.instance = ModernMockImplementation();
});
test('still supports legacy isMock', () {
SharedPreferencesStorePlatform.instance = LegacyIsMockImplementation();
});
});
}
/// An implementation using `implements` that isn't a mock, which isn't allowed.
class IllegalImplementation implements SharedPreferencesStorePlatform {
// Intentionally declare self as not a mock to trigger the
// compliance check.
@override
bool get isMock => false;
@override
Future<bool> clear() {
throw UnimplementedError();
}
@override
Future<Map<String, Object>> getAll() {
throw UnimplementedError();
}
@override
Future<bool> remove(String key) {
throw UnimplementedError();
}
@override
Future<bool> setValue(String valueType, String key, Object value) {
throw UnimplementedError();
}
}
class LegacyIsMockImplementation implements SharedPreferencesStorePlatform {
@override
bool get isMock => true;
@override
Future<bool> clear() {
throw UnimplementedError();
}
@override
Future<Map<String, Object>> getAll() {
throw UnimplementedError();
}
@override
Future<bool> remove(String key) {
throw UnimplementedError();
}
@override
Future<bool> setValue(String valueType, String key, Object value) {
throw UnimplementedError();
}
}
class ModernMockImplementation
with MockPlatformInterfaceMixin
implements SharedPreferencesStorePlatform {
@override
bool get isMock => false;
@override
Future<bool> clear() {
throw UnimplementedError();
}
@override
Future<Map<String, Object>> getAll() {
throw UnimplementedError();
}
@override
Future<bool> remove(String key) {
throw UnimplementedError();
}
@override
Future<bool> setValue(String valueType, String key, Object value) {
throw UnimplementedError();
}
}
| plugins/packages/shared_preferences/shared_preferences_platform_interface/test/shared_preferences_platform_interface_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_platform_interface/test/shared_preferences_platform_interface_test.dart",
"repo_id": "plugins",
"token_count": 1027
} | 1,178 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert' show json;
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:flutter/foundation.dart' show debugPrint, visibleForTesting;
import 'package:path/path.dart' as path;
import 'package:path_provider_windows/path_provider_windows.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
/// The Windows implementation of [SharedPreferencesStorePlatform].
///
/// This class implements the `package:shared_preferences` functionality for Windows.
class SharedPreferencesWindows extends SharedPreferencesStorePlatform {
/// Deprecated instance of [SharedPreferencesWindows].
/// Use [SharedPreferencesStorePlatform.instance] instead.
@Deprecated('Use `SharedPreferencesStorePlatform.instance` instead.')
static SharedPreferencesWindows instance = SharedPreferencesWindows();
/// Registers the Windows implementation.
static void registerWith() {
SharedPreferencesStorePlatform.instance = SharedPreferencesWindows();
}
/// File system used to store to disk. Exposed for testing only.
@visibleForTesting
FileSystem fs = const LocalFileSystem();
/// The path_provider_windows instance used to find the support directory.
@visibleForTesting
PathProviderWindows pathProvider = PathProviderWindows();
/// Local copy of preferences
Map<String, Object>? _cachedPreferences;
/// Cached file for storing preferences.
File? _localDataFilePath;
/// Gets the file where the preferences are stored.
Future<File?> _getLocalDataFile() async {
if (_localDataFilePath != null) {
return _localDataFilePath!;
}
final String? directory = await pathProvider.getApplicationSupportPath();
if (directory == null) {
return null;
}
return _localDataFilePath =
fs.file(path.join(directory, 'shared_preferences.json'));
}
/// Gets the preferences from the stored file. Once read, the preferences are
/// maintained in memory.
Future<Map<String, Object>> _readPreferences() async {
if (_cachedPreferences != null) {
return _cachedPreferences!;
}
Map<String, Object> preferences = <String, Object>{};
final File? localDataFile = await _getLocalDataFile();
if (localDataFile != null && localDataFile.existsSync()) {
final String stringMap = localDataFile.readAsStringSync();
if (stringMap.isNotEmpty) {
final Object? data = json.decode(stringMap);
if (data is Map) {
preferences = data.cast<String, Object>();
}
}
}
_cachedPreferences = preferences;
return preferences;
}
/// Writes the cached preferences to disk. Returns [true] if the operation
/// succeeded.
Future<bool> _writePreferences(Map<String, Object> preferences) async {
try {
final File? localDataFile = await _getLocalDataFile();
if (localDataFile == null) {
debugPrint('Unable to determine where to write preferences.');
return false;
}
if (!localDataFile.existsSync()) {
localDataFile.createSync(recursive: true);
}
final String stringMap = json.encode(preferences);
localDataFile.writeAsStringSync(stringMap);
} catch (e) {
debugPrint('Error saving preferences to disk: $e');
return false;
}
return true;
}
@override
Future<bool> clear() async {
final Map<String, Object> preferences = await _readPreferences();
preferences.clear();
return _writePreferences(preferences);
}
@override
Future<Map<String, Object>> getAll() async {
return _readPreferences();
}
@override
Future<bool> remove(String key) async {
final Map<String, Object> preferences = await _readPreferences();
preferences.remove(key);
return _writePreferences(preferences);
}
@override
Future<bool> setValue(String valueType, String key, Object value) async {
final Map<String, Object> preferences = await _readPreferences();
preferences[key] = value;
return _writePreferences(preferences);
}
}
| plugins/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart",
"repo_id": "plugins",
"token_count": 1338
} | 1,179 |
name: url_launcher_example
description: Demonstrates how to use the url_launcher plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
url_launcher_android:
# When depending on this package from a real application you should use:
# url_launcher_android: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
url_launcher_platform_interface: ^2.0.3
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: ^5.0.0
plugin_platform_interface: ^2.0.0
flutter:
uses-material-design: true
| plugins/packages/url_launcher/url_launcher_android/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_android/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 315
} | 1,180 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <flutter_linux/flutter_linux.h>
#include "include/url_launcher_linux/url_launcher_plugin.h"
// TODO(stuartmorgan): Remove this private header and change the below back to
// a static function once https://github.com/flutter/flutter/issues/88724
// is fixed, and test through the public API instead.
// Handles the canLaunch method call.
FlMethodResponse* can_launch(FlUrlLauncherPlugin* self, FlValue* args);
| plugins/packages/url_launcher/url_launcher_linux/linux/url_launcher_plugin_private.h/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_linux/linux/url_launcher_plugin_private.h",
"repo_id": "plugins",
"token_count": 170
} | 1,181 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
/// Signature for a function provided by the [Link] widget that instructs it to
/// follow the link.
typedef FollowLink = Future<void> Function();
/// Signature for a builder function passed to the [Link] widget to construct
/// the widget tree under it.
typedef LinkWidgetBuilder = Widget Function(
BuildContext context,
FollowLink? followLink,
);
/// Signature for a delegate function to build the [Link] widget.
typedef LinkDelegate = Widget Function(LinkInfo linkWidget);
const MethodCodec _codec = JSONMethodCodec();
/// Defines where a Link URL should be open.
///
/// This is a class instead of an enum to allow future customizability e.g.
/// opening a link in a specific iframe.
class LinkTarget {
/// Const private constructor with a [debugLabel] to allow the creation of
/// multiple distinct const instances.
const LinkTarget._({required this.debugLabel});
/// Used to distinguish multiple const instances of [LinkTarget].
final String debugLabel;
/// Use the default target for each platform.
///
/// On Android, the default is [blank]. On the web, the default is [self].
///
/// iOS, on the other hand, defaults to [self] for web URLs, and [blank] for
/// non-web URLs.
static const LinkTarget defaultTarget =
LinkTarget._(debugLabel: 'defaultTarget');
/// On the web, this opens the link in the same tab where the flutter app is
/// running.
///
/// On Android and iOS, this opens the link in a webview within the app.
static const LinkTarget self = LinkTarget._(debugLabel: 'self');
/// On the web, this opens the link in a new tab or window (depending on the
/// browser and user configuration).
///
/// On Android and iOS, this opens the link in the browser or the relevant
/// app.
static const LinkTarget blank = LinkTarget._(debugLabel: 'blank');
}
/// Encapsulates all the information necessary to build a Link widget.
abstract class LinkInfo {
/// Called at build time to construct the widget tree under the link.
LinkWidgetBuilder get builder;
/// The destination that this link leads to.
Uri? get uri;
/// The target indicating where to open the link.
LinkTarget get target;
/// Whether the link is disabled or not.
bool get isDisabled;
}
typedef _SendMessage = Function(String, ByteData?, void Function(ByteData?));
/// Pushes the [routeName] into Flutter's navigation system via a platform
/// message.
///
/// The platform is notified using [SystemNavigator.routeInformationUpdated]. On
/// older versions of Flutter, this means it will not work unless the
/// application uses a [Router] (e.g. using [MaterialApp.router]).
///
/// Returns the raw data returned by the framework.
// TODO(ianh): Remove the first argument.
Future<ByteData> pushRouteNameToFramework(Object? _, String routeName) {
final Completer<ByteData> completer = Completer<ByteData>();
SystemNavigator.routeInformationUpdated(location: routeName);
final _SendMessage sendMessage = _ambiguate(WidgetsBinding.instance)
?.platformDispatcher
.onPlatformMessage ??
ui.channelBuffers.push;
sendMessage(
'flutter/navigation',
_codec.encodeMethodCall(
MethodCall('pushRouteInformation', <dynamic, dynamic>{
'location': routeName,
'state': null,
}),
),
completer.complete,
);
return completer.future;
}
/// 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_platform_interface/lib/link.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_platform_interface/lib/link.dart",
"repo_id": "plugins",
"token_count": 1128
} | 1,182 |
// Copyright 2013 The Flutter 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_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:url_launcher_web/url_launcher_web.dart';
import 'url_launcher_web_test.mocks.dart';
@GenerateMocks(<Type>[html.Window, html.Navigator])
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('UrlLauncherPlugin', () {
late MockWindow mockWindow;
late MockNavigator mockNavigator;
late UrlLauncherPlugin plugin;
setUp(() {
mockWindow = MockWindow();
mockNavigator = MockNavigator();
when(mockWindow.navigator).thenReturn(mockNavigator);
// Simulate that window.open does something.
when(mockWindow.open(any, any)).thenReturn(MockWindow());
when(mockNavigator.vendor).thenReturn('Google LLC');
when(mockNavigator.appVersion).thenReturn('Mock version!');
plugin = UrlLauncherPlugin(debugWindow: mockWindow);
});
group('canLaunch', () {
testWidgets('"http" URLs -> true', (WidgetTester _) async {
expect(plugin.canLaunch('http://google.com'), completion(isTrue));
});
testWidgets('"https" URLs -> true', (WidgetTester _) async {
expect(
plugin.canLaunch('https://go, (Widogle.com'), completion(isTrue));
});
testWidgets('"mailto" URLs -> true', (WidgetTester _) async {
expect(
plugin.canLaunch('mailto:[email protected]'), completion(isTrue));
});
testWidgets('"tel" URLs -> true', (WidgetTester _) async {
expect(plugin.canLaunch('tel:5551234567'), completion(isTrue));
});
testWidgets('"sms" URLs -> true', (WidgetTester _) async {
expect(plugin.canLaunch('sms:+19725551212?body=hello%20there'),
completion(isTrue));
});
});
group('launch', () {
testWidgets('launching a URL returns true', (WidgetTester _) async {
expect(
plugin.launch(
'https://www.google.com',
),
completion(isTrue));
});
testWidgets('launching a "mailto" returns true', (WidgetTester _) async {
expect(
plugin.launch(
'mailto:[email protected]',
),
completion(isTrue));
});
testWidgets('launching a "tel" returns true', (WidgetTester _) async {
expect(
plugin.launch(
'tel:5551234567',
),
completion(isTrue));
});
testWidgets('launching a "sms" returns true', (WidgetTester _) async {
expect(
plugin.launch(
'sms:+19725551212?body=hello%20there',
),
completion(isTrue));
});
});
group('openNewWindow', () {
testWidgets('http urls should be launched in a new window',
(WidgetTester _) async {
plugin.openNewWindow('http://www.google.com');
verify(mockWindow.open('http://www.google.com', ''));
});
testWidgets('https urls should be launched in a new window',
(WidgetTester _) async {
plugin.openNewWindow('https://www.google.com');
verify(mockWindow.open('https://www.google.com', ''));
});
testWidgets('mailto urls should be launched on a new window',
(WidgetTester _) async {
plugin.openNewWindow('mailto:[email protected]');
verify(mockWindow.open('mailto:[email protected]', ''));
});
testWidgets('tel urls should be launched on a new window',
(WidgetTester _) async {
plugin.openNewWindow('tel:5551234567');
verify(mockWindow.open('tel:5551234567', ''));
});
testWidgets('sms urls should be launched on a new window',
(WidgetTester _) async {
plugin.openNewWindow('sms:+19725551212?body=hello%20there');
verify(mockWindow.open('sms:+19725551212?body=hello%20there', ''));
});
testWidgets(
'setting webOnlyLinkTarget as _self opens the url in the same tab',
(WidgetTester _) async {
plugin.openNewWindow('https://www.google.com',
webOnlyWindowName: '_self');
verify(mockWindow.open('https://www.google.com', '_self'));
});
testWidgets(
'setting webOnlyLinkTarget as _blank opens the url in a new tab',
(WidgetTester _) async {
plugin.openNewWindow('https://www.google.com',
webOnlyWindowName: '_blank');
verify(mockWindow.open('https://www.google.com', '_blank'));
});
group('Safari', () {
setUp(() {
when(mockNavigator.vendor).thenReturn('Apple Computer, Inc.');
when(mockNavigator.appVersion).thenReturn(
'5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15');
// Recreate the plugin, so it grabs the overrides from this group
plugin = UrlLauncherPlugin(debugWindow: mockWindow);
});
testWidgets('http urls should be launched in a new window',
(WidgetTester _) async {
plugin.openNewWindow('http://www.google.com');
verify(mockWindow.open('http://www.google.com', ''));
});
testWidgets('https urls should be launched in a new window',
(WidgetTester _) async {
plugin.openNewWindow('https://www.google.com');
verify(mockWindow.open('https://www.google.com', ''));
});
testWidgets('mailto urls should be launched on the same window',
(WidgetTester _) async {
plugin.openNewWindow('mailto:[email protected]');
verify(mockWindow.open('mailto:[email protected]', '_top'));
});
testWidgets('tel urls should be launched on the same window',
(WidgetTester _) async {
plugin.openNewWindow('tel:5551234567');
verify(mockWindow.open('tel:5551234567', '_top'));
});
testWidgets('sms urls should be launched on the same window',
(WidgetTester _) async {
plugin.openNewWindow('sms:+19725551212?body=hello%20there');
verify(
mockWindow.open('sms:+19725551212?body=hello%20there', '_top'));
});
testWidgets(
'mailto urls should use _blank if webOnlyWindowName is set as _blank',
(WidgetTester _) async {
plugin.openNewWindow('mailto:[email protected]',
webOnlyWindowName: '_blank');
verify(mockWindow.open('mailto:[email protected]', '_blank'));
});
});
});
});
}
| plugins/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart",
"repo_id": "plugins",
"token_count": 2989
} | 1,183 |
name: url_launcher_web
description: Web platform implementation of url_launcher
repository: https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
version: 2.0.14
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: url_launcher
platforms:
web:
pluginClass: UrlLauncherPlugin
fileName: url_launcher_web.dart
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
url_launcher_platform_interface: ^2.0.3
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/url_launcher/url_launcher_web/pubspec.yaml/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/pubspec.yaml",
"repo_id": "plugins",
"token_count": 296
} | 1,184 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.videoplayer">
</manifest>
| plugins/packages/video_player/video_player_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/video_player/video_player_android/android/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 47
} | 1,185 |
name: video_player_avfoundation
description: iOS implementation of the video_player plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/video_player/video_player_avfoundation
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22
version: 2.3.8
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: video_player
platforms:
ios:
dartPluginClass: AVFoundationVideoPlayer
pluginClass: FLTVideoPlayerPlugin
dependencies:
flutter:
sdk: flutter
video_player_platform_interface: ">=4.2.0 <7.0.0"
dev_dependencies:
flutter_test:
sdk: flutter
pigeon: ^2.0.1
| plugins/packages/video_player/video_player_avfoundation/pubspec.yaml/0 | {
"file_path": "plugins/packages/video_player/video_player_avfoundation/pubspec.yaml",
"repo_id": "plugins",
"token_count": 292
} | 1,186 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This test is run using `flutter drive` by the CI (see /script/tool/README.md
// in this repository for details on driving that tooling manually), but can
// also be run using `flutter test` directly during development.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
// 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
Future<void> main() async {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0);
server.forEach((HttpRequest request) {
if (request.uri.path == '/hello.txt') {
request.response.writeln('Hello, world.');
} else if (request.uri.path == '/secondary.txt') {
request.response.writeln('How are you today?');
} else if (request.uri.path == '/headers') {
request.response.writeln('${request.headers}');
} else if (request.uri.path == '/favicon.ico') {
request.response.statusCode = HttpStatus.notFound;
} else {
fail('unexpected request: ${request.method} ${request.uri}');
}
request.response.close();
});
final String prefixUrl = 'http://${server.address.address}:${server.port}';
final String primaryUrl = '$prefixUrl/hello.txt';
final String secondaryUrl = '$prefixUrl/secondary.txt';
final String headersUrl = '$prefixUrl/headers';
testWidgets('loadRequest', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final WebViewController controller = WebViewController()
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageFinished.complete()),
)
..loadRequest(Uri.parse(primaryUrl));
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageFinished.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets('runJavaScriptReturningResult', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageFinished.complete()),
)
..loadRequest(Uri.parse(primaryUrl));
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageFinished.future;
await expectLater(
controller.runJavaScriptReturningResult('1 + 1'),
completion(2),
);
});
testWidgets('loadRequest with headers', (WidgetTester tester) async {
final Map<String, String> headers = <String, String>{
'test_header': 'flutter_test_header'
};
final StreamController<String> pageLoads = StreamController<String>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (String url) => pageLoads.add(url)),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
controller.loadRequest(Uri.parse(headersUrl), headers: headers);
await pageLoads.stream.firstWhere((String url) => url == headersUrl);
final String content = await controller.runJavaScriptReturningResult(
'document.documentElement.innerText',
) as String;
expect(content.contains('flutter_test_header'), isTrue);
});
testWidgets('JavascriptChannel', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageFinished.complete()),
);
final Completer<String> channelCompleter = Completer<String>();
await controller.addJavaScriptChannel(
'Echo',
onMessageReceived: (JavaScriptMessage message) {
channelCompleter.complete(message.message);
},
);
await controller.loadHtmlString(
'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+',
);
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageFinished.future;
await controller.runJavaScript('Echo.postMessage("hello");');
await expectLater(channelCompleter.future, completion('hello'));
});
testWidgets('resize webview', (WidgetTester tester) async {
final Completer<void> initialResizeCompleter = Completer<void>();
final Completer<void> buttonTapResizeCompleter = Completer<void>();
final Completer<void> onPageFinished = Completer<void>();
bool resizeButtonTapped = false;
await tester.pumpWidget(ResizableWebView(
onResize: () {
if (resizeButtonTapped) {
buttonTapResizeCompleter.complete();
} else {
initialResizeCompleter.complete();
}
},
onPageFinished: () => onPageFinished.complete(),
));
await onPageFinished.future;
// Wait for a potential call to resize after page is loaded.
await initialResizeCompleter.future.timeout(
const Duration(seconds: 3),
onTimeout: () => null,
);
resizeButtonTapped = true;
await tester.tap(find.byKey(const ValueKey<String>('resizeButton')));
await tester.pumpAndSettle();
await expectLater(buttonTapResizeCompleter.future, completes);
});
testWidgets('set custom userAgent', (WidgetTester tester) async {
final Completer<void> pageFinished = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageFinished.complete(),
))
..setUserAgent('Custom_User_Agent1')
..loadRequest(Uri.parse('about:blank'));
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageFinished.future;
final String customUserAgent = await _getUserAgent(controller);
expect(customUserAgent, 'Custom_User_Agent1');
});
group('Video playback policy', () {
late String videoTestBase64;
setUpAll(() async {
final ByteData videoData =
await rootBundle.load('assets/sample_video.mp4');
final String base64VideoData =
base64Encode(Uint8List.view(videoData.buffer));
final String videoTest = '''
<!DOCTYPE html><html>
<head><title>Video auto play</title>
<script type="text/javascript">
function play() {
var video = document.getElementById("video");
video.play();
video.addEventListener('timeupdate', videoTimeUpdateHandler, false);
}
function videoTimeUpdateHandler(e) {
var video = document.getElementById("video");
VideoTestTime.postMessage(video.currentTime);
}
function isPaused() {
var video = document.getElementById("video");
return video.paused;
}
function isFullScreen() {
var video = document.getElementById("video");
return video.webkitDisplayingFullscreen;
}
</script>
</head>
<body onload="play();">
<video controls playsinline autoplay id="video">
<source src="data:video/mp4;charset=utf-8;base64,$base64VideoData">
</video>
</body>
</html>
''';
videoTestBase64 = base64Encode(const Utf8Encoder().convert(videoTest));
});
testWidgets('Auto media playback', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
late PlatformWebViewControllerCreationParams params;
if (defaultTargetPlatform == TargetPlatform.iOS) {
params = WebKitWebViewControllerCreationParams(
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
);
} else {
params = const PlatformWebViewControllerCreationParams();
}
WebViewController controller =
WebViewController.fromPlatformCreationParams(params)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()),
);
if (controller.platform is AndroidWebViewController) {
(controller.platform as AndroidWebViewController)
.setMediaPlaybackRequiresUserGesture(false);
}
await controller.loadRequest(
Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageLoaded.future;
bool isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, false);
pageLoaded = Completer<void>();
controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()),
)
..loadRequest(
Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageLoaded.future;
isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, true);
});
testWidgets('Video plays inline', (WidgetTester tester) async {
final Completer<void> pageLoaded = Completer<void>();
final Completer<void> videoPlaying = Completer<void>();
late PlatformWebViewControllerCreationParams params;
if (defaultTargetPlatform == TargetPlatform.iOS) {
params = WebKitWebViewControllerCreationParams(
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
allowsInlineMediaPlayback: true,
);
} else {
params = const PlatformWebViewControllerCreationParams();
}
final WebViewController controller =
WebViewController.fromPlatformCreationParams(params)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()),
)
..addJavaScriptChannel(
'VideoTestTime',
onMessageReceived: (JavaScriptMessage message) {
final double currentTime = double.parse(message.message);
// Let it play for at least 1 second to make sure the related video's properties are set.
if (currentTime > 1 && !videoPlaying.isCompleted) {
videoPlaying.complete(null);
}
},
);
if (controller.platform is AndroidWebViewController) {
(controller.platform as AndroidWebViewController)
.setMediaPlaybackRequiresUserGesture(false);
}
await controller.loadRequest(
Uri.parse('data:text/html;charset=utf-8;base64,$videoTestBase64'),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
await tester.pumpAndSettle();
await pageLoaded.future;
// Makes sure we get the correct event that indicates the video is actually playing.
await videoPlaying.future;
final bool fullScreen = await controller
.runJavaScriptReturningResult('isFullScreen();') as bool;
expect(fullScreen, false);
});
// allowsInlineMediaPlayback is a noop on Android, so it is skipped.
testWidgets(
'Video plays full screen when allowsInlineMediaPlayback is false',
(WidgetTester tester) async {
final Completer<void> pageLoaded = Completer<void>();
final Completer<void> videoPlaying = Completer<void>();
final WebViewController controller =
WebViewController.fromPlatformCreationParams(
WebKitWebViewControllerCreationParams(
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()),
)
..addJavaScriptChannel(
'VideoTestTime',
onMessageReceived: (JavaScriptMessage message) {
final double currentTime = double.parse(message.message);
// Let it play for at least 1 second to make sure the related video's properties are set.
if (currentTime > 1 && !videoPlaying.isCompleted) {
videoPlaying.complete(null);
}
},
)
..loadRequest(
Uri.parse(
'data:text/html;charset=utf-8;base64,$videoTestBase64',
),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
await tester.pumpAndSettle();
await pageLoaded.future;
// Makes sure we get the correct event that indicates the video is actually playing.
await videoPlaying.future;
final bool fullScreen = await controller
.runJavaScriptReturningResult('isFullScreen();') as bool;
expect(fullScreen, true);
}, skip: Platform.isAndroid);
});
group('Audio playback policy', () {
late String audioTestBase64;
setUpAll(() async {
final ByteData audioData =
await rootBundle.load('assets/sample_audio.ogg');
final String base64AudioData =
base64Encode(Uint8List.view(audioData.buffer));
final String audioTest = '''
<!DOCTYPE html><html>
<head><title>Audio auto play</title>
<script type="text/javascript">
function play() {
var audio = document.getElementById("audio");
audio.play();
}
function isPaused() {
var audio = document.getElementById("audio");
return audio.paused;
}
</script>
</head>
<body onload="play();">
<audio controls id="audio">
<source src="data:audio/ogg;charset=utf-8;base64,$base64AudioData">
</audio>
</body>
</html>
''';
audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest));
});
testWidgets('Auto media playback', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
late PlatformWebViewControllerCreationParams params;
if (defaultTargetPlatform == TargetPlatform.iOS) {
params = WebKitWebViewControllerCreationParams(
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
);
} else {
params = const PlatformWebViewControllerCreationParams();
}
WebViewController controller =
WebViewController.fromPlatformCreationParams(params)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()),
);
if (controller.platform is AndroidWebViewController) {
(controller.platform as AndroidWebViewController)
.setMediaPlaybackRequiresUserGesture(false);
}
await controller.loadRequest(
Uri.parse('data:text/html;charset=utf-8;base64,$audioTestBase64'),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
await tester.pumpAndSettle();
await pageLoaded.future;
bool isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, false);
pageLoaded = Completer<void>();
controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()),
)
..loadRequest(
Uri.parse('data:text/html;charset=utf-8;base64,$audioTestBase64'),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
await tester.pumpAndSettle();
await pageLoaded.future;
isPaused =
await controller.runJavaScriptReturningResult('isPaused();') as bool;
expect(isPaused, true);
});
});
testWidgets('getTitle', (WidgetTester tester) async {
const String getTitleTest = '''
<!DOCTYPE html><html>
<head><title>Some title</title>
</head>
<body>
</body>
</html>
''';
final String getTitleTestBase64 =
base64Encode(const Utf8Encoder().convert(getTitleTest));
final Completer<void> pageLoaded = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageLoaded.complete(),
))
..loadRequest(
Uri.parse('data:text/html;charset=utf-8;base64,$getTitleTestBase64'),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageLoaded.future;
// On at least iOS, it does not appear to be guaranteed that the native
// code has the title when the page load completes. Execute some JavaScript
// before checking the title to ensure that the page has been fully parsed
// and processed.
await controller.runJavaScript('1;');
final String? title = await controller.getTitle();
expect(title, 'Some title');
});
group('Programmatic Scroll', () {
testWidgets('setAndGetScrollPosition', (WidgetTester tester) async {
const String scrollTestPage = '''
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 100%;
width: 100%;
}
#container{
width:5000px;
height:5000px;
}
</style>
</head>
<body>
<div id="container"/>
</body>
</html>
''';
final String scrollTestPageBase64 =
base64Encode(const Utf8Encoder().convert(scrollTestPage));
final Completer<void> pageLoaded = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageLoaded.complete(),
))
..loadRequest(Uri.parse(
'data:text/html;charset=utf-8;base64,$scrollTestPageBase64',
));
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageLoaded.future;
await tester.pumpAndSettle(const Duration(seconds: 3));
Offset scrollPos = await controller.getScrollPosition();
// Check scrollTo()
const int X_SCROLL = 123;
const int Y_SCROLL = 321;
// Get the initial position; this ensures that scrollTo is actually
// changing something, but also gives the native view's scroll position
// time to settle.
expect(scrollPos.dx, isNot(X_SCROLL));
expect(scrollPos.dy, isNot(Y_SCROLL));
await controller.scrollTo(X_SCROLL, Y_SCROLL);
scrollPos = await controller.getScrollPosition();
expect(scrollPos.dx, X_SCROLL);
expect(scrollPos.dy, Y_SCROLL);
// Check scrollBy() (on top of scrollTo())
await controller.scrollBy(X_SCROLL, Y_SCROLL);
scrollPos = await controller.getScrollPosition();
expect(scrollPos.dx, X_SCROLL * 2);
expect(scrollPos.dy, Y_SCROLL * 2);
});
});
group('NavigationDelegate', () {
const String blankPage = '<!DOCTYPE html><head></head><body></body></html>';
final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,'
'${base64Encode(const Utf8Encoder().convert(blankPage))}';
testWidgets('can allow requests', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageLoaded.complete(),
onNavigationRequest: (NavigationRequest navigationRequest) {
return (navigationRequest.url.contains('youtube.com'))
? NavigationDecision.prevent
: NavigationDecision.navigate;
},
));
await tester.pumpWidget(WebViewWidget(controller: controller));
controller.loadRequest(Uri.parse(blankPageEncoded));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller.runJavaScript('location.href = "$secondaryUrl"');
await pageLoaded.future; // Wait for the next page load.
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, secondaryUrl);
});
testWidgets('onWebResourceError', (WidgetTester tester) async {
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(onWebResourceError: (WebResourceError error) {
errorCompleter.complete(error);
}))
..loadRequest(Uri.parse('https://www.notawebsite..com'));
await tester.pumpWidget(WebViewWidget(controller: controller));
final WebResourceError error = await errorCompleter.future;
expect(error, isNotNull);
});
testWidgets('onWebResourceError is not called with valid url',
(WidgetTester tester) async {
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final Completer<void> pageFinishCompleter = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageFinishCompleter.complete(),
onWebResourceError: (WebResourceError error) {
errorCompleter.complete(error);
},
))
..loadRequest(
Uri.parse('data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+'),
);
await tester.pumpWidget(WebViewWidget(controller: controller));
expect(errorCompleter.future, doesNotComplete);
await pageFinishCompleter.future;
});
testWidgets('can block requests', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageLoaded.complete(),
onNavigationRequest: (NavigationRequest navigationRequest) {
return (navigationRequest.url.contains('youtube.com'))
? NavigationDecision.prevent
: NavigationDecision.navigate;
}));
await tester.pumpWidget(WebViewWidget(controller: controller));
controller.loadRequest(Uri.parse(blankPageEncoded));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller
.runJavaScript('location.href = "https://www.youtube.com/"');
// There should never be any second page load, since our new URL is
// blocked. Still wait for a potential page change for some time in order
// to give the test a chance to fail.
await pageLoaded.future
.timeout(const Duration(milliseconds: 500), onTimeout: () => '');
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, isNot(contains('youtube.com')));
});
testWidgets('supports asynchronous decisions', (WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageLoaded.complete(),
onNavigationRequest: (NavigationRequest navigationRequest) async {
NavigationDecision decision = NavigationDecision.prevent;
decision = await Future<NavigationDecision>.delayed(
const Duration(milliseconds: 10),
() => NavigationDecision.navigate);
return decision;
}));
await tester.pumpWidget(WebViewWidget(controller: controller));
controller.loadRequest(Uri.parse(blankPageEncoded));
await pageLoaded.future; // Wait for initial page load.
pageLoaded = Completer<void>();
await controller.runJavaScript('location.href = "$secondaryUrl"');
await pageLoaded.future; // Wait for second page to load.
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, secondaryUrl);
});
});
testWidgets('target _blank opens in same window',
(WidgetTester tester) async {
final Completer<void> pageLoaded = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageLoaded.complete(),
));
await tester.pumpWidget(WebViewWidget(controller: controller));
await controller.runJavaScript('window.open("$primaryUrl", "_blank")');
await pageLoaded.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets(
'can open new window and go back',
(WidgetTester tester) async {
Completer<void> pageLoaded = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageLoaded.complete(),
))
..loadRequest(Uri.parse(primaryUrl));
await tester.pumpWidget(WebViewWidget(controller: controller));
expect(controller.currentUrl(), completion(primaryUrl));
await pageLoaded.future;
pageLoaded = Completer<void>();
await controller.runJavaScript('window.open("$secondaryUrl")');
await pageLoaded.future;
pageLoaded = Completer<void>();
expect(controller.currentUrl(), completion(secondaryUrl));
expect(controller.canGoBack(), completion(true));
await controller.goBack();
await pageLoaded.future;
await expectLater(controller.currentUrl(), completion(primaryUrl));
},
);
testWidgets(
'clearLocalStorage',
(WidgetTester tester) async {
Completer<void> pageLoadCompleter = Completer<void>();
final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => pageLoadCompleter.complete(),
))
..loadRequest(Uri.parse(primaryUrl));
await tester.pumpWidget(WebViewWidget(controller: controller));
await pageLoadCompleter.future;
pageLoadCompleter = Completer<void>();
await controller.runJavaScript('localStorage.setItem("myCat", "Tom");');
final String myCatItem = await controller.runJavaScriptReturningResult(
'localStorage.getItem("myCat");',
) as String;
expect(myCatItem, _webViewString('Tom'));
await controller.clearLocalStorage();
// Reload page to have changes take effect.
await controller.reload();
await pageLoadCompleter.future;
late final String? nullItem;
try {
nullItem = await controller.runJavaScriptReturningResult(
'localStorage.getItem("myCat");',
) as String;
} catch (exception) {
if (defaultTargetPlatform == TargetPlatform.iOS &&
exception is ArgumentError &&
(exception.message as String).contains(
'Result of JavaScript execution returned a `null` value.')) {
nullItem = '<null>';
}
}
expect(nullItem, _webViewNull());
},
);
}
// JavaScript `null` evaluate to different string values on Android and iOS.
// This utility method returns the string boolean value of the current platform.
String _webViewNull() {
if (defaultTargetPlatform == TargetPlatform.iOS) {
return '<null>';
}
return 'null';
}
// JavaScript String evaluate to different string values on Android and iOS.
// This utility method returns the string boolean value of the current platform.
String _webViewString(String value) {
if (defaultTargetPlatform == TargetPlatform.iOS) {
return value;
}
return '"$value"';
}
/// Returns the value used for the HTTP User-Agent: request header in subsequent HTTP requests.
Future<String> _getUserAgent(WebViewController controller) async {
return _runJavascriptReturningResult(controller, 'navigator.userAgent;');
}
Future<String> _runJavascriptReturningResult(
WebViewController controller,
String js,
) async {
if (defaultTargetPlatform == TargetPlatform.iOS) {
return await controller.runJavaScriptReturningResult(js) as String;
}
return jsonDecode(await controller.runJavaScriptReturningResult(js) as String)
as String;
}
class ResizableWebView extends StatefulWidget {
const ResizableWebView({
super.key,
required this.onResize,
required this.onPageFinished,
});
final VoidCallback onResize;
final VoidCallback onPageFinished;
@override
State<StatefulWidget> createState() => ResizableWebViewState();
}
class ResizableWebViewState extends State<ResizableWebView> {
late final WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(NavigationDelegate(
onPageFinished: (_) => widget.onPageFinished(),
))
..addJavaScriptChannel(
'Resize',
onMessageReceived: (_) {
widget.onResize();
},
)
..loadRequest(
Uri.parse(
'data:text/html;charset=utf-8;base64,${base64Encode(const Utf8Encoder().convert(resizePage))}',
),
);
double webViewWidth = 200;
double webViewHeight = 200;
static const String resizePage = '''
<!DOCTYPE html><html>
<head><title>Resize test</title>
<script type="text/javascript">
function onResize() {
Resize.postMessage("resize");
}
function onLoad() {
window.onresize = onResize;
}
</script>
</head>
<body onload="onLoad();" bgColor="blue">
</body>
</html>
''';
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
SizedBox(
width: webViewWidth,
height: webViewHeight,
child: WebViewWidget(controller: controller)),
TextButton(
key: const Key('resizeButton'),
onPressed: () {
setState(() {
webViewWidth += 100.0;
webViewHeight += 100.0;
});
},
child: const Text('ResizeButton'),
),
],
),
);
}
}
| plugins/packages/webview_flutter/webview_flutter/example/integration_test/webview_flutter_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/example/integration_test/webview_flutter_test.dart",
"repo_id": "plugins",
"token_count": 12653
} | 1,187 |
// Copyright 2013 The Flutter 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:webview_flutter/webview_flutter.dart' as main_file;
void main() {
group('webview_flutter', () {
test('ensure webview_flutter.dart exports classes from platform interface',
() {
// ignore: unnecessary_statements
main_file.JavaScriptMessage;
// ignore: unnecessary_statements
main_file.JavaScriptMode;
// ignore: unnecessary_statements
main_file.LoadRequestMethod;
// ignore: unnecessary_statements
main_file.NavigationDecision;
// ignore: unnecessary_statements
main_file.NavigationRequest;
// ignore: unnecessary_statements
main_file.NavigationRequestCallback;
// ignore: unnecessary_statements
main_file.PageEventCallback;
// ignore: unnecessary_statements
main_file.PlatformNavigationDelegateCreationParams;
// ignore: unnecessary_statements
main_file.PlatformWebViewControllerCreationParams;
// ignore: unnecessary_statements
main_file.PlatformWebViewCookieManagerCreationParams;
// ignore: unnecessary_statements
main_file.PlatformWebViewWidgetCreationParams;
// ignore: unnecessary_statements
main_file.ProgressCallback;
// ignore: unnecessary_statements
main_file.WebResourceError;
// ignore: unnecessary_statements
main_file.WebResourceErrorCallback;
// ignore: unnecessary_statements
main_file.WebViewCookie;
// ignore: unnecessary_statements
main_file.WebResourceErrorType;
});
});
}
| plugins/packages/webview_flutter/webview_flutter/test/webview_flutter_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/test/webview_flutter_test.dart",
"repo_id": "plugins",
"token_count": 604
} | 1,188 |
// Copyright 2013 The Flutter 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.Mockito.verify;
import static org.mockito.Mockito.when;
import android.webkit.WebStorage;
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 WebStorageHostApiImplTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public WebStorage mockWebStorage;
@Mock WebStorageHostApiImpl.WebStorageCreator mockWebStorageCreator;
InstanceManager testInstanceManager;
WebStorageHostApiImpl testHostApiImpl;
@Before
public void setUp() {
testInstanceManager = InstanceManager.open(identifier -> {});
when(mockWebStorageCreator.createWebStorage()).thenReturn(mockWebStorage);
testHostApiImpl = new WebStorageHostApiImpl(testInstanceManager, mockWebStorageCreator);
testHostApiImpl.create(0L);
}
@After
public void tearDown() {
testInstanceManager.close();
}
@Test
public void deleteAllData() {
testHostApiImpl.deleteAllData(0L);
verify(mockWebStorage).deleteAllData();
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebStorageHostApiImplTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebStorageHostApiImplTest.java",
"repo_id": "plugins",
"token_count": 444
} | 1,189 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This test is run using `flutter drive` by the CI (see /script/tool/README.md
// in this repository for details on driving that tooling manually), but can
// also be run using `flutter test` directly during development.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
// 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:webview_flutter_android/src/instance_manager.dart';
import 'package:webview_flutter_android/src/weak_reference_utils.dart';
import 'package:webview_flutter_android/src/webview_flutter_android_legacy.dart';
import 'package:webview_flutter_android_example/legacy/navigation_decision.dart';
import 'package:webview_flutter_android_example/legacy/navigation_request.dart';
import 'package:webview_flutter_android_example/legacy/web_view.dart';
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
Future<void> main() async {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0);
server.forEach((HttpRequest request) {
if (request.uri.path == '/hello.txt') {
request.response.writeln('Hello, world.');
} else if (request.uri.path == '/secondary.txt') {
request.response.writeln('How are you today?');
} else if (request.uri.path == '/headers') {
request.response.writeln('${request.headers}');
} else if (request.uri.path == '/favicon.ico') {
request.response.statusCode = HttpStatus.notFound;
} else {
fail('unexpected request: ${request.method} ${request.uri}');
}
request.response.close();
});
final String prefixUrl = 'http://${server.address.address}:${server.port}';
final String primaryUrl = '$prefixUrl/hello.txt';
final String secondaryUrl = '$prefixUrl/secondary.txt';
final String headersUrl = '$prefixUrl/headers';
testWidgets('initialUrl', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final Completer<void> pageFinishedCompleter = Completer<void>();
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: primaryUrl,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
onPageFinished: pageFinishedCompleter.complete,
),
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageFinishedCompleter.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets('loadUrl', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final StreamController<String> pageLoads = StreamController<String>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: primaryUrl,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
onPageFinished: (String url) {
pageLoads.add(url);
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
await controller.loadUrl(secondaryUrl);
await expectLater(
pageLoads.stream.firstWhere((String url) => url == secondaryUrl),
completion(secondaryUrl),
);
});
testWidgets(
'withWeakRefenceTo allows encapsulating class to be garbage collected',
(WidgetTester tester) async {
final Completer<int> gcCompleter = Completer<int>();
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: gcCompleter.complete,
);
ClassWithCallbackClass? instance = ClassWithCallbackClass();
instanceManager.addHostCreatedInstance(instance.callbackClass, 0);
instance = null;
// Force garbage collection.
await IntegrationTestWidgetsFlutterBinding.instance
.watchPerformance(() async {
await tester.pumpAndSettle();
});
final int gcIdentifier = await gcCompleter.future;
expect(gcIdentifier, 0);
}, timeout: const Timeout(Duration(seconds: 10)));
testWidgets('evaluateJavascript', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: primaryUrl,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
),
),
);
final WebViewController controller = await controllerCompleter.future;
final String result = await controller.evaluateJavascript('1 + 1');
expect(result, equals('2'));
});
testWidgets('loadUrl with headers', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final StreamController<String> pageStarts = StreamController<String>();
final StreamController<String> pageLoads = StreamController<String>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: primaryUrl,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageStarted: (String url) {
pageStarts.add(url);
},
onPageFinished: (String url) {
pageLoads.add(url);
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
final Map<String, String> headers = <String, String>{
'test_header': 'flutter_test_header'
};
await controller.loadUrl(headersUrl, headers: headers);
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, headersUrl);
await pageStarts.stream.firstWhere((String url) => url == currentUrl);
await pageLoads.stream.firstWhere((String url) => url == currentUrl);
final String content = await controller
.runJavascriptReturningResult('document.documentElement.innerText');
expect(content.contains('flutter_test_header'), isTrue);
});
testWidgets('JavascriptChannel', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final Completer<void> pageStarted = Completer<void>();
final Completer<void> pageLoaded = Completer<void>();
final Completer<String> channelCompleter = Completer<String>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
// This is the data URL for: '<!DOCTYPE html>'
initialUrl:
'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Echo',
onMessageReceived: (JavascriptMessage message) {
channelCompleter.complete(message.message);
},
),
},
onPageStarted: (String url) {
pageStarted.complete(null);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageStarted.future;
await pageLoaded.future;
expect(channelCompleter.isCompleted, isFalse);
await controller.runJavascript('Echo.postMessage("hello");');
await expectLater(channelCompleter.future, completion('hello'));
});
testWidgets('resize webview', (WidgetTester tester) async {
final Completer<void> initialResizeCompleter = Completer<void>();
final Completer<void> buttonTapResizeCompleter = Completer<void>();
final Completer<void> onPageFinished = Completer<void>();
bool resizeButtonTapped = false;
await tester.pumpWidget(ResizableWebView(
onResize: (_) {
if (resizeButtonTapped) {
buttonTapResizeCompleter.complete();
} else {
initialResizeCompleter.complete();
}
},
onPageFinished: () => onPageFinished.complete(),
));
await onPageFinished.future;
// Wait for a potential call to resize after page is loaded.
await initialResizeCompleter.future.timeout(
const Duration(seconds: 3),
onTimeout: () => null,
);
resizeButtonTapped = true;
await tester.tap(find.byKey(const ValueKey<String>('resizeButton')));
await tester.pumpAndSettle();
expect(buttonTapResizeCompleter.future, completes);
});
testWidgets('set custom userAgent', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter1 =
Completer<WebViewController>();
final GlobalKey globalKey = GlobalKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: globalKey,
initialUrl: 'about:blank',
javascriptMode: JavascriptMode.unrestricted,
userAgent: 'Custom_User_Agent1',
onWebViewCreated: (WebViewController controller) {
controllerCompleter1.complete(controller);
},
),
),
);
final WebViewController controller1 = await controllerCompleter1.future;
final String customUserAgent1 = await _getUserAgent(controller1);
expect(customUserAgent1, 'Custom_User_Agent1');
// rebuild the WebView with a different user agent.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: globalKey,
initialUrl: 'about:blank',
javascriptMode: JavascriptMode.unrestricted,
userAgent: 'Custom_User_Agent2',
),
),
);
final String customUserAgent2 = await _getUserAgent(controller1);
expect(customUserAgent2, 'Custom_User_Agent2');
});
testWidgets('use default platform userAgent after webView is rebuilt',
(WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final GlobalKey globalKey = GlobalKey();
// Build the webView with no user agent to get the default platform user agent.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: globalKey,
initialUrl: primaryUrl,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
final String defaultPlatformUserAgent = await _getUserAgent(controller);
// rebuild the WebView with a custom user agent.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: globalKey,
initialUrl: 'about:blank',
javascriptMode: JavascriptMode.unrestricted,
userAgent: 'Custom_User_Agent',
),
),
);
final String customUserAgent = await _getUserAgent(controller);
expect(customUserAgent, 'Custom_User_Agent');
// rebuilds the WebView with no user agent.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: globalKey,
initialUrl: 'about:blank',
javascriptMode: JavascriptMode.unrestricted,
),
),
);
final String customUserAgent2 = await _getUserAgent(controller);
expect(customUserAgent2, defaultPlatformUserAgent);
});
group('Video playback policy', () {
late String videoTestBase64;
setUpAll(() async {
final ByteData videoData =
await rootBundle.load('assets/sample_video.mp4');
final String base64VideoData =
base64Encode(Uint8List.view(videoData.buffer));
final String videoTest = '''
<!DOCTYPE html><html>
<head><title>Video auto play</title>
<script type="text/javascript">
function play() {
var video = document.getElementById("video");
video.play();
video.addEventListener('timeupdate', videoTimeUpdateHandler, false);
}
function videoTimeUpdateHandler(e) {
var video = document.getElementById("video");
VideoTestTime.postMessage(video.currentTime);
}
function isPaused() {
var video = document.getElementById("video");
return video.paused;
}
function isFullScreen() {
var video = document.getElementById("video");
return video.webkitDisplayingFullscreen;
}
</script>
</head>
<body onload="play();">
<video controls playsinline autoplay id="video">
<source src="data:video/mp4;charset=utf-8;base64,$base64VideoData">
</video>
</body>
</html>
''';
videoTestBase64 = base64Encode(const Utf8Encoder().convert(videoTest));
});
testWidgets('Auto media playback', (WidgetTester tester) async {
Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
Completer<void> pageLoaded = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
pageLoaded.complete(null);
},
initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
),
),
);
WebViewController controller = await controllerCompleter.future;
await pageLoaded.future;
String isPaused =
await controller.runJavascriptReturningResult('isPaused();');
expect(isPaused, _webviewBool(false));
controllerCompleter = Completer<WebViewController>();
pageLoaded = Completer<void>();
// We change the key to re-create a new webview as we change the initialMediaPlaybackPolicy
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
controller = await controllerCompleter.future;
await pageLoaded.future;
isPaused = await controller.runJavascriptReturningResult('isPaused();');
expect(isPaused, _webviewBool(true));
});
testWidgets('Changes to initialMediaPlaybackPolicy are ignored',
(WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
Completer<void> pageLoaded = Completer<void>();
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: key,
initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
pageLoaded.complete(null);
},
initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageLoaded.future;
String isPaused =
await controller.runJavascriptReturningResult('isPaused();');
expect(isPaused, _webviewBool(false));
pageLoaded = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: key,
initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
await controller.reload();
await pageLoaded.future;
isPaused = await controller.runJavascriptReturningResult('isPaused();');
expect(isPaused, _webviewBool(false));
});
testWidgets('Video plays inline when allowsInlineMediaPlayback is true',
(WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final Completer<void> pageLoaded = Completer<void>();
final Completer<void> videoPlaying = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
initialUrl: 'data:text/html;charset=utf-8;base64,$videoTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'VideoTestTime',
onMessageReceived: (JavascriptMessage message) {
final double currentTime = double.parse(message.message);
// Let it play for at least 1 second to make sure the related video's properties are set.
if (currentTime > 1 && !videoPlaying.isCompleted) {
videoPlaying.complete(null);
}
},
),
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
allowsInlineMediaPlayback: true,
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageLoaded.future;
// Pump once to trigger the video play.
await tester.pump();
// Makes sure we get the correct event that indicates the video is actually playing.
await videoPlaying.future;
final String fullScreen =
await controller.runJavascriptReturningResult('isFullScreen();');
expect(fullScreen, _webviewBool(false));
});
});
group('Audio playback policy', () {
late String audioTestBase64;
setUpAll(() async {
final ByteData audioData =
await rootBundle.load('assets/sample_audio.ogg');
final String base64AudioData =
base64Encode(Uint8List.view(audioData.buffer));
final String audioTest = '''
<!DOCTYPE html><html>
<head><title>Audio auto play</title>
<script type="text/javascript">
function play() {
var audio = document.getElementById("audio");
audio.play();
}
function isPaused() {
var audio = document.getElementById("audio");
return audio.paused;
}
</script>
</head>
<body onload="play();">
<audio controls id="audio">
<source src="data:audio/ogg;charset=utf-8;base64,$base64AudioData">
</audio>
</body>
</html>
''';
audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest));
});
testWidgets('Auto media playback', (WidgetTester tester) async {
Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
Completer<void> pageStarted = Completer<void>();
Completer<void> pageLoaded = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageStarted: (String url) {
pageStarted.complete(null);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
),
),
);
WebViewController controller = await controllerCompleter.future;
await pageStarted.future;
await pageLoaded.future;
String isPaused =
await controller.runJavascriptReturningResult('isPaused();');
expect(isPaused, _webviewBool(false));
controllerCompleter = Completer<WebViewController>();
pageStarted = Completer<void>();
pageLoaded = Completer<void>();
// We change the key to re-create a new webview as we change the initialMediaPlaybackPolicy
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageStarted: (String url) {
pageStarted.complete(null);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
controller = await controllerCompleter.future;
await pageStarted.future;
await pageLoaded.future;
isPaused = await controller.runJavascriptReturningResult('isPaused();');
expect(isPaused, _webviewBool(true));
});
testWidgets('Changes to initialMediaPlaybackPolicy are ignored',
(WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
Completer<void> pageStarted = Completer<void>();
Completer<void> pageLoaded = Completer<void>();
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: key,
initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageStarted: (String url) {
pageStarted.complete(null);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageStarted.future;
await pageLoaded.future;
String isPaused =
await controller.runJavascriptReturningResult('isPaused();');
expect(isPaused, _webviewBool(false));
pageStarted = Completer<void>();
pageLoaded = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: key,
initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageStarted: (String url) {
pageStarted.complete(null);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
await controller.reload();
await pageStarted.future;
await pageLoaded.future;
isPaused = await controller.runJavascriptReturningResult('isPaused();');
expect(isPaused, _webviewBool(false));
});
});
testWidgets('getTitle', (WidgetTester tester) async {
const String getTitleTest = '''
<!DOCTYPE html><html>
<head><title>Some title</title>
</head>
<body>
</body>
</html>
''';
final String getTitleTestBase64 =
base64Encode(const Utf8Encoder().convert(getTitleTest));
final Completer<void> pageStarted = Completer<void>();
final Completer<void> pageLoaded = Completer<void>();
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
initialUrl: 'data:text/html;charset=utf-8;base64,$getTitleTestBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
onPageStarted: (String url) {
pageStarted.complete(null);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageStarted.future;
await pageLoaded.future;
final String? title = await controller.getTitle();
expect(title, 'Some title');
});
group('Programmatic Scroll', () {
testWidgets('setAndGetScrollPosition', (WidgetTester tester) async {
const String scrollTestPage = '''
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 100%;
width: 100%;
}
#container{
width:5000px;
height:5000px;
}
</style>
</head>
<body>
<div id="container"/>
</body>
</html>
''';
final String scrollTestPageBase64 =
base64Encode(const Utf8Encoder().convert(scrollTestPage));
final Completer<void> pageLoaded = Completer<void>();
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
initialUrl:
'data:text/html;charset=utf-8;base64,$scrollTestPageBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageLoaded.future;
await tester.pumpAndSettle(const Duration(seconds: 3));
int scrollPosX = await controller.getScrollX();
int scrollPosY = await controller.getScrollY();
// Check scrollTo()
const int X_SCROLL = 123;
const int Y_SCROLL = 321;
// Get the initial position; this ensures that scrollTo is actually
// changing something, but also gives the native view's scroll position
// time to settle.
expect(scrollPosX, isNot(X_SCROLL));
expect(scrollPosX, isNot(Y_SCROLL));
await controller.scrollTo(X_SCROLL, Y_SCROLL);
scrollPosX = await controller.getScrollX();
scrollPosY = await controller.getScrollY();
expect(scrollPosX, X_SCROLL);
expect(scrollPosY, Y_SCROLL);
// Check scrollBy() (on top of scrollTo())
await controller.scrollBy(X_SCROLL, Y_SCROLL);
scrollPosX = await controller.getScrollX();
scrollPosY = await controller.getScrollY();
expect(scrollPosX, X_SCROLL * 2);
expect(scrollPosY, Y_SCROLL * 2);
});
});
group('SurfaceAndroidWebView', () {
setUpAll(() {
WebView.platform = SurfaceAndroidWebView();
});
tearDownAll(() {
WebView.platform = AndroidWebView();
});
testWidgets('setAndGetScrollPosition', (WidgetTester tester) async {
const String scrollTestPage = '''
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 100%;
width: 100%;
}
#container{
width:5000px;
height:5000px;
}
</style>
</head>
<body>
<div id="container"/>
</body>
</html>
''';
final String scrollTestPageBase64 =
base64Encode(const Utf8Encoder().convert(scrollTestPage));
final Completer<void> pageLoaded = Completer<void>();
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
initialUrl:
'data:text/html;charset=utf-8;base64,$scrollTestPageBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageLoaded.future;
await tester.pumpAndSettle(const Duration(seconds: 3));
// Check scrollTo()
const int X_SCROLL = 123;
const int Y_SCROLL = 321;
await controller.scrollTo(X_SCROLL, Y_SCROLL);
int scrollPosX = await controller.getScrollX();
int scrollPosY = await controller.getScrollY();
expect(X_SCROLL, scrollPosX);
expect(Y_SCROLL, scrollPosY);
// Check scrollBy() (on top of scrollTo())
await controller.scrollBy(X_SCROLL, Y_SCROLL);
scrollPosX = await controller.getScrollX();
scrollPosY = await controller.getScrollY();
expect(X_SCROLL * 2, scrollPosX);
expect(Y_SCROLL * 2, scrollPosY);
});
testWidgets('inputs are scrolled into view when focused',
(WidgetTester tester) async {
const String scrollTestPage = '''
<!DOCTYPE html>
<html>
<head>
<style>
input {
margin: 10000px 0;
}
#viewport {
position: fixed;
top:0;
bottom:0;
left:0;
right:0;
}
</style>
</head>
<body>
<div id="viewport"></div>
<input type="text" id="inputEl">
</body>
</html>
''';
final String scrollTestPageBase64 =
base64Encode(const Utf8Encoder().convert(scrollTestPage));
final Completer<void> pageLoaded = Completer<void>();
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
await tester.runAsync(() async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: 200,
height: 200,
child: WebView(
initialUrl:
'data:text/html;charset=utf-8;base64,$scrollTestPageBase64',
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
onPageFinished: (String url) {
pageLoaded.complete(null);
},
javascriptMode: JavascriptMode.unrestricted,
),
),
),
);
await Future<void>.delayed(const Duration(milliseconds: 20));
await tester.pump();
});
final WebViewController controller = await controllerCompleter.future;
await pageLoaded.future;
final String viewportRectJSON = await _runJavaScriptReturningResult(
controller, 'JSON.stringify(viewport.getBoundingClientRect())');
final Map<String, dynamic> viewportRectRelativeToViewport =
jsonDecode(viewportRectJSON) as Map<String, dynamic>;
num getDomRectComponent(
Map<String, dynamic> rectAsJson, String component) {
return rectAsJson[component]! as num;
}
// Check that the input is originally outside of the viewport.
final String initialInputClientRectJSON =
await _runJavaScriptReturningResult(
controller, 'JSON.stringify(inputEl.getBoundingClientRect())');
final Map<String, dynamic> initialInputClientRectRelativeToViewport =
jsonDecode(initialInputClientRectJSON) as Map<String, dynamic>;
expect(
getDomRectComponent(
initialInputClientRectRelativeToViewport, 'bottom') <=
getDomRectComponent(viewportRectRelativeToViewport, 'bottom'),
isFalse);
await controller.runJavascript('inputEl.focus()');
// Check that focusing the input brought it into view.
final String lastInputClientRectJSON =
await _runJavaScriptReturningResult(
controller, 'JSON.stringify(inputEl.getBoundingClientRect())');
final Map<String, dynamic> lastInputClientRectRelativeToViewport =
jsonDecode(lastInputClientRectJSON) as Map<String, dynamic>;
expect(
getDomRectComponent(lastInputClientRectRelativeToViewport, 'top') >=
getDomRectComponent(viewportRectRelativeToViewport, 'top'),
isTrue);
expect(
getDomRectComponent(
lastInputClientRectRelativeToViewport, 'bottom') <=
getDomRectComponent(viewportRectRelativeToViewport, 'bottom'),
isTrue);
expect(
getDomRectComponent(lastInputClientRectRelativeToViewport, 'left') >=
getDomRectComponent(viewportRectRelativeToViewport, 'left'),
isTrue);
expect(
getDomRectComponent(lastInputClientRectRelativeToViewport, 'right') <=
getDomRectComponent(viewportRectRelativeToViewport, 'right'),
isTrue);
});
});
group('NavigationDelegate', () {
const String blankPage = '<!DOCTYPE html><head></head><body></body></html>';
final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,'
'${base64Encode(const Utf8Encoder().convert(blankPage))}';
testWidgets('can allow requests', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final StreamController<String> pageLoads =
StreamController<String>.broadcast();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: blankPageEncoded,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) {
return (request.url.contains('youtube.com'))
? NavigationDecision.prevent
: NavigationDecision.navigate;
},
onPageFinished: (String url) => pageLoads.add(url),
),
),
);
await pageLoads.stream.first; // Wait for initial page load.
final WebViewController controller = await controllerCompleter.future;
await controller.runJavascript('location.href = "$secondaryUrl"');
await pageLoads.stream.first; // Wait for the next page load.
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, secondaryUrl);
});
testWidgets('onWebResourceError', (WidgetTester tester) async {
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: 'https://www.notawebsite..com',
onWebResourceError: (WebResourceError error) {
errorCompleter.complete(error);
},
),
),
);
final WebResourceError error = await errorCompleter.future;
expect(error, isNotNull);
expect(error.errorType, isNotNull);
expect(
error.failingUrl?.startsWith('https://www.notawebsite..com'), isTrue);
});
testWidgets('onWebResourceError is not called with valid url',
(WidgetTester tester) async {
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final Completer<void> pageFinishCompleter = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl:
'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+',
onWebResourceError: (WebResourceError error) {
errorCompleter.complete(error);
},
onPageFinished: (_) => pageFinishCompleter.complete(),
),
),
);
expect(errorCompleter.future, doesNotComplete);
await pageFinishCompleter.future;
});
testWidgets(
'onWebResourceError only called for main frame',
(WidgetTester tester) async {
const String iframeTest = '''
<!DOCTYPE html>
<html>
<head>
<title>WebResourceError test</title>
</head>
<body>
<iframe src="https://notawebsite..com"></iframe>
</body>
</html>
''';
final String iframeTestBase64 =
base64Encode(const Utf8Encoder().convert(iframeTest));
final Completer<WebResourceError> errorCompleter =
Completer<WebResourceError>();
final Completer<void> pageFinishCompleter = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl:
'data:text/html;charset=utf-8;base64,$iframeTestBase64',
onWebResourceError: (WebResourceError error) {
errorCompleter.complete(error);
},
onPageFinished: (_) => pageFinishCompleter.complete(),
),
),
);
expect(errorCompleter.future, doesNotComplete);
await pageFinishCompleter.future;
},
);
testWidgets('can block requests', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final StreamController<String> pageLoads =
StreamController<String>.broadcast();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: blankPageEncoded,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) {
return (request.url.contains('youtube.com'))
? NavigationDecision.prevent
: NavigationDecision.navigate;
},
onPageFinished: (String url) => pageLoads.add(url),
),
),
);
await pageLoads.stream.first; // Wait for initial page load.
final WebViewController controller = await controllerCompleter.future;
await controller
.runJavascript('location.href = "https://www.youtube.com/"');
// There should never be any second page load, since our new URL is
// blocked. Still wait for a potential page change for some time in order
// to give the test a chance to fail.
await pageLoads.stream.first
.timeout(const Duration(milliseconds: 500), onTimeout: () => '');
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, isNot(contains('youtube.com')));
});
testWidgets('supports asynchronous decisions', (WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final StreamController<String> pageLoads =
StreamController<String>.broadcast();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: blankPageEncoded,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) async {
NavigationDecision decision = NavigationDecision.prevent;
decision = await Future<NavigationDecision>.delayed(
const Duration(milliseconds: 10),
() => NavigationDecision.navigate);
return decision;
},
onPageFinished: (String url) => pageLoads.add(url),
),
),
);
await pageLoads.stream.first; // Wait for initial page load.
final WebViewController controller = await controllerCompleter.future;
await controller.runJavascript('location.href = "$secondaryUrl"');
await pageLoads.stream.first; // Wait for second page to load.
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, secondaryUrl);
});
});
testWidgets('launches with gestureNavigationEnabled on iOS',
(WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: 400,
height: 300,
child: WebView(
key: GlobalKey(),
initialUrl: primaryUrl,
gestureNavigationEnabled: true,
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
),
),
),
);
final WebViewController controller = await controllerCompleter.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets('target _blank opens in same window',
(WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final Completer<void> pageLoaded = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
pageLoaded.complete(null);
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
await controller.runJavascript('window.open("$primaryUrl", "_blank")');
await pageLoaded.future;
final String? currentUrl = await controller.currentUrl();
expect(currentUrl, primaryUrl);
});
testWidgets(
'can open new window and go back',
(WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
Completer<void> pageLoaded = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
pageLoaded.complete();
},
initialUrl: primaryUrl,
),
),
);
final WebViewController controller = await controllerCompleter.future;
expect(controller.currentUrl(), completion(primaryUrl));
await pageLoaded.future;
pageLoaded = Completer<void>();
await controller.runJavascript('window.open("$secondaryUrl")');
await pageLoaded.future;
pageLoaded = Completer<void>();
expect(controller.currentUrl(), completion(secondaryUrl));
expect(controller.canGoBack(), completion(true));
await controller.goBack();
await pageLoaded.future;
await expectLater(controller.currentUrl(), completion(primaryUrl));
},
);
testWidgets(
'JavaScript does not run in parent window',
(WidgetTester tester) async {
const String iframe = '''
<!DOCTYPE html>
<script>
window.onload = () => {
window.open(`javascript:
var elem = document.createElement("p");
elem.innerHTML = "<b>Executed JS in parent origin: " + window.location.origin + "</b>";
document.body.append(elem);
`);
};
</script>
''';
final String iframeTestBase64 =
base64Encode(const Utf8Encoder().convert(iframe));
final String openWindowTest = '''
<!DOCTYPE html>
<html>
<head>
<title>XSS test</title>
</head>
<body>
<iframe
onload="window.iframeLoaded = true;"
src="data:text/html;charset=utf-8;base64,$iframeTestBase64"></iframe>
</body>
</html>
''';
final String openWindowTestBase64 =
base64Encode(const Utf8Encoder().convert(openWindowTest));
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
final Completer<void> pageLoadCompleter = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
javascriptMode: JavascriptMode.unrestricted,
initialUrl:
'data:text/html;charset=utf-8;base64,$openWindowTestBase64',
onPageFinished: (String url) {
pageLoadCompleter.complete();
},
),
),
);
final WebViewController controller = await controllerCompleter.future;
await pageLoadCompleter.future;
final String iframeLoaded =
await controller.runJavascriptReturningResult('iframeLoaded');
expect(iframeLoaded, 'true');
final String elementText = await controller.runJavascriptReturningResult(
'document.querySelector("p") && document.querySelector("p").textContent',
);
expect(elementText, 'null');
},
);
testWidgets(
'clearCache should clear local storage',
(WidgetTester tester) async {
final Completer<WebViewController> controllerCompleter =
Completer<WebViewController>();
Completer<void> pageLoadCompleter = Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: WebView(
key: GlobalKey(),
initialUrl: primaryUrl,
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (_) => pageLoadCompleter.complete(),
onWebViewCreated: (WebViewController controller) {
controllerCompleter.complete(controller);
},
),
),
);
await pageLoadCompleter.future;
pageLoadCompleter = Completer<void>();
final WebViewController controller = await controllerCompleter.future;
await controller.runJavascript('localStorage.setItem("myCat", "Tom");');
final String myCatItem = await controller.runJavascriptReturningResult(
'localStorage.getItem("myCat");',
);
expect(myCatItem, '"Tom"');
await controller.clearCache();
await pageLoadCompleter.future;
final String nullItem = await controller.runJavascriptReturningResult(
'localStorage.getItem("myCat");',
);
expect(nullItem, 'null');
},
);
}
// JavaScript booleans evaluate to different string values on Android and iOS.
// This utility method returns the string boolean value of the current platform.
String _webviewBool(bool value) {
if (defaultTargetPlatform == TargetPlatform.iOS) {
return value ? '1' : '0';
}
return value ? 'true' : 'false';
}
/// Returns the value used for the HTTP User-Agent: request header in subsequent HTTP requests.
Future<String> _getUserAgent(WebViewController controller) async {
return _runJavaScriptReturningResult(controller, 'navigator.userAgent;');
}
Future<String> _runJavaScriptReturningResult(
WebViewController controller,
String js,
) async {
return jsonDecode(await controller.runJavascriptReturningResult(js))
as String;
}
class ResizableWebView extends StatefulWidget {
const ResizableWebView({
Key? key,
required this.onResize,
required this.onPageFinished,
}) : super(key: key);
final JavascriptMessageHandler onResize;
final VoidCallback onPageFinished;
@override
State<StatefulWidget> createState() => ResizableWebViewState();
}
class ResizableWebViewState extends State<ResizableWebView> {
double webViewWidth = 200;
double webViewHeight = 200;
static const String resizePage = '''
<!DOCTYPE html><html>
<head><title>Resize test</title>
<script type="text/javascript">
function onResize() {
Resize.postMessage("resize");
}
function onLoad() {
window.onresize = onResize;
}
</script>
</head>
<body onload="onLoad();" bgColor="blue">
</body>
</html>
''';
@override
Widget build(BuildContext context) {
final String resizeTestBase64 =
base64Encode(const Utf8Encoder().convert(resizePage));
return Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
SizedBox(
width: webViewWidth,
height: webViewHeight,
child: WebView(
initialUrl:
'data:text/html;charset=utf-8;base64,$resizeTestBase64',
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Resize',
onMessageReceived: widget.onResize,
),
},
onPageFinished: (_) => widget.onPageFinished(),
javascriptMode: JavascriptMode.unrestricted,
),
),
TextButton(
key: const Key('resizeButton'),
onPressed: () {
setState(() {
webViewWidth += 100.0;
webViewHeight += 100.0;
});
},
child: const Text('ResizeButton'),
),
],
),
);
}
}
class CopyableObjectWithCallback with Copyable {
CopyableObjectWithCallback(this.callback);
final VoidCallback callback;
@override
CopyableObjectWithCallback copy() {
return CopyableObjectWithCallback(callback);
}
}
class ClassWithCallbackClass {
ClassWithCallbackClass() {
callbackClass = CopyableObjectWithCallback(
withWeakReferenceTo(
this,
(WeakReference<ClassWithCallbackClass> weakReference) {
return () {
// Weak reference to `this` in callback.
// ignore: unnecessary_statements
weakReference;
};
},
),
);
}
late final CopyableObjectWithCallback callbackClass;
}
| plugins/packages/webview_flutter/webview_flutter_android/example/integration_test/legacy/webview_flutter_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/example/integration_test/legacy/webview_flutter_test.dart",
"repo_id": "plugins",
"token_count": 23478
} | 1,190 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
// ignore: implementation_imports
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
import '../android_webview.dart';
import 'webview_android_widget.dart';
/// Builds an Android webview.
///
/// This is used as the default implementation for [WebView.platform] on Android. It uses
/// an [AndroidView] to embed the webview in the widget hierarchy, and uses a method channel to
/// communicate with the platform code.
class AndroidWebView implements WebViewPlatform {
@override
Widget build({
required BuildContext context,
required CreationParams creationParams,
required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
required JavascriptChannelRegistry javascriptChannelRegistry,
WebViewPlatformCreatedCallback? onWebViewPlatformCreated,
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers,
}) {
return WebViewAndroidWidget(
useHybridComposition: false,
creationParams: creationParams,
callbacksHandler: webViewPlatformCallbacksHandler,
javascriptChannelRegistry: javascriptChannelRegistry,
onBuildWidget: (WebViewAndroidPlatformController controller) {
return GestureDetector(
// We prevent text selection by intercepting the long press event.
// This is a temporary stop gap due to issues with text selection on Android:
// https://github.com/flutter/flutter/issues/24585 - the text selection
// dialog is not responding to touch events.
// https://github.com/flutter/flutter/issues/24584 - the text selection
// handles are not showing.
// TODO(amirh): remove this when the issues above are fixed.
onLongPress: () {},
excludeFromSemantics: true,
child: AndroidView(
viewType: 'plugins.flutter.io/webview',
onPlatformViewCreated: (int id) {
if (onWebViewPlatformCreated != null) {
onWebViewPlatformCreated(controller);
}
},
gestureRecognizers: gestureRecognizers,
layoutDirection:
Directionality.maybeOf(context) ?? TextDirection.rtl,
creationParams: JavaObject.globalInstanceManager
.getIdentifier(controller.webView),
creationParamsCodec: const StandardMessageCodec(),
),
);
},
);
}
@override
Future<bool> clearCookies() {
if (WebViewCookieManagerPlatform.instance == null) {
throw Exception(
'Could not clear cookies as no implementation for WebViewCookieManagerPlatform has been registered.');
}
return WebViewCookieManagerPlatform.instance!.clearCookies();
}
}
| plugins/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android.dart",
"repo_id": "plugins",
"token_count": 1084
} | 1,191 |
// Mocks generated by Mockito 5.3.2 from annotations
// in webview_flutter_android/test/android_webview_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i5;
import 'dart:typed_data' as _i7;
import 'dart:ui' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_android/src/android_webview.dart' as _i2;
import 'package:webview_flutter_android/src/android_webview.g.dart' as _i3;
import 'test_android_webview.g.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 _FakeDownloadListener_0 extends _i1.SmartFake
implements _i2.DownloadListener {
_FakeDownloadListener_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeJavaScriptChannel_1 extends _i1.SmartFake
implements _i2.JavaScriptChannel {
_FakeJavaScriptChannel_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebViewPoint_2 extends _i1.SmartFake implements _i3.WebViewPoint {
_FakeWebViewPoint_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebChromeClient_3 extends _i1.SmartFake
implements _i2.WebChromeClient {
_FakeWebChromeClient_3(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebSettings_4 extends _i1.SmartFake implements _i2.WebSettings {
_FakeWebSettings_4(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeOffset_5 extends _i1.SmartFake implements _i4.Offset {
_FakeOffset_5(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebView_6 extends _i1.SmartFake implements _i2.WebView {
_FakeWebView_6(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWebViewClient_7 extends _i1.SmartFake implements _i2.WebViewClient {
_FakeWebViewClient_7(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [CookieManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockCookieManagerHostApi extends _i1.Mock
implements _i3.CookieManagerHostApi {
MockCookieManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
_i5.Future<bool> clearCookies() => (super.noSuchMethod(
Invocation.method(
#clearCookies,
[],
),
returnValue: _i5.Future<bool>.value(false),
) as _i5.Future<bool>);
@override
_i5.Future<void> setCookie(
String? arg_url,
String? arg_value,
) =>
(super.noSuchMethod(
Invocation.method(
#setCookie,
[
arg_url,
arg_value,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
}
/// A class which mocks [DownloadListener].
///
/// See the documentation for Mockito's code generation for more information.
class MockDownloadListener extends _i1.Mock implements _i2.DownloadListener {
MockDownloadListener() {
_i1.throwOnMissingStub(this);
}
@override
void Function(
String,
String,
String,
String,
int,
) get onDownloadStart => (super.noSuchMethod(
Invocation.getter(#onDownloadStart),
returnValue: (
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
) {},
) as void Function(
String,
String,
String,
String,
int,
));
@override
_i2.DownloadListener copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeDownloadListener_0(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.DownloadListener);
}
/// A class which mocks [JavaScriptChannel].
///
/// See the documentation for Mockito's code generation for more information.
class MockJavaScriptChannel extends _i1.Mock implements _i2.JavaScriptChannel {
MockJavaScriptChannel() {
_i1.throwOnMissingStub(this);
}
@override
String get channelName => (super.noSuchMethod(
Invocation.getter(#channelName),
returnValue: '',
) as String);
@override
void Function(String) get postMessage => (super.noSuchMethod(
Invocation.getter(#postMessage),
returnValue: (String message) {},
) as void Function(String));
@override
_i2.JavaScriptChannel copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeJavaScriptChannel_1(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.JavaScriptChannel);
}
/// A class which mocks [TestDownloadListenerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestDownloadListenerHostApi extends _i1.Mock
implements _i6.TestDownloadListenerHostApi {
MockTestDownloadListenerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? instanceId) => super.noSuchMethod(
Invocation.method(
#create,
[instanceId],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestJavaObjectHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestJavaObjectHostApi extends _i1.Mock
implements _i6.TestJavaObjectHostApi {
MockTestJavaObjectHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void dispose(int? identifier) => super.noSuchMethod(
Invocation.method(
#dispose,
[identifier],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestJavaScriptChannelHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestJavaScriptChannelHostApi extends _i1.Mock
implements _i6.TestJavaScriptChannelHostApi {
MockTestJavaScriptChannelHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? instanceId,
String? channelName,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
instanceId,
channelName,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWebChromeClientHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWebChromeClientHostApi extends _i1.Mock
implements _i6.TestWebChromeClientHostApi {
MockTestWebChromeClientHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? instanceId) => super.noSuchMethod(
Invocation.method(
#create,
[instanceId],
),
returnValueForMissingStub: null,
);
@override
void setSynchronousReturnValueForOnShowFileChooser(
int? instanceId,
bool? value,
) =>
super.noSuchMethod(
Invocation.method(
#setSynchronousReturnValueForOnShowFileChooser,
[
instanceId,
value,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWebSettingsHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWebSettingsHostApi extends _i1.Mock
implements _i6.TestWebSettingsHostApi {
MockTestWebSettingsHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? instanceId,
int? webViewInstanceId,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
instanceId,
webViewInstanceId,
],
),
returnValueForMissingStub: null,
);
@override
void setDomStorageEnabled(
int? instanceId,
bool? flag,
) =>
super.noSuchMethod(
Invocation.method(
#setDomStorageEnabled,
[
instanceId,
flag,
],
),
returnValueForMissingStub: null,
);
@override
void setJavaScriptCanOpenWindowsAutomatically(
int? instanceId,
bool? flag,
) =>
super.noSuchMethod(
Invocation.method(
#setJavaScriptCanOpenWindowsAutomatically,
[
instanceId,
flag,
],
),
returnValueForMissingStub: null,
);
@override
void setSupportMultipleWindows(
int? instanceId,
bool? support,
) =>
super.noSuchMethod(
Invocation.method(
#setSupportMultipleWindows,
[
instanceId,
support,
],
),
returnValueForMissingStub: null,
);
@override
void setJavaScriptEnabled(
int? instanceId,
bool? flag,
) =>
super.noSuchMethod(
Invocation.method(
#setJavaScriptEnabled,
[
instanceId,
flag,
],
),
returnValueForMissingStub: null,
);
@override
void setUserAgentString(
int? instanceId,
String? userAgentString,
) =>
super.noSuchMethod(
Invocation.method(
#setUserAgentString,
[
instanceId,
userAgentString,
],
),
returnValueForMissingStub: null,
);
@override
void setMediaPlaybackRequiresUserGesture(
int? instanceId,
bool? require,
) =>
super.noSuchMethod(
Invocation.method(
#setMediaPlaybackRequiresUserGesture,
[
instanceId,
require,
],
),
returnValueForMissingStub: null,
);
@override
void setSupportZoom(
int? instanceId,
bool? support,
) =>
super.noSuchMethod(
Invocation.method(
#setSupportZoom,
[
instanceId,
support,
],
),
returnValueForMissingStub: null,
);
@override
void setLoadWithOverviewMode(
int? instanceId,
bool? overview,
) =>
super.noSuchMethod(
Invocation.method(
#setLoadWithOverviewMode,
[
instanceId,
overview,
],
),
returnValueForMissingStub: null,
);
@override
void setUseWideViewPort(
int? instanceId,
bool? use,
) =>
super.noSuchMethod(
Invocation.method(
#setUseWideViewPort,
[
instanceId,
use,
],
),
returnValueForMissingStub: null,
);
@override
void setDisplayZoomControls(
int? instanceId,
bool? enabled,
) =>
super.noSuchMethod(
Invocation.method(
#setDisplayZoomControls,
[
instanceId,
enabled,
],
),
returnValueForMissingStub: null,
);
@override
void setBuiltInZoomControls(
int? instanceId,
bool? enabled,
) =>
super.noSuchMethod(
Invocation.method(
#setBuiltInZoomControls,
[
instanceId,
enabled,
],
),
returnValueForMissingStub: null,
);
@override
void setAllowFileAccess(
int? instanceId,
bool? enabled,
) =>
super.noSuchMethod(
Invocation.method(
#setAllowFileAccess,
[
instanceId,
enabled,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWebStorageHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWebStorageHostApi extends _i1.Mock
implements _i6.TestWebStorageHostApi {
MockTestWebStorageHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? instanceId) => super.noSuchMethod(
Invocation.method(
#create,
[instanceId],
),
returnValueForMissingStub: null,
);
@override
void deleteAllData(int? instanceId) => super.noSuchMethod(
Invocation.method(
#deleteAllData,
[instanceId],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWebViewClientHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWebViewClientHostApi extends _i1.Mock
implements _i6.TestWebViewClientHostApi {
MockTestWebViewClientHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(int? instanceId) => super.noSuchMethod(
Invocation.method(
#create,
[instanceId],
),
returnValueForMissingStub: null,
);
@override
void setSynchronousReturnValueForShouldOverrideUrlLoading(
int? instanceId,
bool? value,
) =>
super.noSuchMethod(
Invocation.method(
#setSynchronousReturnValueForShouldOverrideUrlLoading,
[
instanceId,
value,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestWebViewHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestWebViewHostApi extends _i1.Mock
implements _i6.TestWebViewHostApi {
MockTestWebViewHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? instanceId,
bool? useHybridComposition,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
instanceId,
useHybridComposition,
],
),
returnValueForMissingStub: null,
);
@override
void loadData(
int? instanceId,
String? data,
String? mimeType,
String? encoding,
) =>
super.noSuchMethod(
Invocation.method(
#loadData,
[
instanceId,
data,
mimeType,
encoding,
],
),
returnValueForMissingStub: null,
);
@override
void loadDataWithBaseUrl(
int? instanceId,
String? baseUrl,
String? data,
String? mimeType,
String? encoding,
String? historyUrl,
) =>
super.noSuchMethod(
Invocation.method(
#loadDataWithBaseUrl,
[
instanceId,
baseUrl,
data,
mimeType,
encoding,
historyUrl,
],
),
returnValueForMissingStub: null,
);
@override
void loadUrl(
int? instanceId,
String? url,
Map<String?, String?>? headers,
) =>
super.noSuchMethod(
Invocation.method(
#loadUrl,
[
instanceId,
url,
headers,
],
),
returnValueForMissingStub: null,
);
@override
void postUrl(
int? instanceId,
String? url,
_i7.Uint8List? data,
) =>
super.noSuchMethod(
Invocation.method(
#postUrl,
[
instanceId,
url,
data,
],
),
returnValueForMissingStub: null,
);
@override
String? getUrl(int? instanceId) => (super.noSuchMethod(Invocation.method(
#getUrl,
[instanceId],
)) as String?);
@override
bool canGoBack(int? instanceId) => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[instanceId],
),
returnValue: false,
) as bool);
@override
bool canGoForward(int? instanceId) => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[instanceId],
),
returnValue: false,
) as bool);
@override
void goBack(int? instanceId) => super.noSuchMethod(
Invocation.method(
#goBack,
[instanceId],
),
returnValueForMissingStub: null,
);
@override
void goForward(int? instanceId) => super.noSuchMethod(
Invocation.method(
#goForward,
[instanceId],
),
returnValueForMissingStub: null,
);
@override
void reload(int? instanceId) => super.noSuchMethod(
Invocation.method(
#reload,
[instanceId],
),
returnValueForMissingStub: null,
);
@override
void clearCache(
int? instanceId,
bool? includeDiskFiles,
) =>
super.noSuchMethod(
Invocation.method(
#clearCache,
[
instanceId,
includeDiskFiles,
],
),
returnValueForMissingStub: null,
);
@override
_i5.Future<String?> evaluateJavascript(
int? instanceId,
String? javascriptString,
) =>
(super.noSuchMethod(
Invocation.method(
#evaluateJavascript,
[
instanceId,
javascriptString,
],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
String? getTitle(int? instanceId) => (super.noSuchMethod(Invocation.method(
#getTitle,
[instanceId],
)) as String?);
@override
void scrollTo(
int? instanceId,
int? x,
int? y,
) =>
super.noSuchMethod(
Invocation.method(
#scrollTo,
[
instanceId,
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
void scrollBy(
int? instanceId,
int? x,
int? y,
) =>
super.noSuchMethod(
Invocation.method(
#scrollBy,
[
instanceId,
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
int getScrollX(int? instanceId) => (super.noSuchMethod(
Invocation.method(
#getScrollX,
[instanceId],
),
returnValue: 0,
) as int);
@override
int getScrollY(int? instanceId) => (super.noSuchMethod(
Invocation.method(
#getScrollY,
[instanceId],
),
returnValue: 0,
) as int);
@override
_i3.WebViewPoint getScrollPosition(int? instanceId) => (super.noSuchMethod(
Invocation.method(
#getScrollPosition,
[instanceId],
),
returnValue: _FakeWebViewPoint_2(
this,
Invocation.method(
#getScrollPosition,
[instanceId],
),
),
) as _i3.WebViewPoint);
@override
void setWebContentsDebuggingEnabled(bool? enabled) => super.noSuchMethod(
Invocation.method(
#setWebContentsDebuggingEnabled,
[enabled],
),
returnValueForMissingStub: null,
);
@override
void setWebViewClient(
int? instanceId,
int? webViewClientInstanceId,
) =>
super.noSuchMethod(
Invocation.method(
#setWebViewClient,
[
instanceId,
webViewClientInstanceId,
],
),
returnValueForMissingStub: null,
);
@override
void addJavaScriptChannel(
int? instanceId,
int? javaScriptChannelInstanceId,
) =>
super.noSuchMethod(
Invocation.method(
#addJavaScriptChannel,
[
instanceId,
javaScriptChannelInstanceId,
],
),
returnValueForMissingStub: null,
);
@override
void removeJavaScriptChannel(
int? instanceId,
int? javaScriptChannelInstanceId,
) =>
super.noSuchMethod(
Invocation.method(
#removeJavaScriptChannel,
[
instanceId,
javaScriptChannelInstanceId,
],
),
returnValueForMissingStub: null,
);
@override
void setDownloadListener(
int? instanceId,
int? listenerInstanceId,
) =>
super.noSuchMethod(
Invocation.method(
#setDownloadListener,
[
instanceId,
listenerInstanceId,
],
),
returnValueForMissingStub: null,
);
@override
void setWebChromeClient(
int? instanceId,
int? clientInstanceId,
) =>
super.noSuchMethod(
Invocation.method(
#setWebChromeClient,
[
instanceId,
clientInstanceId,
],
),
returnValueForMissingStub: null,
);
@override
void setBackgroundColor(
int? instanceId,
int? color,
) =>
super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[
instanceId,
color,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestAssetManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestAssetManagerHostApi extends _i1.Mock
implements _i6.TestAssetManagerHostApi {
MockTestAssetManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
List<String?> list(String? path) => (super.noSuchMethod(
Invocation.method(
#list,
[path],
),
returnValue: <String?>[],
) as List<String?>);
@override
String getAssetFilePathByName(String? name) => (super.noSuchMethod(
Invocation.method(
#getAssetFilePathByName,
[name],
),
returnValue: '',
) as String);
}
/// A class which mocks [WebChromeClient].
///
/// See the documentation for Mockito's code generation for more information.
class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient {
MockWebChromeClient() {
_i1.throwOnMissingStub(this);
}
@override
_i5.Future<void> setSynchronousReturnValueForOnShowFileChooser(bool? value) =>
(super.noSuchMethod(
Invocation.method(
#setSynchronousReturnValueForOnShowFileChooser,
[value],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i2.WebChromeClient copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWebChromeClient_3(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WebChromeClient);
}
/// A class which mocks [WebView].
///
/// See the documentation for Mockito's code generation for more information.
class MockWebView extends _i1.Mock implements _i2.WebView {
MockWebView() {
_i1.throwOnMissingStub(this);
}
@override
bool get useHybridComposition => (super.noSuchMethod(
Invocation.getter(#useHybridComposition),
returnValue: false,
) as bool);
@override
_i2.WebSettings get settings => (super.noSuchMethod(
Invocation.getter(#settings),
returnValue: _FakeWebSettings_4(
this,
Invocation.getter(#settings),
),
) as _i2.WebSettings);
@override
_i5.Future<void> loadData({
required String? data,
String? mimeType,
String? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadData,
[],
{
#data: data,
#mimeType: mimeType,
#encoding: encoding,
},
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> loadDataWithBaseUrl({
String? baseUrl,
required String? data,
String? mimeType,
String? encoding,
String? historyUrl,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadDataWithBaseUrl,
[],
{
#baseUrl: baseUrl,
#data: data,
#mimeType: mimeType,
#encoding: encoding,
#historyUrl: historyUrl,
},
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> loadUrl(
String? url,
Map<String, String>? headers,
) =>
(super.noSuchMethod(
Invocation.method(
#loadUrl,
[
url,
headers,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> postUrl(
String? url,
_i7.Uint8List? data,
) =>
(super.noSuchMethod(
Invocation.method(
#postUrl,
[
url,
data,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<String?> getUrl() => (super.noSuchMethod(
Invocation.method(
#getUrl,
[],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
_i5.Future<bool> canGoBack() => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[],
),
returnValue: _i5.Future<bool>.value(false),
) as _i5.Future<bool>);
@override
_i5.Future<bool> canGoForward() => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[],
),
returnValue: _i5.Future<bool>.value(false),
) as _i5.Future<bool>);
@override
_i5.Future<void> goBack() => (super.noSuchMethod(
Invocation.method(
#goBack,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> goForward() => (super.noSuchMethod(
Invocation.method(
#goForward,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> reload() => (super.noSuchMethod(
Invocation.method(
#reload,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> clearCache(bool? includeDiskFiles) => (super.noSuchMethod(
Invocation.method(
#clearCache,
[includeDiskFiles],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<String?> evaluateJavascript(String? javascriptString) =>
(super.noSuchMethod(
Invocation.method(
#evaluateJavascript,
[javascriptString],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
_i5.Future<String?> getTitle() => (super.noSuchMethod(
Invocation.method(
#getTitle,
[],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
_i5.Future<void> scrollTo(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollTo,
[
x,
y,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> scrollBy(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollBy,
[
x,
y,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<int> getScrollX() => (super.noSuchMethod(
Invocation.method(
#getScrollX,
[],
),
returnValue: _i5.Future<int>.value(0),
) as _i5.Future<int>);
@override
_i5.Future<int> getScrollY() => (super.noSuchMethod(
Invocation.method(
#getScrollY,
[],
),
returnValue: _i5.Future<int>.value(0),
) as _i5.Future<int>);
@override
_i5.Future<_i4.Offset> getScrollPosition() => (super.noSuchMethod(
Invocation.method(
#getScrollPosition,
[],
),
returnValue: _i5.Future<_i4.Offset>.value(_FakeOffset_5(
this,
Invocation.method(
#getScrollPosition,
[],
),
)),
) as _i5.Future<_i4.Offset>);
@override
_i5.Future<void> setWebViewClient(_i2.WebViewClient? webViewClient) =>
(super.noSuchMethod(
Invocation.method(
#setWebViewClient,
[webViewClient],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> addJavaScriptChannel(
_i2.JavaScriptChannel? javaScriptChannel) =>
(super.noSuchMethod(
Invocation.method(
#addJavaScriptChannel,
[javaScriptChannel],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> removeJavaScriptChannel(
_i2.JavaScriptChannel? javaScriptChannel) =>
(super.noSuchMethod(
Invocation.method(
#removeJavaScriptChannel,
[javaScriptChannel],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setDownloadListener(_i2.DownloadListener? listener) =>
(super.noSuchMethod(
Invocation.method(
#setDownloadListener,
[listener],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setWebChromeClient(_i2.WebChromeClient? client) =>
(super.noSuchMethod(
Invocation.method(
#setWebChromeClient,
[client],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setBackgroundColor(_i4.Color? color) => (super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[color],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i2.WebView copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWebView_6(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WebView);
}
/// A class which mocks [WebViewClient].
///
/// See the documentation for Mockito's code generation for more information.
class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient {
MockWebViewClient() {
_i1.throwOnMissingStub(this);
}
@override
_i5.Future<void> setSynchronousReturnValueForShouldOverrideUrlLoading(
bool? value) =>
(super.noSuchMethod(
Invocation.method(
#setSynchronousReturnValueForShouldOverrideUrlLoading,
[value],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i2.WebViewClient copy() => (super.noSuchMethod(
Invocation.method(
#copy,
[],
),
returnValue: _FakeWebViewClient_7(
this,
Invocation.method(
#copy,
[],
),
),
) as _i2.WebViewClient);
}
| plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_test.mocks.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/test/android_webview_test.mocks.dart",
"repo_id": "plugins",
"token_count": 15737
} | 1,192 |
name: webview_flutter_platform_interface
description: A common platform interface for the webview_flutter plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/webview_flutter/webview_flutter_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview_flutter%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.1
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
meta: ^1.7.0
plugin_platform_interface: ^2.1.0
dev_dependencies:
build_runner: ^2.1.8
flutter_test:
sdk: flutter
mockito: ^5.0.0
| plugins/packages/webview_flutter/webview_flutter_platform_interface/pubspec.yaml/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/pubspec.yaml",
"repo_id": "plugins",
"token_count": 294
} | 1,193 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Class to represent a content-type header value.
class ContentType {
/// Creates a [ContentType] instance by parsing a "content-type" response [header].
///
/// See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
/// See: https://httpwg.org/specs/rfc9110.html#media.type
ContentType.parse(String header) {
final Iterable<String> chunks =
header.split(';').map((String e) => e.trim().toLowerCase());
for (final String chunk in chunks) {
if (!chunk.contains('=')) {
_mimeType = chunk;
} else {
final List<String> bits =
chunk.split('=').map((String e) => e.trim()).toList();
assert(bits.length == 2);
switch (bits[0]) {
case 'charset':
_charset = bits[1];
break;
case 'boundary':
_boundary = bits[1];
break;
default:
throw StateError('Unable to parse "$chunk" in content-type.');
}
}
}
}
String? _mimeType;
String? _charset;
String? _boundary;
/// The MIME-type of the resource or the data.
String? get mimeType => _mimeType;
/// The character encoding standard.
String? get charset => _charset;
/// The separation boundary for multipart entities.
String? get boundary => _boundary;
}
| plugins/packages/webview_flutter/webview_flutter_web/lib/src/content_type.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_web/lib/src/content_type.dart",
"repo_id": "plugins",
"token_count": 593
} | 1,194 |
// Copyright 2013 The Flutter 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 "FWFUIDelegateHostApi.h"
#import "FWFDataConverters.h"
@interface FWFUIDelegateFlutterApiImpl ()
// BinaryMessenger must be weak to prevent a circular reference with the host API it
// references.
@property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger;
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFUIDelegateFlutterApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self initWithBinaryMessenger:binaryMessenger];
if (self) {
_binaryMessenger = binaryMessenger;
_instanceManager = instanceManager;
_webViewConfigurationFlutterApi =
[[FWFWebViewConfigurationFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager];
}
return self;
}
- (long)identifierForDelegate:(FWFUIDelegate *)instance {
return [self.instanceManager identifierWithStrongReferenceForInstance:instance];
}
- (void)onCreateWebViewForDelegate:(FWFUIDelegate *)instance
webView:(WKWebView *)webView
configuration:(WKWebViewConfiguration *)configuration
navigationAction:(WKNavigationAction *)navigationAction
completion:(void (^)(NSError *_Nullable))completion {
if (![self.instanceManager containsInstance:configuration]) {
[self.webViewConfigurationFlutterApi createWithConfiguration:configuration
completion:^(NSError *error) {
NSAssert(!error, @"%@", error);
}];
}
NSNumber *configurationIdentifier =
@([self.instanceManager identifierWithStrongReferenceForInstance:configuration]);
FWFWKNavigationActionData *navigationActionData =
FWFWKNavigationActionDataFromNavigationAction(navigationAction);
[self onCreateWebViewForDelegateWithIdentifier:@([self identifierForDelegate:instance])
webViewIdentifier:
@([self.instanceManager
identifierWithStrongReferenceForInstance:webView])
configurationIdentifier:configurationIdentifier
navigationAction:navigationActionData
completion:completion];
}
@end
@implementation FWFUIDelegate
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [super initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager];
if (self) {
_UIDelegateAPI = [[FWFUIDelegateFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager];
}
return self;
}
- (WKWebView *)webView:(WKWebView *)webView
createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
forNavigationAction:(WKNavigationAction *)navigationAction
windowFeatures:(WKWindowFeatures *)windowFeatures {
[self.UIDelegateAPI onCreateWebViewForDelegate:self
webView:webView
configuration:configuration
navigationAction:navigationAction
completion:^(NSError *error) {
NSAssert(!error, @"%@", error);
}];
return nil;
}
@end
@interface FWFUIDelegateHostApiImpl ()
// BinaryMessenger must be weak to prevent a circular reference with the host API it
// references.
@property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger;
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFUIDelegateHostApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_binaryMessenger = binaryMessenger;
_instanceManager = instanceManager;
}
return self;
}
- (FWFUIDelegate *)delegateForIdentifier:(NSNumber *)identifier {
return (FWFUIDelegate *)[self.instanceManager instanceForIdentifier:identifier.longValue];
}
- (void)createWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable *_Nonnull)error {
FWFUIDelegate *uIDelegate = [[FWFUIDelegate alloc] initWithBinaryMessenger:self.binaryMessenger
instanceManager:self.instanceManager];
[self.instanceManager addDartCreatedInstance:uIDelegate withIdentifier:identifier.longValue];
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIDelegateHostApi.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIDelegateHostApi.m",
"repo_id": "plugins",
"token_count": 2258
} | 1,195 |
// Copyright 2013 The Flutter 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart';
import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart';
import 'package:webview_flutter_wkwebview/src/webkit_proxy.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
import 'webkit_navigation_delegate_test.mocks.dart';
@GenerateMocks(<Type>[WKWebView])
void main() {
WidgetsFlutterBinding.ensureInitialized();
group('WebKitNavigationDelegate', () {
test('WebKitNavigationDelegate uses params field in constructor', () async {
await runZonedGuarded(
() async => WebKitNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
),
(Object error, __) {
expect(error, isNot(isA<TypeError>()));
},
);
});
test('setOnPageFinished', () {
final WebKitNavigationDelegate webKitDelgate = WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: CapturingUIDelegate.new,
),
),
);
late final String callbackUrl;
webKitDelgate.setOnPageFinished((String url) => callbackUrl = url);
CapturingNavigationDelegate.lastCreatedDelegate.didFinishNavigation!(
WKWebView.detached(),
'https://www.google.com',
);
expect(callbackUrl, 'https://www.google.com');
});
test('setOnPageStarted', () {
final WebKitNavigationDelegate webKitDelgate = WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: CapturingUIDelegate.new,
),
),
);
late final String callbackUrl;
webKitDelgate.setOnPageStarted((String url) => callbackUrl = url);
CapturingNavigationDelegate
.lastCreatedDelegate.didStartProvisionalNavigation!(
WKWebView.detached(),
'https://www.google.com',
);
expect(callbackUrl, 'https://www.google.com');
});
test('onWebResourceError from didFailNavigation', () {
final WebKitNavigationDelegate webKitDelgate = WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: CapturingUIDelegate.new,
),
),
);
late final WebKitWebResourceError callbackError;
void onWebResourceError(WebResourceError error) {
callbackError = error as WebKitWebResourceError;
}
webKitDelgate.setOnWebResourceError(onWebResourceError);
CapturingNavigationDelegate.lastCreatedDelegate.didFailNavigation!(
WKWebView.detached(),
const NSError(
code: WKErrorCode.webViewInvalidated,
domain: 'domain',
localizedDescription: 'my desc',
),
);
expect(callbackError.description, 'my desc');
expect(callbackError.errorCode, WKErrorCode.webViewInvalidated);
expect(callbackError.domain, 'domain');
expect(callbackError.errorType, WebResourceErrorType.webViewInvalidated);
expect(callbackError.isForMainFrame, true);
});
test('onWebResourceError from didFailProvisionalNavigation', () {
final WebKitNavigationDelegate webKitDelgate = WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: CapturingUIDelegate.new,
),
),
);
late final WebKitWebResourceError callbackError;
void onWebResourceError(WebResourceError error) {
callbackError = error as WebKitWebResourceError;
}
webKitDelgate.setOnWebResourceError(onWebResourceError);
CapturingNavigationDelegate
.lastCreatedDelegate.didFailProvisionalNavigation!(
WKWebView.detached(),
const NSError(
code: WKErrorCode.webViewInvalidated,
domain: 'domain',
localizedDescription: 'my desc',
),
);
expect(callbackError.description, 'my desc');
expect(callbackError.errorCode, WKErrorCode.webViewInvalidated);
expect(callbackError.domain, 'domain');
expect(callbackError.errorType, WebResourceErrorType.webViewInvalidated);
expect(callbackError.isForMainFrame, true);
});
test('onWebResourceError from webViewWebContentProcessDidTerminate', () {
final WebKitNavigationDelegate webKitDelgate = WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: CapturingUIDelegate.new,
),
),
);
late final WebKitWebResourceError callbackError;
void onWebResourceError(WebResourceError error) {
callbackError = error as WebKitWebResourceError;
}
webKitDelgate.setOnWebResourceError(onWebResourceError);
CapturingNavigationDelegate
.lastCreatedDelegate.webViewWebContentProcessDidTerminate!(
WKWebView.detached(),
);
expect(callbackError.description, '');
expect(callbackError.errorCode, WKErrorCode.webContentProcessTerminated);
expect(callbackError.domain, 'WKErrorDomain');
expect(
callbackError.errorType,
WebResourceErrorType.webContentProcessTerminated,
);
expect(callbackError.isForMainFrame, true);
});
test('onNavigationRequest from decidePolicyForNavigationAction', () {
final WebKitNavigationDelegate webKitDelgate = WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: CapturingUIDelegate.new,
),
),
);
late final NavigationRequest callbackRequest;
FutureOr<NavigationDecision> onNavigationRequest(
NavigationRequest request) {
callbackRequest = request;
return NavigationDecision.navigate;
}
webKitDelgate.setOnNavigationRequest(onNavigationRequest);
expect(
CapturingNavigationDelegate
.lastCreatedDelegate.decidePolicyForNavigationAction!(
WKWebView.detached(),
const WKNavigationAction(
request: NSUrlRequest(url: 'https://www.google.com'),
targetFrame: WKFrameInfo(isMainFrame: false),
navigationType: WKNavigationType.linkActivated,
),
),
completion(WKNavigationActionPolicy.allow),
);
expect(callbackRequest.url, 'https://www.google.com');
expect(callbackRequest.isMainFrame, isFalse);
});
test('Requests to open a new window loads request in same window', () {
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: CapturingUIDelegate.new,
),
),
);
final MockWKWebView mockWebView = MockWKWebView();
const NSUrlRequest request = NSUrlRequest(url: 'https://www.google.com');
CapturingUIDelegate.lastCreatedDelegate.onCreateWebView!(
mockWebView,
WKWebViewConfiguration.detached(),
const WKNavigationAction(
request: request,
targetFrame: WKFrameInfo(isMainFrame: false),
navigationType: WKNavigationType.linkActivated,
),
);
verify(mockWebView.loadRequest(request));
});
});
}
// Records the last created instance of itself.
class CapturingNavigationDelegate extends WKNavigationDelegate {
CapturingNavigationDelegate({
super.didFinishNavigation,
super.didStartProvisionalNavigation,
super.didFailNavigation,
super.didFailProvisionalNavigation,
super.decidePolicyForNavigationAction,
super.webViewWebContentProcessDidTerminate,
}) : super.detached() {
lastCreatedDelegate = this;
}
static CapturingNavigationDelegate lastCreatedDelegate =
CapturingNavigationDelegate();
}
// Records the last created instance of itself.
class CapturingUIDelegate extends WKUIDelegate {
CapturingUIDelegate({super.onCreateWebView}) : super.detached() {
lastCreatedDelegate = this;
}
static CapturingUIDelegate lastCreatedDelegate = CapturingUIDelegate();
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_navigation_delegate_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_navigation_delegate_test.dart",
"repo_id": "plugins",
"token_count": 3578
} | 1,196 |
// Copyright 2013 The Flutter 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:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'analyze_command.dart';
import 'common/core.dart';
void main(List<String> args) {
print('''
*** WARNING ***
This copy of the tooling is now only here as a shim for scripts in other
repositories that have not yet been updated, and can only run 'analyze'. For
full tooling in this repository, see the updated instructions:
https://github.com/flutter/packages/blob/main/script/tool/README.md
to switch to running the published version.
''');
const FileSystem fileSystem = LocalFileSystem();
Directory packagesDir =
fileSystem.currentDirectory.childDirectory('packages');
if (!packagesDir.existsSync()) {
if (fileSystem.currentDirectory.basename == 'packages') {
packagesDir = fileSystem.currentDirectory;
} else {
print('Error: Cannot find a "packages" sub-directory');
io.exit(1);
}
}
final CommandRunner<void> commandRunner = CommandRunner<void>(
'dart pub global run flutter_plugin_tools',
'Productivity utils for hosting multiple plugins within one repository.')
..addCommand(AnalyzeCommand(packagesDir));
commandRunner.run(args).catchError((Object e) {
final ToolExit toolExit = e as ToolExit;
int exitCode = toolExit.exitCode;
// This should never happen; this check is here to guarantee that a ToolExit
// never accidentally has code 0 thus causing CI to pass.
if (exitCode == 0) {
assert(false);
exitCode = 255;
}
io.exit(exitCode);
}, test: (Object e) => e is ToolExit);
}
| plugins/script/tool/lib/src/main.dart/0 | {
"file_path": "plugins/script/tool/lib/src/main.dart",
"repo_id": "plugins",
"token_count": 572
} | 1,197 |
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
| samples/add_to_app/books/android_books/gradlew.bat/0 | {
"file_path": "samples/add_to_app/books/android_books/gradlew.bat",
"repo_id": "samples",
"token_count": 777
} | 1,198 |
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
flutter_application_path = '../flutter_module_books/'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'IosBooks' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for IosBooks
install_all_flutter_pods(flutter_application_path)
end
post_install do |installer|
flutter_post_install(installer) if defined?(flutter_post_install)
end
| samples/add_to_app/books/ios_books/Podfile/0 | {
"file_path": "samples/add_to_app/books/ios_books/Podfile",
"repo_id": "samples",
"token_count": 169
} | 1,199 |
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
flutter_application_path = '../flutter_module'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'IOSFullScreen' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for IOSFullScreen
install_all_flutter_pods(flutter_application_path)
target 'IOSFullScreenTests' do
inherit! :search_paths
# Pods for testing
end
target 'IOSFullScreenUITests' do
inherit! :search_paths
# Pods for testing
end
end
post_install do |installer|
flutter_post_install(installer) if defined?(flutter_post_install)
end
| samples/add_to_app/fullscreen/ios_fullscreen/Podfile/0 | {
"file_path": "samples/add_to_app/fullscreen/ios_fullscreen/Podfile",
"repo_id": "samples",
"token_count": 240
} | 1,200 |
<resources>
<string name="app_name">Multiple Flutters</string>
</resources> | samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/res/values/strings.xml/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/res/values/strings.xml",
"repo_id": "samples",
"token_count": 25
} | 1,201 |
include: package:analysis_defaults/flutter.yaml | samples/add_to_app/multiple_flutters/multiple_flutters_module/analysis_options.yaml/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_module/analysis_options.yaml",
"repo_id": "samples",
"token_count": 14
} | 1,202 |
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
flutter_application_path = '../flutter_module_using_plugin'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'IOSUsingPlugin' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for IOSUsingPlugin
install_all_flutter_pods(flutter_application_path)
target 'IOSUsingPluginTests' do
inherit! :search_paths
# Pods for testing
end
target 'IOSUsingPluginUITests' do
inherit! :search_paths
# Pods for testing
end
end
post_install do |installer|
flutter_post_install(installer) if defined?(flutter_post_install)
end
| samples/add_to_app/plugin/ios_using_plugin/Podfile/0 | {
"file_path": "samples/add_to_app/plugin/ios_using_plugin/Podfile",
"repo_id": "samples",
"token_count": 243
} | 1,203 |
include: package:analysis_defaults/flutter.yaml
| samples/android_splash_screen/analysis_options.yaml/0 | {
"file_path": "samples/android_splash_screen/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,204 |
include: package:analysis_defaults/flutter.yaml
| samples/animations/analysis_options.yaml/0 | {
"file_path": "samples/animations/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,205 |
#import "GeneratedPluginRegistrant.h"
| samples/animations/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/animations/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,206 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
class CarouselDemo extends StatelessWidget {
CarouselDemo({super.key});
static String routeName = 'misc/carousel';
static const List<String> fileNames = [
'assets/eat_cape_town_sm.jpg',
'assets/eat_new_orleans_sm.jpg',
'assets/eat_sydney_sm.jpg',
];
final List<Widget> images =
fileNames.map((file) => Image.asset(file, fit: BoxFit.cover)).toList();
@override
Widget build(context) {
return Scaffold(
appBar: AppBar(
title: const Text('Carousel Demo'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: AspectRatio(
aspectRatio: 1,
child: Carousel(itemBuilder: widgetBuilder),
),
),
),
);
}
Widget widgetBuilder(BuildContext context, int index) {
return images[index % images.length];
}
}
typedef OnCurrentItemChangedCallback = void Function(int currentItem);
class Carousel extends StatefulWidget {
final IndexedWidgetBuilder itemBuilder;
const Carousel({super.key, required this.itemBuilder});
@override
State<Carousel> createState() => _CarouselState();
}
class _CarouselState extends State<Carousel> {
late final PageController _controller;
late int _currentPage;
bool _pageHasChanged = false;
@override
void initState() {
super.initState();
_currentPage = 0;
_controller = PageController(
viewportFraction: .85,
initialPage: _currentPage,
);
}
@override
Widget build(context) {
var size = MediaQuery.of(context).size;
return PageView.builder(
onPageChanged: (value) {
setState(() {
_pageHasChanged = true;
_currentPage = value;
});
},
controller: _controller,
scrollBehavior: ScrollConfiguration.of(context).copyWith(
dragDevices: {
ui.PointerDeviceKind.touch,
ui.PointerDeviceKind.mouse,
},
),
itemBuilder: (context, index) => AnimatedBuilder(
animation: _controller,
builder: (context, child) {
var result = _pageHasChanged ? _controller.page! : _currentPage * 1.0;
// The horizontal position of the page between a 1 and 0
var value = result - index;
value = (1 - (value.abs() * .5)).clamp(0.0, 1.0);
return Center(
child: SizedBox(
height: Curves.easeOut.transform(value) * size.height,
width: Curves.easeOut.transform(value) * size.width,
child: child,
),
);
},
child: widget.itemBuilder(context, index),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
| samples/animations/lib/src/misc/carousel.dart/0 | {
"file_path": "samples/animations/lib/src/misc/carousel.dart",
"repo_id": "samples",
"token_count": 1217
} | 1,207 |
// Copyright 2023 The Flutter team. 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:animations/src/basics/basics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
Widget createAnimatedBuilderDemoScreen() => const MaterialApp(
home: AnimatedBuilderDemo(),
);
void main() {
group('AnimatedBuilder Tests', () {
testWidgets('AnimatedBuilder changes button color', (tester) async {
await tester.pumpWidget(createAnimatedBuilderDemoScreen());
// Get the initial color of the button.
ElevatedButton button = tester.widget(find.byType(ElevatedButton));
MaterialStateProperty<Color?>? initialColor =
button.style!.backgroundColor;
// Tap the button.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// Get the updated color of the button.
button = tester.widget(find.byType(ElevatedButton));
MaterialStateProperty<Color?>? updatedColor =
button.style!.backgroundColor;
// Check if the color has changed.
expect(initialColor, isNot(updatedColor));
});
testWidgets('AnimatedBuilder animates button color', (tester) async {
await tester.pumpWidget(createAnimatedBuilderDemoScreen());
// Get the initial color of the button.
ElevatedButton button = tester.widget(find.byType(ElevatedButton));
MaterialStateProperty<Color?>? initialColor =
button.style!.backgroundColor;
// Tap the button to trigger the animation but don't wait for it to finish.
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
// Check that the color has changed but not to the final color.
button = tester.widget(find.byType(ElevatedButton));
MaterialStateProperty<Color?>? changedColor =
button.style!.backgroundColor;
expect(initialColor, isNot(changedColor));
// Wait for the animation to finish.
await tester.pump(const Duration(milliseconds: 400));
// Check that the color has changed to the final color.
button = tester.widget(find.byType(ElevatedButton));
MaterialStateProperty<Color?>? finalColor = button.style!.backgroundColor;
expect(changedColor, isNot(finalColor));
});
});
}
| samples/animations/test/basics/animated_builder_test.dart/0 | {
"file_path": "samples/animations/test/basics/animated_builder_test.dart",
"repo_id": "samples",
"token_count": 842
} | 1,208 |
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart';
import 'package:test/test.dart';
// Manual test:
// $ dart bin/server.dart
// $ curl -X POST -d '{"by": 1}' -H "Content-Type: application/json" localhost:8080/
void main() {
final port = '8080';
final host = 'http://0.0.0.0:$port';
late Process p;
group(
'Integration test should',
() {
setUp(() async {
p = await Process.start(
'dart',
['run', 'bin/server.dart'],
environment: {'PORT': port},
);
// Wait for server to start and print to stdout.
await p.stdout.first;
});
tearDown(() => p.kill());
test('Increment', () async {
final response = await post(Uri.parse('$host/'), body: '{"by": 1}');
expect(response.statusCode, 200);
expect(response.body, '{"value":1}');
});
test('Get', () async {
final response = await get(Uri.parse('$host/'));
expect(response.statusCode, 200);
final resp = json.decode(response.body) as Map;
expect(resp.containsKey('value'), true);
});
},
onPlatform: <String, dynamic>{
'windows': [
Skip('Failing on Windows CI'),
]
},
);
}
| samples/code_sharing/server/test/server_test.dart/0 | {
"file_path": "samples/code_sharing/server/test/server_test.dart",
"repo_id": "samples",
"token_count": 555
} | 1,209 |
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'platform_selector.dart';
class DefaultValuesPage extends StatelessWidget {
DefaultValuesPage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'default-values';
static const String title = 'Default API Values Example';
static const String subtitle =
'Shows what happens when you pass various things into contextMenuBuilder.';
final PlatformCallback onChangedPlatform;
final TextEditingController _controllerNone = TextEditingController(
text: "When contextMenuBuilder isn't given anything at all.",
);
final TextEditingController _controllerNull = TextEditingController(
text: "When contextMenuBuilder is explicitly given null.",
);
final TextEditingController _controllerCustom = TextEditingController(
text: "When something custom is passed to contextMenuBuilder.",
);
static const String url = '$kCodeUrl/default_values_page.dart';
DialogRoute _showDialog(BuildContext context, String message) {
return DialogRoute<void>(
context: context,
builder: (context) => AlertDialog(title: Text(message)),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(DefaultValuesPage.title),
actions: <Widget>[
PlatformSelector(
onChangedPlatform: onChangedPlatform,
),
IconButton(
icon: const Icon(Icons.code),
onPressed: () async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
),
],
),
body: Center(
child: SizedBox(
width: 400.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'This example simply shows what happens when contextMenuBuilder is given null, a custom value, or omitted altogether.',
),
const SizedBox(
height: 40.0,
),
TextField(
maxLines: 2,
minLines: 2,
controller: _controllerNone,
),
TextField(
maxLines: 2,
minLines: 2,
controller: _controllerNull,
contextMenuBuilder: null,
),
TextField(
maxLines: 2,
minLines: 2,
controller: _controllerCustom,
contextMenuBuilder: (context, editableTextState) {
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: editableTextState.contextMenuAnchors,
buttonItems: <ContextMenuButtonItem>[
ContextMenuButtonItem(
label: 'Custom button',
onPressed: () {
ContextMenuController.removeAny();
Navigator.of(context).push(_showDialog(
context, 'You clicked the custom button.'));
},
),
...editableTextState.contextMenuButtonItems,
],
);
},
),
],
),
),
),
);
}
}
| samples/context_menus/lib/default_values_page.dart/0 | {
"file_path": "samples/context_menus/lib/default_values_page.dart",
"repo_id": "samples",
"token_count": 1675
} | 1,210 |
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild
name: Desktop Photo Search rebuild script
steps:
- name: Remove fluent_ui runners
path: fluent_ui
rmdirs:
- macos
- linux
- windows
- name: Flutter recreate
path: fluent_ui
flutter: create --platforms windows,linux,macos --project-name desktop_photo_search .
- name: Replace fluent_ui/macos/Runner/DebugProfile.entitlements
path: fluent_ui/macos/Runner/DebugProfile.entitlements
patch-u: |
--- b/desktop_photo_search/fluent_ui/macos/Runner/DebugProfile.entitlements
+++ a/desktop_photo_search/fluent_ui/macos/Runner/DebugProfile.entitlements
@@ -6,6 +6,10 @@
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
+ <key>com.apple.security.files.user-selected.read-write</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
- name: Patch fluent_ui/macos/Runner/Release.entitlements
path: fluent_ui/macos/Runner/Release.entitlements
patch-u: |
--- b/desktop_photo_search/fluent_ui/macos/Runner/Release.entitlements
+++ a/desktop_photo_search/fluent_ui/macos/Runner/Release.entitlements
@@ -4,5 +4,9 @@
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
+ <key>com.apple.security.files.user-selected.read-write</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
</dict>
</plist>
- name: Flutter upgrade
path: fluent_ui
flutter: pub upgrade --major-versions
- name: Flutter build macOS
path: fluent_ui
flutter: build macos
- name: Remove material runners
path: material
rmdirs:
- macos
- linux
- windows
- name: Flutter recreate
path: material
flutter: create --platforms windows,linux,macos --project-name desktop_photo_search .
- name: Replace material/macos/Runner/DebugProfile.entitlements
path: material/macos/Runner/DebugProfile.entitlements
patch-u: |
--- b/desktop_photo_search/material/macos/Runner/DebugProfile.entitlements
+++ a/desktop_photo_search/material/macos/Runner/DebugProfile.entitlements
@@ -6,6 +6,10 @@
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
+ <key>com.apple.security.files.user-selected.read-write</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
- name: Replace material/macos/Runner/Release.entitlements
path: material/macos/Runner/Release.entitlements
patch-u: |
--- b/desktop_photo_search/material/macos/Runner/Release.entitlements
+++ a/desktop_photo_search/material/macos/Runner/Release.entitlements
@@ -4,5 +4,9 @@
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
+ <key>com.apple.security.files.user-selected.read-write</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
</dict>
</plist>
- name: Patch material/macos/Runner/Base.lproj/MainMenu.xib
path: material/macos/Runner/Base.lproj/MainMenu.xib
patch-u: |
--- b/desktop_photo_search/material/macos/Runner/Base.lproj/MainMenu.xib
+++ a/desktop_photo_search/material/macos/Runner/Base.lproj/MainMenu.xib
@@ -330,10 +330,11 @@
</items>
<point key="canvasLocation" x="142" y="-258"/>
</menu>
- <window title="APP_NAME" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="MainFlutterWindow" customModule="Runner" customModuleProvider="target">
- <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
+ <!-- Hiding the title bar technique from https://medium.com/flutter-community/transparent-title-bar-on-macos-with-flutter-7043d44f25dc -->
+ <window title="APP_NAME" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" titlebarAppearsTransparent="YES" titleVisibility="hidden" id="QvC-M9-y7g" customClass="MainFlutterWindow" customModule="Runner" customModuleProvider="target">
+ <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES" fullSizeContentView="YES"/>
<rect key="contentRect" x="335" y="390" width="800" height="600"/>
- <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1577"/>
+ <rect key="screenRect" x="0.0" y="0.0" width="1680" height="1025"/>
<view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ">
<rect key="frame" x="0.0" y="0.0" width="800" height="600"/>
<autoresizingMask key="autoresizingMask"/>
- name: Flutter upgrade
path: material
flutter: pub upgrade --major-versions
- name: Flutter build macOS
path: material
flutter: build macos
| samples/desktop_photo_search/codelab_rebuild.yaml/0 | {
"file_path": "samples/desktop_photo_search/codelab_rebuild.yaml",
"repo_id": "samples",
"token_count": 2287
} | 1,211 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'exif.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Exif> _$exifSerializer = new _$ExifSerializer();
class _$ExifSerializer implements StructuredSerializer<Exif> {
@override
final Iterable<Type> types = const [Exif, _$Exif];
@override
final String wireName = 'Exif';
@override
Iterable<Object?> serialize(Serializers serializers, Exif object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[];
Object? value;
value = object.make;
if (value != null) {
result
..add('make')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.model;
if (value != null) {
result
..add('model')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.exposureTime;
if (value != null) {
result
..add('exposure_time')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.aperture;
if (value != null) {
result
..add('aperture')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.focalLength;
if (value != null) {
result
..add('focal_length')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.iso;
if (value != null) {
result
..add('iso')
..add(serializers.serialize(value, specifiedType: const FullType(int)));
}
return result;
}
@override
Exif deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new ExifBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'make':
result.make = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'model':
result.model = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'exposure_time':
result.exposureTime = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'aperture':
result.aperture = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'focal_length':
result.focalLength = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'iso':
result.iso = serializers.deserialize(value,
specifiedType: const FullType(int)) as int?;
break;
}
}
return result.build();
}
}
class _$Exif extends Exif {
@override
final String? make;
@override
final String? model;
@override
final String? exposureTime;
@override
final String? aperture;
@override
final String? focalLength;
@override
final int? iso;
factory _$Exif([void Function(ExifBuilder)? updates]) =>
(new ExifBuilder()..update(updates))._build();
_$Exif._(
{this.make,
this.model,
this.exposureTime,
this.aperture,
this.focalLength,
this.iso})
: super._();
@override
Exif rebuild(void Function(ExifBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
ExifBuilder toBuilder() => new ExifBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Exif &&
make == other.make &&
model == other.model &&
exposureTime == other.exposureTime &&
aperture == other.aperture &&
focalLength == other.focalLength &&
iso == other.iso;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, make.hashCode);
_$hash = $jc(_$hash, model.hashCode);
_$hash = $jc(_$hash, exposureTime.hashCode);
_$hash = $jc(_$hash, aperture.hashCode);
_$hash = $jc(_$hash, focalLength.hashCode);
_$hash = $jc(_$hash, iso.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'Exif')
..add('make', make)
..add('model', model)
..add('exposureTime', exposureTime)
..add('aperture', aperture)
..add('focalLength', focalLength)
..add('iso', iso))
.toString();
}
}
class ExifBuilder implements Builder<Exif, ExifBuilder> {
_$Exif? _$v;
String? _make;
String? get make => _$this._make;
set make(String? make) => _$this._make = make;
String? _model;
String? get model => _$this._model;
set model(String? model) => _$this._model = model;
String? _exposureTime;
String? get exposureTime => _$this._exposureTime;
set exposureTime(String? exposureTime) => _$this._exposureTime = exposureTime;
String? _aperture;
String? get aperture => _$this._aperture;
set aperture(String? aperture) => _$this._aperture = aperture;
String? _focalLength;
String? get focalLength => _$this._focalLength;
set focalLength(String? focalLength) => _$this._focalLength = focalLength;
int? _iso;
int? get iso => _$this._iso;
set iso(int? iso) => _$this._iso = iso;
ExifBuilder();
ExifBuilder get _$this {
final $v = _$v;
if ($v != null) {
_make = $v.make;
_model = $v.model;
_exposureTime = $v.exposureTime;
_aperture = $v.aperture;
_focalLength = $v.focalLength;
_iso = $v.iso;
_$v = null;
}
return this;
}
@override
void replace(Exif other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Exif;
}
@override
void update(void Function(ExifBuilder)? updates) {
if (updates != null) updates(this);
}
@override
Exif build() => _build();
_$Exif _build() {
final _$result = _$v ??
new _$Exif._(
make: make,
model: model,
exposureTime: exposureTime,
aperture: aperture,
focalLength: focalLength,
iso: iso);
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/exif.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/exif.g.dart",
"repo_id": "samples",
"token_count": 2850
} | 1,212 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import '../serializers.dart';
import 'links.dart';
part 'user.g.dart';
abstract class User implements Built<User, UserBuilder> {
factory User([void Function(UserBuilder)? updates]) = _$User;
User._();
@BuiltValueField(wireName: 'id')
String get id;
@BuiltValueField(wireName: 'updated_at')
String? get updatedAt;
@BuiltValueField(wireName: 'username')
String get username;
@BuiltValueField(wireName: 'name')
String get name;
@BuiltValueField(wireName: 'portfolio_url')
String? get portfolioUrl;
@BuiltValueField(wireName: 'bio')
String? get bio;
@BuiltValueField(wireName: 'location')
String? get location;
@BuiltValueField(wireName: 'total_likes')
int? get totalLikes;
@BuiltValueField(wireName: 'total_photos')
int? get totalPhotos;
@BuiltValueField(wireName: 'total_collections')
int? get totalCollections;
@BuiltValueField(wireName: 'links')
Links? get links;
String toJson() {
return json.encode(serializers.serializeWith(User.serializer, this));
}
static User? fromJson(String jsonString) {
return serializers.deserializeWith(
User.serializer, json.decode(jsonString));
}
static Serializer<User> get serializer => _$userSerializer;
}
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/user.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/user.dart",
"repo_id": "samples",
"token_count": 495
} | 1,213 |
// Copyright 2019 The Flutter team. 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:desktop_photo_search/src/unsplash/photo.dart';
import 'package:desktop_photo_search/src/unsplash/search_photos_response.dart';
import 'package:desktop_photo_search/src/unsplash/unsplash.dart';
import 'package:desktop_photo_search/src/unsplash/user.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
void main() {
test('Photo.fromJson', () {
const input = '''
{
"id": "Dwu85P9SOIk",
"created_at": "2016-05-03T11:00:28-04:00",
"updated_at": "2016-07-10T11:00:01-05:00",
"width": 2448,
"height": 3264,
"color": "#6E633A",
"downloads": 1345,
"likes": 24,
"liked_by_user": false,
"description": "A man drinking a coffee.",
"exif": {
"make": "Canon",
"model": "Canon EOS 40D",
"exposure_time": "0.011111111111111112",
"aperture": "4.970854",
"focal_length": "37",
"iso": 100
},
"location": {
"city": "Montreal",
"country": "Canada",
"position": {
"latitude": 45.4732984,
"longitude": -73.6384879
}
},
"tags": [
{ "title": "man" },
{ "title": "drinking" },
{ "title": "coffee" }
],
"current_user_collections": [
{
"id": 206,
"title": "Makers: Cat and Ben",
"published_at": "2016-01-12T18:16:09-05:00",
"updated_at": "2016-07-10T11:00:01-05:00",
"cover_photo": null,
"user": null
}
],
"urls": {
"raw": "https://images.unsplash.com/photo-1417325384643-aac51acc9e5d",
"full": "https://images.unsplash.com/photo-1417325384643-aac51acc9e5d?q=75&fm=jpg",
"regular": "https://images.unsplash.com/photo-1417325384643-aac51acc9e5d?q=75&fm=jpg&w=1080&fit=max",
"small": "https://images.unsplash.com/photo-1417325384643-aac51acc9e5d?q=75&fm=jpg&w=400&fit=max",
"thumb": "https://images.unsplash.com/photo-1417325384643-aac51acc9e5d?q=75&fm=jpg&w=200&fit=max"
},
"links": {
"self": "https://api.unsplash.com/photos/Dwu85P9SOIk",
"html": "https://unsplash.com/photos/Dwu85P9SOIk",
"download": "https://unsplash.com/photos/Dwu85P9SOIk/download",
"download_location": "https://api.unsplash.com/photos/Dwu85P9SOIk/download"
},
"user": {
"id": "QPxL2MGqfrw",
"updated_at": "2016-07-10T11:00:01-05:00",
"username": "exampleuser",
"name": "Joe Example",
"portfolio_url": "https://example.com/",
"bio": "Just an everyday Joe",
"location": "Montreal",
"total_likes": 5,
"total_photos": 10,
"total_collections": 13,
"links": {
"self": "https://api.unsplash.com/users/exampleuser",
"html": "https://unsplash.com/exampleuser",
"photos": "https://api.unsplash.com/users/exampleuser/photos",
"likes": "https://api.unsplash.com/users/exampleuser/likes",
"portfolio": "https://api.unsplash.com/users/exampleuser/portfolio"
}
}
}
''';
final photo = Photo.fromJson(input)!;
expect(photo.id, 'Dwu85P9SOIk');
expect(photo.createdAt, '2016-05-03T11:00:28-04:00');
expect(photo.updatedAt, '2016-07-10T11:00:01-05:00');
expect(photo.width, 2448);
expect(photo.height, 3264);
expect(photo.color, '#6E633A');
expect(photo.downloads, 1345);
expect(photo.likedByUser, false);
expect(photo.exif!.make, 'Canon');
expect(photo.exif!.iso, 100);
expect(photo.location!.city, 'Montreal');
expect(photo.location!.country, 'Canada');
expect(photo.location!.position!.latitude, 45.4732984);
expect(photo.location!.position!.longitude, -73.6384879);
});
test('User.fromJson', () {
const input = '''
{
"id": "pXhwzz1JtQU",
"updated_at": "2016-07-10T11:00:01-05:00",
"username": "jimmyexample",
"name": "James Example",
"first_name": "James",
"last_name": "Example",
"instagram_username": "instantgrammer",
"twitter_username": "jimmy",
"portfolio_url": null,
"bio": "The user's bio",
"location": "Montreal, Qc",
"total_likes": 20,
"total_photos": 10,
"total_collections": 5,
"followed_by_user": false,
"followers_count": 300,
"following_count": 25,
"downloads": 225974,
"profile_image": {
"small": "https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=32&w=32",
"medium": "https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=64&w=64",
"large": "https://images.unsplash.com/face-springmorning.jpg?q=80&fm=jpg&crop=faces&fit=crop&h=128&w=128"
},
"badge": {
"title": "Book contributor",
"primary": true,
"slug": "book-contributor",
"link": "https://book.unsplash.com"
},
"links": {
"self": "https://api.unsplash.com/users/jimmyexample",
"html": "https://unsplash.com/jimmyexample",
"photos": "https://api.unsplash.com/users/jimmyexample/photos",
"likes": "https://api.unsplash.com/users/jimmyexample/likes",
"portfolio": "https://api.unsplash.com/users/jimmyexample/portfolio"
}
}
''';
final user = User.fromJson(input)!;
expect(user.id, 'pXhwzz1JtQU');
});
test('SearchPhotosResponse.fromJson', () {
const input = '''
{
"total": 133,
"total_pages": 7,
"results": [
{
"id": "eOLpJytrbsQ",
"created_at": "2014-11-18T14:35:36-05:00",
"width": 4000,
"height": 3000,
"color": "#A7A2A1",
"likes": 286,
"liked_by_user": false,
"description": "A man drinking a coffee.",
"user": {
"id": "Ul0QVz12Goo",
"username": "ugmonk",
"name": "Jeff Sheldon",
"first_name": "Jeff",
"last_name": "Sheldon",
"instagram_username": "instantgrammer",
"twitter_username": "ugmonk",
"portfolio_url": "http://ugmonk.com/",
"profile_image": {
"small": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=7cfe3b93750cb0c93e2f7caec08b5a41",
"medium": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64&s=5a9dc749c43ce5bd60870b129a40902f",
"large": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128&s=32085a077889586df88bfbe406692202"
},
"links": {
"self": "https://api.unsplash.com/users/ugmonk",
"html": "http://unsplash.com/@ugmonk",
"photos": "https://api.unsplash.com/users/ugmonk/photos",
"likes": "https://api.unsplash.com/users/ugmonk/likes"
}
},
"current_user_collections": [],
"urls": {
"raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f",
"full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f",
"regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515",
"small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb",
"thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef"
},
"links": {
"self": "https://api.unsplash.com/photos/eOLpJytrbsQ",
"html": "http://unsplash.com/photos/eOLpJytrbsQ",
"download": "http://unsplash.com/photos/eOLpJytrbsQ/download"
}
}
]
}
''';
final response = SearchPhotosResponse.fromJson(input)!;
expect(response.total, 133);
expect(response.totalPages, 7);
expect(response.results[0].id, 'eOLpJytrbsQ');
expect(response.results[0].user!.id, 'Ul0QVz12Goo');
});
group('Unsplash API client', () {
test('handles success', () async {
const searchPhotosResponseBody = '''
{
"total": 133,
"total_pages": 7,
"results": [
{
"id": "eOLpJytrbsQ",
"created_at": "2014-11-18T14:35:36-05:00",
"width": 4000,
"height": 3000,
"color": "#A7A2A1",
"likes": 286,
"liked_by_user": false,
"description": "A man drinking a coffee.",
"user": {
"id": "Ul0QVz12Goo",
"username": "ugmonk",
"name": "Jeff Sheldon",
"first_name": "Jeff",
"last_name": "Sheldon",
"instagram_username": "instantgrammer",
"twitter_username": "ugmonk",
"portfolio_url": "http://ugmonk.com/",
"profile_image": {
"small": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=7cfe3b93750cb0c93e2f7caec08b5a41",
"medium": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64&s=5a9dc749c43ce5bd60870b129a40902f",
"large": "https://images.unsplash.com/profile-1441298803695-accd94000cac?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128&s=32085a077889586df88bfbe406692202"
},
"links": {
"self": "https://api.unsplash.com/users/ugmonk",
"html": "http://unsplash.com/@ugmonk",
"photos": "https://api.unsplash.com/users/ugmonk/photos",
"likes": "https://api.unsplash.com/users/ugmonk/likes"
}
},
"current_user_collections": [],
"urls": {
"raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f",
"full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f",
"regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515",
"small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb",
"thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef"
},
"links": {
"self": "https://api.unsplash.com/photos/eOLpJytrbsQ",
"html": "http://unsplash.com/photos/eOLpJytrbsQ",
"download": "http://unsplash.com/photos/eOLpJytrbsQ/download"
}
}
]
}
''';
final httpClient = MockClient((req) async {
return Response(
searchPhotosResponseBody,
200,
request: req,
headers: {'content-type': 'application/json'},
);
});
final unsplashClient = Unsplash(
accessKey: 'not-an-access-key',
httpClient: httpClient,
);
final response = (await unsplashClient.searchPhotos(query: 'red'))!;
expect(response.total, 133);
expect(response.totalPages, 7);
expect(response.results[0].id, 'eOLpJytrbsQ');
expect(response.results[0].user!.id, 'Ul0QVz12Goo');
});
test('handles failure', () async {
const apiError =
'{"errors":["OAuth error: The access token is invalid"]}';
final httpClient = MockClient((req) async {
return Response(
apiError,
401,
request: req,
headers: {'content-type': 'application/json'},
);
});
final unsplashClient = Unsplash(
accessKey: 'not-an-access-key',
httpClient: httpClient,
);
try {
await unsplashClient.searchPhotos(query: 'red');
fail('UnsplashException should have been thrown');
} on UnsplashException catch (e) {
expect(e.toString(),
'UnsplashException: OAuth error: The access token is invalid');
}
});
test('handles broken JSON', () async {
const apiError = '{"tot'; // truncated JSON.
final httpClient = MockClient((req) async {
return Response(
apiError,
401,
request: req,
headers: {'content-type': 'application/json'},
);
});
final unsplashClient = Unsplash(
accessKey: 'not-an-access-key',
httpClient: httpClient,
);
try {
await unsplashClient.searchPhotos(query: 'red');
fail('UnsplashException should have been thrown');
} on UnsplashException catch (e) {
expect(e.toString(), 'UnsplashException: Invalid JSON received');
}
});
});
test('handles utf8 content in JSON', () async {
const searchPhotosResponseBody = '''
{
"total": 22395,
"total_pages": 2240,
"results": [
{
"id": "E4u_Zo9PET8",
"created_at": "2019-12-29T13:45:28-05:00",
"updated_at": "2020-11-05T17:12:18-05:00",
"promoted_at": null,
"width": 2598,
"height": 4618,
"color": "#A53E40",
"blur_hash": "LlO{8lL#XSbu*Jtla0jZOrb^ozjF",
"description": null,
"alt_description": "red apparel",
"urls": {
"raw": "https://images.unsplash.com/photo-1577645113639-32537a4a938b?ixlib=rb-1.2.1\u0026ixid=eyJhcHBfaWQiOjM5NTU5fQ",
"full": "https://images.unsplash.com/photo-1577645113639-32537a4a938b?ixlib=rb-1.2.1\u0026q=85\u0026fm=jpg\u0026crop=entropy\u0026cs=srgb\u0026ixid=eyJhcHBfaWQiOjM5NTU5fQ",
"regular": "https://images.unsplash.com/photo-1577645113639-32537a4a938b?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=1080\u0026fit=max\u0026ixid=eyJhcHBfaWQiOjM5NTU5fQ",
"small": "https://images.unsplash.com/photo-1577645113639-32537a4a938b?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=400\u0026fit=max\u0026ixid=eyJhcHBfaWQiOjM5NTU5fQ",
"thumb": "https://images.unsplash.com/photo-1577645113639-32537a4a938b?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=200\u0026fit=max\u0026ixid=eyJhcHBfaWQiOjM5NTU5fQ"
},
"links": {
"self": "https://api.unsplash.com/photos/E4u_Zo9PET8",
"html": "https://unsplash.com/photos/E4u_Zo9PET8",
"download": "https://unsplash.com/photos/E4u_Zo9PET8/download",
"download_location": "https://api.unsplash.com/photos/E4u_Zo9PET8/download"
},
"categories": [],
"likes": 132,
"liked_by_user": false,
"current_user_collections": [],
"sponsorship": null,
"user": {
"id": "_2nQcPrbyuE",
"updated_at": "2020-11-06T01:37:51-05:00",
"username": "svalenas",
"name": "Sergiu Vălenaș",
"first_name": "Sergiu",
"last_name": "Vălenaș",
"twitter_username": null,
"portfolio_url": null,
"bio": "Gifted psychologist and enthusiast photographer",
"location": "Cluj-Napoca, Romania",
"links": {
"self": "https://api.unsplash.com/users/svalenas",
"html": "https://unsplash.com/@svalenas",
"photos": "https://api.unsplash.com/users/svalenas/photos",
"likes": "https://api.unsplash.com/users/svalenas/likes",
"portfolio": "https://api.unsplash.com/users/svalenas/portfolio",
"following": "https://api.unsplash.com/users/svalenas/following",
"followers": "https://api.unsplash.com/users/svalenas/followers"
},
"profile_image": {
"small": "https://images.unsplash.com/profile-1597067601066-d43176d68553image?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=32\u0026w=32",
"medium": "https://images.unsplash.com/profile-1597067601066-d43176d68553image?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=64\u0026w=64",
"large": "https://images.unsplash.com/profile-1597067601066-d43176d68553image?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=128\u0026w=128"
},
"instagram_username": "svalenas",
"total_collections": 0,
"total_likes": 413,
"total_photos": 129,
"accepted_tos": true
},
"tags": [
{
"type": "landing_page",
"title": "red",
"source": {
"ancestry": {
"type": {
"slug": "wallpapers",
"pretty_slug": "HD Wallpapers"
},
"category": {
"slug": "colors",
"pretty_slug": "Color"
},
"subcategory": {
"slug": "red",
"pretty_slug": "Red"
}
},
"title": "HD Red Wallpapers",
"subtitle": "Download Free Red Wallpapers",
"description": "Choose from a curated selection of red wallpapers for your mobile and desktop screens. Always free on Unsplash.",
"meta_title": "Red Wallpapers: Free HD Download [500+ HQ] | Unsplash",
"meta_description": "Choose from hundreds of free red wallpapers. Download HD wallpapers for free on Unsplash.",
"cover_photo": {
"id": "HyBXy5PHQR8",
"created_at": "2018-02-17T13:44:58-05:00",
"updated_at": "2020-10-21T01:07:42-04:00",
"promoted_at": null,
"width": 3024,
"height": 4032,
"color": "#C51918",
"blur_hash": "L9Bmx_o1o1Jl|cwxWpWpN]\$5N]sU",
"description": null,
"alt_description": "red textile",
"urls": {
"raw": "https://images.unsplash.com/photo-1518893063132-36e46dbe2428?ixlib=rb-1.2.1",
"full": "https://images.unsplash.com/photo-1518893063132-36e46dbe2428?ixlib=rb-1.2.1\u0026q=85\u0026fm=jpg\u0026crop=entropy\u0026cs=srgb",
"regular": "https://images.unsplash.com/photo-1518893063132-36e46dbe2428?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=1080\u0026fit=max",
"small": "https://images.unsplash.com/photo-1518893063132-36e46dbe2428?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=400\u0026fit=max",
"thumb": "https://images.unsplash.com/photo-1518893063132-36e46dbe2428?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=200\u0026fit=max"
},
"links": {
"self": "https://api.unsplash.com/photos/HyBXy5PHQR8",
"html": "https://unsplash.com/photos/HyBXy5PHQR8",
"download": "https://unsplash.com/photos/HyBXy5PHQR8/download",
"download_location": "https://api.unsplash.com/photos/HyBXy5PHQR8/download"
},
"categories": [],
"likes": 1243,
"liked_by_user": false,
"current_user_collections": [],
"sponsorship": null,
"user": {
"id": "6nkkrwW9M-s",
"updated_at": "2020-10-22T20:44:54-04:00",
"username": "montylov",
"name": "MontyLov",
"first_name": "MontyLov",
"last_name": null,
"twitter_username": "MontyLov",
"portfolio_url": "http://montylov.com",
"bio": "Stay humble and innovate.",
"location": null,
"links": {
"self": "https://api.unsplash.com/users/montylov",
"html": "https://unsplash.com/@montylov",
"photos": "https://api.unsplash.com/users/montylov/photos",
"likes": "https://api.unsplash.com/users/montylov/likes",
"portfolio": "https://api.unsplash.com/users/montylov/portfolio",
"following": "https://api.unsplash.com/users/montylov/following",
"followers": "https://api.unsplash.com/users/montylov/followers"
},
"profile_image": {
"small": "https://images.unsplash.com/profile-1588478301600-b5e5203a574aimage?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=32\u0026w=32",
"medium": "https://images.unsplash.com/profile-1588478301600-b5e5203a574aimage?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=64\u0026w=64",
"large": "https://images.unsplash.com/profile-1588478301600-b5e5203a574aimage?ixlib=rb-1.2.1\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=128\u0026w=128"
},
"instagram_username": "montylov",
"total_collections": 1,
"total_likes": 0,
"total_photos": 79,
"accepted_tos": false
}
}
}
},
{
"type": "search",
"title": "rug"
},
{
"type": "search",
"title": "plant"
}
]
}
]
}
''';
final httpClient = MockClient((req) async {
return Response(
searchPhotosResponseBody,
200,
request: req,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final unsplashClient = Unsplash(
accessKey: 'not-an-access-key',
httpClient: httpClient,
);
final response = (await unsplashClient.searchPhotos(query: 'red'))!;
expect(response.total, 22395);
expect(response.totalPages, 2240);
expect(response.results[0].id, 'E4u_Zo9PET8');
expect(response.results[0].user!.id, '_2nQcPrbyuE');
expect(response.results[0].user!.name, 'Sergiu Vălenaș');
});
}
| samples/desktop_photo_search/fluent_ui/test/unsplash_test.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/test/unsplash_test.dart",
"repo_id": "samples",
"token_count": 12984
} | 1,214 |
include: package:analysis_defaults/flutter.yaml
| samples/experimental/federated_plugin/federated_plugin/analysis_options.yaml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,215 |
#import "FederatedPlugin.h"
#if __has_include(<federated_plugin/federated_plugin-Swift.h>)
#import <federated_plugin/federated_plugin-Swift.h>
#else
// Support project import fallback if the generated compatibility header
// is not copied when this plugin is created as a library.
// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
#import "federated_plugin-Swift.h"
#endif
@implementation FederatedPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
[SwiftFederatedPlugin registerWithRegistrar:registrar];
}
@end
| samples/experimental/federated_plugin/federated_plugin/ios/Classes/FederatedPlugin.m/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/ios/Classes/FederatedPlugin.m",
"repo_id": "samples",
"token_count": 200
} | 1,216 |
include: package:analysis_defaults/flutter.yaml
| samples/experimental/federated_plugin/federated_plugin_platform_interface/analysis_options.yaml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_platform_interface/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,217 |
include: package:analysis_defaults/flutter.yaml
| samples/experimental/federated_plugin/federated_plugin_windows/analysis_options.yaml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_windows/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,218 |
// Copyright 2021 The Flutter team. 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:equatable/equatable.dart';
import 'package:hive/hive.dart';
import 'package:linting_tool/model/rule.dart';
part 'profile.g.dart';
@HiveType(typeId: 1)
class RulesProfile extends Equatable {
@HiveField(0)
final String name;
@HiveField(1)
final List<Rule> rules;
const RulesProfile({
required this.name,
required this.rules,
});
@override
List<Object?> get props => [name];
}
| samples/experimental/linting_tool/lib/model/profile.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/model/profile.dart",
"repo_id": "samples",
"token_count": 199
} | 1,219 |
//
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import file_selector_macos
import path_provider_foundation
import url_launcher_macos
import window_size
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
WindowSizePlugin.register(with: registry.registrar(forPlugin: "WindowSizePlugin"))
}
| samples/experimental/linting_tool/macos/Flutter/GeneratedPluginRegistrant.swift/0 | {
"file_path": "samples/experimental/linting_tool/macos/Flutter/GeneratedPluginRegistrant.swift",
"repo_id": "samples",
"token_count": 179
} | 1,220 |
# pedometer_example
Demonstrates how to use the pedometer plugin.
Visit the primary [pedometer README](../README.md) for more information.
| samples/experimental/pedometer/example/README.md/0 | {
"file_path": "samples/experimental/pedometer/example/README.md",
"repo_id": "samples",
"token_count": 40
} | 1,221 |
<resources>
<array name="health_permissions">
<item>androidx.health.permission.HeartRate.READ</item>
<item>androidx.health.permission.HeartRate.WRITE</item>
<item>androidx.health.permission.Steps.READ</item>
<item>androidx.health.permission.Steps.WRITE</item>
</array>
</resources> | samples/experimental/pedometer/example/android/app/src/main/res/values/health-permissions.xml/0 | {
"file_path": "samples/experimental/pedometer/example/android/app/src/main/res/values/health-permissions.xml",
"repo_id": "samples",
"token_count": 113
} | 1,222 |
# From dart SDK: https://github.com/dart-lang/sdk/blob/main/.clang-format
# Defines the Chromium style for automatic reformatting.
# http://clang.llvm.org/docs/ClangFormatStyleOptions.html
BasedOnStyle: Chromium
# clang-format doesn't seem to do a good job of this for longer comments.
ReflowComments: 'false'
# We have lots of these. Though we need to put them all in curly braces,
# clang-format can't do that.
AllowShortIfStatementsOnASingleLine: 'true'
# Put escaped newlines into the rightmost column.
AlignEscapedNewlinesLeft: false
| samples/experimental/pedometer/src/health_connect/.clang-format/0 | {
"file_path": "samples/experimental/pedometer/src/health_connect/.clang-format",
"repo_id": "samples",
"token_count": 169
} | 1,223 |
// Copyright 2023 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
enum Shader {
nothing('nothing'),
bwSplit('bw_split'),
colorSplit('color_split'),
rowOffset('row_offset'),
wavyCirc('wavy_circ'),
wavy('wavy'),
wavy2('wavy2');
const Shader(this.name);
final String name;
Future<ui.FragmentProgram> get program =>
ui.FragmentProgram.fromAsset('shaders/$name.frag');
}
class FragmentShaded extends StatefulWidget {
final Widget child;
final Shader shader;
final int shaderDuration;
static const int dampenDuration = 1000;
static final Map<Shader, ui.FragmentProgram> _programCache = {};
const FragmentShaded({
required this.shader,
required this.shaderDuration,
required this.child,
super.key,
});
@override
State<FragmentShaded> createState() => FragmentShadedState();
}
class FragmentShadedState extends State<FragmentShaded>
with TickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _dampenAnimation;
late final Animation<double> _dampenCurve;
late final AnimationController _dampenController;
late AnimatingSamplerBuilder builder;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: widget.shaderDuration),
)..repeat(reverse: false);
_dampenController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: FragmentShaded.dampenDuration),
);
_dampenCurve = CurvedAnimation(
parent: _dampenController,
curve: Curves.easeInOut,
);
_dampenAnimation =
Tween<double>(begin: 1.0, end: 0.0).animate(_dampenCurve);
initializeFragmentProgramsAndBuilder();
}
Future<void> initializeFragmentProgramsAndBuilder() async {
if (FragmentShaded._programCache.isEmpty) {
for (final shader in Shader.values) {
FragmentShaded._programCache[shader] = await shader.program;
}
}
setState(() {
builder = AnimatingSamplerBuilder(_controller, _dampenAnimation,
FragmentShaded._programCache[widget.shader]!.fragmentShader());
});
}
@override
void dispose() {
_controller.dispose();
_dampenController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (null == FragmentShaded._programCache[widget.shader]) {
setState(() {});
return const SizedBox(
width: 0,
height: 0,
);
}
return Transform.scale(
scale: 0.5,
child: ShaderSamplerBuilder(
builder,
child: widget.child,
),
);
}
void startDampening() {
_dampenController.forward();
}
}
class AnimatingSamplerBuilder extends SamplerBuilder {
AnimatingSamplerBuilder(
this.animation, this.dampenAnimation, this.fragmentShader) {
animation.addListener(notifyListeners);
dampenAnimation.addListener(notifyListeners);
}
final Animation<double> animation;
final Animation<double> dampenAnimation;
final ui.FragmentShader fragmentShader;
@override
void paint(ui.Image image, Size size, ui.Canvas canvas) {
// animation
fragmentShader.setFloat(0, animation.value);
// width
fragmentShader.setFloat(1, size.width);
// height
fragmentShader.setFloat(2, size.height);
// dampener
fragmentShader.setFloat(3, dampenAnimation.value);
// sampler
fragmentShader.setImageSampler(0, image);
canvas.drawRect(Offset.zero & size, Paint()..shader = fragmentShader);
}
}
abstract class SamplerBuilder extends ChangeNotifier {
void paint(ui.Image image, Size size, ui.Canvas canvas);
}
class ShaderSamplerBuilder extends StatelessWidget {
const ShaderSamplerBuilder(this.builder, {required this.child, super.key});
final SamplerBuilder builder;
final Widget child;
@override
Widget build(BuildContext context) {
return RepaintBoundary(
child: _ShaderSamplerImpl(
builder,
child: child,
));
}
}
class _ShaderSamplerImpl extends SingleChildRenderObjectWidget {
const _ShaderSamplerImpl(this.builder, {super.child});
final SamplerBuilder builder;
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderShaderSamplerBuilderWidget(
devicePixelRatio: MediaQuery.of(context).devicePixelRatio,
builder: builder,
);
}
@override
void updateRenderObject(
BuildContext context, covariant RenderObject renderObject) {
(renderObject as _RenderShaderSamplerBuilderWidget)
..devicePixelRatio = MediaQuery.of(context).devicePixelRatio
..builder = builder;
}
}
// A render object that conditionally converts its child into a [ui.Image]
// and then paints it in place of the child.
class _RenderShaderSamplerBuilderWidget extends RenderProxyBox {
// Create a new [_RenderSnapshotWidget].
_RenderShaderSamplerBuilderWidget({
required double devicePixelRatio,
required SamplerBuilder builder,
}) : _devicePixelRatio = devicePixelRatio,
_builder = builder;
/// The device pixel ratio used to create the child image.
double get devicePixelRatio => _devicePixelRatio;
double _devicePixelRatio;
set devicePixelRatio(double value) {
if (value == devicePixelRatio) {
return;
}
_devicePixelRatio = value;
if (_childRaster == null) {
return;
} else {
_childRaster?.dispose();
_childRaster = null;
markNeedsPaint();
}
}
/// The painter used to paint the child snapshot or child widgets.
SamplerBuilder get builder => _builder;
SamplerBuilder _builder;
set builder(SamplerBuilder value) {
if (value == builder) {
return;
}
builder.removeListener(markNeedsPaint);
_builder = value;
builder.addListener(markNeedsPaint);
markNeedsPaint();
}
ui.Image? _childRaster;
@override
void attach(PipelineOwner owner) {
builder.addListener(markNeedsPaint);
super.attach(owner);
}
@override
void detach() {
_childRaster?.dispose();
_childRaster = null;
builder.removeListener(markNeedsPaint);
super.detach();
}
@override
void dispose() {
builder.removeListener(markNeedsPaint);
_childRaster?.dispose();
_childRaster = null;
super.dispose();
}
// Paint [child] with this painting context, then convert to a raster and detach all
// children from this layer.
ui.Image? _paintAndDetachToImage() {
final OffsetLayer offsetLayer = OffsetLayer();
final PaintingContext context =
PaintingContext(offsetLayer, Offset.zero & size);
super.paint(context, Offset.zero);
// This ignore is here because this method is protected by the `PaintingContext`. Adding a new
// method that performs the work of `_paintAndDetachToImage` would avoid the need for this, but
// that would conflict with our goals of minimizing painting context.
// ignore: invalid_use_of_protected_member
context.stopRecordingIfNeeded();
final ui.Image image = offsetLayer.toImageSync(Offset.zero & size,
pixelRatio: devicePixelRatio);
offsetLayer.dispose();
return image;
}
@override
void paint(PaintingContext context, Offset offset) {
if (size.isEmpty) {
_childRaster?.dispose();
_childRaster = null;
return;
}
_childRaster?.dispose();
_childRaster = _paintAndDetachToImage();
builder.paint(_childRaster!, size, context.canvas);
}
}
| samples/experimental/varfont_shader_puzzle/lib/components/fragment_shaded.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/components/fragment_shaded.dart",
"repo_id": "samples",
"token_count": 2705
} | 1,224 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.