text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; part 'leaderboard_entry_data.g.dart'; /// Google character type associated with a [LeaderboardEntryData]. enum CharacterType { /// Dash character. dash, /// Sparky character. sparky, /// Android character. android, /// Dino character. dino, } /// {@template leaderboard_entry_data} /// A model representing a leaderboard entry containing the player's initials, /// score, and chosen character. /// /// Stored in Firestore `leaderboard` collection. /// /// Example: /// ```json /// { /// "playerInitials" : "ABC", /// "score" : 1500, /// "character" : "dash" /// } /// ``` /// {@endtemplate} @JsonSerializable() class LeaderboardEntryData extends Equatable { /// {@macro leaderboard_entry_data} const LeaderboardEntryData({ required this.playerInitials, required this.score, required this.character, }); /// Factory which converts a [Map] into a [LeaderboardEntryData]. factory LeaderboardEntryData.fromJson(Map<String, dynamic> json) { return _$LeaderboardEntryFromJson(json); } /// Converts the [LeaderboardEntryData] to [Map]. Map<String, dynamic> toJson() => _$LeaderboardEntryToJson(this); /// Player's chosen initials for [LeaderboardEntryData]. /// /// Example: 'ABC'. @JsonKey(name: 'playerInitials') final String playerInitials; /// Score for [LeaderboardEntryData]. /// /// Example: 1500. @JsonKey(name: 'score') final int score; /// [CharacterType] for [LeaderboardEntryData]. /// /// Example: [CharacterType.dash]. @JsonKey(name: 'character') final CharacterType character; /// An empty [LeaderboardEntryData] object. static const empty = LeaderboardEntryData( playerInitials: '', score: 0, character: CharacterType.dash, ); @override List<Object?> get props => [playerInitials, score, character]; }
pinball/packages/leaderboard_repository/lib/src/models/leaderboard_entry_data.dart/0
{ "file_path": "pinball/packages/leaderboard_repository/lib/src/models/leaderboard_entry_data.dart", "repo_id": "pinball", "token_count": 610 }
1,051
import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template android_bumper_blinking_behavior} /// Makes an [AndroidBumper] blink back to [AndroidBumperState.lit] when /// [AndroidBumperState.dimmed]. /// {@endtemplate} class AndroidBumperBlinkingBehavior extends TimerComponent with ParentIsA<AndroidBumper> { /// {@macro android_bumper_blinking_behavior} AndroidBumperBlinkingBehavior() : super(period: 0.05); void _onNewState(AndroidBumperState state) { switch (state) { case AndroidBumperState.lit: break; case AndroidBumperState.dimmed: timer ..reset() ..start(); break; } } @override Future<void> onLoad() async { await super.onLoad(); timer.stop(); parent.bloc.stream.listen(_onNewState); } @override void onTick() { super.onTick(); timer.stop(); parent.bloc.onBlinked(); } }
pinball/packages/pinball_components/lib/src/components/android_bumper/behaviors/android_bumper_blinking_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/android_bumper/behaviors/android_bumper_blinking_behavior.dart", "repo_id": "pinball", "token_count": 390 }
1,052
export 'ball_gravitating_behavior.dart'; export 'ball_impulsing_behavior.dart'; export 'ball_scaling_behavior.dart'; export 'ball_turbo_charging_behavior.dart';
pinball/packages/pinball_components/lib/src/components/ball/behaviors/behaviors.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/ball/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 56 }
1,053
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:pinball_components/pinball_components.dart'; part 'chrome_dino_state.dart'; class ChromeDinoCubit extends Cubit<ChromeDinoState> { ChromeDinoCubit() : super(const ChromeDinoState.initial()); void onOpenMouth() { emit(state.copyWith(isMouthOpen: true)); } void onCloseMouth() { emit(state.copyWith(isMouthOpen: false)); } void onChomp(Ball ball) { if (ball != state.ball) { emit(state.copyWith(status: ChromeDinoStatus.chomping, ball: ball)); } } void onSpit() { emit( ChromeDinoState( status: ChromeDinoStatus.idle, isMouthOpen: state.isMouthOpen, ), ); } }
pinball/packages/pinball_components/lib/src/components/chrome_dino/cubit/chrome_dino_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/chrome_dino/cubit/chrome_dino_cubit.dart", "repo_id": "pinball", "token_count": 300 }
1,054
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flutter/services.dart'; import 'package:pinball_components/pinball_components.dart'; /// Allows controlling the [Flipper]'s movement with keyboard input. class FlipperKeyControllingBehavior extends Component with KeyboardHandler, FlameBlocReader<FlipperCubit, FlipperState> { /// The [LogicalKeyboardKey]s that will control the [Flipper]. /// /// [onKeyEvent] method listens to when one of these keys is pressed. late final List<LogicalKeyboardKey> _keys; @override Future<void> onLoad() async { await super.onLoad(); final flipper = parent!.parent! as Flipper; switch (flipper.side) { case BoardSide.left: _keys = [ LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.keyA, ]; break; case BoardSide.right: _keys = [ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.keyD, ]; break; } } @override bool onKeyEvent( RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed, ) { if (!_keys.contains(event.logicalKey)) return true; if (event is RawKeyDownEvent) { bloc.moveUp(); } else if (event is RawKeyUpEvent) { bloc.moveDown(); } return false; } }
pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_key_controlling_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_key_controlling_behavior.dart", "repo_id": "pinball", "token_count": 529 }
1,055
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; /// {@template joint_anchor} /// Non visual [BodyComponent] used to hold a [BodyType.dynamic] in [Joint]s /// with this [BodyType.static]. /// /// It is recommended to use [JointAnchor.body.position] to position the anchor /// point when initializing a [JointDef]. /// /// ```dart /// initialize( /// dynamicBody.body, /// anchor.body, /// dynamicBody.body + anchor.body.position, /// ); /// ``` /// {@endtemplate} class JointAnchor extends BodyComponent with InitialPosition { /// {@macro joint_anchor} JointAnchor(); @override Body createBody() { final bodyDef = BodyDef( position: initialPosition, ); return world.createBody(bodyDef); } }
pinball/packages/pinball_components/lib/src/components/joint_anchor.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/joint_anchor.dart", "repo_id": "pinball", "token_count": 269 }
1,056
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:pinball_components/pinball_components.dart'; part 'multiplier_state.dart'; class MultiplierCubit extends Cubit<MultiplierState> { MultiplierCubit(MultiplierValue multiplierValue) : super(MultiplierState.initial(multiplierValue)); /// Event added when the game's current multiplier changes. void next(int multiplier) { if (state.value.equals(multiplier)) { if (state.spriteState == MultiplierSpriteState.dimmed) { emit(state.copyWith(spriteState: MultiplierSpriteState.lit)); } } else { if (state.spriteState == MultiplierSpriteState.lit) { emit(state.copyWith(spriteState: MultiplierSpriteState.dimmed)); } } } }
pinball/packages/pinball_components/lib/src/components/multiplier/cubit/multiplier_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/multiplier/cubit/multiplier_cubit.dart", "repo_id": "pinball", "token_count": 289 }
1,057
import 'package:bloc/bloc.dart'; part 'signpost_state.dart'; class SignpostCubit extends Cubit<SignpostState> { SignpostCubit() : super(SignpostState.inactive); void onProgressed() { final index = SignpostState.values.indexOf(state); emit( SignpostState.values[(index + 1) % SignpostState.values.length], ); } void onReset() => emit(SignpostState.inactive); bool isFullyProgressed() => state == SignpostState.active3; }
pinball/packages/pinball_components/lib/src/components/signpost/cubit/signpost_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/signpost/cubit/signpost_cubit.dart", "repo_id": "pinball", "token_count": 165 }
1,058
import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template sparky_animatronic} /// Animated Sparky that sits on top of the [SparkyComputer]. /// {@endtemplate} class SparkyAnimatronic extends SpriteAnimationComponent with HasGameRef, ZIndex { /// {@macro sparky_animatronic} SparkyAnimatronic({Iterable<Component>? children}) : super( anchor: Anchor.center, playing: false, children: children, ) { zIndex = ZIndexes.sparkyAnimatronic; } @override Future<void> onLoad() async { await super.onLoad(); final spriteSheet = gameRef.images.fromCache( Assets.images.sparky.animatronic.keyName, ); const amountPerRow = 9; const amountPerColumn = 7; final textureSize = Vector2( spriteSheet.width / amountPerRow, spriteSheet.height / amountPerColumn, ); size = textureSize / 10; animation = SpriteAnimation.fromFrameData( spriteSheet, SpriteAnimationData.sequenced( amount: (amountPerRow * amountPerColumn) - 1, amountPerRow: amountPerRow, stepTime: 1 / 24, textureSize: textureSize, loop: false, ), ); } }
pinball/packages/pinball_components/lib/src/components/sparky_animatronic.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/sparky_animatronic.dart", "repo_id": "pinball", "token_count": 508 }
1,059
name: pinball_components description: Package with the UI game components for the Pinball Game version: 1.0.0+1 publish_to: none environment: sdk: ">=2.16.0 <3.0.0" dependencies: bloc: ^8.0.3 flame: ^1.1.1 flame_bloc: ^1.4.0 flame_forge2d: git: url: https://github.com/flame-engine/flame path: packages/flame_forge2d/ ref: a50d4a1e7d9eaf66726ed1bb9894c9d495547d8f flutter: sdk: flutter intl: ^0.17.0 pinball_audio: path: ../pinball_audio pinball_flame: path: ../pinball_flame pinball_theme: path: ../pinball_theme pinball_ui: path: ../pinball_ui dev_dependencies: bloc_test: ^9.0.3 flame_test: ^1.3.0 flutter_test: sdk: flutter mocktail: ^0.2.0 very_good_analysis: ^2.4.0 flutter: uses-material-design: true generate: true fonts: - family: PixeloidSans fonts: - asset: fonts/PixeloidSans-nR3g1.ttf - asset: fonts/PixeloidSansBold-RpeJo.ttf weight: 700 - family: PixeloidMono fonts: - asset: fonts/PixeloidMono-1G8ae.ttf assets: - assets/images/ - assets/images/ball/ - assets/images/baseboard/ - assets/images/boundary/ - assets/images/dino/ - assets/images/dino/animatronic/ - assets/images/flipper/ - assets/images/launch_ramp/ - assets/images/dash/ - assets/images/dash/bumper/a/ - assets/images/dash/bumper/b/ - assets/images/dash/bumper/main/ - assets/images/android/spaceship/ - assets/images/android/rail/ - assets/images/android/ramp/ - assets/images/android/ramp/arrow/ - assets/images/android/bumper/a/ - assets/images/android/bumper/b/ - assets/images/android/bumper/cow/ - assets/images/kicker/left/ - assets/images/kicker/right/ - assets/images/plunger/ - assets/images/slingshot/ - assets/images/sparky/ - assets/images/sparky/computer/ - assets/images/sparky/bumper/a/ - assets/images/sparky/bumper/b/ - assets/images/sparky/bumper/c/ - assets/images/google_word/letter1/ - assets/images/google_word/letter2/ - assets/images/google_word/letter3/ - assets/images/google_word/letter4/ - assets/images/google_word/letter5/ - assets/images/google_word/letter6/ - assets/images/google_rollover/left/ - assets/images/google_rollover/right/ - assets/images/signpost/ - assets/images/multiball/ - assets/images/multiplier/x2/ - assets/images/multiplier/x3/ - assets/images/multiplier/x4/ - assets/images/multiplier/x5/ - assets/images/multiplier/x6/ - assets/images/score/ - assets/images/backbox/ - assets/images/backbox/button/ - assets/images/flapper/ - assets/images/skill_shot/ - assets/images/display_arrows/ flutter_gen: line_length: 80 assets: package_parameter_enabled: true
pinball/packages/pinball_components/pubspec.yaml/0
{ "file_path": "pinball/packages/pinball_components/pubspec.yaml", "repo_id": "pinball", "token_count": 1246 }
1,060
import 'dart:async'; import 'package:flame/input.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class SpaceshipRailGame extends BallGame { SpaceshipRailGame() : super( ballPriority: ZIndexes.ballOnSpaceshipRail, ballLayer: Layer.spaceshipExitRail, imagesFileNames: [ Assets.images.android.rail.main.keyName, Assets.images.android.rail.exit.keyName, ], ); static const description = ''' Shows how SpaceshipRail are rendered. - Activate the "trace" parameter to overlay the body. - Tap anywhere on the screen to spawn a ball into the game. '''; @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2(-30, -10)); await add(SpaceshipRail()); await ready(); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/android_acres/spaceship_rail_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/android_acres/spaceship_rail_game.dart", "repo_id": "pinball", "token_count": 374 }
1,061
import 'dart:async'; import 'package:flame/input.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class DinoWallsGame extends BallGame { DinoWallsGame() : super(); static const description = ''' Shows how DinoWalls 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(); await images.loadAll([ Assets.images.dino.topWall.keyName, Assets.images.dino.topWallTunnel.keyName, Assets.images.dino.bottomWall.keyName, ]); await add(DinoWalls()); camera.followVector2(Vector2.zero()); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/dino_walls_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/dino_walls_game.dart", "repo_id": "pinball", "token_count": 285 }
1,062
import 'package:flame/input.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class LayerGame extends BallGame with TapDetector { static const description = ''' Shows how Layers work when a Ball hits other components. - Tap anywhere on the screen to spawn a Ball into the game. '''; @override Future<void> onLoad() async { await addAll( [ _BigSquare()..initialPosition = Vector2(30, -40), _SmallSquare()..initialPosition = Vector2(50, -40), _UnlayeredSquare()..initialPosition = Vector2(60, -40), ], ); } } class _BigSquare extends BodyComponent with InitialPosition, Layered { _BigSquare() : super( children: [ _UnlayeredSquare()..initialPosition = Vector2.all(4), _SmallSquare()..initialPosition = Vector2.all(-4), ], ) { paint = Paint() ..color = const Color.fromARGB(255, 8, 218, 241) ..style = PaintingStyle.stroke; layer = Layer.spaceshipEntranceRamp; } @override Body createBody() { final shape = PolygonShape()..setAsBoxXY(16, 16); final fixtureDef = FixtureDef(shape); final bodyDef = BodyDef()..position = initialPosition; return world.createBody(bodyDef)..createFixture(fixtureDef); } } class _SmallSquare extends BodyComponent with InitialPosition, Layered { _SmallSquare() { paint = Paint() ..color = const Color.fromARGB(255, 27, 241, 8) ..style = PaintingStyle.stroke; layer = Layer.board; } @override Body createBody() { final shape = PolygonShape()..setAsBoxXY(2, 2); final fixtureDef = FixtureDef(shape); final bodyDef = BodyDef()..position = initialPosition; return world.createBody(bodyDef)..createFixture(fixtureDef); } } class _UnlayeredSquare extends BodyComponent with InitialPosition { _UnlayeredSquare() { paint = Paint() ..color = const Color.fromARGB(255, 241, 8, 8) ..style = PaintingStyle.stroke; } @override Body createBody() { final shape = PolygonShape()..setAsBoxXY(3, 3); final fixtureDef = FixtureDef(shape); final bodyDef = BodyDef()..position = initialPosition; return world.createBody(bodyDef)..createFixture(fixtureDef); } }
pinball/packages/pinball_components/sandbox/lib/stories/layer/layer_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/layer/layer_game.dart", "repo_id": "pinball", "token_count": 905 }
1,063
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group( 'AndroidSpaceshipCubit', () { blocTest<AndroidSpaceshipCubit, AndroidSpaceshipState>( 'onBallEntered emits withBonus', build: AndroidSpaceshipCubit.new, act: (bloc) => bloc.onBallContacted(), expect: () => [AndroidSpaceshipState.withBonus], ); blocTest<AndroidSpaceshipCubit, AndroidSpaceshipState>( 'onBonusAwarded emits withoutBonus', build: AndroidSpaceshipCubit.new, act: (bloc) => bloc.onBonusAwarded(), expect: () => [AndroidSpaceshipState.withoutBonus], ); }, ); }
pinball/packages/pinball_components/test/src/components/android_spaceship/cubit/android_spaceship_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/android_spaceship/cubit/android_spaceship_cubit_test.dart", "repo_id": "pinball", "token_count": 314 }
1,064
// 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_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; void main() { group('Boundaries', () { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.boundary.outer.keyName, Assets.images.boundary.outerBottom.keyName, Assets.images.boundary.bottom.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.test('loads correctly', (game) async { final component = Boundaries(); await game.ensureAdd(component); expect(game.contains(component), isTrue); }); flameTester.testGameWidget( 'render correctly', setUp: (game, tester) async { await game.images.loadAll(assets); final canvas = ZCanvasComponent(children: [Boundaries()]); await game.ensureAdd(canvas); game.camera.followVector2(Vector2.zero()); game.camera.zoom = 3.2; await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/boundaries.png'), ); }, ); }); }
pinball/packages/pinball_components/test/src/components/boundaries_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/boundaries_test.dart", "repo_id": "pinball", "token_count": 563 }
1,065
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group('DashBumpersState', () { test('supports value equality', () { expect( DashBumpersState( bumperSpriteStates: const { DashBumperId.main: DashBumperSpriteState.active, DashBumperId.a: DashBumperSpriteState.active, DashBumperId.b: DashBumperSpriteState.active, }, ), equals( DashBumpersState( bumperSpriteStates: const { DashBumperId.main: DashBumperSpriteState.active, DashBumperId.a: DashBumperSpriteState.active, DashBumperId.b: DashBumperSpriteState.active, }, ), ), ); }); group('constructor', () { test('can be instantiated', () { expect( const DashBumpersState(bumperSpriteStates: {}), isNotNull, ); }); test('initial has all inactive sprite states', () { const initialState = DashBumpersState( bumperSpriteStates: { DashBumperId.main: DashBumperSpriteState.inactive, DashBumperId.a: DashBumperSpriteState.inactive, DashBumperId.b: DashBumperSpriteState.inactive, }, ); expect(DashBumpersState.initial(), equals(initialState)); }); }); group('isFullyActivated', () { test('returns true when all bumpers have an active state', () { const fullyActivatedState = DashBumpersState( bumperSpriteStates: { DashBumperId.main: DashBumperSpriteState.active, DashBumperId.a: DashBumperSpriteState.active, DashBumperId.b: DashBumperSpriteState.active, }, ); expect(fullyActivatedState.isFullyActivated, isTrue); }); test('returns false when not all bumpers have an active state', () { const notFullyActivatedState = DashBumpersState( bumperSpriteStates: { DashBumperId.main: DashBumperSpriteState.active, DashBumperId.a: DashBumperSpriteState.active, DashBumperId.b: DashBumperSpriteState.inactive, }, ); expect(notFullyActivatedState.isFullyActivated, isFalse); }); }); }); }
pinball/packages/pinball_components/test/src/components/dash_nest_bumper/cubit/dash_bumpers_state_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/dash_nest_bumper/cubit/dash_bumpers_state_test.dart", "repo_id": "pinball", "token_count": 1107 }
1,066
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group( 'GoogleWordCubit', () { final litEvens = { for (int i = 0; i < 6; i++) if (i.isEven) i: GoogleLetterSpriteState.lit else i: GoogleLetterSpriteState.dimmed }; final litOdds = { for (int i = 0; i < 6; i++) if (i.isOdd) i: GoogleLetterSpriteState.lit else i: GoogleLetterSpriteState.dimmed }; blocTest<GoogleWordCubit, GoogleWordState>( 'onRolloverContacted emits first letter lit', build: GoogleWordCubit.new, act: (bloc) => bloc.onRolloverContacted(), expect: () => [ const GoogleWordState( letterSpriteStates: { 0: GoogleLetterSpriteState.lit, 1: GoogleLetterSpriteState.dimmed, 2: GoogleLetterSpriteState.dimmed, 3: GoogleLetterSpriteState.dimmed, 4: GoogleLetterSpriteState.dimmed, 5: GoogleLetterSpriteState.dimmed, }, ), ], ); blocTest<GoogleWordCubit, GoogleWordState>( 'switched emits all even letters lit when first letter is dimmed', build: GoogleWordCubit.new, act: (bloc) => bloc.switched(), expect: () => [GoogleWordState(letterSpriteStates: litEvens)], ); blocTest<GoogleWordCubit, GoogleWordState>( 'switched emits all odd letters lit when first letter is lit', build: GoogleWordCubit.new, seed: () => GoogleWordState(letterSpriteStates: litEvens), act: (bloc) => bloc.switched(), expect: () => [GoogleWordState(letterSpriteStates: litOdds)], ); blocTest<GoogleWordCubit, GoogleWordState>( 'onBonusAwarded emits all even letters lit', build: GoogleWordCubit.new, act: (bloc) => bloc.onBonusAwarded(), expect: () => [GoogleWordState(letterSpriteStates: litEvens)], ); blocTest<GoogleWordCubit, GoogleWordState>( 'onReset emits initial state', build: GoogleWordCubit.new, act: (bloc) => bloc.onReset(), expect: () => [GoogleWordState.initial()], ); }, ); }
pinball/packages/pinball_components/test/src/components/google_word/cubit/google_word_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/google_word/cubit/google_word_cubit_test.dart", "repo_id": "pinball", "token_count": 1086 }
1,067
// ignore_for_file: prefer_const_constructors import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group( 'MultiplierCubit', () { blocTest<MultiplierCubit, MultiplierState>( "emits [lit] when 'next' on x2 dimmed with x2 multiplier value", build: () => MultiplierCubit(MultiplierValue.x2), act: (bloc) => bloc.next(2), expect: () => [ isA<MultiplierState>() ..having( (state) => state.spriteState, 'spriteState', MultiplierSpriteState.lit, ), ], ); blocTest<MultiplierCubit, MultiplierState>( "emits [lit] when 'next' on x3 dimmed with x3 multiplier value", build: () => MultiplierCubit(MultiplierValue.x3), act: (bloc) => bloc.next(3), expect: () => [ isA<MultiplierState>() ..having( (state) => state.spriteState, 'spriteState', MultiplierSpriteState.lit, ), ], ); blocTest<MultiplierCubit, MultiplierState>( "emits [lit] when 'next' on x4 dimmed with x4 multiplier value", build: () => MultiplierCubit(MultiplierValue.x4), act: (bloc) => bloc.next(4), expect: () => [ isA<MultiplierState>() ..having( (state) => state.spriteState, 'spriteState', MultiplierSpriteState.lit, ), ], ); blocTest<MultiplierCubit, MultiplierState>( "emits [lit] when 'next' on x5 dimmed with x5 multiplier value", build: () => MultiplierCubit(MultiplierValue.x5), act: (bloc) => bloc.next(5), expect: () => [ isA<MultiplierState>() ..having( (state) => state.spriteState, 'spriteState', MultiplierSpriteState.lit, ), ], ); blocTest<MultiplierCubit, MultiplierState>( "emits [lit] when 'next' on x6 dimmed with x6 multiplier value", build: () => MultiplierCubit(MultiplierValue.x6), act: (bloc) => bloc.next(6), expect: () => [ isA<MultiplierState>() ..having( (state) => state.spriteState, 'spriteState', MultiplierSpriteState.lit, ), ], ); blocTest<MultiplierCubit, MultiplierState>( "emits [dimmed] when 'next' on lit with different multiplier value", build: () => MultiplierCubit(MultiplierValue.x2), seed: () => MultiplierState( value: MultiplierValue.x2, spriteState: MultiplierSpriteState.lit, ), act: (bloc) => bloc.next(3), expect: () => [ isA<MultiplierState>() ..having( (state) => state.spriteState, 'spriteState', MultiplierSpriteState.dimmed, ), ], ); blocTest<MultiplierCubit, MultiplierState>( "emits nothing when 'next' on lit with same multiplier value", build: () => MultiplierCubit(MultiplierValue.x2), seed: () => MultiplierState( value: MultiplierValue.x2, spriteState: MultiplierSpriteState.lit, ), act: (bloc) => bloc.next(2), expect: () => <MultiplierState>[], ); blocTest<MultiplierCubit, MultiplierState>( "emits nothing when 'next' on dimmed with different multiplier value", build: () => MultiplierCubit(MultiplierValue.x2), act: (bloc) => bloc.next(3), expect: () => <MultiplierState>[], ); }, ); }
pinball/packages/pinball_components/test/src/components/multiplier/cubit/multiplier_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/multiplier/cubit/multiplier_cubit_test.dart", "repo_id": "pinball", "token_count": 1903 }
1,068
// ignore_for_file: cascade_invocations import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/skill_shot/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockSkillShotCubit extends Mock implements SkillShotCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'SkillShotBlinkingBehavior', () { flameTester.testGameWidget( 'calls switched after 0.15 seconds when isBlinking and lit', setUp: (game, tester) async { final behavior = SkillShotBlinkingBehavior(); final bloc = _MockSkillShotCubit(); final streamController = StreamController<SkillShotState>(); whenListen( bloc, streamController.stream, initialState: const SkillShotState.initial(), ); final skillShot = SkillShot.test(bloc: bloc); await skillShot.add(behavior); await game.ensureAdd(skillShot); streamController.add( const SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ), ); await tester.pump(); game.update(0.15); await streamController.close(); verify(bloc.switched).called(1); }, ); flameTester.testGameWidget( 'calls switched after 0.15 seconds when isBlinking and dimmed', setUp: (game, tester) async { final behavior = SkillShotBlinkingBehavior(); final bloc = _MockSkillShotCubit(); final streamController = StreamController<SkillShotState>(); whenListen( bloc, streamController.stream, initialState: const SkillShotState.initial(), ); final skillShot = SkillShot.test(bloc: bloc); await skillShot.add(behavior); await game.ensureAdd(skillShot); streamController.add( const SkillShotState( spriteState: SkillShotSpriteState.dimmed, isBlinking: true, ), ); await tester.pump(); game.update(0.15); await streamController.close(); verify(bloc.switched).called(1); }, ); flameTester.testGameWidget( 'calls onBlinkingFinished after all blinks complete', setUp: (game, tester) async { final behavior = SkillShotBlinkingBehavior(); final bloc = _MockSkillShotCubit(); final streamController = StreamController<SkillShotState>(); whenListen( bloc, streamController.stream, initialState: const SkillShotState.initial(), ); final skillShot = SkillShot.test(bloc: bloc); await skillShot.add(behavior); await game.ensureAdd(skillShot); for (var i = 0; i <= 8; i++) { if (i.isEven) { streamController.add( const SkillShotState( spriteState: SkillShotSpriteState.lit, isBlinking: true, ), ); } else { streamController.add( const SkillShotState( spriteState: SkillShotSpriteState.dimmed, isBlinking: true, ), ); } await tester.pump(); game.update(0.15); } await streamController.close(); verify(bloc.onBlinkingFinished).called(1); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/skill_shot/behaviors/skill_shot_blinking_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/skill_shot/behaviors/skill_shot_blinking_behavior_test.dart", "repo_id": "pinball", "token_count": 1833 }
1,069
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; void main() { group( 'SparkyComputerCubit', () { blocTest<SparkyComputerCubit, SparkyComputerState>( 'onBallEntered emits withBall', build: SparkyComputerCubit.new, act: (bloc) => bloc.onBallEntered(), expect: () => [SparkyComputerState.withBall], ); blocTest<SparkyComputerCubit, SparkyComputerState>( 'onBallTurboCharged emits withoutBall', build: SparkyComputerCubit.new, act: (bloc) => bloc.onBallTurboCharged(), expect: () => [SparkyComputerState.withoutBall], ); }, ); }
pinball/packages/pinball_components/test/src/components/sparky_computer/cubit/sparky_computer_cubit_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/sparky_computer/cubit/sparky_computer_cubit_test.dart", "repo_id": "pinball", "token_count": 312 }
1,070
import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flutter/services.dart'; /// The signature for a key handle function typedef KeyHandlerCallback = bool Function(); /// {@template keyboard_input_controller} /// A [Component] that receives keyboard input and executes registered methods. /// {@endtemplate} class KeyboardInputController extends Component with KeyboardHandler { /// {@macro keyboard_input_controller} KeyboardInputController({ Map<LogicalKeyboardKey, KeyHandlerCallback> keyUp = const {}, Map<LogicalKeyboardKey, KeyHandlerCallback> keyDown = const {}, }) : _keyUp = keyUp, _keyDown = keyDown; final Map<LogicalKeyboardKey, KeyHandlerCallback> _keyUp; final Map<LogicalKeyboardKey, KeyHandlerCallback> _keyDown; /// Trigger a virtual key up event. bool onVirtualKeyUp(LogicalKeyboardKey key) { final handler = _keyUp[key]; if (handler != null) { return handler(); } return true; } @override bool onKeyEvent(RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed) { final isUp = event is RawKeyUpEvent; final handlers = isUp ? _keyUp : _keyDown; final handler = handlers[event.logicalKey]; if (handler != null) { return handler(); } return true; } } /// Add the ability to virtually trigger key events to a [FlameGame]'s /// [KeyboardInputController]. extension VirtualKeyEvents on FlameGame { /// Trigger a key up void triggerVirtualKeyUp(LogicalKeyboardKey key) { final keyControllers = descendants().whereType<KeyboardInputController>(); for (final controller in keyControllers) { if (!controller.onVirtualKeyUp(key)) { break; } } } }
pinball/packages/pinball_flame/lib/src/keyboard_input_controller.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/keyboard_input_controller.dart", "repo_id": "pinball", "token_count": 560 }
1,071
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/material.dart' hide Image; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestCircleComponent extends CircleComponent with ZIndex { _TestCircleComponent(Color color) : super( paint: Paint()..color = color, radius: 10, ); } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('ZCanvasComponent', () { final flameTester = FlameTester(FlameGame.new); const goldensFilePath = '../goldens/rendering/'; test('can be instantiated', () { expect( ZCanvasComponent(), isA<ZCanvasComponent>(), ); }); flameTester.test('loads correctly', (game) async { final component = ZCanvasComponent(); await game.ensureAdd(component); expect(game.contains(component), isTrue); }); flameTester.testGameWidget( 'red circle renders behind blue circle', setUp: (game, tester) async { final canvas = ZCanvasComponent( children: [ _TestCircleComponent(Colors.blue)..zIndex = 1, _TestCircleComponent(Colors.red)..zIndex = 0, ], ); await game.ensureAdd(canvas); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { await expectLater( find.byGame<FlameGame>(), matchesGoldenFile('${goldensFilePath}red_blue.png'), ); }, ); flameTester.testGameWidget( 'blue circle renders behind red circle', setUp: (game, tester) async { final canvas = ZCanvasComponent( children: [ _TestCircleComponent(Colors.blue)..zIndex = 0, _TestCircleComponent(Colors.red)..zIndex = 1 ], ); await game.ensureAdd(canvas); game.camera.followVector2(Vector2.zero()); }, verify: (game, tester) async { await expectLater( find.byGame<FlameGame>(), matchesGoldenFile('${goldensFilePath}blue_red.png'), ); }, ); }); }
pinball/packages/pinball_flame/test/src/canvas/z_canvas_component_test.dart/0
{ "file_path": "pinball/packages/pinball_flame/test/src/canvas/z_canvas_component_test.dart", "repo_id": "pinball", "token_count": 974 }
1,072
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_theme/pinball_theme.dart'; void main() { group('DashTheme', () { test('can be instantiated', () { expect(DashTheme(), isNotNull); }); test('supports value equality', () { expect(DashTheme(), equals(DashTheme())); }); }); }
pinball/packages/pinball_theme/test/src/themes/dash_theme_test.dart/0
{ "file_path": "pinball/packages/pinball_theme/test/src/themes/dash_theme_test.dart", "repo_id": "pinball", "token_count": 139 }
1,073
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** class FontFamily { FontFamily._(); static const String pixeloidMono = 'PixeloidMono'; static const String pixeloidSans = 'PixeloidSans'; }
pinball/packages/pinball_ui/lib/gen/fonts.gen.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/gen/fonts.gen.dart", "repo_id": "pinball", "token_count": 77 }
1,074
export 'animated_ellipsis_text.dart'; export 'crt_background.dart'; export 'pinball_button.dart'; export 'pinball_dpad_button.dart'; export 'pinball_loading_indicator.dart';
pinball/packages/pinball_ui/lib/src/widgets/widgets.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/src/widgets/widgets.dart", "repo_id": "pinball", "token_count": 65 }
1,075
library platform_helper; export 'src/platform_helper.dart';
pinball/packages/platform_helper/lib/platform_helper.dart/0
{ "file_path": "pinball/packages/platform_helper/lib/platform_helper.dart", "repo_id": "pinball", "token_count": 21 }
1,076
import 'package:authentication_repository/authentication_repository.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/app/app.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:share_repository/share_repository.dart'; class _MockAuthenticationRepository extends Mock implements AuthenticationRepository {} class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {} class _MockLeaderboardRepository extends Mock implements LeaderboardRepository { } class _MockShareRepository extends Mock implements ShareRepository {} class _MockPlatformHelper extends Mock implements PlatformHelper { @override bool get isMobile => false; } void main() { group('App', () { late AuthenticationRepository authenticationRepository; late LeaderboardRepository leaderboardRepository; late ShareRepository shareRepository; late PinballAudioPlayer pinballAudioPlayer; late PlatformHelper platformHelper; setUp(() { authenticationRepository = _MockAuthenticationRepository(); leaderboardRepository = _MockLeaderboardRepository(); shareRepository = _MockShareRepository(); pinballAudioPlayer = _MockPinballAudioPlayer(); platformHelper = _MockPlatformHelper(); when(pinballAudioPlayer.load).thenAnswer((_) => [Future.value]); }); testWidgets('renders PinballGamePage', (tester) async { await tester.pumpWidget( App( authenticationRepository: authenticationRepository, leaderboardRepository: leaderboardRepository, shareRepository: shareRepository, pinballAudioPlayer: pinballAudioPlayer, platformHelper: platformHelper, ), ); await tester.pump(const Duration(milliseconds: 1100)); expect(find.byType(PinballGamePage), findsOneWidget); }); }); }
pinball/test/app/view/app_test.dart/0
{ "file_path": "pinball/test/app/view/app_test.dart", "repo_id": "pinball", "token_count": 678 }
1,077
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:pinball/game/game.dart'; void main() { group('GameState', () { test('supports value equality', () { expect( GameState( totalScore: 0, roundScore: 0, multiplier: 1, rounds: 3, bonusHistory: const [], status: GameStatus.waiting, ), equals( const GameState( totalScore: 0, roundScore: 0, multiplier: 1, rounds: 3, bonusHistory: [], status: GameStatus.waiting, ), ), ); }); group('constructor', () { test('can be instantiated', () { expect( const GameState( totalScore: 0, roundScore: 0, multiplier: 1, rounds: 3, bonusHistory: [], status: GameStatus.waiting, ), isNotNull, ); }); }); test( 'throws AssertionError ' 'when totalScore is negative', () { expect( () => GameState( totalScore: -1, roundScore: 0, multiplier: 1, rounds: 3, bonusHistory: const [], status: GameStatus.waiting, ), throwsAssertionError, ); }, ); test( 'throws AssertionError ' 'when roundScore is negative', () { expect( () => GameState( totalScore: 0, roundScore: -1, multiplier: 1, rounds: 3, bonusHistory: const [], status: GameStatus.waiting, ), throwsAssertionError, ); }, ); test( 'throws AssertionError ' 'when multiplier is less than 1', () { expect( () => GameState( totalScore: 0, roundScore: 1, multiplier: 0, rounds: 3, bonusHistory: const [], status: GameStatus.waiting, ), throwsAssertionError, ); }, ); test( 'throws AssertionError ' 'when rounds is negative', () { expect( () => GameState( totalScore: 0, roundScore: 1, multiplier: 1, rounds: -1, bonusHistory: const [], status: GameStatus.waiting, ), throwsAssertionError, ); }, ); group('copyWith', () { test( 'throws AssertionError ' 'when totalScore is decreased', () { const gameState = GameState( totalScore: 2, roundScore: 2, multiplier: 1, rounds: 3, bonusHistory: [], status: GameStatus.waiting, ); expect( () => gameState.copyWith(totalScore: gameState.totalScore - 1), throwsAssertionError, ); }, ); test( 'copies correctly ' 'when no argument specified', () { const gameState = GameState( totalScore: 0, roundScore: 2, multiplier: 1, rounds: 3, bonusHistory: [], status: GameStatus.waiting, ); expect( gameState.copyWith(), equals(gameState), ); }, ); test( 'copies correctly ' 'when all arguments specified', () { const gameState = GameState( totalScore: 0, roundScore: 2, multiplier: 1, rounds: 3, bonusHistory: [], status: GameStatus.waiting, ); final otherGameState = GameState( totalScore: gameState.totalScore + 1, roundScore: gameState.roundScore + 1, multiplier: gameState.multiplier + 1, rounds: gameState.rounds + 1, bonusHistory: const [GameBonus.googleWord], status: GameStatus.playing, ); expect(gameState, isNot(equals(otherGameState))); expect( gameState.copyWith( totalScore: otherGameState.totalScore, roundScore: otherGameState.roundScore, multiplier: otherGameState.multiplier, rounds: otherGameState.rounds, bonusHistory: otherGameState.bonusHistory, status: otherGameState.status, ), equals(otherGameState), ); }, ); }); }); }
pinball/test/game/bloc/game_state_test.dart/0
{ "file_path": "pinball/test/game/bloc/game_state_test.dart", "repo_id": "pinball", "token_count": 2560 }
1,078
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame_forge2d/forge2d_game.dart'; import 'package:flame_test/flame_test.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/displays/leaderboard_display.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' hide Assets; class _MockAppLocalizations extends Mock implements AppLocalizations { @override String get rank => 'rank'; @override String get score => 'score'; @override String get name => 'name'; } class _TestGame extends Forge2DGame with HasTappables { @override Future<void> onLoad() async { await super.onLoad(); images.prefix = ''; await images.loadAll([ const AndroidTheme().leaderboardIcon.keyName, Assets.images.displayArrows.arrowLeft.keyName, Assets.images.displayArrows.arrowRight.keyName, ]); } Future<void> pump(LeaderboardDisplay component) { return ensureAdd( FlameProvider.value( _MockAppLocalizations(), children: [component], ), ); } } const leaderboard = [ LeaderboardEntryData( playerInitials: 'AAA', score: 123, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'BBB', score: 1234, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'CCC', score: 12345, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'DDD', score: 12346, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'EEE', score: 123467, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'FFF', score: 123468, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'GGG', score: 1234689, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'HHH', score: 12346891, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'III', score: 123468912, character: CharacterType.android, ), LeaderboardEntryData( playerInitials: 'JJJ', score: 1234689121, character: CharacterType.android, ), ]; void main() { group('LeaderboardDisplay', () { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); flameTester.test('renders the titles', (game) async { await game.pump(LeaderboardDisplay(entries: const [])); final textComponents = game.descendants().whereType<TextComponent>().toList(); expect(textComponents.length, equals(3)); expect(textComponents[0].text, equals('rank')); expect(textComponents[1].text, equals('score')); expect(textComponents[2].text, equals('name')); }); flameTester.test('renders the first 5 entries', (game) async { await game.pump(LeaderboardDisplay(entries: leaderboard)); for (final text in [ 'AAA', 'BBB', 'CCC', 'DDD', 'EEE', '1st', '2nd', '3rd', '4th', '5th', ]) { expect( game .descendants() .whereType<TextComponent>() .where((textComponent) => textComponent.text == text) .length, equals(1), ); } }); flameTester.test('can open the second page', (game) async { final display = LeaderboardDisplay(entries: leaderboard); await game.pump(display); final arrow = game .descendants() .whereType<ArrowIcon>() .where((arrow) => arrow.direction == ArrowIconDirection.right) .single; // Tap the arrow arrow.onTap(); // Wait for the transition to finish display.updateTree(5); await game.ready(); for (final text in [ 'FFF', 'GGG', 'HHH', 'III', 'JJJ', '6th', '7th', '8th', '9th', '10th', ]) { expect( game .descendants() .whereType<TextComponent>() .where((textComponent) => textComponent.text == text) .length, equals(1), ); } }); flameTester.test( 'can open the second page and go back to the first', (game) async { final display = LeaderboardDisplay(entries: leaderboard); await game.pump(display); var arrow = game .descendants() .whereType<ArrowIcon>() .where((arrow) => arrow.direction == ArrowIconDirection.right) .single; // Tap the arrow arrow.onTap(); // Wait for the transition to finish display.updateTree(5); await game.ready(); for (final text in [ 'FFF', 'GGG', 'HHH', 'III', 'JJJ', '6th', '7th', '8th', '9th', '10th', ]) { expect( game .descendants() .whereType<TextComponent>() .where((textComponent) => textComponent.text == text) .length, equals(1), ); } arrow = game .descendants() .whereType<ArrowIcon>() .where((arrow) => arrow.direction == ArrowIconDirection.left) .single; // Tap the arrow arrow.onTap(); // Wait for the transition to finish display.updateTree(5); await game.ready(); for (final text in [ 'AAA', 'BBB', 'CCC', 'DDD', 'EEE', '1st', '2nd', '3rd', '4th', '5th', ]) { expect( game .descendants() .whereType<TextComponent>() .where((textComponent) => textComponent.text == text) .length, equals(1), ); } }, ); }); }
pinball/test/game/components/backbox/displays/leaderboard_display_test.dart/0
{ "file_path": "pinball/test/game/components/backbox/displays/leaderboard_display_test.dart", "repo_id": "pinball", "token_count": 2995 }
1,079
// ignore_for_file: cascade_invocations, prefer_const_constructors 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/game/components/multiballs/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.multiball.lit.keyName, Assets.images.multiball.dimmed.keyName, ]); } Future<void> pump(Multiballs child, {GameBloc? gameBloc}) { return ensureAdd( FlameBlocProvider<GameBloc, GameState>.value( value: gameBloc ?? GameBloc(), children: [child], ), ); } } class _MockGameBloc extends Mock implements GameBloc {} class _MockMultiballCubit extends Mock implements MultiballCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('MultiballsBehavior', () { final flameTester = FlameTester(_TestGame.new); test('can be instantiated', () { expect( MultiballsBehavior(), isA<MultiballsBehavior>(), ); }); flameTester.test( 'can be loaded', (game) async { final parent = Multiballs.test(); final behavior = MultiballsBehavior(); await game.pump(parent); await parent.ensureAdd(behavior); expect(parent.children, contains(behavior)); }, ); group('listenWhen', () { test( 'is true when the bonusHistory has changed ' 'with a new GameBonus.dashNest', () { final previous = GameState.initial(); final state = previous.copyWith( bonusHistory: [GameBonus.dashNest], ); expect( MultiballsBehavior().listenWhen(previous, state), isTrue, ); }, ); test( 'is true when the bonusHistory has changed ' 'with a new GameBonus.googleWord', () { final previous = GameState.initial(); final state = previous.copyWith( bonusHistory: [GameBonus.googleWord], ); expect( MultiballsBehavior().listenWhen(previous, state), isTrue, ); }, ); test( 'is false when the bonusHistory has changed with a bonus other than ' 'GameBonus.dashNest or GameBonus.googleWord', () { final previous = GameState.initial().copyWith(bonusHistory: [GameBonus.dashNest]); final state = previous.copyWith( bonusHistory: [...previous.bonusHistory, GameBonus.androidSpaceship], ); expect( MultiballsBehavior().listenWhen(previous, state), isFalse, ); }); test('is false when the bonusHistory state is the same', () { final previous = GameState.initial(); final state = GameState( totalScore: 0, roundScore: 10, multiplier: 1, rounds: 0, bonusHistory: const [], status: GameStatus.playing, ); expect( MultiballsBehavior().listenWhen(previous, state), isFalse, ); }); }); group('onNewState', () { late GameBloc gameBloc; setUp(() { gameBloc = _MockGameBloc(); whenListen( gameBloc, Stream<GameState>.empty(), initialState: GameState.initial(), ); }); flameTester.testGameWidget( "calls 'onAnimate' once for every multiball", setUp: (game, tester) async { final behavior = MultiballsBehavior(); final parent = Multiballs.test(); final multiballCubit = _MockMultiballCubit(); final otherMultiballCubit = _MockMultiballCubit(); final multiballs = [ Multiball.test( bloc: multiballCubit, ), Multiball.test( bloc: otherMultiballCubit, ), ]; whenListen( multiballCubit, const Stream<MultiballState>.empty(), initialState: MultiballState.initial(), ); when(multiballCubit.onAnimate).thenAnswer((_) async {}); whenListen( otherMultiballCubit, const Stream<MultiballState>.empty(), initialState: MultiballState.initial(), ); when(otherMultiballCubit.onAnimate).thenAnswer((_) async {}); await parent.addAll(multiballs); await game.pump(parent, gameBloc: gameBloc); await parent.ensureAdd(behavior); await tester.pump(); behavior.onNewState( GameState.initial().copyWith(bonusHistory: [GameBonus.dashNest]), ); for (final multiball in multiballs) { verify( multiball.bloc.onAnimate, ).called(1); } }, ); }); }); }
pinball/test/game/components/multiballs/behaviors/multiballs_behavior_test.dart/0
{ "file_path": "pinball/test/game/components/multiballs/behaviors/multiballs_behavior_test.dart", "repo_id": "pinball", "token_count": 2441 }
1,080
export 'mock_flame_images.dart'; export 'pump_app.dart';
pinball/test/helpers/helpers.dart/0
{ "file_path": "pinball/test/helpers/helpers.dart", "repo_id": "pinball", "token_count": 24 }
1,081
if (typeof firebase === 'undefined') throw new Error('hosting/init-error: Firebase SDK not detected. You must include it before /__/firebase/init.js'); firebase.initializeApp({ "apiKey": "", "appId": "", "authDomain": "", "databaseURL": "", "measurementId": "", "messagingSenderId": "", "projectId": "", "storageBucket": "" });
pinball/web/__/firebase/init.js/0
{ "file_path": "pinball/web/__/firebase/init.js", "repo_id": "pinball", "token_count": 122 }
1,082
// 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.exposureoffset; import android.hardware.camera2.CaptureRequest; import android.util.Range; import androidx.annotation.NonNull; import io.flutter.plugins.camera.CameraProperties; import io.flutter.plugins.camera.features.CameraFeature; /** Controls the exposure offset making the resulting image brighter or darker. */ public class ExposureOffsetFeature extends CameraFeature<Double> { private double currentSetting = 0; /** * Creates a new instance of the {@link ExposureOffsetFeature}. * * @param cameraProperties Collection of the characteristics for the current camera device. */ public ExposureOffsetFeature(CameraProperties cameraProperties) { super(cameraProperties); } @Override public String getDebugName() { return "ExposureOffsetFeature"; } @Override public Double getValue() { return currentSetting; } @Override public void setValue(@NonNull Double value) { double stepSize = getExposureOffsetStepSize(); this.currentSetting = value / stepSize; } // Available on all devices. @Override public boolean checkIsSupported() { return true; } @Override public void updateBuilder(CaptureRequest.Builder requestBuilder) { if (!checkIsSupported()) { return; } requestBuilder.set(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, (int) currentSetting); } /** * Returns the minimum exposure offset. * * @return double Minimum exposure offset. */ public double getMinExposureOffset() { Range<Integer> range = cameraProperties.getControlAutoExposureCompensationRange(); double minStepped = range == null ? 0 : range.getLower(); double stepSize = getExposureOffsetStepSize(); return minStepped * stepSize; } /** * Returns the maximum exposure offset. * * @return double Maximum exposure offset. */ public double getMaxExposureOffset() { Range<Integer> range = cameraProperties.getControlAutoExposureCompensationRange(); double maxStepped = range == null ? 0 : range.getUpper(); double stepSize = getExposureOffsetStepSize(); return maxStepped * stepSize; } /** * Returns the smallest step by which the exposure compensation can be changed. * * <p>Example: if this has a value of 0.5, then an aeExposureCompensation setting of -2 means that * the actual AE offset is -1. More details can be found in the official Android documentation: * https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics.html#CONTROL_AE_COMPENSATION_STEP * * @return double Smallest step by which the exposure compensation can be changed. */ public double getExposureOffsetStepSize() { return cameraProperties.getControlAutoExposureCompensationStep(); } }
plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposureoffset/ExposureOffsetFeature.java/0
{ "file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/exposureoffset/ExposureOffsetFeature.java", "repo_id": "plugins", "token_count": 863 }
1,083
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.camerax; import androidx.camera.core.Camera; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraFlutterApi; public class CameraFlutterApiImpl extends CameraFlutterApi { private final InstanceManager instanceManager; public CameraFlutterApiImpl(BinaryMessenger binaryMessenger, InstanceManager instanceManager) { super(binaryMessenger); this.instanceManager = instanceManager; } void create(Camera camera, Reply<Void> reply) { create(instanceManager.addHostCreatedInstance(camera), reply); } }
plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraFlutterApiImpl.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraFlutterApiImpl.java", "repo_id": "plugins", "token_count": 224 }
1,084
// 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.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.CameraInfo; import io.flutter.plugin.common.BinaryMessenger; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class CameraInfoTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock public CameraInfo mockCameraInfo; @Mock public BinaryMessenger mockBinaryMessenger; InstanceManager testInstanceManager; @Before public void setUp() { testInstanceManager = InstanceManager.open(identifier -> {}); } @After public void tearDown() { testInstanceManager.close(); } @Test public void getSensorRotationDegreesTest() { final CameraInfoHostApiImpl cameraInfoHostApi = new CameraInfoHostApiImpl(testInstanceManager); testInstanceManager.addDartCreatedInstance(mockCameraInfo, 1); when(mockCameraInfo.getSensorRotationDegrees()).thenReturn(90); assertEquals((long) cameraInfoHostApi.getSensorRotationDegrees(1L), 90L); verify(mockCameraInfo).getSensorRotationDegrees(); } @Test public void flutterApiCreateTest() { final CameraInfoFlutterApiImpl spyFlutterApi = spy(new CameraInfoFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); spyFlutterApi.create(mockCameraInfo, reply -> {}); final long identifier = Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(mockCameraInfo)); verify(spyFlutterApi).create(eq(identifier), any()); } }
plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraInfoTest.java/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraInfoTest.java", "repo_id": "plugins", "token_count": 685 }
1,085
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart' show BinaryMessenger; import 'camerax_library.g.dart'; import 'instance_manager.dart'; import 'java_object.dart'; import 'use_case.dart'; /// Use case that provides a camera preview stream for display. /// /// See https://developer.android.com/reference/androidx/camera/core/Preview. class Preview extends UseCase { /// Creates a [Preview]. Preview( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, this.targetRotation, this.targetResolution}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = PreviewHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); _api.createFromInstance(this, targetRotation, targetResolution); } /// Constructs a [Preview] that is not automatically attached to a native object. Preview.detached( {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, this.targetRotation, this.targetResolution}) : super.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager) { _api = PreviewHostApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager); } late final PreviewHostApiImpl _api; /// Target rotation of the camera used for the preview stream. final int? targetRotation; /// Target resolution of the camera preview stream. final ResolutionInfo? targetResolution; /// Sets the surface provider for the preview stream. /// /// Returns the ID of the FlutterSurfaceTextureEntry used on the native end /// used to display the preview stream on a [Texture] of the same ID. Future<int> setSurfaceProvider() { return _api.setSurfaceProviderFromInstance(this); } /// Releases Flutter surface texture used to provide a surface for the preview /// stream. void releaseFlutterSurfaceTexture() { _api.releaseFlutterSurfaceTextureFromInstance(); } /// Retrieves the selected resolution information of this [Preview]. Future<ResolutionInfo> getResolutionInfo() { return _api.getResolutionInfoFromInstance(this); } } /// Host API implementation of [Preview]. class PreviewHostApiImpl extends PreviewHostApi { /// Constructs a [PreviewHostApiImpl]. PreviewHostApiImpl({this.binaryMessenger, InstanceManager? instanceManager}) { this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; } /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. late final InstanceManager instanceManager; /// Creates a [Preview] with the target rotation provided if specified. void createFromInstance( Preview instance, int? targetRotation, ResolutionInfo? targetResolution) { final int identifier = instanceManager.addDartCreatedInstance(instance, onCopy: (Preview original) { return Preview.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, targetRotation: original.targetRotation); }); create(identifier, targetRotation, targetResolution); } /// Sets the surface provider of the specified [Preview] instance and returns /// the ID corresponding to the surface it will provide. Future<int> setSurfaceProviderFromInstance(Preview instance) async { final int? identifier = instanceManager.getIdentifier(instance); assert(identifier != null, 'No Preview has the identifer of that requested to set the surface provider on.'); final int surfaceTextureEntryId = await setSurfaceProvider(identifier!); return surfaceTextureEntryId; } /// Releases Flutter surface texture used to provide a surface for the preview /// stream if a surface provider was set for a [Preview] instance. void releaseFlutterSurfaceTextureFromInstance() { releaseFlutterSurfaceTexture(); } /// Gets the resolution information of the specified [Preview] instance. Future<ResolutionInfo> getResolutionInfoFromInstance(Preview instance) async { final int? identifier = instanceManager.getIdentifier(instance); assert(identifier != null, 'No Preview has the identifer of that requested to get the resolution information for.'); final ResolutionInfo resolutionInfo = await getResolutionInfo(identifier!); return resolutionInfo; } }
plugins/packages/camera/camera_android_camerax/lib/src/preview.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/lib/src/preview.dart", "repo_id": "plugins", "token_count": 1389 }
1,086
// Mocks generated by Mockito 5.3.2 from annotations // in camera_android_camerax/test/preview_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'test_camerax_library.g.dart' as _i3; // 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, ); } /// A class which mocks [TestPreviewHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestPreviewHostApi extends _i1.Mock implements _i3.TestPreviewHostApi { MockTestPreviewHostApi() { _i1.throwOnMissingStub(this); } @override void create( int? identifier, int? rotation, _i2.ResolutionInfo? targetResolution, ) => super.noSuchMethod( Invocation.method( #create, [ identifier, rotation, targetResolution, ], ), returnValueForMissingStub: null, ); @override int setSurfaceProvider(int? identifier) => (super.noSuchMethod( Invocation.method( #setSurfaceProvider, [identifier], ), returnValue: 0, ) as int); @override void releaseFlutterSurfaceTexture() => super.noSuchMethod( Invocation.method( #releaseFlutterSurfaceTexture, [], ), returnValueForMissingStub: null, ); @override _i2.ResolutionInfo getResolutionInfo(int? identifier) => (super.noSuchMethod( Invocation.method( #getResolutionInfo, [identifier], ), returnValue: _FakeResolutionInfo_0( this, Invocation.method( #getResolutionInfo, [identifier], ), ), ) as _i2.ResolutionInfo); }
plugins/packages/camera/camera_android_camerax/test/preview_test.mocks.dart/0
{ "file_path": "plugins/packages/camera/camera_android_camerax/test/preview_test.mocks.dart", "repo_id": "plugins", "token_count": 1063 }
1,087
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import camera_avfoundation; @import XCTest; @import AVFoundation; #import <OCMock/OCMock.h> @interface FLTCam : NSObject <FlutterTexture, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate> - (void)setExposurePointWithResult:(FlutterResult)result x:(double)x y:(double)y; @end @interface CameraExposureTests : XCTestCase @property(readonly, nonatomic) FLTCam *camera; @property(readonly, nonatomic) id mockDevice; @property(readonly, nonatomic) id mockUIDevice; @end @implementation CameraExposureTests - (void)setUp { _camera = [[FLTCam alloc] init]; _mockDevice = OCMClassMock([AVCaptureDevice class]); _mockUIDevice = OCMPartialMock([UIDevice currentDevice]); } - (void)tearDown { [_mockDevice stopMocking]; [_mockUIDevice stopMocking]; } - (void)testSetExpsourePointWithResult_SetsExposurePointOfInterest { // UI is currently in landscape left orientation OCMStub([(UIDevice *)_mockUIDevice orientation]).andReturn(UIDeviceOrientationLandscapeLeft); // Exposure point of interest is supported OCMStub([_mockDevice isExposurePointOfInterestSupported]).andReturn(true); // Set mock device as the current capture device [_camera setValue:_mockDevice forKey:@"captureDevice"]; // Run test [_camera setExposurePointWithResult:^void(id _Nullable result) { } x:1 y:1]; // Verify the focus point of interest has been set OCMVerify([_mockDevice setExposurePointOfInterest:CGPointMake(1, 1)]); } @end
plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraExposureTests.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraExposureTests.m", "repo_id": "plugins", "token_count": 665 }
1,088
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import camera_avfoundation; @import XCTest; @interface QueueUtilsTests : XCTestCase @end @implementation QueueUtilsTests - (void)testShouldStayOnMainQueueIfCalledFromMainQueue { XCTestExpectation *expectation = [self expectationWithDescription:@"Block must be run on the main queue."]; FLTEnsureToRunOnMainQueue(^{ if (NSThread.isMainThread) { [expectation fulfill]; } }); [self waitForExpectationsWithTimeout:1 handler:nil]; } - (void)testShouldDispatchToMainQueueIfCalledFromBackgroundQueue { XCTestExpectation *expectation = [self expectationWithDescription:@"Block must be run on the main queue."]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ FLTEnsureToRunOnMainQueue(^{ if (NSThread.isMainThread) { [expectation fulfill]; } }); }); [self waitForExpectationsWithTimeout:1 handler:nil]; } @end
plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/QueueUtilsTests.m/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/QueueUtilsTests.m", "repo_id": "plugins", "token_count": 383 }
1,089
framework module camera_avfoundation { umbrella header "camera_avfoundation-umbrella.h" export * module * { export * } explicit module Test { header "CameraPlugin_Test.h" header "CameraPermissionUtils.h" header "CameraProperties.h" header "FLTCam.h" header "FLTCam_Test.h" header "FLTSavePhotoDelegate_Test.h" header "FLTThreadSafeEventChannel.h" header "FLTThreadSafeFlutterResult.h" header "FLTThreadSafeMethodChannel.h" header "FLTThreadSafeTextureRegistry.h" header "QueueUtils.h" } }
plugins/packages/camera/camera_avfoundation/ios/Classes/CameraPlugin.modulemap/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/CameraPlugin.modulemap", "repo_id": "plugins", "token_count": 202 }
1,090
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN /** * A thread safe wrapper for FlutterTextureRegistry that can be called from any thread, by * dispatching its underlying engine calls to the main thread. */ @interface FLTThreadSafeTextureRegistry : NSObject /** * Creates a FLTThreadSafeTextureRegistry by wrapping an object conforming to * FlutterTextureRegistry. * @param registry The FlutterTextureRegistry object to be wrapped. */ - (instancetype)initWithTextureRegistry:(NSObject<FlutterTextureRegistry> *)registry; /** * Registers a `FlutterTexture` on the main thread for usage in Flutter and returns an id that can * be used to reference that texture when calling into Flutter with channels. * * On success the completion block completes with the pointer to the registered texture, else with * 0. The completion block runs on the main thread. */ - (void)registerTexture:(NSObject<FlutterTexture> *)texture completion:(void (^)(int64_t))completion; /** * Notifies the Flutter engine on the main thread that the given texture has been updated. */ - (void)textureFrameAvailable:(int64_t)textureId; /** * Notifies the Flutter engine on the main thread to unregister a `FlutterTexture` that has been * previously registered with `registerTexture:`. * @param textureId The result that was previously returned from `registerTexture:`. */ - (void)unregisterTexture:(int64_t)textureId; @end NS_ASSUME_NONNULL_END
plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeTextureRegistry.h/0
{ "file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeTextureRegistry.h", "repo_id": "plugins", "token_count": 449 }
1,091
## 2.4.0 * Allows camera to be switched while video recording. * Updates minimum Flutter version to 3.0. ## 2.3.4 * Updates code for stricter lint checks. ## 2.3.3 * Updates code for stricter lint checks. ## 2.3.2 * Updates MethodChannelCamera to have startVideoRecording call the newer startVideoCapturing. ## 2.3.1 * Exports VideoCaptureOptions to allow dependencies to implement concurrent stream and record. ## 2.3.0 * Adds new capture method for a camera to allow concurrent streaming and recording. ## 2.2.2 * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 2.2.1 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231). * Ignores missing return warnings in preparation for [upcoming analysis changes](https://github.com/flutter/flutter/issues/105750). ## 2.2.0 * Adds image streaming to the platform interface. * Removes unnecessary imports. ## 2.1.6 * Adopts `Object.hash`. * Removes obsolete dependency on `pedantic`. ## 2.1.5 * Fixes asynchronous exceptions handling of the `initializeCamera` method. ## 2.1.4 * Removes dependency on `meta`. ## 2.1.3 * Update to use the `verify` method introduced in platform_plugin_interface 2.1.0. ## 2.1.2 * Adopts new analysis options and fixes all violations. ## 2.1.1 * Add web-relevant docs to platform interface code. ## 2.1.0 * Introduces interface methods for pausing and resuming the camera preview. ## 2.0.1 * Update platform_plugin_interface version requirement. ## 2.0.0 - Stable null safety release. ## 1.6.0 - Added VideoRecordedEvent to support ending a video recording in the native implementation. ## 1.5.0 - Introduces interface methods for locking and unlocking the capture orientation. - Introduces interface method for listening to the device orientation. ## 1.4.0 - Added interface methods to support auto focus. ## 1.3.0 - Introduces an option to set the image format when initializing. ## 1.2.0 - Added interface to support automatic exposure. ## 1.1.0 - Added an optional `maxVideoDuration` parameter to the `startVideoRecording` method, which allows implementations to limit the duration of a video recording. ## 1.0.4 - Added the torch option to the FlashMode enum, which when implemented indicates the flash light should be turned on continuously. ## 1.0.3 - Update Flutter SDK constraint. ## 1.0.2 - Added interface methods to support zoom features. ## 1.0.1 - Added interface methods for setting flash mode. ## 1.0.0 - Initial open-source release
plugins/packages/camera/camera_platform_interface/CHANGELOG.md/0
{ "file_path": "plugins/packages/camera/camera_platform_interface/CHANGELOG.md", "repo_id": "plugins", "token_count": 813 }
1,092
// 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. /// Affect the quality of video recording and image capture: /// /// If a preset is not available on the camera being used a preset of lower quality will be selected automatically. enum ResolutionPreset { /// 352x288 on iOS, 240p (320x240) on Android and Web low, /// 480p (640x480 on iOS, 720x480 on Android and Web) medium, /// 720p (1280x720) high, /// 1080p (1920x1080) veryHigh, /// 2160p (3840x2160 on Android and iOS, 4096x2160 on Web) ultraHigh, /// The highest resolution available. max, }
plugins/packages/camera/camera_platform_interface/lib/src/types/resolution_preset.dart/0
{ "file_path": "plugins/packages/camera/camera_platform_interface/lib/src/types/resolution_preset.dart", "repo_id": "plugins", "token_count": 206 }
1,093
// 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. @testable import file_selector_macos import FlutterMacOS import XCTest class TestPanelController: NSObject, PanelController { // The last panels that the relevant display methods were called on. public var savePanel: NSSavePanel? public var openPanel: NSOpenPanel? // Mock return values for the display methods. public var saveURL: URL? public var openURLs: [URL]? func display(_ panel: NSSavePanel, for window: NSWindow?, completionHandler handler: @escaping (URL?) -> Void) { savePanel = panel handler(saveURL) } func display(_ panel: NSOpenPanel, for window: NSWindow?, completionHandler handler: @escaping ([URL]?) -> Void) { openPanel = panel handler(openURLs) } } class TestViewProvider: NSObject, ViewProvider { var view: NSView? { get { window?.contentView } } var window: NSWindow? = NSWindow() } class exampleTests: XCTestCase { func testOpenSimple() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let returnPath = "/foo/bar" panelController.openURLs = [URL(fileURLWithPath: returnPath)] let called = XCTestExpectation() let options = OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions()) plugin.displayOpenPanel(options: options) { paths in XCTAssertEqual(paths[0], returnPath) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.openPanel) if let panel = panelController.openPanel { XCTAssertTrue(panel.canChooseFiles) // For consistency across platforms, directory selection is disabled. XCTAssertFalse(panel.canChooseDirectories) } } func testOpenWithArguments() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let returnPath = "/foo/bar" panelController.openURLs = [URL(fileURLWithPath: returnPath)] let called = XCTestExpectation() let options = OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions( directoryPath: "/some/dir", nameFieldStringValue: "a name", prompt: "Open it!")) plugin.displayOpenPanel(options: options) { paths in XCTAssertEqual(paths[0], returnPath) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.openPanel) if let panel = panelController.openPanel { XCTAssertEqual(panel.directoryURL?.path, "/some/dir") XCTAssertEqual(panel.nameFieldStringValue, "a name") XCTAssertEqual(panel.prompt, "Open it!") } } func testOpenMultiple() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let returnPaths = ["/foo/bar", "/foo/baz"] panelController.openURLs = returnPaths.map({ path in URL(fileURLWithPath: path) }) let called = XCTestExpectation() let options = OpenPanelOptions( allowsMultipleSelection: true, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions()) plugin.displayOpenPanel(options: options) { paths in XCTAssertEqual(paths.count, returnPaths.count) XCTAssertEqual(paths[0], returnPaths[0]) XCTAssertEqual(paths[1], returnPaths[1]) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.openPanel) } func testOpenWithFilter() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let returnPath = "/foo/bar" panelController.openURLs = [URL(fileURLWithPath: returnPath)] let called = XCTestExpectation() let options = OpenPanelOptions( allowsMultipleSelection: true, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions( allowedFileTypes: AllowedTypes( extensions: ["txt", "json"], mimeTypes: [], utis: ["public.text", "public.image"]))) plugin.displayOpenPanel(options: options) { paths in XCTAssertEqual(paths[0], returnPath) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.openPanel) if let panel = panelController.openPanel { XCTAssertEqual(panel.allowedFileTypes, ["txt", "json", "public.text", "public.image"]) } } func testOpenCancel() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let called = XCTestExpectation() let options = OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: false, canChooseFiles: true, baseOptions: SavePanelOptions()) plugin.displayOpenPanel(options: options) { paths in XCTAssertEqual(paths.count, 0) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.openPanel) } func testSaveSimple() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let returnPath = "/foo/bar" panelController.saveURL = URL(fileURLWithPath: returnPath) let called = XCTestExpectation() let options = SavePanelOptions() plugin.displaySavePanel(options: options) { path in XCTAssertEqual(path, returnPath) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.savePanel) } func testSaveWithArguments() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let returnPath = "/foo/bar" panelController.saveURL = URL(fileURLWithPath: returnPath) let called = XCTestExpectation() let options = SavePanelOptions( directoryPath: "/some/dir", prompt: "Save it!") plugin.displaySavePanel(options: options) { path in XCTAssertEqual(path, returnPath) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.savePanel) if let panel = panelController.savePanel { XCTAssertEqual(panel.directoryURL?.path, "/some/dir") XCTAssertEqual(panel.prompt, "Save it!") } } func testSaveCancel() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let called = XCTestExpectation() let options = SavePanelOptions() plugin.displaySavePanel(options: options) { path in XCTAssertNil(path) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.savePanel) } func testGetDirectorySimple() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let returnPath = "/foo/bar" panelController.openURLs = [URL(fileURLWithPath: returnPath)] let called = XCTestExpectation() let options = OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: true, canChooseFiles: false, baseOptions: SavePanelOptions()) plugin.displayOpenPanel(options: options) { paths in XCTAssertEqual(paths[0], returnPath) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.openPanel) if let panel = panelController.openPanel { XCTAssertTrue(panel.canChooseDirectories) // For consistency across platforms, file selection is disabled. XCTAssertFalse(panel.canChooseFiles) // The Dart API only allows a single directory to be returned, so users shouldn't be allowed // to select multiple. XCTAssertFalse(panel.allowsMultipleSelection) } } func testGetDirectoryCancel() throws { let panelController = TestPanelController() let plugin = FileSelectorPlugin( viewProvider: TestViewProvider(), panelController: panelController) let called = XCTestExpectation() let options = OpenPanelOptions( allowsMultipleSelection: false, canChooseDirectories: true, canChooseFiles: false, baseOptions: SavePanelOptions()) plugin.displayOpenPanel(options: options) { paths in XCTAssertEqual(paths.count, 0) called.fulfill() } wait(for: [called], timeout: 0.5) XCTAssertNotNil(panelController.openPanel) } }
plugins/packages/file_selector/file_selector_macos/example/macos/RunnerTests/RunnerTests.swift/0
{ "file_path": "plugins/packages/file_selector/file_selector_macos/example/macos/RunnerTests/RunnerTests.swift", "repo_id": "plugins", "token_count": 3306 }
1,094
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:html'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:file_selector_web/src/dom_helper.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; void main() { group('dom_helper', () { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); late DomHelper domHelper; late FileUploadInputElement input; FileList? createFileList(List<File> files) { final DataTransfer dataTransfer = DataTransfer(); files.forEach(dataTransfer.items!.add); return dataTransfer.files as FileList?; } void setFilesAndTriggerChange(List<File> files) { input.files = createFileList(files); input.dispatchEvent(Event('change')); } setUp(() { domHelper = DomHelper(); input = FileUploadInputElement(); }); group('getFiles', () { final File mockFile1 = File(<Object>['123456'], 'file1.txt'); final File mockFile2 = File(<Object>[], 'file2.txt'); testWidgets('works', (_) async { final Future<List<XFile>> futureFiles = domHelper.getFiles( input: input, ); setFilesAndTriggerChange(<File>[mockFile1, mockFile2]); final List<XFile> files = await futureFiles; expect(files.length, 2); expect(files[0].name, 'file1.txt'); expect(await files[0].length(), 6); expect(await files[0].readAsString(), '123456'); expect(await files[0].lastModified(), isNotNull); expect(files[1].name, 'file2.txt'); expect(await files[1].length(), 0); expect(await files[1].readAsString(), ''); expect(await files[1].lastModified(), isNotNull); }); testWidgets('works multiple times', (_) async { Future<List<XFile>> futureFiles; List<XFile> files; // It should work the first time futureFiles = domHelper.getFiles(input: input); setFilesAndTriggerChange(<File>[mockFile1]); files = await futureFiles; expect(files.length, 1); expect(files.first.name, mockFile1.name); // The same input should work more than once futureFiles = domHelper.getFiles(input: input); setFilesAndTriggerChange(<File>[mockFile2]); files = await futureFiles; expect(files.length, 1); expect(files.first.name, mockFile2.name); }); testWidgets('sets the <input /> attributes and clicks it', (_) async { const String accept = '.jpg,.png'; const bool multiple = true; bool wasClicked = false; //ignore: unawaited_futures input.onClick.first.then((_) => wasClicked = true); final Future<List<XFile>> futureFile = domHelper.getFiles( accept: accept, multiple: multiple, input: input, ); expect(input.matchesWithAncestors('body'), true); expect(input.accept, accept); expect(input.multiple, multiple); expect( wasClicked, true, reason: 'The <input /> should be clicked otherwise no dialog will be shown', ); setFilesAndTriggerChange(<File>[]); await futureFile; // It should be already removed from the DOM after the file is resolved. expect(input.parent, isNull); }); }); }); }
plugins/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart/0
{ "file_path": "plugins/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart", "repo_id": "plugins", "token_count": 1433 }
1,095
## NEXT * Updates minimum Flutter version to 3.0. ## 2.2.3 * Fixes a minor syntax error in `README.md`. ## 2.2.2 * Modified `README.md` to fix minor syntax issues and added Code Excerpt to `README.md`. * Updates code for new analysis options. * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 2.2.1 * Updates imports for `prefer_relative_imports`. ## 2.2.0 * Deprecates `AndroidGoogleMapsFlutter.useAndroidViewSurface` in favor of [setting the flag directly in the Android implementation](https://pub.dev/packages/google_maps_flutter_android#display-mode). * Updates minimum Flutter version to 2.10. ## 2.1.12 * Fixes violations of new analysis option use_named_constants. ## 2.1.11 * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Moves Android and iOS implementations to federated packages. ## 2.1.10 * Avoids map shift when scrolling on iOS. ## 2.1.9 * Updates integration tests to use the new inspector interface. * Removes obsolete test-only method for accessing a map controller's method channel. * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316). ## 2.1.8 * Switches to new platform interface versions of `buildView` and `updateOptions`. * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231). ## 2.1.7 * Objective-C code cleanup. ## 2.1.6 * Fixes issue in Flutter v3.0.0 where some updates to the map don't take effect on Android. * Fixes iOS native unit tests on M1 devices. * Minor fixes for new analysis options. ## 2.1.5 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.1.4 * Updates Android Google maps sdk version to `18.0.2`. * Adds OS version support information to README. ## 2.1.3 * Fixes iOS crash on `EXC_BAD_ACCESS KERN_PROTECTION_FAILURE` if the map frame changes long after creation. ## 2.1.2 * Removes dependencies from `pubspec.yaml` that are only needed in `example/pubspec.yaml` * Updates Android compileSdkVersion to 31. * Internal code cleanup for stricter analysis options. ## 2.1.1 * Suppresses unchecked cast warning. ## 2.1.0 * Add iOS unit and UI integration test targets. * Provide access to Hybrid Composition on Android through the `GoogleMap` widget. ## 2.0.11 * Add additional marker drag events. ## 2.0.10 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. ## 2.0.9 * Fix Android `NullPointerException` caused by the `GoogleMapController` being disposed before `GoogleMap` was ready. ## 2.0.8 * Mark iOS arm64 simulators as unsupported. ## 2.0.7 * Add iOS unit and UI integration test targets. * Exclude arm64 simulators in example app. * Remove references to the Android V1 embedding. ## 2.0.6 * Migrate maven repo from jcenter to mavenCentral. ## 2.0.5 * Google Maps requires at least Android SDK 20. ## 2.0.4 * Unpin iOS GoogleMaps pod dependency version. ## 2.0.3 * Fix incorrect typecast in TileOverlay example. * Fix english wording in instructions. ## 2.0.2 * Update flutter\_plugin\_android\_lifecycle dependency to 2.0.1 to fix an R8 issue on some versions. ## 2.0.1 * Update platform\_plugin\_interface version requirement. ## 2.0.0 * Migrate to null-safety * BREAKING CHANGE: Passing an unknown map object ID (e.g., MarkerId) to a method, it will throw an `UnknownMapObjectIDError`. Previously it would either silently do nothing, or throw an error trying to call a function on `null`, depneding on the method. ## 1.2.0 * Support custom tiles. ## 1.1.1 * Fix in example app to properly place polyline at initial camera position. ## 1.1.0 * Add support for holes in Polygons. ## 1.0.10 * Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets. ## 1.0.9 * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) ## 1.0.8 * Update Flutter SDK constraint. ## 1.0.7 * Android: Handle deprecation & unchecked warning as error. ## 1.0.6 * Update Dart SDK constraint in example. * Remove unused `test` dependency in the example app. ## 1.0.5 Overhaul lifecycle management in GoogleMapsPlugin. GoogleMapController is now uniformly driven by implementing `DefaultLifecycleObserver`. That observer is registered to a lifecycle from one of three sources: 1. For v2 plugin registration, `GoogleMapsPlugin` obtains the lifecycle via `ActivityAware` methods. 2. For v1 plugin registration, if the activity implements `LifecycleOwner`, it's lifecycle is used directly. 3. For v1 plugin registration, if the activity does not implement `LifecycleOwner`, a proxy lifecycle is created and driven via `ActivityLifecycleCallbacks`. ## 1.0.4 * Cleanup of Android code: * A few minor formatting changes and additions of `@Nullable` annotations. * Removed pass-through of `activityHashCode` to `GoogleMapController`. * Replaced custom lifecycle state ints with `androidx.lifecycle.Lifecycle.State` enum. * Fixed a bug where the Lifecycle object was being leaked `onDetachFromActivity`, by nulling out the field. * Moved GoogleMapListener to its own file. Declaring multiple top level classes in the same file is discouraged. ## 1.0.3 * Update android compileSdkVersion to 29. ## 1.0.2 * Remove `io.flutter.embedded_views_preview` requirement from readme. ## 1.0.1 * Fix headline in the readme. ## 1.0.0 - Out of developer preview 🎉. * Bump the minimal Flutter SDK to 1.22 where platform views are out of developer preview and performing better on iOS. Flutter 1.22 no longer requires adding the `io.flutter.embedded_views_preview` to `Info.plist` in iOS. ## 0.5.33 * Keep handling deprecated Android v1 classes for backward compatibility. ## 0.5.32 * Fix typo in google_maps_flutter/example/map_ui.dart. ## 0.5.31 * Geodesic Polyline support for iOS ## 0.5.30 * Add a `dispose` method to the controller to let the native side know that we're done with said controller. * Call `controller.dispose()` from the `dispose` method of the `GoogleMap` widget. ## 0.5.29+1 * (ios) Pin dependency on GoogleMaps pod to `< 3.10`, to address https://github.com/flutter/flutter/issues/63447 ## 0.5.29 * Pass a constant `_web_only_mapCreationId` to `platform.buildView`, so web can return a cached widget DOM when flutter attempts to repaint there. * Modify some examples slightly so they're more web-friendly. ## 0.5.28+2 * Move test introduced in #2449 to its right location. ## 0.5.28+1 * Android: Make sure map view only calls onDestroy once. * Android: Fix a memory leak regression caused in `0.5.26+4`. ## 0.5.28 * Android: Add liteModeEnabled option. ## 0.5.27+3 * iOS: Update the gesture recognizer blocking policy to "WaitUntilTouchesEnded", which fixes the camera idle callback not triggered issue. * Update the min flutter version to 1.16.3. * Skip `testTakeSnapshot` test on Android. ## 0.5.27+2 * Update lower bound of dart dependency to 2.1.0. ## 0.5.27+1 * Remove endorsement of `web` platform, it's not ready yet. ## 0.5.27 * Migrate the core plugin to use `google_maps_flutter_platform_interface` APIs. ## 0.5.26+4 * Android: Fix map view crash when "exit app" while using `FragmentActivity`. * Android: Remove listeners from `GoogleMap` when disposing. ## 0.5.26+3 * iOS: observe the bounds update for the `GMSMapView` to reset the camera setting. * Update UI related e2e tests to wait for camera update on the platform thread. ## 0.5.26+2 * Fix UIKit availability warnings and CocoaPods podspec lint warnings. ## 0.5.26+1 * Removes an erroneously added method from the GoogleMapController.h header file. ## 0.5.26 * Adds support for toggling zoom controls (Android only) ## 0.5.25+3 * Rename 'Page' in the example app to avoid type conflict with the Flutter Framework. ## 0.5.25+2 * Avoid unnecessary map elements updates by ignoring not platform related attributes (eg. onTap) ## 0.5.25+1 * Add takeSnapshot that takes a snapshot of the map. ## 0.5.25 * Add an optional param `mipmaps` for `BitmapDescriptor.fromAssetImage`. ## 0.5.24+1 * Make the pedantic dev_dependency explicit. ## 0.5.24 * Exposed `getZoomLevel` in `GoogleMapController`. ## 0.5.23+1 * Move core plugin to its own subdirectory, to prepare for federation. ## 0.5.23 * Add methods to programmatically control markers info windows. ## 0.5.22+3 * Fix polygon and circle stroke width according to device density ## 0.5.22+2 * Update README: Add steps to enable Google Map SDK in the Google Developer Console. ## 0.5.22+1 * Fix for toggling traffic layer on Android not working ## 0.5.22 * Support Android v2 embedding. * Bump the min flutter version to `1.12.13+hotfix.5`. * Fixes some e2e tests on Android. ## 0.5.21+17 * Fix Swift example in README.md. ## 0.5.21+16 * Fixed typo in LatLng's documentation. ## 0.5.21+15 * Remove the deprecated `author:` field from pubspec.yaml * Migrate the plugin to the pubspec platforms manifest. * Require Flutter SDK 1.10.0 or greater. ## 0.5.21+14 * Adds support for toggling 3D buildings. ## 0.5.21+13 * Add documentation. ## 0.5.21+12 * Update driver tests in the example app to e2e tests. ## 0.5.21+11 * Define clang module for iOS, fix analyzer warnings. ## 0.5.21+10 * Cast error.code to unsigned long to avoid using NSInteger as %ld format warnings. ## 0.5.21+9 * Remove AndroidX warnings. ## 0.5.21+8 * Add NS*ASSUME_NONNULL*\* macro to reduce iOS compiler warnings. ## 0.5.21+7 * Create a clone of cached elements in GoogleMap (Polyline, Polygon, etc.) to detect modifications if these objects are mutated instead of modified by copy. ## 0.5.21+6 * Override a default method to work around flutter/flutter#40126. ## 0.5.21+5 * Update and migrate iOS example project. ## 0.5.21+4 * Support projection methods to translate between screen and latlng coordinates. ## 0.5.21+3 * Fix `myLocationButton` bug in `google_maps_flutter` iOS. ## 0.5.21+2 * Fix more `prefer_const_constructors` analyzer warnings in example app. ## 0.5.21+1 * Fix `prefer_const_constructors` analyzer warnings in example app. ## 0.5.21 * Don't recreate map elements if they didn't change since last widget build. ## 0.5.20+6 * Adds support for toggling the traffic layer ## 0.5.20+5 * Allow (de-)serialization of CameraPosition ## 0.5.20+4 * Marker drag event ## 0.5.20+3 * Update Android play-services-maps to 17.0.0 ## 0.5.20+2 * Android: Fix polyline width in building phase. ## 0.5.20+1 * Android: Unregister ActivityLifecycleCallbacks on activity destroy (fixes a memory leak). ## 0.5.20 * Add map toolbar support ## 0.5.19+2 * Fix polygons for iOS ## 0.5.19+1 * Fix polyline width according to device density ## 0.5.19 * Adds support for toggling Indoor View on or off. * Allow BitmapDescriptor scaling override ## 0.5.18 * Fixed build issue on iOS. ## 0.5.17 * Add support for Padding. ## 0.5.16+1 * Update Dart code to conform to current Dart formatter. ## 0.5.16 * Add support for custom map styling. ## 0.5.15+1 * Add missing template type parameter to `invokeMethod` calls. * Bump minimum Flutter version to 1.5.0. * Replace invokeMethod with invokeMapMethod wherever necessary. ## 0.5.15 * Add support for Polygons. ## 0.5.14+1 * Example app update(comment out usage of the ImageStreamListener API which has a breaking change that's not yet on master). See: https://github.com/flutter/flutter/issues/33438 ## 0.5.14 * Adds onLongPress callback for GoogleMap. ## 0.5.13 * Add support for Circle overlays. ## 0.5.12 * Prevent calling null callbacks and callbacks on removed objects. ## 0.5.11+1 * Android: Fix an issue where myLocationButtonEnabled setting was not propagated when set to false onMapLoad. ## 0.5.11 * Add myLocationButtonEnabled option. ## 0.5.10 * Support Color's alpha channel when converting to UIColor on iOS. ## 0.5.9 * BitmapDescriptor#fromBytes accounts for screen scale on ios. ## 0.5.8 * Remove some unused variables and rename method ## 0.5.7 * Add a BitmapDescriptor that is aware of scale. ## 0.5.6 * Add support for Polylines on GoogleMap. ## 0.5.5 * Enable iOS accessibility. ## 0.5.4 * Add method getVisibleRegion for get the latlng bounds of the visible map area. ## 0.5.3 * Added support setting marker icons from bytes. ## 0.5.2 * Added onTap for callback for GoogleMap. ## 0.5.1 * Update Android gradle version. * Added infrastructure to write integration tests. ## 0.5.0 * Add a key parameter to the GoogleMap widget. ## 0.4.0 * Change events are call backs on GoogleMap widget. * GoogleMapController no longer handles change events. * trackCameraPosition is inferred from GoogleMap.onCameraMove being set. ## 0.3.0+3 * Update Android play-services-maps to 16.1.0 ## 0.3.0+2 * Address an issue on iOS where icons were not loading. * Add apache http library required false for Android. ## 0.3.0+1 * Add NSNull Checks for markers controller in iOS. * Also address an issue where initial markers are set before initialization. ## 0.3.0 * **Breaking change**. Changed the Marker API to be widget based, it was controller based. Also changed the example app to account for the same. ## 0.2.0+6 * Updated the sample app in README.md. ## 0.2.0+5 * Skip the Gradle Android permissions lint for MyLocation (https://github.com/flutter/flutter/issues/28339) * Suppress unchecked cast warning for the PlatformViewFactory creation parameters. ## 0.2.0+4 * Fixed a crash when the plugin is registered by a background FlutterView. ## 0.2.0+3 * Fixed a memory leak on Android - the map was not properly disposed. ## 0.2.0+2 * Log a more detailed warning at build time about the previous AndroidX migration. ## 0.2.0+1 * Fixed a bug which the camera is not positioned correctly at map initialization(temporary workaround)(https://github.com/flutter/flutter/issues/27550). ## 0.2.0 * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. ## 0.1.0 * Move the map options from the GoogleMapOptions class to GoogleMap widget parameters. ## 0.0.3+3 * Relax Flutter version requirement to 0.11.9. ## 0.0.3+2 * Update README to recommend using the package from pub. ## 0.0.3+1 * Bug fix: custom marker images were not working on iOS as we were not keeping a reference to the plugin registrar so couldn't fetch assets. ## 0.0.3 * Don't export `dart:async`. * Update the minimal required Flutter SDK version to one that supports embedding platform views. ## 0.0.2 * Initial developers preview release.
plugins/packages/google_maps_flutter/google_maps_flutter/CHANGELOG.md/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/CHANGELOG.md", "repo_id": "plugins", "token_count": 4760 }
1,096
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'fake_maps_controllers.dart'; Widget _mapWithTileOverlays(Set<TileOverlay> tileOverlays) { return Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), tileOverlays: tileOverlays, ), ); } void main() { final FakePlatformViewsController fakePlatformViewsController = FakePlatformViewsController(); setUpAll(() { _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler( SystemChannels.platform_views, fakePlatformViewsController.fakePlatformViewsMethodHandler, ); }); setUp(() { fakePlatformViewsController.reset(); }); testWidgets('Initializing a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.tileOverlaysToAdd.length, 1); final TileOverlay initializedTileOverlay = platformGoogleMap.tileOverlaysToAdd.first; expect(initializedTileOverlay, equals(t1)); expect(platformGoogleMap.tileOverlayIdsToRemove.isEmpty, true); expect(platformGoogleMap.tileOverlaysToChange.isEmpty, true); }); testWidgets('Adding a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); const TileOverlay t2 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_2')); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1, t2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.tileOverlaysToAdd.length, 1); final TileOverlay addedTileOverlay = platformGoogleMap.tileOverlaysToAdd.first; expect(addedTileOverlay, equals(t2)); expect(platformGoogleMap.tileOverlayIdsToRemove.isEmpty, true); expect(platformGoogleMap.tileOverlaysToChange.isEmpty, true); }); testWidgets('Removing a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.tileOverlayIdsToRemove.length, 1); expect(platformGoogleMap.tileOverlayIdsToRemove.first, equals(t1.tileOverlayId)); expect(platformGoogleMap.tileOverlaysToChange.isEmpty, true); expect(platformGoogleMap.tileOverlaysToAdd.isEmpty, true); }); testWidgets('Updating a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); const TileOverlay t2 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1'), zIndex: 10); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.tileOverlaysToChange.length, 1); expect(platformGoogleMap.tileOverlaysToChange.first, equals(t2)); expect(platformGoogleMap.tileOverlayIdsToRemove.isEmpty, true); expect(platformGoogleMap.tileOverlaysToAdd.isEmpty, true); }); testWidgets('Updating a tile overlay', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); const TileOverlay t2 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1'), zIndex: 10); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t1})); await tester.pumpWidget(_mapWithTileOverlays(<TileOverlay>{t2})); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.tileOverlaysToChange.length, 1); final TileOverlay update = platformGoogleMap.tileOverlaysToChange.first; expect(update, equals(t2)); expect(update.zIndex, 10); }); testWidgets('Multi Update', (WidgetTester tester) async { TileOverlay t1 = const TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); TileOverlay t2 = const TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_2')); final Set<TileOverlay> prev = <TileOverlay>{t1, t2}; t1 = const TileOverlay( tileOverlayId: TileOverlayId('tile_overlay_1'), visible: false); t2 = const TileOverlay( tileOverlayId: TileOverlayId('tile_overlay_2'), zIndex: 10); final Set<TileOverlay> cur = <TileOverlay>{t1, t2}; await tester.pumpWidget(_mapWithTileOverlays(prev)); await tester.pumpWidget(_mapWithTileOverlays(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.tileOverlaysToChange, cur); expect(platformGoogleMap.tileOverlayIdsToRemove.isEmpty, true); expect(platformGoogleMap.tileOverlaysToAdd.isEmpty, true); }); testWidgets('Multi Update', (WidgetTester tester) async { TileOverlay t2 = const TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_2')); const TileOverlay t3 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_3')); final Set<TileOverlay> prev = <TileOverlay>{t2, t3}; // t1 is added, t2 is updated, t3 is removed. const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); t2 = const TileOverlay( tileOverlayId: TileOverlayId('tile_overlay_2'), zIndex: 10); final Set<TileOverlay> cur = <TileOverlay>{t1, t2}; await tester.pumpWidget(_mapWithTileOverlays(prev)); await tester.pumpWidget(_mapWithTileOverlays(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.tileOverlaysToChange.length, 1); expect(platformGoogleMap.tileOverlaysToAdd.length, 1); expect(platformGoogleMap.tileOverlayIdsToRemove.length, 1); expect(platformGoogleMap.tileOverlaysToChange.first, equals(t2)); expect(platformGoogleMap.tileOverlaysToAdd.first, equals(t1)); expect(platformGoogleMap.tileOverlayIdsToRemove.first, equals(t3.tileOverlayId)); }); testWidgets('Partial Update', (WidgetTester tester) async { const TileOverlay t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); const TileOverlay t2 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_2')); TileOverlay t3 = const TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_3')); final Set<TileOverlay> prev = <TileOverlay>{t1, t2, t3}; t3 = const TileOverlay( tileOverlayId: TileOverlayId('tile_overlay_3'), zIndex: 10); final Set<TileOverlay> cur = <TileOverlay>{t1, t2, t3}; await tester.pumpWidget(_mapWithTileOverlays(prev)); await tester.pumpWidget(_mapWithTileOverlays(cur)); final FakePlatformGoogleMap platformGoogleMap = fakePlatformViewsController.lastCreatedView!; expect(platformGoogleMap.tileOverlaysToChange, <TileOverlay>{t3}); expect(platformGoogleMap.tileOverlayIdsToRemove.isEmpty, true); expect(platformGoogleMap.tileOverlaysToAdd.isEmpty, true); }); } /// This allows a value of type T or T? to be treated as a value of type T?. /// /// We use this so that APIs that have become non-nullable can still be used /// with `!` and `?` on the stable branch. T? _ambiguate<T>(T? value) => value;
plugins/packages/google_maps_flutter/google_maps_flutter/test/tile_overlay_updates_test.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/test/tile_overlay_updates_test.dart", "repo_id": "plugins", "token_count": 3097 }
1,097
mock-maker-inline
plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker", "repo_id": "plugins", "token_count": 7 }
1,098
// Mocks generated by Mockito 5.3.2 from annotations // in google_maps_flutter_web_integration_tests/integration_test/google_maps_plugin_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i2; import 'package:google_maps/google_maps.dart' as _i5; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart' as _i3; import 'package:google_maps_flutter_web/google_maps_flutter_web.dart' as _i4; 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 _FakeStreamController_0<T> extends _i1.SmartFake implements _i2.StreamController<T> { _FakeStreamController_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeLatLngBounds_1 extends _i1.SmartFake implements _i3.LatLngBounds { _FakeLatLngBounds_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeScreenCoordinate_2 extends _i1.SmartFake implements _i3.ScreenCoordinate { _FakeScreenCoordinate_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeLatLng_3 extends _i1.SmartFake implements _i3.LatLng { _FakeLatLng_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [GoogleMapController]. /// /// See the documentation for Mockito's code generation for more information. class MockGoogleMapController extends _i1.Mock implements _i4.GoogleMapController { @override _i2.StreamController<_i3.MapEvent<Object?>> get stream => (super.noSuchMethod( Invocation.getter(#stream), returnValue: _FakeStreamController_0<_i3.MapEvent<Object?>>( this, Invocation.getter(#stream), ), returnValueForMissingStub: _FakeStreamController_0<_i3.MapEvent<Object?>>( this, Invocation.getter(#stream), ), ) as _i2.StreamController<_i3.MapEvent<Object?>>); @override _i2.Stream<_i3.MapEvent<Object?>> get events => (super.noSuchMethod( Invocation.getter(#events), returnValue: _i2.Stream<_i3.MapEvent<Object?>>.empty(), returnValueForMissingStub: _i2.Stream<_i3.MapEvent<Object?>>.empty(), ) as _i2.Stream<_i3.MapEvent<Object?>>); @override bool get isInitialized => (super.noSuchMethod( Invocation.getter(#isInitialized), returnValue: false, returnValueForMissingStub: false, ) as bool); @override void debugSetOverrides({ _i4.DebugCreateMapFunction? createMap, _i4.MarkersController? markers, _i4.CirclesController? circles, _i4.PolygonsController? polygons, _i4.PolylinesController? polylines, }) => super.noSuchMethod( Invocation.method( #debugSetOverrides, [], { #createMap: createMap, #markers: markers, #circles: circles, #polygons: polygons, #polylines: polylines, }, ), returnValueForMissingStub: null, ); @override void init() => super.noSuchMethod( Invocation.method( #init, [], ), returnValueForMissingStub: null, ); @override void updateMapConfiguration(_i3.MapConfiguration? update) => super.noSuchMethod( Invocation.method( #updateMapConfiguration, [update], ), returnValueForMissingStub: null, ); @override void updateStyles(List<_i5.MapTypeStyle>? styles) => super.noSuchMethod( Invocation.method( #updateStyles, [styles], ), returnValueForMissingStub: null, ); @override _i2.Future<_i3.LatLngBounds> getVisibleRegion() => (super.noSuchMethod( Invocation.method( #getVisibleRegion, [], ), returnValue: _i2.Future<_i3.LatLngBounds>.value(_FakeLatLngBounds_1( this, Invocation.method( #getVisibleRegion, [], ), )), returnValueForMissingStub: _i2.Future<_i3.LatLngBounds>.value(_FakeLatLngBounds_1( this, Invocation.method( #getVisibleRegion, [], ), )), ) as _i2.Future<_i3.LatLngBounds>); @override _i2.Future<_i3.ScreenCoordinate> getScreenCoordinate(_i3.LatLng? latLng) => (super.noSuchMethod( Invocation.method( #getScreenCoordinate, [latLng], ), returnValue: _i2.Future<_i3.ScreenCoordinate>.value(_FakeScreenCoordinate_2( this, Invocation.method( #getScreenCoordinate, [latLng], ), )), returnValueForMissingStub: _i2.Future<_i3.ScreenCoordinate>.value(_FakeScreenCoordinate_2( this, Invocation.method( #getScreenCoordinate, [latLng], ), )), ) as _i2.Future<_i3.ScreenCoordinate>); @override _i2.Future<_i3.LatLng> getLatLng(_i3.ScreenCoordinate? screenCoordinate) => (super.noSuchMethod( Invocation.method( #getLatLng, [screenCoordinate], ), returnValue: _i2.Future<_i3.LatLng>.value(_FakeLatLng_3( this, Invocation.method( #getLatLng, [screenCoordinate], ), )), returnValueForMissingStub: _i2.Future<_i3.LatLng>.value(_FakeLatLng_3( this, Invocation.method( #getLatLng, [screenCoordinate], ), )), ) as _i2.Future<_i3.LatLng>); @override _i2.Future<void> moveCamera(_i3.CameraUpdate? cameraUpdate) => (super.noSuchMethod( Invocation.method( #moveCamera, [cameraUpdate], ), returnValue: _i2.Future<void>.value(), returnValueForMissingStub: _i2.Future<void>.value(), ) as _i2.Future<void>); @override _i2.Future<double> getZoomLevel() => (super.noSuchMethod( Invocation.method( #getZoomLevel, [], ), returnValue: _i2.Future<double>.value(0.0), returnValueForMissingStub: _i2.Future<double>.value(0.0), ) as _i2.Future<double>); @override void updateCircles(_i3.CircleUpdates? updates) => super.noSuchMethod( Invocation.method( #updateCircles, [updates], ), returnValueForMissingStub: null, ); @override void updatePolygons(_i3.PolygonUpdates? updates) => super.noSuchMethod( Invocation.method( #updatePolygons, [updates], ), returnValueForMissingStub: null, ); @override void updatePolylines(_i3.PolylineUpdates? updates) => super.noSuchMethod( Invocation.method( #updatePolylines, [updates], ), returnValueForMissingStub: null, ); @override void updateMarkers(_i3.MarkerUpdates? updates) => super.noSuchMethod( Invocation.method( #updateMarkers, [updates], ), returnValueForMissingStub: null, ); @override void showInfoWindow(_i3.MarkerId? markerId) => super.noSuchMethod( Invocation.method( #showInfoWindow, [markerId], ), returnValueForMissingStub: null, ); @override void hideInfoWindow(_i3.MarkerId? markerId) => super.noSuchMethod( Invocation.method( #hideInfoWindow, [markerId], ), returnValueForMissingStub: null, ); @override bool isInfoWindowShown(_i3.MarkerId? markerId) => (super.noSuchMethod( Invocation.method( #isInfoWindowShown, [markerId], ), returnValue: false, returnValueForMissingStub: false, ) as bool); @override void dispose() => super.noSuchMethod( Invocation.method( #dispose, [], ), returnValueForMissingStub: null, ); }
plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.mocks.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.mocks.dart", "repo_id": "plugins", "token_count": 4125 }
1,099
// 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; // Default values for when the gmaps objects return null/undefined values. final gmaps.LatLng _nullGmapsLatLng = gmaps.LatLng(0, 0); final gmaps.LatLngBounds _nullGmapsLatLngBounds = gmaps.LatLngBounds(_nullGmapsLatLng, _nullGmapsLatLng); // Defaults taken from the Google Maps Platform SDK documentation. const String _defaultCssColor = '#000000'; const double _defaultCssOpacity = 0.0; // Converts a [Color] into a valid CSS value #RRGGBB. String _getCssColor(Color color) { if (color == null) { return _defaultCssColor; } return '#${color.value.toRadixString(16).padLeft(8, '0').substring(2)}'; } // Extracts the opacity from a [Color]. double _getCssOpacity(Color color) { if (color == null) { return _defaultCssOpacity; } return color.opacity; } // Converts options from the plugin into gmaps.MapOptions that can be used by the JS SDK. // The following options are not handled here, for various reasons: // The following are not available in web, because the map doesn't rotate there: // compassEnabled // rotateGesturesEnabled // tiltGesturesEnabled // mapToolbarEnabled is unused in web, there's no "map toolbar" // myLocationButtonEnabled Widget not available in web yet, it needs to be built on top of the maps widget // See: https://developers.google.com/maps/documentation/javascript/examples/control-custom // myLocationEnabled needs to be built through dart:html navigator.geolocation // See: https://api.dart.dev/stable/2.8.4/dart-html/Geolocation-class.html // trafficEnabled is handled when creating the GMap object, since it needs to be added as a layer. // trackCameraPosition is just a boolan value that indicates if the map has an onCameraMove handler. // indoorViewEnabled seems to not have an equivalent in web // buildingsEnabled seems to not have an equivalent in web // padding seems to behave differently in web than mobile. You can't move UI elements in web. gmaps.MapOptions _configurationAndStyleToGmapsOptions( MapConfiguration configuration, List<gmaps.MapTypeStyle> styles) { final gmaps.MapOptions options = gmaps.MapOptions(); if (configuration.mapType != null) { options.mapTypeId = _gmapTypeIDForPluginType(configuration.mapType!); } final MinMaxZoomPreference? zoomPreference = configuration.minMaxZoomPreference; if (zoomPreference != null) { options ..minZoom = zoomPreference.minZoom ..maxZoom = zoomPreference.maxZoom; } if (configuration.cameraTargetBounds != null) { // Needs gmaps.MapOptions.restriction and gmaps.MapRestriction // see: https://developers.google.com/maps/documentation/javascript/reference/map#MapOptions.restriction } if (configuration.zoomControlsEnabled != null) { options.zoomControl = configuration.zoomControlsEnabled; } if (configuration.scrollGesturesEnabled == false || configuration.zoomGesturesEnabled == false) { options.gestureHandling = 'none'; } else { options.gestureHandling = 'auto'; } // These don't have any configuration entries, but they seem to be off in the // native maps. options.mapTypeControl = false; options.fullscreenControl = false; options.streetViewControl = false; options.styles = styles; return options; } gmaps.MapTypeId _gmapTypeIDForPluginType(MapType type) { switch (type) { case MapType.satellite: return gmaps.MapTypeId.SATELLITE; case MapType.terrain: return gmaps.MapTypeId.TERRAIN; case MapType.hybrid: return gmaps.MapTypeId.HYBRID; case MapType.normal: case MapType.none: return gmaps.MapTypeId.ROADMAP; } // The enum comes from a different package, which could get a new value at // any time, so provide a fallback that ensures this won't break when used // with a version that contains new values. 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 return gmaps.MapTypeId.ROADMAP; } gmaps.MapOptions _applyInitialPosition( CameraPosition initialPosition, gmaps.MapOptions options, ) { // Adjust the initial position, if passed... if (initialPosition != null) { options.zoom = initialPosition.zoom; options.center = gmaps.LatLng( initialPosition.target.latitude, initialPosition.target.longitude); } return options; } // The keys we'd expect to see in a serialized MapTypeStyle JSON object. final Set<String> _mapStyleKeys = <String>{ 'elementType', 'featureType', 'stylers', }; // Checks if the passed in Map contains some of the _mapStyleKeys. bool _isJsonMapStyle(Map<String, Object?> value) { return _mapStyleKeys.intersection(value.keys.toSet()).isNotEmpty; } // Converts an incoming JSON-encoded Style info, into the correct gmaps array. List<gmaps.MapTypeStyle> _mapStyles(String? mapStyleJson) { List<gmaps.MapTypeStyle> styles = <gmaps.MapTypeStyle>[]; if (mapStyleJson != null) { styles = (json.decode(mapStyleJson, reviver: (Object? key, Object? value) { if (value is Map && _isJsonMapStyle(value as Map<String, Object?>)) { List<Object?> stylers = <Object?>[]; if (value['stylers'] != null) { stylers = (value['stylers']! as List<Object?>) .map<Object?>((Object? e) => e != null ? jsify(e) : null) .toList(); } return gmaps.MapTypeStyle() ..elementType = value['elementType'] as String? ..featureType = value['featureType'] as String? ..stylers = stylers; } return value; }) as List<Object?>) .where((Object? element) => element != null) .cast<gmaps.MapTypeStyle>() .toList(); // .toList calls are required so the JS API understands the underlying data structure. } return styles; } gmaps.LatLng _latLngToGmLatLng(LatLng latLng) { return gmaps.LatLng(latLng.latitude, latLng.longitude); } LatLng _gmLatLngToLatLng(gmaps.LatLng latLng) { return LatLng(latLng.lat.toDouble(), latLng.lng.toDouble()); } LatLngBounds _gmLatLngBoundsTolatLngBounds(gmaps.LatLngBounds latLngBounds) { return LatLngBounds( southwest: _gmLatLngToLatLng(latLngBounds.southWest), northeast: _gmLatLngToLatLng(latLngBounds.northEast), ); } CameraPosition _gmViewportToCameraPosition(gmaps.GMap map) { return CameraPosition( target: _gmLatLngToLatLng(map.center ?? _nullGmapsLatLng), bearing: map.heading?.toDouble() ?? 0, tilt: map.tilt?.toDouble() ?? 0, zoom: map.zoom?.toDouble() ?? 0, ); } // Convert plugin objects to gmaps.Options objects // TODO(ditman): Move to their appropriate objects, maybe make them copy constructors? // Marker.fromMarker(anotherMarker, moreOptions); gmaps.InfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { final String markerTitle = marker.infoWindow.title ?? ''; final String markerSnippet = marker.infoWindow.snippet ?? ''; // If both the title and snippet of an infowindow are empty, we don't really // want an infowindow... if ((markerTitle.isEmpty) && (markerSnippet.isEmpty)) { return null; } // Add an outer wrapper to the contents of the infowindow, we need it to listen // to click events... final HtmlElement container = DivElement() ..id = 'gmaps-marker-${marker.markerId.value}-infowindow'; if (markerTitle.isNotEmpty) { final HtmlElement title = HeadingElement.h3() ..className = 'infowindow-title' ..innerText = markerTitle; container.children.add(title); } if (markerSnippet.isNotEmpty) { final HtmlElement snippet = DivElement() ..className = 'infowindow-snippet' // `sanitizeHtml` is used to clean the (potential) user input from (potential) // XSS attacks through the contents of the marker InfoWindow. // See: https://pub.dev/documentation/sanitize_html/latest/sanitize_html/sanitizeHtml.html // See: b/159137885, b/159598165 // The NodeTreeSanitizer.trusted just tells setInnerHtml to leave the output // of `sanitizeHtml` untouched. // ignore: unsafe_html ..setInnerHtml( sanitizeHtml(markerSnippet), treeSanitizer: NodeTreeSanitizer.trusted, ); container.children.add(snippet); } return gmaps.InfoWindowOptions() ..content = container ..zIndex = marker.zIndex; // TODO(ditman): Compute the pixelOffset of the infoWindow, from the size of the Marker, // and the marker.infoWindow.anchor property. } // Attempts to extract a [gmaps.Size] from `iconConfig[sizeIndex]`. gmaps.Size? _gmSizeFromIconConfig(List<Object?> iconConfig, int sizeIndex) { gmaps.Size? size; if (iconConfig.length >= sizeIndex + 1) { final List<Object?>? rawIconSize = iconConfig[sizeIndex] as List<Object?>?; if (rawIconSize != null) { size = gmaps.Size( rawIconSize[0] as num?, rawIconSize[1] as num?, ); } } return size; } // Converts a [BitmapDescriptor] into a [gmaps.Icon] that can be used in Markers. gmaps.Icon? _gmIconFromBitmapDescriptor(BitmapDescriptor bitmapDescriptor) { final List<Object?> iconConfig = bitmapDescriptor.toJson() as List<Object?>; gmaps.Icon? icon; if (iconConfig != null) { if (iconConfig[0] == 'fromAssetImage') { assert(iconConfig.length >= 2); // iconConfig[2] contains the DPIs of the screen, but that information is // already encoded in the iconConfig[1] icon = gmaps.Icon() ..url = ui.webOnlyAssetManager.getAssetUrl(iconConfig[1]! as String); final gmaps.Size? size = _gmSizeFromIconConfig(iconConfig, 3); if (size != null) { icon ..size = size ..scaledSize = size; } } else if (iconConfig[0] == 'fromBytes') { // Grab the bytes, and put them into a blob final List<int> bytes = iconConfig[1]! as List<int>; // Create a Blob from bytes, but let the browser figure out the encoding final Blob blob = Blob(<dynamic>[bytes]); icon = gmaps.Icon()..url = Url.createObjectUrlFromBlob(blob); final gmaps.Size? size = _gmSizeFromIconConfig(iconConfig, 2); if (size != null) { icon ..size = size ..scaledSize = size; } } } return icon; } // Computes the options for a new [gmaps.Marker] from an incoming set of options // [marker], and the existing marker registered with the map: [currentMarker]. // Preserves the position from the [currentMarker], if set. gmaps.MarkerOptions _markerOptionsFromMarker( Marker marker, gmaps.Marker? currentMarker, ) { return gmaps.MarkerOptions() ..position = currentMarker?.position ?? gmaps.LatLng( marker.position.latitude, marker.position.longitude, ) ..title = sanitizeHtml(marker.infoWindow.title ?? '') ..zIndex = marker.zIndex ..visible = marker.visible ..opacity = marker.alpha ..draggable = marker.draggable ..icon = _gmIconFromBitmapDescriptor(marker.icon); // TODO(ditman): Compute anchor properly, otherwise infowindows attach to the wrong spot. // Flat and Rotation are not supported directly on the web. } gmaps.CircleOptions _circleOptionsFromCircle(Circle circle) { final gmaps.CircleOptions circleOptions = gmaps.CircleOptions() ..strokeColor = _getCssColor(circle.strokeColor) ..strokeOpacity = _getCssOpacity(circle.strokeColor) ..strokeWeight = circle.strokeWidth ..fillColor = _getCssColor(circle.fillColor) ..fillOpacity = _getCssOpacity(circle.fillColor) ..center = gmaps.LatLng(circle.center.latitude, circle.center.longitude) ..radius = circle.radius ..visible = circle.visible ..zIndex = circle.zIndex; return circleOptions; } gmaps.PolygonOptions _polygonOptionsFromPolygon( gmaps.GMap googleMap, Polygon polygon) { // Convert all points to GmLatLng final List<gmaps.LatLng> path = polygon.points.map(_latLngToGmLatLng).toList(); final bool isClockwisePolygon = _isPolygonClockwise(path); final List<List<gmaps.LatLng>> paths = <List<gmaps.LatLng>>[path]; for (int i = 0; i < polygon.holes.length; i++) { final List<LatLng> hole = polygon.holes[i]; final List<gmaps.LatLng> correctHole = _ensureHoleHasReverseWinding( hole, isClockwisePolygon, holeId: i, polygonId: polygon.polygonId, ); paths.add(correctHole); } return gmaps.PolygonOptions() ..paths = paths ..strokeColor = _getCssColor(polygon.strokeColor) ..strokeOpacity = _getCssOpacity(polygon.strokeColor) ..strokeWeight = polygon.strokeWidth ..fillColor = _getCssColor(polygon.fillColor) ..fillOpacity = _getCssOpacity(polygon.fillColor) ..visible = polygon.visible ..zIndex = polygon.zIndex ..geodesic = polygon.geodesic; } List<gmaps.LatLng> _ensureHoleHasReverseWinding( List<LatLng> hole, bool polyIsClockwise, { required int holeId, required PolygonId polygonId, }) { List<gmaps.LatLng> holePath = hole.map(_latLngToGmLatLng).toList(); final bool holeIsClockwise = _isPolygonClockwise(holePath); if (holeIsClockwise == polyIsClockwise) { holePath = holePath.reversed.toList(); if (kDebugMode) { print('Hole [$holeId] in Polygon [${polygonId.value}] has been reversed.' ' Ensure holes in polygons are "wound in the opposite direction to the outer path."' ' More info: https://github.com/flutter/flutter/issues/74096'); } } return holePath; } /// Calculates the direction of a given Polygon /// based on: https://stackoverflow.com/a/1165943 /// /// returns [true] if clockwise [false] if counterclockwise /// /// This method expects that the incoming [path] is a `List` of well-formed, /// non-null [gmaps.LatLng] objects. /// /// Currently, this method is only called from [_polygonOptionsFromPolygon], and /// the `path` is a transformed version of [Polygon.points] or each of the /// [Polygon.holes], guaranteeing that `lat` and `lng` can be accessed with `!`. bool _isPolygonClockwise(List<gmaps.LatLng> path) { double direction = 0.0; for (int i = 0; i < path.length; i++) { direction = direction + ((path[(i + 1) % path.length].lat - path[i].lat) * (path[(i + 1) % path.length].lng + path[i].lng)); } return direction >= 0; } gmaps.PolylineOptions _polylineOptionsFromPolyline( gmaps.GMap googleMap, Polyline polyline) { final List<gmaps.LatLng> paths = polyline.points.map(_latLngToGmLatLng).toList(); return gmaps.PolylineOptions() ..path = paths ..strokeWeight = polyline.width ..strokeColor = _getCssColor(polyline.color) ..strokeOpacity = _getCssOpacity(polyline.color) ..visible = polyline.visible ..zIndex = polyline.zIndex ..geodesic = polyline.geodesic; // this.endCap = Cap.buttCap, // this.jointType = JointType.mitered, // this.patterns = const <PatternItem>[], // this.startCap = Cap.buttCap, // this.width = 10, } // Translates a [CameraUpdate] into operations on a [gmaps.GMap]. void _applyCameraUpdate(gmaps.GMap map, CameraUpdate update) { // Casts [value] to a JSON dictionary (string -> nullable object). [value] // must be a non-null JSON dictionary. Map<String, Object?> asJsonObject(dynamic value) { return (value as Map<Object?, Object?>).cast<String, Object?>(); } // Casts [value] to a JSON list. [value] must be a non-null JSON list. List<Object?> asJsonList(dynamic value) { return value as List<Object?>; } final List<dynamic> json = update.toJson() as List<dynamic>; switch (json[0]) { case 'newCameraPosition': final Map<String, Object?> position = asJsonObject(json[1]); final List<Object?> latLng = asJsonList(position['target']); map.heading = position['bearing'] as num?; map.zoom = position['zoom'] as num?; map.panTo( gmaps.LatLng(latLng[0] as num?, latLng[1] as num?), ); map.tilt = position['tilt'] as num?; break; case 'newLatLng': final List<Object?> latLng = asJsonList(json[1]); map.panTo(gmaps.LatLng(latLng[0] as num?, latLng[1] as num?)); break; case 'newLatLngZoom': final List<Object?> latLng = asJsonList(json[1]); map.zoom = json[2] as num?; map.panTo(gmaps.LatLng(latLng[0] as num?, latLng[1] as num?)); break; case 'newLatLngBounds': final List<Object?> latLngPair = asJsonList(json[1]); final List<Object?> latLng1 = asJsonList(latLngPair[0]); final List<Object?> latLng2 = asJsonList(latLngPair[1]); map.fitBounds( gmaps.LatLngBounds( gmaps.LatLng(latLng1[0] as num?, latLng1[1] as num?), gmaps.LatLng(latLng2[0] as num?, latLng2[1] as num?), ), ); // padding = json[2]; // Needs package:google_maps ^4.0.0 to adjust the padding in fitBounds break; case 'scrollBy': map.panBy(json[1] as num?, json[2] as num?); break; case 'zoomBy': gmaps.LatLng? focusLatLng; final double zoomDelta = json[1] as double? ?? 0; // Web only supports integer changes... final int newZoomDelta = zoomDelta < 0 ? zoomDelta.floor() : zoomDelta.ceil(); if (json.length == 3) { final List<Object?> latLng = asJsonList(json[2]); // With focus try { focusLatLng = _pixelToLatLng(map, latLng[0]! as int, latLng[1]! as int); } catch (e) { // https://github.com/a14n/dart-google-maps/issues/87 // print('Error computing new focus LatLng. JS Error: ' + e.toString()); } } map.zoom = (map.zoom ?? 0) + newZoomDelta; if (focusLatLng != null) { map.panTo(focusLatLng); } break; case 'zoomIn': map.zoom = (map.zoom ?? 0) + 1; break; case 'zoomOut': map.zoom = (map.zoom ?? 0) - 1; break; case 'zoomTo': map.zoom = json[1] as num?; break; default: throw UnimplementedError('Unimplemented CameraMove: ${json[0]}.'); } } // original JS by: Byron Singh (https://stackoverflow.com/a/30541162) gmaps.LatLng _pixelToLatLng(gmaps.GMap map, int x, int y) { final gmaps.LatLngBounds? bounds = map.bounds; final gmaps.Projection? projection = map.projection; final num? zoom = map.zoom; assert( bounds != null, 'Map Bounds required to compute LatLng of screen x/y.'); assert(projection != null, 'Map Projection required to compute LatLng of screen x/y'); assert(zoom != null, 'Current map zoom level required to compute LatLng of screen x/y'); final gmaps.LatLng ne = bounds!.northEast; final gmaps.LatLng sw = bounds.southWest; final gmaps.Point topRight = projection!.fromLatLngToPoint!(ne)!; final gmaps.Point bottomLeft = projection.fromLatLngToPoint!(sw)!; final int scale = 1 << (zoom!.toInt()); // 2 ^ zoom final gmaps.Point point = gmaps.Point((x / scale) + bottomLeft.x!, (y / scale) + topRight.y!); return projection.fromPointToLatLng!(point)!; }
plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart", "repo_id": "plugins", "token_count": 7260 }
1,100
name: google_maps_flutter_web description: Web platform implementation of google_maps_flutter repository: https://github.com/flutter/plugins/tree/main/packages/google_maps_flutter/google_maps_flutter_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%22 version: 0.4.0+5 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: google_maps_flutter platforms: web: pluginClass: GoogleMapsPlugin fileName: google_maps_flutter_web.dart dependencies: flutter: sdk: flutter flutter_web_plugins: sdk: flutter google_maps: ^6.1.0 google_maps_flutter_platform_interface: ^2.2.2 sanitize_html: ^2.0.0 stream_transform: ^2.0.0 dev_dependencies: flutter_test: sdk: flutter # The example deliberately includes limited-use secrets. false_secrets: - /example/web/index.html
plugins/packages/google_maps_flutter/google_maps_flutter_web/pubspec.yaml/0
{ "file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/pubspec.yaml", "repo_id": "plugins", "token_count": 374 }
1,101
group 'io.flutter.plugins.googlesignin' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.2.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { compileSdkVersion 31 defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } lintOptions { disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { implementation 'com.google.android.gms:play-services-auth:20.4.1' implementation 'com.google.guava:guava:31.1-android' testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-inline:5.0.0' }
plugins/packages/google_sign_in/google_sign_in_android/android/build.gradle/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_android/android/build.gradle", "repo_id": "plugins", "token_count": 549 }
1,102
name: google_sign_in_web description: Flutter plugin for Google Sign-In, a secure authentication system for signing in with a Google account on Android, iOS and Web. repository: https://github.com/flutter/plugins/tree/main/packages/google_sign_in/google_sign_in_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22 version: 0.11.0 environment: sdk: ">=2.17.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: google_sign_in platforms: web: pluginClass: GoogleSignInPlugin fileName: google_sign_in_web.dart dependencies: flutter: sdk: flutter flutter_web_plugins: sdk: flutter google_identity_services_web: ^0.2.0 google_sign_in_platform_interface: ^2.2.0 http: ^0.13.5 js: ^0.6.3 dev_dependencies: flutter_test: sdk: flutter
plugins/packages/google_sign_in/google_sign_in_web/pubspec.yaml/0
{ "file_path": "plugins/packages/google_sign_in/google_sign_in_web/pubspec.yaml", "repo_id": "plugins", "token_count": 360 }
1,103
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ignore_for_file: public_member_api_docs import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:video_player/video_player.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Image Picker Demo', home: MyHomePage(title: 'Image Picker Example'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, this.title}) : super(key: key); final String? title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<XFile>? _imageFileList; void _setImageFileListFromFile(XFile? value) { _imageFileList = value == null ? null : <XFile>[value]; } dynamic _pickImageError; bool isVideo = false; VideoPlayerController? _controller; VideoPlayerController? _toBeDisposed; String? _retrieveDataError; final ImagePicker _picker = ImagePicker(); final TextEditingController maxWidthController = TextEditingController(); final TextEditingController maxHeightController = TextEditingController(); final TextEditingController qualityController = TextEditingController(); Future<void> _playVideo(XFile? file) async { if (file != null && mounted) { await _disposeVideoController(); late VideoPlayerController controller; if (kIsWeb) { controller = VideoPlayerController.network(file.path); } else { controller = VideoPlayerController.file(File(file.path)); } _controller = controller; // In web, most browsers won't honor a programmatic call to .play // if the video has a sound track (and is not muted). // Mute the video so it auto-plays in web! // This is not needed if the call to .play is the result of user // interaction (clicking on a "play" button, for example). const double volume = kIsWeb ? 0.0 : 1.0; await controller.setVolume(volume); await controller.initialize(); await controller.setLooping(true); await controller.play(); setState(() {}); } } Future<void> _onImageButtonPressed(ImageSource source, {BuildContext? context, bool isMultiImage = false}) async { if (_controller != null) { await _controller!.setVolume(0.0); } if (isVideo) { final XFile? file = await _picker.pickVideo( source: source, maxDuration: const Duration(seconds: 10)); await _playVideo(file); } else if (isMultiImage) { await _displayPickImageDialog(context!, (double? maxWidth, double? maxHeight, int? quality) async { try { final List<XFile> pickedFileList = await _picker.pickMultiImage( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: quality, ); setState(() { _imageFileList = pickedFileList; }); } catch (e) { setState(() { _pickImageError = e; }); } }); } else { await _displayPickImageDialog(context!, (double? maxWidth, double? maxHeight, int? quality) async { try { final XFile? pickedFile = await _picker.pickImage( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: quality, ); setState(() { _setImageFileListFromFile(pickedFile); }); } catch (e) { setState(() { _pickImageError = e; }); } }); } } @override void deactivate() { if (_controller != null) { _controller!.setVolume(0.0); _controller!.pause(); } super.deactivate(); } @override void dispose() { _disposeVideoController(); maxWidthController.dispose(); maxHeightController.dispose(); qualityController.dispose(); super.dispose(); } Future<void> _disposeVideoController() async { if (_toBeDisposed != null) { await _toBeDisposed!.dispose(); } _toBeDisposed = _controller; _controller = null; } Widget _previewVideo() { final Text? retrieveError = _getRetrieveErrorWidget(); if (retrieveError != null) { return retrieveError; } if (_controller == null) { return const Text( 'You have not yet picked a video', textAlign: TextAlign.center, ); } return Padding( padding: const EdgeInsets.all(10.0), child: AspectRatioVideo(_controller), ); } Widget _previewImages() { final Text? retrieveError = _getRetrieveErrorWidget(); if (retrieveError != null) { return retrieveError; } if (_imageFileList != null) { return Semantics( label: 'image_picker_example_picked_images', child: ListView.builder( key: UniqueKey(), itemBuilder: (BuildContext context, int index) { // Why network for web? // See https://pub.dev/packages/image_picker#getting-ready-for-the-web-platform return Semantics( label: 'image_picker_example_picked_image', child: kIsWeb ? Image.network(_imageFileList![index].path) : Image.file(File(_imageFileList![index].path)), ); }, itemCount: _imageFileList!.length, ), ); } else if (_pickImageError != null) { return Text( 'Pick image error: $_pickImageError', textAlign: TextAlign.center, ); } else { return const Text( 'You have not yet picked an image.', textAlign: TextAlign.center, ); } } Widget _handlePreview() { if (isVideo) { return _previewVideo(); } else { return _previewImages(); } } Future<void> retrieveLostData() async { final LostDataResponse response = await _picker.retrieveLostData(); if (response.isEmpty) { return; } if (response.file != null) { if (response.type == RetrieveType.video) { isVideo = true; await _playVideo(response.file); } else { isVideo = false; setState(() { if (response.files == null) { _setImageFileListFromFile(response.file); } else { _imageFileList = response.files; } }); } } else { _retrieveDataError = response.exception!.code; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title!), ), body: Center( child: !kIsWeb && defaultTargetPlatform == TargetPlatform.android ? FutureBuilder<void>( future: retrieveLostData(), builder: (BuildContext context, AsyncSnapshot<void> snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: return const Text( 'You have not yet picked an image.', textAlign: TextAlign.center, ); case ConnectionState.done: return _handlePreview(); case ConnectionState.active: if (snapshot.hasError) { return Text( 'Pick image/video error: ${snapshot.error}}', textAlign: TextAlign.center, ); } else { return const Text( 'You have not yet picked an image.', textAlign: TextAlign.center, ); } } }, ) : _handlePreview(), ), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Semantics( label: 'image_picker_example_from_gallery', child: FloatingActionButton( onPressed: () { isVideo = false; _onImageButtonPressed(ImageSource.gallery, context: context); }, heroTag: 'image0', tooltip: 'Pick Image from gallery', child: const Icon(Icons.photo), ), ), Padding( padding: const EdgeInsets.only(top: 16.0), child: FloatingActionButton( onPressed: () { isVideo = false; _onImageButtonPressed( ImageSource.gallery, context: context, isMultiImage: true, ); }, heroTag: 'image1', tooltip: 'Pick Multiple Image from gallery', child: const Icon(Icons.photo_library), ), ), Padding( padding: const EdgeInsets.only(top: 16.0), child: FloatingActionButton( onPressed: () { isVideo = false; _onImageButtonPressed(ImageSource.camera, context: context); }, heroTag: 'image2', tooltip: 'Take a Photo', child: const Icon(Icons.camera_alt), ), ), Padding( padding: const EdgeInsets.only(top: 16.0), child: FloatingActionButton( backgroundColor: Colors.red, onPressed: () { isVideo = true; _onImageButtonPressed(ImageSource.gallery); }, heroTag: 'video0', tooltip: 'Pick Video from gallery', child: const Icon(Icons.video_library), ), ), Padding( padding: const EdgeInsets.only(top: 16.0), child: FloatingActionButton( backgroundColor: Colors.red, onPressed: () { isVideo = true; _onImageButtonPressed(ImageSource.camera); }, heroTag: 'video1', tooltip: 'Take a Video', child: const Icon(Icons.videocam), ), ), ], ), ); } Text? _getRetrieveErrorWidget() { if (_retrieveDataError != null) { final Text result = Text(_retrieveDataError!); _retrieveDataError = null; return result; } return null; } Future<void> _displayPickImageDialog( BuildContext context, OnPickImageCallback onPick) async { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Add optional parameters'), content: Column( children: <Widget>[ TextField( controller: maxWidthController, keyboardType: const TextInputType.numberWithOptions(decimal: true), decoration: const InputDecoration( hintText: 'Enter maxWidth if desired'), ), TextField( controller: maxHeightController, keyboardType: const TextInputType.numberWithOptions(decimal: true), decoration: const InputDecoration( hintText: 'Enter maxHeight if desired'), ), TextField( controller: qualityController, keyboardType: TextInputType.number, decoration: const InputDecoration( hintText: 'Enter quality if desired'), ), ], ), actions: <Widget>[ TextButton( child: const Text('CANCEL'), onPressed: () { Navigator.of(context).pop(); }, ), TextButton( child: const Text('PICK'), onPressed: () { final double? width = maxWidthController.text.isNotEmpty ? double.parse(maxWidthController.text) : null; final double? height = maxHeightController.text.isNotEmpty ? double.parse(maxHeightController.text) : null; final int? quality = qualityController.text.isNotEmpty ? int.parse(qualityController.text) : null; onPick(width, height, quality); Navigator.of(context).pop(); }), ], ); }); } } typedef OnPickImageCallback = void Function( double? maxWidth, double? maxHeight, int? quality); class AspectRatioVideo extends StatefulWidget { const AspectRatioVideo(this.controller, {Key? key}) : super(key: key); final VideoPlayerController? controller; @override AspectRatioVideoState createState() => AspectRatioVideoState(); } class AspectRatioVideoState extends State<AspectRatioVideo> { VideoPlayerController? get controller => widget.controller; bool initialized = false; void _onVideoControllerUpdate() { if (!mounted) { return; } if (initialized != controller!.value.isInitialized) { initialized = controller!.value.isInitialized; setState(() {}); } } @override void initState() { super.initState(); controller!.addListener(_onVideoControllerUpdate); } @override void dispose() { controller!.removeListener(_onVideoControllerUpdate); super.dispose(); } @override Widget build(BuildContext context) { if (initialized) { return Center( child: AspectRatio( aspectRatio: controller!.value.aspectRatio, child: VideoPlayer(controller!), ), ); } else { return Container(); } } }
plugins/packages/image_picker/image_picker/example/lib/main.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker/example/lib/main.dart", "repo_id": "plugins", "token_count": 6804 }
1,104
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.imagepicker; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import android.app.Activity; import android.app.Application; import androidx.lifecycle.Lifecycle; import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import java.io.File; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class ImagePickerPluginTest { private static final int SOURCE_CAMERA = 0; private static final int SOURCE_GALLERY = 1; private static final String PICK_IMAGE = "pickImage"; private static final String PICK_MULTI_IMAGE = "pickMultiImage"; private static final String PICK_VIDEO = "pickVideo"; @Rule public ExpectedException exception = ExpectedException.none(); @SuppressWarnings("deprecation") @Mock io.flutter.plugin.common.PluginRegistry.Registrar mockRegistrar; @Mock ActivityPluginBinding mockActivityBinding; @Mock FlutterPluginBinding mockPluginBinding; @Mock Activity mockActivity; @Mock Application mockApplication; @Mock ImagePickerDelegate mockImagePickerDelegate; @Mock MethodChannel.Result mockResult; ImagePickerPlugin plugin; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(mockRegistrar.context()).thenReturn(mockApplication); when(mockActivityBinding.getActivity()).thenReturn(mockActivity); when(mockPluginBinding.getApplicationContext()).thenReturn(mockApplication); plugin = new ImagePickerPlugin(mockImagePickerDelegate, mockActivity); } @Test public void onMethodCall_WhenActivityIsNull_FinishesWithForegroundActivityRequiredError() { MethodCall call = buildMethodCall(PICK_IMAGE, SOURCE_GALLERY); ImagePickerPlugin imagePickerPluginWithNullActivity = new ImagePickerPlugin(mockImagePickerDelegate, null); imagePickerPluginWithNullActivity.onMethodCall(call, mockResult); verify(mockResult) .error("no_activity", "image_picker plugin requires a foreground activity.", null); verifyNoInteractions(mockImagePickerDelegate); } @Test public void onMethodCall_WhenCalledWithUnknownMethod_ThrowsException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Unknown method test"); plugin.onMethodCall(new MethodCall("test", null), mockResult); verifyNoInteractions(mockImagePickerDelegate); verifyNoInteractions(mockResult); } @Test public void onMethodCall_WhenCalledWithUnknownImageSource_ThrowsException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid image source: -1"); plugin.onMethodCall(buildMethodCall(PICK_IMAGE, -1), mockResult); verifyNoInteractions(mockImagePickerDelegate); verifyNoInteractions(mockResult); } @Test public void onMethodCall_WhenSourceIsGallery_InvokesChooseImageFromGallery() { MethodCall call = buildMethodCall(PICK_IMAGE, SOURCE_GALLERY); plugin.onMethodCall(call, mockResult); verify(mockImagePickerDelegate).chooseImageFromGallery(eq(call), any()); verifyNoInteractions(mockResult); } @Test public void onMethodCall_InvokesChooseMultiImageFromGallery() { MethodCall call = buildMethodCall(PICK_MULTI_IMAGE); plugin.onMethodCall(call, mockResult); verify(mockImagePickerDelegate).chooseMultiImageFromGallery(eq(call), any()); verifyNoInteractions(mockResult); } @Test public void onMethodCall_WhenSourceIsCamera_InvokesTakeImageWithCamera() { MethodCall call = buildMethodCall(PICK_IMAGE, SOURCE_CAMERA); plugin.onMethodCall(call, mockResult); verify(mockImagePickerDelegate).takeImageWithCamera(eq(call), any()); verifyNoInteractions(mockResult); } @Test public void onMethodCall_PickingImage_WhenSourceIsCamera_InvokesTakeImageWithCamera_RearCamera() { MethodCall call = buildMethodCall(PICK_IMAGE, SOURCE_CAMERA); HashMap<String, Object> arguments = (HashMap<String, Object>) call.arguments; arguments.put("cameraDevice", 0); plugin.onMethodCall(call, mockResult); verify(mockImagePickerDelegate).setCameraDevice(eq(CameraDevice.REAR)); } @Test public void onMethodCall_PickingImage_WhenSourceIsCamera_InvokesTakeImageWithCamera_FrontCamera() { MethodCall call = buildMethodCall(PICK_IMAGE, SOURCE_CAMERA); HashMap<String, Object> arguments = (HashMap<String, Object>) call.arguments; arguments.put("cameraDevice", 1); plugin.onMethodCall(call, mockResult); verify(mockImagePickerDelegate).setCameraDevice(eq(CameraDevice.FRONT)); } @Test public void onMethodCall_PickingVideo_WhenSourceIsCamera_InvokesTakeImageWithCamera_RearCamera() { MethodCall call = buildMethodCall(PICK_IMAGE, SOURCE_CAMERA); HashMap<String, Object> arguments = (HashMap<String, Object>) call.arguments; arguments.put("cameraDevice", 0); plugin.onMethodCall(call, mockResult); verify(mockImagePickerDelegate).setCameraDevice(eq(CameraDevice.REAR)); } @Test public void onMethodCall_PickingVideo_WhenSourceIsCamera_InvokesTakeImageWithCamera_FrontCamera() { MethodCall call = buildMethodCall(PICK_IMAGE, SOURCE_CAMERA); HashMap<String, Object> arguments = (HashMap<String, Object>) call.arguments; arguments.put("cameraDevice", 1); plugin.onMethodCall(call, mockResult); verify(mockImagePickerDelegate).setCameraDevice(eq(CameraDevice.FRONT)); } @Test public void onResiter_WhenAcitivityIsNull_ShouldNotCrash() { when(mockRegistrar.activity()).thenReturn(null); ImagePickerPlugin.registerWith((mockRegistrar)); assertTrue( "No exception thrown when ImagePickerPlugin.registerWith ran with activity = null", true); } @Test public void onConstructor_WhenContextTypeIsActivity_ShouldNotCrash() { new ImagePickerPlugin(mockImagePickerDelegate, mockActivity); assertTrue( "No exception thrown when ImagePickerPlugin() ran with context instanceof Activity", true); } @Test public void constructDelegate_ShouldUseInternalCacheDirectory() { File mockDirectory = new File("/mockpath"); when(mockActivity.getCacheDir()).thenReturn(mockDirectory); ImagePickerDelegate delegate = plugin.constructDelegate(mockActivity); verify(mockActivity, times(1)).getCacheDir(); assertThat( "Delegate uses cache directory for storing camera captures", delegate.externalFilesDirectory, equalTo(mockDirectory)); } @Test public void onDetachedFromActivity_ShouldReleaseActivityState() { final BinaryMessenger mockBinaryMessenger = mock(BinaryMessenger.class); when(mockPluginBinding.getBinaryMessenger()).thenReturn(mockBinaryMessenger); final HiddenLifecycleReference mockLifecycleReference = mock(HiddenLifecycleReference.class); when(mockActivityBinding.getLifecycle()).thenReturn(mockLifecycleReference); final Lifecycle mockLifecycle = mock(Lifecycle.class); when(mockLifecycleReference.getLifecycle()).thenReturn(mockLifecycle); plugin.onAttachedToEngine(mockPluginBinding); plugin.onAttachedToActivity(mockActivityBinding); assertNotNull(plugin.getActivityState()); plugin.onDetachedFromActivity(); assertNull(plugin.getActivityState()); } private MethodCall buildMethodCall(String method, final int source) { final Map<String, Object> arguments = new HashMap<>(); arguments.put("source", source); return new MethodCall(method, arguments); } private MethodCall buildMethodCall(String method) { return new MethodCall(method, null); } }
plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerPluginTest.java/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImagePickerPluginTest.java", "repo_id": "plugins", "token_count": 2797 }
1,105
name: image_picker_android description: Android implementation of the image_picker plugin. repository: https://github.com/flutter/plugins/tree/main/packages/image_picker/image_picker_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22 version: 0.8.5+6 environment: sdk: ">=2.14.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: image_picker platforms: android: package: io.flutter.plugins.imagepicker pluginClass: ImagePickerPlugin dartPluginClass: ImagePickerAndroid dependencies: flutter: sdk: flutter flutter_plugin_android_lifecycle: ^2.0.1 image_picker_platform_interface: ^2.5.0 dev_dependencies: flutter_test: sdk: flutter mockito: ^5.0.0
plugins/packages/image_picker/image_picker_android/pubspec.yaml/0
{ "file_path": "plugins/packages/image_picker/image_picker_android/pubspec.yaml", "repo_id": "plugins", "token_count": 326 }
1,106
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="12" height="7" viewBox="0 0 12 7"> <rect width="12" height="7" fill="red" /> </svg>
plugins/packages/image_picker/image_picker_ios/example/ios/TestImages/svgImage.svg/0
{ "file_path": "plugins/packages/image_picker/image_picker_ios/example/ios/TestImages/svgImage.svg", "repo_id": "plugins", "token_count": 66 }
1,107
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:file_selector_platform_interface/file_selector_platform_interface.dart'; import 'package:file_selector_windows/file_selector_windows.dart'; import 'package:flutter/foundation.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; /// The Windows implementation of [ImagePickerPlatform]. /// /// This class implements the `package:image_picker` functionality for /// Windows. class ImagePickerWindows extends ImagePickerPlatform { /// Constructs a ImagePickerWindows. ImagePickerWindows(); /// List of image extensions used when picking images @visibleForTesting static const List<String> imageFormats = <String>[ 'jpg', 'jpeg', 'png', 'bmp', 'webp', 'gif', 'tif', 'tiff', 'apng' ]; /// List of video extensions used when picking videos @visibleForTesting static const List<String> videoFormats = <String>[ 'mov', 'wmv', 'mkv', 'mp4', 'webm', 'avi', 'mpeg', 'mpg' ]; /// The file selector used to prompt the user to select images or videos. @visibleForTesting static FileSelectorPlatform fileSelector = FileSelectorWindows(); /// Registers this class as the default instance of [ImagePickerPlatform]. static void registerWith() { ImagePickerPlatform.instance = ImagePickerWindows(); } // `maxWidth`, `maxHeight`, `imageQuality` and `preferredCameraDevice` // arguments are not supported on Windows. If any of these arguments // is supplied, it'll be silently ignored by the Windows version of // the plugin. `source` is not implemented for `ImageSource.camera` // and will throw an exception. @override Future<PickedFile?> pickImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { final XFile? file = await getImage( source: source, maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice); if (file != null) { return PickedFile(file.path); } return null; } // `preferredCameraDevice` and `maxDuration` arguments are not // supported on Windows. If any of these arguments is supplied, // it'll be silently ignored by the Windows version of the plugin. // `source` is not implemented for `ImageSource.camera` and will // throw an exception. @override Future<PickedFile?> pickVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final XFile? file = await getVideo( source: source, preferredCameraDevice: preferredCameraDevice, maxDuration: maxDuration); if (file != null) { return PickedFile(file.path); } return null; } // `maxWidth`, `maxHeight`, `imageQuality`, and `preferredCameraDevice` // arguments are not supported on Windows. If any of these arguments // is supplied, it'll be silently ignored by the Windows version // of the plugin. `source` is not implemented for `ImageSource.camera` // and will throw an exception. @override Future<XFile?> getImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { if (source != ImageSource.gallery) { // TODO(azchohfi): Support ImageSource.camera. // See https://github.com/flutter/flutter/issues/102115 throw UnimplementedError( 'ImageSource.gallery is currently the only supported source on Windows'); } const XTypeGroup typeGroup = XTypeGroup(label: 'images', extensions: imageFormats); final XFile? file = await fileSelector .openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]); return file; } // `preferredCameraDevice` and `maxDuration` arguments are not // supported on Windows. If any of these arguments is supplied, // it'll be silently ignored by the Windows version of the plugin. // `source` is not implemented for `ImageSource.camera` and will // throw an exception. @override Future<XFile?> getVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { if (source != ImageSource.gallery) { // TODO(azchohfi): Support ImageSource.camera. // See https://github.com/flutter/flutter/issues/102115 throw UnimplementedError( 'ImageSource.gallery is currently the only supported source on Windows'); } const XTypeGroup typeGroup = XTypeGroup(label: 'videos', extensions: videoFormats); final XFile? file = await fileSelector .openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]); return file; } // `maxWidth`, `maxHeight`, and `imageQuality` arguments are not // supported on Windows. If any of these arguments is supplied, // it'll be silently ignored by the Windows version of the plugin. @override Future<List<XFile>> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { const XTypeGroup typeGroup = XTypeGroup(label: 'images', extensions: imageFormats); final List<XFile> files = await fileSelector .openFiles(acceptedTypeGroups: <XTypeGroup>[typeGroup]); return files; } }
plugins/packages/image_picker/image_picker_windows/lib/image_picker_windows.dart/0
{ "file_path": "plugins/packages/image_picker/image_picker_windows/lib/image_picker_windows.dart", "repo_id": "plugins", "token_count": 1867 }
1,108
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
plugins/packages/in_app_purchase/in_app_purchase/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "plugins", "token_count": 32 }
1,109
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; typedef AdditionalSteps = void Function(dynamic args); class StubInAppPurchasePlatform { final Map<String, dynamic> _expectedCalls = <String, dynamic>{}; final Map<String, AdditionalSteps?> _additionalSteps = <String, AdditionalSteps?>{}; void addResponse( {required String name, dynamic value, AdditionalSteps? additionalStepBeforeReturn}) { _additionalSteps[name] = additionalStepBeforeReturn; _expectedCalls[name] = value; } final List<MethodCall> _previousCalls = <MethodCall>[]; List<MethodCall> get previousCalls => _previousCalls; MethodCall previousCallMatching(String name) => _previousCalls.firstWhere((MethodCall call) => call.method == name); int countPreviousCalls(String name) => _previousCalls.where((MethodCall call) => call.method == name).length; void reset() { _expectedCalls.clear(); _previousCalls.clear(); _additionalSteps.clear(); } Future<dynamic> fakeMethodCallHandler(MethodCall call) async { _previousCalls.add(call); if (_expectedCalls.containsKey(call.method)) { if (_additionalSteps[call.method] != null) { _additionalSteps[call.method]!(call.arguments); } return Future<dynamic>.sync(() => _expectedCalls[call.method]); } else { return Future<void>.sync(() => null); } } }
plugins/packages/in_app_purchase/in_app_purchase_android/test/stub_in_app_purchase_platform.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/test/stub_in_app_purchase_platform.dart", "repo_id": "plugins", "token_count": 543 }
1,110
// 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. /// Status for a [PurchaseDetails]. /// /// This is the type for [PurchaseDetails.status]. enum PurchaseStatus { /// The purchase process is pending. /// /// You can update UI to let your users know the purchase is pending. pending, /// The purchase is finished and successful. /// /// Update your UI to indicate the purchase is finished and deliver the product. purchased, /// Some error occurred in the purchase. The purchasing process if aborted. error, /// The purchase has been restored to the device. /// /// You should validate the purchase and if valid deliver the content. Once the /// content has been delivered or if the receipt is invalid you should finish /// the purchase by calling the `completePurchase` method. More information on /// verifying purchases can be found [here](https://pub.dev/packages/in_app_purchase#restoring-previous-purchases). restored, /// The purchase has been canceled. /// /// Update your UI to indicate the purchase is canceled. canceled, }
plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/purchase_status.dart/0
{ "file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/purchase_status.dart", "repo_id": "plugins", "token_count": 294 }
1,111
name: ios_platform_images description: A plugin to share images between Flutter and iOS in add-to-app setups. repository: https://github.com/flutter/plugins/tree/main/packages/ios_platform_images issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+ios_platform_images%22 version: 0.2.2 environment: sdk: '>=2.18.0 <3.0.0' flutter: ">=3.3.0" flutter: plugin: platforms: ios: pluginClass: IosPlatformImagesPlugin dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter
plugins/packages/ios_platform_images/pubspec.yaml/0
{ "file_path": "plugins/packages/ios_platform_images/pubspec.yaml", "repo_id": "plugins", "token_count": 237 }
1,112
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- Fingerprint colors --> <color name="warning_color">#E53935</color> <color name="hint_color">#BDBDBD</color> <color name="success_color">#43A047</color> <color name="black_text">#212121</color> <color name="grey_text">#757575</color> </resources>
plugins/packages/local_auth/local_auth_android/android/src/main/res/values/colors.xml/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/res/values/colors.xml", "repo_id": "plugins", "token_count": 118 }
1,113
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true android.enableR8=true
plugins/packages/local_auth/local_auth_android/example/android/gradle.properties/0
{ "file_path": "plugins/packages/local_auth/local_auth_android/example/android/gradle.properties", "repo_id": "plugins", "token_count": 38 }
1,114
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import LocalAuthentication; @import XCTest; #import <OCMock/OCMock.h> #if __has_include(<local_auth/FLTLocalAuthPlugin.h>) #import <local_auth/FLTLocalAuthPlugin.h> #else @import local_auth_ios; #endif // Private API needed for tests. @interface FLTLocalAuthPlugin (Test) - (void)setAuthContextOverrides:(NSArray<LAContext *> *)authContexts; @end // Set a long timeout to avoid flake due to slow CI. static const NSTimeInterval kTimeout = 30.0; @interface FLTLocalAuthPluginTests : XCTestCase @end @implementation FLTLocalAuthPluginTests - (void)setUp { self.continueAfterFailure = NO; } - (void)testSuccessfullAuthWithBiometrics { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; NSString *reason = @"a reason"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(YES, nil); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"authenticate" arguments:@{ @"biometricOnly" : @(YES), @"localizedReason" : reason, }]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSNumber class]]); XCTAssertTrue([result boolValue]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testSuccessfullAuthWithoutBiometrics { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; NSString *reason = @"a reason"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(YES, nil); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"authenticate" arguments:@{ @"biometricOnly" : @(NO), @"localizedReason" : reason, }]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSNumber class]]); XCTAssertTrue([result boolValue]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testFailedAuthWithBiometrics { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; NSString *reason = @"a reason"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(NO, [NSError errorWithDomain:@"error" code:LAErrorAuthenticationFailed userInfo:nil]); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"authenticate" arguments:@{ @"biometricOnly" : @(YES), @"localizedReason" : reason, }]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[FlutterError class]]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testFailedWithUnknownErrorCode { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; NSString *reason = @"a reason"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(NO, [NSError errorWithDomain:@"error" code:99 userInfo:nil]); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"authenticate" arguments:@{ @"biometricOnly" : @(NO), @"localizedReason" : reason, }]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[FlutterError class]]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testSystemCancelledWithoutStickyAuth { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; NSString *reason = @"a reason"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(NO, [NSError errorWithDomain:@"error" code:LAErrorSystemCancel userInfo:nil]); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"authenticate" arguments:@{ @"biometricOnly" : @(NO), @"localizedReason" : reason, @"stickyAuth" : @(NO) }]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSNumber class]]); XCTAssertFalse([result boolValue]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testFailedAuthWithoutBiometrics { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; NSString *reason = @"a reason"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(NO, [NSError errorWithDomain:@"error" code:LAErrorAuthenticationFailed userInfo:nil]); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"authenticate" arguments:@{ @"biometricOnly" : @(NO), @"localizedReason" : reason, }]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[FlutterError class]]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testLocalizedFallbackTitle { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; NSString *reason = @"a reason"; NSString *localizedFallbackTitle = @"a title"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(YES, nil); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"authenticate" arguments:@{ @"biometricOnly" : @(NO), @"localizedReason" : reason, @"localizedFallbackTitle" : localizedFallbackTitle, }]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { OCMVerify([mockAuthContext setLocalizedFallbackTitle:localizedFallbackTitle]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testSkippedLocalizedFallbackTitle { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthentication; NSString *reason = @"a reason"; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. void (^backgroundThreadReplyCaller)(NSInvocation *) = ^(NSInvocation *invocation) { void (^reply)(BOOL, NSError *); [invocation getArgument:&reply atIndex:4]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ reply(YES, nil); }); }; OCMStub([mockAuthContext evaluatePolicy:policy localizedReason:reason reply:[OCMArg any]]) .andDo(backgroundThreadReplyCaller); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"authenticate" arguments:@{ @"biometricOnly" : @(NO), @"localizedReason" : reason, }]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { OCMVerify([mockAuthContext setLocalizedFallbackTitle:nil]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testDeviceSupportsBiometrics_withEnrolledHardware { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"deviceSupportsBiometrics" arguments:@{}]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSNumber class]]); XCTAssertTrue([result boolValue]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testDeviceSupportsBiometrics_withNonEnrolledHardware_iOS11 { if (@available(iOS 11, *)) { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; void (^canEvaluatePolicyHandler)(NSInvocation *) = ^(NSInvocation *invocation) { // Write error NSError *__autoreleasing *authError; [invocation getArgument:&authError atIndex:3]; *authError = [NSError errorWithDomain:@"error" code:LAErrorBiometryNotEnrolled userInfo:nil]; // Write return value BOOL returnValue = NO; NSValue *nsReturnValue = [NSValue valueWithBytes:&returnValue objCType:@encode(BOOL)]; [invocation setReturnValue:&nsReturnValue]; }; OCMStub([mockAuthContext canEvaluatePolicy:policy error:(NSError * __autoreleasing *)[OCMArg anyPointer]]) .andDo(canEvaluatePolicyHandler); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"deviceSupportsBiometrics" arguments:@{}]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSNumber class]]); XCTAssertTrue([result boolValue]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } } - (void)testDeviceSupportsBiometrics_withNoBiometricHardware { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; void (^canEvaluatePolicyHandler)(NSInvocation *) = ^(NSInvocation *invocation) { // Write error NSError *__autoreleasing *authError; [invocation getArgument:&authError atIndex:3]; *authError = [NSError errorWithDomain:@"error" code:0 userInfo:nil]; // Write return value BOOL returnValue = NO; NSValue *nsReturnValue = [NSValue valueWithBytes:&returnValue objCType:@encode(BOOL)]; [invocation setReturnValue:&nsReturnValue]; }; OCMStub([mockAuthContext canEvaluatePolicy:policy error:(NSError * __autoreleasing *)[OCMArg anyPointer]]) .andDo(canEvaluatePolicyHandler); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"deviceSupportsBiometrics" arguments:@{}]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSNumber class]]); XCTAssertFalse([result boolValue]); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testGetEnrolledBiometrics_withFaceID_iOS11 { if (@available(iOS 11, *)) { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); OCMStub([mockAuthContext biometryType]).andReturn(LABiometryTypeFaceID); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"getEnrolledBiometrics" arguments:@{}]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSArray class]]); XCTAssertEqual([result count], 1); XCTAssertEqualObjects(result[0], @"face"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } } - (void)testGetEnrolledBiometrics_withTouchID_iOS11 { if (@available(iOS 11, *)) { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); OCMStub([mockAuthContext biometryType]).andReturn(LABiometryTypeTouchID); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"getEnrolledBiometrics" arguments:@{}]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSArray class]]); XCTAssertEqual([result count], 1); XCTAssertEqualObjects(result[0], @"fingerprint"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } } - (void)testGetEnrolledBiometrics_withTouchID_preIOS11 { if (@available(iOS 11, *)) { return; } FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; OCMStub([mockAuthContext canEvaluatePolicy:policy error:[OCMArg setTo:nil]]).andReturn(YES); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"getEnrolledBiometrics" arguments:@{}]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSArray class]]); XCTAssertEqual([result count], 1); XCTAssertEqualObjects(result[0], @"fingerprint"); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } - (void)testGetEnrolledBiometrics_withoutEnrolledHardware_iOS11 { if (@available(iOS 11, *)) { FLTLocalAuthPlugin *plugin = [[FLTLocalAuthPlugin alloc] init]; id mockAuthContext = OCMClassMock([LAContext class]); plugin.authContextOverrides = @[ mockAuthContext ]; const LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; void (^canEvaluatePolicyHandler)(NSInvocation *) = ^(NSInvocation *invocation) { // Write error NSError *__autoreleasing *authError; [invocation getArgument:&authError atIndex:3]; *authError = [NSError errorWithDomain:@"error" code:LAErrorBiometryNotEnrolled userInfo:nil]; // Write return value BOOL returnValue = NO; NSValue *nsReturnValue = [NSValue valueWithBytes:&returnValue objCType:@encode(BOOL)]; [invocation setReturnValue:&nsReturnValue]; }; OCMStub([mockAuthContext canEvaluatePolicy:policy error:(NSError * __autoreleasing *)[OCMArg anyPointer]]) .andDo(canEvaluatePolicyHandler); FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"getEnrolledBiometrics" arguments:@{}]; XCTestExpectation *expectation = [self expectationWithDescription:@"Result is called"]; [plugin handleMethodCall:call result:^(id _Nullable result) { XCTAssertTrue([NSThread isMainThread]); XCTAssertTrue([result isKindOfClass:[NSArray class]]); XCTAssertEqual([result count], 0); [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:kTimeout handler:nil]; } } @end
plugins/packages/local_auth/local_auth_ios/example/ios/RunnerTests/FLTLocalAuthPluginTests.m/0
{ "file_path": "plugins/packages/local_auth/local_auth_ios/example/ios/RunnerTests/FLTLocalAuthPluginTests.m", "repo_id": "plugins", "token_count": 11610 }
1,115
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v5.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon #undef _HAS_EXCEPTIONS #include "messages.g.h" #include <flutter/basic_message_channel.h> #include <flutter/binary_messenger.h> #include <flutter/encodable_value.h> #include <flutter/standard_message_codec.h> #include <map> #include <optional> #include <string> namespace local_auth_windows { /// The codec used by LocalAuthApi. const flutter::StandardMessageCodec& LocalAuthApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &flutter::StandardCodecSerializer::GetInstance()); } // Sets up an instance of `LocalAuthApi` to handle messages through the // `binary_messenger`. void LocalAuthApi::SetUp(flutter::BinaryMessenger* binary_messenger, LocalAuthApi* api) { { auto channel = std::make_unique<flutter::BasicMessageChannel<flutter::EncodableValue>>( binary_messenger, "dev.flutter.pigeon.LocalAuthApi.isDeviceSupported", &GetCodec()); if (api != nullptr) { channel->SetMessageHandler( [api](const flutter::EncodableValue& message, const flutter::MessageReply<flutter::EncodableValue>& reply) { try { api->IsDeviceSupported([reply](ErrorOr<bool>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } flutter::EncodableList wrapped; wrapped.push_back( flutter::EncodableValue(std::move(output).TakeValue())); reply(flutter::EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel->SetMessageHandler(nullptr); } } { auto channel = std::make_unique<flutter::BasicMessageChannel<flutter::EncodableValue>>( binary_messenger, "dev.flutter.pigeon.LocalAuthApi.authenticate", &GetCodec()); if (api != nullptr) { channel->SetMessageHandler( [api](const flutter::EncodableValue& message, const flutter::MessageReply<flutter::EncodableValue>& reply) { try { const auto& args = std::get<flutter::EncodableList>(message); const auto& encodable_localized_reason_arg = args.at(0); if (encodable_localized_reason_arg.IsNull()) { reply(WrapError("localized_reason_arg unexpectedly null.")); return; } const auto& localized_reason_arg = std::get<std::string>(encodable_localized_reason_arg); api->Authenticate( localized_reason_arg, [reply](ErrorOr<bool>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } flutter::EncodableList wrapped; wrapped.push_back( flutter::EncodableValue(std::move(output).TakeValue())); reply(flutter::EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel->SetMessageHandler(nullptr); } } } flutter::EncodableValue LocalAuthApi::WrapError( std::string_view error_message) { return flutter::EncodableValue(flutter::EncodableList{ flutter::EncodableValue(std::string(error_message)), flutter::EncodableValue("Error"), flutter::EncodableValue()}); } flutter::EncodableValue LocalAuthApi::WrapError(const FlutterError& error) { return flutter::EncodableValue(flutter::EncodableList{ flutter::EncodableValue(error.message()), flutter::EncodableValue(error.code()), error.details()}); } } // namespace local_auth_windows
plugins/packages/local_auth/local_auth_windows/windows/messages.g.cpp/0
{ "file_path": "plugins/packages/local_auth/local_auth_windows/windows/messages.g.cpp", "repo_id": "plugins", "token_count": 1927 }
1,116
name: path_provider_foundation description: iOS and macOS implementation of the path_provider plugin repository: https://github.com/flutter/plugins/tree/main/packages/path_provider/path_provider_foundation issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 version: 2.1.1 environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=3.0.0" flutter: plugin: implements: path_provider platforms: ios: pluginClass: PathProviderPlugin dartPluginClass: PathProviderFoundation sharedDarwinSource: true macos: pluginClass: PathProviderPlugin dartPluginClass: PathProviderFoundation sharedDarwinSource: true dependencies: flutter: sdk: flutter path_provider_platform_interface: ^2.0.1 dev_dependencies: build_runner: ^2.3.2 flutter_test: sdk: flutter mockito: ^5.3.2 path: ^1.8.0 pigeon: ^5.0.0
plugins/packages/path_provider/path_provider_foundation/pubspec.yaml/0
{ "file_path": "plugins/packages/path_provider/path_provider_foundation/pubspec.yaml", "repo_id": "plugins", "token_count": 386 }
1,117
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.quickactions; import static io.flutter.plugins.quickactions.MethodCallHandlerImpl.EXTRA_ACTION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ShortcutManager; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.StandardMethodCodec; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import org.junit.After; import org.junit.Test; public class QuickActionsTest { private static class TestBinaryMessenger implements BinaryMessenger { public MethodCall lastMethodCall; @Override public void send(@NonNull String channel, @Nullable ByteBuffer message) { send(channel, message, null); } @Override public void send( @NonNull String channel, @Nullable ByteBuffer message, @Nullable final BinaryReply callback) { if (channel.equals("plugins.flutter.io/quick_actions_android")) { lastMethodCall = StandardMethodCodec.INSTANCE.decodeMethodCall((ByteBuffer) message.position(0)); } } @Override public void setMessageHandler(@NonNull String channel, @Nullable BinaryMessageHandler handler) { // Do nothing. } } static final int SUPPORTED_BUILD = 25; static final int UNSUPPORTED_BUILD = 24; static final String SHORTCUT_TYPE = "action_one"; @Test public void canAttachToEngine() { final TestBinaryMessenger testBinaryMessenger = new TestBinaryMessenger(); final FlutterPluginBinding mockPluginBinding = mock(FlutterPluginBinding.class); when(mockPluginBinding.getBinaryMessenger()).thenReturn(testBinaryMessenger); final QuickActionsPlugin plugin = new QuickActionsPlugin(); plugin.onAttachedToEngine(mockPluginBinding); } @Test public void onAttachedToActivity_buildVersionSupported_invokesLaunchMethod() throws NoSuchFieldException, IllegalAccessException { // Arrange final TestBinaryMessenger testBinaryMessenger = new TestBinaryMessenger(); final QuickActionsPlugin plugin = new QuickActionsPlugin(); setUpMessengerAndFlutterPluginBinding(testBinaryMessenger, plugin); setBuildVersion(SUPPORTED_BUILD); Field handler = plugin.getClass().getDeclaredField("handler"); handler.setAccessible(true); handler.set(plugin, mock(MethodCallHandlerImpl.class)); final Intent mockIntent = createMockIntentWithQuickActionExtra(); final Activity mockMainActivity = mock(Activity.class); when(mockMainActivity.getIntent()).thenReturn(mockIntent); final ActivityPluginBinding mockActivityPluginBinding = mock(ActivityPluginBinding.class); when(mockActivityPluginBinding.getActivity()).thenReturn(mockMainActivity); final Context mockContext = mock(Context.class); when(mockMainActivity.getApplicationContext()).thenReturn(mockContext); final ShortcutManager mockShortcutManager = mock(ShortcutManager.class); when(mockContext.getSystemService(Context.SHORTCUT_SERVICE)).thenReturn(mockShortcutManager); plugin.onAttachedToActivity(mockActivityPluginBinding); // Act plugin.onAttachedToActivity(mockActivityPluginBinding); // Assert assertNotNull(testBinaryMessenger.lastMethodCall); assertEquals(testBinaryMessenger.lastMethodCall.method, "launch"); assertEquals(testBinaryMessenger.lastMethodCall.arguments, SHORTCUT_TYPE); } @Test public void onNewIntent_buildVersionUnsupported_doesNotInvokeMethod() throws NoSuchFieldException, IllegalAccessException { // Arrange final TestBinaryMessenger testBinaryMessenger = new TestBinaryMessenger(); final QuickActionsPlugin plugin = new QuickActionsPlugin(); setUpMessengerAndFlutterPluginBinding(testBinaryMessenger, plugin); setBuildVersion(UNSUPPORTED_BUILD); final Intent mockIntent = createMockIntentWithQuickActionExtra(); // Act final boolean onNewIntentReturn = plugin.onNewIntent(mockIntent); // Assert assertNull(testBinaryMessenger.lastMethodCall); assertFalse(onNewIntentReturn); } @Test public void onNewIntent_buildVersionSupported_invokesLaunchMethod() throws NoSuchFieldException, IllegalAccessException { // Arrange final TestBinaryMessenger testBinaryMessenger = new TestBinaryMessenger(); final QuickActionsPlugin plugin = new QuickActionsPlugin(); setUpMessengerAndFlutterPluginBinding(testBinaryMessenger, plugin); setBuildVersion(SUPPORTED_BUILD); final Intent mockIntent = createMockIntentWithQuickActionExtra(); final Activity mockMainActivity = mock(Activity.class); when(mockMainActivity.getIntent()).thenReturn(mockIntent); final ActivityPluginBinding mockActivityPluginBinding = mock(ActivityPluginBinding.class); when(mockActivityPluginBinding.getActivity()).thenReturn(mockMainActivity); final Context mockContext = mock(Context.class); when(mockMainActivity.getApplicationContext()).thenReturn(mockContext); final ShortcutManager mockShortcutManager = mock(ShortcutManager.class); when(mockContext.getSystemService(Context.SHORTCUT_SERVICE)).thenReturn(mockShortcutManager); plugin.onAttachedToActivity(mockActivityPluginBinding); // Act final boolean onNewIntentReturn = plugin.onNewIntent(mockIntent); // Assert assertNotNull(testBinaryMessenger.lastMethodCall); assertEquals(testBinaryMessenger.lastMethodCall.method, "launch"); assertEquals(testBinaryMessenger.lastMethodCall.arguments, SHORTCUT_TYPE); assertFalse(onNewIntentReturn); } private void setUpMessengerAndFlutterPluginBinding( TestBinaryMessenger testBinaryMessenger, QuickActionsPlugin plugin) { final FlutterPluginBinding mockPluginBinding = mock(FlutterPluginBinding.class); when(mockPluginBinding.getBinaryMessenger()).thenReturn(testBinaryMessenger); plugin.onAttachedToEngine(mockPluginBinding); } private Intent createMockIntentWithQuickActionExtra() { final Intent mockIntent = mock(Intent.class); when(mockIntent.hasExtra(EXTRA_ACTION)).thenReturn(true); when(mockIntent.getStringExtra(EXTRA_ACTION)).thenReturn(QuickActionsTest.SHORTCUT_TYPE); return mockIntent; } private void setBuildVersion(int buildVersion) throws NoSuchFieldException, IllegalAccessException { Field buildSdkField = Build.VERSION.class.getField("SDK_INT"); buildSdkField.setAccessible(true); final Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(buildSdkField, buildSdkField.getModifiers() & ~Modifier.FINAL); buildSdkField.set(null, buildVersion); } @After public void tearDown() throws NoSuchFieldException, IllegalAccessException { setBuildVersion(0); } }
plugins/packages/quick_actions/quick_actions_android/android/src/test/java/io/flutter/plugins/quickactions/QuickActionsTest.java/0
{ "file_path": "plugins/packages/quick_actions/quick_actions_android/android/src/test/java/io/flutter/plugins/quickactions/QuickActionsTest.java", "repo_id": "plugins", "token_count": 2407 }
1,118
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter import XCTest @testable import quick_actions_ios class DefaultShortcutItemParserTests: XCTestCase { func testParseShortcutItems() { let rawItem = [ "type": "SearchTheThing", "localizedTitle": "Search the thing", "icon": "search_the_thing.png", ] let expectedItem = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"), userInfo: nil) let parser = DefaultShortcutItemParser() XCTAssertEqual(parser.parseShortcutItems([rawItem]), [expectedItem]) } func testParseShortcutItems_noIcon() { let rawItem: [String: Any] = [ "type": "SearchTheThing", "localizedTitle": "Search the thing", "icon": NSNull(), ] let expectedItem = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", localizedSubtitle: nil, icon: nil, userInfo: nil) let parser = DefaultShortcutItemParser() XCTAssertEqual(parser.parseShortcutItems([rawItem]), [expectedItem]) } func testParseShortcutItems_noType() { let rawItem = [ "localizedTitle": "Search the thing", "icon": "search_the_thing.png", ] let parser = DefaultShortcutItemParser() XCTAssertEqual(parser.parseShortcutItems([rawItem]), []) } func testParseShortcutItems_noLocalizedTitle() { let rawItem = [ "type": "SearchTheThing", "icon": "search_the_thing.png", ] let parser = DefaultShortcutItemParser() XCTAssertEqual(parser.parseShortcutItems([rawItem]), []) } }
plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/DefaultShortcutItemParserTests.swift/0
{ "file_path": "plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/DefaultShortcutItemParserTests.swift", "repo_id": "plugins", "token_count": 689 }
1,119
// 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:quick_actions_platform_interface/method_channel/method_channel_quick_actions.dart'; import 'package:quick_actions_platform_interface/platform_interface/quick_actions_platform.dart'; import 'package:quick_actions_platform_interface/types/types.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Store the initial instance before any tests change it. final QuickActionsPlatform initialInstance = QuickActionsPlatform.instance; group('$QuickActionsPlatform', () { test('$MethodChannelQuickActions is the default instance', () { expect(initialInstance, isA<MethodChannelQuickActions>()); }); test('Cannot be implemented with `implements`', () { expect(() { QuickActionsPlatform.instance = ImplementsQuickActionsPlatform(); // In versions of `package:plugin_platform_interface` prior to fixing // https://github.com/flutter/flutter/issues/109339, an attempt to // implement a platform interface using `implements` would sometimes // throw a `NoSuchMethodError` and other times throw an // `AssertionError`. After the issue is fixed, an `AssertionError` will // always be thrown. For the purpose of this test, we don't really care // what exception is thrown, so just allow any exception. }, throwsA(anything)); }); test('Can be extended', () { QuickActionsPlatform.instance = ExtendsQuickActionsPlatform(); }); test( 'Default implementation of initialize() should throw unimplemented error', () { // Arrange final ExtendsQuickActionsPlatform quickActionsPlatform = ExtendsQuickActionsPlatform(); // Act & Assert expect( () => quickActionsPlatform.initialize((String type) {}), throwsUnimplementedError, ); }); test( 'Default implementation of setShortcutItems() should throw unimplemented error', () { // Arrange final ExtendsQuickActionsPlatform quickActionsPlatform = ExtendsQuickActionsPlatform(); // Act & Assert expect( () => quickActionsPlatform.setShortcutItems(<ShortcutItem>[]), throwsUnimplementedError, ); }); test( 'Default implementation of clearShortcutItems() should throw unimplemented error', () { // Arrange final ExtendsQuickActionsPlatform quickActionsPlatform = ExtendsQuickActionsPlatform(); // Act & Assert expect( () => quickActionsPlatform.clearShortcutItems(), throwsUnimplementedError, ); }); }); } class ImplementsQuickActionsPlatform implements QuickActionsPlatform { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } class ExtendsQuickActionsPlatform extends QuickActionsPlatform {}
plugins/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart/0
{ "file_path": "plugins/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart", "repo_id": "plugins", "token_count": 1041 }
1,120
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" #include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
plugins/packages/shared_preferences/shared_preferences/example/ios/Flutter/Release.xcconfig/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences/example/ios/Flutter/Release.xcconfig", "repo_id": "plugins", "token_count": 69 }
1,121
## 2.1.3 * Uses the new `sharedDarwinSource` flag when available. * Updates minimum Flutter version to 3.0. ## 2.1.2 * Updates code for stricter lint checks. ## 2.1.1 * Adds Swift runtime search paths in podspec to avoid crash in Objective-C apps. Convert example app to Objective-C to catch future Swift runtime issues. ## 2.1.0 * Renames the package previously published as [`shared_preferences_macos`](https://pub.dev/packages/shared_preferences_macos) * Adds iOS support.
plugins/packages/shared_preferences/shared_preferences_foundation/CHANGELOG.md/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/CHANGELOG.md", "repo_id": "plugins", "token_count": 153 }
1,122
## NEXT * Updates minimum Flutter version to 3.0. ## 2.1.3 * Updates code for stricter lint checks. ## 2.1.2 * Updates code for stricter lint checks. * Updates code for `no_leading_underscores_for_local_identifiers` lint. * Updates minimum Flutter version to 2.10. ## 2.1.1 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.1.0 * Deprecated `SharedPreferencesWindows.instance` in favor of `SharedPreferencesStorePlatform.instance`. ## 2.0.4 * Removes dependency on `meta`. ## 2.0.3 * Removed obsolete `pluginClass: none` from pubpsec. * Fixes newly enabled analyzer options. ## 2.0.2 * Updated installation instructions in README. ## 2.0.1 * Add `implements` to the pubspec. * Add `registerWith` to the Dart main class. ## 2.0.0 * Migrate to null-safety. ## 0.0.3+1 * Update Flutter SDK constraint. ## 0.0.3 * Update integration test examples to use `testWidgets` instead of `test`. ## 0.0.2+4 * Remove unused `test` dependency. * Update Dart SDK constraint in example. ## 0.0.2+3 * Check in linux/ directory for example/ ## 0.0.2+2 * Bump the `file` package dependency to resolve dep conflicts with `flutter_driver`. ## 0.0.2+1 * Replace path_provider dependency with path_provider_linux. ## 0.0.2 * Add iOS stub. ## 0.0.1 * Initial release to support shared_preferences on Linux.
plugins/packages/shared_preferences/shared_preferences_linux/CHANGELOG.md/0
{ "file_path": "plugins/packages/shared_preferences/shared_preferences_linux/CHANGELOG.md", "repo_id": "plugins", "token_count": 493 }
1,123
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
plugins/packages/url_launcher/url_launcher/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "plugins/packages/url_launcher/url_launcher/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "plugins", "token_count": 32 }
1,124
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher_android/url_launcher_android.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); const MethodChannel channel = MethodChannel('plugins.flutter.io/url_launcher_android'); late List<MethodCall> log; setUp(() { log = <MethodCall>[]; _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { log.add(methodCall); // Return null explicitly instead of relying on the implicit null // returned by the method channel if no return statement is specified. return null; }); }); test('registers instance', () { UrlLauncherAndroid.registerWith(); expect(UrlLauncherPlatform.instance, isA<UrlLauncherAndroid>()); }); group('canLaunch', () { test('calls through', () async { _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { log.add(methodCall); return true; }); final UrlLauncherAndroid launcher = UrlLauncherAndroid(); final bool canLaunch = await launcher.canLaunch('http://example.com/'); expect( log, <Matcher>[ isMethodCall('canLaunch', arguments: <String, Object>{ 'url': 'http://example.com/', }) ], ); expect(canLaunch, true); }); test('returns false if platform returns null', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); final bool canLaunch = await launcher.canLaunch('http://example.com/'); expect(canLaunch, false); }); test('checks a generic URL if an http URL returns false', () async { const String specificUrl = 'http://example.com/'; const String genericUrl = 'http://flutter.dev'; _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { log.add(methodCall); return (methodCall.arguments as Map<Object?, Object?>)['url'] != specificUrl; }); final UrlLauncherAndroid launcher = UrlLauncherAndroid(); final bool canLaunch = await launcher.canLaunch(specificUrl); expect(canLaunch, true); expect(log.length, 2); expect((log[1].arguments as Map<Object?, Object?>)['url'], genericUrl); }); test('checks a generic URL if an https URL returns false', () async { const String specificUrl = 'https://example.com/'; const String genericUrl = 'https://flutter.dev'; _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { log.add(methodCall); return (methodCall.arguments as Map<Object?, Object?>)['url'] != specificUrl; }); final UrlLauncherAndroid launcher = UrlLauncherAndroid(); final bool canLaunch = await launcher.canLaunch(specificUrl); expect(canLaunch, true); expect(log.length, 2); expect((log[1].arguments as Map<Object?, Object?>)['url'], genericUrl); }); test('does not a generic URL if a non-web URL returns false', () async { _ambiguate(TestDefaultBinaryMessengerBinding.instance)! .defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { log.add(methodCall); return false; }); final UrlLauncherAndroid launcher = UrlLauncherAndroid(); final bool canLaunch = await launcher.canLaunch('sms:12345'); expect(canLaunch, false); expect(log.length, 1); }); }); group('launch', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'useWebView': false, 'enableJavaScript': false, 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': <String, String>{}, }) ], ); }); test('passes headers', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{'key': 'value'}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'useWebView': false, 'enableJavaScript': false, 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': <String, String>{'key': 'value'}, }) ], ); }); test('handles universal links only', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); await launcher.launch( 'http://example.com/', useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: true, headers: const <String, String>{}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'useWebView': false, 'enableJavaScript': false, 'enableDomStorage': false, 'universalLinksOnly': true, 'headers': <String, String>{}, }) ], ); }); test('handles force WebView', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: true, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'useWebView': true, 'enableJavaScript': false, 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': <String, String>{}, }) ], ); }); test('handles force WebView with javascript', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: true, enableJavaScript: true, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'useWebView': true, 'enableJavaScript': true, 'enableDomStorage': false, 'universalLinksOnly': false, 'headers': <String, String>{}, }) ], ); }); test('handles force WebView with DOM storage', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: true, enableJavaScript: false, enableDomStorage: true, universalLinksOnly: false, headers: const <String, String>{}, ); expect( log, <Matcher>[ isMethodCall('launch', arguments: <String, Object>{ 'url': 'http://example.com/', 'useWebView': true, 'enableJavaScript': false, 'enableDomStorage': true, 'universalLinksOnly': false, 'headers': <String, String>{}, }) ], ); }); test('returns false if platform returns null', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); final bool launched = await launcher.launch( 'http://example.com/', useSafariVC: true, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ); expect(launched, false); }); }); group('closeWebView', () { test('calls through', () async { final UrlLauncherAndroid launcher = UrlLauncherAndroid(); await launcher.closeWebView(); expect( log, <Matcher>[isMethodCall('closeWebView', arguments: null)], ); }); }); } /// This allows a value of type T or T? to be treated as a value of type T?. /// /// We use this so that APIs that have become non-nullable can still be used /// with `!` and `?` on the stable branch. T? _ambiguate<T>(T? value) => value;
plugins/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart", "repo_id": "plugins", "token_count": 4115 }
1,125
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; const MethodChannel _channel = MethodChannel('plugins.flutter.io/url_launcher_ios'); /// An implementation of [UrlLauncherPlatform] for iOS. class UrlLauncherIOS extends UrlLauncherPlatform { /// Registers this class as the default instance of [UrlLauncherPlatform]. static void registerWith() { UrlLauncherPlatform.instance = UrlLauncherIOS(); } @override final LinkDelegate? linkDelegate = null; @override Future<bool> canLaunch(String url) { return _channel.invokeMethod<bool>( 'canLaunch', <String, Object>{'url': url}, ).then((bool? value) => value ?? false); } @override Future<void> closeWebView() { return _channel.invokeMethod<void>('closeWebView'); } @override Future<bool> launch( String url, { required bool useSafariVC, required bool useWebView, required bool enableJavaScript, required bool enableDomStorage, required bool universalLinksOnly, required Map<String, String> headers, String? webOnlyWindowName, }) { return _channel.invokeMethod<bool>( 'launch', <String, Object>{ 'url': url, 'useSafariVC': useSafariVC, 'enableJavaScript': enableJavaScript, 'enableDomStorage': enableDomStorage, 'universalLinksOnly': universalLinksOnly, 'headers': headers, }, ).then((bool? value) => value ?? false); } }
plugins/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart", "repo_id": "plugins", "token_count": 610 }
1,126
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import FlutterMacOS import XCTest import url_launcher_macos /// A stub to simulate the system Url handler. class StubWorkspace: SystemURLHandler { var isSuccessful = true func open(_ url: URL) -> Bool { return isSuccessful } func urlForApplication(toOpen: URL) -> URL? { return toOpen } } class RunnerTests: XCTestCase { func testCanLaunchSuccessReturnsTrue() throws { let expectation = XCTestExpectation(description: "Check if the URL can be launched") let plugin = UrlLauncherPlugin() let call = FlutterMethodCall( methodName: "canLaunch", arguments: ["url": "https://flutter.dev"]) plugin.handle( call, result: { (result: Any?) -> Void in XCTAssertEqual(result as? Bool, true) expectation.fulfill() }) wait(for: [expectation], timeout: 10.0) } func testCanLaunchNoAppIsAbleToOpenUrlReturnsFalse() throws { let expectation = XCTestExpectation(description: "Check if the URL can be launched") let plugin = UrlLauncherPlugin() let call = FlutterMethodCall( methodName: "canLaunch", arguments: ["url": "example://flutter.dev"]) plugin.handle( call, result: { (result: Any?) -> Void in XCTAssertEqual(result as? Bool, false) expectation.fulfill() }) wait(for: [expectation], timeout: 10.0) } func testCanLaunchInvalidUrlReturnsFalse() throws { let expectation = XCTestExpectation(description: "Check if the URL can be launched") let plugin = UrlLauncherPlugin() let call = FlutterMethodCall( methodName: "canLaunch", arguments: ["url": "brokenUrl"]) plugin.handle( call, result: { (result: Any?) -> Void in XCTAssertEqual(result as? Bool, false) expectation.fulfill() }) wait(for: [expectation], timeout: 10.0) } func testCanLaunchMissingArgumentReturnsFlutterError() throws { let expectation = XCTestExpectation(description: "Check if the URL can be launched") let plugin = UrlLauncherPlugin() let call = FlutterMethodCall( methodName: "canLaunch", arguments: []) plugin.handle( call, result: { (result: Any?) -> Void in XCTAssertTrue(result is FlutterError) expectation.fulfill() }) wait(for: [expectation], timeout: 10.0) } func testLaunchSuccessReturnsTrue() throws { let expectation = XCTestExpectation(description: "Try to open the URL") let workspace = StubWorkspace() let pluginWithStubWorkspace = UrlLauncherPlugin(workspace) let call = FlutterMethodCall( methodName: "launch", arguments: ["url": "https://flutter.dev"]) pluginWithStubWorkspace.handle( call, result: { (result: Any?) -> Void in XCTAssertEqual(result as? Bool, true) expectation.fulfill() }) wait(for: [expectation], timeout: 10.0) } func testLaunchNoAppIsAbleToOpenUrlReturnsFalse() throws { let expectation = XCTestExpectation(description: "Try to open the URL") let workspace = StubWorkspace() workspace.isSuccessful = false let pluginWithStubWorkspace = UrlLauncherPlugin(workspace) let call = FlutterMethodCall( methodName: "launch", arguments: ["url": "schemethatdoesnotexist://flutter.dev"]) pluginWithStubWorkspace.handle( call, result: { (result: Any?) -> Void in XCTAssertEqual(result as? Bool, false) expectation.fulfill() }) wait(for: [expectation], timeout: 10.0) } func testLaunchMissingArgumentReturnsFlutterError() throws { let expectation = XCTestExpectation(description: "Try to open the URL") let workspace = StubWorkspace() let pluginWithStubWorkspace = UrlLauncherPlugin(workspace) let call = FlutterMethodCall( methodName: "launch", arguments: []) pluginWithStubWorkspace.handle( call, result: { (result: Any?) -> Void in XCTAssertTrue(result is FlutterError) expectation.fulfill() }) wait(for: [expectation], timeout: 10.0) } }
plugins/packages/url_launcher/url_launcher_macos/example/macos/RunnerTests/RunnerTests.swift/0
{ "file_path": "plugins/packages/url_launcher/url_launcher_macos/example/macos/RunnerTests/RunnerTests.swift", "repo_id": "plugins", "token_count": 1580 }
1,127
## NEXT * Updates minimum Flutter version to 3.0. ## 6.0.1 * Fixes comment describing file URI construction. ## 6.0.0 * **BREAKING CHANGE**: Removes `MethodChannelVideoPlayer`. The default implementation is now only a placeholder with no functionality; implementations of `video_player` must include their own `VideoPlayerPlatform` Dart implementation. * Updates minimum Flutter version to 2.10. * Fixes violations of new analysis option use_named_constants. ## 5.1.4 * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316). ## 5.1.3 * Updates references to the obsolete master branch. * Removes unnecessary imports. ## 5.1.2 * Adopts `Object.hash`. * Removes obsolete dependency on `pedantic`. ## 5.1.1 * Adds `rotationCorrection` (for Android playing videos recorded in landscapeRight [#60327](https://github.com/flutter/flutter/issues/60327)). ## 5.1.0 * Adds `allowBackgroundPlayback` to `VideoPlayerOptions`. ## 5.0.2 * Adds the Pigeon definitions used to create the method channel implementation. * Internal code cleanup for stricter analysis options. ## 5.0.1 * Update to use the `verify` method introduced in platform_plugin_interface 2.1.0. ## 5.0.0 * **BREAKING CHANGES**: * Updates to extending `PlatformInterface`. Removes `isMock`, in favor of the now-standard `MockPlatformInterfaceMixin`. * Removes test.dart from the public interface. Tests in other packages should mock `VideoPlatformInterface` rather than the method channel. ## 4.2.0 * Add `contentUri` to `DataSourceType`. ## 4.1.0 * Add `httpHeaders` to `DataSource` ## 4.0.0 * **Breaking Changes**: * Migrate to null-safety * Update to latest Pigeon. This includes a breaking change to how the test logic is exposed. * Add note about the `mixWithOthers` option being ignored on the web. * Make DataSource's `uri` parameter nullable. * `messages.dart` sets Dart `2.12`. ## 3.0.0 * Version 3 only was published as nullsafety "previews". ## 2.2.1 * Update Flutter SDK constraint. ## 2.2.0 * Added option to set the video playback speed on the video controller. ## 2.1.1 * Fix mixWithOthers test channel. ## 2.1.0 * Add VideoPlayerOptions with audio mix mode ## 2.0.2 * Migrated tests to use pigeon correctly. ## 2.0.1 * Updated minimum Dart version. * Added class to help testing Pigeon communication. ## 2.0.0 * Migrated to [pigeon](https://pub.dev/packages/pigeon). ## 1.0.5 * Make the pedantic dev_dependency explicit. ## 1.0.4 * Remove the deprecated `author:` field from pubspec.yaml * Require Flutter SDK 1.10.0 or greater. ## 1.0.3 * Document public API. ## 1.0.2 * Fix unawaited futures in the tests. ## 1.0.1 * Return correct platform event type when buffering ## 1.0.0 * Initial release.
plugins/packages/video_player/video_player_platform_interface/CHANGELOG.md/0
{ "file_path": "plugins/packages/video_player/video_player_platform_interface/CHANGELOG.md", "repo_id": "plugins", "token_count": 921 }
1,128
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.os.Build; import android.webkit.CookieManager; import android.webkit.ValueCallback; import io.flutter.plugins.webviewflutter.utils.TestUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.MockedStatic; public class CookieManagerHostApiImplTest { private CookieManager cookieManager; private MockedStatic<CookieManager> staticMockCookieManager; @Before public void setup() { staticMockCookieManager = mockStatic(CookieManager.class); cookieManager = mock(CookieManager.class); when(CookieManager.getInstance()).thenReturn(cookieManager); when(cookieManager.hasCookies()).thenReturn(true); doAnswer( answer -> { ((ValueCallback<Boolean>) answer.getArgument(0)).onReceiveValue(true); return null; }) .when(cookieManager) .removeAllCookies(any()); } @After public void tearDown() { staticMockCookieManager.close(); } @Test public void setCookieShouldCallSetCookie() { // Setup CookieManagerHostApiImpl impl = new CookieManagerHostApiImpl(); // Run impl.setCookie("flutter.dev", "foo=bar; path=/"); // Verify verify(cookieManager).setCookie("flutter.dev", "foo=bar; path=/"); } @Test public void clearCookiesShouldCallRemoveAllCookiesOnAndroidLAbove() { // Setup TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.LOLLIPOP); GeneratedAndroidWebView.Result<Boolean> result = mock(GeneratedAndroidWebView.Result.class); CookieManagerHostApiImpl impl = new CookieManagerHostApiImpl(); // Run impl.clearCookies(result); // Verify verify(cookieManager).removeAllCookies(any()); verify(result).success(true); } @Test public void clearCookiesShouldCallRemoveAllCookieBelowAndroidL() { // Setup TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.KITKAT_WATCH); GeneratedAndroidWebView.Result<Boolean> result = mock(GeneratedAndroidWebView.Result.class); CookieManagerHostApiImpl impl = new CookieManagerHostApiImpl(); // Run impl.clearCookies(result); // Verify verify(cookieManager).removeAllCookie(); verify(result).success(true); } }
plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/CookieManagerHostApiImplTest.java/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/CookieManagerHostApiImplTest.java", "repo_id": "plugins", "token_count": 961 }
1,129
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; void main() { test('WebViewCookie should serialize correctly', () { WebViewCookie cookie; Map<String, String> serializedCookie; // Test serialization cookie = const WebViewCookie( name: 'foo', value: 'bar', domain: 'example.com', path: '/test'); serializedCookie = cookie.toJson(); expect(serializedCookie['name'], 'foo'); expect(serializedCookie['value'], 'bar'); expect(serializedCookie['domain'], 'example.com'); expect(serializedCookie['path'], '/test'); }); }
plugins/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/webview_cookie_test.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/test/legacy/types/webview_cookie_test.dart", "repo_id": "plugins", "token_count": 279 }
1,130
# webview\_flutter\_wkwebview The Apple WKWebView implementation of [`webview_flutter`][1]. ## Usage This package is [endorsed][2], which means you can simply use `webview_flutter` normally. This package will be automatically included in your app when you do. ### External Native API The plugin also provides a native API accessible by the native code of iOS applications or packages. This API follows the convention of breaking changes of the Dart API, which means that any changes to the class that are not backwards compatible will only be made with a major version change of the plugin. Native code other than this external API does not follow breaking change conventions, so app or plugin clients should not use any other native APIs. The API can be accessed by importing the native plugin `webview_flutter_wkwebview`: Objective-C: ```objectivec @import webview_flutter_wkwebview; ``` Then you will have access to the native class `FWFWebViewFlutterWKWebViewExternalAPI`. ## Contributing This package uses [pigeon][3] to generate the communication layer between Flutter and the host platform (iOS). The communication interface is defined in the `pigeons/web_kit.dart` file. After editing the communication interface regenerate the communication layer by running `flutter pub run pigeon --input pigeons/web_kit.dart`. Besides [pigeon][3] this package also uses [mockito][4] to generate mock objects for testing purposes. To generate the mock objects run the following command: ```bash flutter pub run build_runner build --delete-conflicting-outputs ``` If you would like to contribute to the plugin, check out our [contribution guide][5]. [1]: https://pub.dev/packages/webview_flutter [2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin [3]: https://pub.dev/packages/pigeon [4]: https://pub.dev/packages/mockito [5]: https://github.com/flutter/plugins/blob/main/CONTRIBUTING.md
plugins/packages/webview_flutter/webview_flutter_wkwebview/README.md/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/README.md", "repo_id": "plugins", "token_count": 538 }
1,131
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @import Flutter; @import XCTest; @import webview_flutter_wkwebview; #import <OCMock/OCMock.h> @interface FWFNavigationDelegateHostApiTests : XCTestCase @end @implementation FWFNavigationDelegateHostApiTests /** * Creates a partially mocked FWFNavigationDelegate and adds it to instanceManager. * * @param instanceManager Instance manager to add the delegate to. * @param identifier Identifier for the delegate added to the instanceManager. * * @return A mock FWFNavigationDelegate. */ - (id)mockNavigationDelegateWithManager:(FWFInstanceManager *)instanceManager identifier:(long)identifier { FWFNavigationDelegate *navigationDelegate = [[FWFNavigationDelegate alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; [instanceManager addDartCreatedInstance:navigationDelegate withIdentifier:0]; return OCMPartialMock(navigationDelegate); } /** * Creates a mock FWFNavigationDelegateFlutterApiImpl with instanceManager. * * @param instanceManager Instance manager passed to the Flutter API. * * @return A mock FWFNavigationDelegateFlutterApiImpl. */ - (id)mockFlutterApiWithManager:(FWFInstanceManager *)instanceManager { FWFNavigationDelegateFlutterApiImpl *flutterAPI = [[FWFNavigationDelegateFlutterApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; return OCMPartialMock(flutterAPI); } - (void)testCreateWithIdentifier { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFNavigationDelegateHostApiImpl *hostAPI = [[FWFNavigationDelegateHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; [hostAPI createWithIdentifier:@0 error:&error]; FWFNavigationDelegate *navigationDelegate = (FWFNavigationDelegate *)[instanceManager instanceForIdentifier:0]; XCTAssertTrue([navigationDelegate conformsToProtocol:@protocol(WKNavigationDelegate)]); XCTAssertNil(error); } - (void)testDidFinishNavigation { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFNavigationDelegate *mockDelegate = [self mockNavigationDelegateWithManager:instanceManager identifier:0]; FWFNavigationDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate navigationDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); OCMStub([mockWebView URL]).andReturn([NSURL URLWithString:@"https://flutter.dev/"]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; [mockDelegate webView:mockWebView didFinishNavigation:OCMClassMock([WKNavigation class])]; OCMVerify([mockFlutterAPI didFinishNavigationForDelegateWithIdentifier:@0 webViewIdentifier:@1 URL:@"https://flutter.dev/" completion:OCMOCK_ANY]); } - (void)testDidStartProvisionalNavigation { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFNavigationDelegate *mockDelegate = [self mockNavigationDelegateWithManager:instanceManager identifier:0]; FWFNavigationDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate navigationDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); OCMStub([mockWebView URL]).andReturn([NSURL URLWithString:@"https://flutter.dev/"]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; [mockDelegate webView:mockWebView didStartProvisionalNavigation:OCMClassMock([WKNavigation class])]; OCMVerify([mockFlutterAPI didStartProvisionalNavigationForDelegateWithIdentifier:@0 webViewIdentifier:@1 URL:@"https://flutter.dev/" completion:OCMOCK_ANY]); } - (void)testDecidePolicyForNavigationAction { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFNavigationDelegate *mockDelegate = [self mockNavigationDelegateWithManager:instanceManager identifier:0]; FWFNavigationDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate navigationDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; WKNavigationAction *mockNavigationAction = OCMClassMock([WKNavigationAction class]); OCMStub([mockNavigationAction request]) .andReturn([NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.flutter.dev"]]); WKFrameInfo *mockFrameInfo = OCMClassMock([WKFrameInfo class]); OCMStub([mockFrameInfo isMainFrame]).andReturn(YES); OCMStub([mockNavigationAction targetFrame]).andReturn(mockFrameInfo); OCMStub([mockFlutterAPI decidePolicyForNavigationActionForDelegateWithIdentifier:@0 webViewIdentifier:@1 navigationAction: [OCMArg isKindOfClass:[FWFWKNavigationActionData class]] completion: ([OCMArg invokeBlockWithArgs: [FWFWKNavigationActionPolicyEnumData makeWithValue: FWFWKNavigationActionPolicyEnumCancel], [NSNull null], nil])]); WKNavigationActionPolicy __block callbackPolicy = -1; [mockDelegate webView:mockWebView decidePolicyForNavigationAction:mockNavigationAction decisionHandler:^(WKNavigationActionPolicy policy) { callbackPolicy = policy; }]; XCTAssertEqual(callbackPolicy, WKNavigationActionPolicyCancel); } - (void)testDidFailNavigation { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFNavigationDelegate *mockDelegate = [self mockNavigationDelegateWithManager:instanceManager identifier:0]; FWFNavigationDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate navigationDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; [mockDelegate webView:mockWebView didFailNavigation:OCMClassMock([WKNavigation class]) withError:[NSError errorWithDomain:@"domain" code:0 userInfo:nil]]; OCMVerify([mockFlutterAPI didFailNavigationForDelegateWithIdentifier:@0 webViewIdentifier:@1 error:[OCMArg isKindOfClass:[FWFNSErrorData class]] completion:OCMOCK_ANY]); } - (void)testDidFailProvisionalNavigation { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFNavigationDelegate *mockDelegate = [self mockNavigationDelegateWithManager:instanceManager identifier:0]; FWFNavigationDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate navigationDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; [mockDelegate webView:mockWebView didFailProvisionalNavigation:OCMClassMock([WKNavigation class]) withError:[NSError errorWithDomain:@"domain" code:0 userInfo:nil]]; OCMVerify([mockFlutterAPI didFailProvisionalNavigationForDelegateWithIdentifier:@0 webViewIdentifier:@1 error:[OCMArg isKindOfClass:[FWFNSErrorData class]] completion:OCMOCK_ANY]); } - (void)testWebViewWebContentProcessDidTerminate { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFNavigationDelegate *mockDelegate = [self mockNavigationDelegateWithManager:instanceManager identifier:0]; FWFNavigationDelegateFlutterApiImpl *mockFlutterAPI = [self mockFlutterApiWithManager:instanceManager]; OCMStub([mockDelegate navigationDelegateAPI]).andReturn(mockFlutterAPI); WKWebView *mockWebView = OCMClassMock([WKWebView class]); [instanceManager addDartCreatedInstance:mockWebView withIdentifier:1]; [mockDelegate webViewWebContentProcessDidTerminate:mockWebView]; OCMVerify([mockFlutterAPI webViewWebContentProcessDidTerminateForDelegateWithIdentifier:@0 webViewIdentifier:@1 completion:OCMOCK_ANY]); } @end
plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFNavigationDelegateHostApiTests.m/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFNavigationDelegateHostApiTests.m", "repo_id": "plugins", "token_count": 4691 }
1,132
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFUserContentControllerHostApi.h" #import "FWFDataConverters.h" #import "FWFWebViewConfigurationHostApi.h" @interface FWFUserContentControllerHostApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFUserContentControllerHostApiImpl - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _instanceManager = instanceManager; } return self; } - (WKUserContentController *)userContentControllerForIdentifier:(NSNumber *)identifier { return (WKUserContentController *)[self.instanceManager instanceForIdentifier:identifier.longValue]; } - (void)createFromWebViewConfigurationWithIdentifier:(nonnull NSNumber *)identifier configurationIdentifier:(nonnull NSNumber *)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error { WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager instanceForIdentifier:configurationIdentifier.longValue]; [self.instanceManager addDartCreatedInstance:configuration.userContentController withIdentifier:identifier.longValue]; } - (void)addScriptMessageHandlerForControllerWithIdentifier:(nonnull NSNumber *)identifier handlerIdentifier:(nonnull NSNumber *)handler ofName:(nonnull NSString *)name error: (FlutterError *_Nullable *_Nonnull)error { [[self userContentControllerForIdentifier:identifier] addScriptMessageHandler:(id<WKScriptMessageHandler>)[self.instanceManager instanceForIdentifier:handler.longValue] name:name]; } - (void)removeScriptMessageHandlerForControllerWithIdentifier:(nonnull NSNumber *)identifier name:(nonnull NSString *)name error:(FlutterError *_Nullable *_Nonnull) error { [[self userContentControllerForIdentifier:identifier] removeScriptMessageHandlerForName:name]; } - (void)removeAllScriptMessageHandlersForControllerWithIdentifier:(nonnull NSNumber *)identifier error: (FlutterError *_Nullable *_Nonnull) error { if (@available(iOS 14.0, *)) { [[self userContentControllerForIdentifier:identifier] removeAllScriptMessageHandlers]; } else { *error = [FlutterError errorWithCode:@"FWFUnsupportedVersionError" message:@"removeAllScriptMessageHandlers is only supported on versions 14+." details:nil]; } } - (void)addUserScriptForControllerWithIdentifier:(nonnull NSNumber *)identifier userScript:(nonnull FWFWKUserScriptData *)userScript error:(FlutterError *_Nullable *_Nonnull)error { [[self userContentControllerForIdentifier:identifier] addUserScript:FWFWKUserScriptFromScriptData(userScript)]; } - (void)removeAllUserScriptsForControllerWithIdentifier:(nonnull NSNumber *)identifier error:(FlutterError *_Nullable *_Nonnull)error { [[self userContentControllerForIdentifier:identifier] removeAllUserScripts]; } @end
plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUserContentControllerHostApi.m/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUserContentControllerHostApi.m", "repo_id": "plugins", "token_count": 1775 }
1,133
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../common/instance_manager.dart'; import '../common/web_kit.g.dart'; import 'foundation.dart'; Iterable<NSKeyValueObservingOptionsEnumData> _toNSKeyValueObservingOptionsEnumData( Iterable<NSKeyValueObservingOptions> options, ) { return options.map<NSKeyValueObservingOptionsEnumData>(( NSKeyValueObservingOptions option, ) { late final NSKeyValueObservingOptionsEnum? value; switch (option) { case NSKeyValueObservingOptions.newValue: value = NSKeyValueObservingOptionsEnum.newValue; break; case NSKeyValueObservingOptions.oldValue: value = NSKeyValueObservingOptionsEnum.oldValue; break; case NSKeyValueObservingOptions.initialValue: value = NSKeyValueObservingOptionsEnum.initialValue; break; case NSKeyValueObservingOptions.priorNotification: value = NSKeyValueObservingOptionsEnum.priorNotification; break; } return NSKeyValueObservingOptionsEnumData(value: value); }); } extension _NSKeyValueChangeKeyEnumDataConverter on NSKeyValueChangeKeyEnumData { NSKeyValueChangeKey toNSKeyValueChangeKey() { return NSKeyValueChangeKey.values.firstWhere( (NSKeyValueChangeKey element) => element.name == value.name, ); } } /// Handles initialization of Flutter APIs for the Foundation library. class FoundationFlutterApis { /// Constructs a [FoundationFlutterApis]. @visibleForTesting FoundationFlutterApis({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _binaryMessenger = binaryMessenger, object = NSObjectFlutterApiImpl( instanceManager: instanceManager, ); static FoundationFlutterApis _instance = FoundationFlutterApis(); /// Sets the global instance containing the Flutter Apis for the Foundation library. @visibleForTesting static set instance(FoundationFlutterApis instance) { _instance = instance; } /// Global instance containing the Flutter Apis for the Foundation library. static FoundationFlutterApis get instance { return _instance; } final BinaryMessenger? _binaryMessenger; bool _hasBeenSetUp = false; /// Flutter Api for [NSObject]. @visibleForTesting final NSObjectFlutterApiImpl object; /// Ensures all the Flutter APIs have been set up to receive calls from native code. void ensureSetUp() { if (!_hasBeenSetUp) { NSObjectFlutterApi.setup( object, binaryMessenger: _binaryMessenger, ); _hasBeenSetUp = true; } } } /// Host api implementation for [NSObject]. class NSObjectHostApiImpl extends NSObjectHostApi { /// Constructs an [NSObjectHostApiImpl]. NSObjectHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [addObserver] with the ids of the provided object instances. Future<void> addObserverForInstances( NSObject instance, NSObject observer, String keyPath, Set<NSKeyValueObservingOptions> options, ) { return addObserver( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(observer)!, keyPath, _toNSKeyValueObservingOptionsEnumData(options).toList(), ); } /// Calls [removeObserver] with the ids of the provided object instances. Future<void> removeObserverForInstances( NSObject instance, NSObject observer, String keyPath, ) { return removeObserver( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(observer)!, keyPath, ); } } /// Flutter api implementation for [NSObject]. class NSObjectFlutterApiImpl extends NSObjectFlutterApi { /// Constructs a [NSObjectFlutterApiImpl]. NSObjectFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; NSObject _getObject(int identifier) { return instanceManager.getInstanceWithWeakReference(identifier)!; } @override void observeValue( int identifier, String keyPath, int objectIdentifier, List<NSKeyValueChangeKeyEnumData?> changeKeys, List<Object?> changeValues, ) { final void Function(String, NSObject, Map<NSKeyValueChangeKey, Object?>)? function = _getObject(identifier).observeValue; function?.call( keyPath, instanceManager.getInstanceWithWeakReference(objectIdentifier)! as NSObject, Map<NSKeyValueChangeKey, Object?>.fromIterables( changeKeys.map<NSKeyValueChangeKey>( (NSKeyValueChangeKeyEnumData? data) { return data!.toNSKeyValueChangeKey(); }, ), changeValues), ); } @override void dispose(int identifier) { instanceManager.remove(identifier); } }
plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/foundation/foundation_api_impls.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/foundation/foundation_api_impls.dart", "repo_id": "plugins", "token_count": 1849 }
1,134
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart'; import 'package:webview_flutter_wkwebview/src/legacy/wkwebview_cookie_manager.dart'; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart'; import 'web_kit_cookie_manager_test.mocks.dart'; @GenerateMocks(<Type>[ WKHttpCookieStore, WKWebsiteDataStore, ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('WebKitWebViewWidget', () { late MockWKWebsiteDataStore mockWebsiteDataStore; late MockWKHttpCookieStore mockWKHttpCookieStore; late WKWebViewCookieManager cookieManager; setUp(() { mockWebsiteDataStore = MockWKWebsiteDataStore(); mockWKHttpCookieStore = MockWKHttpCookieStore(); when(mockWebsiteDataStore.httpCookieStore) .thenReturn(mockWKHttpCookieStore); cookieManager = WKWebViewCookieManager(websiteDataStore: mockWebsiteDataStore); }); test('clearCookies', () async { when(mockWebsiteDataStore.removeDataOfTypes( <WKWebsiteDataType>{WKWebsiteDataType.cookies}, any)) .thenAnswer((_) => Future<bool>.value(true)); expect(cookieManager.clearCookies(), completion(true)); when(mockWebsiteDataStore.removeDataOfTypes( <WKWebsiteDataType>{WKWebsiteDataType.cookies}, any)) .thenAnswer((_) => Future<bool>.value(false)); expect(cookieManager.clearCookies(), completion(false)); }); test('setCookie', () async { await cookieManager.setCookie( const WebViewCookie(name: 'a', value: 'b', domain: 'c', path: 'd'), ); final NSHttpCookie cookie = verify(mockWKHttpCookieStore.setCookie(captureAny)).captured.single as NSHttpCookie; expect( cookie.properties, <NSHttpCookiePropertyKey, Object>{ NSHttpCookiePropertyKey.name: 'a', NSHttpCookiePropertyKey.value: 'b', NSHttpCookiePropertyKey.domain: 'c', NSHttpCookiePropertyKey.path: 'd', }, ); }); test('setCookie throws argument error with invalid path', () async { expect( () => cookieManager.setCookie( WebViewCookie( name: 'a', value: 'b', domain: 'c', path: String.fromCharCode(0x1F), ), ), throwsArgumentError, ); }); }); }
plugins/packages/webview_flutter/webview_flutter_wkwebview/test/legacy/web_kit_cookie_manager_test.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/legacy/web_kit_cookie_manager_test.dart", "repo_id": "plugins", "token_count": 1156 }
1,135
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart'; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart'; import 'package:webview_flutter_wkwebview/src/webkit_proxy.dart'; import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; import 'webkit_webview_cookie_manager_test.mocks.dart'; @GenerateMocks(<Type>[WKWebsiteDataStore, WKHttpCookieStore]) void main() { WidgetsFlutterBinding.ensureInitialized(); group('WebKitWebViewCookieManager', () { test('clearCookies', () { final MockWKWebsiteDataStore mockWKWebsiteDataStore = MockWKWebsiteDataStore(); final WebKitWebViewCookieManager manager = WebKitWebViewCookieManager( WebKitWebViewCookieManagerCreationParams( webKitProxy: WebKitProxy( defaultWebsiteDataStore: () => mockWKWebsiteDataStore, ), ), ); when( mockWKWebsiteDataStore.removeDataOfTypes( <WKWebsiteDataType>{WKWebsiteDataType.cookies}, any, ), ).thenAnswer((_) => Future<bool>.value(true)); expect(manager.clearCookies(), completion(true)); when( mockWKWebsiteDataStore.removeDataOfTypes( <WKWebsiteDataType>{WKWebsiteDataType.cookies}, any, ), ).thenAnswer((_) => Future<bool>.value(false)); expect(manager.clearCookies(), completion(false)); }); test('setCookie', () async { final MockWKWebsiteDataStore mockWKWebsiteDataStore = MockWKWebsiteDataStore(); final MockWKHttpCookieStore mockCookieStore = MockWKHttpCookieStore(); when(mockWKWebsiteDataStore.httpCookieStore).thenReturn(mockCookieStore); final WebKitWebViewCookieManager manager = WebKitWebViewCookieManager( WebKitWebViewCookieManagerCreationParams( webKitProxy: WebKitProxy( defaultWebsiteDataStore: () => mockWKWebsiteDataStore, ), ), ); await manager.setCookie( const WebViewCookie(name: 'a', value: 'b', domain: 'c', path: 'd'), ); final NSHttpCookie cookie = verify(mockCookieStore.setCookie(captureAny)) .captured .single as NSHttpCookie; expect( cookie.properties, <NSHttpCookiePropertyKey, Object>{ NSHttpCookiePropertyKey.name: 'a', NSHttpCookiePropertyKey.value: 'b', NSHttpCookiePropertyKey.domain: 'c', NSHttpCookiePropertyKey.path: 'd', }, ); }); test('setCookie throws argument error with invalid path', () async { final MockWKWebsiteDataStore mockWKWebsiteDataStore = MockWKWebsiteDataStore(); final MockWKHttpCookieStore mockCookieStore = MockWKHttpCookieStore(); when(mockWKWebsiteDataStore.httpCookieStore).thenReturn(mockCookieStore); final WebKitWebViewCookieManager manager = WebKitWebViewCookieManager( WebKitWebViewCookieManagerCreationParams( webKitProxy: WebKitProxy( defaultWebsiteDataStore: () => mockWKWebsiteDataStore, ), ), ); expect( () => manager.setCookie( WebViewCookie( name: 'a', value: 'b', domain: 'c', path: String.fromCharCode(0x1F), ), ), throwsArgumentError, ); }); }); }
plugins/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_cookie_manager_test.dart/0
{ "file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_cookie_manager_test.dart", "repo_id": "plugins", "token_count": 1595 }
1,136
## 0.13.4+1 * Makes `--packages-for-branch` detect any commit on `main` as being `main`, so that it works with pinned checkouts (e.g., on LUCI). ## 0.13.4 * Adds the ability to validate minimum supported Dart/Flutter versions in `pubspec-check`. ## 0.13.3 * Renames `podspecs` to `podspec-check`. The old name will continue to work. * Adds validation of the Swift-in-Obj-C-projects workaround in the podspecs of iOS plugin implementations that use Swift. ## 0.13.2+1 * Replaces deprecated `flutter format` with `dart format` in `format` implementation. ## 0.13.2 * Falls back to other executables in PATH when `clang-format` does not run. ## 0.13.1 * Updates `version-check` to recognize Pigeon's platform test structure. * Pins `package:git` dependency to `2.0.x` until `dart >=2.18.0` becomes our oldest legacy. * Updates test mocks. ## 0.13.0 * Renames `all-plugins-app` to `create-all-packages-app` to clarify what it actually does. Also renames the project directory it creates from `all_plugins` to `all_packages`. ## 0.12.1 * Modifies `publish_check_command.dart` to do a `dart pub get` in all examples of the package being checked. Workaround for [dart-lang/pub#3618](https://github.com/dart-lang/pub/issues/3618). ## 0.12.0 * Changes the behavior of `--packages-for-branch` on main/master to run for packages changed in the last commit, rather than running for all packages. This allows CI to test the same filtered set of packages in post-submit as are tested in presubmit. * Adds a `fix` command to run `dart fix --apply` in target packages. ## 0.11.0 * Renames `publish-plugin` to `publish`. * Renames arguments to `list`: * `--package` now lists top-level packages (previously `--plugin`). * `--package-or-subpackage` now lists top-level packages (previously `--package`). ## 0.10.0+1 * Recognizes `run_test.sh` as a developer-only file in `version-check`. * Adds `readme-check` validation that the example/README.md for a federated plugin's implementation packages has a warning about the intended use of the example instead of the template boilerplate. ## 0.10.0 * Improves the logic in `version-check` to determine what changes don't require version changes, as well as making any dev-only changes also not require changelog changes since in practice we almost always override the check in that case. * Removes special-case handling of Dependabot PRs, and the (fragile) `--change-description-file` flag was only still used for that case, as the improved diff analysis now handles that case more robustly. ## 0.9.3 * Raises minimum `compileSdkVersion` to 32 for the `all-plugins-app` command. ## 0.9.2 * Adds checking of `code-excerpt` configuration to `readme-check`, to validate that if the excerpting tags are added to a README they are actually being used. ## 0.9.1 * Adds a `--downgrade` flag to `analyze` for analyzing with the oldest possible versions of packages. ## 0.9.0 * Replaces PR-description-based version/changelog/breaking change check overrides in `version-check` with label-based overrides using a new `pr-labels` flag, since we don't actually have reliable access to the PR description in checks. ## 0.8.10 - Adds a new `remove-dev-dependencies` command to remove `dev_dependencies` entries to make legacy version analysis possible in more cases. - Adds a `--lib-only` option to `analyze` to allow only analyzing the client parts of a library for legacy verison compatibility. ## 0.8.9 - Includes `dev_dependencies` when overridding dependencies using `make-deps-path-based`. - Bypasses version and CHANGELOG checks for Dependabot PRs for packages that are known not to be client-affecting. ## 0.8.8 - Allows pre-release versions in `version-check`. ## 0.8.7 - Supports empty custom analysis allow list files. - `drive-examples` now validates files to ensure that they don't accidentally use `test(...)`. - Adds a new `dependabot-check` command to ensure complete Dependabot coverage. - Adds `skip-if-not-supporting-dart-version` to allow for the same use cases as `skip-if-not-supporting-flutter-version` but for packages without Flutter constraints. ## 0.8.6 - Adds `update-release-info` to apply changelog and optional version changes across multiple packages. - Fixes changelog validation when reverting to a `NEXT` state. - Fixes multiplication of `--force` flag when publishing multiple packages. - Adds minimum deployment target flags to `xcode-analyze` to allow enforcing deprecation warning handling in advance of actually dropping support for an OS version. - Checks for template boilerplate in `readme-check`. - `readme-check` now validates example READMEs when present. ## 0.8.5 - Updates `test` to inculde the Dart unit tests of examples, if any. - `drive-examples` now supports non-plugin packages. - Commands that iterate over examples now include non-Flutter example packages. ## 0.8.4 - `readme-check` now validates that there's a info tag on code blocks to identify (and for supported languages, syntax highlight) the language. - `readme-check` now has a `--require-excerpts` flag to require that any Dart code blocks be managed by `code_excerpter`. ## 0.8.3 - Adds a new `update-excerpts` command to maintain README files using the `code-excerpter` package from flutter/site-shared. - `license-check` now ignores submodules. - Allows `make-deps-path-based` to skip packages it has alredy rewritten, so that running multiple times won't fail after the first time. - Removes UWP support, since Flutter has dropped support for UWP. ## 0.8.2+1 - Adds a new `readme-check` command. - Updates `publish-plugin` command documentation. - Fixes `all-plugins-app` to preserve the original application's Dart SDK version to avoid changing language feature opt-ins that the template may rely on. - Fixes `custom-test` to run `pub get` before running Dart test scripts. ## 0.8.2 - Adds a new `custom-test` command. - Switches from deprecated `flutter packages` alias to `flutter pub`. ## 0.8.1 - Fixes an `analyze` regression in 0.8.0 with packages that have non-`example` sub-packages. ## 0.8.0 - Ensures that `firebase-test-lab` runs include an `integration_test` runner. - Adds a `make-deps-path-based` command to convert inter-repo package dependencies to path-based dependencies. - Adds a (hidden) `--run-on-dirty-packages` flag for use with `make-deps-path-based` in CI. - `--packages` now allows using a federated plugin's package as a target without fully specifying it (if it is not the same as the plugin's name). E.g., `--packages=path_provide_ios` now works. - `--run-on-changed-packages` now includes only the changed packages in a federated plugin, not all packages in that plugin. - Fixes `federation-safety-check` handling of plugin deletion, and of top-level files in unfederated plugins whose names match federated plugin heuristics (e.g., `packages/foo/foo_android.iml`). - Adds an auto-retry for failed Firebase Test Lab tests as a short-term patch for flake issues. - Adds support for `CHROME_EXECUTABLE` in `drive-examples` to match similar `flutter` behavior. - Validates `default_package` entries in plugins. - Removes `allow-warnings` from the `podspecs` command. - Adds `skip-if-not-supporting-flutter-version` to allow running tests using a version of Flutter that not all packages support. (E.g., to allow for running some tests against old versions of Flutter to help avoid accidental breakage.) ## 0.7.3 - `native-test` now builds unit tests before running them on Windows and Linux, matching the behavior of other platforms. - Adds `--log-timing` to add timing information to package headers in looping commands. - Adds a `--check-for-missing-changes` flag to `version-check` that requires version updates (except for recognized exemptions) and CHANGELOG changes when modifying packages, unless the PR description explains why it's not needed. ## 0.7.2 - Update Firebase Testlab deprecated test device. (Pixel 4 API 29 -> Pixel 5 API 30). - `native-test --android`, `--ios`, and `--macos` now fail plugins that don't have unit tests, rather than skipping them. - Added a new `federation-safety-check` command to help catch changes to federated packages that have been done in such a way that they will pass in CI, but fail once the change is landed and published. - `publish-check` now validates that there is an `AUTHORS` file. - Added flags to `version-check` to allow overriding the platform interface major version change restriction. - Improved error handling and error messages in CHANGELOG version checks. - `license-check` now validates Kotlin files. - `pubspec-check` now checks that the description is of the pub-recommended length. - Fix `license-check` when run on Windows with line ending conversion enabled. - Fixed `pubspec-check` on Windows. - Add support for `main` as a primary branch. `master` continues to work for compatibility. ## 0.7.1 - Add support for `.pluginToolsConfig.yaml` in the `build-examples` command. ## 0.7.0 - `native-test` now supports `--linux` for unit tests. - Formatting now skips Dart files that contain a line that exactly matches the string `// This file is hand-formatted.`. ## 0.6.0+1 - Fixed `build-examples` to work for non-plugin packages. ## 0.6.0 - Added Android native integration test support to `native-test`. - Added a new `android-lint` command to lint Android plugin native code. - Pubspec validation now checks for `implements` in implementation packages. - Pubspec valitation now checks the full relative path of `repository` entries. - `build-examples` now supports UWP plugins via a `--winuwp` flag. - `native-test` now supports `--windows` for unit tests. - **Breaking change**: `publish` no longer accepts `--no-tag-release` or `--no-push-flags`. Releases now always tag and push. - **Breaking change**: `publish`'s `--package` flag has been replaced with the `--packages` flag used by most other packages. - **Breaking change** Passing both `--run-on-changed-packages` and `--packages` is now an error; previously it the former would be ignored. ## 0.5.0 - `--exclude` and `--custom-analysis` now accept paths to YAML files that contain lists of packages to exclude, in addition to just package names, so that exclude lists can be maintained separately from scripts and CI configuration. - Added an `xctest` flag to select specific test targets, to allow running only unit tests or integration tests. - **Breaking change**: Split Xcode analysis out of `xctest` and into a new `xcode-analyze` command. - Fixed a bug that caused `firebase-test-lab` to hang if it tried to run more than one plugin's tests in a single run. - **Breaking change**: If `firebase-test-lab` is run on a package that supports Android, but for which no tests are run, it now fails instead of skipping. This matches `drive-examples`, as this command is what is used for driving Android Flutter integration tests on CI. - **Breaking change**: Replaced `xctest` with a new `native-test` command that will eventually be able to run native unit and integration tests for all platforms. - Adds the ability to disable test types via `--no-unit` or `--no-integration`. - **Breaking change**: Replaced `java-test` with Android unit test support for the new `native-test` command. - Commands that print a run summary at the end now track and log exclusions similarly to skips for easier auditing. - `version-check` now validates that `NEXT` is not present when changing the version. ## 0.4.1 - Improved `license-check` output. - Use `java -version` rather than `java --version`, for compatibility with more versions of Java. ## 0.4.0 - Modified the output format of many commands - **Breaking change**: `firebase-test-lab` no longer supports `*_e2e.dart` files, only `integration_test/*_test.dart`. - Add a summary to the end of successful command runs for commands using the new output format. - Fixed some cases where a failure in a command for a single package would immediately abort the test. - Deprecated `--plugins` in favor of new `--packages`. `--plugins` continues to work for now, but will be removed in the future. - Make `drive-examples` device detection robust against Flutter tool banners. - `format` is now supported on Windows. ## 0.3.0 - Add a --build-id flag to `firebase-test-lab` instead of hard-coding the use of `CIRRUS_BUILD_ID`. `CIRRUS_BUILD_ID` is the default value for that flag, for backward compatibility. - `xctest` now supports running macOS tests in addition to iOS - **Breaking change**: it now requires an `--ios` and/or `--macos` flag. - **Breaking change**: `build-examples` for iOS now uses `--ios` rather than `--ipa`. - The tooling now runs in strong null-safe mode. - `publish plugins` check against pub.dev to determine if a release should happen. - Modified the output format of many commands - Removed `podspec`'s `--skip` in favor of `--ignore` using the new structure. ## 0.2.0 - Remove `xctest`'s `--skip`, which is redundant with `--ignore`. ## 0.1.4 - Add a `pubspec-check` command ## 0.1.3 - Cosmetic fix to `publish-check` output - Add a --dart-sdk option to `analyze` - Allow reverts in `version-check` ## 0.1.2 - Add `against-pub` flag for version-check, which allows the command to check version with pub. - Add `machine` flag for publish-check, which replaces outputs to something parsable by machines. - Add `skip-conformation` flag to publish-plugin to allow auto publishing. - Change `run-on-changed-packages` to consider all packages as changed if any files have been changed that could affect the entire repository. ## 0.1.1 - Update the allowed third-party licenses for flutter/packages. ## 0.1.0+1 - Re-add the bin/ directory. ## 0.1.0 - **NOTE**: This is no longer intended as a general-purpose package, and is now supported only for flutter/plugins and flutter/tools. - Fix version checks - Remove handling of pre-release null-safe versions - Fix build all for null-safe template apps - Improve handling of web integration tests - Supports enforcing standardized copyright files - Improve handling of iOS tests ## v.0.0.45+3 - Pin `collection` to `1.14.13` to be able to target Flutter stable (v1.22.6). ## v.0.0.45+2 - Make `publish-plugin` to work on non-flutter packages. ## v.0.0.45+1 - Don't call `flutter format` if there are no Dart files to format. ## v.0.0.45 - Add exclude flag to exclude any plugin from further processing. ## v.0.0.44+7 - `all-plugins-app` doesn't override the AGP version. ## v.0.0.44+6 - Fix code formatting. ## v.0.0.44+5 - Remove `-v` flag on drive-examples. ## v.0.0.44+4 - Fix bug where directory isn't passed ## v.0.0.44+3 - More verbose logging ## v.0.0.44+2 - Remove pre-alpha Windows workaround to create examples on the fly. ## v.0.0.44+1 - Print packages that passed tests in `xctest` command. - Remove printing the whole list of simulators. ## v.0.0.44 - Add 'xctest' command to run xctests. ## v.0.0.43 - Allow minor `*-nullsafety` pre release packages. ## v.0.0.42+1 - Fix test command when `--enable-experiment` is called. ## v.0.0.42 - Allow `*-nullsafety` pre release packages. ## v.0.0.41 - Support `--enable-experiment` flag in subcommands `test`, `build-examples`, `drive-examples`, and `firebase-test-lab`. ## v.0.0.40 - Support `integration_test/` directory for `drive-examples` command ## v.0.0.39 - Support `integration_test/` directory for `package:integration_test` ## v.0.0.38 - Add C++ and ObjC++ to clang-format. ## v.0.0.37+2 - Make `http` and `http_multi_server` dependency version constraint more flexible. ## v.0.0.37+1 - All_plugin test puts the plugin dependencies into dependency_overrides. ## v.0.0.37 - Only builds mobile example apps when necessary. ## v.0.0.36+3 - Add support for Linux plugins. ## v.0.0.36+2 - Default to showing podspec lint warnings ## v.0.0.36+1 - Serialize linting podspecs. ## v.0.0.36 - Remove retry on Firebase Test Lab's call to gcloud set. - Remove quiet flag from Firebase Test Lab's gcloud set command. - Allow Firebase Test Lab command to continue past gcloud set network failures. This is a mitigation for the network service sometimes not responding, but it isn't actually necessary to have a network connection for this command. ## v.0.0.35+1 - Minor cleanup to the analyze test. ## v.0.0.35 - Firebase Test Lab command generates a configurable unique path suffix for results. ## v.0.0.34 - Firebase Test Lab command now only tries to configure the project once - Firebase Test Lab command now retries project configuration up to five times. ## v.0.0.33+1 - Fixes formatting issues that got past our CI due to https://github.com/flutter/flutter/issues/51585. - Changes the default package name for testing method `createFakePubspec` back its previous behavior. ## v.0.0.33 - Version check command now fails on breaking changes to platform interfaces. - Updated version check test to be more flexible. ## v.0.0.32+7 - Ensure that Firebase Test Lab tests have a unique storage bucket for each test run. ## v.0.0.32+6 - Ensure that Firebase Test Lab tests have a unique storage bucket for each package. ## v.0.0.32+5 - Remove --fail-fast and --silent from lint podspec command. ## v.0.0.32+4 - Update `publish-plugin` to use `flutter pub publish` instead of just `pub publish`. Enforces a `pub publish` command that matches the Dart SDK in the user's Flutter install. ## v.0.0.32+3 - Update Firebase Testlab deprecated test device. (Pixel 3 API 28 -> Pixel 4 API 29). ## v.0.0.32+2 - Runs pub get before building macos to avoid failures. ## v.0.0.32+1 - Default macOS example builds to false. Previously they were running whenever CI was itself running on macOS. ## v.0.0.32 - `analyze` now asserts that the global `analysis_options.yaml` is the only one by default. Individual directories can be excluded from this check with the new `--custom-analysis` flag. ## v.0.0.31+1 - Add --skip and --no-analyze flags to podspec command. ## v.0.0.31 - Add support for macos on `DriveExamplesCommand` and `BuildExamplesCommand`. ## v.0.0.30 - Adopt pedantic analysis options, fix firebase_test_lab_test. ## v.0.0.29 - Add a command to run pod lib lint on podspec files. ## v.0.0.28 - Increase Firebase test lab timeouts to 5 minutes. ## v.0.0.27 - Run tests with `--platform=chrome` for web plugins. ## v.0.0.26 - Add a command for publishing plugins to pub. ## v.0.0.25 - Update `DriveExamplesCommand` to use `ProcessRunner`. - Make `DriveExamplesCommand` rely on `ProcessRunner` to determine if the test fails or not. - Add simple tests for `DriveExamplesCommand`. ## v.0.0.24 - Gracefully handle pubspec.yaml files for new plugins. - Additional unit testing. ## v.0.0.23 - Add a test case for transitive dependency solving in the `create_all_plugins_app` command. ## v.0.0.22 - Updated firebase-test-lab command with updated conventions for test locations. - Updated firebase-test-lab to add an optional "device" argument. - Updated version-check command to always compare refs instead of using the working copy. - Added unit tests for the firebase-test-lab and version-check commands. - Add ProcessRunner to mock running processes for testing. ## v.0.0.21 - Support the `--plugins` argument for federated plugins. ## v.0.0.20 - Support for finding federated plugins, where one directory contains multiple packages for different platform implementations. ## v.0.0.19+3 - Use `package:file` for file I/O. ## v.0.0.19+2 - Use java as language when calling `flutter create`. ## v.0.0.19+1 - Rename command for `CreateAllPluginsAppCommand`. ## v.0.0.19 - Use flutter create to build app testing plugin compilation. ## v.0.0.18+2 - Fix `.travis.yml` file name in `README.md`. ## v0.0.18+1 - Skip version check if it contains `publish_to: none`. ## v0.0.18 - Add option to exclude packages from generated pubspec command. ## v0.0.17+4 - Avoid trying to version-check pubspecs that are missing a version. ## v0.0.17+3 - version-check accounts for [pre-1.0 patch versions](https://github.com/flutter/flutter/issues/35412). ## v0.0.17+2 - Fix exception handling for version checker ## v0.0.17+1 - Fix bug where we used a flag instead of an option ## v0.0.17 - Add a command for checking the version number ## v0.0.16 - Add a command for generating `pubspec.yaml` for All Plugins app. ## v0.0.15 - Add a command for running driver tests of plugin examples. ## v0.0.14 - Check for dependencies->flutter instead of top level flutter node. ## v0.0.13 - Differentiate between Flutter and non-Flutter (but potentially Flutter consumed) Dart packages.
plugins/script/tool/CHANGELOG.md/0
{ "file_path": "plugins/script/tool/CHANGELOG.md", "repo_id": "plugins", "token_count": 6392 }
1,137
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package dev.flutter.example.androidView import android.app.Activity import android.content.Intent import androidx.activity.ComponentActivity import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import io.flutter.embedding.android.ExclusiveAppComponent import io.flutter.embedding.android.FlutterView import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.platform.PlatformPlugin /** * This is an application-specific wrapper class that exists to expose the intersection of an * application's active activity and an application's visible view to a [FlutterEngine] for * rendering. * * Omitted features from the [io.flutter.embedding.android.FlutterActivity] include: * * **State restoration**. If you're integrating at the view level, you should handle activity * state restoration yourself. * * **Engine creations**. At this level of granularity, you must make an engine and attach. * and all engine features like initial route etc must be configured on the engine yourself. * * **Splash screens**. You must implement it yourself. Read from * `addOnFirstFrameRenderedListener` as needed. * * **Transparency, surface/texture**. These are just [FlutterView] level APIs. Set them on the * [FlutterView] directly. * * **Intents**. This doesn't do any translation of intents into actions in the [FlutterEngine]. * you must do them yourself. * * **Back buttons**. You must decide whether to send it to Flutter via * [FlutterEngine.getNavigationChannel.popRoute()], or consume it natively. Though that * decision may be difficult due to https://github.com/flutter/flutter/issues/67011. * * **Low memory signals**. You're strongly encouraged to pass the low memory signals (such * as from the host `Activity`'s `onTrimMemory` callbacks) to the [FlutterEngine] to let * Flutter and the Dart VM cull its own memory usage. * * Your own [FlutterView] integrating application may need a similar wrapper but you must decide on * what the appropriate intersection between the [FlutterView], the [FlutterEngine] and your * `Activity` should be for your own application. */ class FlutterViewEngine(val engine: FlutterEngine) : LifecycleObserver, ExclusiveAppComponent<Activity>{ private var flutterView: FlutterView? = null private var activity: ComponentActivity? = null private var platformPlugin: PlatformPlugin? = null /** * This is the intersection of an available activity and of a visible [FlutterView]. This is * where Flutter would start rendering. */ private fun hookActivityAndView() { // Assert state. activity!!.let { activity -> flutterView!!.let { flutterView -> platformPlugin = PlatformPlugin(activity, engine.platformChannel) engine.activityControlSurface.attachToActivity(this, activity.lifecycle) flutterView.attachToFlutterEngine(engine) activity.lifecycle.addObserver(this) } } } /** * Lost the intersection of either an available activity or a visible * [FlutterView]. */ private fun unhookActivityAndView() { // Stop reacting to activity events. activity!!.lifecycle.removeObserver(this) // Plugins are no longer attached to an activity. engine.activityControlSurface.detachFromActivity() // Release Flutter's control of UI such as system chrome. platformPlugin!!.destroy() platformPlugin = null // Set Flutter's application state to detached. engine.lifecycleChannel.appIsDetached(); // Detach rendering pipeline. flutterView!!.detachFromFlutterEngine() } /** * Signal that a host `Activity` is now ready. If there is no [FlutterView] instance currently * attached to the view hierarchy and visible, Flutter is not yet rendering. * * You can also choose at this point whether to notify the plugins that an `Activity` is * attached or not. You can also choose at this point whether to connect a Flutter * [PlatformPlugin] at this point which allows your Dart program to trigger things like * haptic feedback and read the clipboard. This sample arbitrarily chooses no for both. */ fun attachToActivity(activity: ComponentActivity) { this.activity = activity if (flutterView != null) { hookActivityAndView() } } /** * Signal that a host `Activity` now no longer connected. If there were a [FlutterView] in * the view hierarchy and visible at this moment, that [FlutterView] will stop rendering. * * You can also choose at this point whether to notify the plugins that an `Activity` is * no longer attached or not. You can also choose at this point whether to disconnect Flutter's * [PlatformPlugin] at this point which stops your Dart program being able to trigger things * like haptic feedback and read the clipboard. This sample arbitrarily chooses yes for both. */ fun detachActivity() { if (flutterView != null) { unhookActivityAndView() } activity = null } /** * Signal that a [FlutterView] instance is created and attached to a visible Android view * hierarchy. * * If an `Activity` was also previously provided, this puts Flutter into the rendering state * for this [FlutterView]. This also connects this wrapper class to listen to the `Activity`'s * lifecycle to pause rendering when the activity is put into the background while the * view is still attached to the view hierarchy. */ fun attachFlutterView(flutterView: FlutterView) { this.flutterView = flutterView if (activity != null) { hookActivityAndView() } } /** * Signal that the attached [FlutterView] instance destroyed or no longer attached to a visible * Android view hierarchy. * * If an `Activity` was attached, this stops Flutter from rendering. It also makes this wrapper * class stop listening to the `Activity`'s lifecycle since it's no longer rendering. */ fun detachFlutterView() { unhookActivityAndView() flutterView = null } /** * Callback to let Flutter respond to the `Activity`'s resumed lifecycle event while both an * `Activity` and a [FlutterView] are attached. */ @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) private fun resumeActivity() { if (activity != null) { engine.lifecycleChannel.appIsResumed() } platformPlugin?.updateSystemUiOverlays() } /** * Callback to let Flutter respond to the `Activity`'s paused lifecycle event while both an * `Activity` and a [FlutterView] are attached. */ @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) private fun pauseActivity() { if (activity != null) { engine.lifecycleChannel.appIsInactive() } } /** * Callback to let Flutter respond to the `Activity`'s stopped lifecycle event while both an * `Activity` and a [FlutterView] are attached. */ @OnLifecycleEvent(Lifecycle.Event.ON_STOP) private fun stopActivity() { if (activity != null) { engine.lifecycleChannel.appIsPaused() } } // These events aren't used but would be needed for Flutter plugins consuming // these events to function. /** * Pass through the `Activity`'s `onRequestPermissionsResult` signal to plugins that may be * listening to it while the `Activity` and the [FlutterView] are connected. */ fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (activity != null && flutterView != null) { engine .activityControlSurface .onRequestPermissionsResult(requestCode, permissions, grantResults); } } /** * Pass through the `Activity`'s `onActivityResult` signal to plugins that may be * listening to it while the `Activity` and the [FlutterView] are connected. */ fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (activity != null && flutterView != null) { engine.activityControlSurface.onActivityResult(requestCode, resultCode, data); } } /** * Pass through the `Activity`'s `onUserLeaveHint` signal to plugins that may be * listening to it while the `Activity` and the [FlutterView] are connected. */ fun onUserLeaveHint() { if (activity != null && flutterView != null) { engine.activityControlSurface.onUserLeaveHint(); } } /** * Called when another App Component is about to become attached to the [ ] this App Component * is currently attached to. * * * This App Component's connections to the [io.flutter.embedding.engine.FlutterEngine] * are still valid at the moment of this call. */ override fun detachFromFlutterEngine() { // Do nothing here } /** * Retrieve the App Component behind this exclusive App Component. * * @return The app component. */ override fun getAppComponent(): Activity { return activity!!; } }
samples/add_to_app/android_view/android_view/app/src/main/java/dev/flutter/example/androidView/FlutterViewEngine.kt/0
{ "file_path": "samples/add_to_app/android_view/android_view/app/src/main/java/dev/flutter/example/androidView/FlutterViewEngine.kt", "repo_id": "samples", "token_count": 3257 }
1,138
rootProject.name = "Flutter View Integration" include ':app' setBinding(new Binding([gradle: this])) evaluate(new File( settingsDir.parentFile, 'flutter_module_using_plugin/.android/include_flutter.groovy' ))
samples/add_to_app/android_view/android_view/settings.gradle/0
{ "file_path": "samples/add_to_app/android_view/android_view/settings.gradle", "repo_id": "samples", "token_count": 70 }
1,139
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="dev.flutter.example.books"> <application android:name=".BookApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".FlutterBookActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize" /> </application> <uses-permission android:name="android.permission.INTERNET" /> </manifest>
samples/add_to_app/books/android_books/app/src/main/AndroidManifest.xml/0
{ "file_path": "samples/add_to_app/books/android_books/app/src/main/AndroidManifest.xml", "repo_id": "samples", "token_count": 484 }
1,140
# Books add-to-app sample This application simulates a mock scenario in which an existing app with business logic and middleware already exists. It demonstrates how to add Flutter to an app that has established patterns for these domains. For more information on how to use it, see the [README.md](../README.md) parent directory. This application also utilizes the [Pigeon](https://pub.dev/packages/pigeon) plugin to avoid manual platform channel wiring. Pigeon autogenerates the platform channel code in Dart/Java/Objective-C to allow interop using higher order functions and data classes instead of string-encoded methods and serialized primitives. The Pigeon autogenerated code is checked-in and ready to use. If the schema in `pigeon/schema.dart` is updated, the generated classes can also be re- generated using: ```shell flutter pub run pigeon --input pigeon/schema.dart \ --dart_out lib/api.dart \ --objc_header_out ../ios_books/IosBooks/api.h \ --objc_source_out ../ios_books/IosBooks/api.m \ --objc_prefix BK \ --java_out ../android_books/app/src/main/java/dev/flutter/example/books/Api.java \ --java_package "dev.flutter.example.books" ``` ## Demonstrated concepts * An existing books catalog app is already implemented in Kotlin and Swift. * The platform-side app has existing middleware constraints that should also be the middleware foundation for the additional Flutter screen. * On Android, the Kotlin app already uses GSON and OkHttp for networking and references the Google Books API as a data source. These same libraries also underpin the data fetched and shown in the Flutter screen. * The platform application interfaces with the Flutter book details page using idiomatic platform API conventions rather than Flutter conventions. * On Android, the Flutter activity receives the book to show via activity intent and returns the edited book by setting the result intent on the activity. No Flutter concepts are leaked into the consumer activity. * The [pigeon](https://pub.dev/packages/pigeon) plugin is used to generate interop APIs and data classes. The same `Book` model class is used within the Kotlin/Swift program, the Dart program and in the interop between Kotlin/Swift and Dart. ## More info For more information about Flutter, check out [flutter.dev](https://flutter.dev). For instructions on how to integrate Flutter modules into your existing applications, see Flutter's [add-to-app documentation](https://flutter.dev/docs/development/add-to-app).
samples/add_to_app/books/flutter_module_books/README.md/0
{ "file_path": "samples/add_to_app/books/flutter_module_books/README.md", "repo_id": "samples", "token_count": 704 }
1,141
include ':app' rootProject.name='AndroidFullScreen' setBinding(new Binding([gradle: this])) evaluate(new File( settingsDir.parentFile, 'flutter_module/.android/include_flutter.groovy' ))
samples/add_to_app/fullscreen/android_fullscreen/settings.gradle/0
{ "file_path": "samples/add_to_app/fullscreen/android_fullscreen/settings.gradle", "repo_id": "samples", "token_count": 75 }
1,142
# multiple_flutters_android This is an add-to-app sample that uses the Flutter engine group API to host multiple instances of Flutter in the app. ## Getting Started ```sh cd ../multiple_flutters_module flutter pub get cd - open -a "Android Studio" multiple_flutters_android/ # macOS command # (build and run) ``` For more information see [multiple_flutters_module](../multiple_flutters_module/README.md).
samples/add_to_app/multiple_flutters/multiple_flutters_android/README.md/0
{ "file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/README.md", "repo_id": "samples", "token_count": 123 }
1,143
<?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17506" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="zV5-X7-f4o"> <device id="retina6_1" orientation="portrait" appearance="light"/> <dependencies> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17505"/> <capability name="Safe area layout guides" minToolsVersion="9.0"/> <capability name="System colors in document resources" minToolsVersion="11.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--Navigation Controller--> <scene sceneID="iJJ-8n-QPC"> <objects> <navigationController id="zV5-X7-f4o" sceneMemberID="viewController"> <navigationBar key="navigationBar" contentMode="scaleToFill" id="NiM-Jj-k9k"> <rect key="frame" x="0.0" y="44" width="414" height="44"/> <autoresizingMask key="autoresizingMask"/> </navigationBar> <connections> <segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="PBq-fn-vqE"/> </connections> </navigationController> <placeholder placeholderIdentifier="IBFirstResponder" id="22r-TG-MDZ" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="-1555" y="-191"/> </scene> <!--Host View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController storyboardIdentifier="NativeViewCount" id="BYZ-38-t0r" customClass="HostViewController" customModule="MultipleFluttersIos" customModuleProvider="target" sceneMemberID="viewController"> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="414" height="896"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Count:" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="CgZ-JE-gda"> <rect key="frame" x="20" y="437.5" width="51" height="21"/> <fontDescription key="fontDescription" type="system" pointSize="17"/> <nil key="textColor"/> <nil key="highlightedColor"/> </label> <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="1234" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="dKf-iz-CSn"> <rect key="frame" x="79" y="437.5" width="39" height="21"/> <constraints> <constraint firstAttribute="width" constant="39" id="Aw7-RN-dwx"/> </constraints> <fontDescription key="fontDescription" type="system" pointSize="17"/> <nil key="textColor"/> <nil key="highlightedColor"/> </label> <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="vVY-o2-UDW"> <rect key="frame" x="350" y="818" width="44" height="44"/> <constraints> <constraint firstAttribute="height" constant="44" id="h7j-l3-taD"/> <constraint firstAttribute="width" constant="44" id="sQd-lU-0zD"/> </constraints> <state key="normal" title="Next"/> <connections> <action selector="onNext" destination="BYZ-38-t0r" eventType="touchUpInside" id="XN9-kg-pAi"/> </connections> </button> <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Ohd-Fe-iAE"> <rect key="frame" x="350" y="772" width="44" height="44"/> <constraints> <constraint firstAttribute="height" constant="44" id="8Nc-hA-ZbV"/> <constraint firstAttribute="width" constant="44" id="P0Q-km-hJ3"/> </constraints> <state key="normal" title="Add"/> <connections> <action selector="onAddCount" destination="BYZ-38-t0r" eventType="touchUpInside" id="QYB-J4-vI2"/> </connections> </button> </subviews> <viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/> <color key="backgroundColor" systemColor="systemBackgroundColor"/> <constraints> <constraint firstItem="CgZ-JE-gda" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="1Dz-Aq-10E"/> <constraint firstItem="vVY-o2-UDW" firstAttribute="top" secondItem="Ohd-Fe-iAE" secondAttribute="bottom" constant="2" id="EqG-G1-3gr"/> <constraint firstItem="vVY-o2-UDW" firstAttribute="bottom" secondItem="6Tk-OE-BBY" secondAttribute="bottom" id="IDv-xt-QVd"/> <constraint firstItem="6Tk-OE-BBY" firstAttribute="trailing" secondItem="vVY-o2-UDW" secondAttribute="trailing" constant="20" id="IQ1-E7-q9T"/> <constraint firstItem="dKf-iz-CSn" firstAttribute="leading" secondItem="CgZ-JE-gda" secondAttribute="trailing" constant="8" symbolic="YES" id="ZKK-wt-eqr"/> <constraint firstItem="dKf-iz-CSn" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="hUq-Je-pdK"/> <constraint firstItem="6Tk-OE-BBY" firstAttribute="trailing" secondItem="Ohd-Fe-iAE" secondAttribute="trailing" constant="20" id="wT9-j5-NMO"/> <constraint firstItem="CgZ-JE-gda" firstAttribute="leading" secondItem="6Tk-OE-BBY" secondAttribute="leading" constant="20" id="ybv-NA-2by"/> </constraints> </view> <navigationItem key="navigationItem" id="NPA-Os-dNw"/> <connections> <outlet property="countView" destination="dKf-iz-CSn" id="9dM-Hg-UMg"/> </connections> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="-722" y="-192"/> </scene> <!--View Controller--> <scene sceneID="e8d-wy-DfZ"> <objects> <viewController id="EXG-G5-awH" sceneMemberID="viewController"> <view key="view" contentMode="scaleToFill" id="3av-sG-Ibb"> <rect key="frame" x="0.0" y="0.0" width="414" height="896"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <viewLayoutGuide key="safeArea" id="R4s-uY-wnW"/> <color key="backgroundColor" systemColor="systemBackgroundColor"/> </view> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="xYB-oQ-Y1A" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="4" y="-192"/> </scene> </scenes> <resources> <systemColor name="systemBackgroundColor"> <color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> </systemColor> </resources> </document>
samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/Base.lproj/Main.storyboard/0
{ "file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/Base.lproj/Main.storyboard", "repo_id": "samples", "token_count": 4680 }
1,144
include ':app' rootProject.name='AndroidUsingPrebuiltModule'
samples/add_to_app/prebuilt_module/android_using_prebuilt_module/settings.gradle/0
{ "file_path": "samples/add_to_app/prebuilt_module/android_using_prebuilt_module/settings.gradle", "repo_id": "samples", "token_count": 18 }
1,145
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:flutter/material.dart'; double generateBorderRadius() => Random().nextDouble() * 64; double generateMargin() => Random().nextDouble() * 64; Color generateColor() => Color(0xFFFFFFFF & Random().nextInt(0xFFFFFFFF)); class AnimatedContainerDemo extends StatefulWidget { const AnimatedContainerDemo({super.key}); static String routeName = 'basics/animated_container'; @override State<AnimatedContainerDemo> createState() => _AnimatedContainerDemoState(); } class _AnimatedContainerDemoState extends State<AnimatedContainerDemo> { late Color color; late double borderRadius; late double margin; @override void initState() { super.initState(); color = Colors.deepPurple; borderRadius = generateBorderRadius(); margin = generateMargin(); } void change() { setState(() { color = generateColor(); borderRadius = generateBorderRadius(); margin = generateMargin(); }); } @override Widget build(BuildContext context) { // This widget is built using an AnimatedContainer, one of the easiest to use // animated Widgets. Whenever the AnimatedContainer's properties, such as decoration, // change, it will handle animating from the previous value to the new value. You can // specify both a Duration and a Curve for the animation. // This Widget is useful for designing animated interfaces that just need to change // the properties of a container. For example, you could use this to design expanding // and shrinking cards. return Scaffold( appBar: AppBar( title: const Text('AnimatedContainer'), ), body: Center( child: Column( children: [ Padding( padding: const EdgeInsets.all(8.0), child: SizedBox( width: 128, height: 128, child: AnimatedContainer( margin: EdgeInsets.all(margin), decoration: BoxDecoration( color: color, borderRadius: BorderRadius.circular(borderRadius), ), duration: const Duration(milliseconds: 400), ), ), ), ElevatedButton( child: const Text( 'change', ), onPressed: () => change(), ), ], ), ), ); } }
samples/animations/lib/src/basics/animated_container.dart/0
{ "file_path": "samples/animations/lib/src/basics/animated_container.dart", "repo_id": "samples", "token_count": 1040 }
1,146
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; class FocusImageDemo extends StatelessWidget { const FocusImageDemo({super.key}); static String routeName = 'misc/focus_image'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Focus Image')), body: const Grid(), ); } } class Grid extends StatelessWidget { const Grid({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: GridView.builder( itemCount: 40, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4), itemBuilder: (context, index) { return (index >= 20) ? const SmallCard( imageAssetName: 'assets/eat_cape_town_sm.jpg', ) : const SmallCard( imageAssetName: 'assets/eat_new_orleans_sm.jpg', ); }, ), ); } } Route _createRoute(BuildContext parentContext, String image) { return PageRouteBuilder<void>( pageBuilder: (context, animation, secondaryAnimation) { return _SecondPage(image); }, transitionsBuilder: (context, animation, secondaryAnimation, child) { var rectAnimation = _createTween(parentContext) .chain(CurveTween(curve: Curves.ease)) .animate(animation); return Stack( children: [ PositionedTransition(rect: rectAnimation, child: child), ], ); }, ); } Tween<RelativeRect> _createTween(BuildContext context) { var windowSize = MediaQuery.of(context).size; var box = context.findRenderObject() as RenderBox; var rect = box.localToGlobal(Offset.zero) & box.size; var relativeRect = RelativeRect.fromSize(rect, windowSize); return RelativeRectTween( begin: relativeRect, end: RelativeRect.fill, ); } class SmallCard extends StatelessWidget { const SmallCard({required this.imageAssetName, super.key}); final String imageAssetName; @override Widget build(BuildContext context) { return Card( child: Material( child: InkWell( onTap: () { var nav = Navigator.of(context); nav.push<void>(_createRoute(context, imageAssetName)); }, child: Image.asset( imageAssetName, fit: BoxFit.cover, ), ), ), ); } } class _SecondPage extends StatelessWidget { final String imageAssetName; const _SecondPage(this.imageAssetName); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, body: Center( child: Material( child: InkWell( onTap: () => Navigator.of(context).pop(), child: AspectRatio( aspectRatio: 1, child: Image.asset( imageAssetName, fit: BoxFit.cover, ), ), ), ), ), ); } }
samples/animations/lib/src/misc/focus_image.dart/0
{ "file_path": "samples/animations/lib/src/misc/focus_image.dart", "repo_id": "samples", "token_count": 1349 }
1,147
// Copyright 2020 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:animations/src/misc/carousel.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; Widget createCarouselDemoScreen() => MaterialApp( home: CarouselDemo(), ); void main() { group('CarouselDemo tests', () { testWidgets('Swipe left moves carousel', (tester) async { await tester.pumpWidget(createCarouselDemoScreen()); // Get the images available on the screen during initial state. var imageList = tester.widgetList(find.byType(Image)).toList(); expect(imageList.length, 2); // Swipe the Carousel. await tester.fling(find.byType(CarouselDemo), const Offset(-400, 0), 800); await tester.pumpAndSettle(); // Get the images available on the screen after swipe. imageList = tester.widgetList(find.byType(Image)).toList(); expect(imageList.length, 3); }); }); }
samples/animations/test/misc/carousel_test.dart/0
{ "file_path": "samples/animations/test/misc/carousel_test.dart", "repo_id": "samples", "token_count": 372 }
1,148
// Copyright 2022 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'dart:io'; import 'dart:isolate'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; /////////////////////////////////////////////////////////////////////////////// // **WARNING:** This is not production code and is only intended to be used for // demonstration purposes. // // The following database works by spawning a background isolate and // communicating with it over Dart's SendPort API. It is presented below as a // demonstration of the feature "Background Isolate Channels" and shows using // plugins from a background isolate. The [SimpleDatabase] operates on the root // isolate and the [_SimpleDatabaseServer] operates on a background isolate. // // Here is an example of the protocol they use to communicate: // // _________________ ________________________ // [:SimpleDatabase] [:_SimpleDatabaseServer] // ----------------- ------------------------ // | | // |<---------------(init)------------------------| // |----------------(init)----------------------->| // |<---------------(ack)------------------------>| // | | // |----------------(add)------------------------>| // |<---------------(ack)-------------------------| // | | // |----------------(query)---------------------->| // |<---------------(result)----------------------| // |<---------------(result)----------------------| // |<---------------(done)------------------------| // /////////////////////////////////////////////////////////////////////////////// /// The size of the database entries in bytes. const int _entrySize = 256; /// All the command codes that can be sent and received between [SimpleDatabase] and /// [_SimpleDatabaseServer]. enum _Codes { init, add, query, ack, result, done, } /// A command sent between [SimpleDatabase] and [_SimpleDatabaseServer]. class _Command { const _Command(this.code, {this.arg0, this.arg1}); final _Codes code; final Object? arg0; final Object? arg1; } /// A SimpleDatabase that stores entries of strings to disk where they can be /// queried. /// /// All the disk operations and queries are executed in a background isolate /// operating. This class just sends and receives messages to the isolate. class SimpleDatabase { SimpleDatabase._(this._isolate, this._path); final Isolate _isolate; final String _path; late final SendPort _sendPort; // Completers are stored in a queue so multiple commands can be queued up and // handled serially. final Queue<Completer<void>> _completers = Queue<Completer<void>>(); // Similarly, StreamControllers are stored in a queue so they can be handled // asynchronously and serially. final Queue<StreamController<String>> _resultsStream = Queue<StreamController<String>>(); /// Open the database at [path] and launch the server on a background isolate.. static Future<SimpleDatabase> open(String path) async { final ReceivePort receivePort = ReceivePort(); final Isolate isolate = await Isolate.spawn(_SimpleDatabaseServer._run, receivePort.sendPort); final SimpleDatabase result = SimpleDatabase._(isolate, path); Completer<void> completer = Completer<void>(); result._completers.addFirst(completer); receivePort.listen((message) { result._handleCommand(message as _Command); }); await completer.future; return result; } /// Writes [value] to the database. Future<void> addEntry(String value) { // No processing happens on the calling isolate, it gets delegated to the // background isolate, see [__SimpleDatabaseServer._doAddEntry]. Completer<void> completer = Completer<void>(); _completers.addFirst(completer); _sendPort.send(_Command(_Codes.add, arg0: value)); return completer.future; } /// Returns all the strings in the database that contain [query]. Stream<String> find(String query) { // No processing happens on the calling isolate, it gets delegated to the // background isolate, see [__SimpleDatabaseServer._doFind]. StreamController<String> resultsStream = StreamController<String>(); _resultsStream.addFirst(resultsStream); _sendPort.send(_Command(_Codes.query, arg0: query)); return resultsStream.stream; } /// Handler invoked when a message is received from the port communicating /// with the database server. void _handleCommand(_Command command) { switch (command.code) { case _Codes.init: _sendPort = command.arg0 as SendPort; // ---------------------------------------------------------------------- // Before using platform channels and plugins from background isolates we // need to register it with its root isolate. This is achieved by // acquiring a [RootIsolateToken] which the background isolate uses to // invoke [BackgroundIsolateBinaryMessenger.ensureInitialized]. // ---------------------------------------------------------------------- RootIsolateToken rootIsolateToken = RootIsolateToken.instance!; _sendPort .send(_Command(_Codes.init, arg0: _path, arg1: rootIsolateToken)); case _Codes.ack: _completers.removeLast().complete(); case _Codes.result: _resultsStream.last.add(command.arg0 as String); case _Codes.done: _resultsStream.removeLast().close(); default: debugPrint('SimpleDatabase unrecognized command: ${command.code}'); } } /// Kills the background isolate and its database server. void stop() { _isolate.kill(); } } /// The portion of the [SimpleDatabase] that runs on the background isolate. /// /// This is where we use the new feature Background Isolate Channels, which /// allows us to use plugins from background isolates. class _SimpleDatabaseServer { _SimpleDatabaseServer(this._sendPort); final SendPort _sendPort; late final String _path; // ---------------------------------------------------------------------- // Here the plugin is used from the background isolate. // ---------------------------------------------------------------------- /// The main entrypoint for the background isolate sent to [Isolate.spawn]. static void _run(SendPort sendPort) { ReceivePort receivePort = ReceivePort(); sendPort.send(_Command(_Codes.init, arg0: receivePort.sendPort)); final _SimpleDatabaseServer server = _SimpleDatabaseServer(sendPort); receivePort.listen((message) async { final _Command command = message as _Command; await server._handleCommand(command); }); } /// Handle the [command] received from the [ReceivePort]. Future<void> _handleCommand(_Command command) async { switch (command.code) { case _Codes.init: _path = command.arg0 as String; // ---------------------------------------------------------------------- // The [RootIsolateToken] is required for // [BackgroundIsolateBinaryMessenger.ensureInitialized] and must be // obtained on the root isolate and passed into the background isolate via // a [SendPort]. // ---------------------------------------------------------------------- RootIsolateToken rootIsolateToken = command.arg1 as RootIsolateToken; // ---------------------------------------------------------------------- // [BackgroundIsolateBinaryMessenger.ensureInitialized] for each // background isolate that will use plugins. This sets up the // [BinaryMessenger] that the Platform Channels will communicate with on // the background isolate. // ---------------------------------------------------------------------- BackgroundIsolateBinaryMessenger.ensureInitialized(rootIsolateToken); _sendPort.send(const _Command(_Codes.ack, arg0: null)); case _Codes.add: _doAddEntry(command.arg0 as String); case _Codes.query: _doFind(command.arg0 as String); default: debugPrint( '_SimpleDatabaseServer unrecognized command ${command.code}'); } } /// Perform the add entry operation. void _doAddEntry(String value) { debugPrint('Performing add: $value'); File file = File(_path); if (!file.existsSync()) { file.createSync(); } RandomAccessFile writer = file.openSync(mode: FileMode.append); List<int> bytes = utf8.encode(value); if (bytes.length > _entrySize) { bytes = bytes.sublist(0, _entrySize); } else if (bytes.length < _entrySize) { List<int> newBytes = List.filled(_entrySize, 0); for (int i = 0; i < bytes.length; ++i) { newBytes[i] = bytes[i]; } bytes = newBytes; } writer.writeFromSync(bytes); writer.closeSync(); _sendPort.send(const _Command(_Codes.ack, arg0: null)); } /// Perform the find entry operation. void _doFind(String query) { debugPrint('Performing find: $query'); File file = File(_path); if (file.existsSync()) { RandomAccessFile reader = file.openSync(); List<int> buffer = List.filled(_entrySize, 0); while (reader.readIntoSync(buffer) == _entrySize) { List<int> foo = buffer.takeWhile((value) => value != 0).toList(); String string = utf8.decode(foo); if (string.contains(query)) { _sendPort.send(_Command(_Codes.result, arg0: string)); } } reader.closeSync(); } _sendPort.send(const _Command(_Codes.done, arg0: null)); } }
samples/background_isolate_channels/lib/simple_database.dart/0
{ "file_path": "samples/background_isolate_channels/lib/simple_database.dart", "repo_id": "samples", "token_count": 3234 }
1,149
import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import 'constants.dart'; import 'platform_selector.dart'; class GlobalSelectionPage extends StatelessWidget { GlobalSelectionPage({ super.key, required this.onChangedPlatform, }); static const String route = 'global-selection'; static const String title = 'Global Selection Example'; static const String subtitle = 'Context menus in and out of global selection'; static const String url = '$kCodeUrl/global_selection_page.dart'; final PlatformCallback onChangedPlatform; final TextEditingController _controller = TextEditingController( text: 'TextFields still show their specific context menu.', ); @override Widget build(BuildContext context) { return SelectionArea( contextMenuBuilder: (context, selectableRegionState) { return AdaptiveTextSelectionToolbar.buttonItems( anchors: selectableRegionState.contextMenuAnchors, buttonItems: <ContextMenuButtonItem>[ ...selectableRegionState.contextMenuButtonItems, ContextMenuButtonItem( onPressed: () { ContextMenuController.removeAny(); Navigator.of(context).pop(); }, label: 'Back', ), ], ); }, child: Scaffold( appBar: AppBar( title: const Text(GlobalSelectionPage.title), actions: <Widget>[ PlatformSelector( onChangedPlatform: onChangedPlatform, ), IconButton( icon: const Icon(Icons.code), onPressed: () async { if (!await launchUrl(Uri.parse(url))) { throw 'Could not launch $url'; } }, ), ], ), body: Center( child: SizedBox( width: 400.0, child: ListView( children: <Widget>[ const SizedBox(height: 20.0), const Text( 'This entire page is wrapped in a SelectionArea with a custom context menu. Clicking on any of the plain text, including the AppBar title, will show the custom menu.', ), const SizedBox(height: 40.0), TextField(controller: _controller), const SizedBox(height: 40.0), const SelectableText( 'SelectableText also shows its own separate context menu.'), ], ), ), ), ), ); } }
samples/context_menus/lib/global_selection_page.dart/0
{ "file_path": "samples/context_menus/lib/global_selection_page.dart", "repo_id": "samples", "token_count": 1182 }
1,150