text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
import 'dart:async'; import 'dart:math'; import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// Signature for the callback called when the used has /// submitted their initials on the [InitialsInputDisplay]. typedef InitialsOnSubmit = void Function(String); final _bodyTextPaint = TextPaint( style: const TextStyle( fontSize: 3, color: PinballColors.white, fontFamily: PinballFonts.pixeloidSans, ), ); final _subtitleTextPaint = TextPaint( style: const TextStyle( fontSize: 1.8, color: PinballColors.white, fontFamily: PinballFonts.pixeloidSans, ), ); /// {@template initials_input_display} /// Display that handles the user input on the game over view. /// {@endtemplate} class InitialsInputDisplay extends Component with HasGameRef { /// {@macro initials_input_display} InitialsInputDisplay({ required int score, required String characterIconPath, InitialsOnSubmit? onSubmit, }) : _onSubmit = onSubmit, super( children: [ _ScoreLabelTextComponent(), _ScoreTextComponent(score.formatScore()), _NameLabelTextComponent(), _CharacterIconSpriteComponent(characterIconPath), _DividerSpriteComponent(), _InstructionsComponent(), ], ); final InitialsOnSubmit? _onSubmit; @override Future<void> onLoad() async { for (var i = 0; i < 3; i++) { await add( InitialsLetterPrompt( position: Vector2( 10.8 + (2.5 * i), -20, ), hasFocus: i == 0, ), ); } await add( KeyboardInputController( keyUp: { LogicalKeyboardKey.arrowLeft: () => _movePrompt(true), LogicalKeyboardKey.arrowRight: () => _movePrompt(false), LogicalKeyboardKey.enter: _submit, }, ), ); } /// Returns the current entered initials String get initials => children .whereType<InitialsLetterPrompt>() .map((prompt) => prompt.char) .join(); bool _submit() { _onSubmit?.call(initials); return true; } bool _movePrompt(bool left) { final prompts = children.whereType<InitialsLetterPrompt>().toList(); final current = prompts.firstWhere((prompt) => prompt.hasFocus) ..hasFocus = false; var index = prompts.indexOf(current) + (left ? -1 : 1); index = min(max(0, index), prompts.length - 1); prompts[index].hasFocus = true; return false; } } class _ScoreLabelTextComponent extends TextComponent { _ScoreLabelTextComponent() : super( anchor: Anchor.centerLeft, position: Vector2(-16.9, -24), textRenderer: _bodyTextPaint.copyWith( (style) => style.copyWith( color: PinballColors.red, ), ), ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().score; } } class _ScoreTextComponent extends TextComponent { _ScoreTextComponent(String score) : super( text: score, anchor: Anchor.centerLeft, position: Vector2(-16.9, -20), textRenderer: _bodyTextPaint, ); } class _NameLabelTextComponent extends TextComponent { _NameLabelTextComponent() : super( anchor: Anchor.center, position: Vector2(10.8, -24), textRenderer: _bodyTextPaint.copyWith( (style) => style.copyWith( color: PinballColors.red, ), ), ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().name; } } class _CharacterIconSpriteComponent extends SpriteComponent with HasGameRef { _CharacterIconSpriteComponent(String characterIconPath) : _characterIconPath = characterIconPath, super( anchor: Anchor.center, position: Vector2(7.6, -20), ); final String _characterIconPath; @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite(gameRef.images.fromCache(_characterIconPath)); this.sprite = sprite; size = sprite.originalSize / 20; } } /// {@template initials_input_display} /// Display that handles the user input on the game over view. /// {@endtemplate} @visibleForTesting class InitialsLetterPrompt extends PositionComponent { /// {@macro initials_input_display} InitialsLetterPrompt({ required Vector2 position, bool hasFocus = false, }) : _hasFocus = hasFocus, super( position: position, ); static const _alphabetCode = 65; static const _alphabetLength = 25; var _charIndex = 0; bool _hasFocus; late RectangleComponent _underscore; late TextComponent _input; late TimerComponent _underscoreBlinker; @override Future<void> onLoad() async { _underscore = RectangleComponent( size: Vector2(1.9, 0.4), anchor: Anchor.center, position: Vector2(-0.1, 1.8), ); await add(_underscore); _input = TextComponent( text: 'A', textRenderer: _bodyTextPaint, anchor: Anchor.center, ); await add(_input); _underscoreBlinker = TimerComponent( period: 0.6, repeat: true, autoStart: _hasFocus, onTick: () { _underscore.paint.color = (_underscore.paint.color == Colors.white) ? Colors.transparent : Colors.white; }, ); await add(_underscoreBlinker); await add( KeyboardInputController( keyUp: { LogicalKeyboardKey.arrowUp: () => _cycle(true), LogicalKeyboardKey.arrowDown: () => _cycle(false), }, ), ); } /// Returns the current selected character String get char => String.fromCharCode(_alphabetCode + _charIndex); bool _cycle(bool up) { if (_hasFocus) { var newCharCode = _charIndex + (up ? -1 : 1); if (newCharCode < 0) newCharCode = _alphabetLength; if (newCharCode > _alphabetLength) newCharCode = 0; _input.text = String.fromCharCode(_alphabetCode + newCharCode); _charIndex = newCharCode; return false; } return true; } /// Returns if this prompt has focus on it bool get hasFocus => _hasFocus; /// Updates this prompt focus set hasFocus(bool hasFocus) { if (hasFocus) { _underscoreBlinker.timer.resume(); } else { _underscoreBlinker.timer.pause(); } _underscore.paint.color = Colors.white; _hasFocus = hasFocus; } } class _DividerSpriteComponent extends SpriteComponent with HasGameRef { _DividerSpriteComponent() : super( anchor: Anchor.center, position: Vector2(0, -17), ); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache(Assets.images.backbox.displayDivider.keyName), ); this.sprite = sprite; size = sprite.originalSize / 20; } } class _InstructionsComponent extends PositionComponent with HasGameRef { _InstructionsComponent() : super( anchor: Anchor.center, position: Vector2(0, -12.3), children: [ _EnterInitialsTextComponent(), _ArrowsTextComponent(), _AndPressTextComponent(), _EnterReturnTextComponent(), _ToSubmitTextComponent(), ], ); } class _EnterInitialsTextComponent extends TextComponent { _EnterInitialsTextComponent() : super( anchor: Anchor.center, position: Vector2(0, -2.4), textRenderer: _subtitleTextPaint, ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().enterInitials; } } class _ArrowsTextComponent extends TextComponent { _ArrowsTextComponent() : super( anchor: Anchor.center, position: Vector2(-13.2, 0), textRenderer: _subtitleTextPaint.copyWith( (style) => style.copyWith( fontWeight: FontWeight.bold, ), ), ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().arrows; } } class _AndPressTextComponent extends TextComponent { _AndPressTextComponent() : super( anchor: Anchor.center, position: Vector2(-3.7, 0), textRenderer: _subtitleTextPaint, ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().andPress; } } class _EnterReturnTextComponent extends TextComponent { _EnterReturnTextComponent() : super( anchor: Anchor.center, position: Vector2(10, 0), textRenderer: _subtitleTextPaint.copyWith( (style) => style.copyWith( fontWeight: FontWeight.bold, ), ), ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().enterReturn; } } class _ToSubmitTextComponent extends TextComponent { _ToSubmitTextComponent() : super( anchor: Anchor.center, position: Vector2(0, 2.4), textRenderer: _subtitleTextPaint, ); @override Future<void> onLoad() async { await super.onLoad(); text = readProvider<AppLocalizations>().toSubmit; } }
pinball/lib/game/components/backbox/displays/initials_input_display.dart/0
{ "file_path": "pinball/lib/game/components/backbox/displays/initials_input_display.dart", "repo_id": "pinball", "token_count": 4001 }
1,171
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/game/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Bonus obtained at the [FlutterForest]. /// /// When all [DashBumper]s are hit at least once three times, the [Signpost] /// progresses. When the [Signpost] fully progresses, the [GameBonus.dashNest] /// is awarded, and the [DashBumper.main] releases a new [Ball]. class FlutterForestBonusBehavior extends Component { @override Future<void> onLoad() async { await super.onLoad(); await add( FlameBlocListener<SignpostCubit, SignpostState>( listenWhen: (_, state) => state == SignpostState.active3, onNewState: (_) { readBloc<GameBloc, GameState>() .add(const BonusActivated(GameBonus.dashNest)); readBloc<SignpostCubit, SignpostState>().onProgressed(); readBloc<DashBumpersCubit, DashBumpersState>().onReset(); add(BonusBallSpawningBehavior()); }, ), ); } }
pinball/lib/game/components/flutter_forest/behaviors/flutter_forest_bonus_behavior.dart/0
{ "file_path": "pinball/lib/game/components/flutter_forest/behaviors/flutter_forest_bonus_behavior.dart", "repo_id": "pinball", "token_count": 445 }
1,172
export 'bloc/game_bloc.dart'; export 'components/components.dart'; export 'game_assets.dart'; export 'pinball_game.dart'; export 'view/view.dart';
pinball/lib/game/game.dart/0
{ "file_path": "pinball/lib/game/game.dart", "repo_id": "pinball", "token_count": 57 }
1,173
export 'widgets/widgets.dart';
pinball/lib/how_to_play/how_to_play.dart/0
{ "file_path": "pinball/lib/how_to_play/how_to_play.dart", "repo_id": "pinball", "token_count": 12 }
1,174
part of 'start_game_bloc.dart'; /// {@template start_game_event} /// Event added during the start game flow. /// {@endtemplate} abstract class StartGameEvent extends Equatable { /// {@macro start_game_event} const StartGameEvent(); } /// {@template play_tapped} /// Play tapped event. /// {@endtemplate} class PlayTapped extends StartGameEvent { /// {@macro play_tapped} const PlayTapped(); @override List<Object> get props => []; } /// {@template replay_tapped} /// Replay tapped event. /// {@endtemplate} class ReplayTapped extends StartGameEvent { /// {@macro replay_tapped} const ReplayTapped(); @override List<Object> get props => []; } /// {@template character_selected} /// Character selected event. /// {@endtemplate} class CharacterSelected extends StartGameEvent { /// {@macro character_selected} const CharacterSelected(); @override List<Object> get props => []; } /// {@template how_to_play_finished} /// How to play finished event. /// {@endtemplate} class HowToPlayFinished extends StartGameEvent { /// {@macro how_to_play_finished} const HowToPlayFinished(); @override List<Object> get props => []; }
pinball/lib/start_game/bloc/start_game_event.dart/0
{ "file_path": "pinball/lib/start_game/bloc/start_game_event.dart", "repo_id": "pinball", "token_count": 366 }
1,175
name: geometry description: Provides a set of helpers for working with 2D geometry. version: 1.0.0+1 publish_to: none environment: sdk: ">=2.16.0 <3.0.0" dependencies: vector_math: ^2.1.1 dev_dependencies: mocktail: ^0.2.0 test: ^1.19.2 very_good_analysis: ^2.4.0
pinball/packages/geometry/pubspec.yaml/0
{ "file_path": "pinball/packages/geometry/pubspec.yaml", "repo_id": "pinball", "token_count": 120 }
1,176
export 'assets.gen.dart'; export 'fonts.gen.dart'; export 'pinball_fonts.dart';
pinball/packages/pinball_components/lib/gen/gen.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/gen/gen.dart", "repo_id": "pinball", "token_count": 33 }
1,177
// ignore_for_file: public_member_api_docs import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:pinball_theme/pinball_theme.dart'; part 'arcade_background_state.dart'; class ArcadeBackgroundCubit extends Cubit<ArcadeBackgroundState> { ArcadeBackgroundCubit() : super(const ArcadeBackgroundState.initial()); void onCharacterSelected(CharacterTheme characterTheme) { emit(ArcadeBackgroundState(characterTheme: characterTheme)); } }
pinball/packages/pinball_components/lib/src/components/arcade_background/cubit/arcade_background_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/arcade_background/cubit/arcade_background_cubit.dart", "repo_id": "pinball", "token_count": 144 }
1,178
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template bumping_behavior} /// Makes any [BodyComponent] that contacts with [parent] bounce off. /// {@endtemplate} class BumpingBehavior extends ContactBehavior { /// {@macro bumping_behavior} BumpingBehavior({required double strength}) : assert(strength >= 0, "Strength can't be negative."), _strength = strength; /// Determines how strong the bump is. final double _strength; /// This is used to recognize the current state of a contact manifold in world /// coordinates. @visibleForTesting final WorldManifold worldManifold = WorldManifold(); @override void postSolve(Object other, Contact contact, ContactImpulse impulse) { super.postSolve(other, contact, impulse); if (other is! BodyComponent) return; contact.getWorldManifold(worldManifold); other.body.applyLinearImpulse( worldManifold.normal ..multiply( Vector2.all(other.body.mass * _strength), ), ); } }
pinball/packages/pinball_components/lib/src/components/bumping_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/bumping_behavior.dart", "repo_id": "pinball", "token_count": 371 }
1,179
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/pinball_components.dart'; import 'package:pinball_components/src/components/bumping_behavior.dart'; import 'package:pinball_components/src/components/dash_bumper/behaviors/behaviors.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/dash_bumpers_cubit.dart'; enum DashBumperSpriteState { active, inactive, } enum DashBumperId { main, a, b, } /// {@template dash_bumper} /// Bumper for the flutter forest. /// {@endtemplate} class DashBumper extends BodyComponent with InitialPosition { /// {@macro dash_bumper} DashBumper._({ required this.id, required double majorRadius, required double minorRadius, required String activeAssetPath, required String inactiveAssetPath, required Vector2 spritePosition, Iterable<Component>? children, }) : _majorRadius = majorRadius, _minorRadius = minorRadius, super( renderBody: false, children: [ DashBumperSpriteGroupComponent( id: id, activeAssetPath: activeAssetPath, inactiveAssetPath: inactiveAssetPath, position: spritePosition, ), DashBumperBallContactBehavior(), ...?children, ], ); /// {@macro dash_bumper} /// /// [DashBumper.main], usually positioned with a [DashAnimatronic] on top of /// it. DashBumper.main({ Iterable<Component>? children, }) : this._( id: DashBumperId.main, majorRadius: 5.1, minorRadius: 3.75, activeAssetPath: Assets.images.dash.bumper.main.active.keyName, inactiveAssetPath: Assets.images.dash.bumper.main.inactive.keyName, spritePosition: Vector2(0, -0.3), children: [ ...?children, BumpingBehavior(strength: 20), ], ); /// {@macro dash_bumper} /// /// [DashBumper.a] is positioned at the right side of the [DashBumper.main] in /// the flutter forest. DashBumper.a({ Iterable<Component>? children, }) : this._( id: DashBumperId.a, majorRadius: 3, minorRadius: 2.2, activeAssetPath: Assets.images.dash.bumper.a.active.keyName, inactiveAssetPath: Assets.images.dash.bumper.a.inactive.keyName, spritePosition: Vector2(0.3, -1.3), children: [ ...?children, BumpingBehavior(strength: 20), ], ); /// {@macro dash_bumper} /// /// [DashBumper.b] is positioned at the left side of the [DashBumper.main] in /// the flutter forest. DashBumper.b({ Iterable<Component>? children, }) : this._( id: DashBumperId.b, majorRadius: 3.1, minorRadius: 2.2, activeAssetPath: Assets.images.dash.bumper.b.active.keyName, inactiveAssetPath: Assets.images.dash.bumper.b.inactive.keyName, spritePosition: Vector2(0.4, -1.2), children: [ ...?children, BumpingBehavior(strength: 20), ], ); /// Creates a [DashBumper] without any children. /// /// This can be used for testing [DashBumper]'s behaviors in isolation. @visibleForTesting DashBumper.test({required this.id}) : _majorRadius = 3, _minorRadius = 2.5; final DashBumperId id; final double _majorRadius; final double _minorRadius; @override Body createBody() { final shape = EllipseShape( center: Vector2.zero(), majorRadius: _majorRadius, minorRadius: _minorRadius, )..rotate(math.pi / 1.9); final bodyDef = BodyDef( position: initialPosition, ); return world.createBody(bodyDef)..createFixtureFromShape(shape); } } @visibleForTesting class DashBumperSpriteGroupComponent extends SpriteGroupComponent<DashBumperSpriteState> with HasGameRef, FlameBlocListenable<DashBumpersCubit, DashBumpersState> { DashBumperSpriteGroupComponent({ required DashBumperId id, required String activeAssetPath, required String inactiveAssetPath, required Vector2 position, }) : _id = id, _activeAssetPath = activeAssetPath, _inactiveAssetPath = inactiveAssetPath, super( anchor: Anchor.center, position: position, ); final DashBumperId _id; final String _activeAssetPath; final String _inactiveAssetPath; @override bool listenWhen(DashBumpersState previousState, DashBumpersState newState) { return previousState.bumperSpriteStates[_id] != newState.bumperSpriteStates[_id]; } @override void onNewState(DashBumpersState state) => current = state.bumperSpriteStates[_id]; @override Future<void> onLoad() async { await super.onLoad(); final sprites = { DashBumperSpriteState.active: Sprite(gameRef.images.fromCache(_activeAssetPath)), DashBumperSpriteState.inactive: Sprite(gameRef.images.fromCache(_inactiveAssetPath)), }; this.sprites = sprites; current = DashBumperSpriteState.inactive; size = sprites[current]!.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/dash_bumper/dash_bumper.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/dash_bumper/dash_bumper.dart", "repo_id": "pinball", "token_count": 2215 }
1,180
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'; class GoogleRolloverBallContactBehavior extends ContactBehavior<GoogleRollover> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; readBloc<GoogleWordCubit, GoogleWordState>().onRolloverContacted(); parent.firstChild<SpriteAnimationComponent>()?.playing = true; } }
pinball/packages/pinball_components/lib/src/components/google_rollover/behaviors/google_rollover_ball_contact_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/google_rollover/behaviors/google_rollover_ball_contact_behavior.dart", "repo_id": "pinball", "token_count": 189 }
1,181
export 'behaviors.dart'; export 'layer_filtering_behavior.dart';
pinball/packages/pinball_components/lib/src/components/layer_sensor/behaviors/behaviors.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/layer_sensor/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 23 }
1,182
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball_components/pinball_components.dart'; class PlungerReleasingBehavior extends Component with FlameBlocListenable<PlungerCubit, PlungerState> { PlungerReleasingBehavior({ required double strength, }) : assert(strength >= 0, "Strength can't be negative."), _strength = strength; final double _strength; late final Plunger _plunger; @override Future<void> onLoad() async { await super.onLoad(); _plunger = parent!.parent! as Plunger; } @override void onNewState(PlungerState state) { super.onNewState(state); if (state.isReleasing) { final velocity = (_plunger.initialPosition.y - _plunger.body.position.y) * _strength; _plunger.body.linearVelocity = Vector2(0, velocity); } } }
pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_releasing_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_releasing_behavior.dart", "repo_id": "pinball", "token_count": 324 }
1,183
import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/skill_shot/behaviors/behaviors.dart'; import 'package:pinball_flame/pinball_flame.dart'; export 'cubit/skill_shot_cubit.dart'; /// {@template skill_shot} /// Rollover awarding extra points. /// {@endtemplate} class SkillShot extends BodyComponent with ZIndex { /// {@macro skill_shot} SkillShot({Iterable<Component>? children}) : this._( children: children, bloc: SkillShotCubit(), ); SkillShot._({ Iterable<Component>? children, required this.bloc, }) : super( renderBody: false, children: [ SkillShotBallContactBehavior(), SkillShotBlinkingBehavior(), _RolloverDecalSpriteComponent(), PinSpriteAnimationComponent(), _TextDecalSpriteGroupComponent(state: bloc.state.spriteState), ...?children, ], ) { zIndex = ZIndexes.decal; } /// Creates a [SkillShot] without any children. /// /// This can be used for testing [SkillShot]'s behaviors in isolation. @visibleForTesting SkillShot.test({ required this.bloc, }); final SkillShotCubit bloc; @override void onRemove() { bloc.close(); super.onRemove(); } @override Body createBody() { final shape = PolygonShape() ..setAsBox( 0.1, 3.7, Vector2(-31.9, 9.1), 0.11, ); final fixtureDef = FixtureDef(shape, isSensor: true); return world.createBody(BodyDef())..createFixture(fixtureDef); } } class _RolloverDecalSpriteComponent extends SpriteComponent with HasGameRef { _RolloverDecalSpriteComponent() : super( anchor: Anchor.center, position: Vector2(-31.9, 9.1), angle: 0.11, ); @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.skillShot.decal.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 20; } } /// {@template pin_sprite_animation_component} /// Animation for pin in [SkillShot] rollover. /// {@endtemplate} @visibleForTesting class PinSpriteAnimationComponent extends SpriteAnimationComponent with HasGameRef { /// {@macro pin_sprite_animation_component} PinSpriteAnimationComponent() : super( anchor: Anchor.center, position: Vector2(-31.9, 9.1), angle: 0, playing: false, ); @override Future<void> onLoad() async { await super.onLoad(); final spriteSheet = gameRef.images.fromCache( Assets.images.skillShot.pin.keyName, ); const amountPerRow = 3; const amountPerColumn = 1; final textureSize = Vector2( spriteSheet.width / amountPerRow, spriteSheet.height / amountPerColumn, ); size = textureSize / 10; animation = SpriteAnimation.fromFrameData( spriteSheet, SpriteAnimationData.sequenced( amount: amountPerRow * amountPerColumn, amountPerRow: amountPerRow, stepTime: 1 / 24, textureSize: textureSize, loop: false, ), )..onComplete = () { animation?.reset(); playing = false; }; } } class _TextDecalSpriteGroupComponent extends SpriteGroupComponent<SkillShotSpriteState> with HasGameRef, ParentIsA<SkillShot> { _TextDecalSpriteGroupComponent({ required SkillShotSpriteState state, }) : super( anchor: Anchor.center, position: Vector2(-35.55, 3.59), current: state, ); @override Future<void> onLoad() async { await super.onLoad(); parent.bloc.stream.listen((state) => current = state.spriteState); final sprites = { SkillShotSpriteState.lit: Sprite( gameRef.images.fromCache(Assets.images.skillShot.lit.keyName), ), SkillShotSpriteState.dimmed: Sprite( gameRef.images.fromCache(Assets.images.skillShot.dimmed.keyName), ), }; this.sprites = sprites; size = sprites[current]!.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/skill_shot/skill_shot.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/skill_shot/skill_shot.dart", "repo_id": "pinball", "token_count": 1749 }
1,184
import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template sparky_computer_sensor_ball_contact_behavior} /// When a [Ball] enters the [SparkyComputer] it is stopped for a period of time /// before a [BallTurboChargingBehavior] is applied to it. /// {@endtemplate} class SparkyComputerSensorBallContactBehavior extends ContactBehavior<SparkyComputer> { @override Future<void> beginContact(Object other, Contact contact) async { super.beginContact(other, contact); if (other is! Ball) return; other.stop(); parent.bloc.onBallEntered(); await parent.add( TimerComponent( period: 1.5, removeOnFinish: true, onTick: () async { other.resume(); await other.add( BallTurboChargingBehavior( impulse: Vector2(40, 110), ), ); parent.bloc.onBallTurboCharged(); }, ), ); } }
pinball/packages/pinball_components/lib/src/components/sparky_computer/behaviors/sparky_computer_sensor_ball_contact_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/sparky_computer/behaviors/sparky_computer_sensor_ball_contact_behavior.dart", "repo_id": "pinball", "token_count": 441 }
1,185
export 'add_game.dart'; export 'games.dart'; export 'trace.dart';
pinball/packages/pinball_components/sandbox/lib/common/common.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/common/common.dart", "repo_id": "pinball", "token_count": 26 }
1,186
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class BaseboardGame extends BallGame { BaseboardGame() : super( imagesFileNames: [ Assets.images.baseboard.left.keyName, Assets.images.baseboard.right.keyName, ], ); static const description = ''' Shows how the Baseboards 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(); final center = screenToWorld(camera.viewport.canvasSize! / 2); await addAll([ Baseboard(side: BoardSide.left) ..initialPosition = center - Vector2(25, 0) ..priority = 1, Baseboard(side: BoardSide.right) ..initialPosition = center + Vector2(25, 0) ..priority = 1, ]); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/bottom_group/baseboard_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/bottom_group/baseboard_game.dart", "repo_id": "pinball", "token_count": 404 }
1,187
import 'dart:async'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class DashBumperBGame extends BallGame { DashBumperBGame() : super( imagesFileNames: [ Assets.images.dash.bumper.b.active.keyName, Assets.images.dash.bumper.b.inactive.keyName, ], ); static const description = ''' Shows how the "b" DashBumper is rendered. - Activate the "trace" parameter to overlay the body. '''; @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2.zero()); await add( FlameBlocProvider<DashBumpersCubit, DashBumpersState>( create: DashBumpersCubit.new, children: [ DashBumper.b()..priority = 1, ], ), ); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/flutter_forest/dash_bumper_b_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/flutter_forest/dash_bumper_b_game.dart", "repo_id": "pinball", "token_count": 412 }
1,188
import 'dart:math'; import 'package:flame/effects.dart'; import 'package:flame/input.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/common/common.dart'; class ScoreGame extends AssetsGame with TapDetector { ScoreGame() : super( imagesFileNames: [ Assets.images.score.fiveThousand.keyName, Assets.images.score.twentyThousand.keyName, Assets.images.score.twoHundredThousand.keyName, Assets.images.score.oneMillion.keyName, ], ); static const description = ''' Simple game to show how score component works, - Tap anywhere on the screen to spawn an image on the given location. '''; final random = Random(); @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2.zero()); } @override void onTapUp(TapUpInfo info) { final index = random.nextInt(Points.values.length); final score = Points.values[index]; add( ScoreComponent( points: score, position: info.eventPosition.game..multiply(Vector2(1, -1)), effectController: EffectController(duration: 1), ), ); } }
pinball/packages/pinball_components/sandbox/lib/stories/score/score_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/score/score_game.dart", "repo_id": "pinball", "token_count": 467 }
1,189
import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; class TestGame extends Forge2DGame { TestGame([List<String>? assets]) : _assets = assets { images.prefix = ''; } final List<String>? _assets; @override Future<void> onLoad() async { if (_assets != null) { await images.loadAll(_assets!); } await super.onLoad(); } } class KeyboardTestGame extends TestGame with HasKeyboardHandlerComponents { KeyboardTestGame([List<String>? assets]) : super(assets); } class TappablesTestGame extends TestGame with HasTappables { TappablesTestGame([List<String>? assets]) : super(assets); }
pinball/packages/pinball_components/test/helpers/test_game.dart/0
{ "file_path": "pinball/packages/pinball_components/test/helpers/test_game.dart", "repo_id": "pinball", "token_count": 235 }
1,190
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; import '../../../../helpers/helpers.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester( () => TestGame([theme.Assets.images.dash.ball.keyName]), ); group('BallScalingBehavior', () { test('can be instantiated', () { expect( BallScalingBehavior(), isA<BallScalingBehavior>(), ); }); flameTester.test('can be loaded', (game) async { final ball = Ball.test(); final behavior = BallScalingBehavior(); await ball.add(behavior); await game.ensureAdd(ball); expect( ball.firstChild<BallScalingBehavior>(), equals(behavior), ); }); flameTester.test('scales the shape radius', (game) async { final ball1 = Ball.test()..initialPosition = Vector2(0, 10); await ball1.add(BallScalingBehavior()); final ball2 = Ball.test()..initialPosition = Vector2(0, -10); await ball2.add(BallScalingBehavior()); await game.ensureAddAll([ball1, ball2]); game.update(1); final shape1 = ball1.body.fixtures.first.shape; final shape2 = ball2.body.fixtures.first.shape; expect( shape1.radius, greaterThan(shape2.radius), ); }); flameTester.test( 'scales the sprite', (game) async { final ball1 = Ball.test()..initialPosition = Vector2(0, 10); await ball1.add(BallScalingBehavior()); final ball2 = Ball.test()..initialPosition = Vector2(0, -10); await ball2.add(BallScalingBehavior()); await game.ensureAddAll([ball1, ball2]); game.update(1); final sprite1 = ball1.descendants().whereType<SpriteComponent>().single; final sprite2 = ball2.descendants().whereType<SpriteComponent>().single; expect( sprite1.scale.x, greaterThan(sprite2.scale.x), ); expect( sprite1.scale.y, greaterThan(sprite2.scale.y), ); }, ); }); }
pinball/packages/pinball_components/test/src/components/ball/behaviors/ball_scaling_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/ball/behaviors/ball_scaling_behavior_test.dart", "repo_id": "pinball", "token_count": 967 }
1,191
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group( 'ChromeDinoCubit', () { final ball = Ball(); blocTest<ChromeDinoCubit, ChromeDinoState>( 'onOpenMouth emits true', build: ChromeDinoCubit.new, act: (bloc) => bloc.onOpenMouth(), expect: () => [ isA<ChromeDinoState>().having( (state) => state.isMouthOpen, 'isMouthOpen', true, ) ], ); blocTest<ChromeDinoCubit, ChromeDinoState>( 'onCloseMouth emits false', build: ChromeDinoCubit.new, act: (bloc) => bloc.onCloseMouth(), expect: () => [ isA<ChromeDinoState>().having( (state) => state.isMouthOpen, 'isMouthOpen', false, ) ], ); blocTest<ChromeDinoCubit, ChromeDinoState>( 'onChomp emits ChromeDinoStatus.chomping and chomped ball ' 'when the ball is not in the mouth', build: ChromeDinoCubit.new, act: (bloc) => bloc.onChomp(ball), expect: () => [ isA<ChromeDinoState>() ..having( (state) => state.status, 'status', ChromeDinoStatus.chomping, ) ..having( (state) => state.ball, 'ball', ball, ) ], ); blocTest<ChromeDinoCubit, ChromeDinoState>( 'onChomp emits nothing when the ball is already in the mouth', build: ChromeDinoCubit.new, seed: () => const ChromeDinoState.initial().copyWith(ball: ball), act: (bloc) => bloc.onChomp(ball), expect: () => <ChromeDinoState>[], ); blocTest<ChromeDinoCubit, ChromeDinoState>( 'onSpit emits ChromeDinoStatus.idle and removes ball', build: ChromeDinoCubit.new, act: (bloc) => bloc.onSpit(), expect: () => [ isA<ChromeDinoState>().having( (state) => state.status, 'status', ChromeDinoStatus.idle, )..having( (state) => state.ball, 'ball', null, ) ], ); }, ); }
pinball/packages/pinball_components/test/src/components/chrome_dino/cubit/chrome_dino_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/chrome_dino/cubit/chrome_dino_cubit_test.dart", "repo_id": "pinball", "token_count": 1233 }
1,192
// ignore_for_file: avoid_dynamic_calls, cascade_invocations import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { Future<void> pump( FlipperMovingBehavior behavior, { FlipperCubit? flipperBloc, PinballAudioPlayer? audioPlayer, }) async { final flipper = Flipper.test(side: BoardSide.left); await ensureAdd(flipper); await flipper.ensureAdd( FlameBlocProvider<FlipperCubit, FlipperState>.value( value: flipperBloc ?? FlipperCubit(), children: [behavior], ), ); } } class _MockFlipperCubit extends Mock implements FlipperCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('FlipperMovingBehavior', () { test('can be instantiated', () { expect( FlipperMovingBehavior(strength: 0), isA<FlipperMovingBehavior>(), ); }); test('throws assertion error when strength is negative', () { expect( () => FlipperMovingBehavior(strength: -1), throwsAssertionError, ); }); flameTester.test('can be loaded', (game) async { final behavior = FlipperMovingBehavior(strength: 0); await game.pump(behavior); expect(game.descendants(), contains(behavior)); }); flameTester.test( 'applies vertical velocity to flipper when moving down', (game) async { final bloc = _MockFlipperCubit(); final streamController = StreamController<FlipperState>(); whenListen( bloc, streamController.stream, initialState: FlipperState.movingUp, ); const strength = 10.0; final behavior = FlipperMovingBehavior(strength: strength); await game.pump(behavior, flipperBloc: bloc); streamController.add(FlipperState.movingDown); await Future<void>.delayed(Duration.zero); final flipper = behavior.ancestors().whereType<Flipper>().single; expect(flipper.body.linearVelocity.x, 0); expect(flipper.body.linearVelocity.y, strength); }, ); flameTester.test( 'applies vertical velocity to flipper when moving up', (game) async { final bloc = _MockFlipperCubit(); whenListen( bloc, Stream.value(FlipperState.movingUp), initialState: FlipperState.movingUp, ); const strength = 10.0; final behavior = FlipperMovingBehavior(strength: strength); await game.pump(behavior, flipperBloc: bloc); game.update(0); final flipper = behavior.ancestors().whereType<Flipper>().single; expect(flipper.body.linearVelocity.x, 0); expect(flipper.body.linearVelocity.y, -strength); }, ); }); }
pinball/packages/pinball_components/test/src/components/flipper/behaviors/flipper_moving_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/flipper/behaviors/flipper_moving_behavior_test.dart", "repo_id": "pinball", "token_count": 1269 }
1,193
// ignore_for_file: cascade_invocations import 'package:bloc_test/bloc_test.dart'; import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/bumping_behavior.dart'; import 'package:pinball_components/src/components/kicker/behaviors/behaviors.dart'; import '../../helpers/helpers.dart'; class _MockKickerCubit extends Mock implements KickerCubit {} void main() { group('Kicker', () { final assets = [ Assets.images.kicker.left.lit.keyName, Assets.images.kicker.left.dimmed.keyName, Assets.images.kicker.right.lit.keyName, Assets.images.kicker.right.dimmed.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); final leftKicker = Kicker( side: BoardSide.left, ) ..initialPosition = Vector2(-20, 0) ..renderBody = false; final rightKicker = Kicker( side: BoardSide.right, )..initialPosition = Vector2(20, 0); await game.ensureAddAll([leftKicker, rightKicker]); game.camera.followVector2(Vector2.zero()); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/kickers.png'), ); }, ); flameTester.test( 'loads correctly', (game) async { final kicker = Kicker.test( side: BoardSide.left, bloc: KickerCubit(), ); await game.ensureAdd(kicker); expect(game.contains(kicker), isTrue); }, ); flameTester.test('closes bloc when removed', (game) async { final bloc = _MockKickerCubit(); whenListen( bloc, const Stream<KickerState>.empty(), initialState: KickerState.lit, ); when(bloc.close).thenAnswer((_) async {}); final kicker = Kicker.test( side: BoardSide.left, bloc: bloc, ); await game.ensureAdd(kicker); game.remove(kicker); await game.ready(); verify(bloc.close).called(1); }); group('adds', () { flameTester.test('new children', (game) async { final component = Component(); final kicker = Kicker( side: BoardSide.left, children: [component], ); await game.ensureAdd(kicker); expect(kicker.children, contains(component)); }); flameTester.test('a BumpingBehavior', (game) async { final kicker = Kicker( side: BoardSide.left, ); await game.ensureAdd(kicker); expect( kicker.children.whereType<BumpingBehavior>().single, isNotNull, ); }); flameTester.test('a KickerBallContactBehavior', (game) async { final kicker = Kicker( side: BoardSide.left, ); await game.ensureAdd(kicker); expect( kicker.children.whereType<KickerBallContactBehavior>().single, isNotNull, ); }); flameTester.test('a KickerBlinkingBehavior', (game) async { final kicker = Kicker( side: BoardSide.left, ); await game.ensureAdd(kicker); expect( kicker.children.whereType<KickerBlinkingBehavior>().single, isNotNull, ); }); }); }); }
pinball/packages/pinball_components/test/src/components/kicker_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/kicker_test.dart", "repo_id": "pinball", "token_count": 1647 }
1,194
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group('PlungerCubit', () { test('can be instantiated', () { expect(PlungerCubit(), isA<PlungerCubit>()); }); blocTest<PlungerCubit, PlungerState>( 'overrides previous pulling state', build: PlungerCubit.new, act: (cubit) => cubit ..pulled() ..autoPulled() ..pulled(), expect: () => [ PlungerState.pulling, PlungerState.autoPulling, PlungerState.pulling, ], ); }); }
pinball/packages/pinball_components/test/src/components/plunger/cubit/plunger_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/plunger/cubit/plunger_cubit_test.dart", "repo_id": "pinball", "token_count": 294 }
1,195
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/src/components/components.dart'; void main() { group('SpaceshipRampState', () { test('supports value equality', () { expect( SpaceshipRampState( hits: 0, lightState: ArrowLightState.inactive, ), equals( SpaceshipRampState( hits: 0, lightState: ArrowLightState.inactive, ), ), ); }); group('constructor', () { test('can be instantiated', () { expect( SpaceshipRampState( hits: 0, lightState: ArrowLightState.inactive, ), isNotNull, ); }); test( 'throws AssertionError ' 'when hits is negative', () { expect( () => SpaceshipRampState( hits: -1, lightState: ArrowLightState.inactive, ), throwsAssertionError, ); }, ); }); test( 'arrowFullyLit returns true when lightState is last one', () { expect( SpaceshipRampState.initial().arrowFullyLit, isFalse, ); expect( SpaceshipRampState.initial() .copyWith(lightState: ArrowLightState.active5) .arrowFullyLit, isTrue, ); }, ); group('copyWith', () { test( 'throws AssertionError ' 'when hits is decreased', () { const rampState = SpaceshipRampState( hits: 0, lightState: ArrowLightState.inactive, ); expect( () => rampState.copyWith(hits: rampState.hits - 1), throwsAssertionError, ); }, ); test( 'copies correctly ' 'when no argument specified', () { const rampState = SpaceshipRampState( hits: 0, lightState: ArrowLightState.inactive, ); expect( rampState.copyWith(), equals(rampState), ); }, ); test( 'copies correctly ' 'when all arguments specified', () { const rampState = SpaceshipRampState( hits: 0, lightState: ArrowLightState.inactive, ); final otherRampState = SpaceshipRampState( hits: rampState.hits + 1, lightState: ArrowLightState.active1, ); expect(rampState, isNot(equals(otherRampState))); expect( rampState.copyWith( hits: otherRampState.hits, lightState: otherRampState.lightState, ), equals(otherRampState), ); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/spaceship_ramp/cubit/spaceship_ramp_state_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/spaceship_ramp/cubit/spaceship_ramp_state_test.dart", "repo_id": "pinball", "token_count": 1539 }
1,196
import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Appends a new [ContactCallbacks] to the parent. /// /// This is a convenience class for adding a [ContactCallbacks] to the parent. /// In contrast with just assigning a [ContactCallbacks] to a userData, this /// class respects the previous userData. /// /// It does so by grouping the userData in a [_UserData], and resetting the /// parent's userData accordingly. class ContactBehavior<T extends BodyComponent> extends Component with ContactCallbacks, ParentIsA<T> { final _fixturesUserData = <Object>{}; /// Specifies which fixtures should be considered for contact. /// /// Fixtures are identifiable by their userData. /// /// If no fixtures are specified, the [ContactCallbacks] is applied to the /// entire body, hence all fixtures are considered. void applyTo(Iterable<Object> userData) => _fixturesUserData.addAll(userData); @override Future<void> onLoad() async { await super.onLoad(); if (_fixturesUserData.isNotEmpty) { for (final fixture in _targetedFixtures) { fixture.userData = _UserData.fromFixture(fixture)..add(this); } } else { parent.body.userData = _UserData.fromBody(parent.body)..add(this); } } Iterable<Fixture> get _targetedFixtures => parent.body.fixtures.where((fixture) { if (_fixturesUserData.contains(fixture.userData)) return true; final userData = fixture.userData; if (userData is _UserData) { return _fixturesUserData.contains(userData.value); } return false; }); } class _UserData with ContactCallbacks { _UserData._(Object? userData) : _userData = [userData]; factory _UserData._fromUserData(Object? userData) { if (userData is _UserData) return userData; return _UserData._(userData); } factory _UserData.fromFixture(Fixture fixture) => _UserData._fromUserData(fixture.userData); factory _UserData.fromBody(Body body) => _UserData._fromUserData(body.userData); final List<Object?> _userData; Iterable<ContactCallbacks> get _contactCallbacks => _userData.whereType<ContactCallbacks>(); Object? get value => _userData.first; void add(Object? userData) => _userData.add(userData); @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); for (final callback in _contactCallbacks) { callback.beginContact(other, contact); } } @override void endContact(Object other, Contact contact) { super.endContact(other, contact); for (final callback in _contactCallbacks) { callback.endContact(other, contact); } } @override void preSolve(Object other, Contact contact, Manifold oldManifold) { super.preSolve(other, contact, oldManifold); for (final callback in _contactCallbacks) { callback.preSolve(other, contact, oldManifold); } } @override void postSolve(Object other, Contact contact, ContactImpulse impulse) { super.postSolve(other, contact, impulse); for (final callback in _contactCallbacks) { callback.postSolve(other, contact, impulse); } } }
pinball/packages/pinball_flame/lib/src/behaviors/contact_behavior.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/behaviors/contact_behavior.dart", "repo_id": "pinball", "token_count": 1109 }
1,197
import 'dart:math'; import 'package:flame/components.dart'; import 'package:flame/image_composition.dart'; import 'package:flutter/material.dart' hide Animation; /// {@template flame.widgets.sprite_animation_widget} /// A [StatelessWidget] that renders a [SpriteAnimation]. /// {@endtemplate} class SpriteAnimationWidget extends StatelessWidget { /// {@macro flame.widgets.sprite_animation_widget} const SpriteAnimationWidget({ required this.controller, this.anchor = Anchor.topLeft, Key? key, }) : super(key: key); /// The positioning [Anchor]. final Anchor anchor; /// Controller in charge of the sprite animations final SpriteAnimationController controller; @override Widget build(BuildContext context) { return AnimatedBuilder( animation: controller, builder: (_, __) { return CustomPaint( painter: SpritePainter( controller.animation.getSprite(), anchor, ), ); }, ); } } /// {@template sprite_animation_controller} /// Custom [AnimationController] that manages sprite assets /// {@endtemplate} class SpriteAnimationController extends AnimationController { /// {@macro sprite_animation_controller} SpriteAnimationController({ required TickerProvider vsync, required this.animation, }) : super(vsync: vsync) { duration = Duration(seconds: animation.totalDuration().ceil()); } /// [SpriteAnimation] associated to this controller final SpriteAnimation animation; double? _lastUpdated; @override void notifyListeners() { super.notifyListeners(); final now = DateTime.now().millisecond.toDouble(); final dt = max<double>(0, (now - (_lastUpdated ?? 0)) / 1000); animation.update(dt); _lastUpdated = now; } } /// {@template sprite_painter} /// [CustomPainter] specialized in [Sprite] assets. /// {@endtemplate} class SpritePainter extends CustomPainter { /// {@macro sprite_painter} SpritePainter( this._sprite, this._anchor, { double angle = 0, }) : _angle = angle; final Sprite _sprite; final Anchor _anchor; final double _angle; @override bool shouldRepaint(SpritePainter oldDelegate) { return oldDelegate._sprite != _sprite || oldDelegate._anchor != _anchor || oldDelegate._angle != _angle; } @override void paint(Canvas canvas, Size size) { final boxSize = size.toVector2(); final rate = boxSize.clone()..divide(_sprite.srcSize); final minRate = min(rate.x, rate.y); final paintSize = _sprite.srcSize * minRate; final anchorPosition = _anchor.toVector2(); final boxAnchorPosition = boxSize.clone()..multiply(anchorPosition); final spriteAnchorPosition = anchorPosition..multiply(paintSize); canvas ..translateVector(boxAnchorPosition..sub(spriteAnchorPosition)) ..renderRotated( _angle, spriteAnchorPosition, (canvas) => _sprite.render(canvas, size: paintSize), ); } }
pinball/packages/pinball_flame/lib/src/sprite_animation.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/sprite_animation.dart", "repo_id": "pinball", "token_count": 1050 }
1,198
import 'dart:math' as math; import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_flame/pinball_flame.dart'; void main() { group('ArcShape', () { test('can be instantiated', () { expect( ArcShape( center: Vector2.zero(), arcRadius: 10, angle: 2 * math.pi, ), isA<ArcShape>(), ); }); }); }
pinball/packages/pinball_flame/test/src/shapes/arc_shape_test.dart/0
{ "file_path": "pinball/packages/pinball_flame/test/src/shapes/arc_shape_test.dart", "repo_id": "pinball", "token_count": 211 }
1,199
import 'package:pinball_theme/pinball_theme.dart'; /// {@template android_theme} /// Defines Android character theme assets and attributes. /// {@endtemplate} class AndroidTheme extends CharacterTheme { /// {@macro android_theme} const AndroidTheme(); @override String get name => 'Android'; @override AssetGenImage get ball => Assets.images.android.ball; @override AssetGenImage get background => Assets.images.android.background; @override AssetGenImage get icon => Assets.images.android.icon; @override AssetGenImage get leaderboardIcon => Assets.images.android.leaderboardIcon; @override AssetGenImage get animation => Assets.images.android.animation; }
pinball/packages/pinball_theme/lib/src/themes/android_theme.dart/0
{ "file_path": "pinball/packages/pinball_theme/lib/src/themes/android_theme.dart", "repo_id": "pinball", "token_count": 197 }
1,200
import 'package:flutter/widgets.dart'; import 'package:pinball_ui/gen/fonts.gen.dart'; import 'package:pinball_ui/pinball_ui.dart'; const _fontPackage = 'pinball_components'; const _primaryFontFamily = FontFamily.pixeloidSans; /// Different [TextStyle] used in the game abstract class PinballTextStyle { /// Font size: 28 | Color: white static const headline1 = TextStyle( fontSize: 28, package: _fontPackage, fontFamily: _primaryFontFamily, color: PinballColors.white, ); /// Font size: 24 | Color: white static const headline2 = TextStyle( fontSize: 24, package: _fontPackage, fontFamily: _primaryFontFamily, color: PinballColors.white, ); /// Font size: 20 | Color: darkBlue static const headline3 = TextStyle( color: PinballColors.darkBlue, fontSize: 20, package: _fontPackage, fontFamily: _primaryFontFamily, fontWeight: FontWeight.bold, ); /// Font size: 16 | Color: white static const headline4 = TextStyle( color: PinballColors.white, fontSize: 16, package: _fontPackage, fontFamily: _primaryFontFamily, ); /// Font size: 214| Color: white static const headline5 = TextStyle( color: PinballColors.white, fontSize: 14, package: _fontPackage, fontFamily: _primaryFontFamily, ); /// Font size: 12 | Color: white static const subtitle1 = TextStyle( fontSize: 12, fontFamily: _primaryFontFamily, package: _fontPackage, color: PinballColors.yellow, ); }
pinball/packages/pinball_ui/lib/src/theme/pinball_text_style.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/src/theme/pinball_text_style.dart", "repo_id": "pinball", "token_count": 519 }
1,201
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_ui/pinball_ui.dart'; void main() { group('AnimatedEllipsisText', () { testWidgets( 'adds a new `.` every 500ms and ' 'resets back to zero after adding 3', (tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: AnimatedEllipsisText('test'), ), ), ); expect(find.text('test'), findsOneWidget); await tester.pump(const Duration(milliseconds: 600)); expect(find.text('test.'), findsOneWidget); await tester.pump(const Duration(milliseconds: 600)); expect(find.text('test..'), findsOneWidget); await tester.pump(const Duration(milliseconds: 600)); expect(find.text('test...'), findsOneWidget); await tester.pump(const Duration(milliseconds: 600)); expect(find.text('test'), findsOneWidget); }); }); }
pinball/packages/pinball_ui/test/src/widgets/animated_ellipsis_text_test.dart/0
{ "file_path": "pinball/packages/pinball_ui/test/src/widgets/animated_ellipsis_text_test.dart", "repo_id": "pinball", "token_count": 418 }
1,202
export 'share_platform.dart';
pinball/packages/share_repository/lib/src/models/models.dart/0
{ "file_path": "pinball/packages/share_repository/lib/src/models/models.dart", "repo_id": "pinball", "token_count": 10 }
1,203
// ignore_for_file: cascade_invocations import 'package:flame/game.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball/game/behaviors/camera_focusing_behavior.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group( 'CameraFocusingBehavior', () { final flameTester = FlameTester(FlameGame.new); test('can be instantiated', () { expect( CameraFocusingBehavior(), isA<CameraFocusingBehavior>(), ); }); flameTester.test('loads', (game) async { late final behavior = CameraFocusingBehavior(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [behavior], ), ); expect(game.descendants(), contains(behavior)); }); flameTester.test('resizes and snaps', (game) async { final behavior = CameraFocusingBehavior(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [behavior], ), ); behavior.onGameResize(Vector2.all(10)); expect(game.camera.zoom, greaterThan(0)); }); flameTester.test( 'changes focus when loaded', (game) async { final behavior = CameraFocusingBehavior(); final previousZoom = game.camera.zoom; expect(game.camera.follow, isNull); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [behavior], ), ); expect(game.camera.follow, isNotNull); expect(game.camera.zoom, isNot(equals(previousZoom))); }, ); flameTester.test( 'listenWhen only listens when status changes', (game) async { final behavior = CameraFocusingBehavior(); const waiting = GameState.initial(); final playing = const GameState.initial().copyWith(status: GameStatus.playing); final gameOver = const GameState.initial().copyWith(status: GameStatus.gameOver); expect(behavior.listenWhen(waiting, waiting), isFalse); expect(behavior.listenWhen(waiting, playing), isTrue); expect(behavior.listenWhen(waiting, gameOver), isTrue); expect(behavior.listenWhen(playing, playing), isFalse); expect(behavior.listenWhen(playing, waiting), isTrue); expect(behavior.listenWhen(playing, gameOver), isTrue); expect(behavior.listenWhen(gameOver, gameOver), isFalse); expect(behavior.listenWhen(gameOver, waiting), isTrue); expect(behavior.listenWhen(gameOver, playing), isTrue); }, ); group('onNewState', () { flameTester.test( 'zooms when started playing', (game) async { final playing = const GameState.initial().copyWith(status: GameStatus.playing); final behavior = CameraFocusingBehavior(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [behavior], ), ); behavior.onNewState(playing); final previousPosition = game.camera.position.clone(); await game.ready(); final zoom = behavior.children.whereType<CameraZoom>().single; game.update(zoom.controller.duration!); game.update(0); expect(zoom.controller.completed, isTrue); expect( game.camera.position, isNot(equals(previousPosition)), ); }, ); flameTester.test( 'zooms when game is over', (game) async { final playing = const GameState.initial().copyWith( status: GameStatus.gameOver, ); final behavior = CameraFocusingBehavior(); await game.ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [behavior], ), ); behavior.onNewState(playing); final previousPosition = game.camera.position.clone(); await game.ready(); final zoom = behavior.children.whereType<CameraZoom>().single; game.update(zoom.controller.duration!); game.update(0); expect(zoom.controller.completed, isTrue); expect( game.camera.position, isNot(equals(previousPosition)), ); }, ); }); }, ); }
pinball/test/game/behaviors/camera_focusing_behavior_test.dart/0
{ "file_path": "pinball/test/game/behaviors/camera_focusing_behavior_test.dart", "repo_id": "pinball", "token_count": 2316 }
1,204
// ignore_for_file: cascade_invocations, prefer_const_constructors import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/components/backbox/bloc/backbox_bloc.dart'; import 'package:pinball/game/components/backbox/displays/displays.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' as theme; import 'package:pinball_ui/pinball_ui.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:share_repository/share_repository.dart'; class _TestGame extends Forge2DGame with HasKeyboardHandlerComponents, HasTappables { final character = theme.DashTheme(); @override Color backgroundColor() => Colors.transparent; @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ character.leaderboardIcon.keyName, Assets.images.backbox.marquee.keyName, Assets.images.backbox.displayDivider.keyName, Assets.images.backbox.button.facebook.keyName, Assets.images.backbox.button.twitter.keyName, Assets.images.backbox.displayTitleDecoration.keyName, Assets.images.displayArrows.arrowLeft.keyName, Assets.images.displayArrows.arrowRight.keyName, ]); } Future<void> pump( Backbox component, { PlatformHelper? platformHelper, }) async { // Not needed once https://github.com/flame-engine/flame/issues/1607 // is fixed await onLoad(); await ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: GameBloc(), children: [ MultiFlameProvider( providers: [ FlameProvider<AppLocalizations>.value( _MockAppLocalizations(), ), FlameProvider<PlatformHelper>.value( platformHelper ?? _MockPlatformHelper(), ), ], children: [component], ), ], ), ); } } class _MockRawKeyUpEvent extends Mock implements RawKeyUpEvent { @override String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return super.toString(); } } RawKeyUpEvent _mockKeyUp(LogicalKeyboardKey key) { final event = _MockRawKeyUpEvent(); when(() => event.logicalKey).thenReturn(key); return event; } class _MockPlatformHelper extends Mock implements PlatformHelper {} class _MockBackboxBloc extends Mock implements BackboxBloc {} class _MockLeaderboardRepository extends Mock implements LeaderboardRepository { } class _MockShareRepository extends Mock implements ShareRepository {} class _MockTapDownInfo extends Mock implements TapDownInfo {} class _MockTapUpInfo extends Mock implements TapUpInfo {} class _MockUrlLauncher extends Mock with MockPlatformInterfaceMixin implements UrlLauncherPlatform {} class _MockAppLocalizations extends Mock implements AppLocalizations { @override String get score => ''; @override String get name => ''; @override String get rank => ''; @override String get enterInitials => ''; @override String get arrows => ''; @override String get andPress => ''; @override String get enterReturn => ''; @override String get toSubmit => ''; @override String get loading => ''; @override String get letEveryone => ''; @override String get bySharingYourScore => ''; @override String get socialMediaAccount => ''; @override String get shareYourScore => ''; @override String get andChallengeYourFriends => ''; @override String get share => ''; @override String get gotoIO => ''; @override String get learnMore => ''; @override String get firebaseOr => ''; @override String get openSourceCode => ''; @override String get initialsErrorTitle => ''; @override String get initialsErrorMessage => ''; @override String get leaderboardErrorMessage => ''; @override String iGotScoreAtPinball(String _) => ''; } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); late BackboxBloc bloc; late PlatformHelper platformHelper; late UrlLauncherPlatform urlLauncher; setUp(() { bloc = _MockBackboxBloc(); platformHelper = _MockPlatformHelper(); whenListen( bloc, Stream<BackboxState>.empty(), initialState: LoadingState(), ); when(() => platformHelper.isMobile).thenReturn(false); }); group('Backbox', () { flameTester.test( 'loads correctly', (game) async { final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect(game.descendants(), contains(backbox)); }, ); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.onLoad(); game.camera ..followVector2(Vector2(0, -130)) ..zoom = 6; await game.pump( Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ), platformHelper: platformHelper, ); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<_TestGame>(), matchesGoldenFile('../golden/backbox.png'), ); }, ); flameTester.test( 'requestInitials adds InitialsInputDisplay', (game) async { final backbox = Backbox.test( bloc: BackboxBloc( leaderboardRepository: _MockLeaderboardRepository(), initialEntries: [LeaderboardEntryData.empty], ), shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); backbox.requestInitials( score: 0, character: game.character, ); await game.ready(); expect( backbox.descendants().whereType<InitialsInputDisplay>().length, equals(1), ); }, ); flameTester.test( 'adds PlayerInitialsSubmitted when initials are submitted', (game) async { final bloc = _MockBackboxBloc(); final state = InitialsFormState( score: 10, character: game.character, ); whenListen( bloc, Stream<BackboxState>.empty(), initialState: state, ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); game.onKeyEvent(_mockKeyUp(LogicalKeyboardKey.enter), {}); verify( () => bloc.add( PlayerInitialsSubmitted( score: 10, initials: 'AAA', character: game.character, ), ), ).called(1); }, ); flameTester.test( 'adds GameOverInfoDisplay when InitialsSuccessState', (game) async { final state = InitialsSuccessState(score: 100); whenListen( bloc, const Stream<InitialsSuccessState>.empty(), initialState: state, ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect( game.descendants().whereType<GameOverInfoDisplay>().length, equals(1), ); }, ); flameTester.test( 'adds the mobile controls overlay ' 'when platform is mobile at InitialsFormState', (game) async { final bloc = _MockBackboxBloc(); final platformHelper = _MockPlatformHelper(); final state = InitialsFormState( score: 10, character: game.character, ); whenListen( bloc, Stream<BackboxState>.empty(), initialState: state, ); when(() => platformHelper.isMobile).thenReturn(true); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect( game.overlays.value, contains(PinballGame.mobileControlsOverlay), ); }, ); flameTester.test( 'remove the mobile controls overlay ' 'when InitialsSuccessState', (game) async { final bloc = _MockBackboxBloc(); final platformHelper = _MockPlatformHelper(); final state = InitialsSuccessState(score: 10); whenListen( bloc, Stream<BackboxState>.empty(), initialState: state, ); when(() => platformHelper.isMobile).thenReturn(true); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect( game.overlays.value, isNot(contains(PinballGame.mobileControlsOverlay)), ); }, ); flameTester.test( 'adds InitialsSubmissionSuccessDisplay on InitialsSuccessState', (game) async { final state = InitialsSuccessState(score: 100); whenListen( bloc, const Stream<InitialsSuccessState>.empty(), initialState: state, ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect( game.descendants().whereType<GameOverInfoDisplay>().length, equals(1), ); }, ); flameTester.test( 'adds ShareScoreRequested event when sharing', (game) async { final state = InitialsSuccessState(score: 100); whenListen( bloc, Stream.value(state), initialState: state, ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); final shareLink = game.descendants().whereType<ShareLinkComponent>().first; shareLink.onTapDown(_MockTapDownInfo()); verify( () => bloc.add( ShareScoreRequested(score: state.score), ), ).called(1); }, ); flameTester.test( 'adds InitialsSubmissionFailureDisplay on InitialsFailureState', (game) async { whenListen( bloc, Stream<BackboxState>.empty(), initialState: InitialsFailureState( score: 0, character: theme.DashTheme(), ), ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect( game .descendants() .whereType<InitialsSubmissionFailureDisplay>() .length, equals(1), ); }, ); group('ShareDisplay', () { setUp(() async { urlLauncher = _MockUrlLauncher(); UrlLauncherPlatform.instance = urlLauncher; }); flameTester.test( 'adds ShareDisplay on ShareState', (game) async { final state = ShareState(score: 100); whenListen( bloc, const Stream<InitialsSuccessState>.empty(), initialState: state, ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect( game.descendants().whereType<ShareDisplay>().length, equals(1), ); }, ); flameTester.test( 'opens Facebook link when sharing with Facebook', (game) async { when(() => urlLauncher.canLaunch(any())) .thenAnswer((_) async => true); when( () => urlLauncher.launch( any(), useSafariVC: any(named: 'useSafariVC'), useWebView: any(named: 'useWebView'), enableJavaScript: any(named: 'enableJavaScript'), enableDomStorage: any(named: 'enableDomStorage'), universalLinksOnly: any(named: 'universalLinksOnly'), headers: any(named: 'headers'), ), ).thenAnswer((_) async => true); final state = ShareState(score: 100); whenListen( bloc, const Stream<ShareState>.empty(), initialState: state, ); final shareRepository = _MockShareRepository(); const fakeUrl = 'http://fakeUrl'; when( () => shareRepository.shareText( value: any(named: 'value'), platform: SharePlatform.facebook, ), ).thenReturn(fakeUrl); final backbox = Backbox.test( bloc: bloc, shareRepository: shareRepository, ); await game.pump( backbox, platformHelper: platformHelper, ); final facebookButton = game.descendants().whereType<FacebookButtonComponent>().first; facebookButton.onTapUp(_MockTapUpInfo()); await game.ready(); verify( () => shareRepository.shareText( value: any(named: 'value'), platform: SharePlatform.facebook, ), ).called(1); }, ); flameTester.test( 'opens Twitter link when sharing with Twitter', (game) async { final state = ShareState(score: 100); whenListen( bloc, Stream.value(state), initialState: state, ); final shareRepository = _MockShareRepository(); const fakeUrl = 'http://fakeUrl'; when( () => shareRepository.shareText( value: any(named: 'value'), platform: SharePlatform.twitter, ), ).thenReturn(fakeUrl); when(() => urlLauncher.canLaunch(any())) .thenAnswer((_) async => true); when( () => urlLauncher.launch( any(), useSafariVC: any(named: 'useSafariVC'), useWebView: any(named: 'useWebView'), enableJavaScript: any(named: 'enableJavaScript'), enableDomStorage: any(named: 'enableDomStorage'), universalLinksOnly: any(named: 'universalLinksOnly'), headers: any(named: 'headers'), ), ).thenAnswer((_) async => true); final backbox = Backbox.test( bloc: bloc, shareRepository: shareRepository, ); await game.pump( backbox, platformHelper: platformHelper, ); final facebookButton = game.descendants().whereType<TwitterButtonComponent>().first; facebookButton.onTapUp(_MockTapUpInfo()); await game.ready(); verify( () => shareRepository.shareText( value: any(named: 'value'), platform: SharePlatform.twitter, ), ).called(1); }, ); }); flameTester.test( 'adds LeaderboardDisplay on LeaderboardSuccessState', (game) async { whenListen( bloc, Stream<BackboxState>.empty(), initialState: LeaderboardSuccessState(entries: const []), ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect( game.descendants().whereType<LeaderboardDisplay>().length, equals(1), ); }, ); flameTester.test( 'adds LeaderboardFailureDisplay on LeaderboardFailureState', (game) async { whenListen( bloc, Stream<BackboxState>.empty(), initialState: LeaderboardFailureState(), ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); expect( game.descendants().whereType<LeaderboardFailureDisplay>().length, equals(1), ); }, ); flameTester.test( 'closes the subscription when it is removed', (game) async { final streamController = StreamController<BackboxState>(); whenListen( bloc, streamController.stream, initialState: LoadingState(), ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); backbox.removeFromParent(); await game.ready(); streamController.add( InitialsFailureState( score: 10, character: theme.DashTheme(), ), ); await game.ready(); expect( backbox .descendants() .whereType<InitialsSubmissionFailureDisplay>() .isEmpty, isTrue, ); }, ); flameTester.test( 'adds PlayerInitialsSubmitted when the timer is finished', (game) async { final initialState = InitialsFailureState( score: 10, character: theme.DashTheme(), ); whenListen( bloc, Stream<BackboxState>.fromIterable([]), initialState: initialState, ); final backbox = Backbox.test( bloc: bloc, shareRepository: _MockShareRepository(), ); await game.pump( backbox, platformHelper: platformHelper, ); game.update(4); verify( () => bloc.add( PlayerInitialsRequested( score: 10, character: theme.DashTheme(), ), ), ).called(1); }, ); }); }
pinball/test/game/components/backbox/backbox_test.dart/0
{ "file_path": "pinball/test/game/components/backbox/backbox_test.dart", "repo_id": "pinball", "token_count": 9042 }
1,205
// ignore_for_file: cascade_invocations import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball/game/game.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(Forge2DGame.new); group('Drain', () { flameTester.test( 'loads correctly', (game) async { final drain = Drain(); await game.ensureAdd(drain); expect(game.contains(drain), isTrue); }, ); flameTester.test( 'body is static', (game) async { final drain = Drain(); await game.ensureAdd(drain); expect(drain.body.bodyType, equals(BodyType.static)); }, ); flameTester.test( 'is sensor', (game) async { final drain = Drain(); await game.ensureAdd(drain); expect(drain.body.fixtures.first.isSensor, isTrue); }, ); }); }
pinball/test/game/components/drain/drain_test.dart/0
{ "file_path": "pinball/test/game/components/drain/drain_test.dart", "repo_id": "pinball", "token_count": 431 }
1,206
// ignore_for_file: invalid_use_of_protected_member 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/game/view/widgets/bonus_animation.dart'; import 'package:pinball_flame/pinball_flame.dart'; import '../../../helpers/helpers.dart'; class _MockCallback extends Mock { void call(); } void main() { TestWidgetsFlutterBinding.ensureInitialized(); const animationDuration = 6; setUp(() async { await mockFlameImages(); }); group('loads SpriteAnimationWidget correctly for', () { testWidgets('dashNest', (tester) async { await tester.pumpApp( BonusAnimation.dashNest(), ); await tester.pump(); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }); testWidgets('dinoChomp', (tester) async { await tester.pumpApp( BonusAnimation.dinoChomp(), ); await tester.pump(); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }); testWidgets('sparkyTurboCharge', (tester) async { await tester.pumpApp( BonusAnimation.sparkyTurboCharge(), ); await tester.pump(); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }); testWidgets('googleWord', (tester) async { await tester.pumpApp( BonusAnimation.googleWord(), ); await tester.pump(); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }); testWidgets('androidSpaceship', (tester) async { await tester.pumpApp( BonusAnimation.androidSpaceship(), ); await tester.pump(); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }); }); testWidgets('called onCompleted callback at the end of animation ', (tester) async { final callback = _MockCallback(); await tester.runAsync(() async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: BonusAnimation.dashNest( onCompleted: callback.call, ), ), ), ); await tester.pump(); await Future<void>.delayed(const Duration(seconds: animationDuration)); await tester.pump(); verify(callback.call).called(1); }); }); testWidgets('called onCompleted once when animation changed', (tester) async { final callback = _MockCallback(); final secondAnimation = BonusAnimation.sparkyTurboCharge( onCompleted: callback.call, ); await tester.runAsync(() async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: BonusAnimation.dashNest( onCompleted: callback.call, ), ), ), ); await tester.pump(); tester .state(find.byType(BonusAnimation)) .didUpdateWidget(secondAnimation); await Future<void>.delayed(const Duration(seconds: animationDuration)); await tester.pump(); verify(callback.call).called(1); }); }); }
pinball/test/game/view/widgets/bonus_animation_test.dart/0
{ "file_path": "pinball/test/game/view/widgets/bonus_animation_test.dart", "repo_id": "pinball", "token_count": 1281 }
1,207
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/select_character/select_character.dart'; import 'package:pinball/start_game/start_game.dart'; import 'package:pinball_theme/pinball_theme.dart'; import 'package:pinball_ui/pinball_ui.dart'; import '../../helpers/helpers.dart'; class _MockCharacterThemeCubit extends Mock implements CharacterThemeCubit {} class _MockStartGameBloc extends Mock implements StartGameBloc {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); late CharacterThemeCubit characterThemeCubit; late StartGameBloc startGameBloc; setUp(() async { await mockFlameImages(); characterThemeCubit = _MockCharacterThemeCubit(); startGameBloc = _MockStartGameBloc(); whenListen( characterThemeCubit, const Stream<CharacterThemeState>.empty(), initialState: const CharacterThemeState.initial(), ); when(() => characterThemeCubit.state) .thenReturn(const CharacterThemeState.initial()); }); group('CharacterSelectionDialog', () { testWidgets('selecting a new character calls characterSelected on cubit', (tester) async { await tester.pumpApp( const CharacterSelectionDialog(), characterThemeCubit: characterThemeCubit, ); await tester.tap(find.byKey(const Key('sparky_character_selection'))); await tester.pump(); verify( () => characterThemeCubit.characterSelected(const SparkyTheme()), ).called(1); }); testWidgets( 'tapping the select button dismisses the character ' 'dialog and calls CharacterSelected event to the bloc', (tester) async { whenListen( startGameBloc, const Stream<StartGameState>.empty(), initialState: const StartGameState.initial(), ); await tester.pumpApp( const CharacterSelectionDialog(), characterThemeCubit: characterThemeCubit, startGameBloc: startGameBloc, ); await tester.tap(find.byType(PinballButton)); await tester.pumpAndSettle(); expect(find.byType(CharacterSelectionDialog), findsNothing); verify(() => startGameBloc.add(const CharacterSelected())).called(1); }); testWidgets('updating the selected character updates the preview', (tester) async { await tester.pumpApp(_TestCharacterPreview()); expect(find.text('Dash'), findsOneWidget); await tester.tap(find.text('test')); await tester.pump(); expect(find.text('Android'), findsOneWidget); }); }); } class _TestCharacterPreview extends StatefulWidget { @override State<StatefulWidget> createState() => _TestCharacterPreviewState(); } class _TestCharacterPreviewState extends State<_TestCharacterPreview> { late CharacterTheme currentCharacter; @override void initState() { super.initState(); currentCharacter = const DashTheme(); } @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ Expanded(child: SelectedCharacter(currentCharacter: currentCharacter)), TextButton( onPressed: () { setState(() { currentCharacter = const AndroidTheme(); }); }, child: const Text('test'), ) ], ); } }
pinball/test/select_character/view/character_selection_page_test.dart/0
{ "file_path": "pinball/test/select_character/view/character_selection_page_test.dart", "repo_id": "pinball", "token_count": 1279 }
1,208
# The Flutter version is not important here, since the CI scripts update Flutter # before running. What matters is that the base image is pinned to minimize # unintended changes when modifying this file. # This is the hash for the 3.0.0 image. FROM cirrusci/flutter@sha256:0224587bba33241cf908184283ec2b544f1b672d87043ead1c00521c368cf844 RUN apt-get update -y # Set up Firebase Test Lab requirements. RUN apt-get install -y --no-install-recommends gnupg RUN echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | \ sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list RUN curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | \ sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - RUN apt-get update && apt-get install -y google-cloud-sdk && \ gcloud config set core/disable_usage_reporting true && \ gcloud config set component_manager/disable_update_check true # Install formatter for C-based languages. RUN apt-get install -y clang-format # Install Linux desktop requirements: # - build tools. RUN apt-get install -y clang cmake ninja-build file pkg-config # - libraries. RUN apt-get install -y libgtk-3-dev libblkid-dev liblzma-dev libgcrypt20-dev # - xvfb to allow running headless. RUN apt-get install -y xvfb libegl1-mesa # Install Chrome and make it the default browser, for url_launcher tests. # IMPORTANT: Web tests should use a pinned version of Chromium, not this, since # this isn't pinned, so any time the docker image is re-created the version of # Chrome may change. RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - RUN echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list RUN apt-get update && apt-get install -y --no-install-recommends google-chrome-stable # Make Chrome the default for http:, https: and file:. RUN apt-get install -y xdg-utils RUN xdg-settings set default-web-browser google-chrome.desktop RUN xdg-mime default google-chrome.desktop inode/directory
plugins/.ci/Dockerfile/0
{ "file_path": "plugins/.ci/Dockerfile", "repo_id": "plugins", "token_count": 703 }
1,209
tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh - name: build examples (Win32) script: .ci/scripts/build_examples_win32.sh - name: native unit tests (Win32) script: .ci/scripts/native_test_win32.sh - name: drive examples (Win32) script: .ci/scripts/drive_examples_win32.sh
plugins/.ci/targets/windows_build_and_platform_tests.yaml/0
{ "file_path": "plugins/.ci/targets/windows_build_and_platform_tests.yaml", "repo_id": "plugins", "token_count": 121 }
1,210
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=false android.enableR8=true
plugins/packages/camera/camera/example/android/gradle.properties/0
{ "file_path": "plugins/packages/camera/camera/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,211
group 'io.flutter.plugins.camera' version '1.0-SNAPSHOT' def args = ["-Xlint:deprecation","-Xlint:unchecked"] buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.0.2' } } rootProject.allprojects { repositories { google() mavenCentral() } } project.getTasks().withType(JavaCompile){ options.compilerArgs.addAll(args) } apply plugin: 'com.android.library' android { compileSdkVersion 31 defaultConfig { targetSdkVersion 31 minSdkVersion 21 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } lintOptions { disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' baseline file("lint-baseline.xml") } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { implementation 'androidx.annotation:annotation:1.5.0' testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-inline:5.0.0' testImplementation 'androidx.test:core:1.4.0' testImplementation 'org.robolectric:robolectric:4.5' }
plugins/packages/camera/camera_android/android/build.gradle/0
{ "file_path": "plugins/packages/camera/camera_android/android/build.gradle", "repo_id": "plugins", "token_count": 698 }
1,212
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camera.features; import android.app.Activity; import androidx.annotation.NonNull; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.DartMessenger; import io.flutter.plugins.camera.features.autofocus.AutoFocusFeature; import io.flutter.plugins.camera.features.exposurelock.ExposureLockFeature; import io.flutter.plugins.camera.features.exposureoffset.ExposureOffsetFeature; import io.flutter.plugins.camera.features.exposurepoint.ExposurePointFeature; import io.flutter.plugins.camera.features.flash.FlashFeature; import io.flutter.plugins.camera.features.focuspoint.FocusPointFeature; import io.flutter.plugins.camera.features.fpsrange.FpsRangeFeature; import io.flutter.plugins.camera.features.noisereduction.NoiseReductionFeature; import io.flutter.plugins.camera.features.resolution.ResolutionFeature; import io.flutter.plugins.camera.features.resolution.ResolutionPreset; import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature; import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature; /** * Factory for creating the supported feature implementation controlling different aspects of the * {@link android.hardware.camera2.CaptureRequest}. */ public interface CameraFeatureFactory { /** * Creates a new instance of the auto focus feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @param recordingVideo indicates if the camera is currently recording. * @return newly created instance of the AutoFocusFeature class. */ AutoFocusFeature createAutoFocusFeature( @NonNull CameraProperties cameraProperties, boolean recordingVideo); /** * Creates a new instance of the exposure lock feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @return newly created instance of the ExposureLockFeature class. */ ExposureLockFeature createExposureLockFeature(@NonNull CameraProperties cameraProperties); /** * Creates a new instance of the exposure offset feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @return newly created instance of the ExposureOffsetFeature class. */ ExposureOffsetFeature createExposureOffsetFeature(@NonNull CameraProperties cameraProperties); /** * Creates a new instance of the flash feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @return newly created instance of the FlashFeature class. */ FlashFeature createFlashFeature(@NonNull CameraProperties cameraProperties); /** * Creates a new instance of the resolution feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @param initialSetting initial resolution preset. * @param cameraName the name of the camera which can be used to identify the camera device. * @return newly created instance of the ResolutionFeature class. */ ResolutionFeature createResolutionFeature( @NonNull CameraProperties cameraProperties, ResolutionPreset initialSetting, String cameraName); /** * Creates a new instance of the focus point feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @param sensorOrientationFeature instance of the SensorOrientationFeature class containing * information about the sensor and device orientation. * @return newly created instance of the FocusPointFeature class. */ FocusPointFeature createFocusPointFeature( @NonNull CameraProperties cameraProperties, @NonNull SensorOrientationFeature sensorOrientationFeature); /** * Creates a new instance of the FPS range feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @return newly created instance of the FpsRangeFeature class. */ FpsRangeFeature createFpsRangeFeature(@NonNull CameraProperties cameraProperties); /** * Creates a new instance of the sensor orientation feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @param activity current activity associated with the camera plugin. * @param dartMessenger instance of the DartMessenger class, used to send state updates back to * Dart. * @return newly created instance of the SensorOrientationFeature class. */ SensorOrientationFeature createSensorOrientationFeature( @NonNull CameraProperties cameraProperties, @NonNull Activity activity, @NonNull DartMessenger dartMessenger); /** * Creates a new instance of the zoom level feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @return newly created instance of the ZoomLevelFeature class. */ ZoomLevelFeature createZoomLevelFeature(@NonNull CameraProperties cameraProperties); /** * Creates a new instance of the exposure point feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @param sensorOrientationFeature instance of the SensorOrientationFeature class containing * information about the sensor and device orientation. * @return newly created instance of the ExposurePointFeature class. */ ExposurePointFeature createExposurePointFeature( @NonNull CameraProperties cameraProperties, @NonNull SensorOrientationFeature sensorOrientationFeature); /** * Creates a new instance of the noise reduction feature. * * @param cameraProperties instance of the CameraProperties class containing information about the * cameras features. * @return newly created instance of the NoiseReductionFeature class. */ NoiseReductionFeature createNoiseReductionFeature(@NonNull CameraProperties cameraProperties); }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeatureFactory.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/CameraFeatureFactory.java", "repo_id": "plugins", "token_count": 1736 }
1,213
// 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.resolution; import android.annotation.TargetApi; import android.hardware.camera2.CaptureRequest; import android.media.CamcorderProfile; import android.media.EncoderProfiles; import android.os.Build; import android.util.Size; import androidx.annotation.VisibleForTesting; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.features.CameraFeature; import java.util.List; /** * Controls the resolutions configuration on the {@link android.hardware.camera2} API. * * <p>The {@link ResolutionFeature} is responsible for converting the platform independent {@link * ResolutionPreset} into a {@link android.media.CamcorderProfile} which contains all the properties * required to configure the resolution using the {@link android.hardware.camera2} API. */ public class ResolutionFeature extends CameraFeature<ResolutionPreset> { private Size captureSize; private Size previewSize; private CamcorderProfile recordingProfileLegacy; private EncoderProfiles recordingProfile; private ResolutionPreset currentSetting; private int cameraId; /** * Creates a new instance of the {@link ResolutionFeature}. * * @param cameraProperties Collection of characteristics for the current camera device. * @param resolutionPreset Platform agnostic enum containing resolution information. * @param cameraName Camera identifier of the camera for which to configure the resolution. */ public ResolutionFeature( CameraProperties cameraProperties, ResolutionPreset resolutionPreset, String cameraName) { super(cameraProperties); this.currentSetting = resolutionPreset; try { this.cameraId = Integer.parseInt(cameraName, 10); } catch (NumberFormatException e) { this.cameraId = -1; return; } configureResolution(resolutionPreset, cameraId); } /** * Gets the {@link android.media.CamcorderProfile} containing the information to configure the * resolution using the {@link android.hardware.camera2} API. * * @return Resolution information to configure the {@link android.hardware.camera2} API. */ public CamcorderProfile getRecordingProfileLegacy() { return this.recordingProfileLegacy; } public EncoderProfiles getRecordingProfile() { return this.recordingProfile; } /** * Gets the optimal preview size based on the configured resolution. * * @return The optimal preview size. */ public Size getPreviewSize() { return this.previewSize; } /** * Gets the optimal capture size based on the configured resolution. * * @return The optimal capture size. */ public Size getCaptureSize() { return this.captureSize; } @Override public String getDebugName() { return "ResolutionFeature"; } @Override public ResolutionPreset getValue() { return currentSetting; } @Override public void setValue(ResolutionPreset value) { this.currentSetting = value; configureResolution(currentSetting, cameraId); } @Override public boolean checkIsSupported() { return cameraId >= 0; } @Override public void updateBuilder(CaptureRequest.Builder requestBuilder) { // No-op: when setting a resolution there is no need to update the request builder. } @VisibleForTesting static Size computeBestPreviewSize(int cameraId, ResolutionPreset preset) throws IndexOutOfBoundsException { if (preset.ordinal() > ResolutionPreset.high.ordinal()) { preset = ResolutionPreset.high; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { EncoderProfiles profile = getBestAvailableCamcorderProfileForResolutionPreset(cameraId, preset); List<EncoderProfiles.VideoProfile> videoProfiles = profile.getVideoProfiles(); EncoderProfiles.VideoProfile defaultVideoProfile = videoProfiles.get(0); if (defaultVideoProfile != null) { return new Size(defaultVideoProfile.getWidth(), defaultVideoProfile.getHeight()); } } @SuppressWarnings("deprecation") // TODO(camsim99): Suppression is currently safe because legacy code is used as a fallback for SDK >= S. // This should be removed when reverting that fallback behavior: https://github.com/flutter/flutter/issues/119668. CamcorderProfile profile = getBestAvailableCamcorderProfileForResolutionPresetLegacy(cameraId, preset); return new Size(profile.videoFrameWidth, profile.videoFrameHeight); } /** * Gets the best possible {@link android.media.CamcorderProfile} for the supplied {@link * ResolutionPreset}. Supports SDK < 31. * * @param cameraId Camera identifier which indicates the device's camera for which to select a * {@link android.media.CamcorderProfile}. * @param preset The {@link ResolutionPreset} for which is to be translated to a {@link * android.media.CamcorderProfile}. * @return The best possible {@link android.media.CamcorderProfile} that matches the supplied * {@link ResolutionPreset}. */ public static CamcorderProfile getBestAvailableCamcorderProfileForResolutionPresetLegacy( int cameraId, ResolutionPreset preset) { if (cameraId < 0) { throw new AssertionError( "getBestAvailableCamcorderProfileForResolutionPreset can only be used with valid (>=0) camera identifiers."); } switch (preset) { // All of these cases deliberately fall through to get the best available profile. case max: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_HIGH)) { return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH); } case ultraHigh: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_2160P)) { return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_2160P); } case veryHigh: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_1080P)) { return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_1080P); } case high: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_720P)) { return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_720P); } case medium: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_480P)) { return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_480P); } case low: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_QVGA)) { return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_QVGA); } default: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_LOW)) { return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_LOW); } else { throw new IllegalArgumentException( "No capture session available for current capture session."); } } } @TargetApi(Build.VERSION_CODES.S) public static EncoderProfiles getBestAvailableCamcorderProfileForResolutionPreset( int cameraId, ResolutionPreset preset) { if (cameraId < 0) { throw new AssertionError( "getBestAvailableCamcorderProfileForResolutionPreset can only be used with valid (>=0) camera identifiers."); } String cameraIdString = Integer.toString(cameraId); switch (preset) { // All of these cases deliberately fall through to get the best available profile. case max: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_HIGH)) { return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_HIGH); } case ultraHigh: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_2160P)) { return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_2160P); } case veryHigh: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_1080P)) { return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_1080P); } case high: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_720P)) { return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_720P); } case medium: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_480P)) { return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_480P); } case low: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_QVGA)) { return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_QVGA); } default: if (CamcorderProfile.hasProfile(cameraId, CamcorderProfile.QUALITY_LOW)) { return CamcorderProfile.getAll(cameraIdString, CamcorderProfile.QUALITY_LOW); } throw new IllegalArgumentException( "No capture session available for current capture session."); } } private void configureResolution(ResolutionPreset resolutionPreset, int cameraId) throws IndexOutOfBoundsException { if (!checkIsSupported()) { return; } boolean captureSizeCalculated = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { recordingProfileLegacy = null; recordingProfile = getBestAvailableCamcorderProfileForResolutionPreset(cameraId, resolutionPreset); List<EncoderProfiles.VideoProfile> videoProfiles = recordingProfile.getVideoProfiles(); EncoderProfiles.VideoProfile defaultVideoProfile = videoProfiles.get(0); if (defaultVideoProfile != null) { captureSizeCalculated = true; captureSize = new Size(defaultVideoProfile.getWidth(), defaultVideoProfile.getHeight()); } } if (!captureSizeCalculated) { recordingProfile = null; @SuppressWarnings("deprecation") CamcorderProfile camcorderProfile = getBestAvailableCamcorderProfileForResolutionPresetLegacy(cameraId, resolutionPreset); recordingProfileLegacy = camcorderProfile; captureSize = new Size(recordingProfileLegacy.videoFrameWidth, recordingProfileLegacy.videoFrameHeight); } previewSize = computeBestPreviewSize(cameraId, resolutionPreset); } }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionFeature.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/resolution/ResolutionFeature.java", "repo_id": "plugins", "token_count": 3627 }
1,214
// 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.flash; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.hardware.camera2.CaptureRequest; import io.flutter.plugins.camera.CameraProperties; import org.junit.Test; public class FlashFeatureTest { @Test public void getDebugName_shouldReturnTheNameOfTheFeature() { CameraProperties mockCameraProperties = mock(CameraProperties.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); assertEquals("FlashFeature", flashFeature.getDebugName()); } @Test public void getValue_shouldReturnAutoIfNotSet() { CameraProperties mockCameraProperties = mock(CameraProperties.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); assertEquals(FlashMode.auto, flashFeature.getValue()); } @Test public void getValue_shouldEchoTheSetValue() { CameraProperties mockCameraProperties = mock(CameraProperties.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); FlashMode expectedValue = FlashMode.torch; flashFeature.setValue(expectedValue); FlashMode actualValue = flashFeature.getValue(); assertEquals(expectedValue, actualValue); } @Test public void checkIsSupported_shouldReturnFalseWhenFlashInfoAvailableIsNull() { CameraProperties mockCameraProperties = mock(CameraProperties.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); when(mockCameraProperties.getFlashInfoAvailable()).thenReturn(null); assertFalse(flashFeature.checkIsSupported()); } @Test public void checkIsSupported_shouldReturnFalseWhenFlashInfoAvailableIsFalse() { CameraProperties mockCameraProperties = mock(CameraProperties.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); when(mockCameraProperties.getFlashInfoAvailable()).thenReturn(false); assertFalse(flashFeature.checkIsSupported()); } @Test public void checkIsSupported_shouldReturnTrueWhenFlashInfoAvailableIsTrue() { CameraProperties mockCameraProperties = mock(CameraProperties.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); when(mockCameraProperties.getFlashInfoAvailable()).thenReturn(true); assertTrue(flashFeature.checkIsSupported()); } @Test public void updateBuilder_shouldReturnWhenCheckIsSupportedIsFalse() { CameraProperties mockCameraProperties = mock(CameraProperties.class); CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); when(mockCameraProperties.getFlashInfoAvailable()).thenReturn(false); flashFeature.updateBuilder(mockBuilder); verify(mockBuilder, never()).set(any(), any()); } @Test public void updateBuilder_shouldSetAeModeAndFlashModeWhenFlashModeIsOff() { CameraProperties mockCameraProperties = mock(CameraProperties.class); CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); when(mockCameraProperties.getFlashInfoAvailable()).thenReturn(true); flashFeature.setValue(FlashMode.off); flashFeature.updateBuilder(mockBuilder); verify(mockBuilder, times(1)) .set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); verify(mockBuilder, times(1)).set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); } @Test public void updateBuilder_shouldSetAeModeAndFlashModeWhenFlashModeIsAlways() { CameraProperties mockCameraProperties = mock(CameraProperties.class); CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); when(mockCameraProperties.getFlashInfoAvailable()).thenReturn(true); flashFeature.setValue(FlashMode.always); flashFeature.updateBuilder(mockBuilder); verify(mockBuilder, times(1)) .set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH); verify(mockBuilder, times(1)).set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); } @Test public void updateBuilder_shouldSetAeModeAndFlashModeWhenFlashModeIsTorch() { CameraProperties mockCameraProperties = mock(CameraProperties.class); CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); when(mockCameraProperties.getFlashInfoAvailable()).thenReturn(true); flashFeature.setValue(FlashMode.torch); flashFeature.updateBuilder(mockBuilder); verify(mockBuilder, times(1)) .set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); verify(mockBuilder, times(1)).set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH); } @Test public void updateBuilder_shouldSetAeModeAndFlashModeWhenFlashModeIsAuto() { CameraProperties mockCameraProperties = mock(CameraProperties.class); CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class); FlashFeature flashFeature = new FlashFeature(mockCameraProperties); when(mockCameraProperties.getFlashInfoAvailable()).thenReturn(true); flashFeature.setValue(FlashMode.auto); flashFeature.updateBuilder(mockBuilder); verify(mockBuilder, times(1)) .set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); verify(mockBuilder, times(1)).set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); } }
plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/flash/FlashFeatureTest.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/flash/FlashFeatureTest.java", "repo_id": "plugins", "token_count": 1873 }
1,215
// 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 'dart:ui'; import 'package:camera_android/camera_android.dart'; import 'package:camera_example/camera_controller.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path_provider/path_provider.dart'; import 'package:video_player/video_player.dart'; void main() { late Directory testDir; IntegrationTestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() async { CameraPlatform.instance = AndroidCamera(); final Directory extDir = await getTemporaryDirectory(); testDir = await Directory('${extDir.path}/test').create(recursive: true); }); tearDownAll(() async { await testDir.delete(recursive: true); }); final Map<ResolutionPreset, Size> presetExpectedSizes = <ResolutionPreset, Size>{ ResolutionPreset.low: const Size(240, 320), ResolutionPreset.medium: const Size(480, 720), ResolutionPreset.high: const Size(720, 1280), ResolutionPreset.veryHigh: const Size(1080, 1920), ResolutionPreset.ultraHigh: const Size(2160, 3840), // Don't bother checking for max here since it could be anything. }; /// Verify that [actual] has dimensions that are at least as large as /// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns /// whether the dimensions exactly match. bool assertExpectedDimensions(Size expectedSize, Size actual) { expect(actual.shortestSide, lessThanOrEqualTo(expectedSize.shortestSide)); expect(actual.longestSide, lessThanOrEqualTo(expectedSize.longestSide)); return actual.shortestSide == expectedSize.shortestSide && actual.longestSide == expectedSize.longestSide; } // This tests that the capture is no bigger than the preset, since we have // automatic code to fall back to smaller sizes when we need to. Returns // whether the image is exactly the desired resolution. Future<bool> testCaptureImageResolution( CameraController controller, ResolutionPreset preset) async { final Size expectedSize = presetExpectedSizes[preset]!; // Take Picture final XFile file = await controller.takePicture(); // Load picture final File fileImage = File(file.path); final Image image = await decodeImageFromList(fileImage.readAsBytesSync()); // Verify image dimensions are as expected expect(image, isNotNull); return assertExpectedDimensions( expectedSize, Size(image.height.toDouble(), image.width.toDouble())); } testWidgets( 'Capture specific image resolutions', (WidgetTester tester) async { final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } for (final CameraDescription cameraDescription in cameras) { bool previousPresetExactlySupported = true; for (final MapEntry<ResolutionPreset, Size> preset in presetExpectedSizes.entries) { final CameraController controller = CameraController(cameraDescription, preset.key); await controller.initialize(); final bool presetExactlySupported = await testCaptureImageResolution(controller, preset.key); assert(!(!previousPresetExactlySupported && presetExactlySupported), 'The camera took higher resolution pictures at a lower resolution.'); previousPresetExactlySupported = presetExactlySupported; await controller.dispose(); } } }, // TODO(egarciad): Fix https://github.com/flutter/flutter/issues/93686. skip: true, ); // This tests that the capture is no bigger than the preset, since we have // automatic code to fall back to smaller sizes when we need to. Returns // whether the image is exactly the desired resolution. Future<bool> testCaptureVideoResolution( CameraController controller, ResolutionPreset preset) async { final Size expectedSize = presetExpectedSizes[preset]!; // Take Video await controller.startVideoRecording(); sleep(const Duration(milliseconds: 300)); final XFile file = await controller.stopVideoRecording(); // Load video metadata final File videoFile = File(file.path); final VideoPlayerController videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final Size video = videoController.value.size; // Verify image dimensions are as expected expect(video, isNotNull); return assertExpectedDimensions( expectedSize, Size(video.height, video.width)); } testWidgets( 'Capture specific video resolutions', (WidgetTester tester) async { final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } for (final CameraDescription cameraDescription in cameras) { bool previousPresetExactlySupported = true; for (final MapEntry<ResolutionPreset, Size> preset in presetExpectedSizes.entries) { final CameraController controller = CameraController(cameraDescription, preset.key); await controller.initialize(); await controller.prepareForVideoRecording(); final bool presetExactlySupported = await testCaptureVideoResolution(controller, preset.key); assert(!(!previousPresetExactlySupported && presetExactlySupported), 'The camera took higher resolution pictures at a lower resolution.'); previousPresetExactlySupported = presetExactlySupported; await controller.dispose(); } } }, // TODO(egarciad): Fix https://github.com/flutter/flutter/issues/93686. skip: true, ); testWidgets('Pause and resume video recording', (WidgetTester tester) async { final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } final CameraController controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, ); await controller.initialize(); await controller.prepareForVideoRecording(); int startPause; int timePaused = 0; await controller.startVideoRecording(); final int recordingStart = DateTime.now().millisecondsSinceEpoch; sleep(const Duration(milliseconds: 500)); await controller.pauseVideoRecording(); startPause = DateTime.now().millisecondsSinceEpoch; sleep(const Duration(milliseconds: 500)); await controller.resumeVideoRecording(); timePaused += DateTime.now().millisecondsSinceEpoch - startPause; sleep(const Duration(milliseconds: 500)); await controller.pauseVideoRecording(); startPause = DateTime.now().millisecondsSinceEpoch; sleep(const Duration(milliseconds: 500)); await controller.resumeVideoRecording(); timePaused += DateTime.now().millisecondsSinceEpoch - startPause; sleep(const Duration(milliseconds: 500)); final XFile file = await controller.stopVideoRecording(); final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; final File videoFile = File(file.path); final VideoPlayerController videoController = VideoPlayerController.file( videoFile, ); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); expect(duration, lessThan(recordingTime - timePaused)); }); testWidgets( 'image streaming', (WidgetTester tester) async { final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } final CameraController controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, ); await controller.initialize(); bool isDetecting = false; await controller.startImageStream((CameraImageData image) { if (isDetecting) { return; } isDetecting = true; expectLater(image, isNotNull).whenComplete(() => isDetecting = false); }); expect(controller.value.isStreamingImages, true); sleep(const Duration(milliseconds: 500)); await controller.stopImageStream(); await controller.dispose(); }, ); testWidgets( 'recording with image stream', (WidgetTester tester) async { final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } final CameraController controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, ); await controller.initialize(); bool isDetecting = false; await controller.startVideoRecording( streamCallback: (CameraImageData image) { if (isDetecting) { return; } isDetecting = true; expectLater(image, isNotNull); }); expect(controller.value.isStreamingImages, true); // Stopping recording before anything is recorded will throw, per // https://developer.android.com/reference/android/media/MediaRecorder.html#stop() // so delay long enough to ensure that some data is recorded. await Future<void>.delayed(const Duration(seconds: 2)); await controller.stopVideoRecording(); await controller.dispose(); expect(controller.value.isStreamingImages, false); }, ); }
plugins/packages/camera/camera_android/example/integration_test/camera_test.dart/0
{ "file_path": "plugins/packages/camera/camera_android/example/integration_test/camera_test.dart", "repo_id": "plugins", "token_count": 3384 }
1,216
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v3.2.9), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.camerax; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"}) public class GeneratedCameraXLibrary { /** Generated class from Pigeon that represents data sent in messages. */ public static class ResolutionInfo { private @NonNull Long width; public @NonNull Long getWidth() { return width; } public void setWidth(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"width\" is null."); } this.width = setterArg; } private @NonNull Long height; public @NonNull Long getHeight() { return height; } public void setHeight(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"height\" is null."); } this.height = setterArg; } /** Constructor is private to enforce null safety; use Builder. */ private ResolutionInfo() {} public static final class Builder { private @Nullable Long width; public @NonNull Builder setWidth(@NonNull Long setterArg) { this.width = setterArg; return this; } private @Nullable Long height; public @NonNull Builder setHeight(@NonNull Long setterArg) { this.height = setterArg; return this; } public @NonNull ResolutionInfo build() { ResolutionInfo pigeonReturn = new ResolutionInfo(); pigeonReturn.setWidth(width); pigeonReturn.setHeight(height); return pigeonReturn; } } @NonNull Map<String, Object> toMap() { Map<String, Object> toMapResult = new HashMap<>(); toMapResult.put("width", width); toMapResult.put("height", height); return toMapResult; } static @NonNull ResolutionInfo fromMap(@NonNull Map<String, Object> map) { ResolutionInfo pigeonResult = new ResolutionInfo(); Object width = map.get("width"); pigeonResult.setWidth( (width == null) ? null : ((width instanceof Integer) ? (Integer) width : (Long) width)); Object height = map.get("height"); pigeonResult.setHeight( (height == null) ? null : ((height instanceof Integer) ? (Integer) height : (Long) height)); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static class CameraPermissionsErrorData { private @NonNull String errorCode; public @NonNull String getErrorCode() { return errorCode; } public void setErrorCode(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"errorCode\" is null."); } this.errorCode = setterArg; } private @NonNull String description; public @NonNull String getDescription() { return description; } public void setDescription(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"description\" is null."); } this.description = setterArg; } /** Constructor is private to enforce null safety; use Builder. */ private CameraPermissionsErrorData() {} public static final class Builder { private @Nullable String errorCode; public @NonNull Builder setErrorCode(@NonNull String setterArg) { this.errorCode = setterArg; return this; } private @Nullable String description; public @NonNull Builder setDescription(@NonNull String setterArg) { this.description = setterArg; return this; } public @NonNull CameraPermissionsErrorData build() { CameraPermissionsErrorData pigeonReturn = new CameraPermissionsErrorData(); pigeonReturn.setErrorCode(errorCode); pigeonReturn.setDescription(description); return pigeonReturn; } } @NonNull Map<String, Object> toMap() { Map<String, Object> toMapResult = new HashMap<>(); toMapResult.put("errorCode", errorCode); toMapResult.put("description", description); return toMapResult; } static @NonNull CameraPermissionsErrorData fromMap(@NonNull Map<String, Object> map) { CameraPermissionsErrorData pigeonResult = new CameraPermissionsErrorData(); Object errorCode = map.get("errorCode"); pigeonResult.setErrorCode((String) errorCode); Object description = map.get("description"); pigeonResult.setDescription((String) description); return pigeonResult; } } public interface Result<T> { void success(T result); void error(Throwable error); } private static class JavaObjectHostApiCodec extends StandardMessageCodec { public static final JavaObjectHostApiCodec INSTANCE = new JavaObjectHostApiCodec(); private JavaObjectHostApiCodec() {} } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface JavaObjectHostApi { void dispose(@NonNull Long identifier); /** The codec used by JavaObjectHostApi. */ static MessageCodec<Object> getCodec() { return JavaObjectHostApiCodec.INSTANCE; } /** * Sets up an instance of `JavaObjectHostApi` to handle messages through the `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, JavaObjectHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.JavaObjectHostApi.dispose", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } api.dispose((identifierArg == null) ? null : identifierArg.longValue()); wrapped.put("result", null); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static class JavaObjectFlutterApiCodec extends StandardMessageCodec { public static final JavaObjectFlutterApiCodec INSTANCE = new JavaObjectFlutterApiCodec(); private JavaObjectFlutterApiCodec() {} } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class JavaObjectFlutterApi { private final BinaryMessenger binaryMessenger; public JavaObjectFlutterApi(BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } public interface Reply<T> { void reply(T reply); } static MessageCodec<Object> getCodec() { return JavaObjectFlutterApiCodec.INSTANCE; } public void dispose(@NonNull Long identifierArg, Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.JavaObjectFlutterApi.dispose", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(identifierArg)), channelReply -> { callback.reply(null); }); } } private static class CameraInfoHostApiCodec extends StandardMessageCodec { public static final CameraInfoHostApiCodec INSTANCE = new CameraInfoHostApiCodec(); private CameraInfoHostApiCodec() {} } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface CameraInfoHostApi { @NonNull Long getSensorRotationDegrees(@NonNull Long identifier); /** The codec used by CameraInfoHostApi. */ static MessageCodec<Object> getCodec() { return CameraInfoHostApiCodec.INSTANCE; } /** * Sets up an instance of `CameraInfoHostApi` to handle messages through the `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, CameraInfoHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } Long output = api.getSensorRotationDegrees( (identifierArg == null) ? null : identifierArg.longValue()); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static class CameraInfoFlutterApiCodec extends StandardMessageCodec { public static final CameraInfoFlutterApiCodec INSTANCE = new CameraInfoFlutterApiCodec(); private CameraInfoFlutterApiCodec() {} } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class CameraInfoFlutterApi { private final BinaryMessenger binaryMessenger; public CameraInfoFlutterApi(BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } public interface Reply<T> { void reply(T reply); } static MessageCodec<Object> getCodec() { return CameraInfoFlutterApiCodec.INSTANCE; } public void create(@NonNull Long identifierArg, Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.CameraInfoFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(identifierArg)), channelReply -> { callback.reply(null); }); } } private static class CameraSelectorHostApiCodec extends StandardMessageCodec { public static final CameraSelectorHostApiCodec INSTANCE = new CameraSelectorHostApiCodec(); private CameraSelectorHostApiCodec() {} } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface CameraSelectorHostApi { void create(@NonNull Long identifier, @Nullable Long lensFacing); @NonNull List<Long> filter(@NonNull Long identifier, @NonNull List<Long> cameraInfoIds); /** The codec used by CameraSelectorHostApi. */ static MessageCodec<Object> getCodec() { return CameraSelectorHostApiCodec.INSTANCE; } /** * Sets up an instance of `CameraSelectorHostApi` to handle messages through the * `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, CameraSelectorHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.CameraSelectorHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } Number lensFacingArg = (Number) args.get(1); api.create( (identifierArg == null) ? null : identifierArg.longValue(), (lensFacingArg == null) ? null : lensFacingArg.longValue()); wrapped.put("result", null); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.CameraSelectorHostApi.filter", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } List<Long> cameraInfoIdsArg = (List<Long>) args.get(1); if (cameraInfoIdsArg == null) { throw new NullPointerException("cameraInfoIdsArg unexpectedly null."); } List<Long> output = api.filter( (identifierArg == null) ? null : identifierArg.longValue(), cameraInfoIdsArg); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static class CameraSelectorFlutterApiCodec extends StandardMessageCodec { public static final CameraSelectorFlutterApiCodec INSTANCE = new CameraSelectorFlutterApiCodec(); private CameraSelectorFlutterApiCodec() {} } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class CameraSelectorFlutterApi { private final BinaryMessenger binaryMessenger; public CameraSelectorFlutterApi(BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } public interface Reply<T> { void reply(T reply); } static MessageCodec<Object> getCodec() { return CameraSelectorFlutterApiCodec.INSTANCE; } public void create( @NonNull Long identifierArg, @Nullable Long lensFacingArg, Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.CameraSelectorFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(identifierArg, lensFacingArg)), channelReply -> { callback.reply(null); }); } } private static class ProcessCameraProviderHostApiCodec extends StandardMessageCodec { public static final ProcessCameraProviderHostApiCodec INSTANCE = new ProcessCameraProviderHostApiCodec(); private ProcessCameraProviderHostApiCodec() {} } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface ProcessCameraProviderHostApi { void getInstance(Result<Long> result); @NonNull List<Long> getAvailableCameraInfos(@NonNull Long identifier); @NonNull Long bindToLifecycle( @NonNull Long identifier, @NonNull Long cameraSelectorIdentifier, @NonNull List<Long> useCaseIds); void unbind(@NonNull Long identifier, @NonNull List<Long> useCaseIds); void unbindAll(@NonNull Long identifier); /** The codec used by ProcessCameraProviderHostApi. */ static MessageCodec<Object> getCodec() { return ProcessCameraProviderHostApiCodec.INSTANCE; } /** * Sets up an instance of `ProcessCameraProviderHostApi` to handle messages through the * `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, ProcessCameraProviderHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ProcessCameraProviderHostApi.getInstance", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { Result<Long> resultCallback = new Result<Long>() { public void success(Long result) { wrapped.put("result", result); reply.reply(wrapped); } public void error(Throwable error) { wrapped.put("error", wrapError(error)); reply.reply(wrapped); } }; api.getInstance(resultCallback); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); reply.reply(wrapped); } }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } List<Long> output = api.getAvailableCameraInfos( (identifierArg == null) ? null : identifierArg.longValue()); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } Number cameraSelectorIdentifierArg = (Number) args.get(1); if (cameraSelectorIdentifierArg == null) { throw new NullPointerException( "cameraSelectorIdentifierArg unexpectedly null."); } List<Long> useCaseIdsArg = (List<Long>) args.get(2); if (useCaseIdsArg == null) { throw new NullPointerException("useCaseIdsArg unexpectedly null."); } Long output = api.bindToLifecycle( (identifierArg == null) ? null : identifierArg.longValue(), (cameraSelectorIdentifierArg == null) ? null : cameraSelectorIdentifierArg.longValue(), useCaseIdsArg); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } List<Long> useCaseIdsArg = (List<Long>) args.get(1); if (useCaseIdsArg == null) { throw new NullPointerException("useCaseIdsArg unexpectedly null."); } api.unbind( (identifierArg == null) ? null : identifierArg.longValue(), useCaseIdsArg); wrapped.put("result", null); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } api.unbindAll((identifierArg == null) ? null : identifierArg.longValue()); wrapped.put("result", null); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static class ProcessCameraProviderFlutterApiCodec extends StandardMessageCodec { public static final ProcessCameraProviderFlutterApiCodec INSTANCE = new ProcessCameraProviderFlutterApiCodec(); private ProcessCameraProviderFlutterApiCodec() {} } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class ProcessCameraProviderFlutterApi { private final BinaryMessenger binaryMessenger; public ProcessCameraProviderFlutterApi(BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } public interface Reply<T> { void reply(T reply); } static MessageCodec<Object> getCodec() { return ProcessCameraProviderFlutterApiCodec.INSTANCE; } public void create(@NonNull Long identifierArg, Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.ProcessCameraProviderFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(identifierArg)), channelReply -> { callback.reply(null); }); } } private static class CameraFlutterApiCodec extends StandardMessageCodec { public static final CameraFlutterApiCodec INSTANCE = new CameraFlutterApiCodec(); private CameraFlutterApiCodec() {} } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class CameraFlutterApi { private final BinaryMessenger binaryMessenger; public CameraFlutterApi(BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } public interface Reply<T> { void reply(T reply); } static MessageCodec<Object> getCodec() { return CameraFlutterApiCodec.INSTANCE; } public void create(@NonNull Long identifierArg, Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.CameraFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(identifierArg)), channelReply -> { callback.reply(null); }); } } private static class SystemServicesHostApiCodec extends StandardMessageCodec { public static final SystemServicesHostApiCodec INSTANCE = new SystemServicesHostApiCodec(); private SystemServicesHostApiCodec() {} @Override protected Object readValueOfType(byte type, ByteBuffer buffer) { switch (type) { case (byte) 128: return CameraPermissionsErrorData.fromMap((Map<String, Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(ByteArrayOutputStream stream, Object value) { if (value instanceof CameraPermissionsErrorData) { stream.write(128); writeValue(stream, ((CameraPermissionsErrorData) value).toMap()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface SystemServicesHostApi { void requestCameraPermissions( @NonNull Boolean enableAudio, Result<CameraPermissionsErrorData> result); void startListeningForDeviceOrientationChange( @NonNull Boolean isFrontFacing, @NonNull Long sensorOrientation); void stopListeningForDeviceOrientationChange(); /** The codec used by SystemServicesHostApi. */ static MessageCodec<Object> getCodec() { return SystemServicesHostApiCodec.INSTANCE; } /** * Sets up an instance of `SystemServicesHostApi` to handle messages through the * `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, SystemServicesHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Boolean enableAudioArg = (Boolean) args.get(0); if (enableAudioArg == null) { throw new NullPointerException("enableAudioArg unexpectedly null."); } Result<CameraPermissionsErrorData> resultCallback = new Result<CameraPermissionsErrorData>() { public void success(CameraPermissionsErrorData result) { wrapped.put("result", result); reply.reply(wrapped); } public void error(Throwable error) { wrapped.put("error", wrapError(error)); reply.reply(wrapped); } }; api.requestCameraPermissions(enableAudioArg, resultCallback); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); reply.reply(wrapped); } }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.SystemServicesHostApi.startListeningForDeviceOrientationChange", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Boolean isFrontFacingArg = (Boolean) args.get(0); if (isFrontFacingArg == null) { throw new NullPointerException("isFrontFacingArg unexpectedly null."); } Number sensorOrientationArg = (Number) args.get(1); if (sensorOrientationArg == null) { throw new NullPointerException("sensorOrientationArg unexpectedly null."); } api.startListeningForDeviceOrientationChange( isFrontFacingArg, (sensorOrientationArg == null) ? null : sensorOrientationArg.longValue()); wrapped.put("result", null); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.SystemServicesHostApi.stopListeningForDeviceOrientationChange", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { api.stopListeningForDeviceOrientationChange(); wrapped.put("result", null); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static class SystemServicesFlutterApiCodec extends StandardMessageCodec { public static final SystemServicesFlutterApiCodec INSTANCE = new SystemServicesFlutterApiCodec(); private SystemServicesFlutterApiCodec() {} } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class SystemServicesFlutterApi { private final BinaryMessenger binaryMessenger; public SystemServicesFlutterApi(BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } public interface Reply<T> { void reply(T reply); } static MessageCodec<Object> getCodec() { return SystemServicesFlutterApiCodec.INSTANCE; } public void onDeviceOrientationChanged(@NonNull String orientationArg, Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.SystemServicesFlutterApi.onDeviceOrientationChanged", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(orientationArg)), channelReply -> { callback.reply(null); }); } public void onCameraError(@NonNull String errorDescriptionArg, Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.SystemServicesFlutterApi.onCameraError", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(errorDescriptionArg)), channelReply -> { callback.reply(null); }); } } private static class PreviewHostApiCodec extends StandardMessageCodec { public static final PreviewHostApiCodec INSTANCE = new PreviewHostApiCodec(); private PreviewHostApiCodec() {} @Override protected Object readValueOfType(byte type, ByteBuffer buffer) { switch (type) { case (byte) 128: return ResolutionInfo.fromMap((Map<String, Object>) readValue(buffer)); case (byte) 129: return ResolutionInfo.fromMap((Map<String, Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(ByteArrayOutputStream stream, Object value) { if (value instanceof ResolutionInfo) { stream.write(128); writeValue(stream, ((ResolutionInfo) value).toMap()); } else if (value instanceof ResolutionInfo) { stream.write(129); writeValue(stream, ((ResolutionInfo) value).toMap()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface PreviewHostApi { void create( @NonNull Long identifier, @Nullable Long rotation, @Nullable ResolutionInfo targetResolution); @NonNull Long setSurfaceProvider(@NonNull Long identifier); void releaseFlutterSurfaceTexture(); @NonNull ResolutionInfo getResolutionInfo(@NonNull Long identifier); /** The codec used by PreviewHostApi. */ static MessageCodec<Object> getCodec() { return PreviewHostApiCodec.INSTANCE; } /** Sets up an instance of `PreviewHostApi` to handle messages through the `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, PreviewHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PreviewHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } Number rotationArg = (Number) args.get(1); ResolutionInfo targetResolutionArg = (ResolutionInfo) args.get(2); api.create( (identifierArg == null) ? null : identifierArg.longValue(), (rotationArg == null) ? null : rotationArg.longValue(), targetResolutionArg); wrapped.put("result", null); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } Long output = api.setSurfaceProvider( (identifierArg == null) ? null : identifierArg.longValue()); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PreviewHostApi.releaseFlutterSurfaceTexture", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { api.releaseFlutterSurfaceTexture(); wrapped.put("result", null); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.PreviewHostApi.getResolutionInfo", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { Map<String, Object> wrapped = new HashMap<>(); try { ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); if (identifierArg == null) { throw new NullPointerException("identifierArg unexpectedly null."); } ResolutionInfo output = api.getResolutionInfo( (identifierArg == null) ? null : identifierArg.longValue()); wrapped.put("result", output); } catch (Error | RuntimeException exception) { wrapped.put("error", wrapError(exception)); } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static Map<String, Object> wrapError(Throwable exception) { Map<String, Object> errorMap = new HashMap<>(); errorMap.put("message", exception.toString()); errorMap.put("code", exception.getClass().getSimpleName()); errorMap.put( "details", "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); return errorMap; } }
plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/GeneratedCameraXLibrary.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/GeneratedCameraXLibrary.java", "repo_id": "plugins", "token_count": 18041 }
1,217
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.Context; import androidx.camera.core.Camera; import androidx.camera.core.CameraInfo; import androidx.camera.core.CameraSelector; import androidx.camera.core.UseCase; import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.lifecycle.LifecycleOwner; import androidx.test.core.app.ApplicationProvider; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.flutter.plugin.common.BinaryMessenger; import java.util.Arrays; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.stubbing.Answer; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class ProcessCameraProviderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public ProcessCameraProvider processCameraProvider; @Mock public BinaryMessenger mockBinaryMessenger; InstanceManager testInstanceManager; private Context context; @Before public void setUp() { testInstanceManager = InstanceManager.open(identifier -> {}); context = ApplicationProvider.getApplicationContext(); } @After public void tearDown() { testInstanceManager.close(); } @Test public void getInstanceTest() { final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final ListenableFuture<ProcessCameraProvider> processCameraProviderFuture = spy(Futures.immediateFuture(processCameraProvider)); final GeneratedCameraXLibrary.Result<Long> mockResult = mock(GeneratedCameraXLibrary.Result.class); testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); try (MockedStatic<ProcessCameraProvider> mockedProcessCameraProvider = Mockito.mockStatic(ProcessCameraProvider.class)) { mockedProcessCameraProvider .when(() -> ProcessCameraProvider.getInstance(context)) .thenAnswer( (Answer<ListenableFuture<ProcessCameraProvider>>) invocation -> processCameraProviderFuture); final ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); processCameraProviderHostApi.getInstance(mockResult); verify(processCameraProviderFuture).addListener(runnableCaptor.capture(), any()); runnableCaptor.getValue().run(); verify(mockResult).success(0L); } } @Test public void getAvailableCameraInfosTest() { final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final CameraInfo mockCameraInfo = mock(CameraInfo.class); testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); testInstanceManager.addDartCreatedInstance(mockCameraInfo, 1); when(processCameraProvider.getAvailableCameraInfos()).thenReturn(Arrays.asList(mockCameraInfo)); assertEquals(processCameraProviderHostApi.getAvailableCameraInfos(0L), Arrays.asList(1L)); verify(processCameraProvider).getAvailableCameraInfos(); } @Test public void bindToLifecycleTest() { final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final Camera mockCamera = mock(Camera.class); final CameraSelector mockCameraSelector = mock(CameraSelector.class); final UseCase mockUseCase = mock(UseCase.class); UseCase[] mockUseCases = new UseCase[] {mockUseCase}; LifecycleOwner mockLifecycleOwner = mock(LifecycleOwner.class); processCameraProviderHostApi.setLifecycleOwner(mockLifecycleOwner); testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); testInstanceManager.addDartCreatedInstance(mockCameraSelector, 1); testInstanceManager.addDartCreatedInstance(mockUseCase, 2); testInstanceManager.addDartCreatedInstance(mockCamera, 3); when(processCameraProvider.bindToLifecycle( mockLifecycleOwner, mockCameraSelector, mockUseCases)) .thenReturn(mockCamera); assertEquals( processCameraProviderHostApi.bindToLifecycle(0L, 1L, Arrays.asList(2L)), Long.valueOf(3)); verify(processCameraProvider) .bindToLifecycle(mockLifecycleOwner, mockCameraSelector, mockUseCases); } @Test public void unbindTest() { final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); final UseCase mockUseCase = mock(UseCase.class); UseCase[] mockUseCases = new UseCase[] {mockUseCase}; testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); testInstanceManager.addDartCreatedInstance(mockUseCase, 1); processCameraProviderHostApi.unbind(0L, Arrays.asList(1L)); verify(processCameraProvider).unbind(mockUseCases); } @Test public void unbindAllTest() { final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); processCameraProviderHostApi.unbindAll(0L); verify(processCameraProvider).unbindAll(); } @Test public void flutterApiCreateTest() { final ProcessCameraProviderFlutterApiImpl spyFlutterApi = spy(new ProcessCameraProviderFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); spyFlutterApi.create(processCameraProvider, reply -> {}); final long identifier = Objects.requireNonNull( testInstanceManager.getIdentifierForStrongReference(processCameraProvider)); verify(spyFlutterApi).create(eq(identifier), any()); } }
plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ProcessCameraProviderTest.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ProcessCameraProviderTest.java", "repo_id": "plugins", "token_count": 2175 }
1,218
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/widgets.dart'; import 'package:stream_transform/stream_transform.dart'; import 'camera.dart'; import 'camera_info.dart'; import 'camera_selector.dart'; import 'camerax_library.g.dart'; import 'preview.dart'; import 'process_camera_provider.dart'; import 'surface.dart'; import 'system_services.dart'; import 'use_case.dart'; /// The Android implementation of [CameraPlatform] that uses the CameraX library. class AndroidCameraCameraX extends CameraPlatform { /// Registers this class as the default instance of [CameraPlatform]. static void registerWith() { CameraPlatform.instance = AndroidCameraCameraX(); } /// The [ProcessCameraProvider] instance used to access camera functionality. @visibleForTesting ProcessCameraProvider? processCameraProvider; /// The [Camera] instance returned by the [processCameraProvider] when a [UseCase] is /// bound to the lifecycle of the camera it manages. @visibleForTesting Camera? camera; /// The [Preview] instance that can be configured to present a live camera preview. @visibleForTesting Preview? preview; /// Whether or not the [preview] is currently bound to the lifecycle that the /// [processCameraProvider] tracks. @visibleForTesting bool previewIsBound = false; bool _previewIsPaused = false; /// The [CameraSelector] used to configure the [processCameraProvider] to use /// the desired camera. @visibleForTesting CameraSelector? cameraSelector; /// The controller we need to broadcast the different camera events. /// /// It is a `broadcast` because multiple controllers will connect to /// different stream views of this Controller. /// This is only exposed for test purposes. It shouldn't be used by clients of /// the plugin as it may break or change at any time. @visibleForTesting final StreamController<CameraEvent> cameraEventStreamController = StreamController<CameraEvent>.broadcast(); /// The stream of camera events. Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController.stream .where((CameraEvent event) => event.cameraId == cameraId); /// Returns list of all available cameras and their descriptions. @override Future<List<CameraDescription>> availableCameras() async { final List<CameraDescription> cameraDescriptions = <CameraDescription>[]; processCameraProvider ??= await ProcessCameraProvider.getInstance(); final List<CameraInfo> cameraInfos = await processCameraProvider!.getAvailableCameraInfos(); CameraLensDirection? cameraLensDirection; int cameraCount = 0; int? cameraSensorOrientation; String? cameraName; for (final CameraInfo cameraInfo in cameraInfos) { // Determine the lens direction by filtering the CameraInfo // TODO(gmackall): replace this with call to CameraInfo.getLensFacing when changes containing that method are available if ((await createCameraSelector(CameraSelector.lensFacingBack) .filter(<CameraInfo>[cameraInfo])) .isNotEmpty) { cameraLensDirection = CameraLensDirection.back; } else if ((await createCameraSelector(CameraSelector.lensFacingFront) .filter(<CameraInfo>[cameraInfo])) .isNotEmpty) { cameraLensDirection = CameraLensDirection.front; } else { //Skip this CameraInfo as its lens direction is unknown continue; } cameraSensorOrientation = await cameraInfo.getSensorRotationDegrees(); cameraName = 'Camera $cameraCount'; cameraCount++; cameraDescriptions.add(CameraDescription( name: cameraName, lensDirection: cameraLensDirection, sensorOrientation: cameraSensorOrientation)); } return cameraDescriptions; } /// Creates an uninitialized camera instance and returns the camera ID. /// /// In the CameraX library, cameras are accessed by combining [UseCase]s /// to an instance of a [ProcessCameraProvider]. Thus, to create an /// unitialized camera instance, this method retrieves a /// [ProcessCameraProvider] instance. /// /// To return the camera ID, which is equivalent to the ID of the surface texture /// that a camera preview can be drawn to, a [Preview] instance is configured /// and bound to the [ProcessCameraProvider] instance. @override Future<int> createCamera( CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, { bool enableAudio = false, }) async { // Must obtain proper permissions before attempting to access a camera. await requestCameraPermissions(enableAudio); // Save CameraSelector that matches cameraDescription. final int cameraSelectorLensDirection = _getCameraSelectorLensDirection(cameraDescription.lensDirection); final bool cameraIsFrontFacing = cameraSelectorLensDirection == CameraSelector.lensFacingFront; cameraSelector = createCameraSelector(cameraSelectorLensDirection); // Start listening for device orientation changes preceding camera creation. startListeningForDeviceOrientationChange( cameraIsFrontFacing, cameraDescription.sensorOrientation); // Retrieve a ProcessCameraProvider instance. processCameraProvider ??= await ProcessCameraProvider.getInstance(); // Configure Preview instance and bind to ProcessCameraProvider. final int targetRotation = _getTargetRotation(cameraDescription.sensorOrientation); final ResolutionInfo? targetResolution = _getTargetResolutionForPreview(resolutionPreset); preview = createPreview(targetRotation, targetResolution); previewIsBound = false; _previewIsPaused = false; final int flutterSurfaceTextureId = await preview!.setSurfaceProvider(); return flutterSurfaceTextureId; } /// Initializes the camera on the device. /// /// Since initialization of a camera does not directly map as an operation to /// the CameraX library, this method just retrieves information about the /// camera and sends a [CameraInitializedEvent]. /// /// [imageFormatGroup] is used to specify the image formatting used. /// On Android this defaults to ImageFormat.YUV_420_888 and applies only to /// the image stream. @override Future<void> initializeCamera( int cameraId, { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) async { // TODO(camsim99): Use imageFormatGroup to configure ImageAnalysis use case // for image streaming. // https://github.com/flutter/flutter/issues/120463 // Configure CameraInitializedEvent to send as representation of a // configured camera: // Retrieve preview resolution. assert( preview != null, 'Preview instance not found. Please call the "createCamera" method before calling "initializeCamera"', ); await _bindPreviewToLifecycle(); final ResolutionInfo previewResolutionInfo = await preview!.getResolutionInfo(); _unbindPreviewFromLifecycle(); // Retrieve exposure and focus mode configurations: // TODO(camsim99): Implement support for retrieving exposure mode configuration. // https://github.com/flutter/flutter/issues/120468 const ExposureMode exposureMode = ExposureMode.auto; const bool exposurePointSupported = false; // TODO(camsim99): Implement support for retrieving focus mode configuration. // https://github.com/flutter/flutter/issues/120467 const FocusMode focusMode = FocusMode.auto; const bool focusPointSupported = false; cameraEventStreamController.add(CameraInitializedEvent( cameraId, previewResolutionInfo.width.toDouble(), previewResolutionInfo.height.toDouble(), exposureMode, exposurePointSupported, focusMode, focusPointSupported)); } /// Releases the resources of the accessed camera. /// /// [cameraId] not used. @override Future<void> dispose(int cameraId) async { preview?.releaseFlutterSurfaceTexture(); processCameraProvider?.unbindAll(); } /// The camera has been initialized. @override Stream<CameraInitializedEvent> onCameraInitialized(int cameraId) { return _cameraEvents(cameraId).whereType<CameraInitializedEvent>(); } /// The camera experienced an error. @override Stream<CameraErrorEvent> onCameraError(int cameraId) { return SystemServices.cameraErrorStreamController.stream .map<CameraErrorEvent>((String errorDescription) { return CameraErrorEvent(cameraId, errorDescription); }); } /// The ui orientation changed. @override Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() { return SystemServices.deviceOrientationChangedStreamController.stream; } /// Pause the active preview on the current frame for the selected camera. /// /// [cameraId] not used. @override Future<void> pausePreview(int cameraId) async { _unbindPreviewFromLifecycle(); _previewIsPaused = true; } /// Resume the paused preview for the selected camera. /// /// [cameraId] not used. @override Future<void> resumePreview(int cameraId) async { await _bindPreviewToLifecycle(); _previewIsPaused = false; } /// Returns a widget showing a live camera preview. @override Widget buildPreview(int cameraId) { return FutureBuilder<void>( future: _bindPreviewToLifecycle(), builder: (BuildContext context, AsyncSnapshot<void> snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: case ConnectionState.active: // Do nothing while waiting for preview to be bound to lifecyle. return const SizedBox.shrink(); case ConnectionState.done: return Texture(textureId: cameraId); } }); } // Methods for binding UseCases to the lifecycle of the camera controlled // by a ProcessCameraProvider instance: /// Binds [preview] instance to the camera lifecycle controlled by the /// [processCameraProvider]. Future<void> _bindPreviewToLifecycle() async { assert(processCameraProvider != null); assert(cameraSelector != null); if (previewIsBound || _previewIsPaused) { // Only bind if preview is not already bound or intentionally paused. return; } camera = await processCameraProvider! .bindToLifecycle(cameraSelector!, <UseCase>[preview!]); previewIsBound = true; } /// Unbinds [preview] instance to camera lifecycle controlled by the /// [processCameraProvider]. void _unbindPreviewFromLifecycle() { if (preview == null || !previewIsBound) { return; } assert(processCameraProvider != null); processCameraProvider!.unbind(<UseCase>[preview!]); previewIsBound = false; } // Methods for mapping Flutter camera constants to CameraX constants: /// Returns [CameraSelector] lens direction that maps to specified /// [CameraLensDirection]. int _getCameraSelectorLensDirection(CameraLensDirection lensDirection) { switch (lensDirection) { case CameraLensDirection.front: return CameraSelector.lensFacingFront; case CameraLensDirection.back: return CameraSelector.lensFacingBack; case CameraLensDirection.external: return CameraSelector.lensFacingExternal; } } /// Returns [Surface] target rotation constant that maps to specified sensor /// orientation. int _getTargetRotation(int sensorOrientation) { switch (sensorOrientation) { case 90: return Surface.ROTATION_90; case 180: return Surface.ROTATION_180; case 270: return Surface.ROTATION_270; case 0: return Surface.ROTATION_0; default: throw ArgumentError( '"$sensorOrientation" is not a valid sensor orientation value'); } } /// Returns [ResolutionInfo] that maps to the specified resolution preset for /// a camera preview. ResolutionInfo? _getTargetResolutionForPreview(ResolutionPreset? resolution) { // TODO(camsim99): Implement resolution configuration. // https://github.com/flutter/flutter/issues/120462 return null; } // Methods for calls that need to be tested: /// Requests camera permissions. @visibleForTesting Future<void> requestCameraPermissions(bool enableAudio) async { await SystemServices.requestCameraPermissions(enableAudio); } /// Subscribes the plugin as a listener to changes in device orientation. @visibleForTesting void startListeningForDeviceOrientationChange( bool cameraIsFrontFacing, int sensorOrientation) { SystemServices.startListeningForDeviceOrientationChange( cameraIsFrontFacing, sensorOrientation); } /// Returns a [CameraSelector] based on the specified camera lens direction. @visibleForTesting CameraSelector createCameraSelector(int cameraSelectorLensDirection) { switch (cameraSelectorLensDirection) { case CameraSelector.lensFacingFront: return CameraSelector.getDefaultFrontCamera(); case CameraSelector.lensFacingBack: return CameraSelector.getDefaultBackCamera(); default: return CameraSelector(lensFacing: cameraSelectorLensDirection); } } /// Returns a [Preview] configured with the specified target rotation and /// resolution. @visibleForTesting Preview createPreview(int targetRotation, ResolutionInfo? targetResolution) { return Preview( targetRotation: targetRotation, targetResolution: targetResolution); } }
plugins/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart", "repo_id": "plugins", "token_count": 4290 }
1,219
// Mocks generated by Mockito 5.3.2 from annotations // in camera_android_camerax/test/android_camera_camerax_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i8; import 'package:camera_android_camerax/src/camera.dart' as _i3; import 'package:camera_android_camerax/src/camera_info.dart' as _i7; import 'package:camera_android_camerax/src/camera_selector.dart' as _i9; import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2; import 'package:camera_android_camerax/src/preview.dart' as _i10; import 'package:camera_android_camerax/src/process_camera_provider.dart' as _i11; import 'package:camera_android_camerax/src/use_case.dart' as _i12; import 'package:flutter/foundation.dart' as _i6; import 'package:flutter/services.dart' as _i5; import 'package:flutter/src/widgets/framework.dart' as _i4; import 'package:flutter/src/widgets/notification_listener.dart' as _i13; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeResolutionInfo_0 extends _i1.SmartFake implements _i2.ResolutionInfo { _FakeResolutionInfo_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeCamera_1 extends _i1.SmartFake implements _i3.Camera { _FakeCamera_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWidget_2 extends _i1.SmartFake implements _i4.Widget { _FakeWidget_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString({_i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info}) => super.toString(); } class _FakeInheritedWidget_3 extends _i1.SmartFake implements _i4.InheritedWidget { _FakeInheritedWidget_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString({_i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info}) => super.toString(); } class _FakeDiagnosticsNode_4 extends _i1.SmartFake implements _i6.DiagnosticsNode { _FakeDiagnosticsNode_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString({ _i6.TextTreeConfiguration? parentConfiguration, _i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info, }) => super.toString(); } /// A class which mocks [Camera]. /// /// See the documentation for Mockito's code generation for more information. class MockCamera extends _i1.Mock implements _i3.Camera {} /// A class which mocks [CameraInfo]. /// /// See the documentation for Mockito's code generation for more information. class MockCameraInfo extends _i1.Mock implements _i7.CameraInfo { @override _i8.Future<int> getSensorRotationDegrees() => (super.noSuchMethod( Invocation.method( #getSensorRotationDegrees, [], ), returnValue: _i8.Future<int>.value(0), returnValueForMissingStub: _i8.Future<int>.value(0), ) as _i8.Future<int>); } /// A class which mocks [CameraSelector]. /// /// See the documentation for Mockito's code generation for more information. class MockCameraSelector extends _i1.Mock implements _i9.CameraSelector { @override _i8.Future<List<_i7.CameraInfo>> filter(List<_i7.CameraInfo>? cameraInfos) => (super.noSuchMethod( Invocation.method( #filter, [cameraInfos], ), returnValue: _i8.Future<List<_i7.CameraInfo>>.value(<_i7.CameraInfo>[]), returnValueForMissingStub: _i8.Future<List<_i7.CameraInfo>>.value(<_i7.CameraInfo>[]), ) as _i8.Future<List<_i7.CameraInfo>>); } /// A class which mocks [Preview]. /// /// See the documentation for Mockito's code generation for more information. class MockPreview extends _i1.Mock implements _i10.Preview { @override _i8.Future<int> setSurfaceProvider() => (super.noSuchMethod( Invocation.method( #setSurfaceProvider, [], ), returnValue: _i8.Future<int>.value(0), returnValueForMissingStub: _i8.Future<int>.value(0), ) as _i8.Future<int>); @override void releaseFlutterSurfaceTexture() => super.noSuchMethod( Invocation.method( #releaseFlutterSurfaceTexture, [], ), returnValueForMissingStub: null, ); @override _i8.Future<_i2.ResolutionInfo> getResolutionInfo() => (super.noSuchMethod( Invocation.method( #getResolutionInfo, [], ), returnValue: _i8.Future<_i2.ResolutionInfo>.value(_FakeResolutionInfo_0( this, Invocation.method( #getResolutionInfo, [], ), )), returnValueForMissingStub: _i8.Future<_i2.ResolutionInfo>.value(_FakeResolutionInfo_0( this, Invocation.method( #getResolutionInfo, [], ), )), ) as _i8.Future<_i2.ResolutionInfo>); } /// A class which mocks [ProcessCameraProvider]. /// /// See the documentation for Mockito's code generation for more information. class MockProcessCameraProvider extends _i1.Mock implements _i11.ProcessCameraProvider { @override _i8.Future<List<_i7.CameraInfo>> getAvailableCameraInfos() => (super.noSuchMethod( Invocation.method( #getAvailableCameraInfos, [], ), returnValue: _i8.Future<List<_i7.CameraInfo>>.value(<_i7.CameraInfo>[]), returnValueForMissingStub: _i8.Future<List<_i7.CameraInfo>>.value(<_i7.CameraInfo>[]), ) as _i8.Future<List<_i7.CameraInfo>>); @override _i8.Future<_i3.Camera> bindToLifecycle( _i9.CameraSelector? cameraSelector, List<_i12.UseCase>? useCases, ) => (super.noSuchMethod( Invocation.method( #bindToLifecycle, [ cameraSelector, useCases, ], ), returnValue: _i8.Future<_i3.Camera>.value(_FakeCamera_1( this, Invocation.method( #bindToLifecycle, [ cameraSelector, useCases, ], ), )), returnValueForMissingStub: _i8.Future<_i3.Camera>.value(_FakeCamera_1( this, Invocation.method( #bindToLifecycle, [ cameraSelector, useCases, ], ), )), ) as _i8.Future<_i3.Camera>); @override void unbind(List<_i12.UseCase>? useCases) => super.noSuchMethod( Invocation.method( #unbind, [useCases], ), returnValueForMissingStub: null, ); @override void unbindAll() => super.noSuchMethod( Invocation.method( #unbindAll, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [BuildContext]. /// /// See the documentation for Mockito's code generation for more information. class MockBuildContext extends _i1.Mock implements _i4.BuildContext { MockBuildContext() { _i1.throwOnMissingStub(this); } @override _i4.Widget get widget => (super.noSuchMethod( Invocation.getter(#widget), returnValue: _FakeWidget_2( this, Invocation.getter(#widget), ), ) as _i4.Widget); @override bool get mounted => (super.noSuchMethod( Invocation.getter(#mounted), returnValue: false, ) as bool); @override bool get debugDoingBuild => (super.noSuchMethod( Invocation.getter(#debugDoingBuild), returnValue: false, ) as bool); @override _i4.InheritedWidget dependOnInheritedElement( _i4.InheritedElement? ancestor, { Object? aspect, }) => (super.noSuchMethod( Invocation.method( #dependOnInheritedElement, [ancestor], {#aspect: aspect}, ), returnValue: _FakeInheritedWidget_3( this, Invocation.method( #dependOnInheritedElement, [ancestor], {#aspect: aspect}, ), ), ) as _i4.InheritedWidget); @override void visitAncestorElements(bool Function(_i4.Element)? visitor) => super.noSuchMethod( Invocation.method( #visitAncestorElements, [visitor], ), returnValueForMissingStub: null, ); @override void visitChildElements(_i4.ElementVisitor? visitor) => super.noSuchMethod( Invocation.method( #visitChildElements, [visitor], ), returnValueForMissingStub: null, ); @override void dispatchNotification(_i13.Notification? notification) => super.noSuchMethod( Invocation.method( #dispatchNotification, [notification], ), returnValueForMissingStub: null, ); @override _i6.DiagnosticsNode describeElement( String? name, { _i6.DiagnosticsTreeStyle? style = _i6.DiagnosticsTreeStyle.errorProperty, }) => (super.noSuchMethod( Invocation.method( #describeElement, [name], {#style: style}, ), returnValue: _FakeDiagnosticsNode_4( this, Invocation.method( #describeElement, [name], {#style: style}, ), ), ) as _i6.DiagnosticsNode); @override _i6.DiagnosticsNode describeWidget( String? name, { _i6.DiagnosticsTreeStyle? style = _i6.DiagnosticsTreeStyle.errorProperty, }) => (super.noSuchMethod( Invocation.method( #describeWidget, [name], {#style: style}, ), returnValue: _FakeDiagnosticsNode_4( this, Invocation.method( #describeWidget, [name], {#style: style}, ), ), ) as _i6.DiagnosticsNode); @override List<_i6.DiagnosticsNode> describeMissingAncestor( {required Type? expectedAncestorType}) => (super.noSuchMethod( Invocation.method( #describeMissingAncestor, [], {#expectedAncestorType: expectedAncestorType}, ), returnValue: <_i6.DiagnosticsNode>[], ) as List<_i6.DiagnosticsNode>); @override _i6.DiagnosticsNode describeOwnershipChain(String? name) => (super.noSuchMethod( Invocation.method( #describeOwnershipChain, [name], ), returnValue: _FakeDiagnosticsNode_4( this, Invocation.method( #describeOwnershipChain, [name], ), ), ) as _i6.DiagnosticsNode); }
plugins/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart", "repo_id": "plugins", "token_count": 5177 }
1,220
// 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 "CameraTestUtils.h" #import <OCMock/OCMock.h> @import AVFoundation; FLTCam *FLTCreateCamWithCaptureSessionQueue(dispatch_queue_t captureSessionQueue) { id inputMock = OCMClassMock([AVCaptureDeviceInput class]); OCMStub([inputMock deviceInputWithDevice:[OCMArg any] error:[OCMArg setTo:nil]]) .andReturn(inputMock); id sessionMock = OCMClassMock([AVCaptureSession class]); OCMStub([sessionMock addInputWithNoConnections:[OCMArg any]]); // no-op OCMStub([sessionMock canSetSessionPreset:[OCMArg any]]).andReturn(YES); return [[FLTCam alloc] initWithCameraName:@"camera" resolutionPreset:@"medium" enableAudio:true orientation:UIDeviceOrientationPortrait captureSession:sessionMock captureSessionQueue:captureSessionQueue error:nil]; } CMSampleBufferRef FLTCreateTestSampleBuffer(void) { CVPixelBufferRef pixelBuffer; CVPixelBufferCreate(kCFAllocatorDefault, 100, 100, kCVPixelFormatType_32BGRA, NULL, &pixelBuffer); CMFormatDescriptionRef formatDescription; CMVideoFormatDescriptionCreateForImageBuffer(kCFAllocatorDefault, pixelBuffer, &formatDescription); CMSampleTimingInfo timingInfo = {CMTimeMake(1, 44100), kCMTimeZero, kCMTimeInvalid}; CMSampleBufferRef sampleBuffer; CMSampleBufferCreateReadyWithImageBuffer(kCFAllocatorDefault, pixelBuffer, formatDescription, &timingInfo, &sampleBuffer); CFRelease(pixelBuffer); CFRelease(formatDescription); return sampleBuffer; }
plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.m", "repo_id": "plugins", "token_count": 763 }
1,221
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FLTSavePhotoDelegate.h" #import "FLTSavePhotoDelegate_Test.h" @interface FLTSavePhotoDelegate () /// The file path for the captured photo. @property(readonly, nonatomic) NSString *path; /// The queue on which captured photos are written to disk. @property(readonly, nonatomic) dispatch_queue_t ioQueue; @end @implementation FLTSavePhotoDelegate - (instancetype)initWithPath:(NSString *)path ioQueue:(dispatch_queue_t)ioQueue completionHandler:(FLTSavePhotoDelegateCompletionHandler)completionHandler { self = [super init]; NSAssert(self, @"super init cannot be nil"); _path = path; _ioQueue = ioQueue; _completionHandler = completionHandler; return self; } - (void)handlePhotoCaptureResultWithError:(NSError *)error photoDataProvider:(NSData * (^)(void))photoDataProvider { if (error) { self.completionHandler(nil, error); return; } __weak typeof(self) weakSelf = self; dispatch_async(self.ioQueue, ^{ typeof(self) strongSelf = weakSelf; if (!strongSelf) return; NSData *data = photoDataProvider(); NSError *ioError; if ([data writeToFile:strongSelf.path options:NSDataWritingAtomic error:&ioError]) { strongSelf.completionHandler(self.path, nil); } else { strongSelf.completionHandler(nil, ioError); } }); } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma clang diagnostic ignored "-Wdeprecated-implementations" - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhotoSampleBuffer:(CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(AVCaptureBracketedStillImageSettings *)bracketSettings error:(NSError *)error API_AVAILABLE(ios(10)) { [self handlePhotoCaptureResultWithError:error photoDataProvider:^NSData * { return [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer: previewPhotoSampleBuffer]; }]; } #pragma clang diagnostic pop - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error API_AVAILABLE(ios(11.0)) { [self handlePhotoCaptureResultWithError:error photoDataProvider:^NSData * { return [photo fileDataRepresentation]; }]; } @end
plugins/packages/camera/camera_avfoundation/ios/Classes/FLTSavePhotoDelegate.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTSavePhotoDelegate.m", "repo_id": "plugins", "token_count": 1245 }
1,222
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import '../../camera_platform_interface.dart'; import '../method_channel/method_channel_camera.dart'; /// The interface that implementations of camera must implement. /// /// Platform implementations should extend this class rather than implement it as `camera` /// 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 /// [CameraPlatform] methods. abstract class CameraPlatform extends PlatformInterface { /// Constructs a CameraPlatform. CameraPlatform() : super(token: _token); static final Object _token = Object(); static CameraPlatform _instance = MethodChannelCamera(); /// The default instance of [CameraPlatform] to use. /// /// Defaults to [MethodChannelCamera]. static CameraPlatform get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [CameraPlatform] when they register themselves. static set instance(CameraPlatform instance) { PlatformInterface.verify(instance, _token); _instance = instance; } /// Completes with a list of available cameras. /// /// This method returns an empty list when no cameras are available. Future<List<CameraDescription>> availableCameras() { throw UnimplementedError('availableCameras() is not implemented.'); } /// Creates an uninitialized camera instance and returns the cameraId. Future<int> createCamera( CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, { bool enableAudio = false, }) { throw UnimplementedError('createCamera() is not implemented.'); } /// Initializes the camera on the device. /// /// [imageFormatGroup] is used to specify the image formatting used. /// On Android this defaults to ImageFormat.YUV_420_888 and applies only to the imageStream. /// On iOS this defaults to kCVPixelFormatType_32BGRA. /// On Web this parameter is currently not supported. Future<void> initializeCamera( int cameraId, { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) { throw UnimplementedError('initializeCamera() is not implemented.'); } /// The camera has been initialized. Stream<CameraInitializedEvent> onCameraInitialized(int cameraId) { throw UnimplementedError('onCameraInitialized() is not implemented.'); } /// The camera's resolution has changed. /// On Web this returns an empty stream. Stream<CameraResolutionChangedEvent> onCameraResolutionChanged(int cameraId) { throw UnimplementedError('onResolutionChanged() is not implemented.'); } /// The camera started to close. Stream<CameraClosingEvent> onCameraClosing(int cameraId) { throw UnimplementedError('onCameraClosing() is not implemented.'); } /// The camera experienced an error. Stream<CameraErrorEvent> onCameraError(int cameraId) { throw UnimplementedError('onCameraError() is not implemented.'); } /// The camera finished recording a video. Stream<VideoRecordedEvent> onVideoRecordedEvent(int cameraId) { throw UnimplementedError('onCameraTimeLimitReached() is not implemented.'); } /// The ui orientation changed. /// /// Implementations for this: /// - Should support all 4 orientations. Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() { throw UnimplementedError( 'onDeviceOrientationChanged() is not implemented.'); } /// Locks the capture orientation. Future<void> lockCaptureOrientation( int cameraId, DeviceOrientation orientation) { throw UnimplementedError('lockCaptureOrientation() is not implemented.'); } /// Unlocks the capture orientation. Future<void> unlockCaptureOrientation(int cameraId) { throw UnimplementedError('unlockCaptureOrientation() is not implemented.'); } /// Captures an image and returns the file where it was saved. Future<XFile> takePicture(int cameraId) { throw UnimplementedError('takePicture() is not implemented.'); } /// Prepare the capture session for video recording. Future<void> prepareForVideoRecording() { throw UnimplementedError('prepareForVideoRecording() is not implemented.'); } /// Starts a video recording. /// /// The length of the recording can be limited by specifying the [maxVideoDuration]. /// By default no maximum duration is specified, /// meaning the recording will continue until manually stopped. /// With [maxVideoDuration] set the video is returned in a [VideoRecordedEvent] /// through the [onVideoRecordedEvent] stream when the set duration is reached. /// /// This method is deprecated in favour of [startVideoCapturing]. Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) { throw UnimplementedError('startVideoRecording() is not implemented.'); } /// Starts a video recording and/or streaming session. /// /// Please see [VideoCaptureOptions] for documentation on the /// configuration options. Future<void> startVideoCapturing(VideoCaptureOptions options) { return startVideoRecording(options.cameraId, maxVideoDuration: options.maxDuration); } /// Stops the video recording and returns the file where it was saved. Future<XFile> stopVideoRecording(int cameraId) { throw UnimplementedError('stopVideoRecording() is not implemented.'); } /// Pause video recording. Future<void> pauseVideoRecording(int cameraId) { throw UnimplementedError('pauseVideoRecording() is not implemented.'); } /// Resume video recording after pausing. Future<void> resumeVideoRecording(int cameraId) { throw UnimplementedError('resumeVideoRecording() is not implemented.'); } /// A new streamed frame is available. /// /// Listening to this stream will start streaming, and canceling will stop. /// Pausing will throw a [CameraException], as pausing the stream would cause /// very high memory usage; to temporarily stop receiving frames, cancel, then /// listen again later. /// /// // TODO(bmparr): Add options to control streaming settings (e.g., // resolution and FPS). Stream<CameraImageData> onStreamedFrameAvailable(int cameraId, {CameraImageStreamOptions? options}) { throw UnimplementedError('onStreamedFrameAvailable() is not implemented.'); } /// Sets the flash mode for the selected camera. /// On Web [FlashMode.auto] corresponds to [FlashMode.always]. Future<void> setFlashMode(int cameraId, FlashMode mode) { throw UnimplementedError('setFlashMode() is not implemented.'); } /// Sets the exposure mode for taking pictures. Future<void> setExposureMode(int cameraId, ExposureMode mode) { throw UnimplementedError('setExposureMode() is not implemented.'); } /// Sets the exposure point for automatically determining the exposure values. /// /// Supplying `null` for the [point] argument will result in resetting to the /// original exposure point value. Future<void> setExposurePoint(int cameraId, Point<double>? point) { throw UnimplementedError('setExposurePoint() is not implemented.'); } /// Gets the minimum supported exposure offset for the selected camera in EV units. Future<double> getMinExposureOffset(int cameraId) { throw UnimplementedError('getMinExposureOffset() is not implemented.'); } /// Gets the maximum supported exposure offset for the selected camera in EV units. Future<double> getMaxExposureOffset(int cameraId) { throw UnimplementedError('getMaxExposureOffset() is not implemented.'); } /// Gets the supported step size for exposure offset for the selected camera in EV units. /// /// Returns 0 when the camera supports using a free value without stepping. Future<double> getExposureOffsetStepSize(int cameraId) { throw UnimplementedError('getMinExposureOffset() is not implemented.'); } /// Sets the exposure offset for the selected camera. /// /// The supplied [offset] value should be in EV units. 1 EV unit represents a /// doubling in brightness. It should be between the minimum and maximum offsets /// obtained through `getMinExposureOffset` and `getMaxExposureOffset` respectively. /// Throws a `CameraException` when an illegal offset is supplied. /// /// When the supplied [offset] value does not align with the step size obtained /// through `getExposureStepSize`, it will automatically be rounded to the nearest step. /// /// Returns the (rounded) offset value that was set. Future<double> setExposureOffset(int cameraId, double offset) { throw UnimplementedError('setExposureOffset() is not implemented.'); } /// Sets the focus mode for taking pictures. Future<void> setFocusMode(int cameraId, FocusMode mode) { throw UnimplementedError('setFocusMode() is not implemented.'); } /// Sets the focus point for automatically determining the focus values. /// /// Supplying `null` for the [point] argument will result in resetting to the /// original focus point value. Future<void> setFocusPoint(int cameraId, Point<double>? point) { throw UnimplementedError('setFocusPoint() is not implemented.'); } /// Gets the maximum supported zoom level for the selected camera. Future<double> getMaxZoomLevel(int cameraId) { throw UnimplementedError('getMaxZoomLevel() is not implemented.'); } /// Gets the minimum supported zoom level for the selected camera. Future<double> getMinZoomLevel(int cameraId) { throw UnimplementedError('getMinZoomLevel() is not implemented.'); } /// Set the zoom level for the selected camera. /// /// The supplied [zoom] value should be between the minimum and the maximum supported /// zoom level returned by `getMinZoomLevel` and `getMaxZoomLevel`. Throws a `CameraException` /// when an illegal zoom level is supplied. Future<void> setZoomLevel(int cameraId, double zoom) { throw UnimplementedError('setZoomLevel() is not implemented.'); } /// Pause the active preview on the current frame for the selected camera. Future<void> pausePreview(int cameraId) { throw UnimplementedError('pausePreview() is not implemented.'); } /// Resume the paused preview for the selected camera. Future<void> resumePreview(int cameraId) { throw UnimplementedError('pausePreview() is not implemented.'); } /// Sets the active camera while recording. Future<void> setDescriptionWhileRecording(CameraDescription description) { throw UnimplementedError( 'setDescriptionWhileRecording() is not implemented.'); } /// Returns a widget showing a live camera preview. Widget buildPreview(int cameraId) { throw UnimplementedError('buildView() has not been implemented.'); } /// Releases the resources of this camera. Future<void> dispose(int cameraId) { throw UnimplementedError('dispose() is not implemented.'); } }
plugins/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart/0
{ "file_path": "plugins/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart", "repo_id": "plugins", "token_count": 3086 }
1,223
name: camera_web description: A Flutter plugin for getting information about and controlling the camera on Web. repository: https://github.com/flutter/plugins/tree/main/packages/camera/camera_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 version: 0.3.1+1 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: camera platforms: web: pluginClass: CameraPlugin fileName: camera_web.dart dependencies: camera_platform_interface: ^2.3.1 flutter: sdk: flutter flutter_web_plugins: sdk: flutter stream_transform: ^2.0.0 dev_dependencies: flutter_test: sdk: flutter
plugins/packages/camera/camera_web/pubspec.yaml/0
{ "file_path": "plugins/packages/camera/camera_web/pubspec.yaml", "repo_id": "plugins", "token_count": 293 }
1,224
// 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:math'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:stream_transform/stream_transform.dart'; /// An implementation of [CameraPlatform] for Windows. class CameraWindows extends CameraPlatform { /// Registers the Windows implementation of CameraPlatform. static void registerWith() { CameraPlatform.instance = CameraWindows(); } /// The method channel used to interact with the native platform. @visibleForTesting final MethodChannel pluginChannel = const MethodChannel('plugins.flutter.io/camera_windows'); /// Camera specific method channels to allow communicating with specific cameras. final Map<int, MethodChannel> _cameraChannels = <int, MethodChannel>{}; /// The controller that broadcasts events coming from handleCameraMethodCall /// /// It is a `broadcast` because multiple controllers will connect to /// different stream views of this Controller. /// This is only exposed for test purposes. It shouldn't be used by clients of /// the plugin as it may break or change at any time. @visibleForTesting final StreamController<CameraEvent> cameraEventStreamController = StreamController<CameraEvent>.broadcast(); /// Returns a stream of camera events for the given [cameraId]. Stream<CameraEvent> _cameraEvents(int cameraId) => cameraEventStreamController.stream .where((CameraEvent event) => event.cameraId == cameraId); @override Future<List<CameraDescription>> availableCameras() async { try { final List<Map<dynamic, dynamic>>? cameras = await pluginChannel .invokeListMethod<Map<dynamic, dynamic>>('availableCameras'); if (cameras == null) { return <CameraDescription>[]; } return cameras.map((Map<dynamic, dynamic> camera) { return CameraDescription( name: camera['name'] as String, lensDirection: parseCameraLensDirection(camera['lensFacing'] as String), sensorOrientation: camera['sensorOrientation'] as int, ); }).toList(); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } } @override Future<int> createCamera( CameraDescription cameraDescription, ResolutionPreset? resolutionPreset, { bool enableAudio = false, }) async { try { // If resolutionPreset is not specified, plugin selects the highest resolution possible. final Map<String, dynamic>? reply = await pluginChannel .invokeMapMethod<String, dynamic>('create', <String, dynamic>{ 'cameraName': cameraDescription.name, 'resolutionPreset': _serializeResolutionPreset(resolutionPreset), 'enableAudio': enableAudio, }); if (reply == null) { throw CameraException('System', 'Cannot create camera'); } return reply['cameraId']! as int; } on PlatformException catch (e) { throw CameraException(e.code, e.message); } } @override Future<void> initializeCamera( int cameraId, { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) async { final int requestedCameraId = cameraId; /// Creates channel for camera events. _cameraChannels.putIfAbsent(requestedCameraId, () { final MethodChannel channel = MethodChannel( 'plugins.flutter.io/camera_windows/camera$requestedCameraId'); channel.setMethodCallHandler( (MethodCall call) => handleCameraMethodCall(call, requestedCameraId), ); return channel; }); final Map<String, double>? reply; try { reply = await pluginChannel.invokeMapMethod<String, double>( 'initialize', <String, dynamic>{ 'cameraId': requestedCameraId, }, ); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } cameraEventStreamController.add( CameraInitializedEvent( requestedCameraId, reply!['previewWidth']!, reply['previewHeight']!, ExposureMode.auto, false, FocusMode.auto, false, ), ); } @override Future<void> dispose(int cameraId) async { await pluginChannel.invokeMethod<void>( 'dispose', <String, dynamic>{'cameraId': cameraId}, ); // Destroy method channel after camera is disposed to be able to handle last messages. if (_cameraChannels.containsKey(cameraId)) { final MethodChannel? cameraChannel = _cameraChannels[cameraId]; cameraChannel?.setMethodCallHandler(null); _cameraChannels.remove(cameraId); } } @override Stream<CameraInitializedEvent> onCameraInitialized(int cameraId) { return _cameraEvents(cameraId).whereType<CameraInitializedEvent>(); } @override Stream<CameraResolutionChangedEvent> onCameraResolutionChanged(int cameraId) { /// Windows API does not automatically change the camera's resolution /// during capture so these events are never send from the platform. /// Support for changing resolution should be implemented, if support for /// requesting resolution change is added to camera platform interface. return const Stream<CameraResolutionChangedEvent>.empty(); } @override Stream<CameraClosingEvent> onCameraClosing(int cameraId) { return _cameraEvents(cameraId).whereType<CameraClosingEvent>(); } @override Stream<CameraErrorEvent> onCameraError(int cameraId) { return _cameraEvents(cameraId).whereType<CameraErrorEvent>(); } @override Stream<VideoRecordedEvent> onVideoRecordedEvent(int cameraId) { return _cameraEvents(cameraId).whereType<VideoRecordedEvent>(); } @override Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() { // TODO(jokerttu): Implement device orientation detection, https://github.com/flutter/flutter/issues/97540. // Force device orientation to landscape as by default camera plugin uses portraitUp orientation. return Stream<DeviceOrientationChangedEvent>.value( const DeviceOrientationChangedEvent(DeviceOrientation.landscapeRight), ); } @override Future<void> lockCaptureOrientation( int cameraId, DeviceOrientation orientation, ) async { // TODO(jokerttu): Implement lock capture orientation feature, https://github.com/flutter/flutter/issues/97540. throw UnimplementedError('lockCaptureOrientation() is not implemented.'); } @override Future<void> unlockCaptureOrientation(int cameraId) async { // TODO(jokerttu): Implement unlock capture orientation feature, https://github.com/flutter/flutter/issues/97540. throw UnimplementedError('unlockCaptureOrientation() is not implemented.'); } @override Future<XFile> takePicture(int cameraId) async { final String? path; path = await pluginChannel.invokeMethod<String>( 'takePicture', <String, dynamic>{'cameraId': cameraId}, ); return XFile(path!); } @override Future<void> prepareForVideoRecording() => pluginChannel.invokeMethod<void>('prepareForVideoRecording'); @override Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async { return startVideoCapturing( VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration)); } @override Future<void> startVideoCapturing(VideoCaptureOptions options) async { if (options.streamCallback != null || options.streamOptions != null) { throw UnimplementedError( 'Streaming is not currently supported on Windows'); } await pluginChannel.invokeMethod<void>( 'startVideoRecording', <String, dynamic>{ 'cameraId': options.cameraId, 'maxVideoDuration': options.maxDuration?.inMilliseconds, }, ); } @override Future<XFile> stopVideoRecording(int cameraId) async { final String? path; path = await pluginChannel.invokeMethod<String>( 'stopVideoRecording', <String, dynamic>{'cameraId': cameraId}, ); return XFile(path!); } @override Future<void> pauseVideoRecording(int cameraId) async { throw UnsupportedError( 'pauseVideoRecording() is not supported due to Win32 API limitations.'); } @override Future<void> resumeVideoRecording(int cameraId) async { throw UnsupportedError( 'resumeVideoRecording() is not supported due to Win32 API limitations.'); } @override Future<void> setFlashMode(int cameraId, FlashMode mode) async { // TODO(jokerttu): Implement flash mode support, https://github.com/flutter/flutter/issues/97537. throw UnimplementedError('setFlashMode() is not implemented.'); } @override Future<void> setExposureMode(int cameraId, ExposureMode mode) async { // TODO(jokerttu): Implement explosure mode support, https://github.com/flutter/flutter/issues/97537. throw UnimplementedError('setExposureMode() is not implemented.'); } @override Future<void> setExposurePoint(int cameraId, Point<double>? point) async { assert(point == null || point.x >= 0 && point.x <= 1); assert(point == null || point.y >= 0 && point.y <= 1); throw UnsupportedError( 'setExposurePoint() is not supported due to Win32 API limitations.'); } @override Future<double> getMinExposureOffset(int cameraId) async { // TODO(jokerttu): Implement exposure control support, https://github.com/flutter/flutter/issues/97537. // Value is returned to support existing implementations. return 0.0; } @override Future<double> getMaxExposureOffset(int cameraId) async { // TODO(jokerttu): Implement exposure control support, https://github.com/flutter/flutter/issues/97537. // Value is returned to support existing implementations. return 0.0; } @override Future<double> getExposureOffsetStepSize(int cameraId) async { // TODO(jokerttu): Implement exposure control support, https://github.com/flutter/flutter/issues/97537. // Value is returned to support existing implementations. return 1.0; } @override Future<double> setExposureOffset(int cameraId, double offset) async { // TODO(jokerttu): Implement exposure control support, https://github.com/flutter/flutter/issues/97537. throw UnimplementedError('setExposureOffset() is not implemented.'); } @override Future<void> setFocusMode(int cameraId, FocusMode mode) async { // TODO(jokerttu): Implement focus mode support, https://github.com/flutter/flutter/issues/97537. throw UnimplementedError('setFocusMode() is not implemented.'); } @override Future<void> setFocusPoint(int cameraId, Point<double>? point) async { assert(point == null || point.x >= 0 && point.x <= 1); assert(point == null || point.y >= 0 && point.y <= 1); throw UnsupportedError( 'setFocusPoint() is not supported due to Win32 API limitations.'); } @override Future<double> getMinZoomLevel(int cameraId) async { // TODO(jokerttu): Implement zoom level support, https://github.com/flutter/flutter/issues/97537. // Value is returned to support existing implementations. return 1.0; } @override Future<double> getMaxZoomLevel(int cameraId) async { // TODO(jokerttu): Implement zoom level support, https://github.com/flutter/flutter/issues/97537. // Value is returned to support existing implementations. return 1.0; } @override Future<void> setZoomLevel(int cameraId, double zoom) async { // TODO(jokerttu): Implement zoom level support, https://github.com/flutter/flutter/issues/97537. throw UnimplementedError('setZoomLevel() is not implemented.'); } @override Future<void> pausePreview(int cameraId) async { await pluginChannel.invokeMethod<double>( 'pausePreview', <String, dynamic>{'cameraId': cameraId}, ); } @override Future<void> resumePreview(int cameraId) async { await pluginChannel.invokeMethod<double>( 'resumePreview', <String, dynamic>{'cameraId': cameraId}, ); } @override Widget buildPreview(int cameraId) { return Texture(textureId: cameraId); } /// Returns the resolution preset as a nullable String. String? _serializeResolutionPreset(ResolutionPreset? resolutionPreset) { switch (resolutionPreset) { case null: return null; case ResolutionPreset.max: return 'max'; case ResolutionPreset.ultraHigh: return 'ultraHigh'; case ResolutionPreset.veryHigh: return 'veryHigh'; case ResolutionPreset.high: return 'high'; case ResolutionPreset.medium: return 'medium'; case ResolutionPreset.low: return 'low'; } } /// Converts messages received from the native platform into camera events. /// /// This is only exposed for test purposes. It shouldn't be used by clients /// of the plugin as it may break or change at any time. @visibleForTesting Future<dynamic> handleCameraMethodCall(MethodCall call, int cameraId) async { switch (call.method) { case 'camera_closing': cameraEventStreamController.add( CameraClosingEvent( cameraId, ), ); break; case 'video_recorded': final Map<String, Object?> arguments = (call.arguments as Map<Object?, Object?>).cast<String, Object?>(); final int? maxDuration = arguments['maxVideoDuration'] as int?; // This is called if maxVideoDuration was given on record start. cameraEventStreamController.add( VideoRecordedEvent( cameraId, XFile(arguments['path']! as String), maxDuration != null ? Duration(milliseconds: maxDuration) : null, ), ); break; case 'error': final Map<String, Object?> arguments = (call.arguments as Map<Object?, Object?>).cast<String, Object?>(); cameraEventStreamController.add( CameraErrorEvent( cameraId, arguments['description']! as String, ), ); break; default: throw UnimplementedError(); } } /// Parses string presentation of the camera lens direction and returns enum value. @visibleForTesting CameraLensDirection parseCameraLensDirection(String string) { switch (string) { case 'front': return CameraLensDirection.front; case 'back': return CameraLensDirection.back; case 'external': return CameraLensDirection.external; } throw ArgumentError('Unknown CameraLensDirection value'); } }
plugins/packages/camera/camera_windows/lib/camera_windows.dart/0
{ "file_path": "plugins/packages/camera/camera_windows/lib/camera_windows.dart", "repo_id": "plugins", "token_count": 5060 }
1,225
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "capture_engine_listener.h" #include <mfcaptureengine.h> #include <wrl/client.h> namespace camera_windows { using Microsoft::WRL::ComPtr; // IUnknown STDMETHODIMP_(ULONG) CaptureEngineListener::AddRef() { return InterlockedIncrement(&ref_); } // IUnknown STDMETHODIMP_(ULONG) CaptureEngineListener::Release() { LONG ref = InterlockedDecrement(&ref_); if (ref == 0) { delete this; } return ref; } // IUnknown STDMETHODIMP_(HRESULT) CaptureEngineListener::QueryInterface(const IID& riid, void** ppv) { *ppv = nullptr; if (riid == IID_IMFCaptureEngineOnEventCallback) { *ppv = static_cast<IMFCaptureEngineOnEventCallback*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } else if (riid == IID_IMFCaptureEngineOnSampleCallback) { *ppv = static_cast<IMFCaptureEngineOnSampleCallback*>(this); ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP CaptureEngineListener::OnEvent(IMFMediaEvent* event) { if (observer_) { observer_->OnEvent(event); } return S_OK; } // IMFCaptureEngineOnSampleCallback HRESULT CaptureEngineListener::OnSample(IMFSample* sample) { HRESULT hr = S_OK; if (this->observer_ && sample) { LONGLONG raw_time_stamp = 0; // Receives the presentation time, in 100-nanosecond units. sample->GetSampleTime(&raw_time_stamp); // Report time in microseconds. this->observer_->UpdateCaptureTime( static_cast<uint64_t>(raw_time_stamp / 10)); if (!this->observer_->IsReadyForSample()) { // No texture target available or not previewing, just return status. return hr; } ComPtr<IMFMediaBuffer> buffer; hr = sample->ConvertToContiguousBuffer(&buffer); // Draw the frame. if (SUCCEEDED(hr) && buffer) { DWORD max_length = 0; DWORD current_length = 0; uint8_t* data; if (SUCCEEDED(buffer->Lock(&data, &max_length, &current_length))) { this->observer_->UpdateBuffer(data, current_length); } hr = buffer->Unlock(); } } return hr; } } // namespace camera_windows
plugins/packages/camera/camera_windows/windows/capture_engine_listener.cpp/0
{ "file_path": "plugins/packages/camera/camera_windows/windows/capture_engine_listener.cpp", "repo_id": "plugins", "token_count": 858 }
1,226
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "texture_handler.h" #include <cassert> namespace camera_windows { TextureHandler::~TextureHandler() { // Texture might still be processed while destructor is called. // Lock mutex for safe destruction const std::lock_guard<std::mutex> lock(buffer_mutex_); if (texture_registrar_ && texture_id_ > 0) { texture_registrar_->UnregisterTexture(texture_id_); } texture_id_ = -1; texture_ = nullptr; texture_registrar_ = nullptr; } int64_t TextureHandler::RegisterTexture() { if (!texture_registrar_) { return -1; } // Create flutter desktop pixelbuffer texture; texture_ = std::make_unique<flutter::TextureVariant>(flutter::PixelBufferTexture( [this](size_t width, size_t height) -> const FlutterDesktopPixelBuffer* { return this->ConvertPixelBufferForFlutter(width, height); })); texture_id_ = texture_registrar_->RegisterTexture(texture_.get()); return texture_id_; } bool TextureHandler::UpdateBuffer(uint8_t* data, uint32_t data_length) { // Scoped lock guard. { const std::lock_guard<std::mutex> lock(buffer_mutex_); if (!TextureRegistered()) { return false; } if (source_buffer_.size() != data_length) { // Update source buffer size. source_buffer_.resize(data_length); } std::copy(data, data + data_length, source_buffer_.data()); } OnBufferUpdated(); return true; }; // Marks texture frame available after buffer is updated. void TextureHandler::OnBufferUpdated() { if (TextureRegistered()) { texture_registrar_->MarkTextureFrameAvailable(texture_id_); } } const FlutterDesktopPixelBuffer* TextureHandler::ConvertPixelBufferForFlutter( size_t target_width, size_t target_height) { // TODO: optimize image processing size by adjusting capture size // dynamically to match target_width and target_height. // If target size changes, create new media type for preview and set new // target framesize to MF_MT_FRAME_SIZE attribute. // Size should be kept inside requested resolution preset. // Update output media type with IMFCaptureSink2::SetOutputMediaType method // call and implement IMFCaptureEngineOnSampleCallback2::OnSynchronizedEvent // to detect size changes. // Lock buffer mutex to protect texture processing std::unique_lock<std::mutex> buffer_lock(buffer_mutex_); if (!TextureRegistered()) { return nullptr; } const uint32_t bytes_per_pixel = 4; const uint32_t pixels_total = preview_frame_width_ * preview_frame_height_; const uint32_t data_size = pixels_total * bytes_per_pixel; if (data_size > 0 && source_buffer_.size() == data_size) { if (dest_buffer_.size() != data_size) { dest_buffer_.resize(data_size); } // Map buffers to structs for easier conversion. MFVideoFormatRGB32Pixel* src = reinterpret_cast<MFVideoFormatRGB32Pixel*>(source_buffer_.data()); FlutterDesktopPixel* dst = reinterpret_cast<FlutterDesktopPixel*>(dest_buffer_.data()); for (uint32_t y = 0; y < preview_frame_height_; y++) { for (uint32_t x = 0; x < preview_frame_width_; x++) { uint32_t sp = (y * preview_frame_width_) + x; if (mirror_preview_) { // Software mirror mode. // IMFCapturePreviewSink also has the SetMirrorState setting, // but if enabled, samples will not be processed. // Calculates mirrored pixel position. uint32_t tp = (y * preview_frame_width_) + ((preview_frame_width_ - 1) - x); dst[tp].r = src[sp].r; dst[tp].g = src[sp].g; dst[tp].b = src[sp].b; dst[tp].a = 255; } else { dst[sp].r = src[sp].r; dst[sp].g = src[sp].g; dst[sp].b = src[sp].b; dst[sp].a = 255; } } } if (!flutter_desktop_pixel_buffer_) { flutter_desktop_pixel_buffer_ = std::make_unique<FlutterDesktopPixelBuffer>(); // Unlocks mutex after texture is processed. flutter_desktop_pixel_buffer_->release_callback = [](void* release_context) { auto mutex = reinterpret_cast<std::mutex*>(release_context); mutex->unlock(); }; } flutter_desktop_pixel_buffer_->buffer = dest_buffer_.data(); flutter_desktop_pixel_buffer_->width = preview_frame_width_; flutter_desktop_pixel_buffer_->height = preview_frame_height_; // Releases unique_lock and set mutex pointer for release context. flutter_desktop_pixel_buffer_->release_context = buffer_lock.release(); return flutter_desktop_pixel_buffer_.get(); } return nullptr; } } // namespace camera_windows
plugins/packages/camera/camera_windows/windows/texture_handler.cpp/0
{ "file_path": "plugins/packages/camera/camera_windows/windows/texture_handler.cpp", "repo_id": "plugins", "token_count": 1810 }
1,227
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package androidx.test.espresso.flutter.action; import static androidx.test.espresso.flutter.action.ActionUtil.loopUntilCompletion; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.util.concurrent.Futures.immediateFailedFuture; import static com.google.common.util.concurrent.Futures.immediateFuture; import android.graphics.Rect; import android.view.InputDevice; import android.view.MotionEvent; import android.view.View; import androidx.test.espresso.UiController; import androidx.test.espresso.ViewAction; import androidx.test.espresso.action.GeneralClickAction; import androidx.test.espresso.action.Press; import androidx.test.espresso.action.Tap; import androidx.test.espresso.flutter.api.FlutterTestingProtocol; import androidx.test.espresso.flutter.api.WidgetAction; import androidx.test.espresso.flutter.api.WidgetMatcher; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** A click on the given Flutter widget by issuing gesture events to the Android system. */ public final class ClickAction implements WidgetAction { private static final String GET_LOCAL_RECT_TASK_NAME = "ClickAction#getLocalRect"; private final ExecutorService executor; public ClickAction(@Nonnull ExecutorService executor) { this.executor = checkNotNull(executor); } @Override public ListenableFuture<Void> perform( @Nullable WidgetMatcher targetWidget, @Nonnull View flutterView, @Nonnull FlutterTestingProtocol flutterTestingProtocol, @Nonnull UiController androidUiController) { try { Future<Rect> widgetRectFuture = flutterTestingProtocol.getLocalRect(targetWidget); Rect widgetRectInDp = loopUntilCompletion( GET_LOCAL_RECT_TASK_NAME, androidUiController, widgetRectFuture, executor); WidgetCoordinatesCalculator coordinatesCalculator = new WidgetCoordinatesCalculator(widgetRectInDp); // Clicks at the center of the Flutter widget (with no visibility check), with all the default // settings of a native View's click action. ViewAction clickAction = new GeneralClickAction( Tap.SINGLE, coordinatesCalculator, Press.FINGER, InputDevice.SOURCE_UNKNOWN, MotionEvent.BUTTON_PRIMARY); clickAction.perform(androidUiController, flutterView); // Espresso will wait for the main thread to finish, so nothing else to wait for in the // testing thread. return immediateFuture(null); } catch (InterruptedException ie) { return immediateFailedFuture(ie); } catch (ExecutionException ee) { return immediateFailedFuture(ee.getCause()); } finally { androidUiController.loopMainThreadUntilIdle(); } } @Override public String toString() { return "click"; } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/ClickAction.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/ClickAction.java", "repo_id": "plugins", "token_count": 1083 }
1,228
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package androidx.test.espresso.flutter.assertion; import static androidx.test.espresso.flutter.matcher.FlutterMatchers.isFlutterView; import static com.google.common.base.Preconditions.checkNotNull; import android.view.View; import androidx.test.espresso.NoMatchingViewException; import androidx.test.espresso.ViewAssertion; import androidx.test.espresso.flutter.api.WidgetAssertion; import androidx.test.espresso.flutter.exception.InvalidFlutterViewException; import androidx.test.espresso.flutter.model.WidgetInfo; import androidx.test.espresso.util.HumanReadables; /** * A {@code ViewAssertion} which performs an action on the given Flutter view. * * <p>This class acts as a bridge to perform {@code WidgetAssertion} on a Flutter widget on the * given Flutter view. */ public final class FlutterViewAssertion implements ViewAssertion { private final WidgetAssertion assertion; private final WidgetInfo widgetInfo; public FlutterViewAssertion(WidgetAssertion assertion, WidgetInfo widgetInfo) { this.assertion = checkNotNull(assertion, "Widget assertion cannot be null."); this.widgetInfo = checkNotNull(widgetInfo, "The widget info to be asserted on cannot be null."); } @Override public void check(View view, NoMatchingViewException noViewFoundException) { if (view == null) { throw noViewFoundException; } else if (!isFlutterView().matches(view)) { throw new InvalidFlutterViewException( String.format("Not a valid Flutter view:%s", HumanReadables.describe(view))); } else { assertion.check(view, widgetInfo); } } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/assertion/FlutterViewAssertion.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/assertion/FlutterViewAssertion.java", "repo_id": "plugins", "token_count": 548 }
1,229
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package androidx.test.espresso.flutter.internal.protocol.impl; import static com.google.common.base.Preconditions.checkNotNull; import androidx.test.espresso.flutter.api.SyntheticAction; import com.google.common.base.Ascii; import com.google.gson.annotations.Expose; /** An action that retrieves the widget offset coordinates to the outer Flutter view. */ final class GetOffsetAction extends SyntheticAction { /** The position of the offset coordinates. */ public enum OffsetType { TOP_LEFT("topLeft"), TOP_RIGHT("topRight"), BOTTOM_LEFT("bottomLeft"), BOTTOM_RIGHT("bottomRight"); private OffsetType(String type) { this.type = type; } private final String type; @Override public String toString() { return type; } public static OffsetType fromString(String typeString) { if (typeString == null) { return null; } for (OffsetType offsetType : OffsetType.values()) { if (Ascii.equalsIgnoreCase(offsetType.type, typeString)) { return offsetType; } } return null; } } @Expose private final String offsetType; /** * Constructor. * * @param type the vertex position. */ public GetOffsetAction(OffsetType type) { super("get_offset"); this.offsetType = checkNotNull(type).toString(); } /** * Constructor. * * @param type the vertex position. * @param timeOutInMillis action's timeout setting in milliseconds. */ public GetOffsetAction(OffsetType type, long timeOutInMillis) { super("get_offset", timeOutInMillis); this.offsetType = checkNotNull(type).toString(); } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetAction.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetAction.java", "repo_id": "plugins", "token_count": 636 }
1,230
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package androidx.test.espresso.flutter.matcher; import static com.google.common.base.Preconditions.checkNotNull; import androidx.test.espresso.flutter.api.WidgetMatcher; import androidx.test.espresso.flutter.model.WidgetInfo; import com.google.gson.annotations.Expose; import javax.annotation.Nonnull; import org.hamcrest.Description; /** A matcher that matches a Flutter widget with a given runtime type. */ public final class WithTypeMatcher extends WidgetMatcher { @Expose private final String type; /** * Constructs the matcher with the given runtime type to be matched with. * * @param type the runtime type to be matched with. */ public WithTypeMatcher(@Nonnull String type) { super("ByType"); this.type = checkNotNull(type); } /** Returns the type string that shall be matched for the widget. */ public String getType() { return type; } @Override public String toString() { return "with runtime type: " + type; } @Override protected boolean matchesSafely(WidgetInfo widget) { return type.equals(widget.getType()); } @Override public void describeTo(Description description) { description.appendText("with runtime type: ").appendText(type); } }
plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/WithTypeMatcher.java/0
{ "file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/WithTypeMatcher.java", "repo_id": "plugins", "token_count": 420 }
1,231
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:file_selector/file_selector.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; /// Screen that shows an example of openFiles class OpenImagePage extends StatelessWidget { /// Default Constructor const OpenImagePage({Key? key}) : super(key: key); Future<void> _openImageFile(BuildContext context) async { // #docregion SingleOpen const XTypeGroup typeGroup = XTypeGroup( label: 'images', extensions: <String>['jpg', 'png'], ); final XFile? file = await openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]); // #enddocregion SingleOpen if (file == null) { // Operation was canceled by the user. return; } final String fileName = file.name; final String filePath = file.path; if (context.mounted) { await showDialog<void>( context: context, builder: (BuildContext context) => ImageDisplay(fileName, filePath), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Open an image'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( style: ElevatedButton.styleFrom( // TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724 // ignore: deprecated_member_use primary: Colors.blue, // ignore: deprecated_member_use onPrimary: Colors.white, ), child: const Text('Press to open an image file(png, jpg)'), onPressed: () => _openImageFile(context), ), ], ), ), ); } } /// Widget that displays a text file in a dialog class ImageDisplay extends StatelessWidget { /// Default Constructor const ImageDisplay(this.fileName, this.filePath, {Key? key}) : super(key: key); /// Image's name final String fileName; /// Image's path final String filePath; @override Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), // On web the filePath is a blob url // while on other platforms it is a system path. content: kIsWeb ? Image.network(filePath) : Image.file(File(filePath)), actions: <Widget>[ TextButton( child: const Text('Close'), onPressed: () { Navigator.pop(context); }, ), ], ); } }
plugins/packages/file_selector/file_selector/example/lib/open_image_page.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector/example/lib/open_image_page.dart", "repo_id": "plugins", "token_count": 1132 }
1,232
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
plugins/packages/file_selector/file_selector/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "plugins/packages/file_selector/file_selector/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "plugins", "token_count": 32 }
1,233
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import file_selector_ios; @import file_selector_ios.Test; @import XCTest; #import <OCMock/OCMock.h> @interface FileSelectorTests : XCTestCase @end @implementation FileSelectorTests - (void)testPickerPresents { FFSFileSelectorPlugin *plugin = [[FFSFileSelectorPlugin alloc] init]; UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[] inMode:UIDocumentPickerModeImport]; id mockPresentingVC = OCMClassMock([UIViewController class]); plugin.documentPickerViewControllerOverride = picker; plugin.presentingViewControllerOverride = mockPresentingVC; [plugin openFileSelectorWithConfig:[FFSFileSelectorConfig makeWithUtis:@[] allowMultiSelection:@NO] completion:^(NSArray<NSString *> *paths, FlutterError *error){ }]; XCTAssertEqualObjects(picker.delegate, plugin); OCMVerify(times(1), [mockPresentingVC presentViewController:picker animated:[OCMArg any] completion:[OCMArg any]]); } - (void)testReturnsPickedFiles { FFSFileSelectorPlugin *plugin = [[FFSFileSelectorPlugin alloc] init]; XCTestExpectation *completionWasCalled = [self expectationWithDescription:@"completion"]; UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[] inMode:UIDocumentPickerModeImport]; plugin.documentPickerViewControllerOverride = picker; [plugin openFileSelectorWithConfig:[FFSFileSelectorConfig makeWithUtis:@[] allowMultiSelection:@YES] completion:^(NSArray<NSString *> *paths, FlutterError *error) { NSArray *expectedPaths = @[ @"/file1.txt", @"/file2.txt" ]; XCTAssertEqualObjects(paths, expectedPaths); [completionWasCalled fulfill]; }]; [plugin documentPicker:picker didPickDocumentsAtURLs:@[ [NSURL URLWithString:@"file:///file1.txt"], [NSURL URLWithString:@"file:///file2.txt"] ]]; [self waitForExpectationsWithTimeout:1.0 handler:nil]; } - (void)testReturnsPickedFileLegacy { // Tests that it handles the pre iOS 11 UIDocumentPickerDelegate method. FFSFileSelectorPlugin *plugin = [[FFSFileSelectorPlugin alloc] init]; XCTestExpectation *completionWasCalled = [self expectationWithDescription:@"completion"]; UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[] inMode:UIDocumentPickerModeImport]; plugin.documentPickerViewControllerOverride = picker; [plugin openFileSelectorWithConfig:[FFSFileSelectorConfig makeWithUtis:@[] allowMultiSelection:@NO] completion:^(NSArray<NSString *> *paths, FlutterError *error) { NSArray *expectedPaths = @[ @"/file1.txt" ]; XCTAssertEqualObjects(paths, expectedPaths); [completionWasCalled fulfill]; }]; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" [plugin documentPicker:picker didPickDocumentAtURL:[NSURL URLWithString:@"file:///file1.txt"]]; #pragma GCC diagnostic pop [self waitForExpectationsWithTimeout:1.0 handler:nil]; } - (void)testCancellingPickerReturnsNil { FFSFileSelectorPlugin *plugin = [[FFSFileSelectorPlugin alloc] init]; UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[] inMode:UIDocumentPickerModeImport]; plugin.documentPickerViewControllerOverride = picker; XCTestExpectation *completionWasCalled = [self expectationWithDescription:@"completion"]; [plugin openFileSelectorWithConfig:[FFSFileSelectorConfig makeWithUtis:@[] allowMultiSelection:@NO] completion:^(NSArray<NSString *> *paths, FlutterError *error) { XCTAssertEqual(paths.count, 0); [completionWasCalled fulfill]; }]; [plugin documentPickerWasCancelled:picker]; [self waitForExpectationsWithTimeout:1.0 handler:nil]; } @end
plugins/packages/file_selector/file_selector_ios/example/ios/RunnerTests/FileSelectorTests.m/0
{ "file_path": "plugins/packages/file_selector/file_selector_ios/example/ios/RunnerTests/FileSelectorTests.m", "repo_id": "plugins", "token_count": 2233 }
1,234
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v3.2.5), do not edit directly. // See also: https://pub.dev/packages/pigeon #import "messages.g.h" #import <Flutter/Flutter.h> #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif static NSDictionary<NSString *, id> *wrapResult(id result, FlutterError *error) { NSDictionary *errorDict = (NSDictionary *)[NSNull null]; if (error) { errorDict = @{ @"code" : (error.code ?: [NSNull null]), @"message" : (error.message ?: [NSNull null]), @"details" : (error.details ?: [NSNull null]), }; } return @{ @"result" : (result ?: [NSNull null]), @"error" : errorDict, }; } static id GetNullableObject(NSDictionary *dict, id key) { id result = dict[key]; return (result == [NSNull null]) ? nil : result; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; return (result == [NSNull null]) ? nil : result; } @interface FFSFileSelectorConfig () + (FFSFileSelectorConfig *)fromMap:(NSDictionary *)dict; + (nullable FFSFileSelectorConfig *)nullableFromMap:(NSDictionary *)dict; - (NSDictionary *)toMap; @end @implementation FFSFileSelectorConfig + (instancetype)makeWithUtis:(NSArray<NSString *> *)utis allowMultiSelection:(NSNumber *)allowMultiSelection { FFSFileSelectorConfig *pigeonResult = [[FFSFileSelectorConfig alloc] init]; pigeonResult.utis = utis; pigeonResult.allowMultiSelection = allowMultiSelection; return pigeonResult; } + (FFSFileSelectorConfig *)fromMap:(NSDictionary *)dict { FFSFileSelectorConfig *pigeonResult = [[FFSFileSelectorConfig alloc] init]; pigeonResult.utis = GetNullableObject(dict, @"utis"); NSAssert(pigeonResult.utis != nil, @""); pigeonResult.allowMultiSelection = GetNullableObject(dict, @"allowMultiSelection"); NSAssert(pigeonResult.allowMultiSelection != nil, @""); return pigeonResult; } + (nullable FFSFileSelectorConfig *)nullableFromMap:(NSDictionary *)dict { return (dict) ? [FFSFileSelectorConfig fromMap:dict] : nil; } - (NSDictionary *)toMap { return @{ @"utis" : (self.utis ?: [NSNull null]), @"allowMultiSelection" : (self.allowMultiSelection ?: [NSNull null]), }; } @end @interface FFSFileSelectorApiCodecReader : FlutterStandardReader @end @implementation FFSFileSelectorApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [FFSFileSelectorConfig fromMap:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface FFSFileSelectorApiCodecWriter : FlutterStandardWriter @end @implementation FFSFileSelectorApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[FFSFileSelectorConfig class]]) { [self writeByte:128]; [self writeValue:[value toMap]]; } else { [super writeValue:value]; } } @end @interface FFSFileSelectorApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation FFSFileSelectorApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[FFSFileSelectorApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[FFSFileSelectorApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *FFSFileSelectorApiGetCodec() { static dispatch_once_t sPred = 0; static FlutterStandardMessageCodec *sSharedObject = nil; dispatch_once(&sPred, ^{ FFSFileSelectorApiCodecReaderWriter *readerWriter = [[FFSFileSelectorApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } void FFSFileSelectorApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FFSFileSelectorApi> *api) { { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.FileSelectorApi.openFile" binaryMessenger:binaryMessenger codec:FFSFileSelectorApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(openFileSelectorWithConfig:completion:)], @"FFSFileSelectorApi api (%@) doesn't respond to " @"@selector(openFileSelectorWithConfig:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; FFSFileSelectorConfig *arg_config = GetNullableObjectAtIndex(args, 0); [api openFileSelectorWithConfig:arg_config completion:^(NSArray<NSString *> *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } }
plugins/packages/file_selector/file_selector_ios/ios/Classes/messages.g.m/0
{ "file_path": "plugins/packages/file_selector/file_selector_ios/ios/Classes/messages.g.m", "repo_id": "plugins", "token_count": 1945 }
1,235
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
plugins/packages/file_selector/file_selector_macos/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "plugins/packages/file_selector/file_selector_macos/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "plugins", "token_count": 32 }
1,236
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( input: 'pigeons/messages.dart', swiftOut: 'macos/Classes/messages.g.swift', dartOut: 'lib/src/messages.g.dart', dartTestOut: 'test/messages_test.g.dart', copyrightHeader: 'pigeons/copyright.txt', )) /// A Pigeon representation of the macOS portion of an `XTypeGroup`. class AllowedTypes { const AllowedTypes({ this.extensions = const <String>[], this.mimeTypes = const <String>[], this.utis = const <String>[], }); // TODO(stuartmorgan): Declare these as non-nullable generics once // https://github.com/flutter/flutter/issues/97848 is fixed. In practice, // the values will never be null, and the native implementation assumes that. final List<String?> extensions; final List<String?> mimeTypes; final List<String?> utis; } /// Options for save panels. /// /// These correspond to NSSavePanel properties (which are, by extension /// NSOpenPanel properties as well). class SavePanelOptions { const SavePanelOptions({ this.allowedFileTypes, this.directoryPath, this.nameFieldStringValue, this.prompt, }); final AllowedTypes? allowedFileTypes; final String? directoryPath; final String? nameFieldStringValue; final String? prompt; } /// Options for open panels. /// /// These correspond to NSOpenPanel properties. class OpenPanelOptions extends SavePanelOptions { const OpenPanelOptions({ this.allowsMultipleSelection = false, this.canChooseDirectories = false, this.canChooseFiles = true, this.baseOptions = const SavePanelOptions(), }); final bool allowsMultipleSelection; final bool canChooseDirectories; final bool canChooseFiles; // NSOpenPanel inherits from NSSavePanel, so shares all of its options. // Ideally this would be done with inheritance rather than composition, but // Pigeon doesn't currently support data class inheritance: // https://github.com/flutter/flutter/issues/117819. final SavePanelOptions baseOptions; } @HostApi(dartHostTestHandler: 'TestFileSelectorApi') abstract class FileSelectorApi { /// Shows an open panel with the given [options], returning the list of /// selected paths. /// /// An empty list corresponds to a cancelled selection. // TODO(stuartmorgan): Declare this return as a non-nullable generic once // https://github.com/flutter/flutter/issues/97848 is fixed. In practice, // the values will never be null, and the calling code assumes that. @async List<String?> displayOpenPanel(OpenPanelOptions options); /// Shows a save panel with the given [options], returning the selected path. /// /// A null return corresponds to a cancelled save. @async String? displaySavePanel(SavePanelOptions options); }
plugins/packages/file_selector/file_selector_macos/pigeons/messages.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector_macos/pigeons/messages.dart", "repo_id": "plugins", "token_count": 873 }
1,237
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:file_selector_platform_interface/src/method_channel/method_channel_file_selector.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { // Store the initial instance before any tests change it. final FileSelectorPlatform initialInstance = FileSelectorPlatform.instance; group('$FileSelectorPlatform', () { test('$MethodChannelFileSelector() is the default instance', () { expect(initialInstance, isInstanceOf<MethodChannelFileSelector>()); }); test('Can be extended', () { FileSelectorPlatform.instance = ExtendsFileSelectorPlatform(); }); }); group('#GetDirectoryPaths', () { test('Should throw unimplemented exception', () async { final FileSelectorPlatform fileSelector = ExtendsFileSelectorPlatform(); await expectLater(() async { return fileSelector.getDirectoryPaths(); }, throwsA(isA<UnimplementedError>())); }); }); } class ExtendsFileSelectorPlatform extends FileSelectorPlatform {}
plugins/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart", "repo_id": "plugins", "token_count": 380 }
1,238
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:html'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; /// Class to manipulate the DOM with the intention of reading files from it. class DomHelper { /// Default constructor, initializes the container DOM element. DomHelper() { final Element body = querySelector('body')!; body.children.add(_container); } final Element _container = Element.tag('file-selector'); /// Sets the <input /> attributes and waits for a file to be selected. Future<List<XFile>> getFiles({ String accept = '', bool multiple = false, @visibleForTesting FileUploadInputElement? input, }) { final Completer<List<XFile>> completer = Completer<List<XFile>>(); final FileUploadInputElement inputElement = input ?? FileUploadInputElement(); _container.children.add( inputElement ..accept = accept ..multiple = multiple, ); inputElement.onChange.first.then((_) { final List<XFile> files = inputElement.files!.map(_convertFileToXFile).toList(); inputElement.remove(); completer.complete(files); }); inputElement.onError.first.then((Event event) { final ErrorEvent error = event as ErrorEvent; final PlatformException platformException = PlatformException( code: error.type, message: error.message, ); inputElement.remove(); completer.completeError(platformException); }); inputElement.click(); return completer.future; } XFile _convertFileToXFile(File file) => XFile( Url.createObjectUrl(file), name: file.name, length: file.size, lastModified: DateTime.fromMillisecondsSinceEpoch( file.lastModified ?? DateTime.now().millisecondsSinceEpoch), ); }
plugins/packages/file_selector/file_selector_web/lib/src/dom_helper.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector_web/lib/src/dom_helper.dart", "repo_id": "plugins", "token_count": 725 }
1,239
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "file_dialog_controller.h" #include <comdef.h> #include <comip.h> #include <windows.h> _COM_SMARTPTR_TYPEDEF(IFileOpenDialog, IID_IFileOpenDialog); namespace file_selector_windows { FileDialogController::FileDialogController(IFileDialog* dialog) : dialog_(dialog) {} FileDialogController::~FileDialogController() {} HRESULT FileDialogController::SetFolder(IShellItem* folder) { return dialog_->SetFolder(folder); } HRESULT FileDialogController::SetFileName(const wchar_t* name) { return dialog_->SetFileName(name); } HRESULT FileDialogController::SetFileTypes(UINT count, COMDLG_FILTERSPEC* filters) { return dialog_->SetFileTypes(count, filters); } HRESULT FileDialogController::SetOkButtonLabel(const wchar_t* text) { return dialog_->SetOkButtonLabel(text); } HRESULT FileDialogController::GetOptions( FILEOPENDIALOGOPTIONS* out_options) const { return dialog_->GetOptions(out_options); } HRESULT FileDialogController::SetOptions(FILEOPENDIALOGOPTIONS options) { return dialog_->SetOptions(options); } HRESULT FileDialogController::Show(HWND parent) { return dialog_->Show(parent); } HRESULT FileDialogController::GetResult(IShellItem** out_item) const { return dialog_->GetResult(out_item); } HRESULT FileDialogController::GetResults(IShellItemArray** out_items) const { IFileOpenDialogPtr open_dialog; HRESULT result = dialog_->QueryInterface(IID_PPV_ARGS(&open_dialog)); if (!SUCCEEDED(result)) { return result; } result = open_dialog->GetResults(out_items); return result; } FileDialogControllerFactory::~FileDialogControllerFactory() {} } // namespace file_selector_windows
plugins/packages/file_selector/file_selector_windows/windows/file_dialog_controller.cpp/0
{ "file_path": "plugins/packages/file_selector/file_selector_windows/windows/file_dialog_controller.cpp", "repo_id": "plugins", "token_count": 634 }
1,240
org.gradle.jvmargs=-Xmx4G android.enableR8=true android.useAndroidX=true android.enableJetifier=true
plugins/packages/flutter_plugin_android_lifecycle/example/android/gradle.properties/0
{ "file_path": "plugins/packages/flutter_plugin_android_lifecycle/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,241
name: google_maps_flutter description: A Flutter plugin for integrating Google Maps in iOS and Android applications. repository: https://github.com/flutter/plugins/tree/main/packages/google_maps_flutter/google_maps_flutter issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%22 version: 2.2.3 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: platforms: android: default_package: google_maps_flutter_android ios: default_package: google_maps_flutter_ios dependencies: flutter: sdk: flutter google_maps_flutter_android: ^2.1.10 google_maps_flutter_ios: ^2.1.10 google_maps_flutter_platform_interface: ^2.2.1 dev_dependencies: flutter_test: sdk: flutter plugin_platform_interface: ^2.0.0 stream_transform: ^2.0.0
plugins/packages/google_maps_flutter/google_maps_flutter/pubspec.yaml/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/pubspec.yaml", "repo_id": "plugins", "token_count": 348 }
1,242
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import google_maps_flutter_ios; @import google_maps_flutter_ios.Test; @import XCTest; @import GoogleMaps; #import <OCMock/OCMock.h> #import "PartiallyMockedMapView.h" @interface FLTGoogleMapFactory (Test) @property(strong, nonatomic, readonly) id<NSObject> sharedMapServices; @end @interface GoogleMapsTests : XCTestCase @end @implementation GoogleMapsTests - (void)testPlugin { FLTGoogleMapsPlugin *plugin = [[FLTGoogleMapsPlugin alloc] init]; XCTAssertNotNil(plugin); } - (void)testFrameObserver { id registrar = OCMProtocolMock(@protocol(FlutterPluginRegistrar)); CGRect frame = CGRectMake(0, 0, 100, 100); PartiallyMockedMapView *mapView = [[PartiallyMockedMapView alloc] initWithFrame:frame camera:[[GMSCameraPosition alloc] initWithLatitude:0 longitude:0 zoom:0]]; FLTGoogleMapController *controller = [[FLTGoogleMapController alloc] initWithMapView:mapView viewIdentifier:0 arguments:nil registrar:registrar]; for (NSInteger i = 0; i < 10; ++i) { [controller view]; } XCTAssertEqual(mapView.frameObserverCount, 1); mapView.frame = frame; XCTAssertEqual(mapView.frameObserverCount, 0); } - (void)testMapsServiceSync { id registrar = OCMProtocolMock(@protocol(FlutterPluginRegistrar)); FLTGoogleMapFactory *factory1 = [[FLTGoogleMapFactory alloc] initWithRegistrar:registrar]; XCTAssertNotNil(factory1.sharedMapServices); FLTGoogleMapFactory *factory2 = [[FLTGoogleMapFactory alloc] initWithRegistrar:registrar]; // Test pointer equality, should be same retained singleton +[GMSServices sharedServices] object. // Retaining the opaque object should be enough to avoid multiple internal initializations, // but don't test the internals of the GoogleMaps API. Assume that it does what is documented. // https://developers.google.com/maps/documentation/ios-sdk/reference/interface_g_m_s_services#a436e03c32b1c0be74e072310a7158831 XCTAssertEqual(factory1.sharedMapServices, factory2.sharedMapServices); } @end
plugins/packages/google_maps_flutter/google_maps_flutter_ios/example/ios/RunnerTests/GoogleMapsTests.m/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/example/ios/RunnerTests/GoogleMapsTests.m", "repo_id": "plugins", "token_count": 946 }
1,243
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FLTGoogleMapsPlugin.h" #pragma mark - GoogleMaps plugin implementation @implementation FLTGoogleMapsPlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { FLTGoogleMapFactory *googleMapFactory = [[FLTGoogleMapFactory alloc] initWithRegistrar:registrar]; [registrar registerViewFactory:googleMapFactory withId:@"plugins.flutter.dev/google_maps_ios" gestureRecognizersBlockingPolicy: FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded]; } @end
plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapsPlugin.m/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapsPlugin.m", "repo_id": "plugins", "token_count": 247 }
1,244
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart' show immutable; import 'types.dart'; /// Cap that can be applied at the start or end vertex of a [Polyline]. @immutable class Cap { const Cap._(this._json); /// Cap that is squared off exactly at the start or end vertex of a [Polyline] /// with solid stroke pattern, equivalent to having no additional cap beyond /// the start or end vertex. /// /// This is the default cap type at start and end vertices of Polylines with /// solid stroke pattern. static const Cap buttCap = Cap._(<Object>['buttCap']); /// Cap that is a semicircle with radius equal to half the stroke width, /// centered at the start or end vertex of a [Polyline] with solid stroke /// pattern. static const Cap roundCap = Cap._(<Object>['roundCap']); /// Cap that is squared off after extending half the stroke width beyond the /// start or end vertex of a [Polyline] with solid stroke pattern. static const Cap squareCap = Cap._(<Object>['squareCap']); /// Constructs a new CustomCap with a bitmap overlay centered at the start or /// end vertex of a [Polyline], orientated according to the direction of the line's /// first or last edge and scaled with respect to the line's stroke width. /// /// CustomCap can be applied to [Polyline] with any stroke pattern. /// /// [bitmapDescriptor] must not be null. /// /// [refWidth] is the reference stroke width (in pixels) - the stroke width for which /// the cap bitmap at its native dimension is designed. Must be positive. Default value /// is 10 pixels. static Cap customCapFromBitmap( BitmapDescriptor bitmapDescriptor, { double refWidth = 10, }) { assert(bitmapDescriptor != null); assert(refWidth > 0.0); return Cap._(<Object>['customCap', bitmapDescriptor.toJson(), refWidth]); } final Object _json; /// Converts this object to something serializable in JSON. Object toJson() => _json; }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cap.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cap.dart", "repo_id": "plugins", "token_count": 594 }
1,245
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'types.dart'; /// [Polyline] update events to be applied to the [GoogleMap]. /// /// Used in [GoogleMapController] when the map is updated. // (Do not re-export) class PolylineUpdates extends MapsObjectUpdates<Polyline> { /// Computes [PolylineUpdates] given previous and current [Polyline]s. PolylineUpdates.from(Set<Polyline> previous, Set<Polyline> current) : super.from(previous, current, objectName: 'polyline'); /// Set of Polylines to be added in this update. Set<Polyline> get polylinesToAdd => objectsToAdd; /// Set of PolylineIds to be removed in this update. Set<PolylineId> get polylineIdsToRemove => objectIdsToRemove.cast<PolylineId>(); /// Set of Polylines to be changed in this update. Set<Polyline> get polylinesToChange => objectsToChange; }
plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline_updates.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline_updates.dart", "repo_id": "plugins", "token_count": 292 }
1,246
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:async/async.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$MethodChannelGoogleMapsFlutter', () { late List<String> log; setUp(() async { log = <String>[]; }); /// Initializes a map with the given ID and canned responses, logging all /// calls to [log]. void configureMockMap( MethodChannelGoogleMapsFlutter maps, { required int mapId, required Future<dynamic>? Function(MethodCall call) handler, }) { final MethodChannel channel = maps.ensureChannelInitialized(mapId); _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler( channel, (MethodCall methodCall) { log.add(methodCall.method); return handler(methodCall); }, ); } Future<void> sendPlatformMessage( int mapId, String method, Map<dynamic, dynamic> data) async { final ByteData byteData = const StandardMethodCodec() .encodeMethodCall(MethodCall(method, data)); await _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .handlePlatformMessage('plugins.flutter.io/google_maps_$mapId', byteData, (ByteData? data) {}); } // Calls each method that uses invokeMethod with a return type other than // void to ensure that the casting/nullability handling succeeds. // // TODO(stuartmorgan): Remove this once there is real test coverage of // each method, since that would cover this issue. test('non-void invokeMethods handle types correctly', () async { const int mapId = 0; final MethodChannelGoogleMapsFlutter maps = MethodChannelGoogleMapsFlutter(); configureMockMap(maps, mapId: mapId, handler: (MethodCall methodCall) async { switch (methodCall.method) { case 'map#getLatLng': return <dynamic>[1.0, 2.0]; case 'markers#isInfoWindowShown': return true; case 'map#getZoomLevel': return 2.5; case 'map#takeSnapshot': return null; } }); await maps.getLatLng(const ScreenCoordinate(x: 0, y: 0), mapId: mapId); await maps.isMarkerInfoWindowShown(const MarkerId(''), mapId: mapId); await maps.getZoomLevel(mapId: mapId); await maps.takeSnapshot(mapId: mapId); // Check that all the invokeMethod calls happened. expect(log, <String>[ 'map#getLatLng', 'markers#isInfoWindowShown', 'map#getZoomLevel', 'map#takeSnapshot', ]); }); test('markers send drag event to correct streams', () async { const int mapId = 1; final Map<dynamic, dynamic> jsonMarkerDragStartEvent = <dynamic, dynamic>{ 'mapId': mapId, 'markerId': 'drag-start-marker', 'position': <double>[1.0, 1.0] }; final Map<dynamic, dynamic> jsonMarkerDragEvent = <dynamic, dynamic>{ 'mapId': mapId, 'markerId': 'drag-marker', 'position': <double>[1.0, 1.0] }; final Map<dynamic, dynamic> jsonMarkerDragEndEvent = <dynamic, dynamic>{ 'mapId': mapId, 'markerId': 'drag-end-marker', 'position': <double>[1.0, 1.0] }; final MethodChannelGoogleMapsFlutter maps = MethodChannelGoogleMapsFlutter(); maps.ensureChannelInitialized(mapId); final StreamQueue<MarkerDragStartEvent> markerDragStartStream = StreamQueue<MarkerDragStartEvent>( maps.onMarkerDragStart(mapId: mapId)); final StreamQueue<MarkerDragEvent> markerDragStream = StreamQueue<MarkerDragEvent>(maps.onMarkerDrag(mapId: mapId)); final StreamQueue<MarkerDragEndEvent> markerDragEndStream = StreamQueue<MarkerDragEndEvent>(maps.onMarkerDragEnd(mapId: mapId)); await sendPlatformMessage( mapId, 'marker#onDragStart', jsonMarkerDragStartEvent); await sendPlatformMessage(mapId, 'marker#onDrag', jsonMarkerDragEvent); await sendPlatformMessage( mapId, 'marker#onDragEnd', jsonMarkerDragEndEvent); expect((await markerDragStartStream.next).value.value, equals('drag-start-marker')); expect((await markerDragStream.next).value.value, equals('drag-marker')); expect((await markerDragEndStream.next).value.value, equals('drag-end-marker')); }); }); } /// 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_platform_interface/test/method_channel/method_channel_google_maps_flutter_test.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/method_channel/method_channel_google_maps_flutter_test.dart", "repo_id": "plugins", "token_count": 2022 }
1,247
## NEXT * Updates minimum Flutter version to 3.0. ## 0.4.0+5 * Updates code for stricter lint checks. ## 0.4.0+4 * Updates code for stricter lint checks. * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 0.4.0+3 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. ## 0.4.0+2 * Updates conversion of `BitmapDescriptor.fromBytes` marker icons to support the new `size` parameter. Issue [#73789](https://github.com/flutter/flutter/issues/73789). * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 0.4.0+1 * Updates `README.md` to describe a hit-testing issue when Flutter widgets are overlaid on top of the Map widget. ## 0.4.0 * Implements the new platform interface versions of `buildView` and `updateOptions` with structured option types. * **BREAKING CHANGE**: No longer implements the unstructured option dictionary versions of those methods, so this version can only be used with `google_maps_flutter` 2.1.8 or later. * Adds `const` constructor parameters in example tests. ## 0.3.3 * Removes custom `analysis_options.yaml` (and fixes code to comply with newest rules). * Updates `package:google_maps` dependency to latest (`^6.1.0`). * Ensures that `convert.dart` sanitizes user-created HTML before passing it to the Maps JS SDK with `sanitizeHtml` from `package:sanitize_html`. [More info](https://pub.dev/documentation/sanitize_html/latest/sanitize_html/sanitizeHtml.html). ## 0.3.2+2 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.3.2+1 * Removes dependency on `meta`. ## 0.3.2 * Add `onDragStart` and `onDrag` to `Marker` ## 0.3.1 * Fix the `getScreenCoordinate(LatLng)` method. [#80710](https://github.com/flutter/flutter/issues/80710) * Wait until the map tiles have loaded before calling `onPlatformViewCreated`, so the returned controller is 100% functional (has bounds, a projection, etc...) * Use zIndex property when initializing Circle objects. [#89374](https://github.com/flutter/flutter/issues/89374) ## 0.3.0+4 * Add `implements` to pubspec. ## 0.3.0+3 * Update the `README.md` usage instructions to not be tied to explicit package versions. ## 0.3.0+2 * Document `liteModeEnabled` is not available on the web. [#83737](https://github.com/flutter/flutter/issues/83737). ## 0.3.0+1 * Change sizing code of `GoogleMap` widget's `HtmlElementView` so it works well when slotted. ## 0.3.0 * Migrate package to null-safety. * **Breaking changes:** * The property `icon` of a `Marker` cannot be `null`. Defaults to `BitmapDescriptor.defaultMarker` * The property `initialCameraPosition` of a `GoogleMapController` can't be `null`. It is also marked as `required`. * The parameter `creationId` of the `buildView` method cannot be `null` (this should be handled internally for users of the plugin) * Most of the Controller methods can't be called after `remove`/`dispose`. Calling these methods now will throw an Assertion error. Before it'd be a no-op, or a null-pointer exception. ## 0.2.1 * Move integration tests to `example`. * Tweak pubspec dependencies for main package. ## 0.2.0 * Make this plugin compatible with the rest of null-safe plugins. * Noop tile overlays methods, so they don't crash on web. **NOTE**: This plugin is **not** null-safe yet! ## 0.1.2 * Update min Flutter SDK to 1.20.0. ## 0.1.1 * Auto-reverse holes if they're the same direction as the polygon. [Issue](https://github.com/flutter/flutter/issues/74096). ## 0.1.0+10 * Update `package:google_maps_flutter_platform_interface` to `^1.1.0`. * Add support for Polygon Holes. ## 0.1.0+9 * Update Flutter SDK constraint. ## 0.1.0+8 * Update `package:google_maps_flutter_platform_interface` to `^1.0.5`. * Add support for `fromBitmap` BitmapDescriptors. [Issue](https://github.com/flutter/flutter/issues/66622). ## 0.1.0+7 * Substitute `undefined_prefixed_name: ignore` analyzer setting by a `dart:ui` shim with conditional exports. [Issue](https://github.com/flutter/flutter/issues/69309). ## 0.1.0+6 * Ensure a single `InfoWindow` is shown at a time. [Issue](https://github.com/flutter/flutter/issues/67380). ## 0.1.0+5 * Update `package:google_maps` to `^3.4.5`. * Fix `GoogleMapController.getLatLng()`. [Issue](https://github.com/flutter/flutter/issues/67606). * Make `InfoWindow` contents clickable so `onTap` works as advertised. [Issue](https://github.com/flutter/flutter/issues/67289). * Fix `InfoWindow` snippets when converting initial markers. [Issue](https://github.com/flutter/flutter/issues/67854). ## 0.1.0+4 * Update `package:sanitize_html` to `^1.4.1` to prevent [a crash](https://github.com/flutter/flutter/issues/67854) when InfoWindow title/snippet have links. ## 0.1.0+3 * Fix crash when converting initial polylines and polygons. [Issue](https://github.com/flutter/flutter/issues/65152). * Correctly convert Colors when rendering polylines, polygons and circles. [Issue](https://github.com/flutter/flutter/issues/67032). ## 0.1.0+2 * Fix crash when converting Markers with icon explicitly set to null. [Issue](https://github.com/flutter/flutter/issues/64938). ## 0.1.0+1 * Port e2e tests to use the new integration_test package. ## 0.1.0 * First open-source version
plugins/packages/google_maps_flutter/google_maps_flutter_web/CHANGELOG.md/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/CHANGELOG.md", "repo_id": "plugins", "token_count": 1792 }
1,248
name: google_maps_flutter_web_integration_tests publish_to: none # Tests require flutter beta or greater to run. environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" dependencies: flutter: sdk: flutter google_maps_flutter_platform_interface: ^2.2.1 google_maps_flutter_web: path: ../ dev_dependencies: build_runner: ^2.1.1 flutter_driver: sdk: flutter flutter_test: sdk: flutter google_maps: ^6.1.0 google_maps_flutter: # Used for projection_test.dart path: ../../google_maps_flutter http: ^0.13.0 integration_test: sdk: flutter mockito: ^5.3.2
plugins/packages/google_maps_flutter/google_maps_flutter_web/example/pubspec.yaml/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/pubspec.yaml", "repo_id": "plugins", "token_count": 262 }
1,249
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. part of google_maps_flutter_web; /// This class manages a set of [PolylinesController]s associated to a [GoogleMapController]. class PolylinesController extends GeometryController { /// Initializes the cache. The [StreamController] comes from the [GoogleMapController], and is shared with other controllers. PolylinesController({ required StreamController<MapEvent<Object?>> stream, }) : _streamController = stream, _polylineIdToController = <PolylineId, PolylineController>{}; // A cache of [PolylineController]s indexed by their [PolylineId]. final Map<PolylineId, PolylineController> _polylineIdToController; // The stream over which polylines broadcast their events final StreamController<MapEvent<Object?>> _streamController; /// Returns the cache of [PolylineContrller]s. Test only. @visibleForTesting Map<PolylineId, PolylineController> get lines => _polylineIdToController; /// Adds a set of [Polyline] objects to the cache. /// /// Wraps each line into its corresponding [PolylineController]. void addPolylines(Set<Polyline> polylinesToAdd) { polylinesToAdd.forEach(_addPolyline); } void _addPolyline(Polyline polyline) { if (polyline == null) { return; } final gmaps.PolylineOptions polylineOptions = _polylineOptionsFromPolyline(googleMap, polyline); final gmaps.Polyline gmPolyline = gmaps.Polyline(polylineOptions) ..map = googleMap; final PolylineController controller = PolylineController( polyline: gmPolyline, consumeTapEvents: polyline.consumeTapEvents, onTap: () { _onPolylineTap(polyline.polylineId); }); _polylineIdToController[polyline.polylineId] = controller; } /// Updates a set of [Polyline] objects with new options. void changePolylines(Set<Polyline> polylinesToChange) { polylinesToChange.forEach(_changePolyline); } void _changePolyline(Polyline polyline) { final PolylineController? polylineController = _polylineIdToController[polyline.polylineId]; polylineController ?.update(_polylineOptionsFromPolyline(googleMap, polyline)); } /// Removes a set of [PolylineId]s from the cache. void removePolylines(Set<PolylineId> polylineIdsToRemove) { polylineIdsToRemove.forEach(_removePolyline); } // Removes a polyline and its controller by its [PolylineId]. void _removePolyline(PolylineId polylineId) { final PolylineController? polylineController = _polylineIdToController[polylineId]; polylineController?.remove(); _polylineIdToController.remove(polylineId); } // Handle internal events bool _onPolylineTap(PolylineId polylineId) { // Have you ended here on your debugging? Is this wrong? // Comment here: https://github.com/flutter/flutter/issues/64084 _streamController.add(PolylineTapEvent(mapId, polylineId)); return _polylineIdToController[polylineId]?.consumeTapEvents ?? false; } }
plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polylines.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polylines.dart", "repo_id": "plugins", "token_count": 1002 }
1,250
org.gradle.jvmargs=-Xmx4G android.enableR8=true android.useAndroidX=true
plugins/packages/google_sign_in/google_sign_in/example/android/gradle.properties/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in/example/android/gradle.properties", "repo_id": "plugins", "token_count": 30 }
1,251
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:google_sign_in/src/fife.dart'; void main() { group('addSizeDirectiveToUrl', () { const double size = 20; group('Old style URLs', () { const String base = 'https://lh3.googleusercontent.com/-ukEAtRyRhw8/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rfhID9XACtdb9q_xK43VSXQvBV11Q.CMID'; const String expected = '$base/s20-c/photo.jpg'; test('with directives, sets size', () { const String url = '$base/s64-c/photo.jpg'; expect(addSizeDirectiveToUrl(url, size), expected); }); test('no directives, sets size and crop', () { const String url = '$base/photo.jpg'; expect(addSizeDirectiveToUrl(url, size), expected); }); test('no crop, sets size and crop', () { const String url = '$base/s64/photo.jpg'; expect(addSizeDirectiveToUrl(url, size), expected); }); }); group('New style URLs', () { const String base = 'https://lh3.googleusercontent.com/a-/AAuE7mC0Lh4F4uDtEaY7hpe-GIsbDpqfMZ3_2UhBQ8Qk'; const String expected = '$base=c-s20'; test('with directives, sets size', () { const String url = '$base=s120-c'; expect(addSizeDirectiveToUrl(url, size), expected); }); test('no directives, sets size and crop', () { const String url = base; expect(addSizeDirectiveToUrl(url, size), expected); }); test('no directives, but with an equals sign, sets size and crop', () { const String url = '$base='; expect(addSizeDirectiveToUrl(url, size), expected); }); test('no crop, adds crop', () { const String url = '$base=s120'; expect(addSizeDirectiveToUrl(url, size), expected); }); test('many directives, sets size and crop, preserves other directives', () { const String url = '$base=s120-c-fSoften=1,50,0'; const String expected = '$base=c-fSoften=1,50,0-s20'; expect(addSizeDirectiveToUrl(url, size), expected); }); }); }); }
plugins/packages/google_sign_in/google_sign_in/test/fife_test.dart/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in/test/fife_test.dart", "repo_id": "plugins", "token_count": 940 }
1,252
# google\_sign\_in\_ios The iOS 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_ios/README.md/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_ios/README.md", "repo_id": "plugins", "token_count": 128 }
1,253
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'google_sign_in_ios' s.version = '0.0.1' s.summary = 'Google Sign-In plugin for Flutter' s.description = <<-DESC Enables Google Sign-In in Flutter apps. DESC s.homepage = 'https://github.com/flutter/plugins/tree/main/packages/google_sign_in' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/google_sign_in/google_sign_in_ios' } s.source_files = 'Classes/**/*.{h,m}' s.public_header_files = 'Classes/**/*.h' s.module_map = 'Classes/FLTGoogleSignInPlugin.modulemap' s.dependency 'Flutter' s.dependency 'GoogleSignIn', '~> 6.2' s.static_framework = true s.platform = :ios, '9.0' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } end
plugins/packages/google_sign_in/google_sign_in_ios/ios/google_sign_in_ios.podspec/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_ios/ios/google_sign_in_ios.podspec", "repo_id": "plugins", "token_count": 470 }
1,254
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; export 'package:image_picker_platform_interface/image_picker_platform_interface.dart' show kTypeImage, kTypeVideo, ImageSource, CameraDevice, LostData, LostDataResponse, PickedFile, XFile, RetrieveType; /// Provides an easy way to pick an image/video from the image library, /// or to take a picture/video with the camera. class ImagePicker { /// The platform interface that drives this plugin @visibleForTesting static ImagePickerPlatform get platform => ImagePickerPlatform.instance; /// Returns a [PickedFile] object wrapping the image that was picked. /// /// The returned [PickedFile] is intended to be used within a single APP session. Do not save the file path and use it across sessions. /// /// The `source` argument controls where the image comes from. This can /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and above only support HEIC images if used /// in addition to a size modification, of which the usage is explained below. /// /// If specified, the image will be at most `maxWidth` wide and /// `maxHeight` tall. Otherwise the image will be returned at it's /// original width and height. /// The `imageQuality` argument modifies the quality of the image, ranging from 0-100 /// where 100 is the original/max quality. If `imageQuality` is null, the image with /// the original quality will be returned. Compression is only supported for certain /// image types such as JPEG and on Android PNG and WebP, too. If compression is not supported for the image that is picked, /// a warning message will be logged. /// /// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera]. /// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device. /// Defaults to [CameraDevice.rear]. Note that Android has no documented parameter for an intent to specify if /// the front or rear camera should be opened, this function is not guaranteed /// to work on an Android device. /// /// In Android, the MainActivity can be destroyed for various reasons. If that happens, the result will be lost /// in this call. You can then call [getLostData] when your app relaunches to retrieve the lost data. /// /// See also [getMultiImage] to allow users to select multiple images at once. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created (iOS only), plugin activity could not /// be allocated (Android only) or due to an unknown error. @Deprecated('Switch to using pickImage instead') Future<PickedFile?> getImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) { return platform.pickImage( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ); } /// Returns a [List<PickedFile>] object wrapping the images that were picked. /// /// The returned [List<PickedFile>] is intended to be used within a single APP session. Do not save the file path and use it across sessions. /// /// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and above only support HEIC images if used /// in addition to a size modification, of which the usage is explained below. /// /// This method is not supported in iOS versions lower than 14. /// /// If specified, the images will be at most `maxWidth` wide and /// `maxHeight` tall. Otherwise the images will be returned at it's /// original width and height. /// The `imageQuality` argument modifies the quality of the images, ranging from 0-100 /// where 100 is the original/max quality. If `imageQuality` is null, the images with /// the original quality will be returned. Compression is only supported for certain /// image types such as JPEG and on Android PNG and WebP, too. If compression is not supported for the image that is picked, /// a warning message will be logged. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created (iOS only), plugin activity could not /// be allocated (Android only) or due to an unknown error. /// /// See also [getImage] to allow users to only pick a single image. @Deprecated('Switch to using pickMultiImage instead') Future<List<PickedFile>?> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) { return platform.pickMultiImage( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ); } /// Returns a [PickedFile] object wrapping the video that was picked. /// /// The returned [PickedFile] is intended to be used within a single APP session. Do not save the file path and use it across sessions. /// /// The [source] argument controls where the video comes from. This can /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// The [maxDuration] argument specifies the maximum duration of the captured video. If no [maxDuration] is specified, /// the maximum duration will be infinite. /// /// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera]. /// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device. /// Defaults to [CameraDevice.rear]. /// /// In Android, the MainActivity can be destroyed for various fo reasons. If that happens, the result will be lost /// in this call. You can then call [getLostData] when your app relaunches to retrieve the lost data. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created and video could not be cached (iOS only), /// plugin activity could not be allocated (Android only) or due to an unknown error. /// @Deprecated('Switch to using pickVideo instead') Future<PickedFile?> getVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) { return platform.pickVideo( source: source, preferredCameraDevice: preferredCameraDevice, maxDuration: maxDuration, ); } /// Retrieve the lost [PickedFile] when [selectImage] or [selectVideo] failed because the MainActivity is destroyed. (Android only) /// /// Image or video can be lost if the MainActivity is destroyed. And there is no guarantee that the MainActivity is always alive. /// Call this method to retrieve the lost data and process the data according to your APP's business logic. /// /// Returns a [LostData] object if successfully retrieved the lost data. The [LostData] object can represent either a /// successful image/video selection, or a failure. /// /// Calling this on a non-Android platform will throw [UnimplementedError] exception. /// /// See also: /// * [LostData], for what's included in the response. /// * [Android Activity Lifecycle](https://developer.android.com/reference/android/app/Activity.html), for more information on MainActivity destruction. @Deprecated('Switch to using retrieveLostData instead') Future<LostData> getLostData() { return platform.retrieveLostData(); } /// Returns an [XFile] object wrapping the image that was picked. /// /// The returned [XFile] is intended to be used within a single APP session. Do not save the file path and use it across sessions. /// /// The `source` argument controls where the image comes from. This can /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and /// above only support HEIC images if used in addition to a size modification, /// of which the usage is explained below. /// /// If specified, the image will be at most `maxWidth` wide and /// `maxHeight` tall. Otherwise the image will be returned at it's /// original width and height. /// The `imageQuality` argument modifies the quality of the image, ranging from 0-100 /// where 100 is the original/max quality. If `imageQuality` is null, the image with /// the original quality will be returned. Compression is only supported for certain /// image types such as JPEG and on Android PNG and WebP, too. If compression is not /// supported for the image that is picked, a warning message will be logged. /// /// Use `preferredCameraDevice` to specify the camera to use when the `source` is /// [ImageSource.camera]. /// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. /// It is also ignored if the chosen camera is not supported on the device. /// Defaults to [CameraDevice.rear]. Note that Android has no documented parameter /// for an intent to specify if the front or rear camera should be opened, this /// function is not guaranteed to work on an Android device. /// /// Use `requestFullMetadata` (defaults to `true`) to control how much additional /// information the plugin tries to get. /// If `requestFullMetadata` is set to `true`, the plugin tries to get the full /// image metadata which may require extra permission requests on some platforms, /// such as `Photo Library Usage` permission on iOS. /// /// In Android, the MainActivity can be destroyed for various reasons. If that happens, the result will be lost /// in this call. You can then call [retrieveLostData] when your app relaunches to retrieve the lost data. /// /// See also [pickMultiImage] to allow users to select multiple images at once. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created (iOS only), plugin activity could not /// be allocated (Android only) or due to an unknown error. Future<XFile?> pickImage({ 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 platform.getImageFromSource( source: source, options: ImagePickerOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, requestFullMetadata: requestFullMetadata, ), ); } /// Returns a [List<XFile>] object wrapping the images that were picked. /// /// The returned [List<XFile>] is intended to be used within a single APP session. Do not save the file path and use it across sessions. /// /// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and above only support HEIC images if used /// in addition to a size modification, of which the usage is explained below. /// /// This method is not supported in iOS versions lower than 14. /// /// If specified, the images will be at most `maxWidth` wide and /// `maxHeight` tall. Otherwise the images will be returned at it's /// original width and height. /// /// The `imageQuality` argument modifies the quality of the images, ranging from 0-100 /// where 100 is the original/max quality. If `imageQuality` is null, the images with /// the original quality will be returned. Compression is only supported for certain /// image types such as JPEG and on Android PNG and WebP, too. If compression is not /// supported for the image that is picked, a warning message will be logged. /// /// Use `requestFullMetadata` (defaults to `true`) to control how much additional /// information the plugin tries to get. /// If `requestFullMetadata` is set to `true`, the plugin tries to get the full /// image metadata which may require extra permission requests on some platforms, /// such as `Photo Library Usage` permission on iOS. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created (iOS only), plugin activity could not /// be allocated (Android only) or due to an unknown error. /// /// See also [pickImage] to allow users to only pick a single image. Future<List<XFile>> pickMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, bool requestFullMetadata = true, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } return platform.getMultiImageWithOptions( options: MultiImagePickerOptions( imageOptions: ImageOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, requestFullMetadata: requestFullMetadata, ), ), ); } /// Returns an [XFile] object wrapping the video that was picked. /// /// The returned [XFile] is intended to be used within a single APP session. Do not save the file path and use it across sessions. /// /// The [source] argument controls where the video comes from. This can /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// The [maxDuration] argument specifies the maximum duration of the captured video. If no [maxDuration] is specified, /// the maximum duration will be infinite. /// /// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera]. /// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device. /// Defaults to [CameraDevice.rear]. /// /// In Android, the MainActivity can be destroyed for various fo reasons. If that happens, the result will be lost /// in this call. You can then call [retrieveLostData] when your app relaunches to retrieve the lost data. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created and video could not be cached (iOS only), /// plugin activity could not be allocated (Android only) or due to an unknown error. /// Future<XFile?> pickVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) { return platform.getVideo( source: source, preferredCameraDevice: preferredCameraDevice, maxDuration: maxDuration, ); } /// Retrieve the lost [XFile] when [pickImage], [pickMultiImage] or [pickVideo] failed because the MainActivity /// is destroyed. (Android only) /// /// Image or video can be lost if the MainActivity is destroyed. And there is no guarantee that the MainActivity is always alive. /// Call this method to retrieve the lost data and process the data according to your APP's business logic. /// /// Returns a [LostDataResponse] object if successfully retrieved the lost data. The [LostDataResponse] object can \ /// represent either a successful image/video selection, or a failure. /// /// Calling this on a non-Android platform will throw [UnimplementedError] exception. /// /// See also: /// * [LostDataResponse], for what's included in the response. /// * [Android Activity Lifecycle](https://developer.android.com/reference/android/app/Activity.html), for more information on MainActivity destruction. Future<LostDataResponse> retrieveLostData() { return platform.getLostData(); } }
plugins/packages/image_picker/image_picker/lib/image_picker.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker/lib/image_picker.dart", "repo_id": "plugins", "token_count": 4797 }
1,255
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.imagepicker; import androidx.core.content.FileProvider; /** * Providing a custom {@code FileProvider} prevents manifest {@code <provider>} name collisions. * * <p>See https://developer.android.com/guide/topics/manifest/provider-element.html for details. */ public class ImagePickerFileProvider extends FileProvider {}
plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerFileProvider.java/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerFileProvider.java", "repo_id": "plugins", "token_count": 144 }
1,256
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
plugins/packages/image_picker/image_picker_android/example/android/gradle.properties/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/example/android/gradle.properties", "repo_id": "plugins", "token_count": 30 }
1,257
// 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:typed_data'; import 'dart:ui'; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_for_web/src/image_resizer.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'package:integration_test/integration_test.dart'; //This is a sample 10x10 png image const String pngFileBase64Contents = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKAQMAAAC3/F3+AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABlBMVEXqQzX+/v6lfubTAAAAAWJLR0QB/wIt3gAAAAlwSFlzAAAHEwAABxMBziAPCAAAAAd0SU1FB+UJHgsdDM0ErZoAAAALSURBVAjXY2DABwAAHgABboVHMgAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMS0wOS0zMFQxMToyOToxMi0wNDowMHCDC24AAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjEtMDktMzBUMTE6Mjk6MTItMDQ6MDAB3rPSAAAAAElFTkSuQmCC'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); // Under test... late ImageResizer imageResizer; late XFile pngFile; setUp(() { imageResizer = ImageResizer(); final html.File pngHtmlFile = _base64ToFile(pngFileBase64Contents, 'pngImage.png'); pngFile = XFile(html.Url.createObjectUrl(pngHtmlFile), name: pngHtmlFile.name, mimeType: pngHtmlFile.type); }); testWidgets('image is loaded correctly ', (WidgetTester tester) async { final html.ImageElement imageElement = await imageResizer.loadImage(pngFile.path); expect(imageElement.width, 10); expect(imageElement.height, 10); }); testWidgets( "canvas is loaded with image's width and height when max width and max height are null", (WidgetTester widgetTester) async { final html.ImageElement imageElement = await imageResizer.loadImage(pngFile.path); final html.CanvasElement canvas = imageResizer.resizeImageElement(imageElement, null, null); expect(canvas.width, imageElement.width); expect(canvas.height, imageElement.height); }); testWidgets( 'canvas size is scaled when max width and max height are not null', (WidgetTester widgetTester) async { final html.ImageElement imageElement = await imageResizer.loadImage(pngFile.path); final html.CanvasElement canvas = imageResizer.resizeImageElement(imageElement, 8, 8); expect(canvas.width, 8); expect(canvas.height, 8); }); testWidgets('resized image is returned after converting canvas to file', (WidgetTester widgetTester) async { final html.ImageElement imageElement = await imageResizer.loadImage(pngFile.path); final html.CanvasElement canvas = imageResizer.resizeImageElement(imageElement, null, null); final XFile resizedImage = await imageResizer.writeCanvasToFile(pngFile, canvas, null); expect(resizedImage.name, 'scaled_${pngFile.name}'); }); testWidgets('image is scaled when maxWidth is set', (WidgetTester tester) async { final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, 5, null, null); expect(scaledImage.name, 'scaled_${pngFile.name}'); final Size scaledImageSize = await _getImageSize(scaledImage); expect(scaledImageSize, const Size(5, 5)); }); testWidgets('image is scaled when maxHeight is set', (WidgetTester tester) async { final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, null, 6, null); expect(scaledImage.name, 'scaled_${pngFile.name}'); final Size scaledImageSize = await _getImageSize(scaledImage); expect(scaledImageSize, const Size(6, 6)); }); testWidgets('image is scaled when imageQuality is set', (WidgetTester tester) async { final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, null, null, 89); expect(scaledImage.name, 'scaled_${pngFile.name}'); }); testWidgets('image is scaled when maxWidth,maxHeight,imageQuality are set', (WidgetTester tester) async { final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, 3, 4, 89); expect(scaledImage.name, 'scaled_${pngFile.name}'); }); testWidgets('image is not scaled when maxWidth,maxHeight, is set', (WidgetTester tester) async { final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, null, null, null); expect(scaledImage.name, pngFile.name); }); } Future<Size> _getImageSize(XFile file) async { final Completer<Size> completer = Completer<Size>(); final html.ImageElement image = html.ImageElement(src: file.path); image.onLoad.listen((html.Event event) { completer.complete(Size(image.width!.toDouble(), image.height!.toDouble())); }); image.onError.listen((html.Event event) { completer.complete(Size.zero); }); return completer.future; } html.File _base64ToFile(String data, String fileName) { final List<String> arr = data.split(','); final String bstr = html.window.atob(arr[1]); int n = bstr.length; final Uint8List u8arr = Uint8List(n); while (n >= 1) { u8arr[n - 1] = bstr.codeUnitAt(n - 1); n--; } return html.File(<Uint8List>[u8arr], fileName); }
plugins/packages/image_picker/image_picker_for_web/example/integration_test/image_resizer_test.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_for_web/example/integration_test/image_resizer_test.dart", "repo_id": "plugins", "token_count": 2021 }
1,258
# image\_picker\_ios The iOS implementation of [`image_picker`][1]. ## Usage This package is [endorsed][2], which means you can simply use `image_picker` normally. This package will be automatically included in your app when you do. [1]: https://pub.dev/packages/image_picker [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
plugins/packages/image_picker/image_picker_ios/README.md/0
{ "file_path": "plugins/packages/image_picker/image_picker_ios/README.md", "repo_id": "plugins", "token_count": 123 }
1,259
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'src/messages.g.dart'; // Converts an [ImageSource] to the corresponding Pigeon API enum value. SourceType _convertSource(ImageSource source) { switch (source) { case ImageSource.camera: return SourceType.camera; case ImageSource.gallery: return SourceType.gallery; } // The enum comes from a different package, which could get a new value at // any time, so a fallback case is necessary. Since there is no reasonable // default behavior, throw to alert the client that they need an updated // version. This is deliberately outside the switch rather than a `default` // so that the linter will flag the switch as needing an update. // ignore: dead_code throw UnimplementedError('Unknown source: $source'); } // Converts a [CameraDevice] to the corresponding Pigeon API enum value. SourceCamera _convertCamera(CameraDevice camera) { switch (camera) { case CameraDevice.front: return SourceCamera.front; case CameraDevice.rear: return SourceCamera.rear; } // The enum comes from a different package, which could get a new value at // any time, so a fallback case is necessary. Since there is no reasonable // default behavior, throw to alert the client that they need an updated // version. This is deliberately outside the switch rather than a `default` // so that the linter will flag the switch as needing an update. // ignore: dead_code throw UnimplementedError('Unknown camera: $camera'); } /// An implementation of [ImagePickerPlatform] for iOS. class ImagePickerIOS extends ImagePickerPlatform { final ImagePickerApi _hostApi = ImagePickerApi(); /// Registers this class as the default platform implementation. static void registerWith() { ImagePickerPlatform.instance = ImagePickerIOS(); } @override Future<PickedFile?> pickImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final String? path = await _pickImageAsPath( source: source, options: ImagePickerOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ), ); return path != null ? PickedFile(path) : null; } @override Future<XFile?> getImageFromSource({ required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) async { final String? path = await _pickImageAsPath( source: source, options: options, ); return path != null ? XFile(path) : null; } @override Future<List<PickedFile>?> pickMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { final List<dynamic>? paths = await _pickMultiImageAsPath( options: MultiImagePickerOptions( imageOptions: ImageOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ), ), ); if (paths == null) { return null; } return paths.map((dynamic path) => PickedFile(path as String)).toList(); } @override Future<List<XFile>> getMultiImageWithOptions({ MultiImagePickerOptions options = const MultiImagePickerOptions(), }) async { final List<String>? paths = await _pickMultiImageAsPath(options: options); if (paths == null) { return <XFile>[]; } return paths.map((String path) => XFile(path)).toList(); } Future<List<String>?> _pickMultiImageAsPath({ MultiImagePickerOptions options = const MultiImagePickerOptions(), }) async { final int? imageQuality = options.imageOptions.imageQuality; if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } final double? maxWidth = options.imageOptions.maxWidth; if (maxWidth != null && maxWidth < 0) { throw ArgumentError.value(maxWidth, 'maxWidth', 'cannot be negative'); } final double? maxHeight = options.imageOptions.maxHeight; if (maxHeight != null && maxHeight < 0) { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } // TODO(stuartmorgan): Remove the cast once Pigeon supports non-nullable // generics, https://github.com/flutter/flutter/issues/97848 return (await _hostApi.pickMultiImage( MaxSize(width: maxWidth, height: maxHeight), imageQuality, options.imageOptions.requestFullMetadata)) ?.cast<String>(); } Future<String?> _pickImageAsPath({ required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) { final int? imageQuality = options.imageQuality; if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { throw ArgumentError.value( imageQuality, 'imageQuality', 'must be between 0 and 100'); } final double? maxHeight = options.maxHeight; final double? maxWidth = options.maxWidth; 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 _hostApi.pickImage( SourceSpecification( type: _convertSource(source), camera: _convertCamera(options.preferredCameraDevice), ), MaxSize(width: maxWidth, height: maxHeight), imageQuality, options.requestFullMetadata, ); } @override Future<PickedFile?> pickVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? path = await _pickVideoAsPath( source: source, maxDuration: maxDuration, preferredCameraDevice: preferredCameraDevice, ); return path != null ? PickedFile(path) : null; } Future<String?> _pickVideoAsPath({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) { return _hostApi.pickVideo( SourceSpecification( type: _convertSource(source), camera: _convertCamera(preferredCameraDevice)), maxDuration?.inSeconds); } @override Future<XFile?> getImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final String? path = await _pickImageAsPath( source: source, options: ImagePickerOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, ), ); return path != null ? XFile(path) : null; } @override Future<List<XFile>?> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { final List<String>? paths = await _pickMultiImageAsPath( options: MultiImagePickerOptions( imageOptions: ImageOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ), ), ); if (paths == null) { return null; } return paths.map((String path) => XFile(path)).toList(); } @override Future<XFile?> getVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? path = await _pickVideoAsPath( source: source, maxDuration: maxDuration, preferredCameraDevice: preferredCameraDevice, ); return path != null ? XFile(path) : null; } }
plugins/packages/image_picker/image_picker_ios/lib/image_picker_ios.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_ios/lib/image_picker_ios.dart", "repo_id": "plugins", "token_count": 2830 }
1,260
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.inapppurchase; import androidx.annotation.Nullable; import com.android.billingclient.api.AccountIdentifiers; import com.android.billingclient.api.BillingResult; import com.android.billingclient.api.Purchase; import com.android.billingclient.api.PurchaseHistoryRecord; import com.android.billingclient.api.SkuDetails; import java.util.ArrayList; import java.util.Collections; import java.util.Currency; import java.util.HashMap; import java.util.List; import java.util.Locale; /** Handles serialization of {@link com.android.billingclient.api.BillingClient} related objects. */ /*package*/ class Translator { static HashMap<String, Object> fromSkuDetail(SkuDetails detail) { HashMap<String, Object> info = new HashMap<>(); info.put("title", detail.getTitle()); info.put("description", detail.getDescription()); info.put("freeTrialPeriod", detail.getFreeTrialPeriod()); info.put("introductoryPrice", detail.getIntroductoryPrice()); info.put("introductoryPriceAmountMicros", detail.getIntroductoryPriceAmountMicros()); info.put("introductoryPriceCycles", detail.getIntroductoryPriceCycles()); info.put("introductoryPricePeriod", detail.getIntroductoryPricePeriod()); info.put("price", detail.getPrice()); info.put("priceAmountMicros", detail.getPriceAmountMicros()); info.put("priceCurrencyCode", detail.getPriceCurrencyCode()); info.put("priceCurrencySymbol", currencySymbolFromCode(detail.getPriceCurrencyCode())); info.put("sku", detail.getSku()); info.put("type", detail.getType()); info.put("subscriptionPeriod", detail.getSubscriptionPeriod()); info.put("originalPrice", detail.getOriginalPrice()); info.put("originalPriceAmountMicros", detail.getOriginalPriceAmountMicros()); return info; } static List<HashMap<String, Object>> fromSkuDetailsList( @Nullable List<SkuDetails> skuDetailsList) { if (skuDetailsList == null) { return Collections.emptyList(); } ArrayList<HashMap<String, Object>> output = new ArrayList<>(); for (SkuDetails detail : skuDetailsList) { output.add(fromSkuDetail(detail)); } return output; } static HashMap<String, Object> fromPurchase(Purchase purchase) { HashMap<String, Object> info = new HashMap<>(); List<String> skus = purchase.getSkus(); info.put("orderId", purchase.getOrderId()); info.put("packageName", purchase.getPackageName()); info.put("purchaseTime", purchase.getPurchaseTime()); info.put("purchaseToken", purchase.getPurchaseToken()); info.put("signature", purchase.getSignature()); info.put("skus", skus); info.put("isAutoRenewing", purchase.isAutoRenewing()); info.put("originalJson", purchase.getOriginalJson()); info.put("developerPayload", purchase.getDeveloperPayload()); info.put("isAcknowledged", purchase.isAcknowledged()); info.put("purchaseState", purchase.getPurchaseState()); info.put("quantity", purchase.getQuantity()); AccountIdentifiers accountIdentifiers = purchase.getAccountIdentifiers(); if (accountIdentifiers != null) { info.put("obfuscatedAccountId", accountIdentifiers.getObfuscatedAccountId()); info.put("obfuscatedProfileId", accountIdentifiers.getObfuscatedProfileId()); } return info; } static HashMap<String, Object> fromPurchaseHistoryRecord( PurchaseHistoryRecord purchaseHistoryRecord) { HashMap<String, Object> info = new HashMap<>(); List<String> skus = purchaseHistoryRecord.getSkus(); info.put("purchaseTime", purchaseHistoryRecord.getPurchaseTime()); info.put("purchaseToken", purchaseHistoryRecord.getPurchaseToken()); info.put("signature", purchaseHistoryRecord.getSignature()); info.put("skus", skus); info.put("developerPayload", purchaseHistoryRecord.getDeveloperPayload()); info.put("originalJson", purchaseHistoryRecord.getOriginalJson()); info.put("quantity", purchaseHistoryRecord.getQuantity()); return info; } static List<HashMap<String, Object>> fromPurchasesList(@Nullable List<Purchase> purchases) { if (purchases == null) { return Collections.emptyList(); } List<HashMap<String, Object>> serialized = new ArrayList<>(); for (Purchase purchase : purchases) { serialized.add(fromPurchase(purchase)); } return serialized; } static List<HashMap<String, Object>> fromPurchaseHistoryRecordList( @Nullable List<PurchaseHistoryRecord> purchaseHistoryRecords) { if (purchaseHistoryRecords == null) { return Collections.emptyList(); } List<HashMap<String, Object>> serialized = new ArrayList<>(); for (PurchaseHistoryRecord purchaseHistoryRecord : purchaseHistoryRecords) { serialized.add(fromPurchaseHistoryRecord(purchaseHistoryRecord)); } return serialized; } static HashMap<String, Object> fromBillingResult(BillingResult billingResult) { HashMap<String, Object> info = new HashMap<>(); info.put("responseCode", billingResult.getResponseCode()); info.put("debugMessage", billingResult.getDebugMessage()); return info; } /** * Gets the symbol of for the given currency code for the default {@link Locale.Category#DISPLAY * DISPLAY} locale. For example, for the US Dollar, the symbol is "$" if the default locale is the * US, while for other locales it may be "US$". If no symbol can be determined, the ISO 4217 * currency code is returned. * * @param currencyCode the ISO 4217 code of the currency * @return the symbol of this currency code for the default {@link Locale.Category#DISPLAY * DISPLAY} locale * @exception NullPointerException if <code>currencyCode</code> is null * @exception IllegalArgumentException if <code>currencyCode</code> is not a supported ISO 4217 * code. */ static String currencySymbolFromCode(String currencyCode) { return Currency.getInstance(currencyCode).getSymbol(); } }
plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/Translator.java/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/Translator.java", "repo_id": "plugins", "token_count": 1942 }
1,261
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Thrown to indicate that an action failed while interacting with the /// in_app_purchase plugin. class InAppPurchaseException implements Exception { /// Creates a [InAppPurchaseException] with the specified source and error /// [code] and optional [message]. InAppPurchaseException({ required this.source, required this.code, this.message, }) : assert(code != null); /// An error code. final String code; /// A human-readable error message, possibly null. final String? message; /// Which source is the error on. final String source; @override String toString() => 'InAppPurchaseException($code, $message, $source)'; }
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_exception.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_exception.dart", "repo_id": "plugins", "token_count": 225 }
1,262
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart'; import 'package:json_annotation/json_annotation.dart'; import '../../store_kit_wrappers.dart'; part 'enum_converters.g.dart'; /// Serializer for [SKPaymentTransactionStateWrapper]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@SKTransactionStatusConverter()`. class SKTransactionStatusConverter implements JsonConverter<SKPaymentTransactionStateWrapper, int?> { /// Default const constructor. const SKTransactionStatusConverter(); @override SKPaymentTransactionStateWrapper fromJson(int? json) { if (json == null) { return SKPaymentTransactionStateWrapper.unspecified; } return $enumDecode<SKPaymentTransactionStateWrapper, dynamic>( _$SKPaymentTransactionStateWrapperEnumMap .cast<SKPaymentTransactionStateWrapper, dynamic>(), json); } /// Converts an [SKPaymentTransactionStateWrapper] to a [PurchaseStatus]. PurchaseStatus toPurchaseStatus( SKPaymentTransactionStateWrapper object, SKError? error) { switch (object) { case SKPaymentTransactionStateWrapper.purchasing: case SKPaymentTransactionStateWrapper.deferred: return PurchaseStatus.pending; case SKPaymentTransactionStateWrapper.purchased: return PurchaseStatus.purchased; case SKPaymentTransactionStateWrapper.restored: return PurchaseStatus.restored; case SKPaymentTransactionStateWrapper.failed: // According to the Apple documentation the error code "2" indicates // the user cancelled the payment (SKErrorPaymentCancelled) and error // code "15" indicates the cancellation of the overlay (SKErrorOverlayCancelled). // An overview of all error codes can be found at: https://developer.apple.com/documentation/storekit/skerrorcode?language=objc if (error != null && (error.code == 2 || error.code == 15)) { return PurchaseStatus.canceled; } return PurchaseStatus.error; case SKPaymentTransactionStateWrapper.unspecified: return PurchaseStatus.error; } } @override int toJson(SKPaymentTransactionStateWrapper object) => _$SKPaymentTransactionStateWrapperEnumMap[object]!; } /// Serializer for [SKSubscriptionPeriodUnit]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@SKSubscriptionPeriodUnitConverter()`. class SKSubscriptionPeriodUnitConverter implements JsonConverter<SKSubscriptionPeriodUnit, int?> { /// Default const constructor. const SKSubscriptionPeriodUnitConverter(); @override SKSubscriptionPeriodUnit fromJson(int? json) { if (json == null) { return SKSubscriptionPeriodUnit.day; } return $enumDecode<SKSubscriptionPeriodUnit, dynamic>( _$SKSubscriptionPeriodUnitEnumMap .cast<SKSubscriptionPeriodUnit, dynamic>(), json); } @override int toJson(SKSubscriptionPeriodUnit object) => _$SKSubscriptionPeriodUnitEnumMap[object]!; } /// Serializer for [SKProductDiscountPaymentMode]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@SKProductDiscountPaymentModeConverter()`. class SKProductDiscountPaymentModeConverter implements JsonConverter<SKProductDiscountPaymentMode, int?> { /// Default const constructor. const SKProductDiscountPaymentModeConverter(); @override SKProductDiscountPaymentMode fromJson(int? json) { if (json == null) { return SKProductDiscountPaymentMode.payAsYouGo; } return $enumDecode<SKProductDiscountPaymentMode, dynamic>( _$SKProductDiscountPaymentModeEnumMap .cast<SKProductDiscountPaymentMode, dynamic>(), json); } @override int toJson(SKProductDiscountPaymentMode object) => _$SKProductDiscountPaymentModeEnumMap[object]!; } // Define a class so we generate serializer helper methods for the enums // See https://github.com/google/json_serializable.dart/issues/778 @JsonSerializable() class _SerializedEnums { late SKPaymentTransactionStateWrapper response; late SKSubscriptionPeriodUnit unit; late SKProductDiscountPaymentMode discountPaymentMode; } /// Serializer for [SKProductDiscountType]. /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@SKProductDiscountTypeConverter()`. class SKProductDiscountTypeConverter implements JsonConverter<SKProductDiscountType, int?> { /// Default const constructor. const SKProductDiscountTypeConverter(); @override SKProductDiscountType fromJson(int? json) { if (json == null) { return SKProductDiscountType.introductory; } return $enumDecode<SKProductDiscountType, dynamic>( _$SKProductDiscountTypeEnumMap.cast<SKProductDiscountType, dynamic>(), json); } @override int toJson(SKProductDiscountType object) => _$SKProductDiscountTypeEnumMap[object]!; }
plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.dart", "repo_id": "plugins", "token_count": 1750 }
1,263
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'in_app_purchase_storekit' s.version = '0.0.1' s.summary = 'Flutter In App Purchase iOS and macOS' s.description = <<-DESC A Flutter plugin for in-app purchases. Exposes APIs for making in-app purchases through the App Store. Downloaded by pub (not CocoaPods). DESC s.homepage = 'https://github.com/flutter/plugins' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/in_app_purchase/in_app_purchase_storekit' } # TODO(mvanbeusekom): update URL when in_app_purchase_storekit package is published. # Updating it before the package is published will cause a lint error and block the tree. s.documentation_url = 'https://pub.dev/packages/in_app_purchase' s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.ios.dependency 'Flutter' s.osx.dependency 'FlutterMacOS' s.ios.deployment_target = '11.0' s.osx.deployment_target = '10.15' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } end
plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/in_app_purchase_storekit.podspec/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/in_app_purchase_storekit.podspec", "repo_id": "plugins", "token_count": 548 }
1,264
# IOS Platform Images A Flutter plugin to share images between Flutter and iOS. This allows Flutter to load images from Images.xcassets and iOS code to load Flutter images. When loading images from Image.xcassets the device specific variant is chosen ([iOS documentation](https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/)). | | iOS | |-------------|-------| | **Support** | 11.0+ | ## Usage ### iOS->Flutter Example ``` dart // Import package import 'package:ios_platform_images/ios_platform_images.dart'; Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: Image(image: IosPlatformImages.load("flutter")), ), //.. ), ); } ``` `IosPlatformImages.load` functions like [[UIImage imageNamed:]](https://developer.apple.com/documentation/uikit/uiimage/1624146-imagenamed). ### Flutter->iOS Example ```objc #import <ios_platform_images/UIImage+ios_platform_images.h> static UIImageView* MakeImage() { UIImage* image = [UIImage flutterImageWithName:@"assets/foo.png"]; return [[UIImageView alloc] initWithImage:image]; } ```
plugins/packages/ios_platform_images/README.md/0
{ "file_path": "plugins/packages/ios_platform_images/README.md", "repo_id": "plugins", "token_count": 407 }
1,265
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="oval"> <solid android:color="#607D8B"/> <size android:width="40dp" android:height="40dp"/> </shape> </item> <item android:drawable="@drawable/ic_fingerprint_white_24dp" android:bottom="8dp" android:left="8dp" android:right="8dp" android:top="8dp"/> </layer-list>
plugins/packages/local_auth/local_auth_android/android/src/main/res/drawable/fingerprint_initial_icon.xml/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/drawable/fingerprint_initial_icon.xml", "repo_id": "plugins", "token_count": 212 }
1,266
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.localauth; import androidx.test.rule.ActivityTestRule; import dev.flutter.plugins.integration_test.FlutterTestRunner; import io.flutter.embedding.android.FlutterFragmentActivity; import io.flutter.plugins.DartIntegrationTest; import org.junit.Rule; import org.junit.runner.RunWith; @DartIntegrationTest @RunWith(FlutterTestRunner.class) public class FlutterFragmentActivityTest { @Rule public ActivityTestRule<FlutterFragmentActivity> rule = new ActivityTestRule<>(FlutterFragmentActivity.class); }
plugins/packages/local_auth/local_auth_android/example/android/app/src/androidTest/java/io/flutter/plugins/localauth/FlutterFragmentActivityTest.java/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/example/android/app/src/androidTest/java/io/flutter/plugins/localauth/FlutterFragmentActivityTest.java", "repo_id": "plugins", "token_count": 212 }
1,267
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:local_auth_platform_interface/local_auth_platform_interface.dart'; import 'types/auth_messages_android.dart'; export 'package:local_auth_android/types/auth_messages_android.dart'; export 'package:local_auth_platform_interface/types/auth_messages.dart'; export 'package:local_auth_platform_interface/types/auth_options.dart'; export 'package:local_auth_platform_interface/types/biometric_type.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/local_auth_android'); /// The implementation of [LocalAuthPlatform] for Android. class LocalAuthAndroid extends LocalAuthPlatform { /// Registers this class as the default instance of [LocalAuthPlatform]. static void registerWith() { LocalAuthPlatform.instance = LocalAuthAndroid(); } @override Future<bool> authenticate({ required String localizedReason, required Iterable<AuthMessages> authMessages, AuthenticationOptions options = const AuthenticationOptions(), }) async { assert(localizedReason.isNotEmpty); final Map<String, Object> args = <String, Object>{ 'localizedReason': localizedReason, 'useErrorDialogs': options.useErrorDialogs, 'stickyAuth': options.stickyAuth, 'sensitiveTransaction': options.sensitiveTransaction, 'biometricOnly': options.biometricOnly, }; args.addAll(const AndroidAuthMessages().args); for (final AuthMessages messages in authMessages) { if (messages is AndroidAuthMessages) { args.addAll(messages.args); } } return (await _channel.invokeMethod<bool>('authenticate', args)) ?? false; } @override Future<bool> deviceSupportsBiometrics() async { return (await _channel.invokeMethod<bool>('deviceSupportsBiometrics')) ?? false; } @override Future<List<BiometricType>> getEnrolledBiometrics() async { final List<String> result = (await _channel.invokeListMethod<String>( 'getEnrolledBiometrics', )) ?? <String>[]; final List<BiometricType> biometrics = <BiometricType>[]; for (final String value in result) { switch (value) { case 'weak': biometrics.add(BiometricType.weak); break; case 'strong': biometrics.add(BiometricType.strong); break; } } return biometrics; } @override Future<bool> isDeviceSupported() async => (await _channel.invokeMethod<bool>('isDeviceSupported')) ?? false; @override Future<bool> stopAuthentication() async => await _channel.invokeMethod<bool>('stopAuthentication') ?? false; }
plugins/packages/local_auth/local_auth_android/lib/local_auth_android.dart/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/lib/local_auth_android.dart", "repo_id": "plugins", "token_count": 958 }
1,268
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'local_auth_ios' s.version = '0.0.1' s.summary = 'Flutter Local Auth' s.description = <<-DESC This Flutter plugin provides means to perform local, on-device authentication of the user. Downloaded by pub (not CocoaPods). DESC s.homepage = 'https://github.com/flutter/plugins' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/local_auth' } s.documentation_url = 'https://pub.dev/packages/local_auth_ios' s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.dependency 'Flutter' s.platform = :ios, '9.0' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } end
plugins/packages/local_auth/local_auth_ios/ios/local_auth_ios.podspec/0
{ "file_path": "plugins/packages/local_auth/local_auth_ios/ios/local_auth_ios.podspec", "repo_id": "plugins", "token_count": 431 }
1,269
## NEXT * Updates minimum Flutter version to 3.0. ## 1.0.0 * Updates version to 1.0 to reflect current status. * Updates minimum Flutter version to 2.10. * Updates mockito-core to 4.6.1. * Removes deprecated FieldSetter from QuickActionsTest. ## 0.6.2 * Updates gradle version to 7.2.1. ## 0.6.1 * Allows Android to trigger quick actions without restarting the app. ## 0.6.0+11 * Updates references to the obsolete master branch. ## 0.6.0+10 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.6.0+9 * Switches to a package-internal implementation of the platform interface.
plugins/packages/quick_actions/quick_actions_android/CHANGELOG.md/0
{ "file_path": "plugins/packages/quick_actions/quick_actions_android/CHANGELOG.md", "repo_id": "plugins", "token_count": 220 }
1,270