text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
export 'clear_stickers_button_layer.dart';
export 'clear_stickers_cancel_button.dart';
export 'clear_stickers_confirm_button.dart';
export 'clear_stickers_dialog.dart';
| photobooth/lib/stickers/widgets/clear_stickers/clear_stickers.dart/0 | {
"file_path": "photobooth/lib/stickers/widgets/clear_stickers/clear_stickers.dart",
"repo_id": "photobooth",
"token_count": 61
} | 1,071 |
name: analytics
description: A Flutter package which adds analytics support
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
very_good_analysis: ^4.0.0+1
| photobooth/packages/analytics/pubspec.yaml/0 | {
"file_path": "photobooth/packages/analytics/pubspec.yaml",
"repo_id": "photobooth",
"token_count": 108
} | 1,072 |
import 'package:camera_platform_interface/src/platform_interface/camera_platform.dart';
import 'package:flutter/foundation.dart';
class CameraOptions {
const CameraOptions({
AudioConstraints? audio,
VideoConstraints? video,
}) : audio = audio ?? const AudioConstraints(),
video = video ?? const VideoConstraints();
final AudioConstraints audio;
final VideoConstraints video;
Future<Map<String, dynamic>> toJson() async {
final videoConstraints = await video.toJson();
return {'audio': audio.toJson(), 'video': videoConstraints};
}
}
enum CameraType { rear, user }
enum Constrain { exact, ideal }
class FacingMode {
const FacingMode({this.constrain, this.type});
final Constrain? constrain;
final CameraType? type;
Object? toJson() {
if (constrain == null) {
return type != null ? describeEnum(type!) : null;
}
return {
describeEnum(constrain!): describeEnum(type!),
};
}
}
class AudioConstraints {
const AudioConstraints({this.enabled = false});
final bool enabled;
Object toJson() => enabled;
}
class VideoConstraints {
const VideoConstraints({
this.enabled = true,
this.facingMode,
this.width,
this.height,
this.deviceId,
});
static const String defaultDeviceId = 'default';
final bool enabled;
final FacingMode? facingMode;
final VideoSize? width;
final VideoSize? height;
final String? deviceId;
Future<Object> toJson() async {
if (!enabled) return false;
final json = <String, dynamic>{};
if (width != null) json['width'] = width!.toJson();
if (height != null) json['height'] = height!.toJson();
if (facingMode != null) json['facingMode'] = facingMode!.toJson();
if (deviceId == defaultDeviceId) {
json['deviceId'] = await CameraPlatform.instance.getDefaultDeviceId();
} else if (deviceId != null) {
json['deviceId'] = deviceId;
}
return json;
}
}
class VideoSize {
const VideoSize({this.minimum, this.ideal, this.maximum});
final int? minimum;
final int? ideal;
final int? maximum;
Object toJson() {
final json = <String, dynamic>{};
if (ideal != null) json['ideal'] = ideal;
if (minimum != null) json['min'] = minimum;
if (maximum != null) json['max'] = maximum;
return json;
}
}
| photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_options.dart/0 | {
"file_path": "photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_options.dart",
"repo_id": "photobooth",
"token_count": 804
} | 1,073 |
import 'dart:async';
import 'dart:convert';
import 'package:image_compositor/image_compositor.dart';
import 'package:image_compositor/src/image_loader.dart';
import 'package:image_compositor/src/offscreen_canvas.dart';
/// {@macro image_compositor}
class ImageCompositor {
/// {@macro image_compositor}
ImageCompositor();
/// Composites the [data] and [layers]
/// and returns a byte array with the provided [aspectRatio].
Future<List<int>> composite({
required String data,
required int width,
required int height,
required List<dynamic> layers,
required double aspectRatio,
}) {
return _OffscreenCompositor(data, width, height, layers, aspectRatio)
.composite();
}
}
class _OffscreenCompositor {
const _OffscreenCompositor(
this.data,
this.width,
this.height,
this.rawLayers,
this.targetAspectRatio,
);
final String data;
final int width;
final int height;
final List<dynamic> rawLayers;
final double targetAspectRatio;
/// Left, Top, Right border size.
static const _frameBorderSize = 15;
Future<List<int>> composite() async {
final layers =
rawLayers.map((l) => CompositeLayer.fromJson(l as Map)).toList();
final imageFutures = <Future<HtmlImage>>[];
/// Load assets in parallel.
final imageFuture = HtmlImageLoader(data).loadImage();
for (var layerIndex = 0; layerIndex < layers.length; layerIndex++) {
final imageFuture =
HtmlImageLoader(layers[layerIndex].assetPath).loadImage();
imageFutures.add(imageFuture);
}
/// Load framed image.
await Future.wait(imageFutures);
final image = await imageFuture;
/// Prepare image elements.
final frameAssetPath = targetAspectRatio < 1
? 'assets/assets/images/photo_frame_mobile_download.png'
: 'assets/assets/images/photo_frame_download.png';
final frameImage = await HtmlImageLoader(frameAssetPath).loadImage();
/// Compute target coordinates and target image size from assets.
final targetWidth = frameImage.width;
final targetHeight = frameImage.height;
/// We will have to create a clipping rectangle within frame and compute
/// videoRect that will correct the aspectratio and crop the image
/// correctly.
final inputVideoAspectRatio = width / height;
var croppedWidth = width.toDouble();
var croppedHeight = height.toDouble();
// Amount to shift drawing so that image gets cropped.
var imageCropOffsetX = 0;
var imageCropOffsetY = 0;
if (inputVideoAspectRatio > targetAspectRatio) {
// Crop left and right of video
croppedWidth = height * targetAspectRatio;
imageCropOffsetX = (croppedWidth - width) ~/ 2;
} else {
// Crop top and bottom of video
croppedHeight = width / targetAspectRatio;
imageCropOffsetY = (croppedHeight - height) ~/ 2;
}
const insideFrameX = _frameBorderSize;
const insideFrameY = _frameBorderSize;
final insideFrameWidth = frameImage.width - (2 * _frameBorderSize);
final insideFrameHeight = insideFrameWidth ~/ targetAspectRatio;
/// Render images to offscreen canvas.
final canvas = OffScreenCanvas(targetWidth, targetHeight)
/// Draw frame to cover full cropped area.
..drawImage(frameImage.imageElement, 0, 0, targetWidth, targetHeight)
/// Clip to frame interior.
..clipRect(
insideFrameX,
insideFrameY,
insideFrameWidth,
insideFrameHeight,
);
/// Scale the image so the cropped portion will cover the inside of
/// the frame.
final imageScaleFactor = (inputVideoAspectRatio > targetAspectRatio)
? insideFrameHeight / image.height
: insideFrameWidth / image.width;
final videoImageX =
insideFrameX + (imageCropOffsetX * imageScaleFactor).toInt();
final videoImageY =
insideFrameY + (imageCropOffsetY * imageScaleFactor).toInt();
final videoImageWidth = (image.width * imageScaleFactor).toInt();
final videoImageHeight = (image.height * imageScaleFactor).toInt();
canvas.drawImage(
image.imageElement,
videoImageX,
videoImageY,
videoImageWidth,
videoImageHeight,
);
for (var layerIndex = 0; layerIndex < layers.length; layerIndex++) {
final layer = layers[layerIndex];
final asset = await imageFutures[layerIndex];
/// Normalize coordinates to 0..1 based on original video image size.
/// then scale to target.
final assetDxPercent = layer.position.x / layer.constraints.x;
final assetDyPercent = layer.position.y / layer.constraints.y;
final assetWidthPercent = layer.size.x / layer.constraints.x;
final assetDx = assetDxPercent * insideFrameWidth;
final assetDy = assetDyPercent * insideFrameHeight;
final assetWidth = assetWidthPercent * insideFrameWidth;
/// Keep aspect ratio of asset since it is centered in layer.
final assetHeight = assetWidth * asset.height / asset.width;
canvas
..save()
..translate(insideFrameX + assetDx, insideFrameY + assetDy)
..translate(assetWidth / 2, assetHeight / 2)
..rotate(layer.angle)
..translate(-assetWidth / 2, -assetHeight / 2)
..drawImage(
asset.imageElement,
0,
0,
assetWidth.toInt(),
assetHeight.toInt(),
)
..restore();
}
/// To data url will convert canvas contents to 64bit encoded PNG.
final dataUrl = await canvas.toDataUrl();
return base64.decode(dataUrl.split(',')[1]);
}
}
| photobooth/packages/image_compositor/lib/src/web.dart/0 | {
"file_path": "photobooth/packages/image_compositor/lib/src/web.dart",
"repo_id": "photobooth",
"token_count": 2015
} | 1,074 |
export 'links_helper.dart';
export 'modal_helper.dart';
| photobooth/packages/photobooth_ui/lib/src/helpers/helpers.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/helpers/helpers.dart",
"repo_id": "photobooth",
"token_count": 23
} | 1,075 |
import 'package:flutter/material.dart';
const _defaultFadeInDuration = Duration(seconds: 1);
/// {@template animated_fade_in}
/// Widget that applies a fade in transition to its child.
/// {@endtemplate}
class AnimatedFadeIn extends StatefulWidget {
/// {@macro animated_fade_in}
const AnimatedFadeIn({
required this.child,
this.duration = _defaultFadeInDuration,
super.key,
});
/// The child which will be faded in.
final Widget child;
/// The duration of the fade in animation.
final Duration duration;
@override
State<AnimatedFadeIn> createState() => _AnimatedFadeInState();
}
class _AnimatedFadeInState extends State<AnimatedFadeIn> {
var _isVisible = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() => _isVisible = true);
});
}
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
duration: widget.duration,
opacity: _isVisible ? 1.0 : 0.0,
child: widget.child,
);
}
}
| photobooth/packages/photobooth_ui/lib/src/widgets/animated_fade_in.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/animated_fade_in.dart",
"repo_id": "photobooth",
"token_count": 375
} | 1,076 |
const transparentImage = <int>[
0x89,
0x50,
0x4E,
0x47,
0x0D,
0x0A,
0x1A,
0x0A,
0x00,
0x00,
0x00,
0x0D,
0x49,
0x48,
0x44,
0x52,
0x00,
0x00,
0x00,
0x01,
0x00,
0x00,
0x00,
0x01,
0x08,
0x06,
0x00,
0x00,
0x00,
0x1F,
0x15,
0xC4,
0x89,
0x00,
0x00,
0x00,
0x0A,
0x49,
0x44,
0x41,
0x54,
0x78,
0x9C,
0x63,
0x00,
0x01,
0x00,
0x00,
0x05,
0x00,
0x01,
0x0D,
0x0A,
0x2D,
0xB4,
0x00,
0x00,
0x00,
0x00,
0x49,
0x45,
0x4E,
0x44,
0xAE,
];
| photobooth/packages/photobooth_ui/test/helpers/constants.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/helpers/constants.dart",
"repo_id": "photobooth",
"token_count": 409
} | 1,077 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
void main() {
group('AppPageView', () {
const footerKey = Key('footer');
const bodyKey = Key('body');
const backgroundKey = Key('background');
const firstOverlayKey = Key('firstOverlay');
const secondOverlayKey = Key('secondOverlayKey');
testWidgets('renders body', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: AppPageView(
footer: Container(key: footerKey),
body: Container(
height: 200,
key: bodyKey,
),
),
),
);
expect(find.byKey(bodyKey), findsOneWidget);
});
testWidgets('renders footer', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: AppPageView(
footer: Container(key: footerKey),
body: Container(
height: 200,
key: bodyKey,
),
),
),
);
expect(find.byKey(footerKey), findsOneWidget);
});
testWidgets('renders background', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: AppPageView(
footer: Container(key: footerKey),
body: Container(
height: 200,
key: bodyKey,
),
background: Container(key: backgroundKey),
),
),
);
expect(find.byKey(backgroundKey), findsOneWidget);
});
testWidgets('renders overlays', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: AppPageView(
footer: Container(key: footerKey),
body: Container(
height: 200,
key: bodyKey,
),
background: Container(key: backgroundKey),
overlays: [
Container(key: firstOverlayKey),
Container(key: secondOverlayKey),
],
),
),
);
expect(find.byKey(firstOverlayKey), findsOneWidget);
expect(find.byKey(secondOverlayKey), findsOneWidget);
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/app_page_view_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/widgets/app_page_view_test.dart",
"repo_id": "photobooth",
"token_count": 1106
} | 1,078 |
import 'package:authentication_repository/authentication_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/app/app.dart';
import 'package:io_photobooth/landing/landing.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:photos_repository/photos_repository.dart';
import 'helpers/helpers.dart';
class MockAuthenticationRepository extends Mock
implements AuthenticationRepository {}
class MockPhotosRepository extends Mock implements PhotosRepository {}
void main() {
group('App', () {
testWidgets('uses default theme on large devices', (tester) async {
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 1000));
await tester.pumpWidget(
App(
authenticationRepository: MockAuthenticationRepository(),
photosRepository: MockPhotosRepository(),
),
);
final materialApp = tester.widget<MaterialApp>(find.byType(MaterialApp));
expect(
materialApp.theme!.textTheme.displayLarge!.fontSize,
equals(PhotoboothTheme.standard.textTheme.displayLarge!.fontSize),
);
});
testWidgets('uses small theme on small devices', (tester) async {
tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 500));
await tester.pumpWidget(
App(
authenticationRepository: MockAuthenticationRepository(),
photosRepository: MockPhotosRepository(),
),
);
final materialApp = tester.widget<MaterialApp>(find.byType(MaterialApp));
expect(
materialApp.theme!.textTheme.displayLarge!.fontSize,
equals(PhotoboothTheme.small.textTheme.displayLarge!.fontSize),
);
});
testWidgets('renders LandingPage', (tester) async {
await tester.pumpWidget(
App(
authenticationRepository: MockAuthenticationRepository(),
photosRepository: MockPhotosRepository(),
),
);
expect(find.byType(LandingPage), findsOneWidget);
});
});
}
| photobooth/test/app_test.dart/0 | {
"file_path": "photobooth/test/app_test.dart",
"repo_id": "photobooth",
"token_count": 779
} | 1,079 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/assets.g.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class FakePhotoboothEvent extends Fake implements PhotoboothEvent {}
class FakePhotoboothState extends Fake implements PhotoboothState {}
class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState>
implements PhotoboothBloc {}
void main() {
const width = 1;
const height = 1;
const data = '';
const image = CameraImage(width: width, height: height, data: data);
late PhotoboothBloc photoboothBloc;
group('StickersLayer', () {
setUpAll(() {
registerFallbackValue(FakePhotoboothEvent());
registerFallbackValue(FakePhotoboothState());
});
setUp(() {
photoboothBloc = MockPhotoboothBloc();
});
testWidgets('displays selected sticker assets', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: const [PhotoAsset(id: '0', asset: Assets.android)],
stickers: [PhotoAsset(id: '0', asset: Assets.props.first)],
image: image,
),
);
await tester.pumpApp(
const StickersLayer(),
photoboothBloc: photoboothBloc,
);
expect(
find.byKey(const Key('stickersLayer_01_google_v1_0_positioned')),
findsOneWidget,
);
});
testWidgets('displays multiple selected sticker assets', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: const [PhotoAsset(id: '0', asset: Assets.android)],
stickers: [
PhotoAsset(id: '0', asset: Assets.props.first),
PhotoAsset(id: '1', asset: Assets.props.first),
PhotoAsset(id: '2', asset: Assets.props.last),
],
image: image,
),
);
await tester.pumpApp(
const StickersLayer(),
photoboothBloc: photoboothBloc,
);
expect(
find.byKey(const Key('stickersLayer_01_google_v1_0_positioned')),
findsOneWidget,
);
expect(
find.byKey(const Key('stickersLayer_01_google_v1_1_positioned')),
findsOneWidget,
);
expect(
find.byKey(const Key('stickersLayer_25_shapes_v1_2_positioned')),
findsOneWidget,
);
});
});
}
| photobooth/test/photobooth/widgets/stickers_layer_test.dart/0 | {
"file_path": "photobooth/test/photobooth/widgets/stickers_layer_test.dart",
"repo_id": "photobooth",
"token_count": 1101
} | 1,080 |
// ignore_for_file: prefer_const_constructors
import 'dart:typed_data';
import 'package:cross_file/cross_file.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class MockPhotoAsset extends Mock implements PhotoAsset {}
void main() {
const shareUrl = 'http://share-url.com';
final bytes = Uint8List.fromList([]);
late ShareBloc shareBloc;
setUpAll(() {
registerFallbackValue(FakeShareEvent());
registerFallbackValue(FakeShareState());
});
setUp(() {
shareBloc = MockShareBloc();
when(() => shareBloc.state).thenReturn(ShareState());
});
group('TwitterButton', () {
testWidgets('pops when tapped', (tester) async {
await tester.pumpApp(TwitterButton(), shareBloc: shareBloc);
await tester.tap(find.byType(TwitterButton));
await tester.pumpAndSettle();
expect(find.byType(TwitterButton), findsNothing);
});
testWidgets('adds ShareOnTwitterTapped event when tapped', (tester) async {
await tester.pumpApp(TwitterButton(), shareBloc: shareBloc);
await tester.tap(find.byType(TwitterButton));
await tester.pumpAndSettle();
verify(() => shareBloc.add(ShareOnTwitterTapped())).called(1);
});
testWidgets(
'does not add ShareOnTwitterTapped event '
'when tapped but state is upload success', (tester) async {
when(() => shareBloc.state).thenReturn(
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.success,
file: XFile.fromData(bytes),
bytes: bytes,
twitterShareUrl: shareUrl,
facebookShareUrl: shareUrl,
),
);
await tester.pumpApp(TwitterButton(), shareBloc: shareBloc);
await tester.tap(find.byType(TwitterButton));
await tester.pumpAndSettle();
verifyNever(() => shareBloc.add(any()));
});
});
}
| photobooth/test/share/widgets/twitter_button_test.dart/0 | {
"file_path": "photobooth/test/share/widgets/twitter_button_test.dart",
"repo_id": "photobooth",
"token_count": 794
} | 1,081 |
import 'package:flame/components.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template bonus_ball_spawning_behavior}
/// After a duration, spawns a bonus ball from the [DinoWalls] and boosts it
/// into the middle of the board.
/// {@endtemplate}
class BonusBallSpawningBehavior extends TimerComponent with HasGameRef {
/// {@macro bonus_ball_spawning_behavior}
BonusBallSpawningBehavior()
: super(
period: 5,
removeOnFinish: true,
);
@override
void onTick() {
final characterTheme = readBloc<CharacterThemeCubit, CharacterThemeState>()
.state
.characterTheme;
gameRef.descendants().whereType<ZCanvasComponent>().single.add(
Ball(assetPath: characterTheme.ball.keyName)
..add(BallImpulsingBehavior(impulse: Vector2(-40, 0)))
..initialPosition = Vector2(29.2, -24.5)
..zIndex = ZIndexes.ballOnBoard,
);
}
}
| pinball/lib/game/behaviors/bonus_ball_spawning_behavior.dart/0 | {
"file_path": "pinball/lib/game/behaviors/bonus_ball_spawning_behavior.dart",
"repo_id": "pinball",
"token_count": 414
} | 1,082 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Increases the multiplier when a [Ball] is shot 5 times into the
/// [SpaceshipRamp].
class RampMultiplierBehavior extends Component
with FlameBlocListenable<SpaceshipRampCubit, SpaceshipRampState> {
@override
bool listenWhen(
SpaceshipRampState previousState,
SpaceshipRampState newState,
) {
final hitsIncreased = previousState.hits < newState.hits;
final achievedFiveShots = newState.hits % 5 == 0;
final notMaxMultiplier =
!readBloc<GameBloc, GameState>().state.isMaxMultiplier;
return hitsIncreased & achievedFiveShots && notMaxMultiplier;
}
@override
void onNewState(SpaceshipRampState state) {
readBloc<GameBloc, GameState>().add(const MultiplierIncreased());
}
}
| pinball/lib/game/components/android_acres/behaviors/ramp_multiplier_behavior.dart/0 | {
"file_path": "pinball/lib/game/components/android_acres/behaviors/ramp_multiplier_behavior.dart",
"repo_id": "pinball",
"token_count": 337
} | 1,083 |
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/input.dart';
import 'package:flutter/material.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:share_repository/share_repository.dart';
/// Signature for the callback called when the user tries to share their score
/// on the [ShareDisplay].
typedef OnSocialShareTap = void Function(SharePlatform);
final _descriptionTextPaint = TextPaint(
style: const TextStyle(
fontSize: 1.6,
color: PinballColors.white,
fontFamily: PinballFonts.pixeloidSans,
),
);
/// {@template share_display}
/// Display that allows users to share their score to social networks.
/// {@endtemplate}
class ShareDisplay extends Component with HasGameRef {
/// {@macro share_display}
ShareDisplay({
OnSocialShareTap? onShare,
}) : super(
children: [
_ShareInstructionsComponent(
onShare: onShare,
),
],
);
}
class _ShareInstructionsComponent extends PositionComponent with HasGameRef {
_ShareInstructionsComponent({
OnSocialShareTap? onShare,
}) : super(
anchor: Anchor.center,
position: Vector2(0, -25),
children: [
_DescriptionComponent(),
_SocialNetworksComponent(
onShare: onShare,
),
],
);
}
class _DescriptionComponent extends PositionComponent with HasGameRef {
_DescriptionComponent()
: super(
anchor: Anchor.center,
position: Vector2.zero(),
children: [
_LetEveryoneTextComponent(),
_SharingYourScoreTextComponent(),
_SocialMediaTextComponent(),
],
);
}
class _LetEveryoneTextComponent extends TextComponent with HasGameRef {
_LetEveryoneTextComponent()
: super(
anchor: Anchor.center,
position: Vector2.zero(),
textRenderer: _descriptionTextPaint,
);
@override
Future<void> onLoad() async {
await super.onLoad();
text = readProvider<AppLocalizations>().letEveryone;
}
}
class _SharingYourScoreTextComponent extends TextComponent with HasGameRef {
_SharingYourScoreTextComponent()
: super(
anchor: Anchor.center,
position: Vector2(0, 2.5),
textRenderer: _descriptionTextPaint,
);
@override
Future<void> onLoad() async {
await super.onLoad();
text = readProvider<AppLocalizations>().bySharingYourScore;
}
}
class _SocialMediaTextComponent extends TextComponent with HasGameRef {
_SocialMediaTextComponent()
: super(
anchor: Anchor.center,
position: Vector2(0, 5),
textRenderer: _descriptionTextPaint,
);
@override
Future<void> onLoad() async {
await super.onLoad();
text = readProvider<AppLocalizations>().socialMediaAccount;
}
}
class _SocialNetworksComponent extends PositionComponent with HasGameRef {
_SocialNetworksComponent({
OnSocialShareTap? onShare,
}) : super(
anchor: Anchor.center,
position: Vector2(0, 12),
children: [
FacebookButtonComponent(onTap: onShare),
TwitterButtonComponent(onTap: onShare),
],
);
}
/// {@template facebook_button_component}
/// Button for sharing on Facebook.
/// {@endtemplate}
class FacebookButtonComponent extends SpriteComponent
with HasGameRef, Tappable {
/// {@macro facebook_button_component}
FacebookButtonComponent({
OnSocialShareTap? onTap,
}) : _onTap = onTap,
super(
anchor: Anchor.center,
position: Vector2(-5, 0),
);
final OnSocialShareTap? _onTap;
@override
bool onTapUp(TapUpInfo info) {
_onTap?.call(SharePlatform.facebook);
return true;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(Assets.images.backbox.button.facebook.keyName),
);
this.sprite = sprite;
size = sprite.originalSize / 25;
}
}
/// {@template twitter_button_component}
/// Button for sharing on Twitter.
/// {@endtemplate}
class TwitterButtonComponent extends SpriteComponent with HasGameRef, Tappable {
/// {@macro twitter_button_component}
TwitterButtonComponent({
OnSocialShareTap? onTap,
}) : _onTap = onTap,
super(
anchor: Anchor.center,
position: Vector2(5, 0),
);
final OnSocialShareTap? _onTap;
@override
bool onTapUp(TapUpInfo info) {
_onTap?.call(SharePlatform.twitter);
return true;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(Assets.images.backbox.button.twitter.keyName),
);
this.sprite = sprite;
size = sprite.originalSize / 25;
}
}
| pinball/lib/game/components/backbox/displays/share_display.dart/0 | {
"file_path": "pinball/lib/game/components/backbox/displays/share_display.dart",
"repo_id": "pinball",
"token_count": 1946
} | 1,084 |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets;
/// {@template launcher}
/// Channel on the right side of the board containing the [LaunchRamp],
/// [Plunger], and [RocketSpriteComponent].
/// {@endtemplate}
class Launcher extends Component {
/// {@macro launcher}
Launcher()
: super(
children: [
LaunchRamp(),
Flapper(),
Plunger()..initialPosition = Vector2(41, 43.7),
RocketSpriteComponent()..position = Vector2(42.8, 62.3),
],
);
}
| pinball/lib/game/components/launcher.dart/0 | {
"file_path": "pinball/lib/game/components/launcher.dart",
"repo_id": "pinball",
"token_count": 236
} | 1,085 |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/gen/gen.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// {@template game_hud}
/// Overlay on the [PinballGame].
///
/// Displays the current [GameState.displayScore], [GameState.rounds] and
/// animates when the player gets a [GameBonus].
/// {@endtemplate}
class GameHud extends StatefulWidget {
/// {@macro game_hud}
const GameHud({Key? key}) : super(key: key);
@override
State<GameHud> createState() => _GameHudState();
}
class _GameHudState extends State<GameHud> {
bool showAnimation = false;
/// Ratio from sprite frame (width 500, height 144) w / h = ratio
static const _ratio = 3.47;
@override
Widget build(BuildContext context) {
final isGameOver =
context.select((GameBloc bloc) => bloc.state.status.isGameOver);
final height = _calculateHeight(context);
return _ScoreViewDecoration(
child: SizedBox(
height: height,
width: height * _ratio,
child: BlocListener<GameBloc, GameState>(
listenWhen: (previous, current) =>
previous.bonusHistory.length != current.bonusHistory.length,
listener: (_, __) => setState(() => showAnimation = true),
child: AnimatedSwitcher(
duration: kThemeAnimationDuration,
child: showAnimation && !isGameOver
? _AnimationView(
onComplete: () {
if (mounted) {
setState(() => showAnimation = false);
}
},
)
: const ScoreView(),
),
),
),
);
}
double _calculateHeight(BuildContext context) {
final height = MediaQuery.of(context).size.height * 0.09;
if (height > 90) {
return 90;
} else if (height < 60) {
return 60;
} else {
return height;
}
}
}
class _ScoreViewDecoration extends StatelessWidget {
const _ScoreViewDecoration({
Key? key,
required this.child,
}) : super(key: key);
final Widget child;
@override
Widget build(BuildContext context) {
const radius = BorderRadius.all(Radius.circular(12));
const borderWidth = 5.0;
return DecoratedBox(
decoration: BoxDecoration(
borderRadius: radius,
border: Border.all(
color: PinballColors.white,
width: borderWidth,
),
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
Assets.images.score.miniScoreBackground.path,
),
),
),
child: Padding(
padding: const EdgeInsets.all(borderWidth - 1),
child: ClipRRect(
borderRadius: radius,
child: child,
),
),
);
}
}
class _AnimationView extends StatelessWidget {
const _AnimationView({
Key? key,
required this.onComplete,
}) : super(key: key);
final VoidCallback onComplete;
@override
Widget build(BuildContext context) {
final lastBonus = context.select(
(GameBloc bloc) => bloc.state.bonusHistory.last,
);
switch (lastBonus) {
case GameBonus.dashNest:
return BonusAnimation.dashNest(onCompleted: onComplete);
case GameBonus.sparkyTurboCharge:
return BonusAnimation.sparkyTurboCharge(onCompleted: onComplete);
case GameBonus.dinoChomp:
return BonusAnimation.dinoChomp(onCompleted: onComplete);
case GameBonus.googleWord:
return BonusAnimation.googleWord(onCompleted: onComplete);
case GameBonus.androidSpaceship:
return BonusAnimation.androidSpaceship(onCompleted: onComplete);
}
}
}
| pinball/lib/game/view/widgets/game_hud.dart/0 | {
"file_path": "pinball/lib/game/view/widgets/game_hud.dart",
"repo_id": "pinball",
"token_count": 1584
} | 1,086 |
import 'package:authentication_repository/authentication_repository.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/app/app.dart';
import 'package:pinball/bootstrap.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:platform_helper/platform_helper.dart';
import 'package:share_repository/share_repository.dart';
void main() {
bootstrap((firestore, firebaseAuth) async {
final leaderboardRepository = LeaderboardRepository(firestore);
const shareRepository =
ShareRepository(appUrl: ShareRepository.pinballGameUrl);
final authenticationRepository = AuthenticationRepository(firebaseAuth);
final pinballAudioPlayer = PinballAudioPlayer();
final platformHelper = PlatformHelper();
await Firebase.initializeApp();
await authenticationRepository.authenticateAnonymously();
return App(
authenticationRepository: authenticationRepository,
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
pinballAudioPlayer: pinballAudioPlayer,
platformHelper: platformHelper,
);
});
}
| pinball/lib/main.dart/0 | {
"file_path": "pinball/lib/main.dart",
"repo_id": "pinball",
"token_count": 376
} | 1,087 |
include: package:very_good_analysis/analysis_options.2.4.0.yaml | pinball/packages/authentication_repository/analysis_options.yaml/0 | {
"file_path": "pinball/packages/authentication_repository/analysis_options.yaml",
"repo_id": "pinball",
"token_count": 22
} | 1,088 |
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
/// {@template leaderboard_repository}
/// Repository to access leaderboard data in Firebase Cloud Firestore.
/// {@endtemplate}
class LeaderboardRepository {
/// {@macro leaderboard_repository}
const LeaderboardRepository(
FirebaseFirestore firebaseFirestore,
) : _firebaseFirestore = firebaseFirestore;
final FirebaseFirestore _firebaseFirestore;
static const _leaderboardLimit = 10;
static const _leaderboardCollectionName = 'leaderboard';
static const _scoreFieldName = 'score';
/// Acquires top 10 [LeaderboardEntryData]s.
Future<List<LeaderboardEntryData>> fetchTop10Leaderboard() async {
try {
final querySnapshot = await _firebaseFirestore
.collection(_leaderboardCollectionName)
.orderBy(_scoreFieldName, descending: true)
.limit(_leaderboardLimit)
.get();
final documents = querySnapshot.docs;
return documents.toLeaderboard();
} on LeaderboardDeserializationException {
rethrow;
} on Exception catch (error, stackTrace) {
throw FetchTop10LeaderboardException(error, stackTrace);
}
}
/// Adds player's score entry to the leaderboard if it is within the top-10
Future<void> addLeaderboardEntry(
LeaderboardEntryData entry,
) async {
final leaderboard = await _fetchLeaderboardSortedByScore();
if (leaderboard.length < 10) {
await _saveScore(entry);
} else {
final tenthPositionScore = leaderboard[9].score;
if (entry.score > tenthPositionScore) {
await _saveScore(entry);
}
}
}
Future<List<LeaderboardEntryData>> _fetchLeaderboardSortedByScore() async {
try {
final querySnapshot = await _firebaseFirestore
.collection(_leaderboardCollectionName)
.orderBy(_scoreFieldName, descending: true)
.get();
final documents = querySnapshot.docs;
return documents.toLeaderboard();
} on Exception catch (error, stackTrace) {
throw FetchLeaderboardException(error, stackTrace);
}
}
Future<void> _saveScore(LeaderboardEntryData entry) {
try {
return _firebaseFirestore
.collection(_leaderboardCollectionName)
.add(entry.toJson());
} on Exception catch (error, stackTrace) {
throw AddLeaderboardEntryException(error, stackTrace);
}
}
}
extension on List<QueryDocumentSnapshot> {
List<LeaderboardEntryData> toLeaderboard() {
final leaderboardEntries = <LeaderboardEntryData>[];
for (final document in this) {
final data = document.data() as Map<String, dynamic>?;
if (data != null) {
try {
leaderboardEntries.add(LeaderboardEntryData.fromJson(data));
} catch (error, stackTrace) {
throw LeaderboardDeserializationException(error, stackTrace);
}
}
}
return leaderboardEntries;
}
}
| pinball/packages/leaderboard_repository/lib/src/leaderboard_repository.dart/0 | {
"file_path": "pinball/packages/leaderboard_repository/lib/src/leaderboard_repository.dart",
"repo_id": "pinball",
"token_count": 1063
} | 1,089 |
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/android_bumper/behaviors/behaviors.dart';
import 'package:pinball_components/src/components/bumping_behavior.dart';
import 'package:pinball_flame/pinball_flame.dart';
export 'cubit/android_bumper_cubit.dart';
/// {@template android_bumper}
/// Bumper for area under the [AndroidSpaceship].
/// {@endtemplate}
class AndroidBumper extends BodyComponent with InitialPosition, ZIndex {
/// {@macro android_bumper}
AndroidBumper._({
required double majorRadius,
required double minorRadius,
required String litAssetPath,
required String dimmedAssetPath,
required Vector2 spritePosition,
Iterable<Component>? children,
required this.bloc,
}) : _majorRadius = majorRadius,
_minorRadius = minorRadius,
super(
renderBody: false,
children: [
AndroidBumperBallContactBehavior(),
AndroidBumperBlinkingBehavior(),
_AndroidBumperSpriteGroupComponent(
dimmedAssetPath: dimmedAssetPath,
litAssetPath: litAssetPath,
position: spritePosition,
state: bloc.state,
),
...?children,
],
) {
zIndex = ZIndexes.androidBumper;
}
/// {@macro android_bumper}
AndroidBumper.a({
Iterable<Component>? children,
}) : this._(
majorRadius: 3.52,
minorRadius: 2.97,
litAssetPath: Assets.images.android.bumper.a.lit.keyName,
dimmedAssetPath: Assets.images.android.bumper.a.dimmed.keyName,
spritePosition: Vector2(0, -0.1),
bloc: AndroidBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// {@macro android_bumper}
AndroidBumper.b({
Iterable<Component>? children,
}) : this._(
majorRadius: 3.19,
minorRadius: 2.79,
litAssetPath: Assets.images.android.bumper.b.lit.keyName,
dimmedAssetPath: Assets.images.android.bumper.b.dimmed.keyName,
spritePosition: Vector2(0, -0.1),
bloc: AndroidBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// {@macro android_bumper}
AndroidBumper.cow({
Iterable<Component>? children,
}) : this._(
majorRadius: 3.45,
minorRadius: 3.11,
litAssetPath: Assets.images.android.bumper.cow.lit.keyName,
dimmedAssetPath: Assets.images.android.bumper.cow.dimmed.keyName,
spritePosition: Vector2(0, -0.35),
bloc: AndroidBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// Creates an [AndroidBumper] without any children.
///
/// This can be used for testing [AndroidBumper]'s behaviors in isolation.
@visibleForTesting
AndroidBumper.test({
required this.bloc,
}) : _majorRadius = 3.52,
_minorRadius = 2.97;
final double _majorRadius;
final double _minorRadius;
final AndroidBumperCubit bloc;
@override
void onRemove() {
bloc.close();
super.onRemove();
}
@override
Body createBody() {
final shape = EllipseShape(
center: Vector2.zero(),
majorRadius: _majorRadius,
minorRadius: _minorRadius,
)..rotate(1.29);
final bodyDef = BodyDef(
position: initialPosition,
);
return world.createBody(bodyDef)..createFixtureFromShape(shape);
}
}
class _AndroidBumperSpriteGroupComponent
extends SpriteGroupComponent<AndroidBumperState>
with HasGameRef, ParentIsA<AndroidBumper> {
_AndroidBumperSpriteGroupComponent({
required String litAssetPath,
required String dimmedAssetPath,
required Vector2 position,
required AndroidBumperState state,
}) : _litAssetPath = litAssetPath,
_dimmedAssetPath = dimmedAssetPath,
super(
anchor: Anchor.center,
position: position,
current: state,
);
final String _litAssetPath;
final String _dimmedAssetPath;
@override
Future<void> onLoad() async {
await super.onLoad();
parent.bloc.stream.listen((state) => current = state);
final sprites = {
AndroidBumperState.lit: Sprite(
gameRef.images.fromCache(_litAssetPath),
),
AndroidBumperState.dimmed:
Sprite(gameRef.images.fromCache(_dimmedAssetPath)),
};
this.sprites = sprites;
size = sprites[current]!.originalSize / 10;
}
}
| pinball/packages/pinball_components/lib/src/components/android_bumper/android_bumper.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/android_bumper/android_bumper.dart",
"repo_id": "pinball",
"token_count": 2010
} | 1,090 |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Scales the ball's body and sprite according to its position on the board.
class BallScalingBehavior extends Component with ParentIsA<Ball> {
@override
void update(double dt) {
super.update(dt);
final boardHeight = BoardDimensions.bounds.height;
const maxShrinkValue = BoardDimensions.perspectiveShrinkFactor;
final standardizedYPosition = parent.body.position.y + (boardHeight / 2);
final scaleFactor = maxShrinkValue +
((standardizedYPosition / boardHeight) * (1 - maxShrinkValue));
parent.body.fixtures.first.shape.radius = (Ball.size.x / 2) * scaleFactor;
final ballSprite = parent.descendants().whereType<SpriteComponent>();
if (ballSprite.isNotEmpty) {
ballSprite.single.scale.setValues(
scaleFactor,
scaleFactor,
);
}
}
}
| pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_scaling_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_scaling_behavior.dart",
"repo_id": "pinball",
"token_count": 339
} | 1,091 |
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template chrome_dino_swivel_behavior}
/// Swivels the [ChromeDino] up and down periodically to match its animation
/// sequence.
/// {@endtemplate}
class ChromeDinoSwivelingBehavior extends TimerComponent
with ParentIsA<ChromeDino> {
/// {@macro chrome_dino_swivel_behavior}
ChromeDinoSwivelingBehavior()
: super(
period: 98 / 48,
repeat: true,
);
late final RevoluteJoint _joint;
@override
Future<void> onLoad() async {
final anchor = _ChromeDinoAnchor()
..initialPosition = parent.initialPosition + Vector2(9, -4);
await add(anchor);
final jointDef = _ChromeDinoAnchorRevoluteJointDef(
chromeDino: parent,
anchor: anchor,
);
_joint = RevoluteJoint(jointDef);
parent.world.createJoint(_joint);
}
@override
void update(double dt) {
super.update(dt);
final angle = _joint.jointAngle();
if (angle < _joint.upperLimit &&
angle > _joint.lowerLimit &&
parent.bloc.state.isMouthOpen) {
parent.bloc.onCloseMouth();
} else if ((angle >= _joint.upperLimit || angle <= _joint.lowerLimit) &&
!parent.bloc.state.isMouthOpen) {
parent.bloc.onOpenMouth();
}
}
@override
void onTick() {
super.onTick();
_joint.setMotorSpeed(-_joint.motorSpeed);
}
}
class _ChromeDinoAnchor extends JointAnchor
with ParentIsA<ChromeDinoSwivelingBehavior> {
@override
void onMount() {
super.onMount();
parent.parent.children
.whereType<SpriteAnimationComponent>()
.forEach((sprite) {
sprite.animation!.currentIndex = 45;
sprite.changeParent(this);
});
}
}
class _ChromeDinoAnchorRevoluteJointDef extends RevoluteJointDef {
_ChromeDinoAnchorRevoluteJointDef({
required ChromeDino chromeDino,
required _ChromeDinoAnchor anchor,
}) {
initialize(
chromeDino.body,
anchor.body,
chromeDino.body.position + anchor.body.position,
);
enableLimit = true;
lowerAngle = -ChromeDino.halfSweepingAngle;
upperAngle = ChromeDino.halfSweepingAngle;
enableMotor = true;
maxMotorTorque = chromeDino.body.mass * 255;
motorSpeed = 2;
}
}
| pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_swiveling_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_swiveling_behavior.dart",
"repo_id": "pinball",
"token_count": 968
} | 1,092 |
export 'flipper_jointing_behavior.dart';
export 'flipper_key_controlling_behavior.dart';
export 'flipper_moving_behavior.dart';
export 'flipper_noise_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/flipper/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/flipper/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 58
} | 1,093 |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
export 'behaviors/behaviors.dart';
export 'cubit/google_word_cubit.dart';
/// {@template google_word}
/// Loads all [GoogleLetter]s to compose a [GoogleWord].
/// {@endtemplate}
class GoogleWord extends PositionComponent {
/// {@macro google_word}
GoogleWord({
required Vector2 position,
}) : super(
position: position,
children: [
GoogleLetter(0)..position = Vector2(-13.1, 1.72),
GoogleLetter(1)..position = Vector2(-8.33, -0.75),
GoogleLetter(2)..position = Vector2(-2.88, -1.85),
GoogleLetter(3)..position = Vector2(2.88, -1.85),
GoogleLetter(4)..position = Vector2(8.33, -0.75),
GoogleLetter(5)..position = Vector2(13.1, 1.72),
],
);
}
| pinball/packages/pinball_components/lib/src/components/google_word/google_word.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/google_word/google_word.dart",
"repo_id": "pinball",
"token_count": 378
} | 1,094 |
part of 'multiball_cubit.dart';
enum MultiballLightState {
lit,
dimmed,
}
// Indicates if the blinking animation is running.
enum MultiballAnimationState {
idle,
blinking,
}
class MultiballState extends Equatable {
const MultiballState({
required this.lightState,
required this.animationState,
});
const MultiballState.initial()
: this(
lightState: MultiballLightState.dimmed,
animationState: MultiballAnimationState.idle,
);
final MultiballLightState lightState;
final MultiballAnimationState animationState;
MultiballState copyWith({
MultiballLightState? lightState,
MultiballAnimationState? animationState,
}) {
return MultiballState(
lightState: lightState ?? this.lightState,
animationState: animationState ?? this.animationState,
);
}
@override
List<Object> get props => [lightState, animationState];
}
| pinball/packages/pinball_components/lib/src/components/multiball/cubit/multiball_state.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/multiball/cubit/multiball_state.dart",
"repo_id": "pinball",
"token_count": 317
} | 1,095 |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Scales a [ScoreComponent] according to its position on the board.
class ScoreComponentScalingBehavior extends Component
with ParentIsA<SpriteComponent> {
@override
void update(double dt) {
super.update(dt);
final boardHeight = BoardDimensions.bounds.height;
const maxShrinkValue = 0.83;
final augmentedPosition = parent.position.y * 3;
final standardizedYPosition = augmentedPosition + (boardHeight / 2);
final scaleFactor = maxShrinkValue +
((standardizedYPosition / boardHeight) * (1 - maxShrinkValue));
parent.scale.setValues(
scaleFactor,
scaleFactor,
);
}
}
| pinball/packages/pinball_components/lib/src/components/score_component/behaviors/score_component_scaling_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/score_component/behaviors/score_component_scaling_behavior.dart",
"repo_id": "pinball",
"token_count": 264
} | 1,096 |
// ignore_for_file: comment_references
part of 'spaceship_ramp_cubit.dart';
class SpaceshipRampState extends Equatable {
const SpaceshipRampState({
required this.hits,
required this.lightState,
}) : assert(hits >= 0, "Hits can't be negative");
const SpaceshipRampState.initial()
: this(
hits: 0,
lightState: ArrowLightState.inactive,
);
final int hits;
final ArrowLightState lightState;
bool get arrowFullyLit => lightState == ArrowLightState.active5;
SpaceshipRampState copyWith({
int? hits,
ArrowLightState? lightState,
}) {
return SpaceshipRampState(
hits: hits ?? this.hits,
lightState: lightState ?? this.lightState,
);
}
@override
List<Object?> get props => [hits, lightState];
}
/// Indicates the state of the arrow on the [SpaceshipRamp].
enum ArrowLightState {
/// Arrow with no lights lit up.
inactive,
/// Arrow with 1 light lit up.
active1,
/// Arrow with 2 lights lit up.
active2,
/// Arrow with 3 lights lit up.
active3,
/// Arrow with 4 lights lit up.
active4,
/// Arrow with all 5 lights lit up.
active5,
}
| pinball/packages/pinball_components/lib/src/components/spaceship_ramp/cubit/spaceship_ramp_state.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/spaceship_ramp/cubit/spaceship_ramp_state.dart",
"repo_id": "pinball",
"token_count": 414
} | 1,097 |
import 'package:intl/intl.dart';
final _numberFormat = NumberFormat('#,###');
/// Adds score related extensions to int
extension ScoreX on int {
/// Formats this number as a score value
String formatScore() {
return _numberFormat.format(this);
}
}
| pinball/packages/pinball_components/lib/src/extensions/score.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/extensions/score.dart",
"repo_id": "pinball",
"token_count": 81
} | 1,098 |
import 'dart:async';
import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class AndroidBumperCowGame extends BallGame {
AndroidBumperCowGame()
: super(
imagesFileNames: [
Assets.images.android.bumper.cow.lit.keyName,
Assets.images.android.bumper.cow.dimmed.keyName,
],
);
static const description = '''
Shows how a AndroidBumper.cow is rendered.
- Activate the "trace" parameter to overlay the body.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
camera.followVector2(Vector2.zero());
await add(
AndroidBumper.cow()..priority = 1,
);
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_bumper_cow_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_bumper_cow_game.dart",
"repo_id": "pinball",
"token_count": 312
} | 1,099 |
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/boundaries/boundaries_game.dart';
void addBoundariesStories(Dashbook dashbook) {
dashbook.storiesOf('Boundaries').addGame(
title: 'Traced',
description: BoundariesGame.description,
gameBuilder: (_) => BoundariesGame(),
);
}
| pinball/packages/pinball_components/sandbox/lib/stories/boundaries/stories.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/boundaries/stories.dart",
"repo_id": "pinball",
"token_count": 136
} | 1,100 |
import 'dart:async';
import 'package:flame/input.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class LaunchRampGame extends BallGame {
LaunchRampGame()
: super(
ballPriority: ZIndexes.ballOnLaunchRamp,
ballLayer: Layer.launcher,
imagesFileNames: [
Assets.images.launchRamp.ramp.keyName,
Assets.images.launchRamp.backgroundRailing.keyName,
Assets.images.launchRamp.foregroundRailing.keyName,
],
);
static const description = '''
Shows how the LaunchRamp is rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a ball into the game.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
camera
..followVector2(Vector2.zero())
..zoom = 7.5;
await add(LaunchRamp());
await ready();
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/launch_ramp/launch_ramp_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/launch_ramp/launch_ramp_game.dart",
"repo_id": "pinball",
"token_count": 418
} | 1,101 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group(
'AndroidBumperCubit',
() {
blocTest<AndroidBumperCubit, AndroidBumperState>(
'onBallContacted emits dimmed',
build: AndroidBumperCubit.new,
act: (bloc) => bloc.onBallContacted(),
expect: () => [AndroidBumperState.dimmed],
);
blocTest<AndroidBumperCubit, AndroidBumperState>(
'onBlinked emits lit',
build: AndroidBumperCubit.new,
act: (bloc) => bloc.onBlinked(),
expect: () => [AndroidBumperState.lit],
);
},
);
}
| pinball/packages/pinball_components/test/src/components/android_bumper/cubit/android_bumper_cubit_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/android_bumper/cubit/android_bumper_cubit_test.dart",
"repo_id": "pinball",
"token_count": 301
} | 1,102 |
import 'package:flame/extensions.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group('BoardDimensions', () {
test('has size', () {
expect(BoardDimensions.size, equals(Vector2(101.6, 143.8)));
});
test('has bounds', () {
expect(BoardDimensions.bounds, isNotNull);
});
test('has perspectiveAngle', () {
expect(BoardDimensions.perspectiveAngle, isNotNull);
});
test('has perspectiveShrinkFactor', () {
expect(BoardDimensions.perspectiveShrinkFactor, equals(0.63));
});
});
}
| pinball/packages/pinball_components/test/src/components/board_dimensions_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/board_dimensions_test.dart",
"repo_id": "pinball",
"token_count": 237
} | 1,103 |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/dash_bumper/behaviors/behaviors.dart';
import '../../../../helpers/helpers.dart';
class _MockDashBumpersCubit extends Mock implements DashBumpersCubit {}
class _MockBall extends Mock implements Ball {}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
group(
'DashBumperBallContactBehavior',
() {
test('can be instantiated', () {
expect(
DashBumperBallContactBehavior(),
isA<DashBumperBallContactBehavior>(),
);
});
flameTester.test(
'beginContact emits onBallContacted with the bumper ID '
'when contacts with a ball',
(game) async {
final behavior = DashBumperBallContactBehavior();
final bloc = _MockDashBumpersCubit();
const id = DashBumperId.main;
whenListen(
bloc,
const Stream<DashBumperSpriteState>.empty(),
initialState: DashBumperSpriteState.active,
);
final bumper = DashBumper.test(id: id);
await bumper.add(behavior);
await game.ensureAdd(
FlameBlocProvider<DashBumpersCubit, DashBumpersState>.value(
value: bloc,
children: [bumper],
),
);
behavior.beginContact(_MockBall(), _MockContact());
verify(() => bloc.onBallContacted(id)).called(1);
},
);
},
);
}
| pinball/packages/pinball_components/test/src/components/dash_nest_bumper/behaviors/dash_bumper_ball_contact_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/dash_nest_bumper/behaviors/dash_bumper_ball_contact_behavior_test.dart",
"repo_id": "pinball",
"token_count": 814
} | 1,104 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/google_rollover/behaviors/behaviors.dart';
import '../../../helpers/helpers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.googleRollover.left.decal.keyName,
Assets.images.googleRollover.left.pin.keyName,
Assets.images.googleRollover.right.decal.keyName,
Assets.images.googleRollover.right.pin.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('GoogleRollover', () {
test('can be instantiated', () {
expect(
GoogleRollover(side: BoardSide.left),
isA<GoogleRollover>(),
);
});
flameTester.test('left loads correctly', (game) async {
final googleRollover = GoogleRollover(side: BoardSide.left);
await game.ensureAdd(googleRollover);
expect(game.contains(googleRollover), isTrue);
});
flameTester.test('right loads correctly', (game) async {
final googleRollover = GoogleRollover(side: BoardSide.right);
await game.ensureAdd(googleRollover);
expect(game.contains(googleRollover), isTrue);
});
group('adds', () {
flameTester.test('new children', (game) async {
final component = Component();
final googleRollover = GoogleRollover(
side: BoardSide.left,
children: [component],
);
await game.ensureAdd(googleRollover);
expect(googleRollover.children, contains(component));
});
flameTester.test('a GoogleRolloverBallContactBehavior', (game) async {
final googleRollover = GoogleRollover(side: BoardSide.left);
await game.ensureAdd(googleRollover);
expect(
googleRollover.children
.whereType<GoogleRolloverBallContactBehavior>()
.single,
isNotNull,
);
});
});
flameTester.test(
'pin stops animating after animation completes',
(game) async {
final googleRollover = GoogleRollover(side: BoardSide.left);
await game.ensureAdd(googleRollover);
final pinSpriteAnimationComponent =
googleRollover.firstChild<SpriteAnimationComponent>()!;
pinSpriteAnimationComponent.playing = true;
game.update(
pinSpriteAnimationComponent.animation!.totalDuration() + 0.1,
);
expect(pinSpriteAnimationComponent.playing, isFalse);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/google_rollover/google_rollover_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/google_rollover/google_rollover_test.dart",
"repo_id": "pinball",
"token_count": 1044
} | 1,105 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/src/pinball_components.dart';
void main() {
group('MultiballState', () {
test('supports value equality', () {
expect(
MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
),
equals(
MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
),
),
);
});
group('constructor', () {
test('can be instantiated', () {
expect(
MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
),
isNotNull,
);
});
});
group('copyWith', () {
test(
'copies correctly '
'when no argument specified',
() {
final multiballState = MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
);
expect(
multiballState.copyWith(),
equals(multiballState),
);
},
);
test(
'copies correctly '
'when all arguments specified',
() {
final multiballState = MultiballState(
animationState: MultiballAnimationState.idle,
lightState: MultiballLightState.dimmed,
);
final otherMultiballState = MultiballState(
animationState: MultiballAnimationState.blinking,
lightState: MultiballLightState.lit,
);
expect(multiballState, isNot(equals(otherMultiballState)));
expect(
multiballState.copyWith(
animationState: MultiballAnimationState.blinking,
lightState: MultiballLightState.lit,
),
equals(otherMultiballState),
);
},
);
});
});
}
| pinball/packages/pinball_components/test/src/components/multiball/cubit/multiball_state_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/multiball/cubit/multiball_state_test.dart",
"repo_id": "pinball",
"token_count": 1011
} | 1,106 |
// ignore_for_file: cascade_invocations
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.signpost.inactive.keyName,
Assets.images.signpost.active1.keyName,
Assets.images.signpost.active2.keyName,
Assets.images.signpost.active3.keyName,
]);
}
Future<void> pump(
Signpost child, {
SignpostCubit? signpostBloc,
DashBumpersCubit? dashBumpersBloc,
}) async {
await onLoad();
await ensureAdd(
FlameMultiBlocProvider(
providers: [
FlameBlocProvider<SignpostCubit, SignpostState>.value(
value: signpostBloc ?? SignpostCubit(),
),
FlameBlocProvider<DashBumpersCubit, DashBumpersState>.value(
value: dashBumpersBloc ?? DashBumpersCubit(),
),
],
children: [child],
),
);
}
}
class _MockSignpostCubit extends Mock implements SignpostCubit {}
class _MockDashBumpersCubit extends Mock implements DashBumpersCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('Signpost', () {
const goldenPath = '../golden/signpost/';
test('can be instantiated', () {
expect(Signpost(), isA<Signpost>());
});
flameTester.test(
'can be added',
(game) async {
final signpost = Signpost();
await game.pump(signpost);
expect(game.descendants().contains(signpost), isTrue);
},
);
group('renders correctly', () {
flameTester.testGameWidget(
'inactive sprite',
setUp: (game, tester) async {
final signpost = Signpost();
await game.pump(signpost);
await tester.pump();
expect(
signpost.firstChild<SpriteGroupComponent>()!.current,
equals(SignpostState.inactive),
);
game.camera.followVector2(Vector2.zero());
},
verify: (game, tester) async {
await expectLater(
find.byGame<_TestGame>(),
matchesGoldenFile('${goldenPath}inactive.png'),
);
},
);
flameTester.testGameWidget(
'active1 sprite',
setUp: (game, tester) async {
final signpost = Signpost();
final bloc = SignpostCubit();
await game.pump(signpost, signpostBloc: bloc);
bloc.onProgressed();
await tester.pump();
expect(
signpost.firstChild<SpriteGroupComponent>()!.current,
equals(SignpostState.active1),
);
game.camera.followVector2(Vector2.zero());
},
verify: (game, tester) async {
await expectLater(
find.byGame<_TestGame>(),
matchesGoldenFile('${goldenPath}active1.png'),
);
},
);
flameTester.testGameWidget(
'active2 sprite',
setUp: (game, tester) async {
final signpost = Signpost();
final bloc = SignpostCubit();
await game.pump(signpost, signpostBloc: bloc);
bloc
..onProgressed()
..onProgressed();
await tester.pump();
expect(
signpost.firstChild<SpriteGroupComponent>()!.current,
equals(SignpostState.active2),
);
game.camera.followVector2(Vector2.zero());
},
verify: (game, tester) async {
await expectLater(
find.byGame<_TestGame>(),
matchesGoldenFile('${goldenPath}active2.png'),
);
},
);
flameTester.testGameWidget(
'active3 sprite',
setUp: (game, tester) async {
final signpost = Signpost();
final bloc = SignpostCubit();
await game.pump(signpost, signpostBloc: bloc);
bloc
..onProgressed()
..onProgressed()
..onProgressed();
await tester.pump();
expect(
signpost.firstChild<SpriteGroupComponent>()!.current,
equals(SignpostState.active3),
);
game.camera.followVector2(Vector2.zero());
},
verify: (game, tester) async {
await expectLater(
find.byGame<_TestGame>(),
matchesGoldenFile('${goldenPath}active3.png'),
);
},
);
});
flameTester.testGameWidget(
'listenWhen is true when all dash bumpers are activated',
setUp: (game, tester) async {
final activatedBumpersState = DashBumpersState(
bumperSpriteStates: {
for (var id in DashBumperId.values) id: DashBumperSpriteState.active
},
);
final signpost = Signpost();
final dashBumpersBloc = _MockDashBumpersCubit();
whenListen(
dashBumpersBloc,
const Stream<DashBumpersState>.empty(),
initialState: DashBumpersState.initial(),
);
await game.pump(signpost, dashBumpersBloc: dashBumpersBloc);
final signpostListener = game
.descendants()
.whereType<FlameBlocListener<DashBumpersCubit, DashBumpersState>>()
.single;
final listenWhen = signpostListener.listenWhen(
DashBumpersState.initial(),
activatedBumpersState,
);
expect(listenWhen, isTrue);
},
);
flameTester.test(
'onNewState calls onProgressed and onReset',
(game) async {
final signpost = Signpost();
final signpostBloc = _MockSignpostCubit();
whenListen(
signpostBloc,
const Stream<SignpostState>.empty(),
initialState: SignpostState.inactive,
);
final dashBumpersBloc = _MockDashBumpersCubit();
whenListen(
dashBumpersBloc,
const Stream<DashBumpersState>.empty(),
initialState: DashBumpersState.initial(),
);
await game.pump(
signpost,
signpostBloc: signpostBloc,
dashBumpersBloc: dashBumpersBloc,
);
game
.descendants()
.whereType<FlameBlocListener<DashBumpersCubit, DashBumpersState>>()
.single
.onNewState(DashBumpersState.initial());
verify(signpostBloc.onProgressed).called(1);
verify(dashBumpersBloc.onReset).called(1);
},
);
flameTester.test('adds new children', (game) async {
final component = Component();
final signpost = Signpost(
children: [component],
);
await game.pump(signpost);
expect(signpost.children, contains(component));
});
});
}
| pinball/packages/pinball_components/test/src/components/signpost/signpost_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/signpost/signpost_test.dart",
"repo_id": "pinball",
"token_count": 3321
} | 1,107 |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/bumping_behavior.dart';
import 'package:pinball_components/src/components/sparky_bumper/behaviors/behaviors.dart';
import '../../../helpers/helpers.dart';
class _MockSparkyBumperCubit extends Mock implements SparkyBumperCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.sparky.bumper.a.lit.keyName,
Assets.images.sparky.bumper.a.dimmed.keyName,
Assets.images.sparky.bumper.b.lit.keyName,
Assets.images.sparky.bumper.b.dimmed.keyName,
Assets.images.sparky.bumper.c.lit.keyName,
Assets.images.sparky.bumper.c.dimmed.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('SparkyBumper', () {
flameTester.test('"a" loads correctly', (game) async {
final sparkyBumper = SparkyBumper.a();
await game.ensureAdd(sparkyBumper);
expect(game.contains(sparkyBumper), isTrue);
});
flameTester.test('"b" loads correctly', (game) async {
final sparkyBumper = SparkyBumper.b();
await game.ensureAdd(sparkyBumper);
expect(game.contains(sparkyBumper), isTrue);
});
flameTester.test('"c" loads correctly', (game) async {
final sparkyBumper = SparkyBumper.c();
await game.ensureAdd(sparkyBumper);
expect(game.contains(sparkyBumper), isTrue);
});
flameTester.test('closes bloc when removed', (game) async {
final bloc = _MockSparkyBumperCubit();
whenListen(
bloc,
const Stream<SparkyBumperState>.empty(),
initialState: SparkyBumperState.lit,
);
when(bloc.close).thenAnswer((_) async {});
final sparkyBumper = SparkyBumper.test(bloc: bloc);
await game.ensureAdd(sparkyBumper);
game.remove(sparkyBumper);
await game.ready();
verify(bloc.close).called(1);
});
group('adds', () {
flameTester.test('a SparkyBumperBallContactBehavior', (game) async {
final sparkyBumper = SparkyBumper.a();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children
.whereType<SparkyBumperBallContactBehavior>()
.single,
isNotNull,
);
});
flameTester.test('a SparkyBumperBlinkingBehavior', (game) async {
final sparkyBumper = SparkyBumper.a();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children
.whereType<SparkyBumperBlinkingBehavior>()
.single,
isNotNull,
);
});
});
group("'a' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final sparkyBumper = SparkyBumper.a(
children: [component],
);
await game.ensureAdd(sparkyBumper);
expect(sparkyBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final sparkyBumper = SparkyBumper.a();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
group("'b' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final sparkyBumper = SparkyBumper.b(
children: [component],
);
await game.ensureAdd(sparkyBumper);
expect(sparkyBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final sparkyBumper = SparkyBumper.b();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
group("'c' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final sparkyBumper = SparkyBumper.c(
children: [component],
);
await game.ensureAdd(sparkyBumper);
expect(sparkyBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final sparkyBumper = SparkyBumper.c();
await game.ensureAdd(sparkyBumper);
expect(
sparkyBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
});
});
}
| pinball/packages/pinball_components/test/src/components/sparky_bumper/sparky_bumper_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/sparky_bumper/sparky_bumper_test.dart",
"repo_id": "pinball",
"token_count": 2119
} | 1,108 |
import 'dart:ui';
import 'package:collection/collection.dart' as collection;
import 'package:flame/components.dart';
import 'package:pinball_flame/src/canvas/canvas_wrapper.dart';
/// {@template z_canvas_component}
/// Draws [ZIndex] components after the all non-[ZIndex] components have been
/// drawn.
/// {@endtemplate}
class ZCanvasComponent extends Component {
/// {@macro z_canvas_component}
ZCanvasComponent({
Iterable<Component>? children,
}) : _zCanvas = _ZCanvas(),
super(children: children);
final _ZCanvas _zCanvas;
@override
void renderTree(Canvas canvas) {
_zCanvas.canvas = canvas;
super.renderTree(_zCanvas);
_zCanvas.render();
}
}
/// Apply to any [Component] that will be rendered according to a
/// [ZIndex.zIndex].
///
/// [ZIndex] components must be descendants of a [ZCanvasComponent].
///
/// {@macro z_canvas.render}
mixin ZIndex on Component {
/// The z-index of this component.
///
/// The higher the value, the later the component will be drawn. Hence,
/// rendering in front of [Component]s with lower [zIndex] values.
int zIndex = 0;
@override
void renderTree(
Canvas canvas,
) {
if (canvas is _ZCanvas) {
canvas.buffer(this);
} else {
super.renderTree(canvas);
}
}
}
/// The [_ZCanvas] allows to postpone the rendering of [ZIndex] components.
///
/// You should not use this class directly.
class _ZCanvas extends CanvasWrapper {
final List<ZIndex> _zBuffer = [];
/// Postpones the rendering of [ZIndex] component and its children.
void buffer(ZIndex component) {
final lowerBound = collection.lowerBound<ZIndex>(
_zBuffer,
component,
compare: (a, b) => a.zIndex.compareTo(b.zIndex),
);
_zBuffer.insert(lowerBound, component);
}
/// Renders all [ZIndex] components and their children.
///
/// {@template z_canvas.render}
/// The rendering order is defined by the parent [ZIndex]. The children of
/// the same parent are rendered in the order they were added.
///
/// If two [Component]s ever overlap each other, and have the same
/// [ZIndex.zIndex], there is no guarantee that the first one will be rendered
/// before the second one.
/// {@endtemplate}
void render() => _zBuffer
..forEach(_render)
..clear();
void _render(Component component) => component.renderTree(canvas);
}
| pinball/packages/pinball_flame/lib/src/canvas/z_canvas_component.dart/0 | {
"file_path": "pinball/packages/pinball_flame/lib/src/canvas/z_canvas_component.dart",
"repo_id": "pinball",
"token_count": 794
} | 1,109 |
// ignore_for_file: cascade_invocations
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_flame/src/canvas/canvas_component.dart';
class _TestSpriteComponent extends SpriteComponent {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('CanvasComponent', () {
final flameTester = FlameTester(FlameGame.new);
test('can be instantiated', () {
expect(
CanvasComponent(),
isA<CanvasComponent>(),
);
});
flameTester.test('loads correctly', (game) async {
final component = CanvasComponent();
await game.ensureAdd(component);
expect(game.contains(component), isTrue);
});
flameTester.test(
'adds children',
(game) async {
final component = Component();
final canvas = CanvasComponent(
onSpritePainted: (paint) => paint.filterQuality = FilterQuality.high,
children: [component],
);
await game.ensureAdd(canvas);
expect(
canvas.children.contains(component),
isTrue,
);
},
);
flameTester.testGameWidget(
'calls onSpritePainted when painting a sprite',
setUp: (game, tester) async {
final spriteComponent = _TestSpriteComponent();
final completer = Completer<Image>();
decodeImageFromList(
Uint8List.fromList(_image),
completer.complete,
);
spriteComponent.sprite = Sprite(await completer.future);
var calls = 0;
final canvas = CanvasComponent(
onSpritePainted: (paint) => calls++,
children: [spriteComponent],
);
await game.ensureAdd(canvas);
await tester.pump();
expect(calls, equals(1));
},
);
});
}
const List<int> _image = <int>[
0x89,
0x50,
0x4E,
0x47,
0x0D,
0x0A,
0x1A,
0x0A,
0x00,
0x00,
0x00,
0x0D,
0x49,
0x48,
0x44,
0x52,
0x00,
0x00,
0x00,
0x01,
0x00,
0x00,
0x00,
0x01,
0x08,
0x06,
0x00,
0x00,
0x00,
0x1F,
0x15,
0xC4,
0x89,
0x00,
0x00,
0x00,
0x0A,
0x49,
0x44,
0x41,
0x54,
0x78,
0x9C,
0x63,
0x00,
0x01,
0x00,
0x00,
0x05,
0x00,
0x01,
0x0D,
0x0A,
0x2D,
0xB4,
0x00,
0x00,
0x00,
0x00,
0x49,
0x45,
0x4E,
0x44,
0xAE,
];
| pinball/packages/pinball_flame/test/src/canvas/canvas_component_test.dart/0 | {
"file_path": "pinball/packages/pinball_flame/test/src/canvas/canvas_component_test.dart",
"repo_id": "pinball",
"token_count": 1236
} | 1,110 |
name: pinball_theme
description: Package containing themes for pinball game.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.16.0 <3.0.0"
dependencies:
equatable: ^2.0.3
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
very_good_analysis: ^2.4.0
flutter:
generate: true
assets:
- assets/images/
- assets/images/android/
- assets/images/dash/
- assets/images/dino/
- assets/images/sparky/
flutter_gen:
assets:
package_parameter_enabled: true
output: lib/src/generated/
line_length: 80
integrations:
flutter_svg: true
| pinball/packages/pinball_theme/pubspec.yaml/0 | {
"file_path": "pinball/packages/pinball_theme/pubspec.yaml",
"repo_id": "pinball",
"token_count": 252
} | 1,111 |
import 'package:flutter/material.dart';
import 'package:pinball_ui/gen/gen.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// Enum with all possible directions of a [PinballDpadButton].
enum PinballDpadDirection {
/// Up
up,
/// Down
down,
/// Left
left,
/// Right
right,
}
extension _PinballDpadDirectionX on PinballDpadDirection {
String toAsset() {
switch (this) {
case PinballDpadDirection.up:
return Assets.images.button.dpadUp.keyName;
case PinballDpadDirection.down:
return Assets.images.button.dpadDown.keyName;
case PinballDpadDirection.left:
return Assets.images.button.dpadLeft.keyName;
case PinballDpadDirection.right:
return Assets.images.button.dpadRight.keyName;
}
}
}
/// {@template pinball_dpad_button}
/// Widget that renders a Dpad button with a given direction.
/// {@endtemplate}
class PinballDpadButton extends StatelessWidget {
/// {@macro pinball_dpad_button}
const PinballDpadButton({
Key? key,
required this.direction,
required this.onTap,
}) : super(key: key);
/// Which [PinballDpadDirection] this button is.
final PinballDpadDirection direction;
/// The function executed when the button is pressed.
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: PinballColors.transparent,
child: InkWell(
onTap: onTap,
highlightColor: PinballColors.transparent,
splashColor: PinballColors.transparent,
child: Image.asset(
direction.toAsset(),
width: 60,
height: 60,
),
),
);
}
}
| pinball/packages/pinball_ui/lib/src/widgets/pinball_dpad_button.dart/0 | {
"file_path": "pinball/packages/pinball_ui/lib/src/widgets/pinball_dpad_button.dart",
"repo_id": "pinball",
"token_count": 637
} | 1,112 |
# platform_helper
[![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link]
[![License: MIT][license_badge]][license_link]
Platform helper for Pinball application.
[license_badge]: https://img.shields.io/badge/license-MIT-blue.svg
[license_link]: https://opensource.org/licenses/MIT
[very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg
[very_good_analysis_link]: https://pub.dev/packages/very_good_analysis | pinball/packages/platform_helper/README.md/0 | {
"file_path": "pinball/packages/platform_helper/README.md",
"repo_id": "pinball",
"token_count": 166
} | 1,113 |
name: pinball
description: Google I/O 2022 Pinball game built with Flutter and Firebase
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.16.0 <3.0.0"
flutter: 2.10.5
dependencies:
authentication_repository:
path: packages/authentication_repository
bloc: ^8.0.2
cloud_firestore: ^3.1.10
equatable: ^2.0.3
firebase_auth: ^3.3.16
firebase_core: ^1.15.0
flame: ^1.1.1
flame_bloc: ^1.4.0
flame_forge2d:
git:
url: https://github.com/flame-engine/flame
path: packages/flame_forge2d/
ref: a50d4a1e7d9eaf66726ed1bb9894c9d495547d8f
flutter:
sdk: flutter
flutter_bloc: ^8.0.1
flutter_localizations:
sdk: flutter
geometry:
path: packages/geometry
intl: ^0.17.0
leaderboard_repository:
path: packages/leaderboard_repository
pinball_audio:
path: packages/pinball_audio
pinball_components:
path: packages/pinball_components
pinball_flame:
path: packages/pinball_flame
pinball_theme:
path: packages/pinball_theme
pinball_ui:
path: packages/pinball_ui
platform_helper:
path: packages/platform_helper
share_repository:
path: packages/share_repository
url_launcher: ^6.1.0
dev_dependencies:
bloc_test: ^9.0.2
flame_test: ^1.3.0
flutter_test:
sdk: flutter
mocktail: ^0.3.0
very_good_analysis: ^2.4.0
flutter:
uses-material-design: true
generate: true
assets:
- assets/images/components/
- assets/images/bonus_animation/
- assets/images/score/
- assets/images/loading_game/
flutter_gen:
line_length: 80
| pinball/pubspec.yaml/0 | {
"file_path": "pinball/pubspec.yaml",
"repo_id": "pinball",
"token_count": 671
} | 1,114 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart';
void main() {
group('GameBloc', () {
test('initial state has 3 rounds and empty score', () {
final gameBloc = GameBloc();
expect(gameBloc.state.roundScore, equals(0));
expect(gameBloc.state.rounds, equals(3));
});
blocTest<GameBloc, GameState>(
'GameStarted starts the game',
build: GameBloc.new,
act: (bloc) => bloc.add(const GameStarted()),
expect: () => [
isA<GameState>()
..having(
(state) => state.status,
'status',
GameStatus.playing,
),
],
);
blocTest<GameBloc, GameState>(
'GameOver finishes the game',
build: GameBloc.new,
act: (bloc) => bloc.add(const GameOver()),
expect: () => [
isA<GameState>()
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
],
);
group('RoundLost', () {
blocTest<GameBloc, GameState>(
'decreases number of rounds '
'when there are already available rounds',
build: GameBloc.new,
act: (bloc) {
bloc.add(const RoundLost());
},
expect: () => [
isA<GameState>()..having((state) => state.rounds, 'rounds', 2),
],
);
blocTest<GameBloc, GameState>(
'sets game over when there are no more rounds',
build: GameBloc.new,
act: (bloc) {
bloc
..add(const RoundLost())
..add(const RoundLost())
..add(const RoundLost());
},
expect: () => [
isA<GameState>()..having((state) => state.rounds, 'rounds', 2),
isA<GameState>()..having((state) => state.rounds, 'rounds', 1),
isA<GameState>()
..having((state) => state.rounds, 'rounds', 0)
..having((state) => state.status, 'status', GameStatus.gameOver),
],
);
blocTest<GameBloc, GameState>(
'apply multiplier to roundScore and add it to totalScore '
'when round is lost',
build: GameBloc.new,
seed: () => const GameState(
totalScore: 10,
roundScore: 5,
multiplier: 3,
rounds: 2,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) {
bloc.add(const RoundLost());
},
expect: () => [
isA<GameState>()
..having((state) => state.totalScore, 'totalScore', 25)
..having((state) => state.roundScore, 'roundScore', 0)
],
);
blocTest<GameBloc, GameState>(
"multiplier doesn't increase score above the max score",
build: GameBloc.new,
seed: () => const GameState(
totalScore: 9999999998,
roundScore: 1,
multiplier: 2,
rounds: 1,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) => bloc.add(const RoundLost()),
expect: () => [
isA<GameState>()
..having(
(state) => state.totalScore,
'totalScore',
9999999999,
)
],
);
blocTest<GameBloc, GameState>(
'resets multiplier when round is lost',
build: GameBloc.new,
seed: () => const GameState(
totalScore: 10,
roundScore: 5,
multiplier: 3,
rounds: 2,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) {
bloc.add(const RoundLost());
},
expect: () => [
isA<GameState>()..having((state) => state.multiplier, 'multiplier', 1)
],
);
});
group('Scored', () {
blocTest<GameBloc, GameState>(
'increases score when playing',
build: GameBloc.new,
act: (bloc) => bloc
..add(const GameStarted())
..add(const Scored(points: 2))
..add(const Scored(points: 3)),
expect: () => [
isA<GameState>()
..having((state) => state.status, 'status', GameStatus.playing),
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 2)
..having((state) => state.status, 'status', GameStatus.playing),
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 5)
..having((state) => state.status, 'status', GameStatus.playing),
],
);
blocTest<GameBloc, GameState>(
"doesn't increase score when game is over",
build: GameBloc.new,
act: (bloc) {
for (var i = 0; i < bloc.state.rounds; i++) {
bloc.add(const RoundLost());
}
bloc.add(const Scored(points: 2));
},
expect: () => [
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 0)
..having((state) => state.rounds, 'rounds', 2)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 0)
..having((state) => state.rounds, 'rounds', 1)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.roundScore, 'roundScore', 0)
..having((state) => state.rounds, 'rounds', 0)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
],
);
blocTest<GameBloc, GameState>(
"doesn't increase score above the max score",
build: GameBloc.new,
seed: () => const GameState(
totalScore: 9999999998,
roundScore: 0,
multiplier: 1,
rounds: 1,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) => bloc.add(const Scored(points: 2)),
expect: () => [
isA<GameState>()..having((state) => state.roundScore, 'roundScore', 1)
],
);
});
group('MultiplierIncreased', () {
blocTest<GameBloc, GameState>(
'increases multiplier '
'when multiplier is below 6 and game is not over',
build: GameBloc.new,
act: (bloc) => bloc
..add(const GameStarted())
..add(const MultiplierIncreased())
..add(const MultiplierIncreased()),
expect: () => [
isA<GameState>()
..having((state) => state.status, 'status', GameStatus.playing),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 2)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 3)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
],
);
blocTest<GameBloc, GameState>(
"doesn't increase multiplier "
'when multiplier is 6 and game is not over',
build: GameBloc.new,
seed: () => const GameState(
totalScore: 10,
roundScore: 0,
multiplier: 6,
rounds: 3,
bonusHistory: [],
status: GameStatus.playing,
),
act: (bloc) => bloc..add(const MultiplierIncreased()),
expect: () => const <GameState>[],
);
blocTest<GameBloc, GameState>(
"doesn't increase multiplier "
'when game is over',
build: GameBloc.new,
act: (bloc) {
bloc.add(const GameStarted());
for (var i = 0; i < bloc.state.rounds; i++) {
bloc.add(const RoundLost());
}
bloc.add(const MultiplierIncreased());
},
expect: () => [
isA<GameState>()
..having((state) => state.status, 'status', GameStatus.playing),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 1)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 1)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
isA<GameState>()
..having((state) => state.multiplier, 'multiplier', 1)
..having(
(state) => state.status,
'status',
GameStatus.gameOver,
),
],
);
});
group(
'BonusActivated',
() {
blocTest<GameBloc, GameState>(
'adds bonus to history',
build: GameBloc.new,
act: (bloc) => bloc
..add(const BonusActivated(GameBonus.googleWord))
..add(const BonusActivated(GameBonus.dashNest)),
expect: () => [
isA<GameState>()
..having(
(state) => state.bonusHistory,
'bonusHistory',
[GameBonus.googleWord],
),
isA<GameState>()
..having(
(state) => state.bonusHistory,
'bonusHistory',
[GameBonus.googleWord, GameBonus.dashNest],
),
],
);
},
);
});
}
| pinball/test/game/bloc/game_bloc_test.dart/0 | {
"file_path": "pinball/test/game/bloc/game_bloc_test.dart",
"repo_id": "pinball",
"token_count": 5063
} | 1,115 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/components/backbox/displays/initials_submission_failure_display.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_components/gen/assets.gen.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
await super.onLoad();
images.prefix = '';
await images.loadAll(
[
Assets.images.errorBackground.keyName,
],
);
}
Future<void> pump(InitialsSubmissionFailureDisplay component) {
return ensureAdd(
FlameProvider.value(
_MockAppLocalizations(),
children: [component],
),
);
}
}
class _MockAppLocalizations extends Mock implements AppLocalizations {
@override
String get initialsErrorTitle => 'Title';
@override
String get initialsErrorMessage => 'Message';
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('InitialsSubmissionFailureDisplay', () {
final flameTester = FlameTester(_TestGame.new);
flameTester.test('renders correctly', (game) async {
await game.pump(
InitialsSubmissionFailureDisplay(
onDismissed: () {},
),
);
expect(
game
.descendants()
.where(
(component) =>
component is TextComponent && component.text == 'Title',
)
.length,
equals(1),
);
expect(
game
.descendants()
.where(
(component) =>
component is TextComponent && component.text == 'Message',
)
.length,
equals(1),
);
});
});
}
| pinball/test/game/components/backbox/displays/initials_submission_failure_display_test.dart/0 | {
"file_path": "pinball/test/game/components/backbox/displays/initials_submission_failure_display_test.dart",
"repo_id": "pinball",
"token_count": 844
} | 1,116 |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/google_gallery/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.googleWord.letter1.lit.keyName,
Assets.images.googleWord.letter1.dimmed.keyName,
Assets.images.googleWord.letter2.lit.keyName,
Assets.images.googleWord.letter2.dimmed.keyName,
Assets.images.googleWord.letter3.lit.keyName,
Assets.images.googleWord.letter3.dimmed.keyName,
Assets.images.googleWord.letter4.lit.keyName,
Assets.images.googleWord.letter4.dimmed.keyName,
Assets.images.googleWord.letter5.lit.keyName,
Assets.images.googleWord.letter5.dimmed.keyName,
Assets.images.googleWord.letter6.lit.keyName,
Assets.images.googleWord.letter6.dimmed.keyName,
Assets.images.googleRollover.left.decal.keyName,
Assets.images.googleRollover.left.pin.keyName,
Assets.images.googleRollover.right.decal.keyName,
Assets.images.googleRollover.right.pin.keyName,
]);
}
Future<void> pump(GoogleGallery child) async {
await ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: _MockGameBloc(),
children: [child],
),
);
}
}
class _MockGameBloc extends Mock implements GameBloc {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('GoogleGallery', () {
flameTester.test('loads correctly', (game) async {
final component = GoogleGallery();
await game.pump(component);
expect(game.descendants(), contains(component));
});
group('loads', () {
flameTester.test(
'two GoogleRollovers',
(game) async {
await game.pump(GoogleGallery());
expect(
game.descendants().whereType<GoogleRollover>().length,
equals(2),
);
},
);
flameTester.test(
'a GoogleWord',
(game) async {
await game.pump(GoogleGallery());
expect(
game.descendants().whereType<GoogleWord>().length,
equals(1),
);
},
);
});
group('adds', () {
flameTester.test(
'ScoringContactBehavior to GoogleRollovers',
(game) async {
await game.pump(GoogleGallery());
game.descendants().whereType<GoogleRollover>().forEach(
(rollover) => expect(
rollover.firstChild<ScoringContactBehavior>(),
isNotNull,
),
);
},
);
flameTester.test(
'RolloverNoiseBehavior to GoogleRollovers',
(game) async {
await game.pump(GoogleGallery());
game.descendants().whereType<GoogleRollover>().forEach(
(rollover) => expect(
rollover.firstChild<RolloverNoiseBehavior>(),
isNotNull,
),
);
},
);
flameTester.test('a GoogleWordBonusBehavior', (game) async {
final component = GoogleGallery();
await game.pump(component);
expect(
component.descendants().whereType<GoogleWordBonusBehavior>().single,
isNotNull,
);
});
});
});
}
| pinball/test/game/components/google_gallery/google_gallery_test.dart/0 | {
"file_path": "pinball/test/game/components/google_gallery/google_gallery_test.dart",
"repo_id": "pinball",
"token_count": 1666
} | 1,117 |
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_ui/pinball_ui.dart';
import '../../../helpers/helpers.dart';
class _MockGameBloc extends Mock implements GameBloc {}
void main() {
group('RoundCountDisplay renders', () {
late GameBloc gameBloc;
const initialState = GameState(
totalScore: 0,
roundScore: 0,
multiplier: 1,
rounds: 3,
bonusHistory: [],
status: GameStatus.playing,
);
setUp(() {
gameBloc = _MockGameBloc();
whenListen(
gameBloc,
Stream.value(initialState),
initialState: initialState,
);
});
testWidgets('three active round indicator', (tester) async {
await tester.pumpApp(
const RoundCountDisplay(),
gameBloc: gameBloc,
);
await tester.pump();
expect(find.byType(RoundIndicator), findsNWidgets(3));
});
testWidgets('two active round indicator', (tester) async {
final state = initialState.copyWith(
rounds: 2,
);
whenListen(
gameBloc,
Stream.value(state),
initialState: state,
);
await tester.pumpApp(
const RoundCountDisplay(),
gameBloc: gameBloc,
);
await tester.pump();
expect(
find.byWidgetPredicate(
(widget) => widget is RoundIndicator && widget.isActive,
),
findsNWidgets(2),
);
expect(
find.byWidgetPredicate(
(widget) => widget is RoundIndicator && !widget.isActive,
),
findsOneWidget,
);
});
testWidgets('one active round indicator', (tester) async {
final state = initialState.copyWith(
rounds: 1,
);
whenListen(
gameBloc,
Stream.value(state),
initialState: state,
);
await tester.pumpApp(
const RoundCountDisplay(),
gameBloc: gameBloc,
);
await tester.pump();
expect(
find.byWidgetPredicate(
(widget) => widget is RoundIndicator && widget.isActive,
),
findsOneWidget,
);
expect(
find.byWidgetPredicate(
(widget) => widget is RoundIndicator && !widget.isActive,
),
findsNWidgets(2),
);
});
});
testWidgets('active round indicator is displaying with proper color',
(tester) async {
await tester.pumpApp(
const RoundIndicator(isActive: true),
);
await tester.pump();
expect(
find.byWidgetPredicate(
(widget) => widget is Container && widget.color == PinballColors.yellow,
),
findsOneWidget,
);
});
testWidgets('inactive round indicator is displaying with proper color',
(tester) async {
await tester.pumpApp(
const RoundIndicator(isActive: false),
);
await tester.pump();
expect(
find.byWidgetPredicate(
(widget) =>
widget is Container &&
widget.color == PinballColors.yellow.withAlpha(128),
),
findsOneWidget,
);
});
}
| pinball/test/game/view/widgets/round_count_display_test.dart/0 | {
"file_path": "pinball/test/game/view/widgets/round_count_display_test.dart",
"repo_id": "pinball",
"token_count": 1426
} | 1,118 |
#!/bin/bash
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
device=com.apple.CoreSimulator.SimDeviceType.iPhone-13
os=com.apple.CoreSimulator.SimRuntime.iOS-16-0
xcrun simctl list
xcrun simctl create Flutter-iPhone "$device" "$os" | xargs xcrun simctl boot
| plugins/.ci/scripts/create_simulator.sh/0 | {
"file_path": "plugins/.ci/scripts/create_simulator.sh",
"repo_id": "plugins",
"token_count": 117
} | 1,119 |
name: camera
description: A Flutter plugin for controlling the camera. Supports previewing
the camera feed, capturing images and video, and streaming image buffers to
Dart.
repository: https://github.com/flutter/plugins/tree/main/packages/camera/camera
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22
version: 0.10.3
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
default_package: camera_android
ios:
default_package: camera_avfoundation
web:
default_package: camera_web
dependencies:
camera_android: ^0.10.1
camera_avfoundation: ^0.9.9
camera_platform_interface: ^2.3.2
camera_web: ^0.3.1
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.2
quiver: ^3.0.0
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
mockito: ^5.0.0
plugin_platform_interface: ^2.0.0
video_player: ^2.0.0
| plugins/packages/camera/camera/pubspec.yaml/0 | {
"file_path": "plugins/packages/camera/camera/pubspec.yaml",
"repo_id": "plugins",
"token_count": 419
} | 1,120 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.exposurelock;
import android.hardware.camera2.CaptureRequest;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.features.CameraFeature;
/** Controls whether or not the exposure mode is currently locked or automatically metering. */
public class ExposureLockFeature extends CameraFeature<ExposureMode> {
private ExposureMode currentSetting = ExposureMode.auto;
/**
* Creates a new instance of the {@see ExposureLockFeature}.
*
* @param cameraProperties Collection of the characteristics for the current camera device.
*/
public ExposureLockFeature(CameraProperties cameraProperties) {
super(cameraProperties);
}
@Override
public String getDebugName() {
return "ExposureLockFeature";
}
@Override
public ExposureMode getValue() {
return currentSetting;
}
@Override
public void setValue(ExposureMode value) {
this.currentSetting = value;
}
// Available on all devices.
@Override
public boolean checkIsSupported() {
return true;
}
@Override
public void updateBuilder(CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
requestBuilder.set(CaptureRequest.CONTROL_AE_LOCK, currentSetting == ExposureMode.locked);
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurelock/ExposureLockFeature.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurelock/ExposureLockFeature.java",
"repo_id": "plugins",
"token_count": 416
} | 1,121 |
// Copyright 2013 The Flutter 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.media;
import android.media.CamcorderProfile;
import android.media.EncoderProfiles;
import android.media.MediaRecorder;
import android.os.Build;
import androidx.annotation.NonNull;
import java.io.IOException;
public class MediaRecorderBuilder {
@SuppressWarnings("deprecation")
static class MediaRecorderFactory {
MediaRecorder makeMediaRecorder() {
return new MediaRecorder();
}
}
private final String outputFilePath;
private final CamcorderProfile camcorderProfile;
private final EncoderProfiles encoderProfiles;
private final MediaRecorderFactory recorderFactory;
private boolean enableAudio;
private int mediaOrientation;
public MediaRecorderBuilder(
@NonNull CamcorderProfile camcorderProfile, @NonNull String outputFilePath) {
this(camcorderProfile, outputFilePath, new MediaRecorderFactory());
}
public MediaRecorderBuilder(
@NonNull EncoderProfiles encoderProfiles, @NonNull String outputFilePath) {
this(encoderProfiles, outputFilePath, new MediaRecorderFactory());
}
MediaRecorderBuilder(
@NonNull CamcorderProfile camcorderProfile,
@NonNull String outputFilePath,
MediaRecorderFactory helper) {
this.outputFilePath = outputFilePath;
this.camcorderProfile = camcorderProfile;
this.encoderProfiles = null;
this.recorderFactory = helper;
}
MediaRecorderBuilder(
@NonNull EncoderProfiles encoderProfiles,
@NonNull String outputFilePath,
MediaRecorderFactory helper) {
this.outputFilePath = outputFilePath;
this.encoderProfiles = encoderProfiles;
this.camcorderProfile = null;
this.recorderFactory = helper;
}
public MediaRecorderBuilder setEnableAudio(boolean enableAudio) {
this.enableAudio = enableAudio;
return this;
}
public MediaRecorderBuilder setMediaOrientation(int orientation) {
this.mediaOrientation = orientation;
return this;
}
public MediaRecorder build() throws IOException, NullPointerException, IndexOutOfBoundsException {
MediaRecorder mediaRecorder = recorderFactory.makeMediaRecorder();
// There's a fixed order that mediaRecorder expects. Only change these functions accordingly.
// You can find the specifics here: https://developer.android.com/reference/android/media/MediaRecorder.
if (enableAudio) mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && encoderProfiles != null) {
EncoderProfiles.VideoProfile videoProfile = encoderProfiles.getVideoProfiles().get(0);
EncoderProfiles.AudioProfile audioProfile = encoderProfiles.getAudioProfiles().get(0);
mediaRecorder.setOutputFormat(encoderProfiles.getRecommendedFileFormat());
if (enableAudio) {
mediaRecorder.setAudioEncoder(audioProfile.getCodec());
mediaRecorder.setAudioEncodingBitRate(audioProfile.getBitrate());
mediaRecorder.setAudioSamplingRate(audioProfile.getSampleRate());
}
mediaRecorder.setVideoEncoder(videoProfile.getCodec());
mediaRecorder.setVideoEncodingBitRate(videoProfile.getBitrate());
mediaRecorder.setVideoFrameRate(videoProfile.getFrameRate());
mediaRecorder.setVideoSize(videoProfile.getWidth(), videoProfile.getHeight());
mediaRecorder.setVideoSize(videoProfile.getWidth(), videoProfile.getHeight());
} else {
mediaRecorder.setOutputFormat(camcorderProfile.fileFormat);
if (enableAudio) {
mediaRecorder.setAudioEncoder(camcorderProfile.audioCodec);
mediaRecorder.setAudioEncodingBitRate(camcorderProfile.audioBitRate);
mediaRecorder.setAudioSamplingRate(camcorderProfile.audioSampleRate);
}
mediaRecorder.setVideoEncoder(camcorderProfile.videoCodec);
mediaRecorder.setVideoEncodingBitRate(camcorderProfile.videoBitRate);
mediaRecorder.setVideoFrameRate(camcorderProfile.videoFrameRate);
mediaRecorder.setVideoSize(
camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
}
mediaRecorder.setOutputFile(outputFilePath);
mediaRecorder.setOrientationHint(this.mediaOrientation);
mediaRecorder.prepare();
return mediaRecorder;
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/media/MediaRecorderBuilder.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/media/MediaRecorderBuilder.java",
"repo_id": "plugins",
"token_count": 1448
} | 1,122 |
// Copyright 2013 The Flutter 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.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class CameraUtilsTest {
@Test
public void serializeDeviceOrientation_serializesCorrectly() {
assertEquals(
"portraitUp",
CameraUtils.serializeDeviceOrientation(PlatformChannel.DeviceOrientation.PORTRAIT_UP));
assertEquals(
"portraitDown",
CameraUtils.serializeDeviceOrientation(PlatformChannel.DeviceOrientation.PORTRAIT_DOWN));
assertEquals(
"landscapeLeft",
CameraUtils.serializeDeviceOrientation(PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT));
assertEquals(
"landscapeRight",
CameraUtils.serializeDeviceOrientation(PlatformChannel.DeviceOrientation.LANDSCAPE_RIGHT));
}
@Test(expected = UnsupportedOperationException.class)
public void serializeDeviceOrientation_throws_for_null() {
CameraUtils.serializeDeviceOrientation(null);
}
@Test
public void deserializeDeviceOrientation_deserializesCorrectly() {
assertEquals(
PlatformChannel.DeviceOrientation.PORTRAIT_UP,
CameraUtils.deserializeDeviceOrientation("portraitUp"));
assertEquals(
PlatformChannel.DeviceOrientation.PORTRAIT_DOWN,
CameraUtils.deserializeDeviceOrientation("portraitDown"));
assertEquals(
PlatformChannel.DeviceOrientation.LANDSCAPE_LEFT,
CameraUtils.deserializeDeviceOrientation("landscapeLeft"));
assertEquals(
PlatformChannel.DeviceOrientation.LANDSCAPE_RIGHT,
CameraUtils.deserializeDeviceOrientation("landscapeRight"));
}
@Test(expected = UnsupportedOperationException.class)
public void deserializeDeviceOrientation_throwsForNull() {
CameraUtils.deserializeDeviceOrientation(null);
}
@Test
public void getAvailableCameras_retrievesValidCameras()
throws CameraAccessException, NumberFormatException {
final Activity mockActivity = mock(Activity.class);
final CameraManager mockCameraManager = mock(CameraManager.class);
final CameraCharacteristics mockCameraCharacteristics = mock(CameraCharacteristics.class);
final String[] mockCameraIds = {"1394902", "-192930", "0283835", "foobar"};
final int mockSensorOrientation0 = 90;
final int mockSensorOrientation2 = 270;
final int mockLensFacing0 = CameraMetadata.LENS_FACING_FRONT;
final int mockLensFacing2 = CameraMetadata.LENS_FACING_EXTERNAL;
when(mockActivity.getSystemService(Context.CAMERA_SERVICE)).thenReturn(mockCameraManager);
when(mockCameraManager.getCameraIdList()).thenReturn(mockCameraIds);
when(mockCameraManager.getCameraCharacteristics(anyString()))
.thenReturn(mockCameraCharacteristics);
when(mockCameraCharacteristics.get(any()))
.thenReturn(mockSensorOrientation0)
.thenReturn(mockLensFacing0)
.thenReturn(mockSensorOrientation2)
.thenReturn(mockLensFacing2);
List<Map<String, Object>> availableCameras = CameraUtils.getAvailableCameras(mockActivity);
assertEquals(availableCameras.size(), 2);
assertEquals(availableCameras.get(0).get("name"), "1394902");
assertEquals(availableCameras.get(0).get("sensorOrientation"), mockSensorOrientation0);
assertEquals(availableCameras.get(0).get("lensFacing"), "front");
assertEquals(availableCameras.get(1).get("name"), "0283835");
assertEquals(availableCameras.get(1).get("sensorOrientation"), mockSensorOrientation2);
assertEquals(availableCameras.get(1).get("lensFacing"), "external");
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraUtilsTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraUtilsTest.java",
"repo_id": "plugins",
"token_count": 1475
} | 1,123 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.camerax">
<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
</manifest>
| plugins/packages/camera/camera_android_camerax/android/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 151
} | 1,124 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesFlutterApi;
public class SystemServicesFlutterApiImpl extends SystemServicesFlutterApi {
public SystemServicesFlutterApiImpl(@NonNull BinaryMessenger binaryMessenger) {
super(binaryMessenger);
}
public void sendDeviceOrientationChangedEvent(
@NonNull String orientation, @NonNull Reply<Void> reply) {
super.onDeviceOrientationChanged(orientation, reply);
}
public void sendCameraError(@NonNull String errorDescription, @NonNull Reply<Void> reply) {
super.onCameraError(errorDescription, reply);
}
}
| plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesFlutterApiImpl.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesFlutterApiImpl.java",
"repo_id": "plugins",
"token_count": 265
} | 1,125 |
// Copyright 2013 The Flutter 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 XCTest;
@import AVFoundation;
#import <OCMock/OCMock.h>
#import "MockFLTThreadSafeFlutterResult.h"
@interface AvailableCamerasTest : XCTestCase
@end
@implementation AvailableCamerasTest
- (void)testAvailableCamerasShouldReturnAllCamerasOnMultiCameraIPhone {
CameraPlugin *camera = [[CameraPlugin alloc] initWithRegistry:nil messenger:nil];
XCTestExpectation *expectation =
[[XCTestExpectation alloc] initWithDescription:@"Result finished"];
// iPhone 13 Cameras:
AVCaptureDevice *wideAngleCamera = OCMClassMock([AVCaptureDevice class]);
OCMStub([wideAngleCamera uniqueID]).andReturn(@"0");
OCMStub([wideAngleCamera position]).andReturn(AVCaptureDevicePositionBack);
AVCaptureDevice *frontFacingCamera = OCMClassMock([AVCaptureDevice class]);
OCMStub([frontFacingCamera uniqueID]).andReturn(@"1");
OCMStub([frontFacingCamera position]).andReturn(AVCaptureDevicePositionFront);
AVCaptureDevice *ultraWideCamera = OCMClassMock([AVCaptureDevice class]);
OCMStub([ultraWideCamera uniqueID]).andReturn(@"2");
OCMStub([ultraWideCamera position]).andReturn(AVCaptureDevicePositionBack);
AVCaptureDevice *telephotoCamera = OCMClassMock([AVCaptureDevice class]);
OCMStub([telephotoCamera uniqueID]).andReturn(@"3");
OCMStub([telephotoCamera position]).andReturn(AVCaptureDevicePositionBack);
NSMutableArray *requiredTypes =
[@[ AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInTelephotoCamera ]
mutableCopy];
if (@available(iOS 13.0, *)) {
[requiredTypes addObject:AVCaptureDeviceTypeBuiltInUltraWideCamera];
}
id discoverySessionMock = OCMClassMock([AVCaptureDeviceDiscoverySession class]);
OCMStub([discoverySessionMock discoverySessionWithDeviceTypes:requiredTypes
mediaType:AVMediaTypeVideo
position:AVCaptureDevicePositionUnspecified])
.andReturn(discoverySessionMock);
NSMutableArray *cameras = [NSMutableArray array];
[cameras addObjectsFromArray:@[ wideAngleCamera, frontFacingCamera, telephotoCamera ]];
if (@available(iOS 13.0, *)) {
[cameras addObject:ultraWideCamera];
}
OCMStub([discoverySessionMock devices]).andReturn([NSArray arrayWithArray:cameras]);
MockFLTThreadSafeFlutterResult *resultObject =
[[MockFLTThreadSafeFlutterResult alloc] initWithExpectation:expectation];
// Set up method call
FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"availableCameras"
arguments:nil];
[camera handleMethodCallAsync:call result:resultObject];
// Verify the result
NSDictionary *dictionaryResult = (NSDictionary *)resultObject.receivedResult;
if (@available(iOS 13.0, *)) {
XCTAssertTrue([dictionaryResult count] == 4);
} else {
XCTAssertTrue([dictionaryResult count] == 3);
}
}
- (void)testAvailableCamerasShouldReturnOneCameraOnSingleCameraIPhone {
CameraPlugin *camera = [[CameraPlugin alloc] initWithRegistry:nil messenger:nil];
XCTestExpectation *expectation =
[[XCTestExpectation alloc] initWithDescription:@"Result finished"];
// iPhone 8 Cameras:
AVCaptureDevice *wideAngleCamera = OCMClassMock([AVCaptureDevice class]);
OCMStub([wideAngleCamera uniqueID]).andReturn(@"0");
OCMStub([wideAngleCamera position]).andReturn(AVCaptureDevicePositionBack);
AVCaptureDevice *frontFacingCamera = OCMClassMock([AVCaptureDevice class]);
OCMStub([frontFacingCamera uniqueID]).andReturn(@"1");
OCMStub([frontFacingCamera position]).andReturn(AVCaptureDevicePositionFront);
NSMutableArray *requiredTypes =
[@[ AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInTelephotoCamera ]
mutableCopy];
if (@available(iOS 13.0, *)) {
[requiredTypes addObject:AVCaptureDeviceTypeBuiltInUltraWideCamera];
}
id discoverySessionMock = OCMClassMock([AVCaptureDeviceDiscoverySession class]);
OCMStub([discoverySessionMock discoverySessionWithDeviceTypes:requiredTypes
mediaType:AVMediaTypeVideo
position:AVCaptureDevicePositionUnspecified])
.andReturn(discoverySessionMock);
NSMutableArray *cameras = [NSMutableArray array];
[cameras addObjectsFromArray:@[ wideAngleCamera, frontFacingCamera ]];
OCMStub([discoverySessionMock devices]).andReturn([NSArray arrayWithArray:cameras]);
MockFLTThreadSafeFlutterResult *resultObject =
[[MockFLTThreadSafeFlutterResult alloc] initWithExpectation:expectation];
// Set up method call
FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"availableCameras"
arguments:nil];
[camera handleMethodCallAsync:call result:resultObject];
// Verify the result
NSDictionary *dictionaryResult = (NSDictionary *)resultObject.receivedResult;
XCTAssertTrue([dictionaryResult count] == 2);
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/AvailableCamerasTest.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/AvailableCamerasTest.m",
"repo_id": "plugins",
"token_count": 1872
} | 1,126 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MockFLTThreadSafeFlutterResult_h
#define MockFLTThreadSafeFlutterResult_h
/**
* Extends FLTThreadSafeFlutterResult to give tests the ability to wait on the result and
* read the received result.
*/
@interface MockFLTThreadSafeFlutterResult : FLTThreadSafeFlutterResult
@property(readonly, nonatomic, nonnull) XCTestExpectation *expectation;
@property(nonatomic, nullable) id receivedResult;
/**
* Initializes the MockFLTThreadSafeFlutterResult with an expectation.
*
* The expectation is fullfilled when a result is called allowing tests to await the result in an
* asynchronous manner.
*/
- (nonnull instancetype)initWithExpectation:(nonnull XCTestExpectation *)expectation;
@end
#endif /* MockFLTThreadSafeFlutterResult_h */
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/MockFLTThreadSafeFlutterResult.h/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/MockFLTThreadSafeFlutterResult.h",
"repo_id": "plugins",
"token_count": 258
} | 1,127 |
// Copyright 2013 The Flutter 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 FlutterMethodChannel that can be called from any thread, by dispatching
* its underlying engine calls to the main thread.
*/
@interface FLTThreadSafeMethodChannel : NSObject
/**
* Creates a FLTThreadSafeMethodChannel by wrapping a FlutterMethodChannel object.
* @param channel The FlutterMethodChannel object to be wrapped.
*/
- (instancetype)initWithMethodChannel:(FlutterMethodChannel *)channel;
/**
* Invokes the specified flutter method on the main thread with the specified arguments.
*/
- (void)invokeMethod:(NSString *)method arguments:(nullable id)arguments;
@end
NS_ASSUME_NONNULL_END
| plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeMethodChannel.h/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeMethodChannel.h",
"repo_id": "plugins",
"token_count": 237
} | 1,128 |
// Copyright 2013 The Flutter 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 focus modes that can be set for a camera.
enum FocusMode {
/// Automatically determine focus settings.
auto,
/// Lock the currently determined focus settings.
locked,
}
/// Returns the focus mode as a String.
String serializeFocusMode(FocusMode focusMode) {
switch (focusMode) {
case FocusMode.locked:
return 'locked';
case FocusMode.auto:
return 'auto';
}
}
/// Returns the focus mode for a given String.
FocusMode deserializeFocusMode(String str) {
switch (str) {
case 'locked':
return FocusMode.locked;
case 'auto':
return FocusMode.auto;
default:
throw ArgumentError('"$str" is not a valid FocusMode value');
}
}
| plugins/packages/camera/camera_platform_interface/lib/src/types/focus_mode.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/lib/src/types/focus_mode.dart",
"repo_id": "plugins",
"token_count": 272
} | 1,129 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 0.2.1+4
* Updates code for stricter lint checks.
## 0.2.1+3
* Updates to latest camera platform interface but fails if user attempts to use streaming with recording (since streaming is currently unsupported on Windows).
## 0.2.1+2
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
## 0.2.1+1
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 0.2.1
* Adds a check for string size before Win32 MultiByte <-> WideChar conversions
## 0.2.0
**BREAKING CHANGES**:
* `CameraException.code` now has value `"CameraAccessDenied"` if camera access permission was denied.
* `CameraException.code` now has value `"camera_error"` if error occurs during capture.
## 0.1.0+5
* Fixes bugs in in error handling.
## 0.1.0+4
* Allows retrying camera initialization after error.
## 0.1.0+3
* Updates the README to better explain how to use the unendorsed package.
## 0.1.0+2
* Updates references to the obsolete master branch.
## 0.1.0+1
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.1.0
* Initial release
| plugins/packages/camera/camera_windows/CHANGELOG.md/0 | {
"file_path": "plugins/packages/camera/camera_windows/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 412
} | 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.
#include "camera.h"
namespace camera_windows {
using flutter::EncodableList;
using flutter::EncodableMap;
using flutter::EncodableValue;
// Camera channel events.
constexpr char kCameraMethodChannelBaseName[] =
"plugins.flutter.io/camera_windows/camera";
constexpr char kVideoRecordedEvent[] = "video_recorded";
constexpr char kCameraClosingEvent[] = "camera_closing";
constexpr char kErrorEvent[] = "error";
// Camera error codes
constexpr char kCameraAccessDenied[] = "CameraAccessDenied";
constexpr char kCameraError[] = "camera_error";
constexpr char kPluginDisposed[] = "plugin_disposed";
std::string GetErrorCode(CameraResult result) {
assert(result != CameraResult::kSuccess);
switch (result) {
case CameraResult::kAccessDenied:
return kCameraAccessDenied;
case CameraResult::kSuccess:
case CameraResult::kError:
default:
return kCameraError;
}
}
CameraImpl::CameraImpl(const std::string& device_id)
: device_id_(device_id), Camera(device_id) {}
CameraImpl::~CameraImpl() {
// Sends camera closing event.
OnCameraClosing();
capture_controller_ = nullptr;
SendErrorForPendingResults(kPluginDisposed,
"Plugin disposed before request was handled");
}
bool CameraImpl::InitCamera(flutter::TextureRegistrar* texture_registrar,
flutter::BinaryMessenger* messenger,
bool record_audio,
ResolutionPreset resolution_preset) {
auto capture_controller_factory =
std::make_unique<CaptureControllerFactoryImpl>();
return InitCamera(std::move(capture_controller_factory), texture_registrar,
messenger, record_audio, resolution_preset);
}
bool CameraImpl::InitCamera(
std::unique_ptr<CaptureControllerFactory> capture_controller_factory,
flutter::TextureRegistrar* texture_registrar,
flutter::BinaryMessenger* messenger, bool record_audio,
ResolutionPreset resolution_preset) {
assert(!device_id_.empty());
messenger_ = messenger;
capture_controller_ =
capture_controller_factory->CreateCaptureController(this);
return capture_controller_->InitCaptureDevice(
texture_registrar, device_id_, record_audio, resolution_preset);
}
bool CameraImpl::AddPendingResult(
PendingResultType type, std::unique_ptr<flutter::MethodResult<>> result) {
assert(result);
auto it = pending_results_.find(type);
if (it != pending_results_.end()) {
result->Error("Duplicate request", "Method handler already called");
return false;
}
pending_results_.insert(std::make_pair(type, std::move(result)));
return true;
}
std::unique_ptr<flutter::MethodResult<>> CameraImpl::GetPendingResultByType(
PendingResultType type) {
auto it = pending_results_.find(type);
if (it == pending_results_.end()) {
return nullptr;
}
auto result = std::move(it->second);
pending_results_.erase(it);
return result;
}
bool CameraImpl::HasPendingResultByType(PendingResultType type) const {
auto it = pending_results_.find(type);
if (it == pending_results_.end()) {
return false;
}
return it->second != nullptr;
}
void CameraImpl::SendErrorForPendingResults(const std::string& error_code,
const std::string& description) {
for (const auto& pending_result : pending_results_) {
pending_result.second->Error(error_code, description);
}
pending_results_.clear();
}
MethodChannel<>* CameraImpl::GetMethodChannel() {
assert(messenger_);
assert(camera_id_);
// Use existing channel if initialized
if (camera_channel_) {
return camera_channel_.get();
}
auto channel_name =
std::string(kCameraMethodChannelBaseName) + std::to_string(camera_id_);
camera_channel_ = std::make_unique<flutter::MethodChannel<>>(
messenger_, channel_name, &flutter::StandardMethodCodec::GetInstance());
return camera_channel_.get();
}
void CameraImpl::OnCreateCaptureEngineSucceeded(int64_t texture_id) {
// Use texture id as camera id
camera_id_ = texture_id;
auto pending_result =
GetPendingResultByType(PendingResultType::kCreateCamera);
if (pending_result) {
pending_result->Success(EncodableMap(
{{EncodableValue("cameraId"), EncodableValue(texture_id)}}));
}
}
void CameraImpl::OnCreateCaptureEngineFailed(CameraResult result,
const std::string& error) {
auto pending_result =
GetPendingResultByType(PendingResultType::kCreateCamera);
if (pending_result) {
std::string error_code = GetErrorCode(result);
pending_result->Error(error_code, error);
}
}
void CameraImpl::OnStartPreviewSucceeded(int32_t width, int32_t height) {
auto pending_result = GetPendingResultByType(PendingResultType::kInitialize);
if (pending_result) {
pending_result->Success(EncodableValue(EncodableMap({
{EncodableValue("previewWidth"),
EncodableValue(static_cast<float>(width))},
{EncodableValue("previewHeight"),
EncodableValue(static_cast<float>(height))},
})));
}
};
void CameraImpl::OnStartPreviewFailed(CameraResult result,
const std::string& error) {
auto pending_result = GetPendingResultByType(PendingResultType::kInitialize);
if (pending_result) {
std::string error_code = GetErrorCode(result);
pending_result->Error(error_code, error);
}
};
void CameraImpl::OnResumePreviewSucceeded() {
auto pending_result =
GetPendingResultByType(PendingResultType::kResumePreview);
if (pending_result) {
pending_result->Success();
}
}
void CameraImpl::OnResumePreviewFailed(CameraResult result,
const std::string& error) {
auto pending_result =
GetPendingResultByType(PendingResultType::kResumePreview);
if (pending_result) {
std::string error_code = GetErrorCode(result);
pending_result->Error(error_code, error);
}
}
void CameraImpl::OnPausePreviewSucceeded() {
auto pending_result =
GetPendingResultByType(PendingResultType::kPausePreview);
if (pending_result) {
pending_result->Success();
}
}
void CameraImpl::OnPausePreviewFailed(CameraResult result,
const std::string& error) {
auto pending_result =
GetPendingResultByType(PendingResultType::kPausePreview);
if (pending_result) {
std::string error_code = GetErrorCode(result);
pending_result->Error(error_code, error);
}
}
void CameraImpl::OnStartRecordSucceeded() {
auto pending_result = GetPendingResultByType(PendingResultType::kStartRecord);
if (pending_result) {
pending_result->Success();
}
};
void CameraImpl::OnStartRecordFailed(CameraResult result,
const std::string& error) {
auto pending_result = GetPendingResultByType(PendingResultType::kStartRecord);
if (pending_result) {
std::string error_code = GetErrorCode(result);
pending_result->Error(error_code, error);
}
};
void CameraImpl::OnStopRecordSucceeded(const std::string& file_path) {
auto pending_result = GetPendingResultByType(PendingResultType::kStopRecord);
if (pending_result) {
pending_result->Success(EncodableValue(file_path));
}
};
void CameraImpl::OnStopRecordFailed(CameraResult result,
const std::string& error) {
auto pending_result = GetPendingResultByType(PendingResultType::kStopRecord);
if (pending_result) {
std::string error_code = GetErrorCode(result);
pending_result->Error(error_code, error);
}
};
void CameraImpl::OnTakePictureSucceeded(const std::string& file_path) {
auto pending_result = GetPendingResultByType(PendingResultType::kTakePicture);
if (pending_result) {
pending_result->Success(EncodableValue(file_path));
}
};
void CameraImpl::OnTakePictureFailed(CameraResult result,
const std::string& error) {
auto pending_take_picture_result =
GetPendingResultByType(PendingResultType::kTakePicture);
if (pending_take_picture_result) {
std::string error_code = GetErrorCode(result);
pending_take_picture_result->Error(error_code, error);
}
};
void CameraImpl::OnVideoRecordSucceeded(const std::string& file_path,
int64_t video_duration_ms) {
if (messenger_ && camera_id_ >= 0) {
auto channel = GetMethodChannel();
std::unique_ptr<EncodableValue> message_data =
std::make_unique<EncodableValue>(
EncodableMap({{EncodableValue("path"), EncodableValue(file_path)},
{EncodableValue("maxVideoDuration"),
EncodableValue(video_duration_ms)}}));
channel->InvokeMethod(kVideoRecordedEvent, std::move(message_data));
}
}
void CameraImpl::OnVideoRecordFailed(CameraResult result,
const std::string& error){};
void CameraImpl::OnCaptureError(CameraResult result, const std::string& error) {
if (messenger_ && camera_id_ >= 0) {
auto channel = GetMethodChannel();
std::unique_ptr<EncodableValue> message_data =
std::make_unique<EncodableValue>(EncodableMap(
{{EncodableValue("description"), EncodableValue(error)}}));
channel->InvokeMethod(kErrorEvent, std::move(message_data));
}
std::string error_code = GetErrorCode(result);
SendErrorForPendingResults(error_code, error);
}
void CameraImpl::OnCameraClosing() {
if (messenger_ && camera_id_ >= 0) {
auto channel = GetMethodChannel();
channel->InvokeMethod(kCameraClosingEvent,
std::move(std::make_unique<EncodableValue>()));
}
}
} // namespace camera_windows
| plugins/packages/camera/camera_windows/windows/camera.cpp/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/camera.cpp",
"repo_id": "plugins",
"token_count": 3686
} | 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.
#include "preview_handler.h"
#include <mfapi.h>
#include <mfcaptureengine.h>
#include <cassert>
#include "capture_engine_listener.h"
#include "string_utils.h"
namespace camera_windows {
using Microsoft::WRL::ComPtr;
// Initializes media type for video preview.
HRESULT BuildMediaTypeForVideoPreview(IMFMediaType* src_media_type,
IMFMediaType** preview_media_type) {
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;
}
// Changes subtype to MFVideoFormat_RGB32.
hr = new_media_type->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32);
if (FAILED(hr)) {
return hr;
}
hr = new_media_type->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);
if (FAILED(hr)) {
return hr;
}
new_media_type.CopyTo(preview_media_type);
return hr;
}
HRESULT PreviewHandler::InitPreviewSink(
IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type,
CaptureEngineListener* sample_callback) {
assert(capture_engine);
assert(base_media_type);
assert(sample_callback);
HRESULT hr = S_OK;
if (preview_sink_) {
// Preview sink already initialized.
return hr;
}
ComPtr<IMFMediaType> preview_media_type;
ComPtr<IMFCaptureSink> capture_sink;
// Get sink with preview type.
hr = capture_engine->GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_PREVIEW,
&capture_sink);
if (FAILED(hr)) {
return hr;
}
hr = capture_sink.As(&preview_sink_);
if (FAILED(hr)) {
preview_sink_ = nullptr;
return hr;
}
hr = preview_sink_->RemoveAllStreams();
if (FAILED(hr)) {
preview_sink_ = nullptr;
return hr;
}
hr = BuildMediaTypeForVideoPreview(base_media_type,
preview_media_type.GetAddressOf());
if (FAILED(hr)) {
preview_sink_ = nullptr;
return hr;
}
DWORD preview_sink_stream_index;
hr = preview_sink_->AddStream(
(DWORD)MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_VIDEO_PREVIEW,
preview_media_type.Get(), nullptr, &preview_sink_stream_index);
if (FAILED(hr)) {
return hr;
}
hr = preview_sink_->SetSampleCallback(preview_sink_stream_index,
sample_callback);
if (FAILED(hr)) {
preview_sink_ = nullptr;
return hr;
}
return hr;
}
HRESULT PreviewHandler::StartPreview(IMFCaptureEngine* capture_engine,
IMFMediaType* base_media_type,
CaptureEngineListener* sample_callback) {
assert(capture_engine);
assert(base_media_type);
HRESULT hr =
InitPreviewSink(capture_engine, base_media_type, sample_callback);
if (FAILED(hr)) {
return hr;
}
preview_state_ = PreviewState::kStarting;
return capture_engine->StartPreview();
}
HRESULT PreviewHandler::StopPreview(IMFCaptureEngine* capture_engine) {
if (preview_state_ == PreviewState::kStarting ||
preview_state_ == PreviewState::kRunning ||
preview_state_ == PreviewState::kPaused) {
preview_state_ = PreviewState::kStopping;
return capture_engine->StopPreview();
}
return E_FAIL;
}
bool PreviewHandler::PausePreview() {
if (preview_state_ != PreviewState::kRunning) {
return false;
}
preview_state_ = PreviewState::kPaused;
return true;
}
bool PreviewHandler::ResumePreview() {
if (preview_state_ != PreviewState::kPaused) {
return false;
}
preview_state_ = PreviewState::kRunning;
return true;
}
void PreviewHandler::OnPreviewStarted() {
assert(preview_state_ == PreviewState::kStarting);
if (preview_state_ == PreviewState::kStarting) {
preview_state_ = PreviewState::kRunning;
}
}
} // namespace camera_windows
| plugins/packages/camera/camera_windows/windows/preview_handler.cpp/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/preview_handler.cpp",
"repo_id": "plugins",
"token_count": 1659
} | 1,132 |
name: file_selector_ios
description: iOS implementation of the file_selector plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/file_selector/file_selector_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22
version: 0.5.0+2
environment:
sdk: ">=2.14.4 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: file_selector
platforms:
ios:
dartPluginClass: FileSelectorIOS
pluginClass: FFSFileSelectorPlugin
dependencies:
file_selector_platform_interface: ^2.2.0
flutter:
sdk: flutter
dev_dependencies:
build_runner: 2.1.11
flutter_test:
sdk: flutter
mockito: ^5.1.0
pigeon: ^3.2.5
| plugins/packages/file_selector/file_selector_ios/pubspec.yaml/0 | {
"file_path": "plugins/packages/file_selector/file_selector_ios/pubspec.yaml",
"repo_id": "plugins",
"token_count": 316
} | 1,133 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.4.0
* Adds `getDirectoryPaths` method to the interface.
## 2.3.0
* Replaces `macUTIs` with `uniformTypeIdentifiers`. `macUTIs` is available as an alias, but will be deprecated in a future release.
## 2.2.0
* Makes `XTypeGroup`'s constructor constant.
## 2.1.1
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 2.1.0
* Adds `allowsAny` to `XTypeGroup` as a simple and future-proof way of identifying
wildcard groups.
## 2.0.4
* Removes dependency on `meta`.
## 2.0.3
* Minor code cleanup for new analysis rules.
* Update to use the `verify` method introduced in plugin_platform_interface 2.1.0.
## 2.0.2
* Update platform_plugin_interface version requirement.
## 2.0.1
* Replace extensions with leading dots.
## 2.0.0
* Migration to null-safety
## 1.0.3+1
* Bump the [cross_file](https://pub.dev/packages/cross_file) package version.
## 1.0.3
* Update Flutter SDK constraint.
## 1.0.2
* Replace locally defined `XFile` types with the versions from the [cross_file](https://pub.dev/packages/cross_file) package.
## 1.0.1
* Allow type groups that allow any file.
## 1.0.0
* Initial release.
| plugins/packages/file_selector/file_selector_platform_interface/CHANGELOG.md/0 | {
"file_path": "plugins/packages/file_selector/file_selector_platform_interface/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 423
} | 1,134 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'src/messages.g.dart';
/// An implementation of [FileSelectorPlatform] for Windows.
class FileSelectorWindows extends FileSelectorPlatform {
final FileSelectorApi _hostApi = FileSelectorApi();
/// Registers the Windows implementation.
static void registerWith() {
FileSelectorPlatform.instance = FileSelectorWindows();
}
@override
Future<XFile?> openFile({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String?> paths = await _hostApi.showOpenDialog(
SelectionOptions(
allowMultiple: false,
selectFolders: false,
allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups),
),
initialDirectory,
confirmButtonText);
return paths.isEmpty ? null : XFile(paths.first!);
}
@override
Future<List<XFile>> openFiles({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String?> paths = await _hostApi.showOpenDialog(
SelectionOptions(
allowMultiple: true,
selectFolders: false,
allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups),
),
initialDirectory,
confirmButtonText);
return paths.map((String? path) => XFile(path!)).toList();
}
@override
Future<String?> getSavePath({
List<XTypeGroup>? acceptedTypeGroups,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) async {
final List<String?> paths = await _hostApi.showSaveDialog(
SelectionOptions(
allowMultiple: false,
selectFolders: false,
allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups),
),
initialDirectory,
suggestedName,
confirmButtonText);
return paths.isEmpty ? null : paths.first!;
}
@override
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) async {
final List<String?> paths = await _hostApi.showOpenDialog(
SelectionOptions(
allowMultiple: false,
selectFolders: true,
allowedTypes: <TypeGroup>[],
),
initialDirectory,
confirmButtonText);
return paths.isEmpty ? null : paths.first!;
}
}
List<TypeGroup> _typeGroupsFromXTypeGroups(List<XTypeGroup>? xtypes) {
return (xtypes ?? <XTypeGroup>[]).map((XTypeGroup xtype) {
if (!xtype.allowsAny && (xtype.extensions?.isEmpty ?? true)) {
throw ArgumentError('Provided type group $xtype does not allow '
'all files, but does not set any of the Windows-supported filter '
'categories. "extensions" must be non-empty for Windows if '
'anything is non-empty.');
}
return TypeGroup(
label: xtype.label ?? '', extensions: xtype.extensions ?? <String>[]);
}).toList();
}
| plugins/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart",
"repo_id": "plugins",
"token_count": 1203
} | 1,135 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.2.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#undef _HAS_EXCEPTIONS
#include "messages.g.h"
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
namespace file_selector_windows {
/* TypeGroup */
const std::string& TypeGroup::label() const { return label_; }
void TypeGroup::set_label(std::string_view value_arg) { label_ = value_arg; }
const flutter::EncodableList& TypeGroup::extensions() const {
return extensions_;
}
void TypeGroup::set_extensions(const flutter::EncodableList& value_arg) {
extensions_ = value_arg;
}
flutter::EncodableMap TypeGroup::ToEncodableMap() const {
return flutter::EncodableMap{
{flutter::EncodableValue("label"), flutter::EncodableValue(label_)},
{flutter::EncodableValue("extensions"),
flutter::EncodableValue(extensions_)},
};
}
TypeGroup::TypeGroup() {}
TypeGroup::TypeGroup(flutter::EncodableMap map) {
auto& encodable_label = map.at(flutter::EncodableValue("label"));
if (const std::string* pointer_label =
std::get_if<std::string>(&encodable_label)) {
label_ = *pointer_label;
}
auto& encodable_extensions = map.at(flutter::EncodableValue("extensions"));
if (const flutter::EncodableList* pointer_extensions =
std::get_if<flutter::EncodableList>(&encodable_extensions)) {
extensions_ = *pointer_extensions;
}
}
/* SelectionOptions */
bool SelectionOptions::allow_multiple() const { return allow_multiple_; }
void SelectionOptions::set_allow_multiple(bool value_arg) {
allow_multiple_ = value_arg;
}
bool SelectionOptions::select_folders() const { return select_folders_; }
void SelectionOptions::set_select_folders(bool value_arg) {
select_folders_ = value_arg;
}
const flutter::EncodableList& SelectionOptions::allowed_types() const {
return allowed_types_;
}
void SelectionOptions::set_allowed_types(
const flutter::EncodableList& value_arg) {
allowed_types_ = value_arg;
}
flutter::EncodableMap SelectionOptions::ToEncodableMap() const {
return flutter::EncodableMap{
{flutter::EncodableValue("allowMultiple"),
flutter::EncodableValue(allow_multiple_)},
{flutter::EncodableValue("selectFolders"),
flutter::EncodableValue(select_folders_)},
{flutter::EncodableValue("allowedTypes"),
flutter::EncodableValue(allowed_types_)},
};
}
SelectionOptions::SelectionOptions() {}
SelectionOptions::SelectionOptions(flutter::EncodableMap map) {
auto& encodable_allow_multiple =
map.at(flutter::EncodableValue("allowMultiple"));
if (const bool* pointer_allow_multiple =
std::get_if<bool>(&encodable_allow_multiple)) {
allow_multiple_ = *pointer_allow_multiple;
}
auto& encodable_select_folders =
map.at(flutter::EncodableValue("selectFolders"));
if (const bool* pointer_select_folders =
std::get_if<bool>(&encodable_select_folders)) {
select_folders_ = *pointer_select_folders;
}
auto& encodable_allowed_types =
map.at(flutter::EncodableValue("allowedTypes"));
if (const flutter::EncodableList* pointer_allowed_types =
std::get_if<flutter::EncodableList>(&encodable_allowed_types)) {
allowed_types_ = *pointer_allowed_types;
}
}
FileSelectorApiCodecSerializer::FileSelectorApiCodecSerializer() {}
flutter::EncodableValue FileSelectorApiCodecSerializer::ReadValueOfType(
uint8_t type, flutter::ByteStreamReader* stream) const {
switch (type) {
case 128:
return flutter::CustomEncodableValue(
SelectionOptions(std::get<flutter::EncodableMap>(ReadValue(stream))));
case 129:
return flutter::CustomEncodableValue(
TypeGroup(std::get<flutter::EncodableMap>(ReadValue(stream))));
default:
return flutter::StandardCodecSerializer::ReadValueOfType(type, stream);
}
}
void FileSelectorApiCodecSerializer::WriteValue(
const flutter::EncodableValue& value,
flutter::ByteStreamWriter* stream) const {
if (const flutter::CustomEncodableValue* custom_value =
std::get_if<flutter::CustomEncodableValue>(&value)) {
if (custom_value->type() == typeid(SelectionOptions)) {
stream->WriteByte(128);
WriteValue(
std::any_cast<SelectionOptions>(*custom_value).ToEncodableMap(),
stream);
return;
}
if (custom_value->type() == typeid(TypeGroup)) {
stream->WriteByte(129);
WriteValue(std::any_cast<TypeGroup>(*custom_value).ToEncodableMap(),
stream);
return;
}
}
flutter::StandardCodecSerializer::WriteValue(value, stream);
}
/** The codec used by FileSelectorApi. */
const flutter::StandardMessageCodec& FileSelectorApi::GetCodec() {
return flutter::StandardMessageCodec::GetInstance(
&FileSelectorApiCodecSerializer::GetInstance());
}
/** Sets up an instance of `FileSelectorApi` to handle messages through the
* `binary_messenger`. */
void FileSelectorApi::SetUp(flutter::BinaryMessenger* binary_messenger,
FileSelectorApi* api) {
{
auto channel =
std::make_unique<flutter::BasicMessageChannel<flutter::EncodableValue>>(
binary_messenger,
"dev.flutter.pigeon.FileSelectorApi.showOpenDialog", &GetCodec());
if (api != nullptr) {
channel->SetMessageHandler(
[api](const flutter::EncodableValue& message,
const flutter::MessageReply<flutter::EncodableValue>& reply) {
flutter::EncodableMap wrapped;
try {
const auto& args = std::get<flutter::EncodableList>(message);
const auto& encodable_options_arg = args.at(0);
if (encodable_options_arg.IsNull()) {
wrapped.emplace(flutter::EncodableValue("error"),
WrapError("options_arg unexpectedly null."));
reply(wrapped);
return;
}
const auto& options_arg = std::any_cast<const SelectionOptions&>(
std::get<flutter::CustomEncodableValue>(
encodable_options_arg));
const auto& encodable_initial_directory_arg = args.at(1);
const auto* initial_directory_arg =
std::get_if<std::string>(&encodable_initial_directory_arg);
const auto& encodable_confirm_button_text_arg = args.at(2);
const auto* confirm_button_text_arg =
std::get_if<std::string>(&encodable_confirm_button_text_arg);
ErrorOr<flutter::EncodableList> output = api->ShowOpenDialog(
options_arg, initial_directory_arg, confirm_button_text_arg);
if (output.has_error()) {
wrapped.emplace(flutter::EncodableValue("error"),
WrapError(output.error()));
} else {
wrapped.emplace(
flutter::EncodableValue("result"),
flutter::EncodableValue(std::move(output).TakeValue()));
}
} catch (const std::exception& exception) {
wrapped.emplace(flutter::EncodableValue("error"),
WrapError(exception.what()));
}
reply(wrapped);
});
} else {
channel->SetMessageHandler(nullptr);
}
}
{
auto channel =
std::make_unique<flutter::BasicMessageChannel<flutter::EncodableValue>>(
binary_messenger,
"dev.flutter.pigeon.FileSelectorApi.showSaveDialog", &GetCodec());
if (api != nullptr) {
channel->SetMessageHandler(
[api](const flutter::EncodableValue& message,
const flutter::MessageReply<flutter::EncodableValue>& reply) {
flutter::EncodableMap wrapped;
try {
const auto& args = std::get<flutter::EncodableList>(message);
const auto& encodable_options_arg = args.at(0);
if (encodable_options_arg.IsNull()) {
wrapped.emplace(flutter::EncodableValue("error"),
WrapError("options_arg unexpectedly null."));
reply(wrapped);
return;
}
const auto& options_arg = std::any_cast<const SelectionOptions&>(
std::get<flutter::CustomEncodableValue>(
encodable_options_arg));
const auto& encodable_initial_directory_arg = args.at(1);
const auto* initial_directory_arg =
std::get_if<std::string>(&encodable_initial_directory_arg);
const auto& encodable_suggested_name_arg = args.at(2);
const auto* suggested_name_arg =
std::get_if<std::string>(&encodable_suggested_name_arg);
const auto& encodable_confirm_button_text_arg = args.at(3);
const auto* confirm_button_text_arg =
std::get_if<std::string>(&encodable_confirm_button_text_arg);
ErrorOr<flutter::EncodableList> output = api->ShowSaveDialog(
options_arg, initial_directory_arg, suggested_name_arg,
confirm_button_text_arg);
if (output.has_error()) {
wrapped.emplace(flutter::EncodableValue("error"),
WrapError(output.error()));
} else {
wrapped.emplace(
flutter::EncodableValue("result"),
flutter::EncodableValue(std::move(output).TakeValue()));
}
} catch (const std::exception& exception) {
wrapped.emplace(flutter::EncodableValue("error"),
WrapError(exception.what()));
}
reply(wrapped);
});
} else {
channel->SetMessageHandler(nullptr);
}
}
}
flutter::EncodableMap FileSelectorApi::WrapError(
std::string_view error_message) {
return flutter::EncodableMap(
{{flutter::EncodableValue("message"),
flutter::EncodableValue(std::string(error_message))},
{flutter::EncodableValue("code"), flutter::EncodableValue("Error")},
{flutter::EncodableValue("details"), flutter::EncodableValue()}});
}
flutter::EncodableMap FileSelectorApi::WrapError(const FlutterError& error) {
return flutter::EncodableMap(
{{flutter::EncodableValue("message"),
flutter::EncodableValue(error.message())},
{flutter::EncodableValue("code"), flutter::EncodableValue(error.code())},
{flutter::EncodableValue("details"), error.details()}});
}
} // namespace file_selector_windows
| plugins/packages/file_selector/file_selector_windows/windows/messages.g.cpp/0 | {
"file_path": "plugins/packages/file_selector/file_selector_windows/windows/messages.g.cpp",
"repo_id": "plugins",
"token_count": 4724
} | 1,136 |
name: flutter_plugin_android_lifecycle
description: Flutter plugin for accessing an Android Lifecycle within other plugins.
repository: https://github.com/flutter/plugins/tree/main/packages/flutter_plugin_android_lifecycle
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+flutter_plugin_android_lifecycle%22
version: 2.0.7
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
package: io.flutter.plugins.flutter_plugin_android_lifecycle
pluginClass: FlutterAndroidLifecyclePlugin
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/flutter_plugin_android_lifecycle/pubspec.yaml/0 | {
"file_path": "plugins/packages/flutter_plugin_android_lifecycle/pubspec.yaml",
"repo_id": "plugins",
"token_count": 270
} | 1,137 |
// Copyright 2013 The Flutter 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'fake_maps_controllers.dart';
Widget _mapWithPolygons(Set<Polygon> polygons) {
return Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)),
polygons: polygons,
),
);
}
List<LatLng> _rectPoints({
required double size,
LatLng center = const LatLng(0, 0),
}) {
final double halfSize = size / 2;
return <LatLng>[
LatLng(center.latitude + halfSize, center.longitude + halfSize),
LatLng(center.latitude - halfSize, center.longitude + halfSize),
LatLng(center.latitude - halfSize, center.longitude - halfSize),
LatLng(center.latitude + halfSize, center.longitude - halfSize),
];
}
Polygon _polygonWithPointsAndHole(PolygonId polygonId) {
_rectPoints(size: 1);
return Polygon(
polygonId: polygonId,
points: _rectPoints(size: 1),
holes: <List<LatLng>>[_rectPoints(size: 0.5)],
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakePlatformViewsController fakePlatformViewsController =
FakePlatformViewsController();
setUpAll(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform_views,
fakePlatformViewsController.fakePlatformViewsMethodHandler,
);
});
setUp(() {
fakePlatformViewsController.reset();
});
testWidgets('Initializing a polygon', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToAdd.length, 1);
final Polygon initializedPolygon = platformGoogleMap.polygonsToAdd.first;
expect(initializedPolygon, equals(p1));
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToChange.isEmpty, true);
});
testWidgets('Adding a polygon', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToAdd.length, 1);
final Polygon addedPolygon = platformGoogleMap.polygonsToAdd.first;
expect(addedPolygon, equals(p2));
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToChange.isEmpty, true);
});
testWidgets('Removing a polygon', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonIdsToRemove.length, 1);
expect(platformGoogleMap.polygonIdsToRemove.first, equals(p1.polygonId));
expect(platformGoogleMap.polygonsToChange.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Updating a polygon', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
const Polygon p2 =
Polygon(polygonId: PolygonId('polygon_1'), geodesic: true);
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange.length, 1);
expect(platformGoogleMap.polygonsToChange.first, equals(p2));
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Mutate a polygon', (WidgetTester tester) async {
final List<LatLng> points = <LatLng>[const LatLng(0.0, 0.0)];
final Polygon p1 = Polygon(
polygonId: const PolygonId('polygon_1'),
points: points,
);
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
p1.points.add(const LatLng(1.0, 1.0));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange.length, 1);
expect(platformGoogleMap.polygonsToChange.first, equals(p1));
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1'));
Polygon p2 = const Polygon(polygonId: PolygonId('polygon_2'));
final Set<Polygon> prev = <Polygon>{p1, p2};
p1 = const Polygon(polygonId: PolygonId('polygon_1'), visible: false);
p2 = const Polygon(polygonId: PolygonId('polygon_2'), geodesic: true);
final Set<Polygon> cur = <Polygon>{p1, p2};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange, cur);
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Polygon p2 = const Polygon(polygonId: PolygonId('polygon_2'));
const Polygon p3 = Polygon(polygonId: PolygonId('polygon_3'));
final Set<Polygon> prev = <Polygon>{p2, p3};
// p1 is added, p2 is updated, p3 is removed.
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
p2 = const Polygon(polygonId: PolygonId('polygon_2'), geodesic: true);
final Set<Polygon> cur = <Polygon>{p1, p2};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange.length, 1);
expect(platformGoogleMap.polygonsToAdd.length, 1);
expect(platformGoogleMap.polygonIdsToRemove.length, 1);
expect(platformGoogleMap.polygonsToChange.first, equals(p2));
expect(platformGoogleMap.polygonsToAdd.first, equals(p1));
expect(platformGoogleMap.polygonIdsToRemove.first, equals(p3.polygonId));
});
testWidgets('Partial Update', (WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2'));
Polygon p3 = const Polygon(polygonId: PolygonId('polygon_3'));
final Set<Polygon> prev = <Polygon>{p1, p2, p3};
p3 = const Polygon(polygonId: PolygonId('polygon_3'), geodesic: true);
final Set<Polygon> cur = <Polygon>{p1, p2, p3};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange, <Polygon>{p3});
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Update non platform related attr', (WidgetTester tester) async {
Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1'));
final Set<Polygon> prev = <Polygon>{p1};
p1 = Polygon(polygonId: const PolygonId('polygon_1'), onTap: () {});
final Set<Polygon> cur = <Polygon>{p1};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange.isEmpty, true);
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Initializing a polygon with points and hole',
(WidgetTester tester) async {
final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToAdd.length, 1);
final Polygon initializedPolygon = platformGoogleMap.polygonsToAdd.first;
expect(initializedPolygon, equals(p1));
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToChange.isEmpty, true);
});
testWidgets('Adding a polygon with points and hole',
(WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
final Polygon p2 = _polygonWithPointsAndHole(const PolygonId('polygon_2'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1, p2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToAdd.length, 1);
final Polygon addedPolygon = platformGoogleMap.polygonsToAdd.first;
expect(addedPolygon, equals(p2));
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToChange.isEmpty, true);
});
testWidgets('Removing a polygon with points and hole',
(WidgetTester tester) async {
final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonIdsToRemove.length, 1);
expect(platformGoogleMap.polygonIdsToRemove.first, equals(p1.polygonId));
expect(platformGoogleMap.polygonsToChange.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Updating a polygon by adding points and hole',
(WidgetTester tester) async {
const Polygon p1 = Polygon(polygonId: PolygonId('polygon_1'));
final Polygon p2 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange.length, 1);
expect(platformGoogleMap.polygonsToChange.first, equals(p2));
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Mutate a polygon with points and holes',
(WidgetTester tester) async {
final Polygon p1 = Polygon(
polygonId: const PolygonId('polygon_1'),
points: _rectPoints(size: 1),
holes: <List<LatLng>>[_rectPoints(size: 0.5)],
);
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
p1.points
..clear()
..addAll(_rectPoints(size: 2));
p1.holes
..clear()
..addAll(<List<LatLng>>[_rectPoints(size: 1)]);
await tester.pumpWidget(_mapWithPolygons(<Polygon>{p1}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange.length, 1);
expect(platformGoogleMap.polygonsToChange.first, equals(p1));
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Multi Update polygons with points and hole',
(WidgetTester tester) async {
Polygon p1 = const Polygon(polygonId: PolygonId('polygon_1'));
Polygon p2 = Polygon(
polygonId: const PolygonId('polygon_2'),
points: _rectPoints(size: 2),
holes: <List<LatLng>>[_rectPoints(size: 1)],
);
final Set<Polygon> prev = <Polygon>{p1, p2};
p1 = const Polygon(polygonId: PolygonId('polygon_1'), visible: false);
p2 = p2.copyWith(
pointsParam: _rectPoints(size: 5),
holesParam: <List<LatLng>>[_rectPoints(size: 2)],
);
final Set<Polygon> cur = <Polygon>{p1, p2};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange, cur);
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
testWidgets('Multi Update polygons with points and hole',
(WidgetTester tester) async {
Polygon p2 = Polygon(
polygonId: const PolygonId('polygon_2'),
points: _rectPoints(size: 2),
holes: <List<LatLng>>[_rectPoints(size: 1)],
);
const Polygon p3 = Polygon(polygonId: PolygonId('polygon_3'));
final Set<Polygon> prev = <Polygon>{p2, p3};
// p1 is added, p2 is updated, p3 is removed.
final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
p2 = p2.copyWith(
pointsParam: _rectPoints(size: 5),
holesParam: <List<LatLng>>[_rectPoints(size: 3)],
);
final Set<Polygon> cur = <Polygon>{p1, p2};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange.length, 1);
expect(platformGoogleMap.polygonsToAdd.length, 1);
expect(platformGoogleMap.polygonIdsToRemove.length, 1);
expect(platformGoogleMap.polygonsToChange.first, equals(p2));
expect(platformGoogleMap.polygonsToAdd.first, equals(p1));
expect(platformGoogleMap.polygonIdsToRemove.first, equals(p3.polygonId));
});
testWidgets('Partial Update polygons with points and hole',
(WidgetTester tester) async {
final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1'));
const Polygon p2 = Polygon(polygonId: PolygonId('polygon_2'));
Polygon p3 = Polygon(
polygonId: const PolygonId('polygon_3'),
points: _rectPoints(size: 2),
holes: <List<LatLng>>[_rectPoints(size: 1)],
);
final Set<Polygon> prev = <Polygon>{p1, p2, p3};
p3 = p3.copyWith(
pointsParam: _rectPoints(size: 5),
holesParam: <List<LatLng>>[_rectPoints(size: 3)],
);
final Set<Polygon> cur = <Polygon>{p1, p2, p3};
await tester.pumpWidget(_mapWithPolygons(prev));
await tester.pumpWidget(_mapWithPolygons(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.polygonsToChange, <Polygon>{p3});
expect(platformGoogleMap.polygonIdsToRemove.isEmpty, true);
expect(platformGoogleMap.polygonsToAdd.isEmpty, true);
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart",
"repo_id": "plugins",
"token_count": 6006
} | 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.
package io.flutter.plugins.googlemaps;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.Choreographer;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.Polyline;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Controller of a single GoogleMaps MapView instance. */
final class GoogleMapController
implements DefaultLifecycleObserver,
ActivityPluginBinding.OnSaveInstanceStateListener,
GoogleMapOptionsSink,
MethodChannel.MethodCallHandler,
OnMapReadyCallback,
GoogleMapListener,
PlatformView {
private static final String TAG = "GoogleMapController";
private final int id;
private final MethodChannel methodChannel;
private final GoogleMapOptions options;
@Nullable private MapView mapView;
@Nullable private GoogleMap googleMap;
private boolean trackCameraPosition = false;
private boolean myLocationEnabled = false;
private boolean myLocationButtonEnabled = false;
private boolean zoomControlsEnabled = true;
private boolean indoorEnabled = true;
private boolean trafficEnabled = false;
private boolean buildingsEnabled = true;
private boolean disposed = false;
@VisibleForTesting final float density;
private MethodChannel.Result mapReadyResult;
private final Context context;
private final LifecycleProvider lifecycleProvider;
private final MarkersController markersController;
private final PolygonsController polygonsController;
private final PolylinesController polylinesController;
private final CirclesController circlesController;
private final TileOverlaysController tileOverlaysController;
private List<Object> initialMarkers;
private List<Object> initialPolygons;
private List<Object> initialPolylines;
private List<Object> initialCircles;
private List<Map<String, ?>> initialTileOverlays;
@VisibleForTesting List<Float> initialPadding;
GoogleMapController(
int id,
Context context,
BinaryMessenger binaryMessenger,
LifecycleProvider lifecycleProvider,
GoogleMapOptions options) {
this.id = id;
this.context = context;
this.options = options;
this.mapView = new MapView(context, options);
this.density = context.getResources().getDisplayMetrics().density;
methodChannel =
new MethodChannel(binaryMessenger, "plugins.flutter.dev/google_maps_android_" + id);
methodChannel.setMethodCallHandler(this);
this.lifecycleProvider = lifecycleProvider;
this.markersController = new MarkersController(methodChannel);
this.polygonsController = new PolygonsController(methodChannel, density);
this.polylinesController = new PolylinesController(methodChannel, density);
this.circlesController = new CirclesController(methodChannel, density);
this.tileOverlaysController = new TileOverlaysController(methodChannel);
}
@Override
public View getView() {
return mapView;
}
@VisibleForTesting
/*package*/ void setView(MapView view) {
mapView = view;
}
void init() {
lifecycleProvider.getLifecycle().addObserver(this);
mapView.getMapAsync(this);
}
private void moveCamera(CameraUpdate cameraUpdate) {
googleMap.moveCamera(cameraUpdate);
}
private void animateCamera(CameraUpdate cameraUpdate) {
googleMap.animateCamera(cameraUpdate);
}
private CameraPosition getCameraPosition() {
return trackCameraPosition ? googleMap.getCameraPosition() : null;
}
private boolean loadedCallbackPending = false;
/**
* Invalidates the map view after the map has finished rendering.
*
* <p>gmscore GL renderer uses a {@link android.view.TextureView}. Android platform views that are
* displayed as a texture after Flutter v3.0.0. require that the view hierarchy is notified after
* all drawing operations have been flushed.
*
* <p>Since the GL renderer doesn't use standard Android views, and instead uses GL directly, we
* notify the view hierarchy by invalidating the view.
*
* <p>Unfortunately, when {@link GoogleMap.OnMapLoadedCallback} is fired, the texture may not have
* been updated yet.
*
* <p>To workaround this limitation, wait two frames. This ensures that at least the frame budget
* (16.66ms at 60hz) have passed since the drawing operation was issued.
*/
private void invalidateMapIfNeeded() {
if (googleMap == null || loadedCallbackPending) {
return;
}
loadedCallbackPending = true;
googleMap.setOnMapLoadedCallback(
new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
loadedCallbackPending = false;
postFrameCallback(
() -> {
postFrameCallback(
() -> {
if (mapView != null) {
mapView.invalidate();
}
});
});
}
});
}
private static void postFrameCallback(Runnable f) {
Choreographer.getInstance()
.postFrameCallback(
new Choreographer.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
f.run();
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
this.googleMap.setIndoorEnabled(this.indoorEnabled);
this.googleMap.setTrafficEnabled(this.trafficEnabled);
this.googleMap.setBuildingsEnabled(this.buildingsEnabled);
googleMap.setOnInfoWindowClickListener(this);
if (mapReadyResult != null) {
mapReadyResult.success(null);
mapReadyResult = null;
}
setGoogleMapListener(this);
updateMyLocationSettings();
markersController.setGoogleMap(googleMap);
polygonsController.setGoogleMap(googleMap);
polylinesController.setGoogleMap(googleMap);
circlesController.setGoogleMap(googleMap);
tileOverlaysController.setGoogleMap(googleMap);
updateInitialMarkers();
updateInitialPolygons();
updateInitialPolylines();
updateInitialCircles();
updateInitialTileOverlays();
if (initialPadding != null && initialPadding.size() == 4) {
setPadding(
initialPadding.get(0),
initialPadding.get(1),
initialPadding.get(2),
initialPadding.get(3));
}
}
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
switch (call.method) {
case "map#waitForMap":
if (googleMap != null) {
result.success(null);
return;
}
mapReadyResult = result;
break;
case "map#update":
{
Convert.interpretGoogleMapOptions(call.argument("options"), this);
result.success(Convert.cameraPositionToJson(getCameraPosition()));
break;
}
case "map#getVisibleRegion":
{
if (googleMap != null) {
LatLngBounds latLngBounds = googleMap.getProjection().getVisibleRegion().latLngBounds;
result.success(Convert.latlngBoundsToJson(latLngBounds));
} else {
result.error(
"GoogleMap uninitialized",
"getVisibleRegion called prior to map initialization",
null);
}
break;
}
case "map#getScreenCoordinate":
{
if (googleMap != null) {
LatLng latLng = Convert.toLatLng(call.arguments);
Point screenLocation = googleMap.getProjection().toScreenLocation(latLng);
result.success(Convert.pointToJson(screenLocation));
} else {
result.error(
"GoogleMap uninitialized",
"getScreenCoordinate called prior to map initialization",
null);
}
break;
}
case "map#getLatLng":
{
if (googleMap != null) {
Point point = Convert.toPoint(call.arguments);
LatLng latLng = googleMap.getProjection().fromScreenLocation(point);
result.success(Convert.latLngToJson(latLng));
} else {
result.error(
"GoogleMap uninitialized", "getLatLng called prior to map initialization", null);
}
break;
}
case "map#takeSnapshot":
{
if (googleMap != null) {
final MethodChannel.Result _result = result;
googleMap.snapshot(
new SnapshotReadyCallback() {
@Override
public void onSnapshotReady(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bitmap.recycle();
_result.success(byteArray);
}
});
} else {
result.error("GoogleMap uninitialized", "takeSnapshot", null);
}
break;
}
case "camera#move":
{
final CameraUpdate cameraUpdate =
Convert.toCameraUpdate(call.argument("cameraUpdate"), density);
moveCamera(cameraUpdate);
result.success(null);
break;
}
case "camera#animate":
{
final CameraUpdate cameraUpdate =
Convert.toCameraUpdate(call.argument("cameraUpdate"), density);
animateCamera(cameraUpdate);
result.success(null);
break;
}
case "markers#update":
{
invalidateMapIfNeeded();
List<Object> markersToAdd = call.argument("markersToAdd");
markersController.addMarkers(markersToAdd);
List<Object> markersToChange = call.argument("markersToChange");
markersController.changeMarkers(markersToChange);
List<Object> markerIdsToRemove = call.argument("markerIdsToRemove");
markersController.removeMarkers(markerIdsToRemove);
result.success(null);
break;
}
case "markers#showInfoWindow":
{
Object markerId = call.argument("markerId");
markersController.showMarkerInfoWindow((String) markerId, result);
break;
}
case "markers#hideInfoWindow":
{
Object markerId = call.argument("markerId");
markersController.hideMarkerInfoWindow((String) markerId, result);
break;
}
case "markers#isInfoWindowShown":
{
Object markerId = call.argument("markerId");
markersController.isInfoWindowShown((String) markerId, result);
break;
}
case "polygons#update":
{
invalidateMapIfNeeded();
List<Object> polygonsToAdd = call.argument("polygonsToAdd");
polygonsController.addPolygons(polygonsToAdd);
List<Object> polygonsToChange = call.argument("polygonsToChange");
polygonsController.changePolygons(polygonsToChange);
List<Object> polygonIdsToRemove = call.argument("polygonIdsToRemove");
polygonsController.removePolygons(polygonIdsToRemove);
result.success(null);
break;
}
case "polylines#update":
{
invalidateMapIfNeeded();
List<Object> polylinesToAdd = call.argument("polylinesToAdd");
polylinesController.addPolylines(polylinesToAdd);
List<Object> polylinesToChange = call.argument("polylinesToChange");
polylinesController.changePolylines(polylinesToChange);
List<Object> polylineIdsToRemove = call.argument("polylineIdsToRemove");
polylinesController.removePolylines(polylineIdsToRemove);
result.success(null);
break;
}
case "circles#update":
{
invalidateMapIfNeeded();
List<Object> circlesToAdd = call.argument("circlesToAdd");
circlesController.addCircles(circlesToAdd);
List<Object> circlesToChange = call.argument("circlesToChange");
circlesController.changeCircles(circlesToChange);
List<Object> circleIdsToRemove = call.argument("circleIdsToRemove");
circlesController.removeCircles(circleIdsToRemove);
result.success(null);
break;
}
case "map#isCompassEnabled":
{
result.success(googleMap.getUiSettings().isCompassEnabled());
break;
}
case "map#isMapToolbarEnabled":
{
result.success(googleMap.getUiSettings().isMapToolbarEnabled());
break;
}
case "map#getMinMaxZoomLevels":
{
List<Float> zoomLevels = new ArrayList<>(2);
zoomLevels.add(googleMap.getMinZoomLevel());
zoomLevels.add(googleMap.getMaxZoomLevel());
result.success(zoomLevels);
break;
}
case "map#isZoomGesturesEnabled":
{
result.success(googleMap.getUiSettings().isZoomGesturesEnabled());
break;
}
case "map#isLiteModeEnabled":
{
result.success(options.getLiteMode());
break;
}
case "map#isZoomControlsEnabled":
{
result.success(googleMap.getUiSettings().isZoomControlsEnabled());
break;
}
case "map#isScrollGesturesEnabled":
{
result.success(googleMap.getUiSettings().isScrollGesturesEnabled());
break;
}
case "map#isTiltGesturesEnabled":
{
result.success(googleMap.getUiSettings().isTiltGesturesEnabled());
break;
}
case "map#isRotateGesturesEnabled":
{
result.success(googleMap.getUiSettings().isRotateGesturesEnabled());
break;
}
case "map#isMyLocationButtonEnabled":
{
result.success(googleMap.getUiSettings().isMyLocationButtonEnabled());
break;
}
case "map#isTrafficEnabled":
{
result.success(googleMap.isTrafficEnabled());
break;
}
case "map#isBuildingsEnabled":
{
result.success(googleMap.isBuildingsEnabled());
break;
}
case "map#getZoomLevel":
{
result.success(googleMap.getCameraPosition().zoom);
break;
}
case "map#setStyle":
{
invalidateMapIfNeeded();
boolean mapStyleSet;
if (call.arguments instanceof String) {
String mapStyle = (String) call.arguments;
if (mapStyle == null) {
mapStyleSet = googleMap.setMapStyle(null);
} else {
mapStyleSet = googleMap.setMapStyle(new MapStyleOptions(mapStyle));
}
} else {
mapStyleSet = googleMap.setMapStyle(null);
}
ArrayList<Object> mapStyleResult = new ArrayList<>(2);
mapStyleResult.add(mapStyleSet);
if (!mapStyleSet) {
mapStyleResult.add(
"Unable to set the map style. Please check console logs for errors.");
}
result.success(mapStyleResult);
break;
}
case "tileOverlays#update":
{
invalidateMapIfNeeded();
List<Map<String, ?>> tileOverlaysToAdd = call.argument("tileOverlaysToAdd");
tileOverlaysController.addTileOverlays(tileOverlaysToAdd);
List<Map<String, ?>> tileOverlaysToChange = call.argument("tileOverlaysToChange");
tileOverlaysController.changeTileOverlays(tileOverlaysToChange);
List<String> tileOverlaysToRemove = call.argument("tileOverlayIdsToRemove");
tileOverlaysController.removeTileOverlays(tileOverlaysToRemove);
result.success(null);
break;
}
case "tileOverlays#clearTileCache":
{
invalidateMapIfNeeded();
String tileOverlayId = call.argument("tileOverlayId");
tileOverlaysController.clearTileCache(tileOverlayId);
result.success(null);
break;
}
case "map#getTileOverlayInfo":
{
String tileOverlayId = call.argument("tileOverlayId");
result.success(tileOverlaysController.getTileOverlayInfo(tileOverlayId));
break;
}
default:
result.notImplemented();
}
}
@Override
public void onMapClick(LatLng latLng) {
final Map<String, Object> arguments = new HashMap<>(2);
arguments.put("position", Convert.latLngToJson(latLng));
methodChannel.invokeMethod("map#onTap", arguments);
}
@Override
public void onMapLongClick(LatLng latLng) {
final Map<String, Object> arguments = new HashMap<>(2);
arguments.put("position", Convert.latLngToJson(latLng));
methodChannel.invokeMethod("map#onLongPress", arguments);
}
@Override
public void onCameraMoveStarted(int reason) {
final Map<String, Object> arguments = new HashMap<>(2);
boolean isGesture = reason == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE;
arguments.put("isGesture", isGesture);
methodChannel.invokeMethod("camera#onMoveStarted", arguments);
}
@Override
public void onInfoWindowClick(Marker marker) {
markersController.onInfoWindowTap(marker.getId());
}
@Override
public void onCameraMove() {
if (!trackCameraPosition) {
return;
}
final Map<String, Object> arguments = new HashMap<>(2);
arguments.put("position", Convert.cameraPositionToJson(googleMap.getCameraPosition()));
methodChannel.invokeMethod("camera#onMove", arguments);
}
@Override
public void onCameraIdle() {
methodChannel.invokeMethod("camera#onIdle", Collections.singletonMap("map", id));
}
@Override
public boolean onMarkerClick(Marker marker) {
return markersController.onMarkerTap(marker.getId());
}
@Override
public void onMarkerDragStart(Marker marker) {
markersController.onMarkerDragStart(marker.getId(), marker.getPosition());
}
@Override
public void onMarkerDrag(Marker marker) {
markersController.onMarkerDrag(marker.getId(), marker.getPosition());
}
@Override
public void onMarkerDragEnd(Marker marker) {
markersController.onMarkerDragEnd(marker.getId(), marker.getPosition());
}
@Override
public void onPolygonClick(Polygon polygon) {
polygonsController.onPolygonTap(polygon.getId());
}
@Override
public void onPolylineClick(Polyline polyline) {
polylinesController.onPolylineTap(polyline.getId());
}
@Override
public void onCircleClick(Circle circle) {
circlesController.onCircleTap(circle.getId());
}
@Override
public void dispose() {
if (disposed) {
return;
}
disposed = true;
methodChannel.setMethodCallHandler(null);
setGoogleMapListener(null);
destroyMapViewIfNecessary();
Lifecycle lifecycle = lifecycleProvider.getLifecycle();
if (lifecycle != null) {
lifecycle.removeObserver(this);
}
}
private void setGoogleMapListener(@Nullable GoogleMapListener listener) {
if (googleMap == null) {
Log.v(TAG, "Controller was disposed before GoogleMap was ready.");
return;
}
googleMap.setOnCameraMoveStartedListener(listener);
googleMap.setOnCameraMoveListener(listener);
googleMap.setOnCameraIdleListener(listener);
googleMap.setOnMarkerClickListener(listener);
googleMap.setOnMarkerDragListener(listener);
googleMap.setOnPolygonClickListener(listener);
googleMap.setOnPolylineClickListener(listener);
googleMap.setOnCircleClickListener(listener);
googleMap.setOnMapClickListener(listener);
googleMap.setOnMapLongClickListener(listener);
}
// @Override
// The minimum supported version of Flutter doesn't have this method on the PlatformView interface, but the maximum
// does. This will override it when available even with the annotation commented out.
public void onInputConnectionLocked() {
// TODO(mklim): Remove this empty override once https://github.com/flutter/flutter/issues/40126 is fixed in stable.
}
// @Override
// The minimum supported version of Flutter doesn't have this method on the PlatformView interface, but the maximum
// does. This will override it when available even with the annotation commented out.
public void onInputConnectionUnlocked() {
// TODO(mklim): Remove this empty override once https://github.com/flutter/flutter/issues/40126 is fixed in stable.
}
// DefaultLifecycleObserver
@Override
public void onCreate(@NonNull LifecycleOwner owner) {
if (disposed) {
return;
}
mapView.onCreate(null);
}
@Override
public void onStart(@NonNull LifecycleOwner owner) {
if (disposed) {
return;
}
mapView.onStart();
}
@Override
public void onResume(@NonNull LifecycleOwner owner) {
if (disposed) {
return;
}
mapView.onResume();
}
@Override
public void onPause(@NonNull LifecycleOwner owner) {
if (disposed) {
return;
}
mapView.onResume();
}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
if (disposed) {
return;
}
mapView.onStop();
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
owner.getLifecycle().removeObserver(this);
if (disposed) {
return;
}
destroyMapViewIfNecessary();
}
@Override
public void onRestoreInstanceState(Bundle bundle) {
if (disposed) {
return;
}
mapView.onCreate(bundle);
}
@Override
public void onSaveInstanceState(Bundle bundle) {
if (disposed) {
return;
}
mapView.onSaveInstanceState(bundle);
}
// GoogleMapOptionsSink methods
@Override
public void setCameraTargetBounds(LatLngBounds bounds) {
googleMap.setLatLngBoundsForCameraTarget(bounds);
}
@Override
public void setCompassEnabled(boolean compassEnabled) {
googleMap.getUiSettings().setCompassEnabled(compassEnabled);
}
@Override
public void setMapToolbarEnabled(boolean mapToolbarEnabled) {
googleMap.getUiSettings().setMapToolbarEnabled(mapToolbarEnabled);
}
@Override
public void setMapType(int mapType) {
googleMap.setMapType(mapType);
}
@Override
public void setTrackCameraPosition(boolean trackCameraPosition) {
this.trackCameraPosition = trackCameraPosition;
}
@Override
public void setRotateGesturesEnabled(boolean rotateGesturesEnabled) {
googleMap.getUiSettings().setRotateGesturesEnabled(rotateGesturesEnabled);
}
@Override
public void setScrollGesturesEnabled(boolean scrollGesturesEnabled) {
googleMap.getUiSettings().setScrollGesturesEnabled(scrollGesturesEnabled);
}
@Override
public void setTiltGesturesEnabled(boolean tiltGesturesEnabled) {
googleMap.getUiSettings().setTiltGesturesEnabled(tiltGesturesEnabled);
}
@Override
public void setMinMaxZoomPreference(Float min, Float max) {
googleMap.resetMinMaxZoomPreference();
if (min != null) {
googleMap.setMinZoomPreference(min);
}
if (max != null) {
googleMap.setMaxZoomPreference(max);
}
}
@Override
public void setPadding(float top, float left, float bottom, float right) {
if (googleMap != null) {
googleMap.setPadding(
(int) (left * density),
(int) (top * density),
(int) (right * density),
(int) (bottom * density));
} else {
setInitialPadding(top, left, bottom, right);
}
}
@VisibleForTesting
void setInitialPadding(float top, float left, float bottom, float right) {
if (initialPadding == null) {
initialPadding = new ArrayList<>();
} else {
initialPadding.clear();
}
initialPadding.add(top);
initialPadding.add(left);
initialPadding.add(bottom);
initialPadding.add(right);
}
@Override
public void setZoomGesturesEnabled(boolean zoomGesturesEnabled) {
googleMap.getUiSettings().setZoomGesturesEnabled(zoomGesturesEnabled);
}
/** This call will have no effect on already created map */
@Override
public void setLiteModeEnabled(boolean liteModeEnabled) {
options.liteMode(liteModeEnabled);
}
@Override
public void setMyLocationEnabled(boolean myLocationEnabled) {
if (this.myLocationEnabled == myLocationEnabled) {
return;
}
this.myLocationEnabled = myLocationEnabled;
if (googleMap != null) {
updateMyLocationSettings();
}
}
@Override
public void setMyLocationButtonEnabled(boolean myLocationButtonEnabled) {
if (this.myLocationButtonEnabled == myLocationButtonEnabled) {
return;
}
this.myLocationButtonEnabled = myLocationButtonEnabled;
if (googleMap != null) {
updateMyLocationSettings();
}
}
@Override
public void setZoomControlsEnabled(boolean zoomControlsEnabled) {
if (this.zoomControlsEnabled == zoomControlsEnabled) {
return;
}
this.zoomControlsEnabled = zoomControlsEnabled;
if (googleMap != null) {
googleMap.getUiSettings().setZoomControlsEnabled(zoomControlsEnabled);
}
}
@Override
public void setInitialMarkers(Object initialMarkers) {
ArrayList<?> markers = (ArrayList<?>) initialMarkers;
this.initialMarkers = markers != null ? new ArrayList<>(markers) : null;
if (googleMap != null) {
updateInitialMarkers();
}
}
private void updateInitialMarkers() {
markersController.addMarkers(initialMarkers);
}
@Override
public void setInitialPolygons(Object initialPolygons) {
ArrayList<?> polygons = (ArrayList<?>) initialPolygons;
this.initialPolygons = polygons != null ? new ArrayList<>(polygons) : null;
if (googleMap != null) {
updateInitialPolygons();
}
}
private void updateInitialPolygons() {
polygonsController.addPolygons(initialPolygons);
}
@Override
public void setInitialPolylines(Object initialPolylines) {
ArrayList<?> polylines = (ArrayList<?>) initialPolylines;
this.initialPolylines = polylines != null ? new ArrayList<>(polylines) : null;
if (googleMap != null) {
updateInitialPolylines();
}
}
private void updateInitialPolylines() {
polylinesController.addPolylines(initialPolylines);
}
@Override
public void setInitialCircles(Object initialCircles) {
ArrayList<?> circles = (ArrayList<?>) initialCircles;
this.initialCircles = circles != null ? new ArrayList<>(circles) : null;
if (googleMap != null) {
updateInitialCircles();
}
}
private void updateInitialCircles() {
circlesController.addCircles(initialCircles);
}
@Override
public void setInitialTileOverlays(List<Map<String, ?>> initialTileOverlays) {
this.initialTileOverlays = initialTileOverlays;
if (googleMap != null) {
updateInitialTileOverlays();
}
}
private void updateInitialTileOverlays() {
tileOverlaysController.addTileOverlays(initialTileOverlays);
}
@SuppressLint("MissingPermission")
private void updateMyLocationSettings() {
if (hasLocationPermission()) {
// The plugin doesn't add the location permission by default so that apps that don't need
// the feature won't require the permission.
// Gradle is doing a static check for missing permission and in some configurations will
// fail the build if the permission is missing. The following disables the Gradle lint.
//noinspection ResourceType
googleMap.setMyLocationEnabled(myLocationEnabled);
googleMap.getUiSettings().setMyLocationButtonEnabled(myLocationButtonEnabled);
} else {
// TODO(amirh): Make the options update fail.
// https://github.com/flutter/flutter/issues/24327
Log.e(TAG, "Cannot enable MyLocation layer as location permissions are not granted");
}
}
private boolean hasLocationPermission() {
return checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
|| checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED;
}
private int checkSelfPermission(String permission) {
if (permission == null) {
throw new IllegalArgumentException("permission is null");
}
return context.checkPermission(
permission, android.os.Process.myPid(), android.os.Process.myUid());
}
private void destroyMapViewIfNecessary() {
if (mapView == null) {
return;
}
mapView.onDestroy();
mapView = null;
}
public void setIndoorEnabled(boolean indoorEnabled) {
this.indoorEnabled = indoorEnabled;
}
public void setTrafficEnabled(boolean trafficEnabled) {
this.trafficEnabled = trafficEnabled;
if (googleMap == null) {
return;
}
googleMap.setTrafficEnabled(trafficEnabled);
}
public void setBuildingsEnabled(boolean buildingsEnabled) {
this.buildingsEnabled = buildingsEnabled;
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapController.java/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapController.java",
"repo_id": "plugins",
"token_count": 11801
} | 1,139 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
void main() {
group('diffs', () {
// A options instance with every field set, to test diffs against.
final MapConfiguration diffBase = MapConfiguration(
compassEnabled: false,
mapToolbarEnabled: false,
cameraTargetBounds: CameraTargetBounds(LatLngBounds(
northeast: const LatLng(30, 20), southwest: const LatLng(10, 40))),
mapType: MapType.normal,
minMaxZoomPreference: const MinMaxZoomPreference(1.0, 10.0),
rotateGesturesEnabled: false,
scrollGesturesEnabled: false,
tiltGesturesEnabled: false,
trackCameraPosition: false,
zoomControlsEnabled: false,
zoomGesturesEnabled: false,
liteModeEnabled: false,
myLocationEnabled: false,
myLocationButtonEnabled: false,
padding: const EdgeInsets.all(5.0),
indoorViewEnabled: false,
trafficEnabled: false,
buildingsEnabled: false,
);
test('only include changed fields', () async {
const MapConfiguration nullOptions = MapConfiguration();
// Everything should be null since nothing changed.
expect(diffBase.diffFrom(diffBase), nullOptions);
});
test('only apply non-null fields', () async {
const MapConfiguration smallDiff = MapConfiguration(compassEnabled: true);
final MapConfiguration updated = diffBase.applyDiff(smallDiff);
// The diff should be updated.
expect(updated.compassEnabled, true);
// Spot check that other fields weren't stomped.
expect(updated.mapToolbarEnabled, isNot(null));
expect(updated.cameraTargetBounds, isNot(null));
expect(updated.mapType, isNot(null));
expect(updated.zoomControlsEnabled, isNot(null));
expect(updated.liteModeEnabled, isNot(null));
expect(updated.padding, isNot(null));
expect(updated.trafficEnabled, isNot(null));
});
test('handle compassEnabled', () async {
const MapConfiguration diff = MapConfiguration(compassEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.compassEnabled, true);
});
test('handle mapToolbarEnabled', () async {
const MapConfiguration diff = MapConfiguration(mapToolbarEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.mapToolbarEnabled, true);
});
test('handle cameraTargetBounds', () async {
final CameraTargetBounds newBounds = CameraTargetBounds(LatLngBounds(
northeast: const LatLng(55, 15), southwest: const LatLng(5, 15)));
final MapConfiguration diff =
MapConfiguration(cameraTargetBounds: newBounds);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.cameraTargetBounds, newBounds);
});
test('handle mapType', () async {
const MapConfiguration diff =
MapConfiguration(mapType: MapType.satellite);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.mapType, MapType.satellite);
});
test('handle minMaxZoomPreference', () async {
const MinMaxZoomPreference newZoomPref = MinMaxZoomPreference(3.3, 4.5);
const MapConfiguration diff =
MapConfiguration(minMaxZoomPreference: newZoomPref);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.minMaxZoomPreference, newZoomPref);
});
test('handle rotateGesturesEnabled', () async {
const MapConfiguration diff =
MapConfiguration(rotateGesturesEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.rotateGesturesEnabled, true);
});
test('handle scrollGesturesEnabled', () async {
const MapConfiguration diff =
MapConfiguration(scrollGesturesEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.scrollGesturesEnabled, true);
});
test('handle tiltGesturesEnabled', () async {
const MapConfiguration diff = MapConfiguration(tiltGesturesEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.tiltGesturesEnabled, true);
});
test('handle trackCameraPosition', () async {
const MapConfiguration diff = MapConfiguration(trackCameraPosition: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.trackCameraPosition, true);
});
test('handle zoomControlsEnabled', () async {
const MapConfiguration diff = MapConfiguration(zoomControlsEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.zoomControlsEnabled, true);
});
test('handle zoomGesturesEnabled', () async {
const MapConfiguration diff = MapConfiguration(zoomGesturesEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.zoomGesturesEnabled, true);
});
test('handle liteModeEnabled', () async {
const MapConfiguration diff = MapConfiguration(liteModeEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.liteModeEnabled, true);
});
test('handle myLocationEnabled', () async {
const MapConfiguration diff = MapConfiguration(myLocationEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.myLocationEnabled, true);
});
test('handle myLocationButtonEnabled', () async {
const MapConfiguration diff =
MapConfiguration(myLocationButtonEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.myLocationButtonEnabled, true);
});
test('handle padding', () async {
const EdgeInsets newPadding =
EdgeInsets.symmetric(vertical: 1.0, horizontal: 3.0);
const MapConfiguration diff = MapConfiguration(padding: newPadding);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.padding, newPadding);
});
test('handle indoorViewEnabled', () async {
const MapConfiguration diff = MapConfiguration(indoorViewEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.indoorViewEnabled, true);
});
test('handle trafficEnabled', () async {
const MapConfiguration diff = MapConfiguration(trafficEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.trafficEnabled, true);
});
test('handle buildingsEnabled', () async {
const MapConfiguration diff = MapConfiguration(buildingsEnabled: true);
const MapConfiguration empty = MapConfiguration();
final MapConfiguration updated = diffBase.applyDiff(diff);
// A diff applied to empty options should be the diff itself.
expect(empty.applyDiff(diff), diff);
// A diff applied to non-empty options should update that field.
expect(updated.buildingsEnabled, true);
});
});
group('isEmpty', () {
test('is true for empty', () async {
const MapConfiguration nullOptions = MapConfiguration();
expect(nullOptions.isEmpty, true);
});
test('is false with compassEnabled', () async {
const MapConfiguration diff = MapConfiguration(compassEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with mapToolbarEnabled', () async {
const MapConfiguration diff = MapConfiguration(mapToolbarEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with cameraTargetBounds', () async {
final CameraTargetBounds newBounds = CameraTargetBounds(LatLngBounds(
northeast: const LatLng(55, 15), southwest: const LatLng(5, 15)));
final MapConfiguration diff =
MapConfiguration(cameraTargetBounds: newBounds);
expect(diff.isEmpty, false);
});
test('is false with mapType', () async {
const MapConfiguration diff =
MapConfiguration(mapType: MapType.satellite);
expect(diff.isEmpty, false);
});
test('is false with minMaxZoomPreference', () async {
const MinMaxZoomPreference newZoomPref = MinMaxZoomPreference(3.3, 4.5);
const MapConfiguration diff =
MapConfiguration(minMaxZoomPreference: newZoomPref);
expect(diff.isEmpty, false);
});
test('is false with rotateGesturesEnabled', () async {
const MapConfiguration diff =
MapConfiguration(rotateGesturesEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with scrollGesturesEnabled', () async {
const MapConfiguration diff =
MapConfiguration(scrollGesturesEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with tiltGesturesEnabled', () async {
const MapConfiguration diff = MapConfiguration(tiltGesturesEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with trackCameraPosition', () async {
const MapConfiguration diff = MapConfiguration(trackCameraPosition: true);
expect(diff.isEmpty, false);
});
test('is false with zoomControlsEnabled', () async {
const MapConfiguration diff = MapConfiguration(zoomControlsEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with zoomGesturesEnabled', () async {
const MapConfiguration diff = MapConfiguration(zoomGesturesEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with liteModeEnabled', () async {
const MapConfiguration diff = MapConfiguration(liteModeEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with myLocationEnabled', () async {
const MapConfiguration diff = MapConfiguration(myLocationEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with myLocationButtonEnabled', () async {
const MapConfiguration diff =
MapConfiguration(myLocationButtonEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with padding', () async {
const EdgeInsets newPadding =
EdgeInsets.symmetric(vertical: 1.0, horizontal: 3.0);
const MapConfiguration diff = MapConfiguration(padding: newPadding);
expect(diff.isEmpty, false);
});
test('is false with indoorViewEnabled', () async {
const MapConfiguration diff = MapConfiguration(indoorViewEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with trafficEnabled', () async {
const MapConfiguration diff = MapConfiguration(trafficEnabled: true);
expect(diff.isEmpty, false);
});
test('is false with buildingsEnabled', () async {
const MapConfiguration diff = MapConfiguration(buildingsEnabled: true);
expect(diff.isEmpty, false);
});
});
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/map_configuration_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/map_configuration_test.dart",
"repo_id": "plugins",
"token_count": 4925
} | 1,140 |
// Mocks generated by Mockito 5.3.2 from annotations
// in google_maps_flutter_web_integration_tests/integration_test/google_maps_controller_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:google_maps/google_maps.dart' as _i2;
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'
as _i4;
import 'package:google_maps_flutter_web/google_maps_flutter_web.dart' as _i3;
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
// ignore_for_file: subtype_of_sealed_class
class _FakeGMap_0 extends _i1.SmartFake implements _i2.GMap {
_FakeGMap_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [CirclesController].
///
/// See the documentation for Mockito's code generation for more information.
class MockCirclesController extends _i1.Mock implements _i3.CirclesController {
@override
Map<_i4.CircleId, _i3.CircleController> get circles => (super.noSuchMethod(
Invocation.getter(#circles),
returnValue: <_i4.CircleId, _i3.CircleController>{},
returnValueForMissingStub: <_i4.CircleId, _i3.CircleController>{},
) as Map<_i4.CircleId, _i3.CircleController>);
@override
_i2.GMap get googleMap => (super.noSuchMethod(
Invocation.getter(#googleMap),
returnValue: _FakeGMap_0(
this,
Invocation.getter(#googleMap),
),
returnValueForMissingStub: _FakeGMap_0(
this,
Invocation.getter(#googleMap),
),
) as _i2.GMap);
@override
set googleMap(_i2.GMap? _googleMap) => super.noSuchMethod(
Invocation.setter(
#googleMap,
_googleMap,
),
returnValueForMissingStub: null,
);
@override
int get mapId => (super.noSuchMethod(
Invocation.getter(#mapId),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
set mapId(int? _mapId) => super.noSuchMethod(
Invocation.setter(
#mapId,
_mapId,
),
returnValueForMissingStub: null,
);
@override
void addCircles(Set<_i4.Circle>? circlesToAdd) => super.noSuchMethod(
Invocation.method(
#addCircles,
[circlesToAdd],
),
returnValueForMissingStub: null,
);
@override
void changeCircles(Set<_i4.Circle>? circlesToChange) => super.noSuchMethod(
Invocation.method(
#changeCircles,
[circlesToChange],
),
returnValueForMissingStub: null,
);
@override
void removeCircles(Set<_i4.CircleId>? circleIdsToRemove) =>
super.noSuchMethod(
Invocation.method(
#removeCircles,
[circleIdsToRemove],
),
returnValueForMissingStub: null,
);
@override
void bindToMap(
int? mapId,
_i2.GMap? googleMap,
) =>
super.noSuchMethod(
Invocation.method(
#bindToMap,
[
mapId,
googleMap,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [PolygonsController].
///
/// See the documentation for Mockito's code generation for more information.
class MockPolygonsController extends _i1.Mock
implements _i3.PolygonsController {
@override
Map<_i4.PolygonId, _i3.PolygonController> get polygons => (super.noSuchMethod(
Invocation.getter(#polygons),
returnValue: <_i4.PolygonId, _i3.PolygonController>{},
returnValueForMissingStub: <_i4.PolygonId, _i3.PolygonController>{},
) as Map<_i4.PolygonId, _i3.PolygonController>);
@override
_i2.GMap get googleMap => (super.noSuchMethod(
Invocation.getter(#googleMap),
returnValue: _FakeGMap_0(
this,
Invocation.getter(#googleMap),
),
returnValueForMissingStub: _FakeGMap_0(
this,
Invocation.getter(#googleMap),
),
) as _i2.GMap);
@override
set googleMap(_i2.GMap? _googleMap) => super.noSuchMethod(
Invocation.setter(
#googleMap,
_googleMap,
),
returnValueForMissingStub: null,
);
@override
int get mapId => (super.noSuchMethod(
Invocation.getter(#mapId),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
set mapId(int? _mapId) => super.noSuchMethod(
Invocation.setter(
#mapId,
_mapId,
),
returnValueForMissingStub: null,
);
@override
void addPolygons(Set<_i4.Polygon>? polygonsToAdd) => super.noSuchMethod(
Invocation.method(
#addPolygons,
[polygonsToAdd],
),
returnValueForMissingStub: null,
);
@override
void changePolygons(Set<_i4.Polygon>? polygonsToChange) => super.noSuchMethod(
Invocation.method(
#changePolygons,
[polygonsToChange],
),
returnValueForMissingStub: null,
);
@override
void removePolygons(Set<_i4.PolygonId>? polygonIdsToRemove) =>
super.noSuchMethod(
Invocation.method(
#removePolygons,
[polygonIdsToRemove],
),
returnValueForMissingStub: null,
);
@override
void bindToMap(
int? mapId,
_i2.GMap? googleMap,
) =>
super.noSuchMethod(
Invocation.method(
#bindToMap,
[
mapId,
googleMap,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [PolylinesController].
///
/// See the documentation for Mockito's code generation for more information.
class MockPolylinesController extends _i1.Mock
implements _i3.PolylinesController {
@override
Map<_i4.PolylineId, _i3.PolylineController> get lines => (super.noSuchMethod(
Invocation.getter(#lines),
returnValue: <_i4.PolylineId, _i3.PolylineController>{},
returnValueForMissingStub: <_i4.PolylineId, _i3.PolylineController>{},
) as Map<_i4.PolylineId, _i3.PolylineController>);
@override
_i2.GMap get googleMap => (super.noSuchMethod(
Invocation.getter(#googleMap),
returnValue: _FakeGMap_0(
this,
Invocation.getter(#googleMap),
),
returnValueForMissingStub: _FakeGMap_0(
this,
Invocation.getter(#googleMap),
),
) as _i2.GMap);
@override
set googleMap(_i2.GMap? _googleMap) => super.noSuchMethod(
Invocation.setter(
#googleMap,
_googleMap,
),
returnValueForMissingStub: null,
);
@override
int get mapId => (super.noSuchMethod(
Invocation.getter(#mapId),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
set mapId(int? _mapId) => super.noSuchMethod(
Invocation.setter(
#mapId,
_mapId,
),
returnValueForMissingStub: null,
);
@override
void addPolylines(Set<_i4.Polyline>? polylinesToAdd) => super.noSuchMethod(
Invocation.method(
#addPolylines,
[polylinesToAdd],
),
returnValueForMissingStub: null,
);
@override
void changePolylines(Set<_i4.Polyline>? polylinesToChange) =>
super.noSuchMethod(
Invocation.method(
#changePolylines,
[polylinesToChange],
),
returnValueForMissingStub: null,
);
@override
void removePolylines(Set<_i4.PolylineId>? polylineIdsToRemove) =>
super.noSuchMethod(
Invocation.method(
#removePolylines,
[polylineIdsToRemove],
),
returnValueForMissingStub: null,
);
@override
void bindToMap(
int? mapId,
_i2.GMap? googleMap,
) =>
super.noSuchMethod(
Invocation.method(
#bindToMap,
[
mapId,
googleMap,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [MarkersController].
///
/// See the documentation for Mockito's code generation for more information.
class MockMarkersController extends _i1.Mock implements _i3.MarkersController {
@override
Map<_i4.MarkerId, _i3.MarkerController> get markers => (super.noSuchMethod(
Invocation.getter(#markers),
returnValue: <_i4.MarkerId, _i3.MarkerController>{},
returnValueForMissingStub: <_i4.MarkerId, _i3.MarkerController>{},
) as Map<_i4.MarkerId, _i3.MarkerController>);
@override
_i2.GMap get googleMap => (super.noSuchMethod(
Invocation.getter(#googleMap),
returnValue: _FakeGMap_0(
this,
Invocation.getter(#googleMap),
),
returnValueForMissingStub: _FakeGMap_0(
this,
Invocation.getter(#googleMap),
),
) as _i2.GMap);
@override
set googleMap(_i2.GMap? _googleMap) => super.noSuchMethod(
Invocation.setter(
#googleMap,
_googleMap,
),
returnValueForMissingStub: null,
);
@override
int get mapId => (super.noSuchMethod(
Invocation.getter(#mapId),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
set mapId(int? _mapId) => super.noSuchMethod(
Invocation.setter(
#mapId,
_mapId,
),
returnValueForMissingStub: null,
);
@override
void addMarkers(Set<_i4.Marker>? markersToAdd) => super.noSuchMethod(
Invocation.method(
#addMarkers,
[markersToAdd],
),
returnValueForMissingStub: null,
);
@override
void changeMarkers(Set<_i4.Marker>? markersToChange) => super.noSuchMethod(
Invocation.method(
#changeMarkers,
[markersToChange],
),
returnValueForMissingStub: null,
);
@override
void removeMarkers(Set<_i4.MarkerId>? markerIdsToRemove) =>
super.noSuchMethod(
Invocation.method(
#removeMarkers,
[markerIdsToRemove],
),
returnValueForMissingStub: null,
);
@override
void showMarkerInfoWindow(_i4.MarkerId? markerId) => super.noSuchMethod(
Invocation.method(
#showMarkerInfoWindow,
[markerId],
),
returnValueForMissingStub: null,
);
@override
void hideMarkerInfoWindow(_i4.MarkerId? markerId) => super.noSuchMethod(
Invocation.method(
#hideMarkerInfoWindow,
[markerId],
),
returnValueForMissingStub: null,
);
@override
bool isInfoWindowShown(_i4.MarkerId? markerId) => (super.noSuchMethod(
Invocation.method(
#isInfoWindowShown,
[markerId],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
void bindToMap(
int? mapId,
_i2.GMap? googleMap,
) =>
super.noSuchMethod(
Invocation.method(
#bindToMap,
[
mapId,
googleMap,
],
),
returnValueForMissingStub: null,
);
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.mocks.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.mocks.dart",
"repo_id": "plugins",
"token_count": 5464
} | 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.
part of google_maps_flutter_web;
/// The `CircleController` class wraps a [gmaps.Circle] and its `onTap` behavior.
class CircleController {
/// Creates a `CircleController`, which wraps a [gmaps.Circle] object and its `onTap` behavior.
CircleController({
required gmaps.Circle circle,
bool consumeTapEvents = false,
ui.VoidCallback? onTap,
}) : _circle = circle,
_consumeTapEvents = consumeTapEvents {
if (onTap != null) {
circle.onClick.listen((_) {
onTap.call();
});
}
}
gmaps.Circle? _circle;
final bool _consumeTapEvents;
/// Returns the wrapped [gmaps.Circle]. Only used for testing.
@visibleForTesting
gmaps.Circle? get circle => _circle;
/// Returns `true` if this Controller will use its own `onTap` handler to consume events.
bool get consumeTapEvents => _consumeTapEvents;
/// Updates the options of the wrapped [gmaps.Circle] object.
///
/// This cannot be called after [remove].
void update(gmaps.CircleOptions options) {
assert(_circle != null, 'Cannot `update` Circle after calling `remove`.');
_circle!.options = options;
}
/// Disposes of the currently wrapped [gmaps.Circle].
void remove() {
if (_circle != null) {
_circle!.visible = false;
_circle!.radius = 0;
_circle!.map = null;
_circle = null;
}
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/circle.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/circle.dart",
"repo_id": "plugins",
"token_count": 516
} | 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.
package io.flutter.plugins.googlesigninexample;
import static org.junit.Assert.assertTrue;
import androidx.test.core.app.ActivityScenario;
import io.flutter.plugins.googlesignin.GoogleSignInPlugin;
import org.junit.Test;
public class GoogleSignInTest {
@Test
public void googleSignInPluginIsAdded() {
final ActivityScenario<GoogleSignInTestActivity> scenario =
ActivityScenario.launch(GoogleSignInTestActivity.class);
scenario.onActivity(
activity -> {
assertTrue(activity.engine.getPlugins().has(GoogleSignInPlugin.class));
});
}
}
| plugins/packages/google_sign_in/google_sign_in_android/example/android/app/src/androidTest/java/io/flutter/plugins/googlesigninexample/GoogleSignInTest.java/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_android/example/android/app/src/androidTest/java/io/flutter/plugins/googlesigninexample/GoogleSignInTest.java",
"repo_id": "plugins",
"token_count": 247
} | 1,143 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.3.0
* Adopts `plugin_platform_interface`. As a result, `isMock` is deprecated in
favor of the now-standard `MockPlatformInterfaceMixin`.
## 2.2.0
* Adds support for the `serverClientId` parameter.
## 2.1.3
* Enables mocking models by changing overridden operator == parameter type from `dynamic` to `Object`.
* Removes unnecessary imports.
* Adds `SignInInitParameters` class to hold all sign in params, including the new `forceCodeForRefreshToken`.
## 2.1.2
* Internal code cleanup for stricter analysis options.
## 2.1.1
* Removes dependency on `meta`.
## 2.1.0
* Add serverAuthCode attribute to user data
## 2.0.1
* Updates `init` function in `MethodChannelGoogleSignIn` to parametrize `clientId` property.
## 2.0.0
* Migrate to null-safety.
## 1.1.3
* Update Flutter SDK constraint.
## 1.1.2
* Update lower bound of dart dependency to 2.1.0.
## 1.1.1
* Add attribute serverAuthCode.
## 1.1.0
* Add hasRequestedScope method to determine if an Oauth scope has been granted.
* Add requestScope Method to request new Oauth scopes be granted by the user.
## 1.0.4
* Make the pedantic dev_dependency explicit.
## 1.0.3
* Remove the deprecated `author:` field from pubspec.yaml
* Require Flutter SDK 1.10.0 or greater.
## 1.0.2
* Add missing documentation.
## 1.0.1
* Switch away from quiver_hashcode.
## 1.0.0
* Initial release.
| plugins/packages/google_sign_in/google_sign_in_platform_interface/CHANGELOG.md/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_platform_interface/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 478
} | 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.
import 'package:flutter/services.dart' show PlatformException;
import 'package:flutter_test/flutter_test.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:google_sign_in_web/google_sign_in_web.dart';
import 'package:google_sign_in_web/src/gis_client.dart';
import 'package:google_sign_in_web/src/people.dart';
import 'package:integration_test/integration_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart' as mockito;
import 'google_sign_in_web_test.mocks.dart';
import 'src/dom.dart';
import 'src/person.dart';
// Mock GisSdkClient so we can simulate any response from the JS side.
@GenerateMocks(<Type>[], customMocks: <MockSpec<dynamic>>[
MockSpec<GisSdkClient>(onMissingStub: OnMissingStub.returnDefault),
])
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('Constructor', () {
const String expectedClientId = '3xp3c73d_c113n7_1d';
testWidgets('Loads clientId when set in a meta', (_) async {
final GoogleSignInPlugin plugin = GoogleSignInPlugin(
debugOverrideLoader: true,
);
expect(plugin.autoDetectedClientId, isNull);
// Add it to the test page now, and try again
final DomHtmlMetaElement meta =
document.createElement('meta') as DomHtmlMetaElement
..name = clientIdMetaName
..content = expectedClientId;
document.head.appendChild(meta);
final GoogleSignInPlugin another = GoogleSignInPlugin(
debugOverrideLoader: true,
);
expect(another.autoDetectedClientId, expectedClientId);
// cleanup
meta.remove();
});
});
group('initWithParams', () {
late GoogleSignInPlugin plugin;
late MockGisSdkClient mockGis;
setUp(() {
plugin = GoogleSignInPlugin(
debugOverrideLoader: true,
);
mockGis = MockGisSdkClient();
});
testWidgets('initializes if all is OK', (_) async {
await plugin.initWithParams(
const SignInInitParameters(
clientId: 'some-non-null-client-id',
scopes: <String>['ok1', 'ok2', 'ok3'],
),
overrideClient: mockGis,
);
expect(plugin.initialized, completes);
});
testWidgets('asserts clientId is not null', (_) async {
expect(() async {
await plugin.initWithParams(
const SignInInitParameters(),
overrideClient: mockGis,
);
}, throwsAssertionError);
});
testWidgets('asserts serverClientId must be null', (_) async {
expect(() async {
await plugin.initWithParams(
const SignInInitParameters(
clientId: 'some-non-null-client-id',
serverClientId: 'unexpected-non-null-client-id',
),
overrideClient: mockGis,
);
}, throwsAssertionError);
});
testWidgets('asserts no scopes have any spaces', (_) async {
expect(() async {
await plugin.initWithParams(
const SignInInitParameters(
clientId: 'some-non-null-client-id',
scopes: <String>['ok1', 'ok2', 'not ok', 'ok3'],
),
overrideClient: mockGis,
);
}, throwsAssertionError);
});
testWidgets('must be called for most of the API to work', (_) async {
expect(() async {
await plugin.signInSilently();
}, throwsStateError);
expect(() async {
await plugin.signIn();
}, throwsStateError);
expect(() async {
await plugin.getTokens(email: '');
}, throwsStateError);
expect(() async {
await plugin.signOut();
}, throwsStateError);
expect(() async {
await plugin.disconnect();
}, throwsStateError);
expect(() async {
await plugin.isSignedIn();
}, throwsStateError);
expect(() async {
await plugin.clearAuthCache(token: '');
}, throwsStateError);
expect(() async {
await plugin.requestScopes(<String>[]);
}, throwsStateError);
});
});
group('(with mocked GIS)', () {
late GoogleSignInPlugin plugin;
late MockGisSdkClient mockGis;
const SignInInitParameters options = SignInInitParameters(
clientId: 'some-non-null-client-id',
scopes: <String>['ok1', 'ok2', 'ok3'],
);
setUp(() {
plugin = GoogleSignInPlugin(
debugOverrideLoader: true,
);
mockGis = MockGisSdkClient();
});
group('signInSilently', () {
setUp(() {
plugin.initWithParams(options, overrideClient: mockGis);
});
testWidgets('always returns null, regardless of GIS response', (_) async {
final GoogleSignInUserData someUser = extractUserData(person)!;
mockito
.when(mockGis.signInSilently())
.thenAnswer((_) => Future<GoogleSignInUserData>.value(someUser));
expect(plugin.signInSilently(), completion(isNull));
mockito
.when(mockGis.signInSilently())
.thenAnswer((_) => Future<GoogleSignInUserData?>.value());
expect(plugin.signInSilently(), completion(isNull));
});
});
group('signIn', () {
setUp(() {
plugin.initWithParams(options, overrideClient: mockGis);
});
testWidgets('returns the signed-in user', (_) async {
final GoogleSignInUserData someUser = extractUserData(person)!;
mockito
.when(mockGis.signIn())
.thenAnswer((_) => Future<GoogleSignInUserData>.value(someUser));
expect(await plugin.signIn(), someUser);
});
testWidgets('returns null if no user is signed in', (_) async {
mockito
.when(mockGis.signIn())
.thenAnswer((_) => Future<GoogleSignInUserData?>.value());
expect(await plugin.signIn(), isNull);
});
testWidgets('converts inner errors to PlatformException', (_) async {
mockito.when(mockGis.signIn()).thenThrow('popup_closed');
try {
await plugin.signIn();
fail('signIn should have thrown an exception');
} catch (exception) {
expect(exception, isA<PlatformException>());
expect((exception as PlatformException).code, 'popup_closed');
}
});
});
});
}
| plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart",
"repo_id": "plugins",
"token_count": 2677
} | 1,145 |
## 0.8.5+6
* Updates minimum Flutter version to 3.0.
* Fixes names of picked files to match original filenames where possible.
## 0.8.5+5
* Updates code for stricter lint checks.
## 0.8.5+4
* Fixes null cast exception when restoring a cancelled selection.
## 0.8.5+3
* Updates minimum Flutter version to 2.10.
* Bumps gradle from 7.1.2 to 7.2.1.
## 0.8.5+2
* Updates `image_picker_platform_interface` constraint to the correct minimum
version.
## 0.8.5+1
* Switches to an internal method channel implementation.
## 0.8.5
* Updates gradle to 7.1.2.
## 0.8.4+13
* Minor fixes for new analysis options.
## 0.8.4+12
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.8.4+11
* Splits from `image_picker` as a federated implementation.
| plugins/packages/image_picker/image_picker_android/CHANGELOG.md/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 298
} | 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.
package io.flutter.plugins.imagepicker;
import static io.flutter.plugins.imagepicker.ImagePickerCache.MAP_KEY_IMAGE_QUALITY;
import static io.flutter.plugins.imagepicker.ImagePickerCache.SHARED_PREFERENCES_NAME;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import io.flutter.plugin.common.MethodCall;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class ImagePickerCacheTest {
private static final int IMAGE_QUALITY = 90;
@Mock Activity mockActivity;
@Mock SharedPreferences mockPreference;
@Mock SharedPreferences.Editor mockEditor;
@Mock MethodCall mockMethodCall;
static Map<String, Object> preferenceStorage;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
preferenceStorage = new HashMap();
when(mockActivity.getPackageName()).thenReturn("com.example.test");
when(mockActivity.getPackageManager()).thenReturn(mock(PackageManager.class));
when(mockActivity.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE))
.thenReturn(mockPreference);
when(mockPreference.edit()).thenReturn(mockEditor);
when(mockEditor.putInt(any(String.class), any(int.class)))
.then(
i -> {
preferenceStorage.put(i.getArgument(0), i.getArgument(1));
return mockEditor;
});
when(mockEditor.putLong(any(String.class), any(long.class)))
.then(
i -> {
preferenceStorage.put(i.getArgument(0), i.getArgument(1));
return mockEditor;
});
when(mockEditor.putString(any(String.class), any(String.class)))
.then(
i -> {
preferenceStorage.put(i.getArgument(0), i.getArgument(1));
return mockEditor;
});
when(mockPreference.getInt(any(String.class), any(int.class)))
.then(
i -> {
int result =
(int)
((preferenceStorage.get(i.getArgument(0)) != null)
? preferenceStorage.get(i.getArgument(0))
: i.getArgument(1));
return result;
});
when(mockPreference.getLong(any(String.class), any(long.class)))
.then(
i -> {
long result =
(long)
((preferenceStorage.get(i.getArgument(0)) != null)
? preferenceStorage.get(i.getArgument(0))
: i.getArgument(1));
return result;
});
when(mockPreference.getString(any(String.class), any(String.class)))
.then(
i -> {
String result =
(String)
((preferenceStorage.get(i.getArgument(0)) != null)
? preferenceStorage.get(i.getArgument(0))
: i.getArgument(1));
return result;
});
when(mockPreference.contains(any(String.class))).thenReturn(true);
}
@Test
public void ImageCache_ShouldBeAbleToSetAndGetQuality() {
when(mockMethodCall.argument(MAP_KEY_IMAGE_QUALITY)).thenReturn(IMAGE_QUALITY);
ImagePickerCache cache = new ImagePickerCache(mockActivity);
cache.saveDimensionWithMethodCall(mockMethodCall);
Map<String, Object> resultMap = cache.getCacheMap();
int imageQuality = (int) resultMap.get(cache.MAP_KEY_IMAGE_QUALITY);
assertThat(imageQuality, equalTo(IMAGE_QUALITY));
when(mockMethodCall.argument(MAP_KEY_IMAGE_QUALITY)).thenReturn(null);
cache.saveDimensionWithMethodCall(mockMethodCall);
Map<String, Object> resultMapWithDefaultQuality = cache.getCacheMap();
int defaultImageQuality = (int) resultMapWithDefaultQuality.get(cache.MAP_KEY_IMAGE_QUALITY);
assertThat(defaultImageQuality, equalTo(100));
}
}
| plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerCacheTest.java/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerCacheTest.java",
"repo_id": "plugins",
"token_count": 1921
} | 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.
import 'dart:async';
import 'dart:html' as html;
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'src/image_resizer.dart';
const String _kImagePickerInputsDomId = '__image_picker_web-file-input';
const String _kAcceptImageMimeType = 'image/*';
const String _kAcceptVideoMimeType = 'video/3gpp,video/x-m4v,video/mp4,video/*';
/// The web implementation of [ImagePickerPlatform].
///
/// This class implements the `package:image_picker` functionality for the web.
class ImagePickerPlugin extends ImagePickerPlatform {
/// A constructor that allows tests to override the function that creates file inputs.
ImagePickerPlugin({
@visibleForTesting ImagePickerPluginTestOverrides? overrides,
@visibleForTesting ImageResizer? imageResizer,
}) : _overrides = overrides {
_imageResizer = imageResizer ?? ImageResizer();
_target = _ensureInitialized(_kImagePickerInputsDomId);
}
final ImagePickerPluginTestOverrides? _overrides;
bool get _hasOverrides => _overrides != null;
late html.Element _target;
late ImageResizer _imageResizer;
/// Registers this class as the default instance of [ImagePickerPlatform].
static void registerWith(Registrar registrar) {
ImagePickerPlatform.instance = ImagePickerPlugin();
}
/// Returns a [PickedFile] with the image that was picked.
///
/// The `source` argument controls where the image comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// Note that the `maxWidth`, `maxHeight` and `imageQuality` arguments are not supported on the web. If any of these arguments is supplied, it'll be silently ignored by the web version of the plugin.
///
/// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera].
/// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device.
/// Defaults to [CameraDevice.rear].
///
/// If no images were picked, the return value is null.
@override
Future<PickedFile> pickImage({
required ImageSource source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
CameraDevice preferredCameraDevice = CameraDevice.rear,
}) {
final String? capture =
computeCaptureAttribute(source, preferredCameraDevice);
return pickFile(accept: _kAcceptImageMimeType, capture: capture);
}
/// Returns a [PickedFile] containing the video that was picked.
///
/// The [source] argument controls where the video comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// Note that the `maxDuration` argument is not supported on the web. If the argument is supplied, it'll be silently ignored by the web version of the plugin.
///
/// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera].
/// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device.
/// Defaults to [CameraDevice.rear].
///
/// If no images were picked, the return value is null.
@override
Future<PickedFile> pickVideo({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) {
final String? capture =
computeCaptureAttribute(source, preferredCameraDevice);
return pickFile(accept: _kAcceptVideoMimeType, capture: capture);
}
/// Injects a file input with the specified accept+capture attributes, and
/// returns the PickedFile that the user selected locally.
///
/// `capture` is only supported in mobile browsers.
/// See https://caniuse.com/#feat=html-media-capture
@visibleForTesting
Future<PickedFile> pickFile({
String? accept,
String? capture,
}) {
final html.FileUploadInputElement input =
createInputElement(accept, capture) as html.FileUploadInputElement;
_injectAndActivate(input);
return _getSelectedFile(input);
}
/// Returns an [XFile] with the image that was picked.
///
/// The `source` argument controls where the image comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// Note that the `maxWidth`, `maxHeight` and `imageQuality` arguments are not supported on the web. If any of these arguments is supplied, it'll be silently ignored by the web version of the plugin.
///
/// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera].
/// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device.
/// Defaults to [CameraDevice.rear].
///
/// If no images were picked, the return value is null.
@override
Future<XFile> getImage({
required ImageSource source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
CameraDevice preferredCameraDevice = CameraDevice.rear,
}) async {
final String? capture =
computeCaptureAttribute(source, preferredCameraDevice);
final List<XFile> files = await getFiles(
accept: _kAcceptImageMimeType,
capture: capture,
);
return _imageResizer.resizeImageIfNeeded(
files.first,
maxWidth,
maxHeight,
imageQuality,
);
}
/// Returns an [XFile] containing the video that was picked.
///
/// The [source] argument controls where the video comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// Note that the `maxDuration` argument is not supported on the web. If the argument is supplied, it'll be silently ignored by the web version of the plugin.
///
/// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera].
/// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device.
/// Defaults to [CameraDevice.rear].
///
/// If no images were picked, the return value is null.
@override
Future<XFile> getVideo({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) async {
final String? capture =
computeCaptureAttribute(source, preferredCameraDevice);
final List<XFile> files = await getFiles(
accept: _kAcceptVideoMimeType,
capture: capture,
);
return files.first;
}
/// Injects a file input, and returns a list of XFile that the user selected locally.
@override
Future<List<XFile>> getMultiImage({
double? maxWidth,
double? maxHeight,
int? imageQuality,
}) async {
final List<XFile> images = await getFiles(
accept: _kAcceptImageMimeType,
multiple: true,
);
final Iterable<Future<XFile>> resized = images.map(
(XFile image) => _imageResizer.resizeImageIfNeeded(
image,
maxWidth,
maxHeight,
imageQuality,
),
);
return Future.wait<XFile>(resized);
}
/// Injects a file input with the specified accept+capture attributes, and
/// returns a list of XFile that the user selected locally.
///
/// `capture` is only supported in mobile browsers.
///
/// `multiple` can be passed to allow for multiple selection of files. Defaults
/// to false.
///
/// See https://caniuse.com/#feat=html-media-capture
@visibleForTesting
Future<List<XFile>> getFiles({
String? accept,
String? capture,
bool multiple = false,
}) {
final html.FileUploadInputElement input = createInputElement(
accept,
capture,
multiple: multiple,
) as html.FileUploadInputElement;
_injectAndActivate(input);
return _getSelectedXFiles(input);
}
// DOM methods
/// Converts plugin configuration into a proper value for the `capture` attribute.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#capture
@visibleForTesting
String? computeCaptureAttribute(ImageSource source, CameraDevice device) {
if (source == ImageSource.camera) {
return (device == CameraDevice.front) ? 'user' : 'environment';
}
return null;
}
List<html.File>? _getFilesFromInput(html.FileUploadInputElement input) {
if (_hasOverrides) {
return _overrides!.getMultipleFilesFromInput(input);
}
return input.files;
}
/// Handles the OnChange event from a FileUploadInputElement object
/// Returns a list of selected files.
List<html.File>? _handleOnChangeEvent(html.Event event) {
final html.FileUploadInputElement? input =
event.target as html.FileUploadInputElement?;
return input == null ? null : _getFilesFromInput(input);
}
/// Monitors an <input type="file"> and returns the selected file.
Future<PickedFile> _getSelectedFile(html.FileUploadInputElement input) {
final Completer<PickedFile> completer = Completer<PickedFile>();
// Observe the input until we can return something
input.onChange.first.then((html.Event event) {
final List<html.File>? files = _handleOnChangeEvent(event);
if (!completer.isCompleted && files != null) {
completer.complete(PickedFile(
html.Url.createObjectUrl(files.first),
));
}
});
input.onError.first.then((html.Event event) {
if (!completer.isCompleted) {
completer.completeError(event);
}
});
// Note that we don't bother detaching from these streams, since the
// "input" gets re-created in the DOM every time the user needs to
// pick a file.
return completer.future;
}
/// Monitors an <input type="file"> and returns the selected file(s).
Future<List<XFile>> _getSelectedXFiles(html.FileUploadInputElement input) {
final Completer<List<XFile>> completer = Completer<List<XFile>>();
// Observe the input until we can return something
input.onChange.first.then((html.Event event) {
final List<html.File>? files = _handleOnChangeEvent(event);
if (!completer.isCompleted && files != null) {
completer.complete(files.map((html.File file) {
return XFile(
html.Url.createObjectUrl(file),
name: file.name,
length: file.size,
lastModified: DateTime.fromMillisecondsSinceEpoch(
file.lastModified ?? DateTime.now().millisecondsSinceEpoch,
),
mimeType: file.type,
);
}).toList());
}
});
input.onError.first.then((html.Event event) {
if (!completer.isCompleted) {
completer.completeError(event);
}
});
// Note that we don't bother detaching from these streams, since the
// "input" gets re-created in the DOM every time the user needs to
// pick a file.
return completer.future;
}
/// Initializes a DOM container where we can host input elements.
html.Element _ensureInitialized(String id) {
html.Element? target = html.querySelector('#$id');
if (target == null) {
final html.Element targetElement =
html.Element.tag('flt-image-picker-inputs')..id = id;
html.querySelector('body')!.children.add(targetElement);
target = targetElement;
}
return target;
}
/// Creates an input element that accepts certain file types, and
/// allows to `capture` from the device's cameras (where supported)
@visibleForTesting
html.Element createInputElement(
String? accept,
String? capture, {
bool multiple = false,
}) {
if (_hasOverrides) {
return _overrides!.createInputElement(accept, capture);
}
final html.Element element = html.FileUploadInputElement()
..accept = accept
..multiple = multiple;
if (capture != null) {
element.setAttribute('capture', capture);
}
return element;
}
/// Injects the file input element, and clicks on it
void _injectAndActivate(html.Element element) {
_target.children.clear();
_target.children.add(element);
element.click();
}
}
// Some tools to override behavior for unit-testing
/// A function that creates a file input with the passed in `accept` and `capture` attributes.
@visibleForTesting
typedef OverrideCreateInputFunction = html.Element Function(
String? accept,
String? capture,
);
/// A function that extracts list of files from the file `input` passed in.
@visibleForTesting
typedef OverrideExtractMultipleFilesFromInputFunction = List<html.File>
Function(html.Element? input);
/// Overrides for some of the functionality above.
@visibleForTesting
class ImagePickerPluginTestOverrides {
/// Override the creation of the input element.
late OverrideCreateInputFunction createInputElement;
/// Override the extraction of the selected files from an input element.
late OverrideExtractMultipleFilesFromInputFunction getMultipleFilesFromInput;
}
| plugins/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart",
"repo_id": "plugins",
"token_count": 4272
} | 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.
#import "ImagePickerTestImages.h"
@implementation ImagePickerTestImages
+ (NSData *)JPGTestData {
NSBundle *bundle = [NSBundle bundleForClass:self];
NSURL *url = [bundle URLForResource:@"jpgImage" withExtension:@"jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
if (!data.length) {
// When the tests are run outside the example project (podspec lint) the image may not be
// embedded in the test bundle. Fall back to the base64 string representation of the jpg.
data = [[NSData alloc]
initWithBase64EncodedString:
@"/9j/4AAQSkZJRgABAQAALgAuAAD/4QCMRXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABA"
"AAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAAAuAAAAAQAAAC4AAAABAAOg"
"AQADAAAAAQABAACgAgAEAAAAAQAAAAygAwAEAAAAAQAAAAcAAAAA/+EJc2h0dHA6Ly9ucy5hZG9iZS5jb20"
"veGFwLzEuMC8APD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz"
"4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiP"
"iA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucy"
"MiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczpwaG90b3Nob3A9Imh0dHA6Ly9ucy5hZ"
"G9iZS5jb20vcGhvdG9zaG9wLzEuMC8iIHBob3Rvc2hvcDpDcmVkaXQ9IsKpIEdvb2dsZSIvPiA8L3JkZjpSR"
"EY+IDwveDp4bXBtZXRhPiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI"
"CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDw/eHBhY2tldCBlbmQ9In"
"ciPz4A/+0AVlBob3Rvc2hvcCAzLjAAOEJJTQQEAAAAAAAdHAFaAAMbJUccAgAAAgACHAJuAAnCqSBHb29nbG"
"UAOEJJTQQlAAAAAAAQmkt2IF3PgNJVMGnV2zijEf/AABEIAAcADAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQA"
"AAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQ"
"gjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h"
"5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp"
"6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAAB"
"AncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0R"
"FRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tr"
"e4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2wBDAAQDAwMDAgQDAwMEBAQFBgoGBg"
"UFBgwICQcKDgwPDg4MDQ0PERYTDxAVEQ0NExoTFRcYGRkZDxIbHRsYHRYYGRj/2wBDAQQEBAYFBgsGBgsYEA0"
"QGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBj/3QAEAAH/2gAMAwEA"
"AhEDEQA/AMWiiivzk/qo/9k="
options:0];
}
return data;
}
+ (NSData *)PNGTestData {
NSBundle *bundle = [NSBundle bundleForClass:self];
NSURL *url = [bundle URLForResource:@"pngImage" withExtension:@"png"];
NSData *data = [NSData dataWithContentsOfURL:url];
if (!data.length) {
// When the tests are run outside the example project (podspec lint) the image may not be
// embedded in the test bundle. Fall back to the base64 string representation of the png.
data = [[NSData alloc]
initWithBase64EncodedString:
@"iVBORw0KGgoAAAAEQ2dCSVAAIAYsuHdmAAAADUlIRFIAAAAMAAAABwgGAAAAPLKsJAAAAARnQU1BAACxjwv8Y"
"QUAAAABc1JHQgCuzhzpAAAAIGNIUk0AAHomAACAhAAA+"
"gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAJcEh"
"ZcwAABxMAAAcTAc4gDwgAAAAOSURBVGMwdX71nxTMMKqBCAwAsfuEYQAAAABJRU5ErkJggg=="
options:0];
}
return data;
}
+ (NSData *)GIFTestData {
NSBundle *bundle = [NSBundle bundleForClass:self];
NSURL *url = [bundle URLForResource:@"gifImage" withExtension:@"gif"];
NSData *data = [NSData dataWithContentsOfURL:url];
if (!data.length) {
// When the tests are run outside the example project (podspec lint) the image may not be
// embedded in the test bundle. Fall back to the base64 string representation of the gif.
data = [[NSData alloc]
initWithBase64EncodedString:
@"R0lGODlhDAAHAPAAAOpCNQAAACH5BABkAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAADAAHAAACCISP"
"qcvtD1UBACH5BABkAAAALAAAAAAMAAcAhuc/JPA/K+49Ne4+PvA7MrhYHoB+A4N9BYh+BYZ+E4xyG496HZJ"
"8F5J4GaRtE6tsH7tWIr9SK7xVKJl3IKpvI7lrKc1FLc5PLNJILsdTJMFVJsZWJshWIM9XIshWJNBWLd1SK9"
"BUMNFRNOlAI+9CMuNJMetHPnuCAF66F1u8FVu7GV27HGytG3utGH6rHGK1G3WxFWeuIHqlIG60IGi4JTnTDz"
"jZDy/VEy/eFTnVEDzXFxflABfjBRPmBRbnBxPrABvpARntAxLuCBXuCQTyAAb1BgvwACnmDSPpDSLjECPpED"
"HhFFDLGIeAFoiBFoqCF4uCHYWnHJGVJqSNJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAdWgAIXCjE3PTtAPDUuByQfCzQ4Qj9BPjktBgAcC"
"StJRURGQzYwJyMdDDM6SkhHS0xRCAEgD1IsKikoLzJTDgQlEBQNT05NUBMVBQMmGCEZHhsaEhEiFoEAIfkEAG"
"QAAAAsAAAAAAwABwCFB+8ACewACu0ACe4ACO8AC+4ACu8ADOwAD+wAEOYAEekAA/EABfAAB/IAAfUAA/UAAP"
"cAAfcAAvYAA/cBBPQABfUABvQAB/UBBvYBCfAACPEAC/AACvIACvMBAPgAAPkAAPgBAPkBAvgBAPoAAPoBA"
"PsBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"AAAAAAAAAAAAAAAAAAAAAAAABkfAAadjeUxEEYnk8QBoLhUHCASJJCWLyiTiIZFG3lAoO4F4SiUwScywYCQQ8"
"ScEEokCG06D8pA4mBUWCQoIBwIGGQQGBgUFQQA7"
options:0];
}
return data;
}
@end
| plugins/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImagePickerTestImages.m/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImagePickerTestImages.m",
"repo_id": "plugins",
"token_count": 5112
} | 1,149 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.0.3), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis
// ignore_for_file: avoid_relative_lib_imports
// @dart = 2.12
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#106316)
// ignore: unnecessary_import
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
// Manually changed due to https://github.com/flutter/flutter/issues/97744
import 'package:image_picker_ios/src/messages.g.dart';
class _TestHostImagePickerApiCodec extends StandardMessageCodec {
const _TestHostImagePickerApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is MaxSize) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is SourceSpecification) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return MaxSize.decode(readValue(buffer)!);
case 129:
return SourceSpecification.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestHostImagePickerApi {
static const MessageCodec<Object?> codec = _TestHostImagePickerApiCodec();
Future<String?> pickImage(SourceSpecification source, MaxSize maxSize,
int? imageQuality, bool requestFullMetadata);
Future<List<String?>?> pickMultiImage(
MaxSize maxSize, int? imageQuality, bool requestFullMetadata);
Future<String?> pickVideo(
SourceSpecification source, int? maxDurationSeconds);
static void setup(TestHostImagePickerApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ImagePickerApi.pickImage', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickImage was null.');
final List<Object?> args = (message as List<Object?>?)!;
final SourceSpecification? arg_source =
(args[0] as SourceSpecification?);
assert(arg_source != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickImage was null, expected non-null SourceSpecification.');
final MaxSize? arg_maxSize = (args[1] as MaxSize?);
assert(arg_maxSize != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickImage was null, expected non-null MaxSize.');
final int? arg_imageQuality = (args[2] as int?);
final bool? arg_requestFullMetadata = (args[3] as bool?);
assert(arg_requestFullMetadata != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickImage was null, expected non-null bool.');
final String? output = await api.pickImage(arg_source!, arg_maxSize!,
arg_imageQuality, arg_requestFullMetadata!);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ImagePickerApi.pickMultiImage', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickMultiImage was null.');
final List<Object?> args = (message as List<Object?>?)!;
final MaxSize? arg_maxSize = (args[0] as MaxSize?);
assert(arg_maxSize != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickMultiImage was null, expected non-null MaxSize.');
final int? arg_imageQuality = (args[1] as int?);
final bool? arg_requestFullMetadata = (args[2] as bool?);
assert(arg_requestFullMetadata != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickMultiImage was null, expected non-null bool.');
final List<String?>? output = await api.pickMultiImage(
arg_maxSize!, arg_imageQuality, arg_requestFullMetadata!);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ImagePickerApi.pickVideo', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickVideo was null.');
final List<Object?> args = (message as List<Object?>?)!;
final SourceSpecification? arg_source =
(args[0] as SourceSpecification?);
assert(arg_source != null,
'Argument for dev.flutter.pigeon.ImagePickerApi.pickVideo was null, expected non-null SourceSpecification.');
final int? arg_maxDurationSeconds = (args[1] as int?);
final String? output =
await api.pickVideo(arg_source!, arg_maxDurationSeconds);
return <Object?, Object?>{'result': output};
});
}
}
}
}
| plugins/packages/image_picker/image_picker_ios/test/test_api.g.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/test/test_api.g.dart",
"repo_id": "plugins",
"token_count": 2436
} | 1,150 |
org.gradle.jvmargs=-Xmx4G
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
| plugins/packages/in_app_purchase/in_app_purchase_android/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 38
} | 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 'package:flutter/foundation.dart';
import 'package:json_annotation/json_annotation.dart';
import 'billing_client_wrapper.dart';
// WARNING: Changes to `@JsonSerializable` classes need to be reflected in the
// below generated file. Run `flutter packages pub run build_runner watch` to
// rebuild and watch for further changes.
part 'sku_details_wrapper.g.dart';
/// The error message shown when the map represents billing result is invalid from method channel.
///
/// This usually indicates a series underlining code issue in the plugin.
@visibleForTesting
const String kInvalidBillingResultErrorMessage =
'Invalid billing result map from method channel.';
/// Dart wrapper around [`com.android.billingclient.api.SkuDetails`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetails).
///
/// Contains the details of an available product in Google Play Billing.
@JsonSerializable()
@SkuTypeConverter()
@immutable
class SkuDetailsWrapper {
/// Creates a [SkuDetailsWrapper] with the given purchase details.
@visibleForTesting
const SkuDetailsWrapper({
required this.description,
required this.freeTrialPeriod,
required this.introductoryPrice,
@Deprecated('Use `introductoryPriceAmountMicros` parameter instead')
String introductoryPriceMicros = '',
this.introductoryPriceAmountMicros = 0,
required this.introductoryPriceCycles,
required this.introductoryPricePeriod,
required this.price,
required this.priceAmountMicros,
required this.priceCurrencyCode,
required this.priceCurrencySymbol,
required this.sku,
required this.subscriptionPeriod,
required this.title,
required this.type,
required this.originalPrice,
required this.originalPriceAmountMicros,
}) : _introductoryPriceMicros = introductoryPriceMicros;
/// Constructs an instance of this from a key value map of data.
///
/// The map needs to have named string keys with values matching the names and
/// types of all of the members on this class.
@visibleForTesting
factory SkuDetailsWrapper.fromJson(Map<String, dynamic> map) =>
_$SkuDetailsWrapperFromJson(map);
final String _introductoryPriceMicros;
/// Textual description of the product.
@JsonKey(defaultValue: '')
final String description;
/// Trial period in ISO 8601 format.
@JsonKey(defaultValue: '')
final String freeTrialPeriod;
/// Introductory price, only applies to [SkuType.subs]. Formatted ("$0.99").
@JsonKey(defaultValue: '')
final String introductoryPrice;
/// [introductoryPrice] in micro-units 990000.
///
/// Returns 0 if the SKU is not a subscription or doesn't have an introductory
/// period.
final int introductoryPriceAmountMicros;
/// String representation of [introductoryPrice] in micro-units 990000
@Deprecated('Use `introductoryPriceAmountMicros` instead.')
@JsonKey(ignore: true)
String get introductoryPriceMicros => _introductoryPriceMicros.isEmpty
? introductoryPriceAmountMicros.toString()
: _introductoryPriceMicros;
/// The number of subscription billing periods for which the user will be given the introductory price, such as 3.
/// Returns 0 if the SKU is not a subscription or doesn't have an introductory period.
@JsonKey(defaultValue: 0)
final int introductoryPriceCycles;
/// The billing period of [introductoryPrice], in ISO 8601 format.
@JsonKey(defaultValue: '')
final String introductoryPricePeriod;
/// Formatted with currency symbol ("$0.99").
@JsonKey(defaultValue: '')
final String price;
/// [price] in micro-units ("990000").
@JsonKey(defaultValue: 0)
final int priceAmountMicros;
/// [price] ISO 4217 currency code.
@JsonKey(defaultValue: '')
final String priceCurrencyCode;
/// [price] localized currency symbol
/// For example, for the US Dollar, the symbol is "$" if the locale
/// is the US, while for other locales it may be "US$".
@JsonKey(defaultValue: '')
final String priceCurrencySymbol;
/// The product ID in Google Play Console.
@JsonKey(defaultValue: '')
final String sku;
/// Applies to [SkuType.subs], formatted in ISO 8601.
@JsonKey(defaultValue: '')
final String subscriptionPeriod;
/// The product's title.
@JsonKey(defaultValue: '')
final String title;
/// The [SkuType] of the product.
final SkuType type;
/// The original price that the user purchased this product for.
@JsonKey(defaultValue: '')
final String originalPrice;
/// [originalPrice] in micro-units ("990000").
@JsonKey(defaultValue: 0)
final int originalPriceAmountMicros;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is SkuDetailsWrapper &&
other.description == description &&
other.freeTrialPeriod == freeTrialPeriod &&
other.introductoryPrice == introductoryPrice &&
other.introductoryPriceAmountMicros == introductoryPriceAmountMicros &&
other.introductoryPriceCycles == introductoryPriceCycles &&
other.introductoryPricePeriod == introductoryPricePeriod &&
other.price == price &&
other.priceAmountMicros == priceAmountMicros &&
other.sku == sku &&
other.subscriptionPeriod == subscriptionPeriod &&
other.title == title &&
other.type == type &&
other.originalPrice == originalPrice &&
other.originalPriceAmountMicros == originalPriceAmountMicros;
}
@override
int get hashCode {
return Object.hash(
description.hashCode,
freeTrialPeriod.hashCode,
introductoryPrice.hashCode,
introductoryPriceAmountMicros.hashCode,
introductoryPriceCycles.hashCode,
introductoryPricePeriod.hashCode,
price.hashCode,
priceAmountMicros.hashCode,
sku.hashCode,
subscriptionPeriod.hashCode,
title.hashCode,
type.hashCode,
originalPrice,
originalPriceAmountMicros);
}
}
/// Translation of [`com.android.billingclient.api.SkuDetailsResponseListener`](https://developer.android.com/reference/com/android/billingclient/api/SkuDetailsResponseListener.html).
///
/// Returned by [BillingClient.querySkuDetails].
@JsonSerializable()
@immutable
class SkuDetailsResponseWrapper {
/// Creates a [SkuDetailsResponseWrapper] with the given purchase details.
@visibleForTesting
const SkuDetailsResponseWrapper(
{required this.billingResult, required this.skuDetailsList});
/// Constructs an instance of this from a key value map of data.
///
/// The map needs to have named string keys with values matching the names and
/// types of all of the members on this class.
factory SkuDetailsResponseWrapper.fromJson(Map<String, dynamic> map) =>
_$SkuDetailsResponseWrapperFromJson(map);
/// The final result of the [BillingClient.querySkuDetails] call.
final BillingResultWrapper billingResult;
/// A list of [SkuDetailsWrapper] matching the query to [BillingClient.querySkuDetails].
@JsonKey(defaultValue: <SkuDetailsWrapper>[])
final List<SkuDetailsWrapper> skuDetailsList;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is SkuDetailsResponseWrapper &&
other.billingResult == billingResult &&
other.skuDetailsList == skuDetailsList;
}
@override
int get hashCode => Object.hash(billingResult, skuDetailsList);
}
/// Params containing the response code and the debug message from the Play Billing API response.
@JsonSerializable()
@BillingResponseConverter()
@immutable
class BillingResultWrapper {
/// Constructs the object with [responseCode] and [debugMessage].
const BillingResultWrapper({required this.responseCode, this.debugMessage});
/// Constructs an instance of this from a key value map of data.
///
/// The map needs to have named string keys with values matching the names and
/// types of all of the members on this class.
factory BillingResultWrapper.fromJson(Map<String, dynamic>? map) {
if (map == null || map.isEmpty) {
return const BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: kInvalidBillingResultErrorMessage);
}
return _$BillingResultWrapperFromJson(map);
}
/// Response code returned in the Play Billing API calls.
final BillingResponse responseCode;
/// Debug message returned in the Play Billing API calls.
///
/// Defaults to `null`.
/// This message uses an en-US locale and should not be shown to users.
final String? debugMessage;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is BillingResultWrapper &&
other.responseCode == responseCode &&
other.debugMessage == debugMessage;
}
@override
int get hashCode => Object.hash(responseCode, debugMessage);
}
| plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/sku_details_wrapper.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/sku_details_wrapper.dart",
"repo_id": "plugins",
"token_count": 2846
} | 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.
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' as widgets;
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_android/billing_client_wrappers.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_android/src/channel.dart';
import 'billing_client_wrappers/purchase_wrapper_test.dart';
import 'stub_in_app_purchase_platform.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final StubInAppPurchasePlatform stubPlatform = StubInAppPurchasePlatform();
late InAppPurchaseAndroidPlatformAddition iapAndroidPlatformAddition;
const String startConnectionCall =
'BillingClient#startConnection(BillingClientStateListener)';
const String endConnectionCall = 'BillingClient#endConnection()';
setUpAll(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, stubPlatform.fakeMethodCallHandler);
});
setUp(() {
widgets.WidgetsFlutterBinding.ensureInitialized();
const String debugMessage = 'dummy message';
const BillingResponse responseCode = BillingResponse.ok;
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
stubPlatform.addResponse(
name: startConnectionCall,
value: buildBillingResultMap(expectedBillingResult));
stubPlatform.addResponse(name: endConnectionCall);
iapAndroidPlatformAddition =
InAppPurchaseAndroidPlatformAddition(BillingClient((_) {}));
});
group('consume purchases', () {
const String consumeMethodName =
'BillingClient#consumeAsync(String, ConsumeResponseListener)';
test('consume purchase async success', () async {
const BillingResponse expectedCode = BillingResponse.ok;
const String debugMessage = 'dummy message';
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: expectedCode, debugMessage: debugMessage);
stubPlatform.addResponse(
name: consumeMethodName,
value: buildBillingResultMap(expectedBillingResult),
);
final BillingResultWrapper billingResultWrapper =
await iapAndroidPlatformAddition.consumePurchase(
GooglePlayPurchaseDetails.fromPurchase(dummyPurchase));
expect(billingResultWrapper, equals(expectedBillingResult));
});
});
group('queryPastPurchase', () {
group('queryPurchaseDetails', () {
const String queryMethodName = 'BillingClient#queryPurchases(String)';
test('handles error', () async {
const String debugMessage = 'dummy message';
const BillingResponse responseCode = BillingResponse.developerError;
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
stubPlatform
.addResponse(name: queryMethodName, value: <dynamic, dynamic>{
'billingResult': buildBillingResultMap(expectedBillingResult),
'responseCode': const BillingResponseConverter().toJson(responseCode),
'purchasesList': <Map<String, dynamic>>[]
});
final QueryPurchaseDetailsResponse response =
await iapAndroidPlatformAddition.queryPastPurchases();
expect(response.pastPurchases, isEmpty);
expect(response.error, isNotNull);
expect(
response.error!.message, BillingResponse.developerError.toString());
expect(response.error!.source, kIAPSource);
});
test('returns SkuDetailsResponseWrapper', () async {
const String debugMessage = 'dummy message';
const BillingResponse responseCode = BillingResponse.ok;
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
stubPlatform
.addResponse(name: queryMethodName, value: <String, dynamic>{
'billingResult': buildBillingResultMap(expectedBillingResult),
'responseCode': const BillingResponseConverter().toJson(responseCode),
'purchasesList': <Map<String, dynamic>>[
buildPurchaseMap(dummyPurchase),
]
});
// Since queryPastPurchases makes 2 platform method calls (one for each SkuType), the result will contain 2 dummyWrapper instead
// of 1.
final QueryPurchaseDetailsResponse response =
await iapAndroidPlatformAddition.queryPastPurchases();
expect(response.error, isNull);
expect(response.pastPurchases.first.purchaseID, dummyPurchase.orderId);
});
test('should store platform exception in the response', () async {
const String debugMessage = 'dummy message';
const BillingResponse responseCode = BillingResponse.developerError;
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
stubPlatform.addResponse(
name: queryMethodName,
value: <dynamic, dynamic>{
'responseCode':
const BillingResponseConverter().toJson(responseCode),
'billingResult': buildBillingResultMap(expectedBillingResult),
'purchasesList': <Map<String, dynamic>>[]
},
additionalStepBeforeReturn: (dynamic _) {
throw PlatformException(
code: 'error_code',
message: 'error_message',
details: <dynamic, dynamic>{'info': 'error_info'},
);
});
final QueryPurchaseDetailsResponse response =
await iapAndroidPlatformAddition.queryPastPurchases();
expect(response.pastPurchases, isEmpty);
expect(response.error, isNotNull);
expect(response.error!.code, 'error_code');
expect(response.error!.message, 'error_message');
expect(
response.error!.details, <String, dynamic>{'info': 'error_info'});
});
});
});
group('isFeatureSupported', () {
const String isFeatureSupportedMethodName =
'BillingClient#isFeatureSupported(String)';
test('isFeatureSupported returns false', () async {
late Map<Object?, Object?> arguments;
stubPlatform.addResponse(
name: isFeatureSupportedMethodName,
value: false,
additionalStepBeforeReturn: (dynamic value) =>
arguments = value as Map<dynamic, dynamic>,
);
final bool isSupported = await iapAndroidPlatformAddition
.isFeatureSupported(BillingClientFeature.subscriptions);
expect(isSupported, isFalse);
expect(arguments['feature'], equals('subscriptions'));
});
test('isFeatureSupported returns true', () async {
late Map<Object?, Object?> arguments;
stubPlatform.addResponse(
name: isFeatureSupportedMethodName,
value: true,
additionalStepBeforeReturn: (dynamic value) =>
arguments = value as Map<dynamic, dynamic>,
);
final bool isSupported = await iapAndroidPlatformAddition
.isFeatureSupported(BillingClientFeature.subscriptions);
expect(isSupported, isTrue);
expect(arguments['feature'], equals('subscriptions'));
});
});
group('launchPriceChangeConfirmationFlow', () {
const String launchPriceChangeConfirmationFlowMethodName =
'BillingClient#launchPriceChangeConfirmationFlow (Activity, PriceChangeFlowParams, PriceChangeConfirmationListener)';
const String dummySku = 'sku';
const BillingResultWrapper expectedBillingResultPriceChangeConfirmation =
BillingResultWrapper(
responseCode: BillingResponse.ok,
debugMessage: 'dummy message',
);
test('serializes and deserializes data', () async {
stubPlatform.addResponse(
name: launchPriceChangeConfirmationFlowMethodName,
value:
buildBillingResultMap(expectedBillingResultPriceChangeConfirmation),
);
expect(
await iapAndroidPlatformAddition.launchPriceChangeConfirmationFlow(
sku: dummySku,
),
equals(expectedBillingResultPriceChangeConfirmation),
);
});
test('passes sku to launchPriceChangeConfirmationFlow', () async {
stubPlatform.addResponse(
name: launchPriceChangeConfirmationFlowMethodName,
value:
buildBillingResultMap(expectedBillingResultPriceChangeConfirmation),
);
await iapAndroidPlatformAddition.launchPriceChangeConfirmationFlow(
sku: dummySku,
);
final MethodCall call = stubPlatform
.previousCallMatching(launchPriceChangeConfirmationFlowMethodName);
expect(call.arguments, equals(<dynamic, dynamic>{'sku': dummySku}));
});
});
}
/// 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_android/test/in_app_purchase_android_platform_addition_test.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_addition_test.dart",
"repo_id": "plugins",
"token_count": 3376
} | 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 '../errors/in_app_purchase_error.dart';
import 'purchase_status.dart';
import 'purchase_verification_data.dart';
/// Represents the transaction details of a purchase.
class PurchaseDetails {
/// Creates a new PurchaseDetails object with the provided data.
PurchaseDetails({
this.purchaseID,
required this.productID,
required this.verificationData,
required this.transactionDate,
required this.status,
});
/// A unique identifier of the purchase.
final String? purchaseID;
/// The product identifier of the purchase.
final String productID;
/// The verification data of the purchase.
///
/// Use this to verify the purchase. See [PurchaseVerificationData] for
/// details on how to verify purchase use this data. You should never use any
/// purchase data until verified.
final PurchaseVerificationData verificationData;
/// The timestamp of the transaction.
///
/// Milliseconds since epoch.
///
/// The value is `null` if [status] is not [PurchaseStatus.purchased].
final String? transactionDate;
/// The status that this [PurchaseDetails] is currently on.
PurchaseStatus status;
/// The error details when the [status] is [PurchaseStatus.error].
///
/// The value is `null` if [status] is not [PurchaseStatus.error].
IAPError? error;
/// The developer has to call [InAppPurchasePlatform.completePurchase] if the value is `true`
/// and the product has been delivered to the user.
///
/// The initial value is `false`.
/// * See also [InAppPurchasePlatform.completePurchase] for more details on completing purchases.
bool pendingCompletePurchase = false;
}
| plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/purchase_details.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/purchase_details.dart",
"repo_id": "plugins",
"token_count": 486
} | 1,154 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint ios_platform_images.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'ios_platform_images'
s.version = '0.0.1'
s.summary = 'Flutter iOS Platform Images'
s.description = <<-DESC
A Flutter plugin to share images between Flutter and iOS.
Downloaded by pub (not CocoaPods).
DESC
s.homepage = 'https://github.com/flutter/plugins'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/ios_platform_images' }
s.documentation_url = 'https://pub.dev/packages/ios_platform_images'
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.platform = :ios, '11.0'
# Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.swift_version = '5.0'
end
| plugins/packages/ios_platform_images/ios/ios_platform_images.podspec/0 | {
"file_path": "plugins/packages/ios_platform_images/ios/ios_platform_images.podspec",
"repo_id": "plugins",
"token_count": 474
} | 1,155 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="@+id/fingerprint_required"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="24dp"
android:paddingBottom="20dp"
android:gravity="center_vertical"
android:textColor="@color/black_text"
style="@android:style/TextAppearance.DeviceDefault.Medium"
android:textSize="@dimen/huge_text_size"/>
<TextView
android:id="@+id/go_to_setting_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="28dp"
android:textColor="@color/grey_text"
android:textStyle="normal"
android:textSize="@dimen/medium_text_size"/>
</LinearLayout>
| plugins/packages/local_auth/local_auth_android/android/src/main/res/layout/go_to_setting.xml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/layout/go_to_setting.xml",
"repo_id": "plugins",
"token_count": 394
} | 1,156 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 1.0.6
* Removes unused `intl` dependency.
## 1.0.5
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 1.0.4
* Updates references to the obsolete master branch.
* Removes unnecessary imports.
## 1.0.3
* Fixes regression in the default method channel implementation of
`deviceSupportsBiometrics` from federation that would cause it to return true
only if something is enrolled.
## 1.0.2
* Adopts `Object.hash`.
## 1.0.1
* Export externally used types from local_auth_platform_interface.dart directly.
## 1.0.0
* Initial release.
| plugins/packages/local_auth/local_auth_platform_interface/CHANGELOG.md/0 | {
"file_path": "plugins/packages/local_auth/local_auth_platform_interface/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 205
} | 1,157 |
name: path_provider
description: Flutter plugin for getting commonly used locations on host platform file systems, such as the temp and app data directories.
repository: https://github.com/flutter/plugins/tree/main/packages/path_provider/path_provider
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22
version: 2.0.12
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
default_package: path_provider_android
ios:
default_package: path_provider_foundation
linux:
default_package: path_provider_linux
macos:
default_package: path_provider_foundation
windows:
default_package: path_provider_windows
dependencies:
flutter:
sdk: flutter
path_provider_android: ^2.0.6
path_provider_foundation: ^2.1.0
path_provider_linux: ^2.0.1
path_provider_platform_interface: ^2.0.0
path_provider_windows: ^2.0.2
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
plugin_platform_interface: ^2.0.0
test: ^1.16.0
| plugins/packages/path_provider/path_provider/pubspec.yaml/0 | {
"file_path": "plugins/packages/path_provider/path_provider/pubspec.yaml",
"repo_id": "plugins",
"token_count": 482
} | 1,158 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.2.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name
// @dart = 2.12
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
enum StorageDirectory {
root,
music,
podcasts,
ringtones,
alarms,
notifications,
pictures,
movies,
downloads,
dcim,
documents,
}
class _PathProviderApiCodec extends StandardMessageCodec {
const _PathProviderApiCodec();
}
class PathProviderApi {
/// Constructor for [PathProviderApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
PathProviderApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _PathProviderApiCodec();
Future<String?> getTemporaryPath() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getTemporaryPath', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return (replyMap['result'] as String?);
}
}
Future<String?> getApplicationSupportPath() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getApplicationSupportPath', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return (replyMap['result'] as String?);
}
}
Future<String?> getApplicationDocumentsPath() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getApplicationDocumentsPath', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return (replyMap['result'] as String?);
}
}
Future<String?> getExternalStoragePath() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalStoragePath', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else {
return (replyMap['result'] as String?);
}
}
Future<List<String?>> getExternalCachePaths() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalCachePaths', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as List<Object?>?)!.cast<String?>();
}
}
Future<List<String?>> getExternalStoragePaths(
StorageDirectory arg_directory) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalStoragePaths', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = await channel
.send(<Object?>[arg_directory.index]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as List<Object?>?)!.cast<String?>();
}
}
}
| plugins/packages/path_provider/path_provider_android/lib/messages.g.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_android/lib/messages.g.dart",
"repo_id": "plugins",
"token_count": 2711
} | 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.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider_linux/path_provider_linux.dart';
void main() {
runApp(const MyApp());
}
/// Sample app
class MyApp extends StatefulWidget {
/// Default Constructor
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String? _tempDirectory = 'Unknown';
String? _downloadsDirectory = 'Unknown';
String? _appSupportDirectory = 'Unknown';
String? _documentsDirectory = 'Unknown';
final PathProviderLinux _provider = PathProviderLinux();
@override
void initState() {
super.initState();
initDirectories();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initDirectories() async {
String? tempDirectory;
String? downloadsDirectory;
String? appSupportDirectory;
String? documentsDirectory;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
tempDirectory = await _provider.getTemporaryPath();
} on PlatformException {
tempDirectory = 'Failed to get temp directory.';
}
try {
downloadsDirectory = await _provider.getDownloadsPath();
} on PlatformException {
downloadsDirectory = 'Failed to get downloads directory.';
}
try {
documentsDirectory = await _provider.getApplicationDocumentsPath();
} on PlatformException {
documentsDirectory = 'Failed to get documents directory.';
}
try {
appSupportDirectory = await _provider.getApplicationSupportPath();
} on PlatformException {
appSupportDirectory = 'Failed to get documents directory.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) {
return;
}
setState(() {
_tempDirectory = tempDirectory;
_downloadsDirectory = downloadsDirectory;
_appSupportDirectory = appSupportDirectory;
_documentsDirectory = documentsDirectory;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Path Provider Linux example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text('Temp Directory: $_tempDirectory\n'),
Text('Documents Directory: $_documentsDirectory\n'),
Text('Downloads Directory: $_downloadsDirectory\n'),
Text('Application Support Directory: $_appSupportDirectory\n'),
],
),
),
),
);
}
}
| plugins/packages/path_provider/path_provider_linux/example/lib/main.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_linux/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 1013
} | 1,160 |
// Copyright 2013 The Flutter 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.quickactions;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.content.res.Resources;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
class MethodCallHandlerImpl implements MethodChannel.MethodCallHandler {
protected static final String EXTRA_ACTION = "some unique action key";
private static final String CHANNEL_ID = "plugins.flutter.io/quick_actions_android";
private final Context context;
private Activity activity;
MethodCallHandlerImpl(Context context, Activity activity) {
this.context = context;
this.activity = activity;
}
void setActivity(Activity activity) {
this.activity = activity;
}
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
// We already know that this functionality does not work for anything
// lower than API 25 so we chose not to return error. Instead we do nothing.
result.success(null);
return;
}
ShortcutManager shortcutManager =
(ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
switch (call.method) {
case "setShortcutItems":
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
List<Map<String, String>> serializedShortcuts = call.arguments();
List<ShortcutInfo> shortcuts = deserializeShortcuts(serializedShortcuts);
Executor uiThreadExecutor = new UiThreadExecutor();
ThreadPoolExecutor executor =
new ThreadPoolExecutor(
0, 1, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
executor.execute(
() -> {
boolean dynamicShortcutsSet = false;
try {
shortcutManager.setDynamicShortcuts(shortcuts);
dynamicShortcutsSet = true;
} catch (Exception e) {
// Leave dynamicShortcutsSet as false
}
final boolean didSucceed = dynamicShortcutsSet;
// TODO(camsim99): Move re-dispatch below to background thread when Flutter 2.8+ is
// stable.
uiThreadExecutor.execute(
() -> {
if (didSucceed) {
result.success(null);
} else {
result.error(
"quick_action_setshortcutitems_failure",
"Exception thrown when setting dynamic shortcuts",
null);
}
});
});
}
return;
case "clearShortcutItems":
shortcutManager.removeAllDynamicShortcuts();
break;
case "getLaunchAction":
if (activity == null) {
result.error(
"quick_action_getlaunchaction_no_activity",
"There is no activity available when launching action",
null);
return;
}
final Intent intent = activity.getIntent();
final String launchAction = intent.getStringExtra(EXTRA_ACTION);
if (launchAction != null && !launchAction.isEmpty()) {
shortcutManager.reportShortcutUsed(launchAction);
intent.removeExtra(EXTRA_ACTION);
}
result.success(launchAction);
return;
default:
result.notImplemented();
return;
}
result.success(null);
}
@TargetApi(Build.VERSION_CODES.N_MR1)
private List<ShortcutInfo> deserializeShortcuts(List<Map<String, String>> shortcuts) {
final List<ShortcutInfo> shortcutInfos = new ArrayList<>();
for (Map<String, String> shortcut : shortcuts) {
final String icon = shortcut.get("icon");
final String type = shortcut.get("type");
final String title = shortcut.get("localizedTitle");
final ShortcutInfo.Builder shortcutBuilder = new ShortcutInfo.Builder(context, type);
final int resourceId = loadResourceId(context, icon);
final Intent intent = getIntentToOpenMainActivity(type);
if (resourceId > 0) {
shortcutBuilder.setIcon(Icon.createWithResource(context, resourceId));
}
final ShortcutInfo shortcutInfo =
shortcutBuilder.setLongLabel(title).setShortLabel(title).setIntent(intent).build();
shortcutInfos.add(shortcutInfo);
}
return shortcutInfos;
}
private int loadResourceId(Context context, String icon) {
if (icon == null) {
return 0;
}
final String packageName = context.getPackageName();
final Resources res = context.getResources();
final int resourceId = res.getIdentifier(icon, "drawable", packageName);
if (resourceId == 0) {
return res.getIdentifier(icon, "mipmap", packageName);
} else {
return resourceId;
}
}
private Intent getIntentToOpenMainActivity(String type) {
final String packageName = context.getPackageName();
return context
.getPackageManager()
.getLaunchIntentForPackage(packageName)
.setAction(Intent.ACTION_RUN)
.putExtra(EXTRA_ACTION, type)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
}
private static class UiThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable command) {
handler.post(command);
}
}
}
| plugins/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/MethodCallHandlerImpl.java/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/MethodCallHandlerImpl.java",
"repo_id": "plugins",
"token_count": 2482
} | 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.
import UIKit
/// A parser that parses an array of raw shortcut items.
protocol ShortcutItemParser {
/// Parses an array of raw shortcut items into an array of UIApplicationShortcutItems
///
/// - Parameter items an array of raw shortcut items to be parsed.
/// - Returns an array of parsed shortcut items to be set.
///
func parseShortcutItems(_ items: [[String: Any]]) -> [UIApplicationShortcutItem]
}
/// A default implementation of the `ShortcutItemParser` protocol.
final class DefaultShortcutItemParser: ShortcutItemParser {
func parseShortcutItems(_ items: [[String: Any]]) -> [UIApplicationShortcutItem] {
return items.compactMap { deserializeShortcutItem(with: $0) }
}
private func deserializeShortcutItem(with serialized: [String: Any]) -> UIApplicationShortcutItem?
{
guard
let type = serialized["type"] as? String,
let localizedTitle = serialized["localizedTitle"] as? String
else {
return nil
}
let icon = (serialized["icon"] as? String).map {
UIApplicationShortcutIcon(templateImageName: $0)
}
// type and localizedTitle are required.
return UIApplicationShortcutItem(
type: type,
localizedTitle: localizedTitle,
localizedSubtitle: nil,
icon: icon,
userInfo: nil)
}
}
| plugins/packages/quick_actions/quick_actions_ios/ios/Classes/ShortcutItemParser.swift/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/ios/Classes/ShortcutItemParser.swift",
"repo_id": "plugins",
"token_count": 465
} | 1,162 |
name: quick_actions_platform_interface
description: A common platform interface for the quick_actions plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/quick_actions/quick_actions_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+quick_actions%22
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 1.0.3
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.1
| plugins/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml",
"repo_id": "plugins",
"token_count": 262
} | 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.
package io.flutter.plugins.sharedpreferences;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Implementation of the {@link MethodChannel.MethodCallHandler} for the plugin. It is also
* responsible of managing the {@link android.content.SharedPreferences}.
*/
@SuppressWarnings("unchecked")
class MethodCallHandlerImpl implements MethodChannel.MethodCallHandler {
private static final String SHARED_PREFERENCES_NAME = "FlutterSharedPreferences";
// Fun fact: The following is a base64 encoding of the string "This is the prefix for a list."
private static final String LIST_IDENTIFIER = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu";
private static final String BIG_INTEGER_PREFIX = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy";
private static final String DOUBLE_PREFIX = "VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu";
private final android.content.SharedPreferences preferences;
private final ExecutorService executor;
private final Handler handler;
/**
* Constructs a {@link MethodCallHandlerImpl} instance. Creates a {@link
* android.content.SharedPreferences} based on the {@code context}.
*/
MethodCallHandlerImpl(Context context) {
preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
executor =
new ThreadPoolExecutor(0, 1, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
handler = new Handler(Looper.getMainLooper());
}
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
String key = call.argument("key");
try {
switch (call.method) {
case "setBool":
commitAsync(preferences.edit().putBoolean(key, (boolean) call.argument("value")), result);
break;
case "setDouble":
double doubleValue = ((Number) call.argument("value")).doubleValue();
String doubleValueStr = Double.toString(doubleValue);
commitAsync(preferences.edit().putString(key, DOUBLE_PREFIX + doubleValueStr), result);
break;
case "setInt":
Number number = call.argument("value");
if (number instanceof BigInteger) {
BigInteger integerValue = (BigInteger) number;
commitAsync(
preferences
.edit()
.putString(
key, BIG_INTEGER_PREFIX + integerValue.toString(Character.MAX_RADIX)),
result);
} else {
commitAsync(preferences.edit().putLong(key, number.longValue()), result);
}
break;
case "setString":
String value = (String) call.argument("value");
if (value.startsWith(LIST_IDENTIFIER)
|| value.startsWith(BIG_INTEGER_PREFIX)
|| value.startsWith(DOUBLE_PREFIX)) {
result.error(
"StorageError",
"This string cannot be stored as it clashes with special identifier prefixes.",
null);
return;
}
commitAsync(preferences.edit().putString(key, value), result);
break;
case "setStringList":
List<String> list = call.argument("value");
commitAsync(
preferences.edit().putString(key, LIST_IDENTIFIER + encodeList(list)), result);
break;
case "commit":
// We've been committing the whole time.
result.success(true);
break;
case "getAll":
result.success(getAllPrefs());
return;
case "remove":
commitAsync(preferences.edit().remove(key), result);
break;
case "clear":
Set<String> keySet = getAllPrefs().keySet();
SharedPreferences.Editor clearEditor = preferences.edit();
for (String keyToDelete : keySet) {
clearEditor.remove(keyToDelete);
}
commitAsync(clearEditor, result);
break;
default:
result.notImplemented();
break;
}
} catch (IOException e) {
result.error("IOException encountered", call.method, e);
}
}
public void teardown() {
handler.removeCallbacksAndMessages(null);
executor.shutdown();
}
private void commitAsync(
final SharedPreferences.Editor editor, final MethodChannel.Result result) {
executor.execute(
new Runnable() {
@Override
public void run() {
final boolean response = editor.commit();
handler.post(
new Runnable() {
@Override
public void run() {
result.success(response);
}
});
}
});
}
private List<String> decodeList(String encodedList) throws IOException {
ObjectInputStream stream = null;
try {
stream = new ObjectInputStream(new ByteArrayInputStream(Base64.decode(encodedList, 0)));
return (List<String>) stream.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(e);
} finally {
if (stream != null) {
stream.close();
}
}
}
private String encodeList(List<String> list) throws IOException {
ObjectOutputStream stream = null;
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
stream = new ObjectOutputStream(byteStream);
stream.writeObject(list);
stream.flush();
return Base64.encodeToString(byteStream.toByteArray(), 0);
} finally {
if (stream != null) {
stream.close();
}
}
}
// Filter preferences to only those set by the flutter app.
private Map<String, Object> getAllPrefs() throws IOException {
Map<String, ?> allPrefs = preferences.getAll();
Map<String, Object> filteredPrefs = new HashMap<>();
for (String key : allPrefs.keySet()) {
if (key.startsWith("flutter.")) {
Object value = allPrefs.get(key);
if (value instanceof String) {
String stringValue = (String) value;
if (stringValue.startsWith(LIST_IDENTIFIER)) {
value = decodeList(stringValue.substring(LIST_IDENTIFIER.length()));
} else if (stringValue.startsWith(BIG_INTEGER_PREFIX)) {
String encoded = stringValue.substring(BIG_INTEGER_PREFIX.length());
value = new BigInteger(encoded, Character.MAX_RADIX);
} else if (stringValue.startsWith(DOUBLE_PREFIX)) {
String doubleStr = stringValue.substring(DOUBLE_PREFIX.length());
value = Double.valueOf(doubleStr);
}
} else if (value instanceof Set) {
// This only happens for previous usage of setStringSet. The app expects a list.
List<String> listValue = new ArrayList<>((Set) value);
// Let's migrate the value too while we are at it.
boolean success =
preferences
.edit()
.remove(key)
.putString(key, LIST_IDENTIFIER + encodeList(listValue))
.commit();
if (!success) {
// If we are unable to migrate the existing preferences, it means we potentially lost them.
// In this case, an error from getAllPrefs() is appropriate since it will alert the app during plugin initialization.
throw new IOException("Could not migrate set to list");
}
value = listValue;
}
filteredPrefs.put(key, value);
}
}
return filteredPrefs;
}
}
| plugins/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/MethodCallHandlerImpl.java",
"repo_id": "plugins",
"token_count": 3450
} | 1,164 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.0.4
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.0.3
* Fixes newly enabled analyzer options.
* Removes dependency on `meta`.
## 2.0.2
* Add `implements` to pubspec.
## 2.0.1
* Updated installation instructions in README.
* Move tests to `example` directory, so they run as integration_tests with `flutter drive`.
## 2.0.0
* Migrate to null-safety.
## 0.1.2+8
* Update Flutter SDK constraint.
## 0.1.2+7
* Removed Android folder from `shared_preferences_web`.
## 0.1.2+6
* Update lower bound of dart dependency to 2.1.0.
## 0.1.2+5
* Declare API stability and compatibility with `1.0.0` (more details at: https://github.com/flutter/flutter/wiki/Package-migration-to-1.0.0).
## 0.1.2+4
* Make the pedantic dev_dependency explicit.
## 0.1.2+3
* Bump gradle version to avoid bugs with android projects
# 0.1.2+2
* Remove unused onMethodCall method.
# 0.1.2+1
* Add an android/ folder with no-op implementation to workaround https://github.com/flutter/flutter/issues/46898.
# 0.1.2
* Bump lower constraint on Flutter version.
* Add stub podspec file.
# 0.1.1
* Adds a `shared_preferences_macos` package.
# 0.1.0+1
- Remove the deprecated `author:` field from pubspec.yaml
- Require Flutter SDK 1.10.0 or greater.
# 0.1.0
- Initial release.
| plugins/packages/shared_preferences/shared_preferences_web/CHANGELOG.md/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_web/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 519
} | 1,165 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.1.3
* Updates code for stricter lint checks.
## 2.1.2
* Updates code for stricter lint checks.
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
## 2.1.1
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.1.0
* Deprecated `SharedPreferencesWindows.instance` in favor of `SharedPreferencesStorePlatform.instance`.
## 2.0.4
* Removes dependency on `meta`.
## 2.0.3
* Removed obsolete `pluginClass: none` from pubpsec.
* Fixes newly enabled analyzer options.
## 2.0.2
* Updated installation instructions in README.
## 2.0.1
* Add `implements` to pubspec.yaml.
* Add `registerWith` to the Dart main class.
## 2.0.0
* Migrate to null-safety.
## 0.0.2+3
* Remove 'ffi' dependency.
## 0.0.2+2
* Relax 'ffi' version constraint.
## 0.0.2+1
* Update Flutter SDK constraint.
## 0.0.2
* Update integration test examples to use `testWidgets` instead of `test`.
## 0.0.1+3
* Remove unused `test` dependency.
## 0.0.1+2
* Check in windows/ directory for example/
## 0.0.1+1
* Add iOS stub for compatibility with 1.17 and earlier.
## 0.0.1
* Initial release to support shared_preferences on Windows.
| plugins/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_windows/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 474
} | 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:file/memory.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:path_provider_windows/path_provider_windows.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:shared_preferences_windows/shared_preferences_windows.dart';
void main() {
late MemoryFileSystem fileSystem;
late PathProviderWindows pathProvider;
setUp(() {
fileSystem = MemoryFileSystem.test();
pathProvider = FakePathProviderWindows();
});
Future<String> getFilePath() async {
final String? directory = await pathProvider.getApplicationSupportPath();
return path.join(directory!, 'shared_preferences.json');
}
Future<void> writeTestFile(String value) async {
fileSystem.file(await getFilePath())
..createSync(recursive: true)
..writeAsStringSync(value);
}
Future<String> readTestFile() async {
return fileSystem.file(await getFilePath()).readAsStringSync();
}
SharedPreferencesWindows getPreferences() {
final SharedPreferencesWindows prefs = SharedPreferencesWindows();
prefs.fs = fileSystem;
prefs.pathProvider = pathProvider;
return prefs;
}
test('registered instance', () {
SharedPreferencesWindows.registerWith();
expect(SharedPreferencesStorePlatform.instance,
isA<SharedPreferencesWindows>());
});
test('getAll', () async {
await writeTestFile('{"key1": "one", "key2": 2}');
final SharedPreferencesWindows prefs = getPreferences();
final Map<String, Object> values = await prefs.getAll();
expect(values, hasLength(2));
expect(values['key1'], 'one');
expect(values['key2'], 2);
});
test('remove', () async {
await writeTestFile('{"key1":"one","key2":2}');
final SharedPreferencesWindows prefs = getPreferences();
await prefs.remove('key2');
expect(await readTestFile(), '{"key1":"one"}');
});
test('setValue', () async {
await writeTestFile('{}');
final SharedPreferencesWindows prefs = getPreferences();
await prefs.setValue('', 'key1', 'one');
await prefs.setValue('', 'key2', 2);
expect(await readTestFile(), '{"key1":"one","key2":2}');
});
test('clear', () async {
await writeTestFile('{"key1":"one","key2":2}');
final SharedPreferencesWindows prefs = getPreferences();
await prefs.clear();
expect(await readTestFile(), '{}');
});
}
/// Fake implementation of PathProviderWindows that returns hard-coded paths,
/// allowing tests to run on any platform.
///
/// Note that this should only be used with an in-memory filesystem, as the
/// path it returns is a root path that does not actually exist on Windows.
class FakePathProviderWindows extends PathProviderPlatform
implements PathProviderWindows {
@override
late VersionInfoQuerier versionInfoQuerier;
@override
Future<String?> getApplicationSupportPath() async => r'C:\appsupport';
@override
Future<String?> getTemporaryPath() async => null;
@override
Future<String?> getLibraryPath() async => null;
@override
Future<String?> getApplicationDocumentsPath() async => null;
@override
Future<String?> getDownloadsPath() async => null;
@override
Future<String> getPath(String folderID) async => '';
}
| plugins/packages/shared_preferences/shared_preferences_windows/test/shared_preferences_windows_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_windows/test/shared_preferences_windows_test.dart",
"repo_id": "plugins",
"token_count": 1129
} | 1,167 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
const MethodChannel _channel =
MethodChannel('plugins.flutter.io/url_launcher_android');
/// An implementation of [UrlLauncherPlatform] for Android.
class UrlLauncherAndroid extends UrlLauncherPlatform {
/// Registers this class as the default instance of [UrlLauncherPlatform].
static void registerWith() {
UrlLauncherPlatform.instance = UrlLauncherAndroid();
}
@override
final LinkDelegate? linkDelegate = null;
@override
Future<bool> canLaunch(String url) async {
final bool canLaunchSpecificUrl = await _canLaunchUrl(url);
if (!canLaunchSpecificUrl) {
final String scheme = _getUrlScheme(url);
// canLaunch can return false when a custom application is registered to
// handle a web URL, but the caller doesn't have permission to see what
// that handler is. If that happens, try a web URL (with the same scheme
// variant, to be safe) that should not have a custom handler. If that
// returns true, then there is a browser, which means that there is
// at least one handler for the original URL.
if (scheme == 'http' || scheme == 'https') {
return _canLaunchUrl('$scheme://flutter.dev');
}
}
return canLaunchSpecificUrl;
}
Future<bool> _canLaunchUrl(String url) {
return _channel.invokeMethod<bool>(
'canLaunch',
<String, Object>{'url': url},
).then((bool? value) => value ?? false);
}
@override
Future<void> closeWebView() {
return _channel.invokeMethod<void>('closeWebView');
}
@override
Future<bool> launch(
String url, {
required bool useSafariVC,
required bool useWebView,
required bool enableJavaScript,
required bool enableDomStorage,
required bool universalLinksOnly,
required Map<String, String> headers,
String? webOnlyWindowName,
}) {
return _channel.invokeMethod<bool>(
'launch',
<String, Object>{
'url': url,
'useWebView': useWebView,
'enableJavaScript': enableJavaScript,
'enableDomStorage': enableDomStorage,
'universalLinksOnly': universalLinksOnly,
'headers': headers,
},
).then((bool? value) => value ?? false);
}
// Returns the part of [url] up to the first ':', or an empty string if there
// is no ':'. This deliberately does not use [Uri] to extract the scheme
// so that it works on strings that aren't actually valid URLs, since Android
// is very lenient about what it accepts for launching.
String _getUrlScheme(String url) {
final int schemeEnd = url.indexOf(':');
if (schemeEnd == -1) {
return '';
}
return url.substring(0, schemeEnd);
}
}
| plugins/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart",
"repo_id": "plugins",
"token_count": 1014
} | 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 <SafariServices/SafariServices.h>
#import "FLTURLLauncherPlugin.h"
@interface FLTURLLaunchSession : NSObject <SFSafariViewControllerDelegate>
@property(copy, nonatomic) FlutterResult flutterResult;
@property(strong, nonatomic) NSURL *url;
@property(strong, nonatomic) SFSafariViewController *safari;
@property(nonatomic, copy) void (^didFinish)(void);
@end
@implementation FLTURLLaunchSession
- (instancetype)initWithUrl:url withFlutterResult:result {
self = [super init];
if (self) {
self.url = url;
self.flutterResult = result;
self.safari = [[SFSafariViewController alloc] initWithURL:url];
self.safari.delegate = self;
}
return self;
}
- (void)safariViewController:(SFSafariViewController *)controller
didCompleteInitialLoad:(BOOL)didLoadSuccessfully {
if (didLoadSuccessfully) {
self.flutterResult(@YES);
} else {
self.flutterResult([FlutterError
errorWithCode:@"Error"
message:[NSString stringWithFormat:@"Error while launching %@", self.url]
details:nil]);
}
}
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller {
[controller dismissViewControllerAnimated:YES completion:nil];
self.didFinish();
}
- (void)close {
[self safariViewControllerDidFinish:self.safari];
}
@end
@interface FLTURLLauncherPlugin ()
@property(strong, nonatomic) FLTURLLaunchSession *currentSession;
@end
@implementation FLTURLLauncherPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel =
[FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/url_launcher_ios"
binaryMessenger:registrar.messenger];
FLTURLLauncherPlugin *plugin = [[FLTURLLauncherPlugin alloc] init];
[registrar addMethodCallDelegate:plugin channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
NSString *url = call.arguments[@"url"];
if ([@"canLaunch" isEqualToString:call.method]) {
result(@([self canLaunchURL:url]));
} else if ([@"launch" isEqualToString:call.method]) {
NSNumber *useSafariVC = call.arguments[@"useSafariVC"];
if (useSafariVC.boolValue) {
[self launchURLInVC:url result:result];
} else {
[self launchURL:url call:call result:result];
}
} else if ([@"closeWebView" isEqualToString:call.method]) {
[self closeWebViewWithResult:result];
} else {
result(FlutterMethodNotImplemented);
}
}
- (BOOL)canLaunchURL:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
UIApplication *application = [UIApplication sharedApplication];
return [application canOpenURL:url];
}
- (void)launchURL:(NSString *)urlString
call:(FlutterMethodCall *)call
result:(FlutterResult)result {
NSURL *url = [NSURL URLWithString:urlString];
UIApplication *application = [UIApplication sharedApplication];
NSNumber *universalLinksOnly = call.arguments[@"universalLinksOnly"] ?: @0;
NSDictionary *options = @{UIApplicationOpenURLOptionUniversalLinksOnly : universalLinksOnly};
[application openURL:url
options:options
completionHandler:^(BOOL success) {
result(@(success));
}];
}
- (void)launchURLInVC:(NSString *)urlString result:(FlutterResult)result {
NSURL *url = [NSURL URLWithString:urlString];
self.currentSession = [[FLTURLLaunchSession alloc] initWithUrl:url withFlutterResult:result];
__weak typeof(self) weakSelf = self;
self.currentSession.didFinish = ^(void) {
weakSelf.currentSession = nil;
};
[self.topViewController presentViewController:self.currentSession.safari
animated:YES
completion:nil];
}
- (void)closeWebViewWithResult:(FlutterResult)result {
if (self.currentSession != nil) {
[self.currentSession close];
}
result(nil);
}
- (UIViewController *)topViewController {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// TODO(stuartmorgan) Provide a non-deprecated codepath. See
// https://github.com/flutter/flutter/issues/104117
return [self topViewControllerFromViewController:[UIApplication sharedApplication]
.keyWindow.rootViewController];
#pragma clang diagnostic pop
}
/**
* This method recursively iterate through the view hierarchy
* to return the top most view controller.
*
* It supports the following scenarios:
*
* - The view controller is presenting another view.
* - The view controller is a UINavigationController.
* - The view controller is a UITabBarController.
*
* @return The top most view controller.
*/
- (UIViewController *)topViewControllerFromViewController:(UIViewController *)viewController {
if ([viewController isKindOfClass:[UINavigationController class]]) {
UINavigationController *navigationController = (UINavigationController *)viewController;
return [self
topViewControllerFromViewController:[navigationController.viewControllers lastObject]];
}
if ([viewController isKindOfClass:[UITabBarController class]]) {
UITabBarController *tabController = (UITabBarController *)viewController;
return [self topViewControllerFromViewController:tabController.selectedViewController];
}
if (viewController.presentedViewController) {
return [self topViewControllerFromViewController:viewController.presentedViewController];
}
return viewController;
}
@end
| plugins/packages/url_launcher/url_launcher_ios/ios/Classes/FLTURLLauncherPlugin.m/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_ios/ios/Classes/FLTURLLauncherPlugin.m",
"repo_id": "plugins",
"token_count": 1988
} | 1,169 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:url_launcher_linux/url_launcher_linux.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$UrlLauncherLinux', () {
const MethodChannel channel =
MethodChannel('plugins.flutter.io/url_launcher_linux');
final List<MethodCall> log = <MethodCall>[];
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
log.add(methodCall);
// Return null explicitly instead of relying on the implicit null
// returned by the method channel if no return statement is specified.
return null;
});
tearDown(() {
log.clear();
});
test('registers instance', () {
UrlLauncherLinux.registerWith();
expect(UrlLauncherPlatform.instance, isA<UrlLauncherLinux>());
});
test('canLaunch', () async {
final UrlLauncherLinux launcher = UrlLauncherLinux();
await launcher.canLaunch('http://example.com/');
expect(
log,
<Matcher>[
isMethodCall('canLaunch', arguments: <String, Object>{
'url': 'http://example.com/',
})
],
);
});
test('canLaunch should return false if platform returns null', () async {
final UrlLauncherLinux launcher = UrlLauncherLinux();
final bool canLaunch = await launcher.canLaunch('http://example.com/');
expect(canLaunch, false);
});
test('launch', () async {
final UrlLauncherLinux launcher = UrlLauncherLinux();
await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': false,
'headers': <String, String>{},
})
],
);
});
test('launch with headers', () async {
final UrlLauncherLinux launcher = UrlLauncherLinux();
await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{'key': 'value'},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': false,
'headers': <String, String>{'key': 'value'},
})
],
);
});
test('launch universal links only', () async {
final UrlLauncherLinux launcher = UrlLauncherLinux();
await launcher.launch(
'http://example.com/',
useSafariVC: false,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: true,
headers: const <String, String>{},
);
expect(
log,
<Matcher>[
isMethodCall('launch', arguments: <String, Object>{
'url': 'http://example.com/',
'enableJavaScript': false,
'enableDomStorage': false,
'universalLinksOnly': true,
'headers': <String, String>{},
})
],
);
});
test('launch should return false if platform returns null', () async {
final UrlLauncherLinux launcher = UrlLauncherLinux();
final bool launched = await launcher.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
);
expect(launched, false);
});
});
}
/// 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_linux/test/url_launcher_linux_test.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart",
"repo_id": "plugins",
"token_count": 1962
} | 1,170 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.