text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
{ "projects": { "default": "pinball-dev" } }
pinball/.firebaserc/0
{ "file_path": "pinball/.firebaserc", "repo_id": "pinball", "token_count": 26 }
1,079
const functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); const db = admin.firestore(); exports.timedLeaderboardCleanup = functions.firestore .document("leaderboard/{leaderboardEntry}") .onCreate(async (_, __) => { functions.logger.info( "Document created, getting all leaderboard documents" ); const snapshot = await db .collection("leaderboard") .orderBy("score", "desc") .offset(10) .get(); functions.logger.info( `Preparing to delete ${snapshot.docs.length} documents.` ); try { await Promise.all(snapshot.docs.map((doc) => doc.ref.delete())); functions.logger.info("Success"); } catch (error) { functions.logger.error(`Failed to delete documents ${error}`); } });
pinball/functions/index.js/0
{ "file_path": "pinball/functions/index.js", "repo_id": "pinball", "token_count": 301 }
1,080
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Behavior that handles playing a bonus sound effect class BonusNoiseBehavior extends Component { @override Future<void> onLoad() async { await add( FlameBlocListener<GameBloc, GameState>( listenWhen: (previous, current) { return previous.bonusHistory.length != current.bonusHistory.length; }, onNewState: (state) { final bonus = state.bonusHistory.last; final audioPlayer = readProvider<PinballAudioPlayer>(); switch (bonus) { case GameBonus.googleWord: audioPlayer.play(PinballAudio.google); break; case GameBonus.sparkyTurboCharge: audioPlayer.play(PinballAudio.sparky); break; case GameBonus.dinoChomp: audioPlayer.play(PinballAudio.dino); break; case GameBonus.androidSpaceship: audioPlayer.play(PinballAudio.android); break; case GameBonus.dashNest: audioPlayer.play(PinballAudio.dash); break; } }, ), ); } }
pinball/lib/game/behaviors/bonus_noise_behavior.dart/0
{ "file_path": "pinball/lib/game/behaviors/bonus_noise_behavior.dart", "repo_id": "pinball", "token_count": 623 }
1,081
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'; /// Changes arrow lit when a [Ball] is shot into the [SpaceshipRamp]. class RampProgressBehavior extends Component with FlameBlocListenable<SpaceshipRampCubit, SpaceshipRampState> { @override bool listenWhen( SpaceshipRampState previousState, SpaceshipRampState newState, ) { return previousState.hits < newState.hits; } @override void onNewState(SpaceshipRampState state) { final gameBloc = readBloc<GameBloc, GameState>(); final spaceshipCubit = readBloc<SpaceshipRampCubit, SpaceshipRampState>(); final canProgress = !gameBloc.state.isMaxMultiplier || (gameBloc.state.isMaxMultiplier && !state.arrowFullyLit); if (canProgress) { spaceshipCubit.onProgressed(); } if (spaceshipCubit.state.arrowFullyLit && !gameBloc.state.isMaxMultiplier) { spaceshipCubit.onProgressed(); } } }
pinball/lib/game/components/android_acres/behaviors/ramp_progress_behavior.dart/0
{ "file_path": "pinball/lib/game/components/android_acres/behaviors/ramp_progress_behavior.dart", "repo_id": "pinball", "token_count": 409 }
1,082
import 'package:flame/components.dart'; import 'package:pinball/game/behaviors/behaviors.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template bottom_group} /// Grouping of the board's symmetrical bottom [Component]s. /// /// The [BottomGroup] consists of [Flipper]s, [Baseboard]s and [Kicker]s. /// {@endtemplate} class BottomGroup extends Component with ZIndex { /// {@macro bottom_group} BottomGroup() : super( children: [ _BottomGroupSide(side: BoardSide.right), _BottomGroupSide(side: BoardSide.left), ], ) { zIndex = ZIndexes.bottomGroup; } } /// {@template bottom_group_side} /// Group with one side of [BottomGroup]'s symmetric [Component]s. /// /// For example, [Flipper]s are symmetric components. /// {@endtemplate} class _BottomGroupSide extends Component { /// {@macro bottom_group_side} _BottomGroupSide({ required BoardSide side, }) : _side = side; final BoardSide _side; @override Future<void> onLoad() async { final direction = _side.direction; final centerXAdjustment = _side.isLeft ? -0.45 : -6.8; final flipper = Flipper( side: _side, )..initialPosition = Vector2((11.6 * direction) + centerXAdjustment, 43.6); final baseboard = Baseboard(side: _side) ..initialPosition = Vector2( (25.38 * direction) + centerXAdjustment, 28.71, ); final kicker = Kicker( side: _side, children: [ ScoringContactBehavior(points: Points.fiveThousand) ..applyTo(['bouncy_edge']), KickerNoiseBehavior()..applyTo(['bouncy_edge']), ], )..initialPosition = Vector2( (22.44 * direction) + centerXAdjustment, 25.1, ); await addAll([flipper, baseboard, kicker]); } }
pinball/lib/game/components/bottom_group.dart/0
{ "file_path": "pinball/lib/game/components/bottom_group.dart", "repo_id": "pinball", "token_count": 736 }
1,083
export 'multiballs_behavior.dart';
pinball/lib/game/components/multiballs/behaviors/behaviors.dart/0
{ "file_path": "pinball/lib/game/components/multiballs/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 12 }
1,084
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template mobile_controls} /// Widget with the controls used to enable the user initials input on mobile. /// {@endtemplate} class MobileControls extends StatelessWidget { /// {@macro mobile_controls} const MobileControls({ Key? key, required this.game, }) : super(key: key); /// Game instance final PinballGame game; @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context); return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ MobileDpad( onTapUp: () => game.triggerVirtualKeyUp(LogicalKeyboardKey.arrowUp), onTapDown: () => game.triggerVirtualKeyUp( LogicalKeyboardKey.arrowDown, ), onTapLeft: () => game.triggerVirtualKeyUp( LogicalKeyboardKey.arrowLeft, ), onTapRight: () => game.triggerVirtualKeyUp( LogicalKeyboardKey.arrowRight, ), ), PinballButton( text: l10n.enter, onTap: () => game.triggerVirtualKeyUp(LogicalKeyboardKey.enter), ), ], ); } }
pinball/lib/game/view/widgets/mobile_controls.dart/0
{ "file_path": "pinball/lib/game/view/widgets/mobile_controls.dart", "repo_id": "pinball", "token_count": 573 }
1,085
export 'more_information_dialog.dart';
pinball/lib/more_information/more_information.dart/0
{ "file_path": "pinball/lib/more_information/more_information.dart", "repo_id": "pinball", "token_count": 13 }
1,086
library authentication_repository; export 'src/authentication_repository.dart';
pinball/packages/authentication_repository/lib/authentication_repository.dart/0
{ "file_path": "pinball/packages/authentication_repository/lib/authentication_repository.dart", "repo_id": "pinball", "token_count": 24 }
1,087
/// {@template leaderboard_exception} /// Base exception for leaderboard repository failures. /// {@endtemplate} abstract class LeaderboardException implements Exception { /// {@macro leaderboard_exception} const LeaderboardException(this.error, this.stackTrace); /// The error that was caught. final Object error; /// The Stacktrace associated with the [error]. final StackTrace stackTrace; } /// {@template leaderboard_deserialization_exception} /// Exception thrown when leaderboard data cannot be deserialized in the /// expected way. /// {@endtemplate} class LeaderboardDeserializationException extends LeaderboardException { /// {@macro leaderboard_deserialization_exception} const LeaderboardDeserializationException(Object error, StackTrace stackTrace) : super(error, stackTrace); } /// {@template fetch_top_10_leaderboard_exception} /// Exception thrown when failure occurs while fetching top 10 leaderboard. /// {@endtemplate} class FetchTop10LeaderboardException extends LeaderboardException { /// {@macro fetch_top_10_leaderboard_exception} const FetchTop10LeaderboardException(Object error, StackTrace stackTrace) : super(error, stackTrace); } /// {@template fetch_leaderboard_exception} /// Exception thrown when failure occurs while fetching the leaderboard. /// {@endtemplate} class FetchLeaderboardException extends LeaderboardException { /// {@macro fetch_top_10_leaderboard_exception} const FetchLeaderboardException(Object error, StackTrace stackTrace) : super(error, stackTrace); } /// {@template add_leaderboard_entry_exception} /// Exception thrown when failure occurs while adding entry to leaderboard. /// {@endtemplate} class AddLeaderboardEntryException extends LeaderboardException { /// {@macro add_leaderboard_entry_exception} const AddLeaderboardEntryException(Object error, StackTrace stackTrace) : super(error, stackTrace); }
pinball/packages/leaderboard_repository/lib/src/models/exceptions.dart/0
{ "file_path": "pinball/packages/leaderboard_repository/lib/src/models/exceptions.dart", "repo_id": "pinball", "token_count": 532 }
1,088
# pinball_components [![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] [![License: MIT][license_badge]][license_link] Package with the UI game components for the Pinball Game [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/pinball_components/README.md/0
{ "file_path": "pinball/packages/pinball_components/README.md", "repo_id": "pinball", "token_count": 171 }
1,089
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class AndroidBumperBallContactBehavior extends ContactBehavior<AndroidBumper> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; parent.bloc.onBallContacted(); } }
pinball/packages/pinball_components/lib/src/components/android_bumper/behaviors/android_bumper_ball_contact_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/android_bumper/behaviors/android_bumper_ball_contact_behavior.dart", "repo_id": "pinball", "token_count": 141 }
1,090
import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template ball_turbo_charging_behavior} /// Puts the [Ball] in flames and [_impulse]s it. /// {@endtemplate} class BallTurboChargingBehavior extends TimerComponent with ParentIsA<Ball> { /// {@macro ball_turbo_charging_behavior} BallTurboChargingBehavior({ required Vector2 impulse, }) : _impulse = impulse, super(period: 5, removeOnFinish: true); final Vector2 _impulse; @override Future<void> onLoad() async { await super.onLoad(); parent.body.linearVelocity = _impulse; await parent.add(_TurboChargeSpriteAnimationComponent()); } @override void onRemove() { parent .firstChild<_TurboChargeSpriteAnimationComponent>()! .removeFromParent(); super.onRemove(); } } class _TurboChargeSpriteAnimationComponent extends SpriteAnimationComponent with HasGameRef, ZIndex, ParentIsA<Ball> { _TurboChargeSpriteAnimationComponent() : super( anchor: const Anchor(0.53, 0.72), ) { zIndex = ZIndexes.turboChargeFlame; } late final Vector2 _textureSize; @override void update(double dt) { super.update(dt); final direction = -parent.body.linearVelocity.normalized(); angle = math.atan2(direction.x, -direction.y); size = (_textureSize / 45) * parent.body.fixtures.first.shape.radius; } @override Future<void> onLoad() async { await super.onLoad(); final spriteSheet = gameRef.images.fromCache( Assets.images.ball.flameEffect.keyName, ); const amountPerRow = 8; const amountPerColumn = 4; _textureSize = Vector2( spriteSheet.width / amountPerRow, spriteSheet.height / amountPerColumn, ); animation = SpriteAnimation.fromFrameData( spriteSheet, SpriteAnimationData.sequenced( amount: amountPerRow * amountPerColumn, amountPerRow: amountPerRow, stepTime: 1 / 24, textureSize: _textureSize, ), ); } }
pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_turbo_charging_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_turbo_charging_behavior.dart", "repo_id": "pinball", "token_count": 793 }
1,091
import 'dart:async'; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart' hide Timer; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/chrome_dino/behaviors/behaviors.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/chrome_dino_cubit.dart'; /// {@template chrome_dino} /// Dino that swivels back and forth, opening its mouth to eat a [Ball]. /// /// Upon eating a [Ball], the dino rotates and spits the [Ball] out in the /// opposite direction. /// {@endtemplate} class ChromeDino extends BodyComponent with InitialPosition, ContactCallbacks, ZIndex { /// {@macro chrome_dino} ChromeDino({Iterable<Component>? children}) : bloc = ChromeDinoCubit(), super( children: [ _ChromeDinoMouthSprite(), _ChromeDinoHeadSprite(), ChromeDinoMouthOpeningBehavior()..applyTo(['mouth_opening']), ChromeDinoSwivelingBehavior(), ChromeDinoChompingBehavior()..applyTo(['inside_mouth']), ChromeDinoSpittingBehavior(), ...?children, ], renderBody: false, ) { zIndex = ZIndexes.dino; } /// Creates a [ChromeDino] without any children. /// /// This can be used for testing [ChromeDino]'s behaviors in isolation. @visibleForTesting ChromeDino.test({ required this.bloc, }); final ChromeDinoCubit bloc; /// Angle to rotate the dino up or down from the starting horizontal position. static const halfSweepingAngle = 0.1143; @override void onRemove() { bloc.close(); super.onRemove(); } List<FixtureDef> _createFixtureDefs() { const mouthAngle = -(halfSweepingAngle + 0.28); final size = Vector2(6, 6); final topEdge = PolygonShape() ..setAsBox( size.x / 2, 0.1, initialPosition + Vector2(-4, -1.4), mouthAngle, ); final topEdgeFixtureDef = FixtureDef(topEdge, density: 100); final backEdge = PolygonShape() ..setAsBox( 0.1, size.y / 2, initialPosition + Vector2(-1, 0.5), -halfSweepingAngle, ); final backEdgeFixtureDef = FixtureDef(backEdge, density: 100); final bottomEdge = PolygonShape() ..setAsBox( size.x / 2, 0.1, initialPosition + Vector2(-3.3, 4.7), mouthAngle, ); final bottomEdgeFixtureDef = FixtureDef( bottomEdge, density: 100, ); final mouthOpeningEdge = PolygonShape() ..setAsBox( 0.1, size.y / 2.5, initialPosition + Vector2(-6.4, 2.7), -halfSweepingAngle, ); final mouthOpeningEdgeFixtureDef = FixtureDef( mouthOpeningEdge, density: 0.1, userData: 'mouth_opening', ); final insideSensor = PolygonShape() ..setAsBox( 0.2, 0.2, initialPosition + Vector2(-3, 1.5), 0, ); final insideSensorFixtureDef = FixtureDef( insideSensor, isSensor: true, userData: 'inside_mouth', ); return [ topEdgeFixtureDef, backEdgeFixtureDef, bottomEdgeFixtureDef, mouthOpeningEdgeFixtureDef, insideSensorFixtureDef, ]; } @override Body createBody() { final bodyDef = BodyDef( position: initialPosition, type: BodyType.dynamic, gravityScale: Vector2.zero(), ); final body = world.createBody(bodyDef); _createFixtureDefs().forEach(body.createFixture); return body; } } class _ChromeDinoMouthSprite extends SpriteAnimationComponent with HasGameRef { _ChromeDinoMouthSprite() : super( anchor: Anchor(Anchor.center.x + 0.47, Anchor.center.y - 0.29), angle: ChromeDino.halfSweepingAngle, ); @override Future<void> onLoad() async { await super.onLoad(); final image = gameRef.images.fromCache( Assets.images.dino.animatronic.mouth.keyName, ); const amountPerRow = 11; const amountPerColumn = 9; final textureSize = Vector2( image.width / amountPerRow, image.height / amountPerColumn, ); size = textureSize / 10; final data = SpriteAnimationData.sequenced( amount: (amountPerColumn * amountPerRow) - 1, amountPerRow: amountPerRow, stepTime: 1 / 24, textureSize: textureSize, ); animation = SpriteAnimation.fromFrameData(image, data); } } class _ChromeDinoHeadSprite extends SpriteAnimationComponent with HasGameRef { _ChromeDinoHeadSprite() : super( anchor: Anchor(Anchor.center.x + 0.47, Anchor.center.y - 0.29), angle: ChromeDino.halfSweepingAngle, ); @override Future<void> onLoad() async { await super.onLoad(); final image = gameRef.images.fromCache( Assets.images.dino.animatronic.head.keyName, ); const amountPerRow = 11; const amountPerColumn = 9; final textureSize = Vector2( image.width / amountPerRow, image.height / amountPerColumn, ); size = textureSize / 10; final data = SpriteAnimationData.sequenced( amount: (amountPerColumn * amountPerRow) - 1, amountPerRow: amountPerRow, stepTime: 1 / 24, textureSize: textureSize, ); animation = SpriteAnimation.fromFrameData(image, data); } }
pinball/packages/pinball_components/lib/src/components/chrome_dino/chrome_dino.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/chrome_dino/chrome_dino.dart", "repo_id": "pinball", "token_count": 2255 }
1,092
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'; /// Joints the [Flipper] to allow pivoting around one end. class FlipperJointingBehavior extends Component with ParentIsA<Flipper>, HasGameRef { @override Future<void> onLoad() async { await super.onLoad(); final anchor = _FlipperAnchor(flipper: parent); await add(anchor); final jointDef = _FlipperAnchorRevoluteJointDef( flipper: parent, anchor: anchor, ); parent.world.createJoint(RevoluteJoint(jointDef)); } } /// {@template flipper_anchor} /// [JointAnchor] positioned at the end of a [Flipper]. /// /// The end of a [Flipper] depends on its [Flipper.side]. /// {@endtemplate} class _FlipperAnchor extends JointAnchor { /// {@macro flipper_anchor} _FlipperAnchor({ required Flipper flipper, }) { initialPosition = Vector2( (Flipper.size.x * flipper.side.direction) / 2 - (1.65 * flipper.side.direction), -0.15, ); } } /// {@template flipper_anchor_revolute_joint_def} /// Hinges one end of [Flipper] to a [_FlipperAnchor] to achieve a pivoting /// motion. /// {@endtemplate} class _FlipperAnchorRevoluteJointDef extends RevoluteJointDef { /// {@macro flipper_anchor_revolute_joint_def} _FlipperAnchorRevoluteJointDef({ required Flipper flipper, required _FlipperAnchor anchor, }) { initialize( flipper.body, anchor.body, flipper.body.position + anchor.body.position, ); enableLimit = true; upperAngle = 0.611; lowerAngle = -upperAngle; } }
pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_jointing_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_jointing_behavior.dart", "repo_id": "pinball", "token_count": 674 }
1,093
import 'package:flame_forge2d/flame_forge2d.dart'; /// Forces a given [BodyComponent] to position their [body] to an /// [initialPosition]. /// /// Note: If the [initialPosition] is set after the [BodyComponent] has been /// loaded it will have no effect; defaulting to [Vector2.zero]. mixin InitialPosition on BodyComponent { final Vector2 _initialPosition = Vector2.zero(); set initialPosition(Vector2 value) { assert( !isLoaded, 'Cannot set initialPosition after component has already loaded.', ); if (value == initialPosition) return; _initialPosition.setFrom(value); } /// The initial position of the [body]. Vector2 get initialPosition => _initialPosition; @override Future<void> onLoad() async { await super.onLoad(); assert( body.position == initialPosition, 'Body position does not match initialPosition.', ); } }
pinball/packages/pinball_components/lib/src/components/initial_position.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/initial_position.dart", "repo_id": "pinball", "token_count": 282 }
1,094
import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/src/components/multiball/behaviors/behaviors.dart'; import 'package:pinball_components/src/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/multiball_cubit.dart'; /// {@template multiball} /// A [Component] for the multiball lighting decals on the board. /// {@endtemplate} class Multiball extends Component { /// {@macro multiball} Multiball._({ required Vector2 position, double rotation = 0, Iterable<Component>? children, required this.bloc, }) : super( children: [ MultiballBlinkingBehavior(), MultiballSpriteGroupComponent( position: position, litAssetPath: Assets.images.multiball.lit.keyName, dimmedAssetPath: Assets.images.multiball.dimmed.keyName, rotation: rotation, state: bloc.state.lightState, ), ...?children, ], ); /// {@macro multiball} Multiball.a({ Iterable<Component>? children, }) : this._( position: Vector2(-23.3, 7.5), rotation: -27 * math.pi / 180, bloc: MultiballCubit(), children: children, ); /// {@macro multiball} Multiball.b({ Iterable<Component>? children, }) : this._( position: Vector2(-7.65, -6.2), rotation: -2 * math.pi / 180, bloc: MultiballCubit(), children: children, ); /// {@macro multiball} Multiball.c({ Iterable<Component>? children, }) : this._( position: Vector2(-1.1, -9.3), rotation: 6 * math.pi / 180, bloc: MultiballCubit(), children: children, ); /// {@macro multiball} Multiball.d({ Iterable<Component>? children, }) : this._( position: Vector2(14.8, 7), rotation: 27 * math.pi / 180, bloc: MultiballCubit(), children: children, ); /// Creates an [Multiball] without any children. /// /// This can be used for testing [Multiball]'s behaviors in isolation. @visibleForTesting Multiball.test({ required this.bloc, }); final MultiballCubit bloc; @override void onRemove() { bloc.close(); super.onRemove(); } } /// {@template multiball_sprite_group_component} /// A [SpriteGroupComponent] for the multiball over the board. /// {@endtemplate} @visibleForTesting class MultiballSpriteGroupComponent extends SpriteGroupComponent<MultiballLightState> with HasGameRef, ParentIsA<Multiball> { /// {@macro multiball_sprite_group_component} MultiballSpriteGroupComponent({ required Vector2 position, required String litAssetPath, required String dimmedAssetPath, required double rotation, required MultiballLightState state, }) : _litAssetPath = litAssetPath, _dimmedAssetPath = dimmedAssetPath, super( anchor: Anchor.center, position: position, angle: rotation, current: state, ); final String _litAssetPath; final String _dimmedAssetPath; @override Future<void> onLoad() async { await super.onLoad(); parent.bloc.stream.listen((state) => current = state.lightState); final sprites = { MultiballLightState.lit: Sprite( gameRef.images.fromCache(_litAssetPath), ), MultiballLightState.dimmed: Sprite(gameRef.images.fromCache(_dimmedAssetPath)), }; this.sprites = sprites; size = sprites[current]!.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/multiball/multiball.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/multiball/multiball.dart", "repo_id": "pinball", "token_count": 1552 }
1,095
import 'dart:async'; import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/score_component/behaviors/score_component_scaling_behavior.dart'; import 'package:pinball_flame/pinball_flame.dart'; enum Points { fiveThousand, twentyThousand, twoHundredThousand, oneMillion, } /// {@template score_component} /// A [ScoreComponent] that spawns at a given [position] with a moving /// animation. /// {@endtemplate} class ScoreComponent extends SpriteComponent with HasGameRef, ZIndex { /// {@macro score_component} ScoreComponent({ required this.points, required Vector2 position, required EffectController effectController, }) : _effectController = effectController, super( position: position, anchor: Anchor.center, children: [ScoreComponentScalingBehavior()], ) { zIndex = ZIndexes.score; } /// Creates a [ScoreComponent] without any children. /// /// This can be used for testing [ScoreComponent]'s behaviors in isolation. @visibleForTesting ScoreComponent.test({ required this.points, required Vector2 position, required EffectController effectController, }) : _effectController = effectController, super( position: position, anchor: Anchor.center, ); late Points points; late final Effect _effect; final EffectController _effectController; @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache(points.asset), ); this.sprite = sprite; size = sprite.originalSize / 55; await add( _effect = MoveEffect.by( Vector2(0, -5), _effectController, ), ); } @override void update(double dt) { super.update(dt); if (_effect.controller.completed) { removeFromParent(); } } } extension PointsX on Points { int get value { switch (this) { case Points.fiveThousand: return 5000; case Points.twentyThousand: return 20000; case Points.twoHundredThousand: return 200000; case Points.oneMillion: return 1000000; } } } extension on Points { String get asset { switch (this) { case Points.fiveThousand: return Assets.images.score.fiveThousand.keyName; case Points.twentyThousand: return Assets.images.score.twentyThousand.keyName; case Points.twoHundredThousand: return Assets.images.score.twoHundredThousand.keyName; case Points.oneMillion: return Assets.images.score.oneMillion.keyName; } } }
pinball/packages/pinball_components/lib/src/components/score_component/score_component.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/score_component/score_component.dart", "repo_id": "pinball", "token_count": 1034 }
1,096
import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/pinball_components.dart' hide Assets; import 'package:pinball_components/src/components/spaceship_ramp/behavior/behavior.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/spaceship_ramp_cubit.dart'; /// {@template spaceship_ramp} /// Ramp leading into the [AndroidSpaceship]. /// {@endtemplate} class SpaceshipRamp extends Component { /// {@macro spaceship_ramp} SpaceshipRamp({ Iterable<Component>? children, }) : this._( children: children, ); SpaceshipRamp._({ Iterable<Component>? children, }) : super( children: [ FlameBlocProvider<SpaceshipRampCubit, SpaceshipRampState>( create: SpaceshipRampCubit.new, children: [ _SpaceshipRampOpening( outsideLayer: Layer.spaceship, outsidePriority: ZIndexes.ballOnSpaceship, rotation: math.pi, ) ..initialPosition = Vector2(-13.7, -18.6) ..layer = Layer.spaceshipEntranceRamp, _SpaceshipRampBackground(), SpaceshipRampBoardOpening() ..initialPosition = Vector2(3.4, -39.5), _SpaceshipRampForegroundRailing(), SpaceshipRampBase()..initialPosition = Vector2(3.4, -42.5), _SpaceshipRampBackgroundRailingSpriteComponent(), SpaceshipRampArrowSpriteComponent(), ...?children, ], ), ], ); /// Creates a [SpaceshipRamp] without any children. /// /// This can be used for testing [SpaceshipRamp]'s behaviors in isolation. @visibleForTesting SpaceshipRamp.test({ Iterable<Component>? children, }) : super(children: children); } class _SpaceshipRampBackground extends BodyComponent with InitialPosition, Layered, ZIndex { _SpaceshipRampBackground() : super( renderBody: false, children: [ _SpaceshipRampBackgroundRampSpriteComponent(), ], ) { layer = Layer.spaceshipEntranceRamp; zIndex = ZIndexes.spaceshipRamp; } /// Width between walls of the ramp. static const width = 5.0; List<FixtureDef> _createFixtureDefs() { final outerLeftCurveShape = BezierCurveShape( controlPoints: [ Vector2(-30.75, -37.3), Vector2(-32.5, -71.25), Vector2(-14.2, -71.25), ], ); final outerRightCurveShape = BezierCurveShape( controlPoints: [ outerLeftCurveShape.vertices.last, Vector2(2.5, -71.9), Vector2(6.1, -44.9), ], ); final boardOpeningEdgeShape = EdgeShape() ..set( outerRightCurveShape.vertices.last, Vector2(7.3, -41.1), ); return [ FixtureDef(outerRightCurveShape), FixtureDef(outerLeftCurveShape), FixtureDef(boardOpeningEdgeShape), ]; } @override Body createBody() { final bodyDef = BodyDef(position: initialPosition); final body = world.createBody(bodyDef); _createFixtureDefs().forEach(body.createFixture); return body; } } class _SpaceshipRampBackgroundRailingSpriteComponent extends SpriteComponent with HasGameRef, ZIndex { _SpaceshipRampBackgroundRailingSpriteComponent() : super( anchor: Anchor.center, position: Vector2(-11.7, -54.3), ) { zIndex = ZIndexes.spaceshipRampBackgroundRailing; } @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.android.ramp.railingBackground.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } } class _SpaceshipRampBackgroundRampSpriteComponent extends SpriteComponent with HasGameRef { _SpaceshipRampBackgroundRampSpriteComponent() : super( anchor: Anchor.center, position: Vector2(-10.7, -53.6), ); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.android.ramp.main.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } } /// {@template spaceship_ramp_arrow_sprite_component} /// An arrow inside [SpaceshipRamp]. /// /// Lights progressively whenever a [Ball] gets into [SpaceshipRamp]. /// {@endtemplate} @visibleForTesting class SpaceshipRampArrowSpriteComponent extends SpriteGroupComponent<ArrowLightState> with HasGameRef, ZIndex, FlameBlocListenable<SpaceshipRampCubit, SpaceshipRampState> { /// {@macro spaceship_ramp_arrow_sprite_component} SpaceshipRampArrowSpriteComponent() : super( anchor: Anchor.center, position: Vector2(-3.9, -56.5), ) { zIndex = ZIndexes.spaceshipRampArrow; } @override bool listenWhen( SpaceshipRampState previousState, SpaceshipRampState newState, ) { return previousState.lightState != newState.lightState; } @override void onNewState(SpaceshipRampState state) { current = state.lightState; } @override Future<void> onLoad() async { await super.onLoad(); final sprites = <ArrowLightState, Sprite>{}; this.sprites = sprites; for (final spriteState in ArrowLightState.values) { sprites[spriteState] = Sprite( gameRef.images.fromCache(spriteState.path), ); } current = ArrowLightState.inactive; size = sprites[current]!.originalSize / 10; } } extension on ArrowLightState { String get path { switch (this) { case ArrowLightState.inactive: return Assets.images.android.ramp.arrow.inactive.keyName; case ArrowLightState.active1: return Assets.images.android.ramp.arrow.active1.keyName; case ArrowLightState.active2: return Assets.images.android.ramp.arrow.active2.keyName; case ArrowLightState.active3: return Assets.images.android.ramp.arrow.active3.keyName; case ArrowLightState.active4: return Assets.images.android.ramp.arrow.active4.keyName; case ArrowLightState.active5: return Assets.images.android.ramp.arrow.active5.keyName; } } } class SpaceshipRampBoardOpening extends BodyComponent with Layered, ZIndex, InitialPosition { SpaceshipRampBoardOpening() : super( renderBody: false, children: [ _SpaceshipRampBoardOpeningSpriteComponent(), RampBallAscendingContactBehavior()..applyTo(['inside']), LayerContactBehavior(layer: Layer.spaceshipEntranceRamp) ..applyTo(['inside']), LayerContactBehavior( layer: Layer.board, onBegin: false, )..applyTo(['outside']), ZIndexContactBehavior( zIndex: ZIndexes.ballOnBoard, onBegin: false, )..applyTo(['outside']), ZIndexContactBehavior(zIndex: ZIndexes.ballOnSpaceshipRamp) ..applyTo(['middle', 'inside']), ], ) { zIndex = ZIndexes.spaceshipRampBoardOpening; layer = Layer.opening; } /// Creates a [SpaceshipRampBoardOpening] without any children. /// /// This can be used for testing [SpaceshipRampBoardOpening]'s behaviors in /// isolation. @visibleForTesting SpaceshipRampBoardOpening.test(); List<FixtureDef> _createFixtureDefs() { final topEdge = EdgeShape() ..set( Vector2(-3.4, -1.2), Vector2(3.4, -1.6), ); final bottomEdge = EdgeShape() ..set( Vector2(-6.2, 1.5), Vector2(6.2, 1.5), ); final middleCurve = BezierCurveShape( controlPoints: [ topEdge.vertex1, Vector2(0, 2.3), Vector2(7.5, 2.3), topEdge.vertex2, ], ); final leftCurve = BezierCurveShape( controlPoints: [ Vector2(-4.4, -1.2), Vector2(-4.65, 0), bottomEdge.vertex1, ], ); final rightCurve = BezierCurveShape( controlPoints: [ Vector2(4.4, -1.6), Vector2(4.65, 0), bottomEdge.vertex2, ], ); const outsideKey = 'outside'; return [ FixtureDef( topEdge, isSensor: true, userData: 'inside', ), FixtureDef( bottomEdge, isSensor: true, userData: outsideKey, ), FixtureDef( middleCurve, isSensor: true, userData: 'middle', ), FixtureDef( leftCurve, isSensor: true, userData: outsideKey, ), FixtureDef( rightCurve, isSensor: true, userData: outsideKey, ), ]; } @override Body createBody() { final bodyDef = BodyDef(position: initialPosition); final body = world.createBody(bodyDef); _createFixtureDefs().forEach(body.createFixture); return body; } } class _SpaceshipRampBoardOpeningSpriteComponent extends SpriteComponent with HasGameRef { _SpaceshipRampBoardOpeningSpriteComponent() : super(anchor: Anchor.center); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.android.ramp.boardOpening.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } } class _SpaceshipRampForegroundRailing extends BodyComponent with InitialPosition, Layered, ZIndex { _SpaceshipRampForegroundRailing() : super( renderBody: false, children: [_SpaceshipRampForegroundRailingSpriteComponent()], ) { layer = Layer.spaceshipEntranceRamp; zIndex = ZIndexes.spaceshipRampForegroundRailing; } List<FixtureDef> _createFixtureDefs() { final innerLeftCurveShape = BezierCurveShape( controlPoints: [ Vector2(-24.5, -38), Vector2(-26.3, -64), Vector2(-13.8, -64.5), ], ); final innerRightCurveShape = BezierCurveShape( controlPoints: [ innerLeftCurveShape.vertices.last, Vector2(-2.5, -66.2), Vector2(0, -44.5), ], ); final boardOpeningEdgeShape = EdgeShape() ..set( innerRightCurveShape.vertices.last, Vector2(-0.85, -40.8), ); return [ FixtureDef(innerLeftCurveShape), FixtureDef(innerRightCurveShape), FixtureDef(boardOpeningEdgeShape), ]; } @override Body createBody() { final bodyDef = BodyDef(position: initialPosition); final body = world.createBody(bodyDef); _createFixtureDefs().forEach(body.createFixture); return body; } } class _SpaceshipRampForegroundRailingSpriteComponent extends SpriteComponent with HasGameRef { _SpaceshipRampForegroundRailingSpriteComponent() : super( anchor: Anchor.center, position: Vector2(-12.3, -52.5), ); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.android.ramp.railingForeground.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } } @visibleForTesting class SpaceshipRampBase extends BodyComponent with InitialPosition, ContactCallbacks { SpaceshipRampBase() : super(renderBody: false); @override void preSolve(Object other, Contact contact, Manifold oldManifold) { super.preSolve(other, contact, oldManifold); if (other is! Layered) return; // Although, the Layer should already be taking care of the contact // filtering, this is to ensure the ball doesn't collide with the ramp base // when the filtering is calculated on different time steps. contact.setEnabled(other.layer == Layer.board); } @override Body createBody() { final shape = BezierCurveShape( controlPoints: [ Vector2(-4.25, 1.75), Vector2(-2, -2.1), Vector2(2, -2.3), Vector2(4.1, 1.5), ], ); final bodyDef = BodyDef(position: initialPosition, userData: this); return world.createBody(bodyDef)..createFixtureFromShape(shape); } } /// {@template spaceship_ramp_opening} /// [LayerSensor] with [Layer.spaceshipEntranceRamp] to filter [Ball] collisions /// inside [_SpaceshipRampBackground]. /// {@endtemplate} class _SpaceshipRampOpening extends LayerSensor { /// {@macro spaceship_ramp_opening} _SpaceshipRampOpening({ Layer? outsideLayer, int? outsidePriority, required double rotation, }) : _rotation = rotation, super( insideLayer: Layer.spaceshipEntranceRamp, outsideLayer: outsideLayer, orientation: LayerEntranceOrientation.down, insideZIndex: ZIndexes.ballOnSpaceshipRamp, outsideZIndex: outsidePriority, ); final double _rotation; static final Vector2 _size = Vector2(_SpaceshipRampBackground.width / 3, .1); @override Shape get shape { return PolygonShape() ..setAsBox( _size.x, _size.y, initialPosition, _rotation, ); } }
pinball/packages/pinball_components/lib/src/components/spaceship_ramp/spaceship_ramp.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/spaceship_ramp/spaceship_ramp.dart", "repo_id": "pinball", "token_count": 5756 }
1,097
export 'components/components.dart'; export 'extensions/extensions.dart';
pinball/packages/pinball_components/lib/src/pinball_components.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/pinball_components.dart", "repo_id": "pinball", "token_count": 24 }
1,098
import 'dart:async'; import 'package:flame/input.dart'; import 'package:flame_bloc/flame_bloc.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 AndroidSpaceshipGame extends BallGame { AndroidSpaceshipGame() : super( ballPriority: ZIndexes.ballOnSpaceship, ballLayer: Layer.spaceship, imagesFileNames: [ Assets.images.android.spaceship.saucer.keyName, Assets.images.android.spaceship.animatronic.keyName, Assets.images.android.spaceship.lightBeam.keyName, ], ); static const description = ''' Shows how the AndroidSpaceship and AndroidAnimatronic are 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()); await add( FlameBlocProvider<AndroidSpaceshipCubit, AndroidSpaceshipState>( create: AndroidSpaceshipCubit.new, children: [ AndroidSpaceship(position: Vector2.zero()), AndroidAnimatronic(), ], ), ); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_spaceship_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_spaceship_game.dart", "repo_id": "pinball", "token_count": 533 }
1,099
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class ChromeDinoGame extends BallGame { ChromeDinoGame() : super( imagesFileNames: [ Assets.images.dino.animatronic.mouth.keyName, Assets.images.dino.animatronic.head.keyName, ], ); static const description = ''' Shows how ChromeDino 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()); await add(ChromeDino()); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/chrome_dino_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/chrome_dino_game.dart", "repo_id": "pinball", "token_count": 304 }
1,100
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/launch_ramp/launch_ramp_game.dart'; void addLaunchRampStories(Dashbook dashbook) { dashbook.storiesOf('LaunchRamp').addGame( title: 'Traced', description: LaunchRampGame.description, gameBuilder: (_) => LaunchRampGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/launch_ramp/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/launch_ramp/stories.dart", "repo_id": "pinball", "token_count": 144 }
1,101
name: sandbox description: A sanbox application where components are showcased and developed in an isolated way version: 1.0.0+1 publish_to: none environment: sdk: ">=2.16.0 <3.0.0" dependencies: dashbook: ^0.1.7 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 pinball_components: path: ../ pinball_flame: path: ../../pinball_flame pinball_theme: path: ../../pinball_theme dev_dependencies: flutter_test: sdk: flutter very_good_analysis: ^2.4.0 flutter: uses-material-design: true
pinball/packages/pinball_components/sandbox/pubspec.yaml/0
{ "file_path": "pinball/packages/pinball_components/sandbox/pubspec.yaml", "repo_id": "pinball", "token_count": 308 }
1,102
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.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_flame/pinball_flame.dart'; import '../../../helpers/helpers.dart'; class _MockAndroidSpaceshipCubit extends Mock implements AndroidSpaceshipCubit { } void main() { group('AndroidSpaceship', () { final assets = [ Assets.images.android.spaceship.saucer.keyName, Assets.images.android.spaceship.lightBeam.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); late AndroidSpaceshipCubit bloc; setUp(() { bloc = _MockAndroidSpaceshipCubit(); }); flameTester.test('loads correctly', (game) async { final component = FlameBlocProvider<AndroidSpaceshipCubit, AndroidSpaceshipState>.value( value: bloc, children: [AndroidSpaceship(position: Vector2.zero())], ); await game.ensureAdd(component); expect(game.contains(component), isTrue); }); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); final canvas = ZCanvasComponent( children: [ FlameBlocProvider<AndroidSpaceshipCubit, AndroidSpaceshipState>.value( value: bloc, children: [AndroidSpaceship(position: Vector2.zero())], ), ], ); await game.ensureAdd(canvas); game.camera.followVector2(Vector2.zero()); await game.ready(); await tester.pump(); }, verify: (game, tester) async { const goldenFilePath = '../golden/android_spaceship/'; final animationDuration = game .descendants() .whereType<SpriteAnimationComponent>() .single .animation! .totalDuration(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldenFilePath}start.png'), ); game.update(animationDuration * 0.5); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldenFilePath}middle.png'), ); game.update(animationDuration * 0.5); await tester.pump(); await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldenFilePath}end.png'), ); }, ); }); }
pinball/packages/pinball_components/test/src/components/android_spaceship/android_spaceship_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/android_spaceship/android_spaceship_test.dart", "repo_id": "pinball", "token_count": 1158 }
1,103
import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group( 'BoardSide', () { test('has two values', () { expect(BoardSide.values.length, equals(2)); }); }, ); group('BoardSideX', () { test('isLeft is correct', () { const side = BoardSide.left; expect(side.isLeft, isTrue); expect(side.isRight, isFalse); }); test('isRight is correct', () { const side = BoardSide.right; expect(side.isLeft, isFalse); expect(side.isRight, isTrue); }); test('direction is correct', () { const side = BoardSide.left; expect(side.direction, equals(-1)); const side2 = BoardSide.right; expect(side2.direction, equals(1)); }); }); }
pinball/packages/pinball_components/test/src/components/board_side_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/board_side_test.dart", "repo_id": "pinball", "token_count": 334 }
1,104
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group( 'DashBumperCubit', () { blocTest<DashBumpersCubit, DashBumpersState>( 'onBallContacted emits active for contacted bumper', build: DashBumpersCubit.new, act: (bloc) => bloc.onBallContacted(DashBumperId.main), expect: () => [ const DashBumpersState( bumperSpriteStates: { DashBumperId.main: DashBumperSpriteState.active, DashBumperId.a: DashBumperSpriteState.inactive, DashBumperId.b: DashBumperSpriteState.inactive, }, ), ], ); blocTest<DashBumpersCubit, DashBumpersState>( 'onReset emits initial state', build: DashBumpersCubit.new, seed: () => DashBumpersState( bumperSpriteStates: { for (var id in DashBumperId.values) id: DashBumperSpriteState.active }, ), act: (bloc) => bloc.onReset(), expect: () => [DashBumpersState.initial()], ); }, ); }
pinball/packages/pinball_components/test/src/components/dash_nest_bumper/cubit/dash_bumpers_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/dash_nest_bumper/cubit/dash_bumpers_cubit_test.dart", "repo_id": "pinball", "token_count": 557 }
1,105
// 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_components/pinball_components.dart'; class _TestGame extends Forge2DGame { Future<void> pump( GoogleWordAnimatingBehavior child, { required GoogleWordCubit bloc, }) async { await ensureAdd( FlameBlocProvider<GoogleWordCubit, GoogleWordState>.value( value: bloc, children: [child], ), ); } } class _MockGoogleWordCubit extends Mock implements GoogleWordCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('GoogleWordAnimatingBehavior', () { flameTester.testGameWidget( 'calls switched after timer period reached', setUp: (game, tester) async { final behavior = GoogleWordAnimatingBehavior(); final bloc = _MockGoogleWordCubit(); await game.pump(behavior, bloc: bloc); game.update(behavior.timer.limit); verify(bloc.switched).called(1); }, ); flameTester.testGameWidget( 'calls onReset and removes itself ' 'after all blinks complete', setUp: (game, tester) async { final behavior = GoogleWordAnimatingBehavior(); final bloc = _MockGoogleWordCubit(); await game.pump(behavior, bloc: bloc); for (var i = 0; i <= 14; i++) { game.update(behavior.timer.limit); } await game.ready(); verify(bloc.onReset).called(1); expect( game.descendants().whereType<GoogleWordAnimatingBehavior>().isEmpty, isTrue, ); }, ); }); }
pinball/packages/pinball_components/test/src/components/google_word/behaviors/google_word_animating_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/google_word/behaviors/google_word_animating_behavior_test.dart", "repo_id": "pinball", "token_count": 739 }
1,106
// 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/multiball/behaviors/behaviors.dart'; import '../../../helpers/helpers.dart'; class _MockMultiballCubit extends Mock implements MultiballCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.multiball.lit.keyName, Assets.images.multiball.dimmed.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); group('Multiball', () { group('loads correctly', () { flameTester.test('"a"', (game) async { final multiball = Multiball.a(); await game.ensureAdd(multiball); expect(game.contains(multiball), isTrue); }); flameTester.test('"b"', (game) async { final multiball = Multiball.b(); await game.ensureAdd(multiball); expect(game.contains(multiball), isTrue); }); flameTester.test('"c"', (game) async { final multiball = Multiball.c(); await game.ensureAdd(multiball); expect(game.contains(multiball), isTrue); }); flameTester.test('"d"', (game) async { final multiball = Multiball.d(); await game.ensureAdd(multiball); expect(game.contains(multiball), isTrue); }); }); flameTester.test( 'closes bloc when removed', (game) async { final bloc = _MockMultiballCubit(); whenListen( bloc, const Stream<MultiballLightState>.empty(), initialState: MultiballLightState.dimmed, ); when(bloc.close).thenAnswer((_) async {}); final multiball = Multiball.test(bloc: bloc); await game.ensureAdd(multiball); game.remove(multiball); await game.ready(); verify(bloc.close).called(1); }, ); group('adds', () { flameTester.test('new children', (game) async { final component = Component(); final multiball = Multiball.a( children: [component], ); await game.ensureAdd(multiball); expect(multiball.children, contains(component)); }); flameTester.test('a MultiballBlinkingBehavior', (game) async { final multiball = Multiball.a(); await game.ensureAdd(multiball); expect( multiball.children.whereType<MultiballBlinkingBehavior>().single, isNotNull, ); }); }); }); }
pinball/packages/pinball_components/test/src/components/multiball/multiball_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/multiball/multiball_test.dart", "repo_id": "pinball", "token_count": 1174 }
1,107
// ignore_for_file: cascade_invocations import 'package:bloc_test/bloc_test.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/skill_shot/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockBall extends Mock implements Ball {} class _MockContact extends Mock implements Contact {} class _MockSkillShotCubit extends Mock implements SkillShotCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'SkillShotBallContactBehavior', () { test('can be instantiated', () { expect( SkillShotBallContactBehavior(), isA<SkillShotBallContactBehavior>(), ); }); flameTester.testGameWidget( 'beginContact animates pin and calls onBallContacted ' 'when contacts with a ball', setUp: (game, tester) async { await game.images.load(Assets.images.skillShot.pin.keyName); final behavior = SkillShotBallContactBehavior(); final bloc = _MockSkillShotCubit(); whenListen( bloc, const Stream<SkillShotState>.empty(), initialState: const SkillShotState.initial(), ); final skillShot = SkillShot.test(bloc: bloc); await skillShot.addAll([behavior, PinSpriteAnimationComponent()]); await game.ensureAdd(skillShot); behavior.beginContact(_MockBall(), _MockContact()); await tester.pump(); expect( skillShot.firstChild<PinSpriteAnimationComponent>()!.playing, isTrue, ); verify(skillShot.bloc.onBallContacted).called(1); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/skill_shot/behaviors/skill_shot_ball_contact_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/skill_shot/behaviors/skill_shot_ball_contact_behavior_test.dart", "repo_id": "pinball", "token_count": 800 }
1,108
// ignore_for_file: cascade_invocations import 'package:bloc_test/bloc_test.dart'; 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_components/pinball_components.dart'; import 'package:pinball_components/src/components/sparky_computer/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockSparkyComputerCubit extends Mock implements SparkyComputerCubit {} class _MockBall extends Mock implements Ball {} class _MockContact extends Mock implements Contact {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'SparkyComputerSensorBallContactBehavior', () { test('can be instantiated', () { expect( SparkyComputerSensorBallContactBehavior(), isA<SparkyComputerSensorBallContactBehavior>(), ); }); group('beginContact', () { flameTester.test( 'stops a ball', (game) async { final behavior = SparkyComputerSensorBallContactBehavior(); final bloc = _MockSparkyComputerCubit(); whenListen( bloc, const Stream<SparkyComputerState>.empty(), initialState: SparkyComputerState.withoutBall, ); final sparkyComputer = SparkyComputer.test( bloc: bloc, ); await sparkyComputer.add(behavior); await game.ensureAdd(sparkyComputer); final ball = _MockBall(); await behavior.beginContact(ball, _MockContact()); verify(ball.stop).called(1); }, ); flameTester.test( 'emits onBallEntered when contacts with a ball', (game) async { final behavior = SparkyComputerSensorBallContactBehavior(); final bloc = _MockSparkyComputerCubit(); whenListen( bloc, const Stream<SparkyComputerState>.empty(), initialState: SparkyComputerState.withoutBall, ); final sparkyComputer = SparkyComputer.test( bloc: bloc, ); await sparkyComputer.add(behavior); await game.ensureAdd(sparkyComputer); await behavior.beginContact(_MockBall(), _MockContact()); verify(sparkyComputer.bloc.onBallEntered).called(1); }, ); flameTester.test( 'adds TimerComponent when contacts with a ball', (game) async { final behavior = SparkyComputerSensorBallContactBehavior(); final bloc = _MockSparkyComputerCubit(); whenListen( bloc, const Stream<SparkyComputerState>.empty(), initialState: SparkyComputerState.withoutBall, ); final sparkyComputer = SparkyComputer.test( bloc: bloc, ); await sparkyComputer.add(behavior); await game.ensureAdd(sparkyComputer); await behavior.beginContact(_MockBall(), _MockContact()); await game.ready(); expect( sparkyComputer.firstChild<TimerComponent>(), isA<TimerComponent>(), ); }, ); flameTester.test( 'TimerComponent resumes ball and calls onBallTurboCharged onTick', (game) async { final behavior = SparkyComputerSensorBallContactBehavior(); final bloc = _MockSparkyComputerCubit(); whenListen( bloc, const Stream<SparkyComputerState>.empty(), initialState: SparkyComputerState.withoutBall, ); final sparkyComputer = SparkyComputer.test( bloc: bloc, ); await sparkyComputer.add(behavior); await game.ensureAdd(sparkyComputer); final ball = _MockBall(); await behavior.beginContact(ball, _MockContact()); await game.ready(); game.update( sparkyComputer.firstChild<TimerComponent>()!.timer.limit, ); await game.ready(); verify(ball.resume).called(1); verify(sparkyComputer.bloc.onBallTurboCharged).called(1); }, ); }); }, ); }
pinball/packages/pinball_components/test/src/components/sparky_computer/behaviors/sparky_computer_sensor_ball_contact_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/sparky_computer/behaviors/sparky_computer_sensor_ball_contact_behavior_test.dart", "repo_id": "pinball", "token_count": 2093 }
1,109
import 'package:bloc/bloc.dart'; import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; /// {@template flame_provider} /// Provider-style component, similar to Provider in Flutter, but used to /// retrieve [Component] objects previously provided /// {@endtemplate} class FlameProvider<T> extends Component { //// {@macro flame_provider} FlameProvider.value( this.provider, { Iterable<Component>? children, }) : super(children: children); /// The object that needs to be provided final T provider; } //// {@template multi_flame_provider} /// MultiProvider-style component, similar to MultiProvider in Flutter, /// but used to retrieve more than one [Component] object previously provided /// {@endtemplate} class MultiFlameProvider extends Component { /// {@macro multi_flame_provider} MultiFlameProvider({ required List<FlameProvider<dynamic>> providers, Iterable<Component>? children, }) : _providers = providers, _initialChildren = children, assert(providers.isNotEmpty, 'At least one provider must be given') { _addProviders(); } final List<FlameProvider<dynamic>> _providers; final Iterable<Component>? _initialChildren; FlameProvider<dynamic>? _lastProvider; Future<void> _addProviders() async { final _list = [..._providers]; var current = _list.removeAt(0); while (_list.isNotEmpty) { final provider = _list.removeAt(0); await current.add(provider); current = provider; } await add(_providers.first); _lastProvider = current; _initialChildren?.forEach(add); } @override Future<void> add(Component component) async { if (_lastProvider == null) { await super.add(component); } await _lastProvider?.add(component); } } /// Extended API on [Component] extension ReadFlameProvider on Component { /// Retrieve an object of type [T] that was previously provided T readProvider<T>() { final providers = ancestors().whereType<FlameProvider<T>>(); assert( providers.isNotEmpty, 'No FlameProvider<$T> available on the component tree', ); return providers.first.provider; } /// Retrieve a bloc [B] with state [S] previously provided B readBloc<B extends BlocBase<S>, S>() { final providers = ancestors().whereType<FlameBlocProvider<B, S>>(); assert( providers.isNotEmpty, 'No FlameBlocProvider<$B, $S> available on the component tree', ); return providers.first.bloc; } }
pinball/packages/pinball_flame/lib/src/flame_provider.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/flame_provider.dart", "repo_id": "pinball", "token_count": 837 }
1,110
import 'dart:typed_data'; import 'dart:ui'; import 'package:flutter/material.dart' hide Image; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_flame/src/canvas/canvas_wrapper.dart'; class _MockCanvas extends Mock implements Canvas {} class _MockImage extends Mock implements Image {} class _MockPicture extends Mock implements Picture {} class _MockParagraph extends Mock implements Paragraph {} class _MockVertices extends Mock implements Vertices {} void main() { group('CanvasWrapper', () { group('CanvasWrapper', () { late Canvas canvas; late Path path; late RRect rRect; late Rect rect; late Paint paint; late Image atlas; late BlendMode blendMode; late Color color; late Offset offset; late Float64List float64list; late Float32List float32list; late Int32List int32list; late Picture picture; late Paragraph paragraph; late Vertices vertices; setUp(() { canvas = _MockCanvas(); path = Path(); rRect = RRect.zero; rect = Rect.zero; paint = Paint(); atlas = _MockImage(); blendMode = BlendMode.clear; color = Colors.black; offset = Offset.zero; float64list = Float64List(1); float32list = Float32List(1); int32list = Int32List(1); picture = _MockPicture(); paragraph = _MockParagraph(); vertices = _MockVertices(); }); test("clipPath calls Canvas's clipPath", () { CanvasWrapper() ..canvas = canvas ..clipPath(path, doAntiAlias: false); verify( () => canvas.clipPath(path, doAntiAlias: false), ).called(1); }); test("clipRRect calls Canvas's clipRRect", () { CanvasWrapper() ..canvas = canvas ..clipRRect(rRect, doAntiAlias: false); verify( () => canvas.clipRRect(rRect, doAntiAlias: false), ).called(1); }); test("clipRect calls Canvas's clipRect", () { CanvasWrapper() ..canvas = canvas ..clipRect(rect, doAntiAlias: false); verify( () => canvas.clipRect(rect, doAntiAlias: false), ).called(1); }); test("drawArc calls Canvas's drawArc", () { CanvasWrapper() ..canvas = canvas ..drawArc(rect, 0, 1, false, paint); verify( () => canvas.drawArc(rect, 0, 1, false, paint), ).called(1); }); test("drawAtlas calls Canvas's drawAtlas", () { CanvasWrapper() ..canvas = canvas ..drawAtlas(atlas, [], [], [], blendMode, rect, paint); verify( () => canvas.drawAtlas(atlas, [], [], [], blendMode, rect, paint), ).called(1); }); test("drawCircle calls Canvas's drawCircle", () { CanvasWrapper() ..canvas = canvas ..drawCircle(offset, 0, paint); verify( () => canvas.drawCircle(offset, 0, paint), ).called(1); }); test("drawColor calls Canvas's drawColor", () { CanvasWrapper() ..canvas = canvas ..drawColor(color, blendMode); verify( () => canvas.drawColor(color, blendMode), ).called(1); }); test("drawDRRect calls Canvas's drawDRRect", () { CanvasWrapper() ..canvas = canvas ..drawDRRect(rRect, rRect, paint); verify( () => canvas.drawDRRect(rRect, rRect, paint), ).called(1); }); test("drawImage calls Canvas's drawImage", () { CanvasWrapper() ..canvas = canvas ..drawImage(atlas, offset, paint); verify( () => canvas.drawImage(atlas, offset, paint), ).called(1); }); test("drawImageNine calls Canvas's drawImageNine", () { CanvasWrapper() ..canvas = canvas ..drawImageNine(atlas, rect, rect, paint); verify( () => canvas.drawImageNine(atlas, rect, rect, paint), ).called(1); }); test("drawImageRect calls Canvas's drawImageRect", () { CanvasWrapper() ..canvas = canvas ..drawImageRect(atlas, rect, rect, paint); verify( () => canvas.drawImageRect(atlas, rect, rect, paint), ).called(1); }); test("drawLine calls Canvas's drawLine", () { CanvasWrapper() ..canvas = canvas ..drawLine(offset, offset, paint); verify( () => canvas.drawLine(offset, offset, paint), ).called(1); }); test("drawOval calls Canvas's drawOval", () { CanvasWrapper() ..canvas = canvas ..drawOval(rect, paint); verify( () => canvas.drawOval(rect, paint), ).called(1); }); test("drawPaint calls Canvas's drawPaint", () { CanvasWrapper() ..canvas = canvas ..drawPaint(paint); verify( () => canvas.drawPaint(paint), ).called(1); }); test("drawParagraph calls Canvas's drawParagraph", () { CanvasWrapper() ..canvas = canvas ..drawParagraph(paragraph, offset); verify( () => canvas.drawParagraph(paragraph, offset), ).called(1); }); test("drawPath calls Canvas's drawPath", () { CanvasWrapper() ..canvas = canvas ..drawPath(path, paint); verify( () => canvas.drawPath(path, paint), ).called(1); }); test("drawPicture calls Canvas's drawPicture", () { CanvasWrapper() ..canvas = canvas ..drawPicture(picture); verify( () => canvas.drawPicture(picture), ).called(1); }); test("drawPoints calls Canvas's drawPoints", () { CanvasWrapper() ..canvas = canvas ..drawPoints(PointMode.points, [offset], paint); verify( () => canvas.drawPoints(PointMode.points, [offset], paint), ).called(1); }); test("drawRRect calls Canvas's drawRRect", () { CanvasWrapper() ..canvas = canvas ..drawRRect(rRect, paint); verify( () => canvas.drawRRect(rRect, paint), ).called(1); }); test("drawRawAtlas calls Canvas's drawRawAtlas", () { CanvasWrapper() ..canvas = canvas ..drawRawAtlas( atlas, float32list, float32list, int32list, BlendMode.clear, rect, paint, ); verify( () => canvas.drawRawAtlas( atlas, float32list, float32list, int32list, BlendMode.clear, rect, paint, ), ).called(1); }); test("drawRawPoints calls Canvas's drawRawPoints", () { CanvasWrapper() ..canvas = canvas ..drawRawPoints(PointMode.points, float32list, paint); verify( () => canvas.drawRawPoints(PointMode.points, float32list, paint), ).called(1); }); test("drawRect calls Canvas's drawRect", () { CanvasWrapper() ..canvas = canvas ..drawRect(rect, paint); verify( () => canvas.drawRect(rect, paint), ).called(1); }); test("drawShadow calls Canvas's drawShadow", () { CanvasWrapper() ..canvas = canvas ..drawShadow(path, color, 0, false); verify( () => canvas.drawShadow(path, color, 0, false), ).called(1); }); test("drawVertices calls Canvas's drawVertices", () { CanvasWrapper() ..canvas = canvas ..drawVertices(vertices, blendMode, paint); verify( () => canvas.drawVertices(vertices, blendMode, paint), ).called(1); }); test("getSaveCount calls Canvas's getSaveCount", () { final canvasWrapper = CanvasWrapper()..canvas = canvas; when(() => canvas.getSaveCount()).thenReturn(1); canvasWrapper.getSaveCount(); verify(() => canvas.getSaveCount()).called(1); expect(canvasWrapper.getSaveCount(), 1); }); test("restore calls Canvas's restore", () { CanvasWrapper() ..canvas = canvas ..restore(); verify(() => canvas.restore()).called(1); }); test("rotate calls Canvas's rotate", () { CanvasWrapper() ..canvas = canvas ..rotate(0); verify(() => canvas.rotate(0)).called(1); }); test("save calls Canvas's save", () { CanvasWrapper() ..canvas = canvas ..save(); verify(() => canvas.save()).called(1); }); test("saveLayer calls Canvas's saveLayer", () { CanvasWrapper() ..canvas = canvas ..saveLayer(rect, paint); verify(() => canvas.saveLayer(rect, paint)).called(1); }); test("scale calls Canvas's scale", () { CanvasWrapper() ..canvas = canvas ..scale(0, 0); verify(() => canvas.scale(0, 0)).called(1); }); test("skew calls Canvas's skew", () { CanvasWrapper() ..canvas = canvas ..skew(0, 0); verify(() => canvas.skew(0, 0)).called(1); }); test("transform calls Canvas's transform", () { CanvasWrapper() ..canvas = canvas ..transform(float64list); verify(() => canvas.transform(float64list)).called(1); }); test("translate calls Canvas's translate", () { CanvasWrapper() ..canvas = canvas ..translate(0, 0); verify(() => canvas.translate(0, 0)).called(1); }); }); }); }
pinball/packages/pinball_flame/test/src/canvas/canvas_wrapper_test.dart/0
{ "file_path": "pinball/packages/pinball_flame/test/src/canvas/canvas_wrapper_test.dart", "repo_id": "pinball", "token_count": 4717 }
1,111
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_theme/pinball_theme.dart'; void main() { group('AndroidTheme', () { test('can be instantiated', () { expect(AndroidTheme(), isNotNull); }); test('supports value equality', () { expect(AndroidTheme(), equals(AndroidTheme())); }); }); }
pinball/packages/pinball_theme/test/src/themes/android_theme_test.dart/0
{ "file_path": "pinball/packages/pinball_theme/test/src/themes/android_theme_test.dart", "repo_id": "pinball", "token_count": 139 }
1,112
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** import 'package:flutter/widgets.dart'; class $AssetsImagesGen { const $AssetsImagesGen(); $AssetsImagesButtonGen get button => const $AssetsImagesButtonGen(); $AssetsImagesDialogGen get dialog => const $AssetsImagesDialogGen(); } class $AssetsImagesButtonGen { const $AssetsImagesButtonGen(); AssetGenImage get dpadDown => const AssetGenImage('assets/images/button/dpad_down.png'); AssetGenImage get dpadLeft => const AssetGenImage('assets/images/button/dpad_left.png'); AssetGenImage get dpadRight => const AssetGenImage('assets/images/button/dpad_right.png'); AssetGenImage get dpadUp => const AssetGenImage('assets/images/button/dpad_up.png'); AssetGenImage get pinballButton => const AssetGenImage('assets/images/button/pinball_button.png'); } class $AssetsImagesDialogGen { const $AssetsImagesDialogGen(); AssetGenImage get background => const AssetGenImage('assets/images/dialog/background.png'); } class Assets { Assets._(); static const $AssetsImagesGen images = $AssetsImagesGen(); } class AssetGenImage extends AssetImage { const AssetGenImage(String assetName) : super(assetName, package: 'pinball_ui'); Image image({ Key? key, ImageFrameBuilder? frameBuilder, ImageLoadingBuilder? loadingBuilder, ImageErrorWidgetBuilder? errorBuilder, String? semanticLabel, bool excludeFromSemantics = false, double? width, double? height, Color? color, BlendMode? colorBlendMode, BoxFit? fit, AlignmentGeometry alignment = Alignment.center, ImageRepeat repeat = ImageRepeat.noRepeat, Rect? centerSlice, bool matchTextDirection = false, bool gaplessPlayback = false, bool isAntiAlias = false, FilterQuality filterQuality = FilterQuality.low, }) { return Image( key: key, image: this, frameBuilder: frameBuilder, loadingBuilder: loadingBuilder, errorBuilder: errorBuilder, semanticLabel: semanticLabel, excludeFromSemantics: excludeFromSemantics, width: width, height: height, color: color, colorBlendMode: colorBlendMode, fit: fit, alignment: alignment, repeat: repeat, centerSlice: centerSlice, matchTextDirection: matchTextDirection, gaplessPlayback: gaplessPlayback, isAntiAlias: isAntiAlias, filterQuality: filterQuality, ); } String get path => assetName; }
pinball/packages/pinball_ui/lib/gen/assets.gen.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/gen/assets.gen.dart", "repo_id": "pinball", "token_count": 882 }
1,113
import 'package:flutter/material.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template pinball_loading_indicator} /// Pixel-art loading indicator /// {@endtemplate} class PinballLoadingIndicator extends StatelessWidget { /// {@macro pinball_loading_indicator} const PinballLoadingIndicator({ Key? key, required this.value, }) : assert( value >= 0.0 && value <= 1.0, 'Progress must be between 0 and 1', ), super(key: key); /// Progress value final double value; @override Widget build(BuildContext context) { return Column( children: [ _InnerIndicator(value: value, widthFactor: 0.95), _InnerIndicator(value: value, widthFactor: 0.98), _InnerIndicator(value: value), _InnerIndicator(value: value), _InnerIndicator(value: value, widthFactor: 0.98), _InnerIndicator(value: value, widthFactor: 0.95) ], ); } } class _InnerIndicator extends StatelessWidget { const _InnerIndicator({ Key? key, required this.value, this.widthFactor = 1.0, }) : super(key: key); final double value; final double widthFactor; @override Widget build(BuildContext context) { return FractionallySizedBox( widthFactor: widthFactor, child: Column( children: [ LinearProgressIndicator( backgroundColor: PinballColors.loadingDarkBlue, color: PinballColors.loadingDarkRed, value: value, ), LinearProgressIndicator( backgroundColor: PinballColors.loadingLightBlue, color: PinballColors.loadingLightRed, value: value, ), ], ), ); } }
pinball/packages/pinball_ui/lib/src/widgets/pinball_loading_indicator.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/src/widgets/pinball_loading_indicator.dart", "repo_id": "pinball", "token_count": 713 }
1,114
include: package:very_good_analysis/analysis_options.2.4.0.yaml
pinball/packages/platform_helper/analysis_options.yaml/0
{ "file_path": "pinball/packages/platform_helper/analysis_options.yaml", "repo_id": "pinball", "token_count": 22 }
1,115
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball/game/game.dart'; void main() { group('GameEvent', () { group('RoundLost', () { test('can be instantiated', () { expect(const RoundLost(), isNotNull); }); test('supports value equality', () { expect( RoundLost(), equals(const RoundLost()), ); }); }); group('Scored', () { test('can be instantiated', () { expect(const Scored(points: 1), isNotNull); }); test('supports value equality', () { expect( Scored(points: 1), equals(const Scored(points: 1)), ); expect( const Scored(points: 1), isNot(equals(const Scored(points: 2))), ); }); test( 'throws AssertionError ' 'when score is smaller than 1', () { expect(() => Scored(points: 0), throwsAssertionError); }); }); group('MultiplierIncreased', () { test('can be instantiated', () { expect(const MultiplierIncreased(), isNotNull); }); test('supports value equality', () { expect( MultiplierIncreased(), equals(const MultiplierIncreased()), ); }); }); group('BonusActivated', () { test('can be instantiated', () { expect(const BonusActivated(GameBonus.dashNest), isNotNull); }); test('supports value equality', () { expect( BonusActivated(GameBonus.googleWord), equals(const BonusActivated(GameBonus.googleWord)), ); expect( const BonusActivated(GameBonus.googleWord), isNot(equals(const BonusActivated(GameBonus.dashNest))), ); }); }); }); group('GameStarted', () { test('can be instantiated', () { expect(const GameStarted(), isNotNull); }); test('supports value equality', () { expect( GameStarted(), equals(const GameStarted()), ); }); }); group('GameOver', () { test('can be instantiated', () { expect(const GameOver(), isNotNull); }); test('supports value equality', () { expect( GameOver(), equals(const GameOver()), ); }); }); }
pinball/test/game/bloc/game_event_test.dart/0
{ "file_path": "pinball/test/game/bloc/game_event_test.dart", "repo_id": "pinball", "token_count": 1040 }
1,116
// 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:pinball/game/components/backbox/displays/initials_submission_success_display.dart'; void main() { group('InitialsSubmissionSuccessDisplay', () { final flameTester = FlameTester(Forge2DGame.new); flameTester.test('renders correctly', (game) async { await game.ensureAdd(InitialsSubmissionSuccessDisplay()); final component = game.firstChild<TextComponent>(); expect(component, isNotNull); expect(component?.text, equals('Success!')); }); }); }
pinball/test/game/components/backbox/displays/initials_submission_success_display_test.dart/0
{ "file_path": "pinball/test/game/components/backbox/displays/initials_submission_success_display_test.dart", "repo_id": "pinball", "token_count": 251 }
1,117
// 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: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.launchRamp.ramp.keyName, Assets.images.launchRamp.backgroundRailing.keyName, Assets.images.launchRamp.foregroundRailing.keyName, Assets.images.flapper.backSupport.keyName, Assets.images.flapper.frontSupport.keyName, Assets.images.flapper.flap.keyName, Assets.images.plunger.plunger.keyName, Assets.images.plunger.rocket.keyName, ]); } Future<void> pump(Launcher launchRamp) { return ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [launchRamp], ), ); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('Launcher', () { flameTester.test( 'loads correctly', (game) async { final component = Launcher(); await game.pump(component); expect(game.descendants(), contains(component)); }, ); group('loads', () { flameTester.test( 'a LaunchRamp', (game) async { final component = Launcher(); await game.pump(component); final descendantsQuery = component.descendants().whereType<LaunchRamp>(); expect(descendantsQuery.length, equals(1)); }, ); flameTester.test( 'a Flapper', (game) async { final component = Launcher(); await game.pump(component); final descendantsQuery = component.descendants().whereType<Flapper>(); expect(descendantsQuery.length, equals(1)); }, ); flameTester.test( 'a Plunger', (game) async { final component = Launcher(); await game.pump(component); final descendantsQuery = component.descendants().whereType<Plunger>(); expect(descendantsQuery.length, equals(1)); }, ); flameTester.test( 'a RocketSpriteComponent', (game) async { final component = Launcher(); await game.pump(component); final descendantsQuery = component.descendants().whereType<RocketSpriteComponent>(); expect(descendantsQuery.length, equals(1)); }, ); }); }); }
pinball/test/game/components/launcher_test.dart/0
{ "file_path": "pinball/test/game/components/launcher_test.dart", "repo_id": "pinball", "token_count": 1159 }
1,118
import 'dart:async'; 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/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; import '../../../helpers/helpers.dart'; class _MockGameBloc extends Mock implements GameBloc {} void main() { late GameBloc gameBloc; late StreamController<GameState> stateController; const totalScore = 123456789; const roundScore = 1234; const initialState = GameState( totalScore: totalScore, roundScore: roundScore, multiplier: 1, rounds: 1, bonusHistory: [], status: GameStatus.playing, ); setUp(() { gameBloc = _MockGameBloc(); stateController = StreamController<GameState>()..add(initialState); whenListen( gameBloc, stateController.stream, initialState: initialState, ); }); group('ScoreView', () { testWidgets('renders score', (tester) async { await tester.pumpApp( const ScoreView(), gameBloc: gameBloc, ); await tester.pump(); expect( find.text(initialState.displayScore.formatScore()), findsOneWidget, ); }); testWidgets('renders game over', (tester) async { final l10n = await AppLocalizations.delegate.load(const Locale('en')); stateController.add( initialState.copyWith(status: GameStatus.gameOver), ); await tester.pumpApp( const ScoreView(), gameBloc: gameBloc, ); await tester.pump(); expect(find.text(l10n.gameOver), findsOneWidget); }); testWidgets('updates the score', (tester) async { await tester.pumpApp( const ScoreView(), gameBloc: gameBloc, ); expect( find.text(initialState.displayScore.formatScore()), findsOneWidget, ); final newState = initialState.copyWith( roundScore: 5678, ); stateController.add(newState); await tester.pump(); expect( find.text(newState.displayScore.formatScore()), findsOneWidget, ); }); }); }
pinball/test/game/view/widgets/score_view_test.dart/0
{ "file_path": "pinball/test/game/view/widgets/score_view_test.dart", "repo_id": "pinball", "token_count": 930 }
1,119
{ "name": "FlutterFire - MOVED", "platforms": [ "Android", "iOS" ], "content": "FlutterFire.md", "related": [ "FirebaseExtended/flutterfire" ] }
plugins/.opensource/project.json/0
{ "file_path": "plugins/.opensource/project.json", "repo_id": "plugins", "token_count": 76 }
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; // Mirrors exposure_mode.dart public enum ExposureMode { auto("auto"), locked("locked"); private final String strValue; ExposureMode(String strValue) { this.strValue = strValue; } /** * Tries to convert the supplied string into an {@see ExposureMode} enum value. * * <p>When the supplied string doesn't match a valid {@see ExposureMode} enum value, null is * returned. * * @param modeStr String value to convert into an {@see ExposureMode} enum value. * @return Matching {@see ExposureMode} enum value, or null if no match is found. */ public static ExposureMode getValueForString(String modeStr) { for (ExposureMode value : values()) { if (value.strValue.equals(modeStr)) { return value; } } return null; } @Override public String toString() { return strValue; } }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurelock/ExposureMode.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposurelock/ExposureMode.java", "repo_id": "plugins", "token_count": 347 }
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.types; public class CameraCaptureProperties { private Float lastLensAperture; private Long lastSensorExposureTime; private Integer lastSensorSensitivity; /** * Gets the last known lens aperture. (As f-stop value) * * @return the last known lens aperture. (As f-stop value) */ public Float getLastLensAperture() { return lastLensAperture; } /** * Sets the last known lens aperture. (As f-stop value) * * @param lastLensAperture - The last known lens aperture to set. (As f-stop value) */ public void setLastLensAperture(Float lastLensAperture) { this.lastLensAperture = lastLensAperture; } /** * Gets the last known sensor exposure time in nanoseconds. * * @return the last known sensor exposure time in nanoseconds. */ public Long getLastSensorExposureTime() { return lastSensorExposureTime; } /** * Sets the last known sensor exposure time in nanoseconds. * * @param lastSensorExposureTime - The last known sensor exposure time to set, in nanoseconds. */ public void setLastSensorExposureTime(Long lastSensorExposureTime) { this.lastSensorExposureTime = lastSensorExposureTime; } /** * Gets the last known sensor sensitivity in ISO arithmetic units. * * @return the last known sensor sensitivity in ISO arithmetic units. */ public Integer getLastSensorSensitivity() { return lastSensorSensitivity; } /** * Sets the last known sensor sensitivity in ISO arithmetic units. * * @param lastSensorSensitivity - The last known sensor sensitivity to set, in ISO arithmetic * units. */ public void setLastSensorSensitivity(Integer lastSensorSensitivity) { this.lastSensorSensitivity = lastSensorSensitivity; } }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/CameraCaptureProperties.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/CameraCaptureProperties.java", "repo_id": "plugins", "token_count": 584 }
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 junit.framework.TestCase.assertNull; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import android.os.Handler; import androidx.annotation.NonNull; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.StandardMethodCodec; import io.flutter.plugins.camera.features.autofocus.FocusMode; import io.flutter.plugins.camera.features.exposurelock.ExposureMode; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class DartMessengerTest { /** A {@link BinaryMessenger} implementation that does nothing but save its messages. */ private static class FakeBinaryMessenger implements BinaryMessenger { private final List<ByteBuffer> sentMessages = new ArrayList<>(); @Override public void send(@NonNull String channel, ByteBuffer message) { sentMessages.add(message); } @Override public void send(@NonNull String channel, ByteBuffer message, BinaryReply callback) { send(channel, message); } @Override public void setMessageHandler(@NonNull String channel, BinaryMessageHandler handler) {} List<ByteBuffer> getMessages() { return new ArrayList<>(sentMessages); } } private Handler mockHandler; private DartMessenger dartMessenger; private FakeBinaryMessenger fakeBinaryMessenger; @Before public void setUp() { mockHandler = mock(Handler.class); fakeBinaryMessenger = new FakeBinaryMessenger(); dartMessenger = new DartMessenger(fakeBinaryMessenger, 0, mockHandler); } @Test public void sendCameraErrorEvent_includesErrorDescriptions() { doAnswer(createPostHandlerAnswer()).when(mockHandler).post(any(Runnable.class)); dartMessenger.sendCameraErrorEvent("error description"); List<ByteBuffer> sentMessages = fakeBinaryMessenger.getMessages(); assertEquals(1, sentMessages.size()); MethodCall call = decodeSentMessage(sentMessages.get(0)); assertEquals("error", call.method); assertEquals("error description", call.argument("description")); } @Test public void sendCameraInitializedEvent_includesPreviewSize() { doAnswer(createPostHandlerAnswer()).when(mockHandler).post(any(Runnable.class)); dartMessenger.sendCameraInitializedEvent(0, 0, ExposureMode.auto, FocusMode.auto, true, true); List<ByteBuffer> sentMessages = fakeBinaryMessenger.getMessages(); assertEquals(1, sentMessages.size()); MethodCall call = decodeSentMessage(sentMessages.get(0)); assertEquals("initialized", call.method); assertEquals(0, (double) call.argument("previewWidth"), 0); assertEquals(0, (double) call.argument("previewHeight"), 0); assertEquals("ExposureMode auto", call.argument("exposureMode"), "auto"); assertEquals("FocusMode continuous", call.argument("focusMode"), "auto"); assertEquals("exposurePointSupported", call.argument("exposurePointSupported"), true); assertEquals("focusPointSupported", call.argument("focusPointSupported"), true); } @Test public void sendCameraClosingEvent() { doAnswer(createPostHandlerAnswer()).when(mockHandler).post(any(Runnable.class)); dartMessenger.sendCameraClosingEvent(); List<ByteBuffer> sentMessages = fakeBinaryMessenger.getMessages(); assertEquals(1, sentMessages.size()); MethodCall call = decodeSentMessage(sentMessages.get(0)); assertEquals("camera_closing", call.method); assertNull(call.argument("description")); } @Test public void sendDeviceOrientationChangedEvent() { doAnswer(createPostHandlerAnswer()).when(mockHandler).post(any(Runnable.class)); dartMessenger.sendDeviceOrientationChangeEvent(PlatformChannel.DeviceOrientation.PORTRAIT_UP); List<ByteBuffer> sentMessages = fakeBinaryMessenger.getMessages(); assertEquals(1, sentMessages.size()); MethodCall call = decodeSentMessage(sentMessages.get(0)); assertEquals("orientation_changed", call.method); assertEquals(call.argument("orientation"), "portraitUp"); } private static Answer<Boolean> createPostHandlerAnswer() { return new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { Runnable runnable = invocation.getArgument(0, Runnable.class); if (runnable != null) { runnable.run(); } return true; } }; } private MethodCall decodeSentMessage(ByteBuffer sentMessage) { sentMessage.position(0); return StandardMethodCodec.INSTANCE.decodeMethodCall(sentMessage); } }
plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/DartMessengerTest.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/DartMessengerTest.java", "repo_id": "plugins", "token_count": 1638 }
1,123
// Copyright 2013 The Flutter 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.sensororientation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.hardware.camera2.CameraMetadata; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.DartMessenger; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.MockedStatic; public class SensorOrientationFeatureTest { private MockedStatic<DeviceOrientationManager> mockedStaticDeviceOrientationManager; private Activity mockActivity; private CameraProperties mockCameraProperties; private DartMessenger mockDartMessenger; private DeviceOrientationManager mockDeviceOrientationManager; @Before public void before() { mockedStaticDeviceOrientationManager = mockStatic(DeviceOrientationManager.class); mockActivity = mock(Activity.class); mockCameraProperties = mock(CameraProperties.class); mockDartMessenger = mock(DartMessenger.class); mockDeviceOrientationManager = mock(DeviceOrientationManager.class); when(mockCameraProperties.getSensorOrientation()).thenReturn(0); when(mockCameraProperties.getLensFacing()).thenReturn(CameraMetadata.LENS_FACING_BACK); mockedStaticDeviceOrientationManager .when(() -> DeviceOrientationManager.create(mockActivity, mockDartMessenger, false, 0)) .thenReturn(mockDeviceOrientationManager); } @After public void after() { mockedStaticDeviceOrientationManager.close(); } @Test public void ctor_shouldStartDeviceOrientationManager() { SensorOrientationFeature sensorOrientationFeature = new SensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger); verify(mockDeviceOrientationManager, times(1)).start(); } @Test public void getDebugName_shouldReturnTheNameOfTheFeature() { SensorOrientationFeature sensorOrientationFeature = new SensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger); assertEquals("SensorOrientationFeature", sensorOrientationFeature.getDebugName()); } @Test public void getValue_shouldReturnNullIfNotSet() { SensorOrientationFeature sensorOrientationFeature = new SensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger); assertEquals(0, (int) sensorOrientationFeature.getValue()); } @Test public void getValue_shouldEchoSetValue() { SensorOrientationFeature sensorOrientationFeature = new SensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger); sensorOrientationFeature.setValue(90); assertEquals(90, (int) sensorOrientationFeature.getValue()); } @Test public void checkIsSupport_returnsTrue() { SensorOrientationFeature sensorOrientationFeature = new SensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger); assertTrue(sensorOrientationFeature.checkIsSupported()); } @Test public void getDeviceOrientationManager_shouldReturnInitializedDartOrientationManagerInstance() { SensorOrientationFeature sensorOrientationFeature = new SensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger); assertEquals( mockDeviceOrientationManager, sensorOrientationFeature.getDeviceOrientationManager()); } @Test public void lockCaptureOrientation_shouldLockToSpecifiedOrientation() { SensorOrientationFeature sensorOrientationFeature = new SensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger); sensorOrientationFeature.lockCaptureOrientation(DeviceOrientation.PORTRAIT_DOWN); assertEquals( DeviceOrientation.PORTRAIT_DOWN, sensorOrientationFeature.getLockedCaptureOrientation()); } @Test public void unlockCaptureOrientation_shouldSetLockToNull() { SensorOrientationFeature sensorOrientationFeature = new SensorOrientationFeature(mockCameraProperties, mockActivity, mockDartMessenger); sensorOrientationFeature.unlockCaptureOrientation(); assertNull(sensorOrientationFeature.getLockedCaptureOrientation()); } }
plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/sensororientation/SensorOrientationFeatureTest.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/sensororientation/SensorOrientationFeatureTest.java", "repo_id": "plugins", "token_count": 1453 }
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 android.content.Context; import androidx.annotation.NonNull; import androidx.lifecycle.LifecycleOwner; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.view.TextureRegistry; /** Platform implementation of the camera_plugin implemented with the CameraX library. */ public final class CameraAndroidCameraxPlugin implements FlutterPlugin, ActivityAware { private InstanceManager instanceManager; private FlutterPluginBinding pluginBinding; private ProcessCameraProviderHostApiImpl processCameraProviderHostApi; public SystemServicesHostApiImpl systemServicesHostApi; /** * Initialize this within the {@code #configureFlutterEngine} of a Flutter activity or fragment. * * <p>See {@code io.flutter.plugins.camera.MainActivity} for an example. */ public CameraAndroidCameraxPlugin() {} void setUp(BinaryMessenger binaryMessenger, Context context, TextureRegistry textureRegistry) { // Set up instance manager. instanceManager = InstanceManager.open( identifier -> { new GeneratedCameraXLibrary.JavaObjectFlutterApi(binaryMessenger) .dispose(identifier, reply -> {}); }); // Set up Host APIs. GeneratedCameraXLibrary.CameraInfoHostApi.setup( binaryMessenger, new CameraInfoHostApiImpl(instanceManager)); GeneratedCameraXLibrary.CameraSelectorHostApi.setup( binaryMessenger, new CameraSelectorHostApiImpl(binaryMessenger, instanceManager)); GeneratedCameraXLibrary.JavaObjectHostApi.setup( binaryMessenger, new JavaObjectHostApiImpl(instanceManager)); processCameraProviderHostApi = new ProcessCameraProviderHostApiImpl(binaryMessenger, instanceManager, context); GeneratedCameraXLibrary.ProcessCameraProviderHostApi.setup( binaryMessenger, processCameraProviderHostApi); systemServicesHostApi = new SystemServicesHostApiImpl(binaryMessenger, instanceManager); GeneratedCameraXLibrary.SystemServicesHostApi.setup(binaryMessenger, systemServicesHostApi); GeneratedCameraXLibrary.PreviewHostApi.setup( binaryMessenger, new PreviewHostApiImpl(binaryMessenger, instanceManager, textureRegistry)); } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { pluginBinding = flutterPluginBinding; } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { if (instanceManager != null) { instanceManager.close(); } } // Activity Lifecycle methods: @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) { setUp( pluginBinding.getBinaryMessenger(), pluginBinding.getApplicationContext(), pluginBinding.getTextureRegistry()); updateContext(pluginBinding.getApplicationContext()); processCameraProviderHostApi.setLifecycleOwner( (LifecycleOwner) activityPluginBinding.getActivity()); systemServicesHostApi.setActivity(activityPluginBinding.getActivity()); systemServicesHostApi.setPermissionsRegistry( activityPluginBinding::addRequestPermissionsResultListener); } @Override public void onDetachedFromActivityForConfigChanges() { updateContext(pluginBinding.getApplicationContext()); } @Override public void onReattachedToActivityForConfigChanges( @NonNull ActivityPluginBinding activityPluginBinding) { updateContext(activityPluginBinding.getActivity()); } @Override public void onDetachedFromActivity() { updateContext(pluginBinding.getApplicationContext()); } /** * Updates context that is used to fetch the corresponding instance of a {@code * ProcessCameraProvider}. */ public void updateContext(Context context) { if (processCameraProviderHostApi != null) { processCameraProviderHostApi.setContext(context); } } }
plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraAndroidCameraxPlugin.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraAndroidCameraxPlugin.java", "repo_id": "plugins", "token_count": 1326 }
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. package io.flutter.plugins.camerax; import android.app.Activity; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraPermissionsErrorData; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Result; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesHostApi; public class SystemServicesHostApiImpl implements SystemServicesHostApi { private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; @VisibleForTesting public CameraXProxy cameraXProxy = new CameraXProxy(); @VisibleForTesting public DeviceOrientationManager deviceOrientationManager; @VisibleForTesting public SystemServicesFlutterApiImpl systemServicesFlutterApi; private Activity activity; private PermissionsRegistry permissionsRegistry; public SystemServicesHostApiImpl( BinaryMessenger binaryMessenger, InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; this.systemServicesFlutterApi = new SystemServicesFlutterApiImpl(binaryMessenger); } public void setActivity(Activity activity) { this.activity = activity; } public void setPermissionsRegistry(PermissionsRegistry permissionsRegistry) { this.permissionsRegistry = permissionsRegistry; } /** * Requests camera permissions using an instance of a {@link CameraPermissionsManager}. * * <p>Will result with {@code null} if permissions were approved or there were no errors; * otherwise, it will result with the error data explaining what went wrong. */ @Override public void requestCameraPermissions( Boolean enableAudio, Result<CameraPermissionsErrorData> result) { CameraPermissionsManager cameraPermissionsManager = cameraXProxy.createCameraPermissionsManager(); cameraPermissionsManager.requestPermissions( activity, permissionsRegistry, enableAudio, (String errorCode, String description) -> { if (errorCode == null) { result.success(null); } else { // If permissions are ongoing or denied, error data will be sent to be handled. CameraPermissionsErrorData errorData = new CameraPermissionsErrorData.Builder() .setErrorCode(errorCode) .setDescription(description) .build(); result.success(errorData); } }); } /** * Starts listening for device orientation changes using an instace of a {@link * DeviceOrientationManager}. * * <p>Whenever a change in device orientation is detected by the {@code DeviceOrientationManager}, * the {@link SystemServicesFlutterApi} will be used to notify the Dart side. */ @Override public void startListeningForDeviceOrientationChange( Boolean isFrontFacing, Long sensorOrientation) { deviceOrientationManager = cameraXProxy.createDeviceOrientationManager( activity, isFrontFacing, sensorOrientation.intValue(), (DeviceOrientation newOrientation) -> { systemServicesFlutterApi.sendDeviceOrientationChangedEvent( serializeDeviceOrientation(newOrientation), reply -> {}); }); deviceOrientationManager.start(); } /** Serializes {@code DeviceOrientation} into a String that the Dart side is able to recognize. */ String serializeDeviceOrientation(DeviceOrientation orientation) { return orientation.toString(); } /** * Tells the {@code deviceOrientationManager} to stop listening for orientation updates. * * <p>Has no effect if the {@code deviceOrientationManager} was never created to listen for device * orientation updates. */ @Override public void stopListeningForDeviceOrientationChange() { if (deviceOrientationManager != null) { deviceOrientationManager.stop(); } } }
plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesHostApiImpl.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesHostApiImpl.java", "repo_id": "plugins", "token_count": 1424 }
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. import 'package:camera_android_camerax/camera_android_camerax.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() async { CameraPlatform.instance = AndroidCameraCameraX(); }); testWidgets('availableCameras only supports valid back or front cameras', (WidgetTester tester) async { final List<CameraDescription> availableCameras = await CameraPlatform.instance.availableCameras(); for (final CameraDescription cameraDescription in availableCameras) { expect( cameraDescription.lensDirection, isNot(CameraLensDirection.external)); expect(cameraDescription.sensorOrientation, anyOf(0, 90, 180, 270)); } }); }
plugins/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart", "repo_id": "plugins", "token_count": 330 }
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 'package:flutter/foundation.dart' show immutable; import 'package:flutter/services.dart'; import 'camerax_library.g.dart'; import 'instance_manager.dart'; /// Root of the Java class hierarchy. /// /// See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html. @immutable class JavaObject { /// Constructs a [JavaObject] without creating the associated Java object. /// /// This should only be used by subclasses created by this library or to /// create copies. JavaObject.detached({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _api = JavaObjectHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ); /// Global instance of [InstanceManager]. static final InstanceManager globalInstanceManager = InstanceManager( onWeakReferenceRemoved: (int identifier) { JavaObjectHostApiImpl().dispose(identifier); }, ); /// Pigeon Host Api implementation for [JavaObject]. final JavaObjectHostApiImpl _api; /// Release the reference to a native Java instance. static void dispose(JavaObject instance) { instance._api.instanceManager.removeWeakReference(instance); } } /// Handles methods calls to the native Java Object class. class JavaObjectHostApiImpl extends JavaObjectHostApi { /// Constructs a [JavaObjectHostApiImpl]. JavaObjectHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; } /// Handles callbacks methods for the native Java Object class. class JavaObjectFlutterApiImpl implements JavaObjectFlutterApi { /// Constructs a [JavaObjectFlutterApiImpl]. JavaObjectFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; @override void dispose(int identifier) { instanceManager.remove(identifier); } }
plugins/packages/camera/camera_android_camerax/lib/src/java_object.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/lib/src/java_object.dart", "repo_id": "plugins", "token_count": 743 }
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. import 'package:camera_android_camerax/src/camerax_library.g.dart'; import 'package:camera_android_camerax/src/instance_manager.dart'; import 'package:camera_android_camerax/src/preview.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'preview_test.mocks.dart'; import 'test_camerax_library.g.dart'; @GenerateMocks(<Type>[TestPreviewHostApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('Preview', () { tearDown(() => TestPreviewHostApi.setup(null)); test('detached create does not call create on the Java side', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); Preview.detached( instanceManager: instanceManager, targetRotation: 90, targetResolution: ResolutionInfo(width: 50, height: 10), ); verifyNever(mockApi.create(argThat(isA<int>()), argThat(isA<int>()), argThat(isA<ResolutionInfo>()))); }); test('create calls create on the Java side', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const int targetRotation = 90; const int targetResolutionWidth = 10; const int targetResolutionHeight = 50; Preview( instanceManager: instanceManager, targetRotation: targetRotation, targetResolution: ResolutionInfo( width: targetResolutionWidth, height: targetResolutionHeight), ); final VerificationResult createVerification = verify(mockApi.create( argThat(isA<int>()), argThat(equals(targetRotation)), captureAny)); final ResolutionInfo capturedResolutionInfo = createVerification.captured.single as ResolutionInfo; expect(capturedResolutionInfo.width, equals(targetResolutionWidth)); expect(capturedResolutionInfo.height, equals(targetResolutionHeight)); }); test( 'setSurfaceProvider makes call to set surface provider for preview instance', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); const int textureId = 8; final Preview preview = Preview.detached( instanceManager: instanceManager, ); instanceManager.addHostCreatedInstance( preview, 0, onCopy: (_) => Preview.detached(), ); when(mockApi.setSurfaceProvider(instanceManager.getIdentifier(preview))) .thenReturn(textureId); expect(await preview.setSurfaceProvider(), equals(textureId)); verify( mockApi.setSurfaceProvider(instanceManager.getIdentifier(preview))); }); test( 'releaseFlutterSurfaceTexture makes call to relase flutter surface texture entry', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final Preview preview = Preview.detached(); preview.releaseFlutterSurfaceTexture(); verify(mockApi.releaseFlutterSurfaceTexture()); }); test( 'getResolutionInfo makes call to get resolution information for preview instance', () async { final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); TestPreviewHostApi.setup(mockApi); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: (_) {}, ); final Preview preview = Preview.detached( instanceManager: instanceManager, ); const int resolutionWidth = 10; const int resolutionHeight = 60; final ResolutionInfo testResolutionInfo = ResolutionInfo(width: resolutionWidth, height: resolutionHeight); instanceManager.addHostCreatedInstance( preview, 0, onCopy: (_) => Preview.detached(), ); when(mockApi.getResolutionInfo(instanceManager.getIdentifier(preview))) .thenReturn(testResolutionInfo); final ResolutionInfo previewResolutionInfo = await preview.getResolutionInfo(); expect(previewResolutionInfo.width, equals(resolutionWidth)); expect(previewResolutionInfo.height, equals(resolutionHeight)); verify(mockApi.getResolutionInfo(instanceManager.getIdentifier(preview))); }); }); }
plugins/packages/camera/camera_android_camerax/test/preview_test.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/test/preview_test.dart", "repo_id": "plugins", "token_count": 1794 }
1,129
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import camera_avfoundation; @import camera_avfoundation.Test; @import XCTest; @interface CameraCaptureSessionQueueRaceConditionTests : XCTestCase @end @implementation CameraCaptureSessionQueueRaceConditionTests - (void)testFixForCaptureSessionQueueNullPointerCrashDueToRaceCondition { CameraPlugin *camera = [[CameraPlugin alloc] initWithRegistry:nil messenger:nil]; XCTestExpectation *disposeExpectation = [self expectationWithDescription:@"dispose's result block must be called"]; XCTestExpectation *createExpectation = [self expectationWithDescription:@"create's result block must be called"]; FlutterMethodCall *disposeCall = [FlutterMethodCall methodCallWithMethodName:@"dispose" arguments:nil]; FlutterMethodCall *createCall = [FlutterMethodCall methodCallWithMethodName:@"create" arguments:@{@"resolutionPreset" : @"medium", @"enableAudio" : @(1)}]; // Mimic a dispose call followed by a create call, which can be triggered by slightly dragging the // home bar, causing the app to be inactive, and immediately regain active. [camera handleMethodCall:disposeCall result:^(id _Nullable result) { [disposeExpectation fulfill]; }]; [camera createCameraOnSessionQueueWithCreateMethodCall:createCall result:[[FLTThreadSafeFlutterResult alloc] initWithResult:^(id _Nullable result) { [createExpectation fulfill]; }]]; [self waitForExpectationsWithTimeout:1 handler:nil]; // `captureSessionQueue` must not be nil after `create` call. Otherwise a nil // `captureSessionQueue` passed into `AVCaptureVideoDataOutput::setSampleBufferDelegate:queue:` // API will cause a crash. XCTAssertNotNil(camera.captureSessionQueue, @"captureSessionQueue must not be nil after create method. "); } @end
plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraCaptureSessionQueueRaceConditionTests.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraCaptureSessionQueueRaceConditionTests.m", "repo_id": "plugins", "token_count": 949 }
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. @import camera_avfoundation; @import XCTest; #import "MockFLTThreadSafeFlutterResult.h" @implementation MockFLTThreadSafeFlutterResult - (instancetype)initWithExpectation:(XCTestExpectation *)expectation { self = [super init]; _expectation = expectation; return self; } - (void)sendSuccessWithData:(id)data { self.receivedResult = data; [self.expectation fulfill]; } - (void)sendSuccess { self.receivedResult = nil; [self.expectation fulfill]; } @end
plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/MockFLTThreadSafeFlutterResult.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/MockFLTThreadSafeFlutterResult.m", "repo_id": "plugins", "token_count": 206 }
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. #import "CameraPlugin.h" #import "CameraPlugin_Test.h" @import AVFoundation; #import "CameraPermissionUtils.h" #import "CameraProperties.h" #import "FLTCam.h" #import "FLTThreadSafeEventChannel.h" #import "FLTThreadSafeFlutterResult.h" #import "FLTThreadSafeMethodChannel.h" #import "FLTThreadSafeTextureRegistry.h" #import "QueueUtils.h" @interface CameraPlugin () @property(readonly, nonatomic) FLTThreadSafeTextureRegistry *registry; @property(readonly, nonatomic) NSObject<FlutterBinaryMessenger> *messenger; @end @implementation CameraPlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/camera_avfoundation" binaryMessenger:[registrar messenger]]; CameraPlugin *instance = [[CameraPlugin alloc] initWithRegistry:[registrar textures] messenger:[registrar messenger]]; [registrar addMethodCallDelegate:instance channel:channel]; } - (instancetype)initWithRegistry:(NSObject<FlutterTextureRegistry> *)registry messenger:(NSObject<FlutterBinaryMessenger> *)messenger { self = [super init]; NSAssert(self, @"super init cannot be nil"); _registry = [[FLTThreadSafeTextureRegistry alloc] initWithTextureRegistry:registry]; _messenger = messenger; _captureSessionQueue = dispatch_queue_create("io.flutter.camera.captureSessionQueue", NULL); dispatch_queue_set_specific(_captureSessionQueue, FLTCaptureSessionQueueSpecific, (void *)FLTCaptureSessionQueueSpecific, NULL); [self initDeviceEventMethodChannel]; [self startOrientationListener]; return self; } - (void)initDeviceEventMethodChannel { FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/camera_avfoundation/fromPlatform" binaryMessenger:_messenger]; _deviceEventMethodChannel = [[FLTThreadSafeMethodChannel alloc] initWithMethodChannel:methodChannel]; } - (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { [UIDevice.currentDevice endGeneratingDeviceOrientationNotifications]; } - (void)startOrientationListener { [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]]; } - (void)orientationChanged:(NSNotification *)note { UIDevice *device = note.object; UIDeviceOrientation orientation = device.orientation; if (orientation == UIDeviceOrientationFaceUp || orientation == UIDeviceOrientationFaceDown) { // Do not change when oriented flat. return; } __weak typeof(self) weakSelf = self; dispatch_async(self.captureSessionQueue, ^{ // `FLTCam::setDeviceOrientation` must be called on capture session queue. [weakSelf.camera setDeviceOrientation:orientation]; // `CameraPlugin::sendDeviceOrientation` can be called on any queue. [weakSelf sendDeviceOrientation:orientation]; }); } - (void)sendDeviceOrientation:(UIDeviceOrientation)orientation { [_deviceEventMethodChannel invokeMethod:@"orientation_changed" arguments:@{@"orientation" : FLTGetStringForUIDeviceOrientation(orientation)}]; } - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result { // Invoke the plugin on another dispatch queue to avoid blocking the UI. __weak typeof(self) weakSelf = self; dispatch_async(self.captureSessionQueue, ^{ FLTThreadSafeFlutterResult *threadSafeResult = [[FLTThreadSafeFlutterResult alloc] initWithResult:result]; [weakSelf handleMethodCallAsync:call result:threadSafeResult]; }); } - (void)handleMethodCallAsync:(FlutterMethodCall *)call result:(FLTThreadSafeFlutterResult *)result { if ([@"availableCameras" isEqualToString:call.method]) { if (@available(iOS 10.0, *)) { NSMutableArray *discoveryDevices = [@[ AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInTelephotoCamera ] mutableCopy]; if (@available(iOS 13.0, *)) { [discoveryDevices addObject:AVCaptureDeviceTypeBuiltInUltraWideCamera]; } AVCaptureDeviceDiscoverySession *discoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:discoveryDevices mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified]; NSArray<AVCaptureDevice *> *devices = discoverySession.devices; NSMutableArray<NSDictionary<NSString *, NSObject *> *> *reply = [[NSMutableArray alloc] initWithCapacity:devices.count]; for (AVCaptureDevice *device in devices) { NSString *lensFacing; switch ([device position]) { case AVCaptureDevicePositionBack: lensFacing = @"back"; break; case AVCaptureDevicePositionFront: lensFacing = @"front"; break; case AVCaptureDevicePositionUnspecified: lensFacing = @"external"; break; } [reply addObject:@{ @"name" : [device uniqueID], @"lensFacing" : lensFacing, @"sensorOrientation" : @90, }]; } [result sendSuccessWithData:reply]; } else { [result sendNotImplemented]; } } else if ([@"create" isEqualToString:call.method]) { [self handleCreateMethodCall:call result:result]; } else if ([@"startImageStream" isEqualToString:call.method]) { [_camera startImageStreamWithMessenger:_messenger]; [result sendSuccess]; } else if ([@"stopImageStream" isEqualToString:call.method]) { [_camera stopImageStream]; [result sendSuccess]; } else if ([@"receivedImageStreamData" isEqualToString:call.method]) { [_camera receivedImageStreamData]; [result sendSuccess]; } else { NSDictionary *argsMap = call.arguments; NSUInteger cameraId = ((NSNumber *)argsMap[@"cameraId"]).unsignedIntegerValue; if ([@"initialize" isEqualToString:call.method]) { NSString *videoFormatValue = ((NSString *)argsMap[@"imageFormatGroup"]); [_camera setVideoFormat:FLTGetVideoFormatFromString(videoFormatValue)]; __weak CameraPlugin *weakSelf = self; _camera.onFrameAvailable = ^{ if (![weakSelf.camera isPreviewPaused]) { [weakSelf.registry textureFrameAvailable:cameraId]; } }; FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName: [NSString stringWithFormat:@"plugins.flutter.io/camera_avfoundation/camera%lu", (unsigned long)cameraId] binaryMessenger:_messenger]; FLTThreadSafeMethodChannel *threadSafeMethodChannel = [[FLTThreadSafeMethodChannel alloc] initWithMethodChannel:methodChannel]; _camera.methodChannel = threadSafeMethodChannel; [threadSafeMethodChannel invokeMethod:@"initialized" arguments:@{ @"previewWidth" : @(_camera.previewSize.width), @"previewHeight" : @(_camera.previewSize.height), @"exposureMode" : FLTGetStringForFLTExposureMode([_camera exposureMode]), @"focusMode" : FLTGetStringForFLTFocusMode([_camera focusMode]), @"exposurePointSupported" : @([_camera.captureDevice isExposurePointOfInterestSupported]), @"focusPointSupported" : @([_camera.captureDevice isFocusPointOfInterestSupported]), }]; [self sendDeviceOrientation:[UIDevice currentDevice].orientation]; [_camera start]; [result sendSuccess]; } else if ([@"takePicture" isEqualToString:call.method]) { if (@available(iOS 10.0, *)) { [_camera captureToFile:result]; } else { [result sendNotImplemented]; } } else if ([@"dispose" isEqualToString:call.method]) { [_registry unregisterTexture:cameraId]; [_camera close]; [result sendSuccess]; } else if ([@"prepareForVideoRecording" isEqualToString:call.method]) { [self.camera setUpCaptureSessionForAudio]; [result sendSuccess]; } else if ([@"startVideoRecording" isEqualToString:call.method]) { BOOL enableStream = [call.arguments[@"enableStream"] boolValue]; if (enableStream) { [_camera startVideoRecordingWithResult:result messengerForStreaming:_messenger]; } else { [_camera startVideoRecordingWithResult:result]; } } else if ([@"stopVideoRecording" isEqualToString:call.method]) { [_camera stopVideoRecordingWithResult:result]; } else if ([@"pauseVideoRecording" isEqualToString:call.method]) { [_camera pauseVideoRecordingWithResult:result]; } else if ([@"resumeVideoRecording" isEqualToString:call.method]) { [_camera resumeVideoRecordingWithResult:result]; } else if ([@"getMaxZoomLevel" isEqualToString:call.method]) { [_camera getMaxZoomLevelWithResult:result]; } else if ([@"getMinZoomLevel" isEqualToString:call.method]) { [_camera getMinZoomLevelWithResult:result]; } else if ([@"setZoomLevel" isEqualToString:call.method]) { CGFloat zoom = ((NSNumber *)argsMap[@"zoom"]).floatValue; [_camera setZoomLevel:zoom Result:result]; } else if ([@"setFlashMode" isEqualToString:call.method]) { [_camera setFlashModeWithResult:result mode:call.arguments[@"mode"]]; } else if ([@"setExposureMode" isEqualToString:call.method]) { [_camera setExposureModeWithResult:result mode:call.arguments[@"mode"]]; } else if ([@"setExposurePoint" isEqualToString:call.method]) { BOOL reset = ((NSNumber *)call.arguments[@"reset"]).boolValue; double x = 0.5; double y = 0.5; if (!reset) { x = ((NSNumber *)call.arguments[@"x"]).doubleValue; y = ((NSNumber *)call.arguments[@"y"]).doubleValue; } [_camera setExposurePointWithResult:result x:x y:y]; } else if ([@"getMinExposureOffset" isEqualToString:call.method]) { [result sendSuccessWithData:@(_camera.captureDevice.minExposureTargetBias)]; } else if ([@"getMaxExposureOffset" isEqualToString:call.method]) { [result sendSuccessWithData:@(_camera.captureDevice.maxExposureTargetBias)]; } else if ([@"getExposureOffsetStepSize" isEqualToString:call.method]) { [result sendSuccessWithData:@(0.0)]; } else if ([@"setExposureOffset" isEqualToString:call.method]) { [_camera setExposureOffsetWithResult:result offset:((NSNumber *)call.arguments[@"offset"]).doubleValue]; } else if ([@"lockCaptureOrientation" isEqualToString:call.method]) { [_camera lockCaptureOrientationWithResult:result orientation:call.arguments[@"orientation"]]; } else if ([@"unlockCaptureOrientation" isEqualToString:call.method]) { [_camera unlockCaptureOrientationWithResult:result]; } else if ([@"setFocusMode" isEqualToString:call.method]) { [_camera setFocusModeWithResult:result mode:call.arguments[@"mode"]]; } else if ([@"setFocusPoint" isEqualToString:call.method]) { BOOL reset = ((NSNumber *)call.arguments[@"reset"]).boolValue; double x = 0.5; double y = 0.5; if (!reset) { x = ((NSNumber *)call.arguments[@"x"]).doubleValue; y = ((NSNumber *)call.arguments[@"y"]).doubleValue; } [_camera setFocusPointWithResult:result x:x y:y]; } else if ([@"pausePreview" isEqualToString:call.method]) { [_camera pausePreviewWithResult:result]; } else if ([@"resumePreview" isEqualToString:call.method]) { [_camera resumePreviewWithResult:result]; } else { [result sendNotImplemented]; } } } - (void)handleCreateMethodCall:(FlutterMethodCall *)call result:(FLTThreadSafeFlutterResult *)result { // Create FLTCam only if granted camera access (and audio access if audio is enabled) __weak typeof(self) weakSelf = self; FLTRequestCameraPermissionWithCompletionHandler(^(FlutterError *error) { typeof(self) strongSelf = weakSelf; if (!strongSelf) return; if (error) { [result sendFlutterError:error]; } else { // Request audio permission on `create` call with `enableAudio` argument instead of the // `prepareForVideoRecording` call. This is because `prepareForVideoRecording` call is // optional, and used as a workaround to fix a missing frame issue on iOS. BOOL audioEnabled = [call.arguments[@"enableAudio"] boolValue]; if (audioEnabled) { // Setup audio capture session only if granted audio access. FLTRequestAudioPermissionWithCompletionHandler(^(FlutterError *error) { // cannot use the outter `strongSelf` typeof(self) strongSelf = weakSelf; if (!strongSelf) return; if (error) { [result sendFlutterError:error]; } else { [strongSelf createCameraOnSessionQueueWithCreateMethodCall:call result:result]; } }); } else { [strongSelf createCameraOnSessionQueueWithCreateMethodCall:call result:result]; } } }); } - (void)createCameraOnSessionQueueWithCreateMethodCall:(FlutterMethodCall *)createMethodCall result:(FLTThreadSafeFlutterResult *)result { __weak typeof(self) weakSelf = self; dispatch_async(self.captureSessionQueue, ^{ typeof(self) strongSelf = weakSelf; if (!strongSelf) return; NSString *cameraName = createMethodCall.arguments[@"cameraName"]; NSString *resolutionPreset = createMethodCall.arguments[@"resolutionPreset"]; NSNumber *enableAudio = createMethodCall.arguments[@"enableAudio"]; NSError *error; FLTCam *cam = [[FLTCam alloc] initWithCameraName:cameraName resolutionPreset:resolutionPreset enableAudio:[enableAudio boolValue] orientation:[[UIDevice currentDevice] orientation] captureSessionQueue:strongSelf.captureSessionQueue error:&error]; if (error) { [result sendError:error]; } else { if (strongSelf.camera) { [strongSelf.camera close]; } strongSelf.camera = cam; [strongSelf.registry registerTexture:cam completion:^(int64_t textureId) { [result sendSuccessWithData:@{ @"cameraId" : @(textureId), }]; }]; } }); } @end
plugins/packages/camera/camera_avfoundation/ios/Classes/CameraPlugin.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/CameraPlugin.m", "repo_id": "plugins", "token_count": 6131 }
1,132
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FLTThreadSafeMethodChannel.h" #import "QueueUtils.h" @interface FLTThreadSafeMethodChannel () @property(nonatomic, strong) FlutterMethodChannel *channel; @end @implementation FLTThreadSafeMethodChannel - (instancetype)initWithMethodChannel:(FlutterMethodChannel *)channel { self = [super init]; if (self) { _channel = channel; } return self; } - (void)invokeMethod:(NSString *)method arguments:(id)arguments { __weak typeof(self) weakSelf = self; FLTEnsureToRunOnMainQueue(^{ [weakSelf.channel invokeMethod:method arguments:arguments]; }); } @end
plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeMethodChannel.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeMethodChannel.m", "repo_id": "plugins", "token_count": 235 }
1,133
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_H_ #include <flutter/method_channel.h> #include <flutter/standard_method_codec.h> #include <functional> #include "capture_controller.h" namespace camera_windows { using flutter::EncodableMap; using flutter::MethodChannel; using flutter::MethodResult; // A set of result types that are stored // for processing asynchronous commands. enum class PendingResultType { kCreateCamera, kInitialize, kTakePicture, kStartRecord, kStopRecord, kPausePreview, kResumePreview, }; // Interface implemented by cameras. // // Access is provided to an associated |CaptureController|, which can be used // to capture video or photo from the camera. class Camera : public CaptureControllerListener { public: explicit Camera(const std::string& device_id) {} virtual ~Camera() = default; // Disallow copy and move. Camera(const Camera&) = delete; Camera& operator=(const Camera&) = delete; // Tests if this camera has the specified device ID. virtual bool HasDeviceId(std::string& device_id) const = 0; // Tests if this camera has the specified camera ID. virtual bool HasCameraId(int64_t camera_id) const = 0; // Adds a pending result. // // Returns an error result if the result has already been added. virtual bool AddPendingResult(PendingResultType type, std::unique_ptr<MethodResult<>> result) = 0; // Checks if a pending result of the specified type already exists. virtual bool HasPendingResultByType(PendingResultType type) const = 0; // Returns a |CaptureController| that allows capturing video or still photos // from this camera. virtual camera_windows::CaptureController* GetCaptureController() = 0; // Initializes this camera and its associated capture controller. // // Returns false if initialization fails. virtual bool InitCamera(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset) = 0; }; // Concrete implementation of the |Camera| interface. // // This implementation is responsible for initializing the capture controller, // listening for camera events, processing pending results, and notifying // application code of processed events via the method channel. class CameraImpl : public Camera { public: explicit CameraImpl(const std::string& device_id); virtual ~CameraImpl(); // Disallow copy and move. CameraImpl(const CameraImpl&) = delete; CameraImpl& operator=(const CameraImpl&) = delete; // CaptureControllerListener void OnCreateCaptureEngineSucceeded(int64_t texture_id) override; void OnCreateCaptureEngineFailed(CameraResult result, const std::string& error) override; void OnStartPreviewSucceeded(int32_t width, int32_t height) override; void OnStartPreviewFailed(CameraResult result, const std::string& error) override; void OnPausePreviewSucceeded() override; void OnPausePreviewFailed(CameraResult result, const std::string& error) override; void OnResumePreviewSucceeded() override; void OnResumePreviewFailed(CameraResult result, const std::string& error) override; void OnStartRecordSucceeded() override; void OnStartRecordFailed(CameraResult result, const std::string& error) override; void OnStopRecordSucceeded(const std::string& file_path) override; void OnStopRecordFailed(CameraResult result, const std::string& error) override; void OnTakePictureSucceeded(const std::string& file_path) override; void OnTakePictureFailed(CameraResult result, const std::string& error) override; void OnVideoRecordSucceeded(const std::string& file_path, int64_t video_duration) override; void OnVideoRecordFailed(CameraResult result, const std::string& error) override; void OnCaptureError(CameraResult result, const std::string& error) override; // Camera bool HasDeviceId(std::string& device_id) const override { return device_id_ == device_id; } bool HasCameraId(int64_t camera_id) const override { return camera_id_ == camera_id; } bool AddPendingResult(PendingResultType type, std::unique_ptr<MethodResult<>> result) override; bool HasPendingResultByType(PendingResultType type) const override; camera_windows::CaptureController* GetCaptureController() override { return capture_controller_.get(); } bool InitCamera(flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset) override; // Initializes the camera and its associated capture controller. // // This is a convenience method called by |InitCamera| but also used in // tests. // // Returns false if initialization fails. bool InitCamera( std::unique_ptr<CaptureControllerFactory> capture_controller_factory, flutter::TextureRegistrar* texture_registrar, flutter::BinaryMessenger* messenger, bool record_audio, ResolutionPreset resolution_preset); private: // Loops through all pending results and calls their error handler with given // error ID and description. Pending results are cleared in the process. // // error_code: A string error code describing the error. // description: A user-readable error message (optional). void SendErrorForPendingResults(const std::string& error_code, const std::string& description); // Called when camera is disposed. // Sends camera closing message to the cameras method channel. void OnCameraClosing(); // Initializes method channel instance and returns pointer it. MethodChannel<>* GetMethodChannel(); // Finds pending result by type. // Returns nullptr if type is not present. std::unique_ptr<MethodResult<>> GetPendingResultByType( PendingResultType type); std::map<PendingResultType, std::unique_ptr<MethodResult<>>> pending_results_; std::unique_ptr<CaptureController> capture_controller_; std::unique_ptr<MethodChannel<>> camera_channel_; flutter::BinaryMessenger* messenger_ = nullptr; int64_t camera_id_ = -1; std::string device_id_; }; // Factory class for creating |Camera| instances from a specified device ID. class CameraFactory { public: CameraFactory() {} virtual ~CameraFactory() = default; // Disallow copy and move. CameraFactory(const CameraFactory&) = delete; CameraFactory& operator=(const CameraFactory&) = delete; // Creates camera for given device id. virtual std::unique_ptr<Camera> CreateCamera( const std::string& device_id) = 0; }; // Concrete implementation of |CameraFactory|. class CameraFactoryImpl : public CameraFactory { public: CameraFactoryImpl() {} virtual ~CameraFactoryImpl() = default; // Disallow copy and move. CameraFactoryImpl(const CameraFactoryImpl&) = delete; CameraFactoryImpl& operator=(const CameraFactoryImpl&) = delete; std::unique_ptr<Camera> CreateCamera(const std::string& device_id) override { return std::make_unique<CameraImpl>(device_id); } }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAMERA_H_
plugins/packages/camera/camera_windows/windows/camera.h/0
{ "file_path": "plugins/packages/camera/camera_windows/windows/camera.h", "repo_id": "plugins", "token_count": 2499 }
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. #ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PREVIEW_HANDLER_H_ #define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PREVIEW_HANDLER_H_ #include <mfapi.h> #include <mfcaptureengine.h> #include <wrl/client.h> #include <memory> #include <string> #include "capture_engine_listener.h" namespace camera_windows { using Microsoft::WRL::ComPtr; // States the preview handler can be in. // // When created, the handler starts in |kNotStarted| state and mostly // transitions in sequential order of the states. When the preview is running, // it can be set to the |kPaused| state and later resumed to |kRunning| state. enum class PreviewState { kNotStarted, kStarting, kRunning, kPaused, kStopping }; // Handler for a camera's video preview. // // Handles preview sink initialization and manages the state of the video // preview. class PreviewHandler { public: PreviewHandler() {} virtual ~PreviewHandler() = default; // Prevent copying. PreviewHandler(PreviewHandler const&) = delete; PreviewHandler& operator=(PreviewHandler const&) = delete; // Initializes preview sink and requests capture engine to start previewing. // Sets preview state to: starting. // // capture_engine: A pointer to capture engine instance. Used to start // the actual recording. // base_media_type: A pointer to base media type used as a base // for the actual video capture media type. // sample_callback: A pointer to capture engine listener. // This is set as sample callback for preview sink. HRESULT StartPreview(IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type, CaptureEngineListener* sample_callback); // Stops existing recording. // // capture_engine: A pointer to capture engine instance. Used to stop // the ongoing recording. HRESULT StopPreview(IMFCaptureEngine* capture_engine); // Set the preview handler recording state to: paused. bool PausePreview(); // Set the preview handler recording state to: running. bool ResumePreview(); // Set the preview handler recording state to: running. void OnPreviewStarted(); // Returns true if preview state is running or paused. bool IsInitialized() const { return preview_state_ == PreviewState::kRunning || preview_state_ == PreviewState::kPaused; } // Returns true if preview state is running. bool IsRunning() const { return preview_state_ == PreviewState::kRunning; } // Return true if preview state is paused. bool IsPaused() const { return preview_state_ == PreviewState::kPaused; } // Returns true if preview state is starting. bool IsStarting() const { return preview_state_ == PreviewState::kStarting; } private: // Initializes record sink for video file capture. HRESULT InitPreviewSink(IMFCaptureEngine* capture_engine, IMFMediaType* base_media_type, CaptureEngineListener* sample_callback); PreviewState preview_state_ = PreviewState::kNotStarted; ComPtr<IMFCapturePreviewSink> preview_sink_; }; } // namespace camera_windows #endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PREVIEW_HANDLER_H_
plugins/packages/camera/camera_windows/windows/preview_handler.h/0
{ "file_path": "plugins/packages/camera/camera_windows/windows/preview_handler.h", "repo_id": "plugins", "token_count": 1093 }
1,135
org.gradle.jvmargs=-Xmx4G android.enableR8=true android.useAndroidX=true android.enableJetifier=true
plugins/packages/espresso/example/android/gradle.properties/0
{ "file_path": "plugins/packages/espresso/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,136
name: file_selector_example description: A new Flutter project. publish_to: none version: 1.0.0+1 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: file_selector: # When depending on this package from a real application you should use: # file_selector: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ flutter: sdk: flutter path_provider: ^2.0.9 dev_dependencies: build_runner: ^2.1.10 flutter_test: sdk: flutter flutter: uses-material-design: true
plugins/packages/file_selector/file_selector/example/pubspec.yaml/0
{ "file_path": "plugins/packages/file_selector/file_selector/example/pubspec.yaml", "repo_id": "plugins", "token_count": 267 }
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. // Autogenerated from Pigeon (v3.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List; import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer; import 'package:flutter/services.dart'; class TypeGroup { TypeGroup({ required this.label, required this.extensions, }); String label; List<String?> extensions; Object encode() { final Map<Object?, Object?> pigeonMap = <Object?, Object?>{}; pigeonMap['label'] = label; pigeonMap['extensions'] = extensions; return pigeonMap; } static TypeGroup decode(Object message) { final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>; return TypeGroup( label: pigeonMap['label']! as String, extensions: (pigeonMap['extensions'] as List<Object?>?)!.cast<String?>(), ); } } class SelectionOptions { SelectionOptions({ required this.allowMultiple, required this.selectFolders, required this.allowedTypes, }); bool allowMultiple; bool selectFolders; List<TypeGroup?> allowedTypes; Object encode() { final Map<Object?, Object?> pigeonMap = <Object?, Object?>{}; pigeonMap['allowMultiple'] = allowMultiple; pigeonMap['selectFolders'] = selectFolders; pigeonMap['allowedTypes'] = allowedTypes; return pigeonMap; } static SelectionOptions decode(Object message) { final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>; return SelectionOptions( allowMultiple: pigeonMap['allowMultiple']! as bool, selectFolders: pigeonMap['selectFolders']! as bool, allowedTypes: (pigeonMap['allowedTypes'] as List<Object?>?)!.cast<TypeGroup?>(), ); } } class _FileSelectorApiCodec extends StandardMessageCodec { const _FileSelectorApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is SelectionOptions) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is TypeGroup) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return SelectionOptions.decode(readValue(buffer)!); case 129: return TypeGroup.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class FileSelectorApi { /// Constructor for [FileSelectorApi]. 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. FileSelectorApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _FileSelectorApiCodec(); Future<List<String?>> showOpenDialog(SelectionOptions arg_options, String? arg_initialDirectory, String? arg_confirmButtonText) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.FileSelectorApi.showOpenDialog', codec, binaryMessenger: _binaryMessenger); final Map<Object?, Object?>? replyMap = await channel.send( <Object?>[arg_options, arg_initialDirectory, arg_confirmButtonText]) 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?>> showSaveDialog( SelectionOptions arg_options, String? arg_initialDirectory, String? arg_suggestedName, String? arg_confirmButtonText) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.FileSelectorApi.showSaveDialog', codec, binaryMessenger: _binaryMessenger); final Map<Object?, Object?>? replyMap = await channel.send(<Object?>[ arg_options, arg_initialDirectory, arg_suggestedName, arg_confirmButtonText ]) 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/file_selector/file_selector_windows/lib/src/messages.g.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector_windows/lib/src/messages.g.dart", "repo_id": "plugins", "token_count": 2176 }
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. // Autogenerated from Pigeon (v3.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon #ifndef PIGEON_MESSAGES_G_FILE_SELECTOR_WINDOWS_H_ #define PIGEON_MESSAGES_G_FILE_SELECTOR_WINDOWS_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 { /* Generated class from Pigeon. */ class FlutterError { public: FlutterError(const std::string& code) : code_(code) {} FlutterError(const std::string& code, const std::string& message) : code_(code), message_(message) {} FlutterError(const std::string& code, const std::string& message, const flutter::EncodableValue& details) : code_(code), message_(message), details_(details) {} const std::string& code() const { return code_; } const std::string& message() const { return message_; } const flutter::EncodableValue& details() const { return details_; } private: std::string code_; std::string message_; flutter::EncodableValue details_; }; template <class T> class ErrorOr { public: ErrorOr(const T& rhs) { new (&v_) T(rhs); } ErrorOr(const T&& rhs) { v_ = std::move(rhs); } ErrorOr(const FlutterError& rhs) { new (&v_) FlutterError(rhs); } ErrorOr(const FlutterError&& rhs) { v_ = std::move(rhs); } bool has_error() const { return std::holds_alternative<FlutterError>(v_); } const T& value() const { return std::get<T>(v_); }; const FlutterError& error() const { return std::get<FlutterError>(v_); }; private: friend class FileSelectorApi; ErrorOr() = default; T TakeValue() && { return std::get<T>(std::move(v_)); } std::variant<T, FlutterError> v_; }; /* Generated class from Pigeon that represents data sent in messages. */ class TypeGroup { public: TypeGroup(); const std::string& label() const; void set_label(std::string_view value_arg); const flutter::EncodableList& extensions() const; void set_extensions(const flutter::EncodableList& value_arg); private: TypeGroup(flutter::EncodableMap map); flutter::EncodableMap ToEncodableMap() const; friend class FileSelectorApi; friend class FileSelectorApiCodecSerializer; std::string label_; flutter::EncodableList extensions_; }; /* Generated class from Pigeon that represents data sent in messages. */ class SelectionOptions { public: SelectionOptions(); bool allow_multiple() const; void set_allow_multiple(bool value_arg); bool select_folders() const; void set_select_folders(bool value_arg); const flutter::EncodableList& allowed_types() const; void set_allowed_types(const flutter::EncodableList& value_arg); private: SelectionOptions(flutter::EncodableMap map); flutter::EncodableMap ToEncodableMap() const; friend class FileSelectorApi; friend class FileSelectorApiCodecSerializer; bool allow_multiple_; bool select_folders_; flutter::EncodableList allowed_types_; }; class FileSelectorApiCodecSerializer : public flutter::StandardCodecSerializer { public: inline static FileSelectorApiCodecSerializer& GetInstance() { static FileSelectorApiCodecSerializer sInstance; return sInstance; } FileSelectorApiCodecSerializer(); public: void WriteValue(const flutter::EncodableValue& value, flutter::ByteStreamWriter* stream) const override; protected: flutter::EncodableValue ReadValueOfType( uint8_t type, flutter::ByteStreamReader* stream) const override; }; /* Generated class from Pigeon that represents a handler of messages from * Flutter. */ class FileSelectorApi { public: FileSelectorApi(const FileSelectorApi&) = delete; FileSelectorApi& operator=(const FileSelectorApi&) = delete; virtual ~FileSelectorApi(){}; virtual ErrorOr<flutter::EncodableList> ShowOpenDialog( const SelectionOptions& options, const std::string* initial_directory, const std::string* confirm_button_text) = 0; virtual ErrorOr<flutter::EncodableList> ShowSaveDialog( const SelectionOptions& options, const std::string* initial_directory, const std::string* suggested_name, const std::string* confirm_button_text) = 0; /** The codec used by FileSelectorApi. */ static const flutter::StandardMessageCodec& GetCodec(); /** Sets up an instance of `FileSelectorApi` to handle messages through the * `binary_messenger`. */ static void SetUp(flutter::BinaryMessenger* binary_messenger, FileSelectorApi* api); static flutter::EncodableMap WrapError(std::string_view error_message); static flutter::EncodableMap WrapError(const FlutterError& error); protected: FileSelectorApi() = default; }; } // namespace file_selector_windows #endif // PIGEON_MESSAGES_G_FILE_SELECTOR_WINDOWS_H_
plugins/packages/file_selector/file_selector_windows/windows/messages.g.h/0
{ "file_path": "plugins/packages/file_selector/file_selector_windows/windows/messages.g.h", "repo_id": "plugins", "token_count": 1676 }
1,139
group 'io.flutter.plugins.flutter_plugin_android_lifecycle' version '1.0' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.2.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { compileSdkVersion 31 defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles 'proguard.txt' } lintOptions { disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' } dependencies { implementation "androidx.annotation:annotation:1.1.0" } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-core:5.1.1' }
plugins/packages/flutter_plugin_android_lifecycle/android/build.gradle/0
{ "file_path": "plugins/packages/flutter_plugin_android_lifecycle/android/build.gradle", "repo_id": "plugins", "token_count": 553 }
1,140
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '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 _mapWithPolylines(Set<Polyline> polylines) { return Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), polylines: polylines, ), ); } 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 polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToAdd.length, 1); final Polyline initializedPolyline = platformGoogleMap.polylinesToAdd.first; expect(initializedPolyline, equals(p1)); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToChange.isEmpty, true); }); testWidgets('Adding a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2')); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToAdd.length, 1); final Polyline addedPolyline = platformGoogleMap.polylinesToAdd.first; expect(addedPolyline, equals(p2)); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToChange.isEmpty, true); }); testWidgets('Removing a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylineIdsToRemove.length, 1); expect(platformGoogleMap.polylineIdsToRemove.first, equals(p1.polylineId)); expect(platformGoogleMap.polylinesToChange.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets('Updating a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_1'), geodesic: true); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.length, 1); expect(platformGoogleMap.polylinesToChange.first, equals(p2)); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets('Updating a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_1'), geodesic: true); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.length, 1); final Polyline update = platformGoogleMap.polylinesToChange.first; expect(update, equals(p2)); expect(update.geodesic, true); }); testWidgets('Mutate a polyline', (WidgetTester tester) async { final List<LatLng> points = <LatLng>[const LatLng(0.0, 0.0)]; final Polyline p1 = Polyline( polylineId: const PolylineId('polyline_1'), points: points, ); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); p1.points.add(const LatLng(1.0, 1.0)); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.length, 1); expect(platformGoogleMap.polylinesToChange.first, equals(p1)); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets('Multi Update', (WidgetTester tester) async { Polyline p1 = const Polyline(polylineId: PolylineId('polyline_1')); Polyline p2 = const Polyline(polylineId: PolylineId('polyline_2')); final Set<Polyline> prev = <Polyline>{p1, p2}; p1 = const Polyline(polylineId: PolylineId('polyline_1'), visible: false); p2 = const Polyline(polylineId: PolylineId('polyline_2'), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange, cur); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets('Multi Update', (WidgetTester tester) async { Polyline p2 = const Polyline(polylineId: PolylineId('polyline_2')); const Polyline p3 = Polyline(polylineId: PolylineId('polyline_3')); final Set<Polyline> prev = <Polyline>{p2, p3}; // p1 is added, p2 is updated, p3 is removed. const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); p2 = const Polyline(polylineId: PolylineId('polyline_2'), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.length, 1); expect(platformGoogleMap.polylinesToAdd.length, 1); expect(platformGoogleMap.polylineIdsToRemove.length, 1); expect(platformGoogleMap.polylinesToChange.first, equals(p2)); expect(platformGoogleMap.polylinesToAdd.first, equals(p1)); expect(platformGoogleMap.polylineIdsToRemove.first, equals(p3.polylineId)); }); testWidgets('Partial Update', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2')); Polyline p3 = const Polyline(polylineId: PolylineId('polyline_3')); final Set<Polyline> prev = <Polyline>{p1, p2, p3}; p3 = const Polyline(polylineId: PolylineId('polyline_3'), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2, p3}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange, <Polyline>{p3}); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.isEmpty, true); }); testWidgets('Update non platform related attr', (WidgetTester tester) async { Polyline p1 = const Polyline(polylineId: PolylineId('polyline_1')); final Set<Polyline> prev = <Polyline>{p1}; p1 = Polyline(polylineId: const PolylineId('polyline_1'), onTap: () {}); final Set<Polyline> cur = <Polyline>{p1}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.polylinesToChange.isEmpty, true); expect(platformGoogleMap.polylineIdsToRemove.isEmpty, true); expect(platformGoogleMap.polylinesToAdd.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/polyline_updates_test.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart", "repo_id": "plugins", "token_count": 3256 }
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. package io.flutter.plugins.googlemaps; import android.content.Context; import com.google.android.gms.maps.model.CameraPosition; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.StandardMessageCodec; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugin.platform.PlatformViewFactory; import java.util.List; import java.util.Map; public class GoogleMapFactory extends PlatformViewFactory { private final BinaryMessenger binaryMessenger; private final LifecycleProvider lifecycleProvider; private final GoogleMapInitializer googleMapInitializer; GoogleMapFactory( BinaryMessenger binaryMessenger, Context context, LifecycleProvider lifecycleProvider) { super(StandardMessageCodec.INSTANCE); this.binaryMessenger = binaryMessenger; this.lifecycleProvider = lifecycleProvider; this.googleMapInitializer = new GoogleMapInitializer(context, binaryMessenger); } @SuppressWarnings("unchecked") @Override public PlatformView create(Context context, int id, Object args) { Map<String, Object> params = (Map<String, Object>) args; final GoogleMapBuilder builder = new GoogleMapBuilder(); Convert.interpretGoogleMapOptions(params.get("options"), builder); if (params.containsKey("initialCameraPosition")) { CameraPosition position = Convert.toCameraPosition(params.get("initialCameraPosition")); builder.setInitialCameraPosition(position); } if (params.containsKey("markersToAdd")) { builder.setInitialMarkers(params.get("markersToAdd")); } if (params.containsKey("polygonsToAdd")) { builder.setInitialPolygons(params.get("polygonsToAdd")); } if (params.containsKey("polylinesToAdd")) { builder.setInitialPolylines(params.get("polylinesToAdd")); } if (params.containsKey("circlesToAdd")) { builder.setInitialCircles(params.get("circlesToAdd")); } if (params.containsKey("tileOverlaysToAdd")) { builder.setInitialTileOverlays((List<Map<String, ?>>) params.get("tileOverlaysToAdd")); } return builder.build(id, context, binaryMessenger, lifecycleProvider); } }
plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapFactory.java/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapFactory.java", "repo_id": "plugins", "token_count": 730 }
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.googlemaps; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import com.google.android.gms.internal.maps.zzag; import com.google.android.gms.maps.model.Polyline; import org.junit.Test; import org.mockito.Mockito; public class PolylineControllerTest { @Test public void controller_SetsStrokeDensity() { final zzag z = mock(zzag.class); final Polyline polyline = spy(new Polyline(z)); final float density = 5; final float strokeWidth = 3; final PolylineController controller = new PolylineController(polyline, false, density); controller.setWidth(strokeWidth); Mockito.verify(polyline).setWidth(density * strokeWidth); } }
plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/PolylineControllerTest.java/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/PolylineControllerTest.java", "repo_id": "plugins", "token_count": 288 }
1,143
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:js_util' show getProperty; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps/google_maps.dart' as gmaps; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:google_maps_flutter_web/google_maps_flutter_web.dart'; import 'package:integration_test/integration_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'google_maps_plugin_test.mocks.dart'; @GenerateMocks(<Type>[], customMocks: <MockSpec<dynamic>>[ MockSpec<GoogleMapController>(onMissingStub: OnMissingStub.returnDefault), ]) /// Test GoogleMapsPlugin void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('GoogleMapsPlugin', () { late MockGoogleMapController controller; late GoogleMapsPlugin plugin; late Completer<int> reportedMapIdCompleter; int numberOnPlatformViewCreatedCalls = 0; void onPlatformViewCreated(int id) { reportedMapIdCompleter.complete(id); numberOnPlatformViewCreatedCalls++; } setUp(() { controller = MockGoogleMapController(); plugin = GoogleMapsPlugin(); reportedMapIdCompleter = Completer<int>(); }); group('init/dispose', () { group('before buildWidget', () { testWidgets('init throws assertion', (WidgetTester tester) async { expect(() => plugin.init(0), throwsAssertionError); }); }); group('after buildWidget', () { setUp(() { plugin.debugSetMapById(<int, GoogleMapController>{0: controller}); }); testWidgets('cannot call methods after dispose', (WidgetTester tester) async { plugin.dispose(mapId: 0); verify(controller.dispose()); expect( () => plugin.init(0), throwsAssertionError, reason: 'Method calls should fail after dispose.', ); }); }); }); group('buildView', () { const int testMapId = 33930; const CameraPosition initialCameraPosition = CameraPosition(target: LatLng(0, 0)); testWidgets( 'returns an HtmlElementView and caches the controller for later', (WidgetTester tester) async { final Map<int, GoogleMapController> cache = <int, GoogleMapController>{}; plugin.debugSetMapById(cache); final Widget widget = plugin.buildViewWithConfiguration( testMapId, onPlatformViewCreated, widgetConfiguration: const MapWidgetConfiguration( initialCameraPosition: initialCameraPosition, textDirection: TextDirection.ltr, ), ); expect(widget, isA<HtmlElementView>()); expect( (widget as HtmlElementView).viewType, contains('$testMapId'), reason: 'view type should contain the mapId passed when creating the map.', ); expect(cache, contains(testMapId)); expect( cache[testMapId], isNotNull, reason: 'cached controller cannot be null.', ); expect( cache[testMapId]!.isInitialized, isTrue, reason: 'buildView calls init on the controller', ); }); testWidgets('returns cached instance if it already exists', (WidgetTester tester) async { const HtmlElementView expected = HtmlElementView(viewType: 'only-for-testing'); when(controller.widget).thenReturn(expected); plugin.debugSetMapById(<int, GoogleMapController>{ testMapId: controller, }); final Widget widget = plugin.buildViewWithConfiguration( testMapId, onPlatformViewCreated, widgetConfiguration: const MapWidgetConfiguration( initialCameraPosition: initialCameraPosition, textDirection: TextDirection.ltr, ), ); expect(widget, equals(expected)); }); testWidgets( 'asynchronously reports onPlatformViewCreated the first time it happens', (WidgetTester tester) async { final Map<int, GoogleMapController> cache = <int, GoogleMapController>{}; plugin.debugSetMapById(cache); plugin.buildViewWithConfiguration( testMapId, onPlatformViewCreated, widgetConfiguration: const MapWidgetConfiguration( initialCameraPosition: initialCameraPosition, textDirection: TextDirection.ltr, ), ); // Simulate Google Maps JS SDK being "ready" cache[testMapId]!.stream.add(WebMapReadyEvent(testMapId)); expect( cache[testMapId]!.isInitialized, isTrue, reason: 'buildView calls init on the controller', ); expect( await reportedMapIdCompleter.future, testMapId, reason: 'Should call onPlatformViewCreated with the mapId', ); // Fire repeated event again... cache[testMapId]!.stream.add(WebMapReadyEvent(testMapId)); expect( numberOnPlatformViewCreatedCalls, equals(1), reason: 'Should not call onPlatformViewCreated for the same controller multiple times', ); }); }); group('setMapStyles', () { const String mapStyle = ''' [{ "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [{"color": "#6b9a76"}] }]'''; testWidgets('translates styles for controller', (WidgetTester tester) async { plugin.debugSetMapById(<int, GoogleMapController>{0: controller}); await plugin.setMapStyle(mapStyle, mapId: 0); final dynamic captured = verify(controller.updateStyles(captureThat(isList))).captured[0]; final List<gmaps.MapTypeStyle> styles = captured as List<gmaps.MapTypeStyle>; expect(styles.length, 1); // Let's peek inside the styles... final gmaps.MapTypeStyle style = styles[0]; expect(style.featureType, 'poi.park'); expect(style.elementType, 'labels.text.fill'); expect(style.stylers?.length, 1); expect(getProperty<String>(style.stylers![0]!, 'color'), '#6b9a76'); }); }); group('Noop methods:', () { const int mapId = 0; setUp(() { plugin.debugSetMapById(<int, GoogleMapController>{mapId: controller}); }); // Options testWidgets('updateTileOverlays', (WidgetTester tester) async { final Future<void> update = plugin.updateTileOverlays( mapId: mapId, newTileOverlays: <TileOverlay>{}, ); expect(update, completion(null)); }); testWidgets('updateTileOverlays', (WidgetTester tester) async { final Future<void> update = plugin.clearTileCache( const TileOverlayId('any'), mapId: mapId, ); expect(update, completion(null)); }); }); // These methods only pass-through values from the plugin to the controller // so we verify them all together here... group('Pass-through methods:', () { const int mapId = 0; setUp(() { plugin.debugSetMapById(<int, GoogleMapController>{mapId: controller}); }); // Options testWidgets('updateMapConfiguration', (WidgetTester tester) async { const MapConfiguration configuration = MapConfiguration(mapType: MapType.satellite); await plugin.updateMapConfiguration(configuration, mapId: mapId); verify(controller.updateMapConfiguration(configuration)); }); // Geometry testWidgets('updateMarkers', (WidgetTester tester) async { final MarkerUpdates expectedUpdates = MarkerUpdates.from( const <Marker>{}, const <Marker>{}, ); await plugin.updateMarkers(expectedUpdates, mapId: mapId); verify(controller.updateMarkers(expectedUpdates)); }); testWidgets('updatePolygons', (WidgetTester tester) async { final PolygonUpdates expectedUpdates = PolygonUpdates.from( const <Polygon>{}, const <Polygon>{}, ); await plugin.updatePolygons(expectedUpdates, mapId: mapId); verify(controller.updatePolygons(expectedUpdates)); }); testWidgets('updatePolylines', (WidgetTester tester) async { final PolylineUpdates expectedUpdates = PolylineUpdates.from( const <Polyline>{}, const <Polyline>{}, ); await plugin.updatePolylines(expectedUpdates, mapId: mapId); verify(controller.updatePolylines(expectedUpdates)); }); testWidgets('updateCircles', (WidgetTester tester) async { final CircleUpdates expectedUpdates = CircleUpdates.from( const <Circle>{}, const <Circle>{}, ); await plugin.updateCircles(expectedUpdates, mapId: mapId); verify(controller.updateCircles(expectedUpdates)); }); // Camera testWidgets('animateCamera', (WidgetTester tester) async { final CameraUpdate expectedUpdates = CameraUpdate.newLatLng( const LatLng(43.3626, -5.8433), ); await plugin.animateCamera(expectedUpdates, mapId: mapId); verify(controller.moveCamera(expectedUpdates)); }); testWidgets('moveCamera', (WidgetTester tester) async { final CameraUpdate expectedUpdates = CameraUpdate.newLatLng( const LatLng(43.3628, -5.8478), ); await plugin.moveCamera(expectedUpdates, mapId: mapId); verify(controller.moveCamera(expectedUpdates)); }); // Viewport testWidgets('getVisibleRegion', (WidgetTester tester) async { when(controller.getVisibleRegion()) .thenAnswer((_) async => LatLngBounds( northeast: const LatLng(47.2359634, -68.0192019), southwest: const LatLng(34.5019594, -120.4974629), )); await plugin.getVisibleRegion(mapId: mapId); verify(controller.getVisibleRegion()); }); testWidgets('getZoomLevel', (WidgetTester tester) async { when(controller.getZoomLevel()).thenAnswer((_) async => 10); await plugin.getZoomLevel(mapId: mapId); verify(controller.getZoomLevel()); }); testWidgets('getScreenCoordinate', (WidgetTester tester) async { when(controller.getScreenCoordinate(any)).thenAnswer( (_) async => const ScreenCoordinate(x: 320, y: 240) // fake return ); const LatLng latLng = LatLng(43.3613, -5.8499); await plugin.getScreenCoordinate(latLng, mapId: mapId); verify(controller.getScreenCoordinate(latLng)); }); testWidgets('getLatLng', (WidgetTester tester) async { when(controller.getLatLng(any)).thenAnswer( (_) async => const LatLng(43.3613, -5.8499) // fake return ); const ScreenCoordinate coordinates = ScreenCoordinate(x: 19, y: 26); await plugin.getLatLng(coordinates, mapId: mapId); verify(controller.getLatLng(coordinates)); }); // InfoWindows testWidgets('showMarkerInfoWindow', (WidgetTester tester) async { const MarkerId markerId = MarkerId('testing-123'); await plugin.showMarkerInfoWindow(markerId, mapId: mapId); verify(controller.showInfoWindow(markerId)); }); testWidgets('hideMarkerInfoWindow', (WidgetTester tester) async { const MarkerId markerId = MarkerId('testing-123'); await plugin.hideMarkerInfoWindow(markerId, mapId: mapId); verify(controller.hideInfoWindow(markerId)); }); testWidgets('isMarkerInfoWindowShown', (WidgetTester tester) async { when(controller.isInfoWindowShown(any)).thenReturn(true); const MarkerId markerId = MarkerId('testing-123'); await plugin.isMarkerInfoWindowShown(markerId, mapId: mapId); verify(controller.isInfoWindowShown(markerId)); }); }); // Verify all event streams are filtered correctly from the main one... group('Event Streams', () { const int mapId = 0; late StreamController<MapEvent<Object?>> streamController; setUp(() { streamController = StreamController<MapEvent<Object?>>.broadcast(); when(controller.events) .thenAnswer((Invocation realInvocation) => streamController.stream); plugin.debugSetMapById(<int, GoogleMapController>{mapId: controller}); }); // Dispatches a few events in the global streamController, and expects *only* the passed event to be there. Future<void> testStreamFiltering( Stream<MapEvent<Object?>> stream, MapEvent<Object?> event) async { Timer.run(() { streamController.add(_OtherMapEvent(mapId)); streamController.add(event); streamController.add(_OtherMapEvent(mapId)); streamController.close(); }); final List<MapEvent<Object?>> events = await stream.toList(); expect(events.length, 1); expect(events[0], event); } // Camera events testWidgets('onCameraMoveStarted', (WidgetTester tester) async { final CameraMoveStartedEvent event = CameraMoveStartedEvent(mapId); final Stream<CameraMoveStartedEvent> stream = plugin.onCameraMoveStarted(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onCameraMoveStarted', (WidgetTester tester) async { final CameraMoveEvent event = CameraMoveEvent( mapId, const CameraPosition( target: LatLng(43.3790, -5.8660), ), ); final Stream<CameraMoveEvent> stream = plugin.onCameraMove(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onCameraIdle', (WidgetTester tester) async { final CameraIdleEvent event = CameraIdleEvent(mapId); final Stream<CameraIdleEvent> stream = plugin.onCameraIdle(mapId: mapId); await testStreamFiltering(stream, event); }); // Marker events testWidgets('onMarkerTap', (WidgetTester tester) async { final MarkerTapEvent event = MarkerTapEvent( mapId, const MarkerId('test-123'), ); final Stream<MarkerTapEvent> stream = plugin.onMarkerTap(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onInfoWindowTap', (WidgetTester tester) async { final InfoWindowTapEvent event = InfoWindowTapEvent( mapId, const MarkerId('test-123'), ); final Stream<InfoWindowTapEvent> stream = plugin.onInfoWindowTap(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onMarkerDragStart', (WidgetTester tester) async { final MarkerDragStartEvent event = MarkerDragStartEvent( mapId, const LatLng(43.3677, -5.8372), const MarkerId('test-123'), ); final Stream<MarkerDragStartEvent> stream = plugin.onMarkerDragStart(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onMarkerDrag', (WidgetTester tester) async { final MarkerDragEvent event = MarkerDragEvent( mapId, const LatLng(43.3677, -5.8372), const MarkerId('test-123'), ); final Stream<MarkerDragEvent> stream = plugin.onMarkerDrag(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onMarkerDragEnd', (WidgetTester tester) async { final MarkerDragEndEvent event = MarkerDragEndEvent( mapId, const LatLng(43.3677, -5.8372), const MarkerId('test-123'), ); final Stream<MarkerDragEndEvent> stream = plugin.onMarkerDragEnd(mapId: mapId); await testStreamFiltering(stream, event); }); // Geometry testWidgets('onPolygonTap', (WidgetTester tester) async { final PolygonTapEvent event = PolygonTapEvent( mapId, const PolygonId('test-123'), ); final Stream<PolygonTapEvent> stream = plugin.onPolygonTap(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onPolylineTap', (WidgetTester tester) async { final PolylineTapEvent event = PolylineTapEvent( mapId, const PolylineId('test-123'), ); final Stream<PolylineTapEvent> stream = plugin.onPolylineTap(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onCircleTap', (WidgetTester tester) async { final CircleTapEvent event = CircleTapEvent( mapId, const CircleId('test-123'), ); final Stream<CircleTapEvent> stream = plugin.onCircleTap(mapId: mapId); await testStreamFiltering(stream, event); }); // Map taps testWidgets('onTap', (WidgetTester tester) async { final MapTapEvent event = MapTapEvent( mapId, const LatLng(43.3597, -5.8458), ); final Stream<MapTapEvent> stream = plugin.onTap(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onLongPress', (WidgetTester tester) async { final MapLongPressEvent event = MapLongPressEvent( mapId, const LatLng(43.3608, -5.8425), ); final Stream<MapLongPressEvent> stream = plugin.onLongPress(mapId: mapId); await testStreamFiltering(stream, event); }); }); }); } class _OtherMapEvent extends MapEvent<Object?> { _OtherMapEvent(int mapId) : super(mapId, null); }
plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart", "repo_id": "plugins", "token_count": 7653 }
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. part of google_maps_flutter_web; /// This class manages all the [CircleController]s associated to a [GoogleMapController]. class CirclesController extends GeometryController { /// Initialize the cache. The [StreamController] comes from the [GoogleMapController], and is shared with other controllers. CirclesController({ required StreamController<MapEvent<Object?>> stream, }) : _streamController = stream, _circleIdToController = <CircleId, CircleController>{}; // A cache of [CircleController]s indexed by their [CircleId]. final Map<CircleId, CircleController> _circleIdToController; // The stream over which circles broadcast their events final StreamController<MapEvent<Object?>> _streamController; /// Returns the cache of [CircleController]s. Test only. @visibleForTesting Map<CircleId, CircleController> get circles => _circleIdToController; /// Adds a set of [Circle] objects to the cache. /// /// Wraps each [Circle] into its corresponding [CircleController]. void addCircles(Set<Circle> circlesToAdd) { circlesToAdd.forEach(_addCircle); } void _addCircle(Circle circle) { if (circle == null) { return; } final gmaps.CircleOptions circleOptions = _circleOptionsFromCircle(circle); final gmaps.Circle gmCircle = gmaps.Circle(circleOptions)..map = googleMap; final CircleController controller = CircleController( circle: gmCircle, consumeTapEvents: circle.consumeTapEvents, onTap: () { _onCircleTap(circle.circleId); }); _circleIdToController[circle.circleId] = controller; } /// Updates a set of [Circle] objects with new options. void changeCircles(Set<Circle> circlesToChange) { circlesToChange.forEach(_changeCircle); } void _changeCircle(Circle circle) { final CircleController? circleController = _circleIdToController[circle.circleId]; circleController?.update(_circleOptionsFromCircle(circle)); } /// Removes a set of [CircleId]s from the cache. void removeCircles(Set<CircleId> circleIdsToRemove) { circleIdsToRemove.forEach(_removeCircle); } // Removes a circle and its controller by its [CircleId]. void _removeCircle(CircleId circleId) { final CircleController? circleController = _circleIdToController[circleId]; circleController?.remove(); _circleIdToController.remove(circleId); } // Handles the global onCircleTap function to funnel events from circles into the stream. bool _onCircleTap(CircleId circleId) { // Have you ended here on your debugging? Is this wrong? // Comment here: https://github.com/flutter/flutter/issues/64084 _streamController.add(CircleTapEvent(mapId, circleId)); return _circleIdToController[circleId]?.consumeTapEvents ?? false; } }
plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/circles.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/circles.dart", "repo_id": "plugins", "token_count": 934 }
1,145
# google\_sign\_in\_android The Android implementation of [`google_sign_in`][1]. ## Usage This package is [endorsed][2], which means you can simply use `google_sign_in` normally. This package will be automatically included in your app when you do. [1]: https://pub.dev/packages/google_sign_in [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
plugins/packages/google_sign_in/google_sign_in_android/README.md/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_android/README.md", "repo_id": "plugins", "token_count": 128 }
1,146
name: google_sign_in_example description: Example of Google Sign-In plugin. publish_to: none environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter google_sign_in_android: # When depending on this package from a real application you should use: # google_sign_in_android: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ google_sign_in_platform_interface: ^2.2.0 http: ^0.13.0 dev_dependencies: espresso: ^0.2.0 flutter_driver: sdk: flutter flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
plugins/packages/google_sign_in/google_sign_in_android/example/pubspec.yaml/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_android/example/pubspec.yaml", "repo_id": "plugins", "token_count": 309 }
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. package io.flutter.plugins.imagepicker; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import android.Manifest; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class ImagePickerDelegateTest { private static final Double WIDTH = 10.0; private static final Double HEIGHT = 10.0; private static final Double MAX_DURATION = 10.0; private static final Integer IMAGE_QUALITY = 90; @Mock Activity mockActivity; @Mock ImageResizer mockImageResizer; @Mock MethodCall mockMethodCall; @Mock MethodChannel.Result mockResult; @Mock ImagePickerDelegate.PermissionManager mockPermissionManager; @Mock FileUtils mockFileUtils; @Mock Intent mockIntent; @Mock ImagePickerCache cache; ImagePickerDelegate.FileUriResolver mockFileUriResolver; MockedStatic<File> mockStaticFile; private static class MockFileUriResolver implements ImagePickerDelegate.FileUriResolver { @Override public Uri resolveFileProviderUriForFile(String fileProviderName, File imageFile) { return null; } @Override public void getFullImagePath(Uri imageUri, ImagePickerDelegate.OnPathReadyListener listener) { listener.onPathReady("pathFromUri"); } } @Before public void setUp() { MockitoAnnotations.initMocks(this); mockStaticFile = Mockito.mockStatic(File.class); mockStaticFile .when(() -> File.createTempFile(any(), any(), any())) .thenReturn(new File("/tmpfile")); when(mockActivity.getPackageName()).thenReturn("com.example.test"); when(mockActivity.getPackageManager()).thenReturn(mock(PackageManager.class)); when(mockFileUtils.getPathFromUri(any(Context.class), any(Uri.class))) .thenReturn("pathFromUri"); when(mockImageResizer.resizeImageIfNeeded("pathFromUri", null, null, null)) .thenReturn("originalPath"); when(mockImageResizer.resizeImageIfNeeded("pathFromUri", null, null, IMAGE_QUALITY)) .thenReturn("originalPath"); when(mockImageResizer.resizeImageIfNeeded("pathFromUri", WIDTH, HEIGHT, null)) .thenReturn("scaledPath"); when(mockImageResizer.resizeImageIfNeeded("pathFromUri", WIDTH, null, null)) .thenReturn("scaledPath"); when(mockImageResizer.resizeImageIfNeeded("pathFromUri", null, HEIGHT, null)) .thenReturn("scaledPath"); mockFileUriResolver = new MockFileUriResolver(); Uri mockUri = mock(Uri.class); when(mockIntent.getData()).thenReturn(mockUri); } @After public void tearDown() { mockStaticFile.close(); } @Test public void whenConstructed_setsCorrectFileProviderName() { ImagePickerDelegate delegate = createDelegate(); assertThat(delegate.fileProviderName, equalTo("com.example.test.flutter.image_provider")); } @Test public void chooseImageFromGallery_WhenPendingResultExists_FinishesWithAlreadyActiveError() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.chooseImageFromGallery(mockMethodCall, mockResult); verifyFinishedWithAlreadyActiveError(); verifyNoMoreInteractions(mockResult); } @Test public void chooseMultiImageFromGallery_WhenPendingResultExists_FinishesWithAlreadyActiveError() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.chooseMultiImageFromGallery(mockMethodCall, mockResult); verifyFinishedWithAlreadyActiveError(); verifyNoMoreInteractions(mockResult); } public void chooseImageFromGallery_WhenHasExternalStoragePermission_LaunchesChooseFromGalleryIntent() { when(mockPermissionManager.isPermissionGranted(Manifest.permission.READ_EXTERNAL_STORAGE)) .thenReturn(true); ImagePickerDelegate delegate = createDelegate(); delegate.chooseImageFromGallery(mockMethodCall, mockResult); verify(mockActivity) .startActivityForResult( any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY)); } @Test public void takeImageWithCamera_WhenPendingResultExists_FinishesWithAlreadyActiveError() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.takeImageWithCamera(mockMethodCall, mockResult); verifyFinishedWithAlreadyActiveError(); verifyNoMoreInteractions(mockResult); } @Test public void takeImageWithCamera_WhenHasNoCameraPermission_RequestsForPermission() { when(mockPermissionManager.isPermissionGranted(Manifest.permission.CAMERA)).thenReturn(false); when(mockPermissionManager.needRequestCameraPermission()).thenReturn(true); ImagePickerDelegate delegate = createDelegate(); delegate.takeImageWithCamera(mockMethodCall, mockResult); verify(mockPermissionManager) .askForPermission( Manifest.permission.CAMERA, ImagePickerDelegate.REQUEST_CAMERA_IMAGE_PERMISSION); } @Test public void takeImageWithCamera_WhenCameraPermissionNotPresent_RequestsForPermission() { when(mockPermissionManager.needRequestCameraPermission()).thenReturn(false); ImagePickerDelegate delegate = createDelegate(); delegate.takeImageWithCamera(mockMethodCall, mockResult); verify(mockActivity) .startActivityForResult( any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA)); } @Test public void takeImageWithCamera_WhenHasCameraPermission_AndAnActivityCanHandleCameraIntent_LaunchesTakeWithCameraIntent() { when(mockPermissionManager.isPermissionGranted(Manifest.permission.CAMERA)).thenReturn(true); ImagePickerDelegate delegate = createDelegate(); delegate.takeImageWithCamera(mockMethodCall, mockResult); verify(mockActivity) .startActivityForResult( any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA)); } @Test public void takeImageWithCamera_WhenHasCameraPermission_AndNoActivityToHandleCameraIntent_FinishesWithNoCamerasAvailableError() { when(mockPermissionManager.isPermissionGranted(Manifest.permission.CAMERA)).thenReturn(true); doThrow(ActivityNotFoundException.class) .when(mockActivity) .startActivityForResult(any(Intent.class), anyInt()); ImagePickerDelegate delegate = createDelegate(); delegate.takeImageWithCamera(mockMethodCall, mockResult); verify(mockResult) .error("no_available_camera", "No cameras available for taking pictures.", null); verifyNoMoreInteractions(mockResult); } @Test public void takeImageWithCamera_WritesImageToCacheDirectory() { when(mockPermissionManager.isPermissionGranted(Manifest.permission.CAMERA)).thenReturn(true); ImagePickerDelegate delegate = createDelegate(); delegate.takeImageWithCamera(mockMethodCall, mockResult); mockStaticFile.verify( () -> File.createTempFile(any(), eq(".jpg"), eq(new File("/image_picker_cache"))), times(1)); } @Test public void onRequestPermissionsResult_WhenCameraPermissionDenied_FinishesWithError() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onRequestPermissionsResult( ImagePickerDelegate.REQUEST_CAMERA_IMAGE_PERMISSION, new String[] {Manifest.permission.CAMERA}, new int[] {PackageManager.PERMISSION_DENIED}); verify(mockResult).error("camera_access_denied", "The user did not allow camera access.", null); verifyNoMoreInteractions(mockResult); } @Test public void onRequestTakeVideoPermissionsResult_WhenCameraPermissionGranted_LaunchesTakeVideoWithCameraIntent() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onRequestPermissionsResult( ImagePickerDelegate.REQUEST_CAMERA_VIDEO_PERMISSION, new String[] {Manifest.permission.CAMERA}, new int[] {PackageManager.PERMISSION_GRANTED}); verify(mockActivity) .startActivityForResult( any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA)); } @Test public void onRequestTakeImagePermissionsResult_WhenCameraPermissionGranted_LaunchesTakeWithCameraIntent() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onRequestPermissionsResult( ImagePickerDelegate.REQUEST_CAMERA_IMAGE_PERMISSION, new String[] {Manifest.permission.CAMERA}, new int[] {PackageManager.PERMISSION_GRANTED}); verify(mockActivity) .startActivityForResult( any(Intent.class), eq(ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA)); } @Test public void onActivityResult_WhenPickFromGalleryCanceled_FinishesWithNull() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_CANCELED, null); verify(mockResult).success(null); verifyNoMoreInteractions(mockResult); } @Test public void onActivityResult_WhenPickFromGalleryCanceled_StoresNothingInCache() { ImagePickerDelegate delegate = createDelegate(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_CANCELED, null); verify(cache, never()).saveResult(any(), any(), any()); } @Test public void onActivityResult_WhenImagePickedFromGallery_AndNoResizeNeeded_FinishesWithImagePath() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent); verify(mockResult).success("originalPath"); verifyNoMoreInteractions(mockResult); } @Test public void onActivityResult_WhenImagePickedFromGallery_AndNoResizeNeeded_StoresImageInCache() { ImagePickerDelegate delegate = createDelegate(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent); ArgumentCaptor<ArrayList<String>> pathListCapture = ArgumentCaptor.forClass(ArrayList.class); verify(cache, times(1)).saveResult(pathListCapture.capture(), any(), any()); assertEquals("pathFromUri", pathListCapture.getValue().get(0)); } @Test public void onActivityResult_WhenImagePickedFromGallery_AndResizeNeeded_FinishesWithScaledImagePath() { when(mockMethodCall.argument("maxWidth")).thenReturn(WIDTH); ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent); verify(mockResult).success("scaledPath"); verifyNoMoreInteractions(mockResult); } @Test public void onActivityResult_WhenVideoPickedFromGallery_AndResizeParametersSupplied_FinishesWithFilePath() { when(mockMethodCall.argument("maxWidth")).thenReturn(WIDTH); ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY, Activity.RESULT_OK, mockIntent); verify(mockResult).success("pathFromUri"); verifyNoMoreInteractions(mockResult); } @Test public void onActivityResult_WhenTakeImageWithCameraCanceled_FinishesWithNull() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA, Activity.RESULT_CANCELED, null); verify(mockResult).success(null); verifyNoMoreInteractions(mockResult); } @Test public void onActivityResult_WhenImageTakenWithCamera_AndNoResizeNeeded_FinishesWithImagePath() { ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA, Activity.RESULT_OK, mockIntent); verify(mockResult).success("originalPath"); verifyNoMoreInteractions(mockResult); } @Test public void onActivityResult_WhenImageTakenWithCamera_AndResizeNeeded_FinishesWithScaledImagePath() { when(mockMethodCall.argument("maxWidth")).thenReturn(WIDTH); ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA, Activity.RESULT_OK, mockIntent); verify(mockResult).success("scaledPath"); verifyNoMoreInteractions(mockResult); } @Test public void onActivityResult_WhenVideoTakenWithCamera_AndResizeParametersSupplied_FinishesWithFilePath() { when(mockMethodCall.argument("maxWidth")).thenReturn(WIDTH); ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA, Activity.RESULT_OK, mockIntent); verify(mockResult).success("pathFromUri"); verifyNoMoreInteractions(mockResult); } @Test public void onActivityResult_WhenVideoTakenWithCamera_AndMaxDurationParametersSupplied_FinishesWithFilePath() { when(mockMethodCall.argument("maxDuration")).thenReturn(MAX_DURATION); ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall(); delegate.onActivityResult( ImagePickerDelegate.REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA, Activity.RESULT_OK, mockIntent); verify(mockResult).success("pathFromUri"); verifyNoMoreInteractions(mockResult); } @Test public void retrieveLostImage_ShouldBeAbleToReturnLastItemFromResultMapWhenSingleFileIsRecovered() { Map<String, Object> resultMap = new HashMap<>(); ArrayList<String> pathList = new ArrayList<>(); pathList.add("/example/first_item"); pathList.add("/example/last_item"); resultMap.put("pathList", pathList); when(mockImageResizer.resizeImageIfNeeded(pathList.get(0), null, null, 100)) .thenReturn(pathList.get(0)); when(mockImageResizer.resizeImageIfNeeded(pathList.get(1), null, null, 100)) .thenReturn(pathList.get(1)); when(cache.getCacheMap()).thenReturn(resultMap); MethodChannel.Result mockResult = mock(MethodChannel.Result.class); ImagePickerDelegate mockDelegate = createDelegate(); ArgumentCaptor<Map<String, Object>> valueCapture = ArgumentCaptor.forClass(Map.class); doNothing().when(mockResult).success(valueCapture.capture()); mockDelegate.retrieveLostImage(mockResult); assertEquals("/example/last_item", valueCapture.getValue().get("path")); } private ImagePickerDelegate createDelegate() { return new ImagePickerDelegate( mockActivity, new File("/image_picker_cache"), mockImageResizer, null, null, cache, mockPermissionManager, mockFileUriResolver, mockFileUtils); } private ImagePickerDelegate createDelegateWithPendingResultAndMethodCall() { return new ImagePickerDelegate( mockActivity, new File("/image_picker_cache"), mockImageResizer, mockResult, mockMethodCall, cache, mockPermissionManager, mockFileUriResolver, mockFileUtils); } private void verifyFinishedWithAlreadyActiveError() { verify(mockResult).error("already_active", "Image picker is already active", null); } }
plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerDelegateTest.java/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerDelegateTest.java", "repo_id": "plugins", "token_count": 5850 }
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 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/image_picker_android'); /// An Android implementation of [ImagePickerPlatform]. class ImagePickerAndroid extends ImagePickerPlatform { /// The MethodChannel that is being used by this implementation of the plugin. @visibleForTesting MethodChannel get channel => _channel; /// Registers this class as the default platform implementation. static void registerWith() { ImagePickerPlatform.instance = ImagePickerAndroid(); } @override Future<PickedFile?> pickImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final String? path = await _getImagePath( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ); return path != null ? PickedFile(path) : null; } @override Future<List<PickedFile>?> pickMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { final List<dynamic>? paths = await _getMultiImagePath( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ); if (paths == null) { return null; } return paths.map((dynamic path) => PickedFile(path as String)).toList(); } Future<List<dynamic>?> _getMultiImagePath({ double? maxWidth, double? maxHeight, int? imageQuality, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } return _channel.invokeMethod<List<dynamic>?>( 'pickMultiImage', <String, dynamic>{ 'maxWidth': maxWidth, 'maxHeight': maxHeight, 'imageQuality': imageQuality, }, ); } Future<String?> _getImagePath({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, bool requestFullMetadata = true, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } return _channel.invokeMethod<String>( 'pickImage', <String, dynamic>{ 'source': source.index, 'maxWidth': maxWidth, 'maxHeight': maxHeight, 'imageQuality': imageQuality, 'cameraDevice': preferredCameraDevice.index, 'requestFullMetadata': requestFullMetadata, }, ); } @override Future<PickedFile?> pickVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? path = await _getVideoPath( source: source, maxDuration: maxDuration, preferredCameraDevice: preferredCameraDevice, ); return path != null ? PickedFile(path) : null; } Future<String?> _getVideoPath({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) { return _channel.invokeMethod<String>( 'pickVideo', <String, dynamic>{ 'source': source.index, 'maxDuration': maxDuration?.inSeconds, 'cameraDevice': preferredCameraDevice.index }, ); } @override Future<XFile?> getImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final String? path = await _getImagePath( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ); return path != null ? XFile(path) : null; } @override Future<XFile?> getImageFromSource({ required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) async { final String? path = await _getImagePath( source: source, maxHeight: options.maxHeight, maxWidth: options.maxWidth, imageQuality: options.imageQuality, preferredCameraDevice: options.preferredCameraDevice, requestFullMetadata: options.requestFullMetadata, ); return path != null ? XFile(path) : null; } @override Future<List<XFile>?> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { final List<dynamic>? paths = await _getMultiImagePath( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ); if (paths == null) { return null; } return paths.map((dynamic path) => XFile(path as String)).toList(); } @override Future<XFile?> getVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? path = await _getVideoPath( source: source, maxDuration: maxDuration, preferredCameraDevice: preferredCameraDevice, ); return path != null ? XFile(path) : null; } @override Future<LostData> retrieveLostData() async { final LostDataResponse result = await getLostData(); if (result.isEmpty) { return LostData.empty(); } return LostData( file: result.file != null ? PickedFile(result.file!.path) : null, exception: result.exception, type: result.type, ); } @override Future<LostDataResponse> getLostData() async { List<XFile>? pickedFileList; final Map<String, dynamic>? result = await _channel.invokeMapMethod<String, dynamic>('retrieve'); if (result == null) { return LostDataResponse.empty(); } assert(result.containsKey('path') != result.containsKey('errorCode')); final String? type = result['type'] as String?; assert(type == kTypeImage || type == kTypeVideo); RetrieveType? retrieveType; if (type == kTypeImage) { retrieveType = RetrieveType.image; } else if (type == kTypeVideo) { retrieveType = RetrieveType.video; } PlatformException? exception; if (result.containsKey('errorCode')) { exception = PlatformException( code: result['errorCode']! as String, message: result['errorMessage'] as String?); } final String? path = result['path'] as String?; final List<String>? pathList = (result['pathList'] as List<dynamic>?)?.cast<String>(); if (pathList != null) { pickedFileList = <XFile>[]; for (final String path in pathList) { pickedFileList.add(XFile(path)); } } return LostDataResponse( file: path != null ? XFile(path) : null, exception: exception, type: retrieveType, files: pickedFileList, ); } }
plugins/packages/image_picker/image_picker_android/lib/image_picker_android.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/lib/image_picker_android.dart", "repo_id": "plugins", "token_count": 2851 }
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. import 'dart:async'; import 'dart:html' as html; import 'dart:math'; import 'dart:ui'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'image_resizer_utils.dart'; /// Helper class that resizes images. class ImageResizer { /// Resizes the image if needed. /// (Does not support gif images) Future<XFile> resizeImageIfNeeded(XFile file, double? maxWidth, double? maxHeight, int? imageQuality) async { if (!imageResizeNeeded(maxWidth, maxHeight, imageQuality) || file.mimeType == 'image/gif') { // Implement maxWidth and maxHeight for image/gif return file; } try { final html.ImageElement imageElement = await loadImage(file.path); final html.CanvasElement canvas = resizeImageElement(imageElement, maxWidth, maxHeight); final XFile resizedImage = await writeCanvasToFile(file, canvas, imageQuality); html.Url.revokeObjectUrl(file.path); return resizedImage; } catch (e) { return file; } } /// function that loads the blobUrl into an imageElement Future<html.ImageElement> loadImage(String blobUrl) { final Completer<html.ImageElement> imageLoadCompleter = Completer<html.ImageElement>(); final html.ImageElement imageElement = html.ImageElement(); // ignore: unsafe_html imageElement.src = blobUrl; imageElement.onLoad.listen((html.Event event) { imageLoadCompleter.complete(imageElement); }); imageElement.onError.listen((html.Event event) { const String exception = 'Error while loading image.'; imageElement.remove(); imageLoadCompleter.completeError(exception); }); return imageLoadCompleter.future; } /// Draws image to a canvas while resizing the image to fit the [maxWidth],[maxHeight] constraints html.CanvasElement resizeImageElement( html.ImageElement source, double? maxWidth, double? maxHeight) { final Size newImageSize = calculateSizeOfDownScaledImage( Size(source.width!.toDouble(), source.height!.toDouble()), maxWidth, maxHeight); final html.CanvasElement canvas = html.CanvasElement(); canvas.width = newImageSize.width.toInt(); canvas.height = newImageSize.height.toInt(); final html.CanvasRenderingContext2D context = canvas.context2D; if (maxHeight == null && maxWidth == null) { context.drawImage(source, 0, 0); } else { context.drawImageScaled(source, 0, 0, canvas.width!, canvas.height!); } return canvas; } /// function that converts a canvas element to Xfile /// [imageQuality] is only supported for jpeg and webp images. Future<XFile> writeCanvasToFile( XFile originalFile, html.CanvasElement canvas, int? imageQuality) async { final double calculatedImageQuality = (min(imageQuality ?? 100, 100)) / 100.0; final html.Blob blob = await canvas.toBlob(originalFile.mimeType, calculatedImageQuality); return XFile(html.Url.createObjectUrlFromBlob(blob), mimeType: originalFile.mimeType, name: 'scaled_${originalFile.name}', lastModified: DateTime.now(), length: blob.size); } }
plugins/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart", "repo_id": "plugins", "token_count": 1181 }
1,150
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "ImagePickerTestImages.h" @import image_picker_ios; @import image_picker_ios.Test; @import XCTest; @interface ImageUtilTests : XCTestCase @end @implementation ImageUtilTests - (void)testScaledImage_ShouldBeScaled { UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData]; UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image maxWidth:@3 maxHeight:@2 isMetadataAvailable:YES]; XCTAssertEqual(newImage.size.width, 3); XCTAssertEqual(newImage.size.height, 2); } - (void)testScaledImage_ShouldBeScaledWithNoMetadata { UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData]; UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image maxWidth:@3 maxHeight:@2 isMetadataAvailable:NO]; XCTAssertEqual(newImage.size.width, 3); XCTAssertEqual(newImage.size.height, 2); } - (void)testScaledImage_ShouldBeCorrectRotation { NSURL *imageURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"jpgImageWithRightOrientation" withExtension:@"jpg"]; NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; UIImage *image = [UIImage imageWithData:imageData]; XCTAssertEqual(image.size.width, 130); XCTAssertEqual(image.size.height, 174); XCTAssertEqual(image.imageOrientation, UIImageOrientationRight); UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image maxWidth:@10 maxHeight:@10 isMetadataAvailable:YES]; XCTAssertEqual(newImage.size.width, 10); XCTAssertEqual(newImage.size.height, 7); XCTAssertEqual(newImage.imageOrientation, UIImageOrientationUp); } - (void)testScaledGIFImage_ShouldBeScaled { // gif image that frame size is 3 and the duration is 1 second. GIFInfo *info = [FLTImagePickerImageUtil scaledGIFImage:ImagePickerTestImages.GIFTestData maxWidth:@3 maxHeight:@2]; NSArray<UIImage *> *images = info.images; NSTimeInterval duration = info.interval; XCTAssertEqual(images.count, 3); XCTAssertEqual(duration, 1); for (UIImage *newImage in images) { XCTAssertEqual(newImage.size.width, 3); XCTAssertEqual(newImage.size.height, 2); } } @end
plugins/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImageUtilTests.m/0
{ "file_path": "plugins/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImageUtilTests.m", "repo_id": "plugins", "token_count": 1362 }
1,151
name: example description: Example for image_picker_windows implementation. publish_to: 'none' version: 1.0.0 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter image_picker_platform_interface: ^2.4.3 image_picker_windows: # When depending on this package from a real application you should use: # image_picker_windows: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: .. video_player: ^2.1.4 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true
plugins/packages/image_picker/image_picker_windows/example/pubspec.yaml/0
{ "file_path": "plugins/packages/image_picker/image_picker_windows/example/pubspec.yaml", "repo_id": "plugins", "token_count": 272 }
1,152
# in\_app\_purchase\_android The Android implementation of [`in_app_purchase`][1]. ## Usage This package has been [endorsed][2], meaning that you only need to add `in_app_purchase` as a dependency in your `pubspec.yaml`. This package will be automatically included in your app when you do. If you wish to use the Android package only, you can [add `in_app_purchase_android` directly][3]. ## Contributing This plugin uses [json_serializable](https://pub.dev/packages/json_serializable) for the many data structs passed between the underlying platform layers and Dart. After editing any of the serialized data structs, rebuild the serializers by running `flutter packages pub run build_runner build --delete-conflicting-outputs`. `flutter packages pub run build_runner watch --delete-conflicting-outputs` will watch the filesystem for changes. If you would like to contribute to the plugin, check out our [contribution guide](https://github.com/flutter/plugins/blob/main/CONTRIBUTING.md). [1]: https://pub.dev/packages/in_app_purchase [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin [3]: https://pub.dev/packages/in_app_purchase_android/install
plugins/packages/in_app_purchase/in_app_purchase_android/README.md/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/README.md", "repo_id": "plugins", "token_count": 357 }
1,153
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'sku_details_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** SkuDetailsWrapper _$SkuDetailsWrapperFromJson(Map json) => SkuDetailsWrapper( description: json['description'] as String? ?? '', freeTrialPeriod: json['freeTrialPeriod'] as String? ?? '', introductoryPrice: json['introductoryPrice'] as String? ?? '', introductoryPriceAmountMicros: json['introductoryPriceAmountMicros'] as int? ?? 0, introductoryPriceCycles: json['introductoryPriceCycles'] as int? ?? 0, introductoryPricePeriod: json['introductoryPricePeriod'] as String? ?? '', price: json['price'] as String? ?? '', priceAmountMicros: json['priceAmountMicros'] as int? ?? 0, priceCurrencyCode: json['priceCurrencyCode'] as String? ?? '', priceCurrencySymbol: json['priceCurrencySymbol'] as String? ?? '', sku: json['sku'] as String? ?? '', subscriptionPeriod: json['subscriptionPeriod'] as String? ?? '', title: json['title'] as String? ?? '', type: const SkuTypeConverter().fromJson(json['type'] as String?), originalPrice: json['originalPrice'] as String? ?? '', originalPriceAmountMicros: json['originalPriceAmountMicros'] as int? ?? 0, ); SkuDetailsResponseWrapper _$SkuDetailsResponseWrapperFromJson(Map json) => SkuDetailsResponseWrapper( billingResult: BillingResultWrapper.fromJson((json['billingResult'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), skuDetailsList: (json['skuDetailsList'] as List<dynamic>?) ?.map((e) => SkuDetailsWrapper.fromJson( Map<String, dynamic>.from(e as Map))) .toList() ?? [], ); BillingResultWrapper _$BillingResultWrapperFromJson(Map json) => BillingResultWrapper( responseCode: const BillingResponseConverter() .fromJson(json['responseCode'] as int?), debugMessage: json['debugMessage'] as String?, );
plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/sku_details_wrapper.g.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/sku_details_wrapper.g.dart", "repo_id": "plugins", "token_count": 787 }
1,154
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart' 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 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'billing_client_wrappers/purchase_wrapper_test.dart'; import 'billing_client_wrappers/sku_details_wrapper_test.dart'; import 'stub_in_app_purchase_platform.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final StubInAppPurchasePlatform stubPlatform = StubInAppPurchasePlatform(); late InAppPurchaseAndroidPlatform iapAndroidPlatform; 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); InAppPurchaseAndroidPlatform.registerPlatform(); iapAndroidPlatform = InAppPurchasePlatform.instance as InAppPurchaseAndroidPlatform; }); tearDown(() { stubPlatform.reset(); }); group('connection management', () { test('connects on initialization', () { //await iapAndroidPlatform.isAvailable(); expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(1)); }); }); group('isAvailable', () { test('true', () async { stubPlatform.addResponse(name: 'BillingClient#isReady()', value: true); expect(await iapAndroidPlatform.isAvailable(), isTrue); }); test('false', () async { stubPlatform.addResponse(name: 'BillingClient#isReady()', value: false); expect(await iapAndroidPlatform.isAvailable(), isFalse); }); }); group('querySkuDetails', () { const String queryMethodName = 'BillingClient#querySkuDetailsAsync(SkuDetailsParams, SkuDetailsResponseListener)'; test('handles empty skuDetails', () 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), 'skuDetailsList': <Map<String, dynamic>>[], }); final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails(<String>{''}); expect(response.productDetails, isEmpty); }); test('should get correct product details', () 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), 'skuDetailsList': <Map<String, dynamic>>[buildSkuMap(dummySkuDetails)] }); // Since queryProductDetails makes 2 platform method calls (one for each SkuType), the result will contain 2 dummyWrapper instead // of 1. final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails(<String>{'valid'}); expect(response.productDetails.first.title, dummySkuDetails.title); expect(response.productDetails.first.description, dummySkuDetails.description); expect(response.productDetails.first.price, dummySkuDetails.price); expect(response.productDetails.first.currencySymbol, r'$'); }); test('should get the correct notFoundIDs', () 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), 'skuDetailsList': <Map<String, dynamic>>[buildSkuMap(dummySkuDetails)] }); // Since queryProductDetails makes 2 platform method calls (one for each SkuType), the result will contain 2 dummyWrapper instead // of 1. final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails(<String>{'invalid'}); expect(response.notFoundIDs.first, 'invalid'); }); test( 'should have error stored in the response when platform exception is thrown', () async { const BillingResponse responseCode = BillingResponse.ok; stubPlatform.addResponse( name: queryMethodName, value: <String, dynamic>{ 'responseCode': const BillingResponseConverter().toJson(responseCode), 'skuDetailsList': <Map<String, dynamic>>[ buildSkuMap(dummySkuDetails) ] }, additionalStepBeforeReturn: (dynamic _) { throw PlatformException( code: 'error_code', message: 'error_message', details: <dynamic, dynamic>{'info': 'error_info'}, ); }); // Since queryProductDetails makes 2 platform method calls (one for each SkuType), the result will contain 2 dummyWrapper instead // of 1. final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails(<String>{'invalid'}); expect(response.notFoundIDs, <String>['invalid']); expect(response.productDetails, isEmpty); expect(response.error, isNotNull); expect(response.error!.source, kIAPSource); expect(response.error!.code, 'error_code'); expect(response.error!.message, 'error_message'); expect(response.error!.details, <String, dynamic>{'info': 'error_info'}); }); }); group('restorePurchases', () { 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>>[] }); expect( iapAndroidPlatform.restorePurchases(), throwsA( isA<InAppPurchaseException>() .having( (InAppPurchaseException e) => e.source, 'source', kIAPSource) .having((InAppPurchaseException e) => e.code, 'code', kRestoredPurchaseErrorCode) .having((InAppPurchaseException e) => e.message, 'message', responseCode.toString()), ), ); }); 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'}, ); }); expect( iapAndroidPlatform.restorePurchases(), throwsA( isA<PlatformException>() .having((PlatformException e) => e.code, 'code', 'error_code') .having((PlatformException e) => e.message, 'message', 'error_message') .having((PlatformException e) => e.details, 'details', <String, dynamic>{'info': 'error_info'}), ), ); }); test('returns SkuDetailsResponseWrapper', () async { final Completer<List<PurchaseDetails>> completer = Completer<List<PurchaseDetails>>(); final Stream<List<PurchaseDetails>> stream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = stream.listen((List<PurchaseDetails> purchaseDetailsList) { if (purchaseDetailsList.first.status == PurchaseStatus.restored) { completer.complete(purchaseDetailsList); subscription.cancel(); } }); 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 dummyPurchase instances instead // of 1. await iapAndroidPlatform.restorePurchases(); final List<PurchaseDetails> restoredPurchases = await completer.future; expect(restoredPurchases.length, 2); for (final PurchaseDetails element in restoredPurchases) { final GooglePlayPurchaseDetails purchase = element as GooglePlayPurchaseDetails; expect(purchase.productID, dummyPurchase.sku); expect(purchase.purchaseID, dummyPurchase.orderId); expect(purchase.verificationData.localVerificationData, dummyPurchase.originalJson); expect(purchase.verificationData.serverVerificationData, dummyPurchase.purchaseToken); expect(purchase.verificationData.source, kIAPSource); expect(purchase.transactionDate, dummyPurchase.purchaseTime.toString()); expect(purchase.billingClientPurchase, dummyPurchase); expect(purchase.status, PurchaseStatus.restored); } }); }); group('make payment', () { const String launchMethodName = 'BillingClient#launchBillingFlow(Activity, BillingFlowParams)'; const String consumeMethodName = 'BillingClient#consumeAsync(String, ConsumeResponseListener)'; test('buy non consumable, serializes and deserializes data', () async { const SkuDetailsWrapper skuDetails = dummySkuDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'skus': <String>[skuDetails.sku], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClient.callHandler(call); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((_) { purchaseDetails = _.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(skuDetails), applicationUserName: accountId); final bool launchResult = await iapAndroidPlatform.buyNonConsumable( purchaseParam: purchaseParam); final PurchaseDetails result = await completer.future; expect(launchResult, isTrue); expect(result.purchaseID, 'orderID1'); expect(result.status, PurchaseStatus.purchased); expect(result.productID, dummySkuDetails.sku); }); test('handles an error with an empty purchases list', () async { const SkuDetailsWrapper skuDetails = dummySkuDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.error; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': const <dynamic>[] }); iapAndroidPlatform.billingClient.callHandler(call); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((_) { purchaseDetails = _.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(skuDetails), applicationUserName: accountId); await iapAndroidPlatform.buyNonConsumable(purchaseParam: purchaseParam); final PurchaseDetails result = await completer.future; expect(result.error, isNotNull); expect(result.error!.source, kIAPSource); expect(result.status, PurchaseStatus.error); expect(result.purchaseID, isEmpty); }); test('buy consumable with auto consume, serializes and deserializes data', () async { const SkuDetailsWrapper skuDetails = dummySkuDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'skus': <String>[skuDetails.sku], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClient.callHandler(call); }); final Completer<String> consumeCompleter = Completer<String>(); // adding call back for consume purchase const BillingResponse expectedCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResultForConsume = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResultForConsume), additionalStepBeforeReturn: (dynamic args) { final String purchaseToken = (args as Map<Object?, Object?>)['purchaseToken']! as String; consumeCompleter.complete(purchaseToken); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((_) { purchaseDetails = _.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(skuDetails), applicationUserName: accountId); final bool launchResult = await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam); // Verify that the result has succeeded final GooglePlayPurchaseDetails result = await completer.future as GooglePlayPurchaseDetails; expect(launchResult, isTrue); expect(result.billingClientPurchase, isNotNull); expect(result.billingClientPurchase.purchaseToken, await consumeCompleter.future); expect(result.status, PurchaseStatus.purchased); expect(result.error, isNull); }); test('buyNonConsumable propagates failures to launch the billing flow', () async { const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.error; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult)); final bool result = await iapAndroidPlatform.buyNonConsumable( purchaseParam: GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(dummySkuDetails))); // Verify that the failure has been converted and returned expect(result, isFalse); }); test('buyConsumable propagates failures to launch the billing flow', () async { const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.developerError; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), ); final bool result = await iapAndroidPlatform.buyConsumable( purchaseParam: GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(dummySkuDetails))); // Verify that the failure has been converted and returned expect(result, isFalse); }); test('adds consumption failures to PurchaseDetails objects', () async { const SkuDetailsWrapper skuDetails = dummySkuDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'skus': <String>[skuDetails.sku], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClient.callHandler(call); }); final Completer<String> consumeCompleter = Completer<String>(); // adding call back for consume purchase const BillingResponse expectedCode = BillingResponse.error; const BillingResultWrapper expectedBillingResultForConsume = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResultForConsume), additionalStepBeforeReturn: (dynamic args) { final String purchaseToken = (args as Map<Object?, Object?>)['purchaseToken']! as String; consumeCompleter.complete(purchaseToken); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((_) { purchaseDetails = _.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(skuDetails), applicationUserName: accountId); await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam); // Verify that the result has an error for the failed consumption final GooglePlayPurchaseDetails result = await completer.future as GooglePlayPurchaseDetails; expect(result.billingClientPurchase, isNotNull); expect(result.billingClientPurchase.purchaseToken, await consumeCompleter.future); expect(result.status, PurchaseStatus.error); expect(result.error, isNotNull); expect(result.error!.code, kConsumptionFailedErrorCode); }); test( 'buy consumable without auto consume, consume api should not receive calls', () async { const SkuDetailsWrapper skuDetails = dummySkuDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.developerError; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'skus': <String>[skuDetails.sku], 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClient.callHandler(call); }); final Completer<String?> consumeCompleter = Completer<String?>(); // adding call back for consume purchase const BillingResponse expectedCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResultForConsume = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResultForConsume), additionalStepBeforeReturn: (dynamic args) { final String purchaseToken = (args as Map<Object?, Object?>)['purchaseToken']! as String; consumeCompleter.complete(purchaseToken); }); final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((_) { consumeCompleter.complete(null); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(skuDetails), applicationUserName: accountId); await iapAndroidPlatform.buyConsumable( purchaseParam: purchaseParam, autoConsume: false); expect(null, await consumeCompleter.future); }); test( 'should get canceled purchase status when response code is BillingResponse.userCanceled', () async { const SkuDetailsWrapper skuDetails = dummySkuDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.userCanceled; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': <dynamic>[ <dynamic, dynamic>{ 'orderId': 'orderID1', 'sku': skuDetails.sku, 'isAutoRenewing': false, 'packageName': 'package', 'purchaseTime': 1231231231, 'purchaseToken': 'token', 'signature': 'sign', 'originalJson': 'json', 'developerPayload': 'dummy payload', 'isAcknowledged': true, 'purchaseState': 1, } ] }); iapAndroidPlatform.billingClient.callHandler(call); }); final Completer<String> consumeCompleter = Completer<String>(); // adding call back for consume purchase const BillingResponse expectedCode = BillingResponse.userCanceled; const BillingResultWrapper expectedBillingResultForConsume = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: consumeMethodName, value: buildBillingResultMap(expectedBillingResultForConsume), additionalStepBeforeReturn: (dynamic args) { final String purchaseToken = (args as Map<Object?, Object?>)['purchaseToken']! as String; consumeCompleter.complete(purchaseToken); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((_) { purchaseDetails = _.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(skuDetails), applicationUserName: accountId); await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam); // Verify that the result has an error for the failed consumption final GooglePlayPurchaseDetails result = await completer.future as GooglePlayPurchaseDetails; expect(result.status, PurchaseStatus.canceled); }); test( 'should get purchased purchase status when upgrading subscription by deferred proration mode', () async { const SkuDetailsWrapper skuDetails = dummySkuDetails; const String accountId = 'hashedAccountId'; const String debugMessage = 'dummy message'; const BillingResponse sentCode = BillingResponse.ok; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: sentCode, debugMessage: debugMessage); stubPlatform.addResponse( name: launchMethodName, value: buildBillingResultMap(expectedBillingResult), additionalStepBeforeReturn: (dynamic _) { // Mock java update purchase callback. final MethodCall call = MethodCall(kOnPurchasesUpdated, <dynamic, dynamic>{ 'billingResult': buildBillingResultMap(expectedBillingResult), 'responseCode': const BillingResponseConverter().toJson(sentCode), 'purchasesList': const <dynamic>[] }); iapAndroidPlatform.billingClient.callHandler(call); }); final Completer<PurchaseDetails> completer = Completer<PurchaseDetails>(); PurchaseDetails purchaseDetails; final Stream<List<PurchaseDetails>> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription<List<PurchaseDetails>> subscription; subscription = purchaseStream.listen((_) { purchaseDetails = _.first; completer.complete(purchaseDetails); subscription.cancel(); }, onDone: () {}); final GooglePlayPurchaseParam purchaseParam = GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromSkuDetails(skuDetails), applicationUserName: accountId, changeSubscriptionParam: ChangeSubscriptionParam( oldPurchaseDetails: GooglePlayPurchaseDetails.fromPurchase( dummyUnacknowledgedPurchase), prorationMode: ProrationMode.deferred, )); await iapAndroidPlatform.buyNonConsumable(purchaseParam: purchaseParam); final PurchaseDetails result = await completer.future; expect(result.status, PurchaseStatus.purchased); }); }); group('complete purchase', () { const String completeMethodName = 'BillingClient#(AcknowledgePurchaseParams params, (AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)'; test('complete purchase success', () async { const BillingResponse expectedCode = BillingResponse.ok; const String debugMessage = 'dummy message'; const BillingResultWrapper expectedBillingResult = BillingResultWrapper( responseCode: expectedCode, debugMessage: debugMessage); stubPlatform.addResponse( name: completeMethodName, value: buildBillingResultMap(expectedBillingResult), ); final PurchaseDetails purchaseDetails = GooglePlayPurchaseDetails.fromPurchase(dummyUnacknowledgedPurchase); final Completer<BillingResultWrapper> completer = Completer<BillingResultWrapper>(); purchaseDetails.status = PurchaseStatus.purchased; if (purchaseDetails.pendingCompletePurchase) { final BillingResultWrapper billingResultWrapper = await iapAndroidPlatform.completePurchase(purchaseDetails); expect(billingResultWrapper, equals(expectedBillingResult)); completer.complete(billingResultWrapper); } expect(await completer.future, equals(expectedBillingResult)); }); }); } /// 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_test.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_test.dart", "repo_id": "plugins", "token_count": 13908 }
1,155
// Copyright 2013 The Flutter 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 'product_details.dart'; /// The parameter object for generating a purchase. class PurchaseParam { /// Creates a new purchase parameter object with the given data. PurchaseParam({ required this.productDetails, this.applicationUserName, }); /// The product to create payment for. /// /// It has to match one of the valid [ProductDetails] objects that you get from [ProductDetailsResponse] after calling [InAppPurchasePlatform.queryProductDetails]. final ProductDetails productDetails; /// An opaque id for the user's account that's unique to your app. (Optional) /// /// Used to help the store detect irregular activity. /// Do not pass in a clear text, your developer ID, the user’s Apple ID, or the /// user's Google ID for this field. /// For example, you can use a one-way hash of the user’s account name on your server. final String? applicationUserName; }
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/purchase_param.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/purchase_param.dart", "repo_id": "plugins", "token_count": 278 }
1,156
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:ui' as ui; import 'package:flutter/foundation.dart' show SynchronousFuture, describeIdentity, immutable, objectRuntimeType; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; class _FutureImageStreamCompleter extends ImageStreamCompleter { _FutureImageStreamCompleter({ required Future<ui.Codec> codec, required this.futureScale, }) { codec.then<void>(_onCodecReady, onError: (Object error, StackTrace stack) { reportError( context: ErrorDescription('resolving a single-frame image stream'), exception: error, stack: stack, silent: true, ); }); } final Future<double> futureScale; Future<void> _onCodecReady(ui.Codec codec) async { try { final ui.FrameInfo nextFrame = await codec.getNextFrame(); final double scale = await futureScale; setImage(ImageInfo(image: nextFrame.image, scale: scale)); } catch (exception, stack) { reportError( context: ErrorDescription('resolving an image frame'), exception: exception, stack: stack, silent: true, ); } } } /// Performs exactly like a [MemoryImage] but instead of taking in bytes it takes /// in a future that represents bytes. @immutable class _FutureMemoryImage extends ImageProvider<_FutureMemoryImage> { /// Constructor for FutureMemoryImage. [_futureBytes] is the bytes that will /// be loaded into an image and [_futureScale] is the scale that will be applied to /// that image to account for high-resolution images. const _FutureMemoryImage(this._futureBytes, this._futureScale); final Future<Uint8List> _futureBytes; final Future<double> _futureScale; /// See [ImageProvider.obtainKey]. @override Future<_FutureMemoryImage> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<_FutureMemoryImage>(this); } @override ImageStreamCompleter loadBuffer( _FutureMemoryImage key, DecoderBufferCallback decode, // ignore: deprecated_member_use ) { return _FutureImageStreamCompleter( codec: _loadAsync(key, decode), futureScale: _futureScale, ); } Future<ui.Codec> _loadAsync( _FutureMemoryImage key, DecoderBufferCallback decode, // ignore: deprecated_member_use ) { assert(key == this); return _futureBytes.then(ui.ImmutableBuffer.fromUint8List).then(decode); } /// See [ImageProvider.operator==]. @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is _FutureMemoryImage && _futureBytes == other._futureBytes && _futureScale == other._futureScale; } /// See [ImageProvider.hashCode]. @override int get hashCode => Object.hash(_futureBytes.hashCode, _futureScale); /// See [ImageProvider.toString]. @override String toString() => '${objectRuntimeType(this, '_FutureMemoryImage')}' '(${describeIdentity(_futureBytes)}, scale: $_futureScale)'; } // ignore: avoid_classes_with_only_static_members /// Class to help loading of iOS platform images into Flutter. /// /// For example, loading an image that is in `Assets.xcassts`. class IosPlatformImages { static const MethodChannel _channel = MethodChannel('plugins.flutter.io/ios_platform_images'); /// Loads an image from asset catalogs. The equivalent would be: /// `[UIImage imageNamed:name]`. /// /// Throws an exception if the image can't be found. /// /// See [https://developer.apple.com/documentation/uikit/uiimage/1624146-imagenamed?language=objc] static ImageProvider load(String name) { final Future<Map<String, dynamic>?> loadInfo = _channel.invokeMapMethod<String, dynamic>('loadImage', name); final Completer<Uint8List> bytesCompleter = Completer<Uint8List>(); final Completer<double> scaleCompleter = Completer<double>(); loadInfo.then((Map<String, dynamic>? map) { if (map == null) { scaleCompleter.completeError( Exception("Image couldn't be found: $name"), ); bytesCompleter.completeError( Exception("Image couldn't be found: $name"), ); return; } scaleCompleter.complete(map['scale']! as double); bytesCompleter.complete(map['data']! as Uint8List); }); return _FutureMemoryImage(bytesCompleter.future, scaleCompleter.future); } /// Resolves an URL for a resource. The equivalent would be: /// `[[NSBundle mainBundle] URLForResource:name withExtension:ext]`. /// /// Returns null if the resource can't be found. /// /// See [https://developer.apple.com/documentation/foundation/nsbundle/1411540-urlforresource?language=objc] static Future<String?> resolveURL(String name, {String? extension}) { return _channel .invokeMethod<String>('resolveURL', <Object?>[name, extension]); } }
plugins/packages/ios_platform_images/lib/ios_platform_images.dart/0
{ "file_path": "plugins/packages/ios_platform_images/lib/ios_platform_images.dart", "repo_id": "plugins", "token_count": 1727 }
1,157
## 1.0.18 * Updates minimum Flutter version to 3.0. * Updates androidx.core version to 1.9.0. * Upgrades compile SDK version to 33. ## 1.0.17 * Adds compatibility with `intl` 0.18.0. ## 1.0.16 * Updates androidx.fragment version to 1.5.5. ## 1.0.15 * Updates androidx.fragment version to 1.5.4. ## 1.0.14 * Fixes device credential authentication for API versions before R. ## 1.0.13 * Updates imports for `prefer_relative_imports`. ## 1.0.12 * Updates androidx.fragment version to 1.5.2. * Updates minimum Flutter version to 2.10. ## 1.0.11 * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 1.0.10 * Updates `local_auth_platform_interface` constraint to the correct minimum version. ## 1.0.9 * Updates androidx.fragment version to 1.5.1. ## 1.0.8 * Removes usages of `FingerprintManager` and other `BiometricManager` deprecated method usages. ## 1.0.7 * Updates gradle version to 7.2.1. ## 1.0.6 * Updates androidx.core version to 1.8.0. ## 1.0.5 * Updates references to the obsolete master branch. ## 1.0.4 * Minor fixes for new analysis options. ## 1.0.3 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 1.0.2 * Fixes `getEnrolledBiometrics` to match documented behaviour: Present biometrics that are not enrolled are no longer returned. * `getEnrolledBiometrics` now only returns `weak` and `strong` biometric types. * `deviceSupportsBiometrics` now returns the correct value regardless of enrollment state. ## 1.0.1 * Adopts `Object.hash`. ## 1.0.0 * Initial release from migration to federated architecture.
plugins/packages/local_auth/local_auth_android/CHANGELOG.md/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/CHANGELOG.md", "repo_id": "plugins", "token_count": 584 }
1,158
<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_signin" 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/fingerprint_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 android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/fingerprint_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/fingerprint_initial_icon"/> <TextView android:id="@+id/fingerprint_status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingStart="16dp" android:paddingEnd="0dp" android:paddingLeft="16dp" android:paddingRight="0dp" android:paddingTop="12dp" android:paddingBottom="12dp" android:textColor="@color/hint_color" /> </LinearLayout> </LinearLayout>
plugins/packages/local_auth/local_auth_android/android/src/main/res/layout/scan_fp.xml/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/layout/scan_fp.xml", "repo_id": "plugins", "token_count": 720 }
1,159
buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.3.1' } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir }
plugins/packages/local_auth/local_auth_android/example/android/build.gradle/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/example/android/build.gradle", "repo_id": "plugins", "token_count": 202 }
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. import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; import 'messages.g.dart' as messages; messages.StorageDirectory _convertStorageDirectory( StorageDirectory? directory) { switch (directory) { case null: return messages.StorageDirectory.root; case StorageDirectory.music: return messages.StorageDirectory.music; case StorageDirectory.podcasts: return messages.StorageDirectory.podcasts; case StorageDirectory.ringtones: return messages.StorageDirectory.ringtones; case StorageDirectory.alarms: return messages.StorageDirectory.alarms; case StorageDirectory.notifications: return messages.StorageDirectory.notifications; case StorageDirectory.pictures: return messages.StorageDirectory.pictures; case StorageDirectory.movies: return messages.StorageDirectory.movies; case StorageDirectory.downloads: return messages.StorageDirectory.downloads; case StorageDirectory.dcim: return messages.StorageDirectory.dcim; case StorageDirectory.documents: return messages.StorageDirectory.documents; } } /// The Android implementation of [PathProviderPlatform]. class PathProviderAndroid extends PathProviderPlatform { final messages.PathProviderApi _api = messages.PathProviderApi(); /// Registers this class as the default instance of [PathProviderPlatform]. static void registerWith() { PathProviderPlatform.instance = PathProviderAndroid(); } @override Future<String?> getTemporaryPath() { return _api.getTemporaryPath(); } @override Future<String?> getApplicationSupportPath() { return _api.getApplicationSupportPath(); } @override Future<String?> getLibraryPath() { throw UnsupportedError('getLibraryPath is not supported on Android'); } @override Future<String?> getApplicationDocumentsPath() { return _api.getApplicationDocumentsPath(); } @override Future<String?> getExternalStoragePath() { return _api.getExternalStoragePath(); } @override Future<List<String>?> getExternalCachePaths() async { return (await _api.getExternalCachePaths()).cast<String>(); } @override Future<List<String>?> getExternalStoragePaths({ StorageDirectory? type, }) async { return (await _api.getExternalStoragePaths(_convertStorageDirectory(type))) .cast<String>(); } @override Future<String?> getDownloadsPath() { throw UnsupportedError('getDownloadsPath is not supported on Android'); } }
plugins/packages/path_provider/path_provider_android/lib/path_provider_android.dart/0
{ "file_path": "plugins/packages/path_provider/path_provider_android/lib/path_provider_android.dart", "repo_id": "plugins", "token_count": 820 }
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 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('getTemporaryDirectory', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; final String? result = await provider.getTemporaryPath(); _verifySampleFile(result, 'temporaryDirectory'); }); testWidgets('getApplicationDocumentsDirectory', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; final String? result = await provider.getApplicationDocumentsPath(); _verifySampleFile(result, 'applicationDocuments'); }); testWidgets('getApplicationSupportDirectory', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; final String? result = await provider.getApplicationSupportPath(); _verifySampleFile(result, 'applicationSupport'); }); testWidgets('getLibraryDirectory', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; final String? result = await provider.getLibraryPath(); _verifySampleFile(result, 'library'); }); testWidgets('getDownloadsDirectory', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; final String? result = await provider.getDownloadsPath(); // _verifySampleFile causes hangs in driver for some reason, so just // validate that a non-empty path was returned. expect(result, isNotEmpty); }); } /// Verify a file called [name] in [directoryPath] by recreating it with test /// contents when necessary. /// /// If [createDirectory] is true, the directory will be created if missing. void _verifySampleFile(String? directoryPath, String name) { expect(directoryPath, isNotNull); if (directoryPath == null) { return; } final Directory directory = Directory(directoryPath); final File file = File('${directory.path}${Platform.pathSeparator}$name'); if (file.existsSync()) { file.deleteSync(); expect(file.existsSync(), isFalse); } file.writeAsStringSync('Hello world!'); expect(file.readAsStringSync(), 'Hello world!'); expect(directory.listSync(), isNotEmpty); file.deleteSync(); }
plugins/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart/0
{ "file_path": "plugins/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart", "repo_id": "plugins", "token_count": 748 }
1,162
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.quickactions; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ShortcutManager; import android.os.Build; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.PluginRegistry.NewIntentListener; /** QuickActionsPlugin */ public class QuickActionsPlugin implements FlutterPlugin, ActivityAware, NewIntentListener { private static final String CHANNEL_ID = "plugins.flutter.io/quick_actions_android"; private MethodChannel channel; private MethodCallHandlerImpl handler; private Activity activity; /** * Plugin registration. * * <p>Must be called when the application is created. */ @SuppressWarnings("deprecation") public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) { final QuickActionsPlugin plugin = new QuickActionsPlugin(); plugin.setupChannel(registrar.messenger(), registrar.context(), registrar.activity()); } @Override public void onAttachedToEngine(FlutterPluginBinding binding) { setupChannel(binding.getBinaryMessenger(), binding.getApplicationContext(), null); } @Override public void onDetachedFromEngine(FlutterPluginBinding binding) { teardownChannel(); } @Override public void onAttachedToActivity(ActivityPluginBinding binding) { activity = binding.getActivity(); handler.setActivity(activity); binding.addOnNewIntentListener(this); onNewIntent(activity.getIntent()); } @Override public void onDetachedFromActivity() { handler.setActivity(null); } @Override public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) { binding.removeOnNewIntentListener(this); onAttachedToActivity(binding); } @Override public void onDetachedFromActivityForConfigChanges() { onDetachedFromActivity(); } @Override public boolean onNewIntent(Intent intent) { // Do nothing for anything lower than API 25 as the functionality isn't supported. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) { return false; } // Notify the Dart side if the launch intent has the intent extra relevant to quick actions. if (intent.hasExtra(MethodCallHandlerImpl.EXTRA_ACTION) && channel != null) { Context context = activity.getApplicationContext(); ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE); String shortcutId = intent.getStringExtra(MethodCallHandlerImpl.EXTRA_ACTION); channel.invokeMethod("launch", shortcutId); shortcutManager.reportShortcutUsed(shortcutId); } return false; } private void setupChannel(BinaryMessenger messenger, Context context, Activity activity) { channel = new MethodChannel(messenger, CHANNEL_ID); handler = new MethodCallHandlerImpl(context, activity); channel.setMethodCallHandler(handler); } private void teardownChannel() { channel.setMethodCallHandler(null); channel = null; handler = null; } }
plugins/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/QuickActionsPlugin.java/0
{ "file_path": "plugins/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/QuickActionsPlugin.java", "repo_id": "plugins", "token_count": 1059 }
1,163
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" #include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
plugins/packages/shared_preferences/shared_preferences/example/ios/Flutter/Debug.xcconfig/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences/example/ios/Flutter/Debug.xcconfig", "repo_id": "plugins", "token_count": 69 }
1,164
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.sharedpreferences; import android.content.Context; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodChannel; /** SharedPreferencesPlugin */ public class SharedPreferencesPlugin implements FlutterPlugin { private static final String CHANNEL_NAME = "plugins.flutter.io/shared_preferences_android"; private MethodChannel channel; private MethodCallHandlerImpl handler; @SuppressWarnings("deprecation") public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) { final SharedPreferencesPlugin plugin = new SharedPreferencesPlugin(); plugin.setupChannel(registrar.messenger(), registrar.context()); } @Override public void onAttachedToEngine(FlutterPlugin.FlutterPluginBinding binding) { setupChannel(binding.getBinaryMessenger(), binding.getApplicationContext()); } @Override public void onDetachedFromEngine(FlutterPlugin.FlutterPluginBinding binding) { teardownChannel(); } private void setupChannel(BinaryMessenger messenger, Context context) { channel = new MethodChannel(messenger, CHANNEL_NAME); handler = new MethodCallHandlerImpl(context); channel.setMethodCallHandler(handler); } private void teardownChannel() { handler.teardown(); handler = null; channel.setMethodCallHandler(null); channel = null; } }
plugins/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/SharedPreferencesPlugin.java/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/SharedPreferencesPlugin.java", "repo_id": "plugins", "token_count": 467 }
1,165
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true android.enableR8=true
plugins/packages/url_launcher/url_launcher/example/android/gradle.properties/0
{ "file_path": "plugins/packages/url_launcher/url_launcher/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,166
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
plugins/packages/url_launcher/url_launcher/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "plugins/packages/url_launcher/url_launcher/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "plugins", "token_count": 32 }
1,167
## NEXT * Updates minimum Flutter version to 3.0. ## 6.0.23 * Updates code for stricter lint checks. ## 6.0.22 * Updates code for new analysis options. ## 6.0.21 * Updates androidx.annotation to 1.2.0. ## 6.0.20 * Updates android gradle plugin to 4.2.0. ## 6.0.19 * Revert gradle back to 3.4.2. ## 6.0.18 * Updates gradle to 7.2.2. * Updates minimum Flutter version to 2.10. ## 6.0.17 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 6.0.16 * Adds fallback querying for `canLaunch` with web URLs, to avoid false negatives when there is a custom scheme handler. ## 6.0.15 * Switches to an in-package method channel implementation. ## 6.0.14 * Updates code for new analysis options. * Removes dependency on `meta`. ## 6.0.13 * Splits from `shared_preferences` as a federated implementation.
plugins/packages/url_launcher/url_launcher_android/CHANGELOG.md/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_android/CHANGELOG.md", "repo_id": "plugins", "token_count": 319 }
1,168
name: url_launcher_android description: Android implementation of the url_launcher plugin. repository: https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22 version: 6.0.23 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: url_launcher platforms: android: package: io.flutter.plugins.urllauncher pluginClass: UrlLauncherPlugin dartPluginClass: UrlLauncherAndroid dependencies: flutter: sdk: flutter url_launcher_platform_interface: ^2.0.3 dev_dependencies: flutter_test: sdk: flutter mockito: ^5.0.0 plugin_platform_interface: ^2.0.0 test: ^1.16.3
plugins/packages/url_launcher/url_launcher_android/pubspec.yaml/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_android/pubspec.yaml", "repo_id": "plugins", "token_count": 333 }
1,169
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'url_launcher_ios' s.version = '0.0.1' s.summary = 'Flutter plugin for launching a URL.' s.description = <<-DESC A Flutter plugin for making the underlying platform (Android or iOS) launch a URL. DESC s.homepage = 'https://github.com/flutter/plugins/tree/main/packages/url_launcher' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/url_launcher/url_launcher_ios' } s.documentation_url = 'https://pub.dev/packages/url_launcher' s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.dependency 'Flutter' s.platform = :ios, '11.0' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } end
plugins/packages/url_launcher/url_launcher_ios/ios/url_launcher_ios.podspec/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_ios/ios/url_launcher_ios.podspec", "repo_id": "plugins", "token_count": 441 }
1,170
// Copyright 2013 The Flutter 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:plugin_platform_interface/plugin_platform_interface.dart'; import '../link.dart'; import '../method_channel_url_launcher.dart'; import '../url_launcher_platform_interface.dart'; /// The interface that implementations of url_launcher must implement. /// /// Platform implementations should extend this class rather than implement it as `url_launcher` /// does not consider newly added methods to be breaking changes. Extending this class /// (using `extends`) ensures that the subclass will get the default implementation, while /// platform implementations that `implements` this interface will be broken by newly added /// [UrlLauncherPlatform] methods. abstract class UrlLauncherPlatform extends PlatformInterface { /// Constructs a UrlLauncherPlatform. UrlLauncherPlatform() : super(token: _token); static final Object _token = Object(); static UrlLauncherPlatform _instance = MethodChannelUrlLauncher(); /// The default instance of [UrlLauncherPlatform] to use. /// /// Defaults to [MethodChannelUrlLauncher]. static UrlLauncherPlatform get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [UrlLauncherPlatform] when they register themselves. // TODO(amirh): Extract common platform interface logic. // https://github.com/flutter/flutter/issues/43368 static set instance(UrlLauncherPlatform instance) { PlatformInterface.verify(instance, _token); _instance = instance; } /// The delegate used by the Link widget to build itself. LinkDelegate? get linkDelegate; /// Returns `true` if this platform is able to launch [url]. Future<bool> canLaunch(String url) { throw UnimplementedError('canLaunch() has not been implemented.'); } /// Passes [url] to the underlying platform for handling. /// /// Returns `true` if the given [url] was successfully launched. /// /// For documentation on the other arguments, see the `launch` documentation /// in `package:url_launcher/url_launcher.dart`. 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, }) { throw UnimplementedError('launch() has not been implemented.'); } /// Passes [url] to the underlying platform for handling. /// /// Returns `true` if the given [url] was successfully launched. Future<bool> launchUrl(String url, LaunchOptions options) { final bool isWebURL = url.startsWith('http:') || url.startsWith('https:'); final bool useWebView = options.mode == PreferredLaunchMode.inAppWebView || (isWebURL && options.mode == PreferredLaunchMode.platformDefault); return launch( url, useSafariVC: useWebView, useWebView: useWebView, enableJavaScript: options.webViewConfiguration.enableJavaScript, enableDomStorage: options.webViewConfiguration.enableDomStorage, universalLinksOnly: options.mode == PreferredLaunchMode.externalNonBrowserApplication, headers: options.webViewConfiguration.headers, webOnlyWindowName: options.webOnlyWindowName, ); } /// Closes the WebView, if one was opened earlier by [launch]. Future<void> closeWebView() { throw UnimplementedError('closeWebView() has not been implemented.'); } }
plugins/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart", "repo_id": "plugins", "token_count": 1050 }
1,171
name: regular_integration_tests publish_to: none environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter dev_dependencies: build_runner: ^2.1.1 flutter_driver: sdk: flutter flutter_test: sdk: flutter flutter_web_plugins: sdk: flutter integration_test: sdk: flutter mockito: ^5.3.2 url_launcher_platform_interface: ^2.0.3 url_launcher_web: path: ../
plugins/packages/url_launcher/url_launcher_web/example/pubspec.yaml/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_web/example/pubspec.yaml", "repo_id": "plugins", "token_count": 202 }
1,172
name: video_player description: Flutter plugin for displaying inline video with other Flutter widgets on Android, iOS, and web. repository: https://github.com/flutter/plugins/tree/main/packages/video_player/video_player issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22 version: 2.5.1 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: platforms: android: default_package: video_player_android ios: default_package: video_player_avfoundation web: default_package: video_player_web dependencies: flutter: sdk: flutter html: ^0.15.0 video_player_android: ^2.3.5 video_player_avfoundation: ^2.2.17 video_player_platform_interface: ">=5.1.1 <7.0.0" video_player_web: ^2.0.0 dev_dependencies: flutter_test: sdk: flutter
plugins/packages/video_player/video_player/pubspec.yaml/0
{ "file_path": "plugins/packages/video_player/video_player/pubspec.yaml", "repo_id": "plugins", "token_count": 368 }
1,173
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import static android.content.Context.INPUT_METHOD_SERVICE; import android.content.Context; import android.graphics.Rect; import android.os.Build; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.webkit.WebView; import android.widget.ListPopupWindow; /** * A WebView subclass that mirrors the same implementation hacks that the system WebView does in * order to correctly create an InputConnection. * * <p>These hacks are only needed in Android versions below N and exist to create an InputConnection * on the WebView's dedicated input, or IME, thread. The majority of this proxying logic is in * {@link #checkInputConnectionProxy}. * * <p>See also {@link ThreadedInputConnectionProxyAdapterView}. */ class InputAwareWebView extends WebView { private static final String TAG = "InputAwareWebView"; private View threadedInputConnectionProxyView; private ThreadedInputConnectionProxyAdapterView proxyAdapterView; private View containerView; InputAwareWebView(Context context, View containerView) { super(context); this.containerView = containerView; } void setContainerView(View containerView) { this.containerView = containerView; if (proxyAdapterView == null) { return; } Log.w(TAG, "The containerView has changed while the proxyAdapterView exists."); if (containerView != null) { setInputConnectionTarget(proxyAdapterView); } } /** * Set our proxy adapter view to use its cached input connection instead of creating new ones. * * <p>This is used to avoid losing our input connection when the virtual display is resized. */ void lockInputConnection() { if (proxyAdapterView == null) { return; } proxyAdapterView.setLocked(true); } /** Sets the proxy adapter view back to its default behavior. */ void unlockInputConnection() { if (proxyAdapterView == null) { return; } proxyAdapterView.setLocked(false); } /** Restore the original InputConnection, if needed. */ void dispose() { resetInputConnection(); } /** * Creates an InputConnection from the IME thread when needed. * * <p>We only need to create a {@link ThreadedInputConnectionProxyAdapterView} and create an * InputConnectionProxy on the IME thread when WebView is doing the same thing. So we rely on the * system calling this method for WebView's proxy view in order to know when we need to create our * own. * * <p>This method would normally be called for any View that used the InputMethodManager. We rely * on flutter/engine filtering the calls we receive down to the ones in our hierarchy and the * system WebView in order to know whether or not the system WebView expects an InputConnection on * the IME thread. */ @Override public boolean checkInputConnectionProxy(final View view) { // Check to see if the view param is WebView's ThreadedInputConnectionProxyView. View previousProxy = threadedInputConnectionProxyView; threadedInputConnectionProxyView = view; if (previousProxy == view) { // This isn't a new ThreadedInputConnectionProxyView. Ignore it. return super.checkInputConnectionProxy(view); } if (containerView == null) { Log.e( TAG, "Can't create a proxy view because there's no container view. Text input may not work."); return super.checkInputConnectionProxy(view); } // We've never seen this before, so we make the assumption that this is WebView's // ThreadedInputConnectionProxyView. We are making the assumption that the only view that could // possibly be interacting with the IMM here is WebView's ThreadedInputConnectionProxyView. proxyAdapterView = new ThreadedInputConnectionProxyAdapterView( /*containerView=*/ containerView, /*targetView=*/ view, /*imeHandler=*/ view.getHandler()); setInputConnectionTarget(/*targetView=*/ proxyAdapterView); return super.checkInputConnectionProxy(view); } /** * Ensure that input creation happens back on {@link #containerView}'s thread once this view no * longer has focus. * * <p>The logic in {@link #checkInputConnectionProxy} forces input creation to happen on Webview's * thread for all connections. We undo it here so users will be able to go back to typing in * Flutter UIs as expected. */ @Override public void clearFocus() { super.clearFocus(); resetInputConnection(); } /** * Ensure that input creation happens back on {@link #containerView}. * * <p>The logic in {@link #checkInputConnectionProxy} forces input creation to happen on Webview's * thread for all connections. We undo it here so users will be able to go back to typing in * Flutter UIs as expected. */ private void resetInputConnection() { if (proxyAdapterView == null) { // No need to reset the InputConnection to the default thread if we've never changed it. return; } if (containerView == null) { Log.e(TAG, "Can't reset the input connection to the container view because there is none."); return; } setInputConnectionTarget(/*targetView=*/ containerView); } /** * This is the crucial trick that gets the InputConnection creation to happen on the correct * thread pre Android N. * https://cs.chromium.org/chromium/src/content/public/android/java/src/org/chromium/content/browser/input/ThreadedInputConnectionFactory.java?l=169&rcl=f0698ee3e4483fad5b0c34159276f71cfaf81f3a * * <p>{@code targetView} should have a {@link View#getHandler} method with the thread that future * InputConnections should be created on. */ void setInputConnectionTarget(final View targetView) { if (containerView == null) { Log.e( TAG, "Can't set the input connection target because there is no containerView to use as a handler."); return; } targetView.requestFocus(); containerView.post( new Runnable() { @Override public void run() { if (containerView == null) { Log.e( TAG, "Can't set the input connection target because there is no containerView to use as a handler."); return; } InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE); // This is a hack to make InputMethodManager believe that the target view now has focus. // As a result, InputMethodManager will think that targetView is focused, and will call // getHandler() of the view when creating input connection. // Step 1: Set targetView as InputMethodManager#mNextServedView. This does not affect // the real window focus. targetView.onWindowFocusChanged(true); // Step 2: Have InputMethodManager focus in on targetView. As a result, IMM will call // onCreateInputConnection() on targetView on the same thread as // targetView.getHandler(). It will also call subsequent InputConnection methods on this // thread. This is the IME thread in cases where targetView is our proxyAdapterView. imm.isActive(containerView); } }); } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { // This works around a crash when old (<67.0.3367.0) Chromium versions are used. // Prior to Chromium 67.0.3367 the following sequence happens when a select drop down is shown // on tablets: // // - WebView is calling ListPopupWindow#show // - buildDropDown is invoked, which sets mDropDownList to a DropDownListView. // - showAsDropDown is invoked - resulting in mDropDownList being added to the window and is // also synchronously performing the following sequence: // - WebView's focus change listener is loosing focus (as mDropDownList got it) // - WebView is hiding all popups (as it lost focus) // - WebView's SelectPopupDropDown#hide is invoked. // - DropDownPopupWindow#dismiss is invoked setting mDropDownList to null. // - mDropDownList#setSelection is invoked and is throwing a NullPointerException (as we just set mDropDownList to null). // // To workaround this, we drop the problematic focus lost call. // See more details on: https://github.com/flutter/flutter/issues/54164 // // We don't do this after Android P as it shipped with a new enough WebView version, and it's // better to not do this on all future Android versions in case DropDownListView's code changes. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && isCalledFromListPopupWindowShow() && !focused) { return; } super.onFocusChanged(focused, direction, previouslyFocusedRect); } private boolean isCalledFromListPopupWindowShow() { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); for (StackTraceElement stackTraceElement : stackTraceElements) { if (stackTraceElement.getClassName().equals(ListPopupWindow.class.getCanonicalName()) && stackTraceElement.getMethodName().equals("show")) { return true; } } return false; } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/InputAwareWebView.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/InputAwareWebView.java", "repo_id": "plugins", "token_count": 3115 }
1,174
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.Context; import android.webkit.DownloadListener; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebViewClient; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.WebViewHostApiImpl.WebViewPlatformView; import java.util.HashMap; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class WebViewTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public WebViewPlatformView mockWebView; @Mock WebViewHostApiImpl.WebViewProxy mockWebViewProxy; @Mock Context mockContext; @Mock BinaryMessenger mockBinaryMessenger; InstanceManager testInstanceManager; WebViewHostApiImpl testHostApiImpl; @Before public void setUp() { testInstanceManager = InstanceManager.open(identifier -> {}); when(mockWebViewProxy.createWebView(mockContext, mockBinaryMessenger, testInstanceManager)) .thenReturn(mockWebView); testHostApiImpl = new WebViewHostApiImpl( testInstanceManager, mockBinaryMessenger, mockWebViewProxy, mockContext, null); testHostApiImpl.create(0L, true); } @After public void tearDown() { testInstanceManager.close(); } @Test public void loadData() { testHostApiImpl.loadData( 0L, "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", "text/plain", "base64"); verify(mockWebView) .loadData("VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", "text/plain", "base64"); } @Test public void loadDataWithNullValues() { testHostApiImpl.loadData(0L, "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", null, null); verify(mockWebView).loadData("VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", null, null); } @Test public void loadDataWithBaseUrl() { testHostApiImpl.loadDataWithBaseUrl( 0L, "https://flutter.dev", "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", "text/plain", "base64", "about:blank"); verify(mockWebView) .loadDataWithBaseURL( "https://flutter.dev", "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", "text/plain", "base64", "about:blank"); } @Test public void loadDataWithBaseUrlAndNullValues() { testHostApiImpl.loadDataWithBaseUrl( 0L, null, "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", null, null, null); verify(mockWebView) .loadDataWithBaseURL(null, "VGhpcyBkYXRhIGlzIGJhc2U2NCBlbmNvZGVkLg==", null, null, null); } @Test public void loadUrl() { testHostApiImpl.loadUrl(0L, "https://www.google.com", new HashMap<>()); verify(mockWebView).loadUrl("https://www.google.com", new HashMap<>()); } @Test public void postUrl() { testHostApiImpl.postUrl(0L, "https://www.google.com", new byte[] {0x01, 0x02}); verify(mockWebView).postUrl("https://www.google.com", new byte[] {0x01, 0x02}); } @Test public void getUrl() { when(mockWebView.getUrl()).thenReturn("https://www.google.com"); assertEquals(testHostApiImpl.getUrl(0L), "https://www.google.com"); } @Test public void canGoBack() { when(mockWebView.canGoBack()).thenReturn(true); assertEquals(testHostApiImpl.canGoBack(0L), true); } @Test public void canGoForward() { when(mockWebView.canGoForward()).thenReturn(false); assertEquals(testHostApiImpl.canGoForward(0L), false); } @Test public void goBack() { testHostApiImpl.goBack(0L); verify(mockWebView).goBack(); } @Test public void goForward() { testHostApiImpl.goForward(0L); verify(mockWebView).goForward(); } @Test public void reload() { testHostApiImpl.reload(0L); verify(mockWebView).reload(); } @Test public void clearCache() { testHostApiImpl.clearCache(0L, false); verify(mockWebView).clearCache(false); } @Test public void evaluateJavaScript() { final String[] successValue = new String[1]; testHostApiImpl.evaluateJavascript( 0L, "2 + 2", new GeneratedAndroidWebView.Result<String>() { @Override public void success(String result) { successValue[0] = result; } @Override public void error(Throwable error) {} }); @SuppressWarnings("unchecked") final ArgumentCaptor<ValueCallback<String>> callbackCaptor = ArgumentCaptor.forClass(ValueCallback.class); verify(mockWebView).evaluateJavascript(eq("2 + 2"), callbackCaptor.capture()); callbackCaptor.getValue().onReceiveValue("da result"); assertEquals(successValue[0], "da result"); } @Test public void getTitle() { when(mockWebView.getTitle()).thenReturn("My title"); assertEquals(testHostApiImpl.getTitle(0L), "My title"); } @Test public void scrollTo() { testHostApiImpl.scrollTo(0L, 12L, 13L); verify(mockWebView).scrollTo(12, 13); } @Test public void scrollBy() { testHostApiImpl.scrollBy(0L, 15L, 23L); verify(mockWebView).scrollBy(15, 23); } @Test public void getScrollX() { when(mockWebView.getScrollX()).thenReturn(55); assertEquals((long) testHostApiImpl.getScrollX(0L), 55); } @Test public void getScrollY() { when(mockWebView.getScrollY()).thenReturn(23); assertEquals((long) testHostApiImpl.getScrollY(0L), 23); } @Test public void getScrollPosition() { when(mockWebView.getScrollX()).thenReturn(1); when(mockWebView.getScrollY()).thenReturn(2); final GeneratedAndroidWebView.WebViewPoint position = testHostApiImpl.getScrollPosition(0L); assertEquals((long) position.getX(), 1L); assertEquals((long) position.getY(), 2L); } @Test public void setWebViewClient() { final WebViewClient mockWebViewClient = mock(WebViewClient.class); testInstanceManager.addDartCreatedInstance(mockWebViewClient, 1L); testHostApiImpl.setWebViewClient(0L, 1L); verify(mockWebView).setWebViewClient(mockWebViewClient); } @Test public void addJavaScriptChannel() { final JavaScriptChannel javaScriptChannel = new JavaScriptChannel(mock(JavaScriptChannelFlutterApiImpl.class), "aName", null); testInstanceManager.addDartCreatedInstance(javaScriptChannel, 1L); testHostApiImpl.addJavaScriptChannel(0L, 1L); verify(mockWebView).addJavascriptInterface(javaScriptChannel, "aName"); } @Test public void removeJavaScriptChannel() { final JavaScriptChannel javaScriptChannel = new JavaScriptChannel(mock(JavaScriptChannelFlutterApiImpl.class), "aName", null); testInstanceManager.addDartCreatedInstance(javaScriptChannel, 1L); testHostApiImpl.removeJavaScriptChannel(0L, 1L); verify(mockWebView).removeJavascriptInterface("aName"); } @Test public void setDownloadListener() { final DownloadListener mockDownloadListener = mock(DownloadListener.class); testInstanceManager.addDartCreatedInstance(mockDownloadListener, 1L); testHostApiImpl.setDownloadListener(0L, 1L); verify(mockWebView).setDownloadListener(mockDownloadListener); } @Test public void setWebChromeClient() { final WebChromeClient mockWebChromeClient = mock(WebChromeClient.class); testInstanceManager.addDartCreatedInstance(mockWebChromeClient, 1L); testHostApiImpl.setWebChromeClient(0L, 1L); verify(mockWebView).setWebChromeClient(mockWebChromeClient); } @Test public void defaultWebChromeClientIsSecureWebChromeClient() { final WebViewPlatformView webView = new WebViewPlatformView(mockContext, null, null); assertTrue( webView.getWebChromeClient() instanceof WebChromeClientHostApiImpl.SecureWebChromeClient); assertFalse( webView.getWebChromeClient() instanceof WebChromeClientHostApiImpl.WebChromeClientImpl); } @Test public void defaultWebChromeClientDoesNotAttemptToCommunicateWithDart() { final WebViewPlatformView webView = new WebViewPlatformView(mockContext, null, null); // This shouldn't throw an Exception. Objects.requireNonNull(webView.getWebChromeClient()).onProgressChanged(webView, 0); } @Test public void disposeDoesNotCallDestroy() { final boolean[] destroyCalled = {false}; final WebViewPlatformView webView = new WebViewPlatformView(mockContext, null, null) { @Override public void destroy() { destroyCalled[0] = true; } }; webView.dispose(); assertFalse(destroyCalled[0]); } @Test public void destroyWebViewWhenDisposedFromJavaObjectHostApi() { final boolean[] destroyCalled = {false}; final WebViewPlatformView webView = new WebViewPlatformView(mockContext, null, null) { @Override public void destroy() { destroyCalled[0] = true; } }; testInstanceManager.addDartCreatedInstance(webView, 0); final JavaObjectHostApiImpl javaObjectHostApi = new JavaObjectHostApiImpl(testInstanceManager); javaObjectHostApi.dispose(0L); assertTrue(destroyCalled[0]); } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewTest.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewTest.java", "repo_id": "plugins", "token_count": 3760 }
1,175
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_android/src/android_webview.dart' as android_webview; import 'package:webview_flutter_android/src/legacy/webview_android_cookie_manager.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; import 'webview_android_cookie_manager_test.mocks.dart'; @GenerateMocks(<Type>[android_webview.CookieManager]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); setUp(() { android_webview.CookieManager.instance = MockCookieManager(); }); test('clearCookies should call android_webview.clearCookies', () { when(android_webview.CookieManager.instance.clearCookies()) .thenAnswer((_) => Future<bool>.value(true)); WebViewAndroidCookieManager().clearCookies(); verify(android_webview.CookieManager.instance.clearCookies()); }); test('setCookie should throw ArgumentError for cookie with invalid path', () { expect( () => WebViewAndroidCookieManager().setCookie(const WebViewCookie( name: 'foo', value: 'bar', domain: 'flutter.dev', path: 'invalid;path', )), throwsA(const TypeMatcher<ArgumentError>()), ); }); test( 'setCookie should call android_webview.csetCookie with properly formatted cookie value', () { WebViewAndroidCookieManager().setCookie(const WebViewCookie( name: 'foo&', value: 'bar@', domain: 'flutter.dev', )); verify(android_webview.CookieManager.instance .setCookie('flutter.dev', 'foo%26=bar%40; path=/')); }); }
plugins/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart", "repo_id": "plugins", "token_count": 680 }
1,176
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; void main() { final List<String> validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_'.split(''); final List<String> commonInvalidChars = r'`~!@#$%^&*()-=+[]{}\|"' ':;/?<>,. '.split(''); final List<int> digits = List<int>.generate(10, (int index) => index++); test( 'ctor should create JavascriptChannel when name starts with a valid character followed by a number.', () { for (final String char in validChars) { for (final int digit in digits) { final JavascriptChannel channel = JavascriptChannel(name: '$char$digit', onMessageReceived: (_) {}); expect(channel.name, '$char$digit'); } } }); test('ctor should assert when channel name starts with a number.', () { for (final int i in digits) { expect( () => JavascriptChannel(name: '$i', onMessageReceived: (_) {}), throwsAssertionError, ); } }); test('ctor should assert when channel contains invalid char.', () { for (final String validChar in validChars) { for (final String invalidChar in commonInvalidChars) { expect( () => JavascriptChannel( name: validChar + invalidChar, onMessageReceived: (_) {}), throwsAssertionError, ); } } }); }
plugins/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/javascript_channel_test.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/javascript_channel_test.dart", "repo_id": "plugins", "token_count": 620 }
1,177
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <XCTest/XCTest.h> @import webview_flutter_wkwebview; @import webview_flutter_wkwebview.Test; @interface FWFInstanceManagerTests : XCTestCase @end @implementation FWFInstanceManagerTests - (void)testAddDartCreatedInstance { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; NSObject *object = [[NSObject alloc] init]; [instanceManager addDartCreatedInstance:object withIdentifier:0]; XCTAssertEqualObjects([instanceManager instanceForIdentifier:0], object); XCTAssertEqual([instanceManager identifierWithStrongReferenceForInstance:object], 0); } - (void)testAddHostCreatedInstance { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; NSObject *object = [[NSObject alloc] init]; [instanceManager addHostCreatedInstance:object]; long identifier = [instanceManager identifierWithStrongReferenceForInstance:object]; XCTAssertNotEqual(identifier, NSNotFound); XCTAssertEqualObjects([instanceManager instanceForIdentifier:identifier], object); } - (void)testRemoveInstanceWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; NSObject *object = [[NSObject alloc] init]; [instanceManager addDartCreatedInstance:object withIdentifier:0]; XCTAssertEqualObjects([instanceManager removeInstanceWithIdentifier:0], object); XCTAssertEqual([instanceManager strongInstanceCount], 0); } - (void)testDeallocCallbackIsIgnoredIfNull { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wnonnull" // This sets deallocCallback to nil to test that uses are null checked. FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] initWithDeallocCallback:nil]; #pragma clang diagnostic pop [instanceManager addDartCreatedInstance:[[NSObject alloc] init] withIdentifier:0]; // Tests that this doesn't cause a EXC_BAD_ACCESS crash. [instanceManager removeInstanceWithIdentifier:0]; } @end
plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFInstanceManagerTests.m/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFInstanceManagerTests.m", "repo_id": "plugins", "token_count": 598 }
1,178