text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// ignore_for_file: cascade_invocations
import 'package:flame/extensions.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_flame/pinball_flame.dart';
void main() {
final flameTester = FlameTester(
() => PinballForge2DGame(gravity: Vector2.zero()),
);
group('PinballForge2DGame', () {
test('can instantiate', () {
expect(
() => PinballForge2DGame(gravity: Vector2.zero()),
returnsNormally,
);
});
flameTester.test(
'screenToFlameWorld throws UnimplementedError',
(game) async {
expect(
() => game.screenToFlameWorld(Vector2.zero()),
throwsUnimplementedError,
);
},
);
flameTester.test(
'screenToWorld throws UnimplementedError',
(game) async {
expect(
() => game.screenToWorld(Vector2.zero()),
throwsUnimplementedError,
);
},
);
flameTester.test(
'worldToScreen throws UnimplementedError',
(game) async {
expect(
() => game.worldToScreen(Vector2.zero()),
throwsUnimplementedError,
);
},
);
group('clampDt', () {
test('returns dt', () {
const dt = 0.0001;
expect(PinballForge2DGame.clampDt(dt), equals(dt));
});
test('returns result of 1/60 as dt is to high', () {
const dt = 1.0;
expect(PinballForge2DGame.clampDt(dt), equals(1 / 60));
});
});
});
}
| pinball/packages/pinball_flame/test/src/pinball_forge2d_game_test.dart/0 | {
"file_path": "pinball/packages/pinball_flame/test/src/pinball_forge2d_game_test.dart",
"repo_id": "pinball",
"token_count": 698
} | 1,222 |
library pinball_theme;
export 'src/generated/generated.dart';
export 'src/themes/themes.dart';
| pinball/packages/pinball_theme/lib/pinball_theme.dart/0 | {
"file_path": "pinball/packages/pinball_theme/lib/pinball_theme.dart",
"repo_id": "pinball",
"token_count": 34
} | 1,223 |
include: package:very_good_analysis/analysis_options.2.4.0.yaml
analyzer:
exclude:
- lib/**/*.gen.dart
| pinball/packages/pinball_ui/analysis_options.yaml/0 | {
"file_path": "pinball/packages/pinball_ui/analysis_options.yaml",
"repo_id": "pinball",
"token_count": 44
} | 1,224 |
import 'package:flutter/material.dart';
import 'package:pinball_ui/gen/gen.dart';
/// {@template pixelated_decoration}
/// Widget with pixelated background and layout defined for dialog displays.
/// {@endtemplate}
class PixelatedDecoration extends StatelessWidget {
/// {@macro pixelated_decoration}
const PixelatedDecoration({
Key? key,
required Widget header,
required Widget body,
}) : _header = header,
_body = body,
super(key: key);
final Widget _header;
final Widget _body;
@override
Widget build(BuildContext context) {
const radius = BorderRadius.all(Radius.circular(12));
return Material(
borderRadius: radius,
child: Padding(
padding: const EdgeInsets.all(5),
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: radius,
image: DecorationImage(
fit: BoxFit.fill,
image: AssetImage(Assets.images.dialog.background.keyName),
),
),
child: ClipRRect(
borderRadius: radius,
child: Column(
children: [
Expanded(
child: Center(
child: _header,
),
),
Expanded(
flex: 4,
child: _body,
),
],
),
),
),
),
);
}
}
| pinball/packages/pinball_ui/lib/src/dialog/pixelated_decoration.dart/0 | {
"file_path": "pinball/packages/pinball_ui/lib/src/dialog/pixelated_decoration.dart",
"repo_id": "pinball",
"token_count": 720
} | 1,225 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_ui/pinball_ui.dart';
void main() {
group('PinballColors', () {
test('white is 0xFFFFFFFF', () {
expect(PinballColors.white, const Color(0xFFFFFFFF));
});
test('black is 0xFF000000', () {
expect(PinballColors.black, const Color(0xFF000000));
});
test('darkBlue is 0xFF0C32A4', () {
expect(PinballColors.darkBlue, const Color(0xFF0C32A4));
});
test('yellow is 0xFFFFEE02', () {
expect(PinballColors.yellow, const Color(0xFFFFEE02));
});
test('orange is 0xFFE5AB05', () {
expect(PinballColors.orange, const Color(0xFFE5AB05));
});
test('red is 0xFFF03939', () {
expect(PinballColors.red, const Color(0xFFF03939));
});
test('blue is 0xFF4B94F6', () {
expect(PinballColors.blue, const Color(0xFF4B94F6));
});
test('transparent is 0x00000000', () {
expect(PinballColors.transparent, const Color(0x00000000));
});
test('loadingDarkRed is 0xFFE33B2D', () {
expect(PinballColors.loadingDarkRed, const Color(0xFFE33B2D));
});
test('loadingLightRed is 0xFFEC5E2B', () {
expect(PinballColors.loadingLightRed, const Color(0xFFEC5E2B));
});
test('loadingDarkBlue is 0xFF4087F8', () {
expect(PinballColors.loadingDarkBlue, const Color(0xFF4087F8));
});
test('loadingLightBlue is 0xFF6CCAE4', () {
expect(PinballColors.loadingLightBlue, const Color(0xFF6CCAE4));
});
test('crtBackground is 0xFF274E54', () {
expect(PinballColors.crtBackground, const Color(0xFF274E54));
});
});
}
| pinball/packages/pinball_ui/test/src/theme/pinball_colors_test.dart/0 | {
"file_path": "pinball/packages/pinball_ui/test/src/theme/pinball_colors_test.dart",
"repo_id": "pinball",
"token_count": 714
} | 1,226 |
# share_repository
[![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link]
[![License: MIT][license_badge]][license_link]
Repository to facilitate sharing scores.
[license_badge]: https://img.shields.io/badge/license-MIT-blue.svg
[license_link]: https://opensource.org/licenses/MIT
[very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg
[very_good_analysis_link]: https://pub.dev/packages/very_good_analysis | pinball/packages/share_repository/README.md/0 | {
"file_path": "pinball/packages/share_repository/README.md",
"repo_id": "pinball",
"token_count": 168
} | 1,227 |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/forge2d_game.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_theme/pinball_theme.dart' as theme;
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
theme.Assets.images.dash.ball.keyName,
]);
}
Future<void> pump(BonusBallSpawningBehavior child) async {
await ensureAdd(
FlameBlocProvider<CharacterThemeCubit, CharacterThemeState>.value(
value: CharacterThemeCubit(),
children: [
ZCanvasComponent(
children: [child],
),
],
),
);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('FlutterForestBonusBehavior', () {
final flameTester = FlameTester(_TestGame.new);
flameTester.test(
'adds a ball with a BallImpulsingBehavior to the game onTick '
'resulting in a -40 x impulse',
(game) async {
await game.onLoad();
final behavior = BonusBallSpawningBehavior();
await game.pump(behavior);
game.update(behavior.timer.limit);
await game.ready();
final ball = game.descendants().whereType<Ball>().single;
expect(ball.body.linearVelocity.x, equals(-40));
expect(ball.body.linearVelocity.y, equals(0));
},
);
});
}
| pinball/test/game/behaviors/bonus_ball_spawning_behavior_test.dart/0 | {
"file_path": "pinball/test/game/behaviors/bonus_ball_spawning_behavior_test.dart",
"repo_id": "pinball",
"token_count": 687
} | 1,228 |
// 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/android_acres/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.android.ramp.boardOpening.keyName,
Assets.images.android.ramp.railingForeground.keyName,
Assets.images.android.ramp.railingBackground.keyName,
Assets.images.android.ramp.main.keyName,
Assets.images.android.ramp.arrow.inactive.keyName,
Assets.images.android.ramp.arrow.active1.keyName,
Assets.images.android.ramp.arrow.active2.keyName,
Assets.images.android.ramp.arrow.active3.keyName,
Assets.images.android.ramp.arrow.active4.keyName,
Assets.images.android.ramp.arrow.active5.keyName,
]);
}
Future<void> pump(
SpaceshipRamp child, {
required GameBloc gameBloc,
required SpaceshipRampCubit bloc,
}) async {
await ensureAdd(
FlameMultiBlocProvider(
providers: [
FlameBlocProvider<GameBloc, GameState>.value(
value: gameBloc,
),
FlameBlocProvider<SpaceshipRampCubit, SpaceshipRampState>.value(
value: bloc,
),
],
children: [
ZCanvasComponent(children: [child]),
],
),
);
}
}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockSpaceshipRampCubit extends Mock implements SpaceshipRampCubit {}
class _FakeGameEvent extends Fake implements GameEvent {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('RampProgressBehavior', () {
late GameBloc gameBloc;
setUp(() {
registerFallbackValue(_FakeGameEvent());
gameBloc = _MockGameBloc();
});
final flameTester = FlameTester(_TestGame.new);
flameTester.test(
'adds onProgressed '
'when hits and multiplier are less than 6',
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = SpaceshipRampState.initial();
final streamController = StreamController<SpaceshipRampState>();
whenListen(
bloc,
streamController.stream,
initialState: state,
);
when(() => gameBloc.state).thenReturn(
GameState.initial().copyWith(
multiplier: 1,
),
);
final behavior = RampProgressBehavior();
final parent = SpaceshipRamp.test(
children: [behavior],
);
await game.pump(
parent,
gameBloc: gameBloc,
bloc: bloc,
);
streamController.add(state.copyWith(hits: 5));
await Future<void>.delayed(Duration.zero);
verify(bloc.onProgressed).called(1);
},
);
flameTester.test(
'adds onProgressed '
'when hits and multiplier are 6 but arrow is not fully lit',
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = SpaceshipRampState.initial();
final streamController = StreamController<SpaceshipRampState>();
whenListen(
bloc,
streamController.stream,
initialState: state,
);
when(() => gameBloc.state).thenReturn(
GameState.initial().copyWith(
multiplier: 6,
),
);
final behavior = RampProgressBehavior();
final parent = SpaceshipRamp.test(
children: [behavior],
);
await game.pump(
parent,
gameBloc: gameBloc,
bloc: bloc,
);
streamController.add(state.copyWith(hits: 5));
await Future<void>.delayed(Duration.zero);
verify(bloc.onProgressed).called(1);
},
);
flameTester.test(
"doesn't add onProgressed "
'when hits and multiplier are 6 and arrow is fully lit',
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = SpaceshipRampState.initial();
final streamController = StreamController<SpaceshipRampState>();
whenListen(
bloc,
streamController.stream,
initialState: state,
);
when(() => gameBloc.state).thenReturn(
GameState.initial().copyWith(
multiplier: 6,
),
);
final behavior = RampProgressBehavior();
final parent = SpaceshipRamp.test(
children: [behavior],
);
await game.pump(
parent,
gameBloc: gameBloc,
bloc: bloc,
);
streamController.add(
state.copyWith(
hits: 5,
lightState: ArrowLightState.active5,
),
);
await Future<void>.delayed(Duration.zero);
verifyNever(bloc.onProgressed);
},
);
flameTester.test(
'adds onProgressed to dim arrow '
'when arrow is fully lit after hit and multiplier is less than 6',
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = SpaceshipRampState.initial();
final streamController = StreamController<SpaceshipRampState>();
whenListen(
bloc,
streamController.stream,
initialState: state,
);
when(() => gameBloc.state).thenReturn(
GameState.initial().copyWith(
multiplier: 5,
),
);
final behavior = RampProgressBehavior();
final parent = SpaceshipRamp.test(
children: [behavior],
);
await game.pump(
parent,
gameBloc: gameBloc,
bloc: bloc,
);
streamController.add(
state.copyWith(
hits: 5,
lightState: ArrowLightState.active5,
),
);
await Future<void>.delayed(Duration.zero);
verify(bloc.onProgressed).called(2);
},
);
flameTester.test(
"doesn't add onProgressed to dim arrow "
'when arrow is not fully lit after hit',
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = SpaceshipRampState.initial();
final streamController = StreamController<SpaceshipRampState>();
whenListen(
bloc,
streamController.stream,
initialState: state,
);
when(() => gameBloc.state).thenReturn(
GameState.initial().copyWith(
multiplier: 5,
),
);
final behavior = RampProgressBehavior();
final parent = SpaceshipRamp.test(
children: [behavior],
);
await game.pump(
parent,
gameBloc: gameBloc,
bloc: bloc,
);
streamController.add(
state.copyWith(
hits: 4,
lightState: ArrowLightState.active4,
),
);
await Future<void>.delayed(Duration.zero);
verify(bloc.onProgressed).called(1);
},
);
flameTester.test(
"doesn't add onProgressed to dim arrow "
'when multiplier is 6 after hit',
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = SpaceshipRampState.initial();
final streamController = StreamController<SpaceshipRampState>();
whenListen(
bloc,
streamController.stream,
initialState: state,
);
when(() => gameBloc.state).thenReturn(
GameState.initial().copyWith(
multiplier: 6,
),
);
final behavior = RampProgressBehavior();
final parent = SpaceshipRamp.test(
children: [behavior],
);
await game.pump(
parent,
gameBloc: gameBloc,
bloc: bloc,
);
streamController.add(
state.copyWith(hits: 4),
);
await Future<void>.delayed(Duration.zero);
verify(bloc.onProgressed).called(1);
},
);
});
}
| pinball/test/game/components/android_acres/behaviors/ramp_progress_behavior_test.dart/0 | {
"file_path": "pinball/test/game/components/android_acres/behaviors/ramp_progress_behavior_test.dart",
"repo_id": "pinball",
"token_count": 3873
} | 1,229 |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/forge2d_game.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/dino_desert/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.dino.animatronic.head.keyName,
Assets.images.dino.animatronic.mouth.keyName,
Assets.images.dino.topWall.keyName,
Assets.images.dino.bottomWall.keyName,
Assets.images.slingshot.upper.keyName,
Assets.images.slingshot.lower.keyName,
],
);
}
Future<void> pump(
DinoDesert child, {
required GameBloc gameBloc,
}) async {
await ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: gameBloc,
children: [child],
),
);
}
}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockBall extends Mock implements Ball {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('ChromeDinoBonusBehavior', () {
late GameBloc gameBloc;
setUp(() {
gameBloc = _MockGameBloc();
});
final flameTester = FlameTester(_TestGame.new);
flameTester.testGameWidget(
'adds GameBonus.dinoChomp to the game '
'when ChromeDinoStatus.chomping is emitted',
setUp: (game, tester) async {
await game.onLoad();
final behavior = ChromeDinoBonusBehavior();
final parent = DinoDesert.test();
final chromeDino = ChromeDino();
await parent.add(chromeDino);
await game.pump(
parent,
gameBloc: gameBloc,
);
await parent.ensureAdd(behavior);
chromeDino.bloc.onChomp(_MockBall());
await tester.pump();
verify(
() => gameBloc.add(const BonusActivated(GameBonus.dinoChomp)),
).called(1);
},
);
});
}
| pinball/test/game/components/dino_desert/behaviors/chrome_dino_bonus_behavior_test.dart/0 | {
"file_path": "pinball/test/game/components/dino_desert/behaviors/chrome_dino_bonus_behavior_test.dart",
"repo_id": "pinball",
"token_count": 929
} | 1,230 |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/sparky_scorch/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.sparky.computer.top.keyName,
Assets.images.sparky.computer.base.keyName,
Assets.images.sparky.computer.glow.keyName,
Assets.images.sparky.animatronic.keyName,
Assets.images.sparky.bumper.a.lit.keyName,
Assets.images.sparky.bumper.a.dimmed.keyName,
Assets.images.sparky.bumper.b.lit.keyName,
Assets.images.sparky.bumper.b.dimmed.keyName,
Assets.images.sparky.bumper.c.lit.keyName,
Assets.images.sparky.bumper.c.dimmed.keyName,
]);
}
Future<void> pump(SparkyScorch child) async {
await ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: GameBloc(),
children: [child],
),
);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('SparkyScorch', () {
flameTester.test('loads correctly', (game) async {
final component = SparkyScorch();
await game.pump(component);
expect(
game.descendants().whereType<SparkyScorch>().length,
equals(1),
);
});
group('loads', () {
flameTester.test(
'a SparkyComputer',
(game) async {
await game.pump(SparkyScorch());
expect(
game.descendants().whereType<SparkyComputer>().length,
equals(1),
);
},
);
flameTester.test(
'a SparkyAnimatronic',
(game) async {
await game.pump(SparkyScorch());
expect(
game.descendants().whereType<SparkyAnimatronic>().length,
equals(1),
);
},
);
flameTester.test(
'three SparkyBumper',
(game) async {
await game.pump(SparkyScorch());
expect(
game.descendants().whereType<SparkyBumper>().length,
equals(3),
);
},
);
flameTester.test(
'three SparkyBumpers with BumperNoiseBehavior',
(game) async {
await game.pump(SparkyScorch());
final bumpers = game.descendants().whereType<SparkyBumper>();
for (final bumper in bumpers) {
expect(
bumper.firstChild<BumperNoiseBehavior>(),
isNotNull,
);
}
},
);
});
group('adds', () {
flameTester.test(
'ScoringContactBehavior to SparkyComputer',
(game) async {
await game.pump(SparkyScorch());
final sparkyComputer =
game.descendants().whereType<SparkyComputer>().single;
expect(
sparkyComputer.firstChild<ScoringContactBehavior>(),
isNotNull,
);
},
);
flameTester.test('a SparkyComputerBonusBehavior', (game) async {
final sparkyScorch = SparkyScorch();
await game.pump(sparkyScorch);
expect(
sparkyScorch.children.whereType<SparkyComputerBonusBehavior>().single,
isNotNull,
);
});
});
});
}
| pinball/test/game/components/sparky_scorch/sparky_scorch_test.dart/0 | {
"file_path": "pinball/test/game/components/sparky_scorch/sparky_scorch_test.dart",
"repo_id": "pinball",
"token_count": 1734
} | 1,231 |
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/more_information/more_information.dart';
import 'package:pinball_ui/pinball_ui.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import '../helpers/helpers.dart';
bool _tapTextSpan(RichText richText, String text) {
final isTapped = !richText.text.visitChildren(
(visitor) => _findTextAndTap(visitor, text),
);
return isTapped;
}
bool _findTextAndTap(InlineSpan visitor, String text) {
if (visitor is TextSpan && visitor.text == text) {
(visitor.recognizer as TapGestureRecognizer?)?.onTap?.call();
return false;
}
return true;
}
class _MockUrlLauncher extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
void main() {
group('MoreInformationDialog', () {
late UrlLauncherPlatform urlLauncher;
setUp(() async {
urlLauncher = _MockUrlLauncher();
UrlLauncherPlatform.instance = urlLauncher;
});
group('showMoreInformationDialog', () {
testWidgets('inflates the dialog', (tester) async {
await tester.pumpApp(
Builder(
builder: (context) {
return TextButton(
onPressed: () => showMoreInformationDialog(context),
child: const Text('test'),
);
},
),
);
await tester.tap(find.text('test'));
await tester.pump();
expect(find.byType(MoreInformationDialog), findsOneWidget);
});
});
testWidgets('renders "Made with..." and "Google I/O"', (tester) async {
await tester.pumpApp(const MoreInformationDialog());
expect(find.text('Google I/O'), findsOneWidget);
expect(
find.byWidgetPredicate(
(widget) =>
widget is RichText &&
widget.text.toPlainText() == 'Made with Flutter & Firebase',
),
findsOneWidget,
);
});
testWidgets(
'tapping on "Flutter" opens the flutter website',
(tester) async {
when(() => urlLauncher.canLaunch(any())).thenAnswer((_) async => true);
when(
() => urlLauncher.launch(
any(),
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
).thenAnswer((_) async => true);
await tester.pumpApp(const MoreInformationDialog());
final flutterTextFinder = find.byWidgetPredicate(
(widget) => widget is RichText && _tapTextSpan(widget, 'Flutter'),
);
await tester.tap(flutterTextFinder);
await tester.pumpAndSettle();
verify(
() => urlLauncher.launch(
'https://flutter.dev',
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
);
},
);
testWidgets(
'tapping on "Firebase" opens the firebase website',
(tester) async {
when(() => urlLauncher.canLaunch(any())).thenAnswer((_) async => true);
when(
() => urlLauncher.launch(
any(),
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
).thenAnswer((_) async => true);
await tester.pumpApp(const MoreInformationDialog());
final firebaseTextFinder = find.byWidgetPredicate(
(widget) => widget is RichText && _tapTextSpan(widget, 'Firebase'),
);
await tester.tap(firebaseTextFinder);
await tester.pumpAndSettle();
verify(
() => urlLauncher.launch(
'https://firebase.google.com',
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
);
},
);
<String, String>{
'Open Source Code': 'https://github.com/flutter/pinball',
'Google I/O': 'https://events.google.com/io/',
'Flutter Games': 'http://flutter.dev/games',
'How it’s made':
'https://medium.com/flutter/i-o-pinball-powered-by-flutter-and-firebase-d22423f3f5d',
'Terms of Service': 'https://policies.google.com/terms',
'Privacy Policy': 'https://policies.google.com/privacy',
}.forEach((text, link) {
testWidgets(
'tapping on "$text" opens the link - $link',
(tester) async {
when(() => urlLauncher.canLaunch(any()))
.thenAnswer((_) async => true);
when(
() => urlLauncher.launch(
link,
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
).thenAnswer((_) async => true);
await tester.pumpApp(const MoreInformationDialog());
await tester.tap(find.text(text));
await tester.pumpAndSettle();
verify(
() => urlLauncher.launch(
link,
useSafariVC: any(named: 'useSafariVC'),
useWebView: any(named: 'useWebView'),
enableJavaScript: any(named: 'enableJavaScript'),
enableDomStorage: any(named: 'enableDomStorage'),
universalLinksOnly: any(named: 'universalLinksOnly'),
headers: any(named: 'headers'),
),
);
},
);
});
});
}
| pinball/test/more_information/more_information_dialog_test.dart/0 | {
"file_path": "pinball/test/more_information/more_information_dialog_test.dart",
"repo_id": "pinball",
"token_count": 3011
} | 1,232 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
- name: validate iOS and macOS podspecs
script: script/tool_runner.sh
args: ["podspec-check"]
| plugins/.ci/targets/macos_lint_podspecs.yaml/0 | {
"file_path": "plugins/.ci/targets/macos_lint_podspecs.yaml",
"repo_id": "plugins",
"token_count": 65
} | 1,233 |
## 0.10.4
* Temporarily fixes issue with requested video profiles being null by falling back to deprecated behavior in that case.
## 0.10.3
* Adds back use of Optional type.
* Updates minimum Flutter version to 3.0.
## 0.10.2+3
* Updates code for stricter lint checks.
## 0.10.2+2
* Fixes zoom computation for virtual cameras hiding physical cameras in Android 11+.
* Removes the unused CameraZoom class from the codebase.
## 0.10.2+1
* Updates code for stricter lint checks.
## 0.10.2
* Remove usage of deprecated quiver Optional type.
## 0.10.1
* Implements an option to also stream when recording a video.
## 0.10.0+5
* Fixes `ArrayIndexOutOfBoundsException` when the permission request is interrupted.
## 0.10.0+4
* Upgrades `androidx.annotation` version to 1.5.0.
## 0.10.0+3
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
## 0.10.0+2
* Removes call to `join` on the camera's background `HandlerThread`.
* Updates minimum Flutter version to 2.10.
## 0.10.0+1
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 0.10.0
* **Breaking Change** Updates Android camera access permission error codes to be consistent with other platforms. If your app still handles the legacy `cameraPermission` exception, please update it to handle the new permission exception codes that are noted in the README.
* Ignores missing return warnings in preparation for [upcoming analysis changes](https://github.com/flutter/flutter/issues/105750).
## 0.9.8+3
* Skips duplicate calls to stop background thread and removes unnecessary closings of camera capture sessions on Android.
## 0.9.8+2
* Fixes exception in registerWith caused by the switch to an in-package method channel.
## 0.9.8+1
* Ignores deprecation warnings for upcoming styleFrom button API changes.
## 0.9.8
* Switches to internal method channel implementation.
## 0.9.7+1
* Splits from `camera` as a federated implementation.
| plugins/packages/camera/camera_android/CHANGELOG.md/0 | {
"file_path": "plugins/packages/camera/camera_android/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 584
} | 1,234 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.fpsrange;
import android.hardware.camera2.CaptureRequest;
import android.os.Build;
import android.util.Range;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.features.CameraFeature;
/**
* Controls the frames per seconds (FPS) range configuration on the {@link android.hardware.camera2}
* API.
*/
public class FpsRangeFeature extends CameraFeature<Range<Integer>> {
private static final Range<Integer> MAX_PIXEL4A_RANGE = new Range<>(30, 30);
private Range<Integer> currentSetting;
/**
* Creates a new instance of the {@link FpsRangeFeature}.
*
* @param cameraProperties Collection of characteristics for the current camera device.
*/
public FpsRangeFeature(CameraProperties cameraProperties) {
super(cameraProperties);
if (isPixel4A()) {
// HACK: There is a bug in the Pixel 4A where it cannot support 60fps modes
// even though they are reported as supported by
// `getControlAutoExposureAvailableTargetFpsRanges`.
// For max device compatibility we will keep FPS under 60 even if they report they are
// capable of achieving 60 fps. Highest working FPS is 30.
// https://issuetracker.google.com/issues/189237151
currentSetting = MAX_PIXEL4A_RANGE;
} else {
Range<Integer>[] ranges = cameraProperties.getControlAutoExposureAvailableTargetFpsRanges();
if (ranges != null) {
for (Range<Integer> range : ranges) {
int upper = range.getUpper();
if (upper >= 10) {
if (currentSetting == null || upper > currentSetting.getUpper()) {
currentSetting = range;
}
}
}
}
}
}
private boolean isPixel4A() {
return Build.BRAND.equals("google") && Build.MODEL.equals("Pixel 4a");
}
@Override
public String getDebugName() {
return "FpsRangeFeature";
}
@Override
public Range<Integer> getValue() {
return currentSetting;
}
@Override
public void setValue(Range<Integer> value) {
this.currentSetting = value;
}
// Always supported
@Override
public boolean checkIsSupported() {
return true;
}
@Override
public void updateBuilder(CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
requestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, currentSetting);
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/fpsrange/FpsRangeFeature.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/fpsrange/FpsRangeFeature.java",
"repo_id": "plugins",
"token_count": 873
} | 1,235 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.types;
import android.os.SystemClock;
/**
* This is a simple class for managing a timeout. In the camera we generally keep two timeouts: one
* for focusing and one for pre-capture metering.
*
* <p>We use timeouts to ensure a picture is always captured within a reasonable amount of time even
* if the settings don't converge and focus can't be locked.
*
* <p>You generally check the status of the timeout in the CameraCaptureCallback during the capture
* sequence and use it to move to the next state if the timeout has passed.
*/
public class Timeout {
/** The timeout time in milliseconds */
private final long timeoutMs;
/** When this timeout was started. Will be used later to check if the timeout has expired yet. */
private final long timeStarted;
/**
* Factory method to create a new Timeout.
*
* @param timeoutMs timeout to use.
* @return returns a new Timeout.
*/
public static Timeout create(long timeoutMs) {
return new Timeout(timeoutMs);
}
/**
* Create a new timeout.
*
* @param timeoutMs the time in milliseconds for this timeout to lapse.
*/
private Timeout(long timeoutMs) {
this.timeoutMs = timeoutMs;
this.timeStarted = SystemClock.elapsedRealtime();
}
/** Will return true when the timeout period has lapsed. */
public boolean getIsExpired() {
return (SystemClock.elapsedRealtime() - timeStarted) > timeoutMs;
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/Timeout.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/Timeout.java",
"repo_id": "plugins",
"token_count": 454
} | 1,236 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=false
android.enableR8=true
| plugins/packages/camera/camera_android/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/camera/camera_android/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 38
} | 1,237 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:camera_android/src/type_conversion.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('CameraImageData can be created', () {
final CameraImageData cameraImage =
cameraImageFromPlatformData(<dynamic, dynamic>{
'format': 1,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.height, 1);
expect(cameraImage.width, 4);
expect(cameraImage.format.group, ImageFormatGroup.unknown);
expect(cameraImage.planes.length, 1);
});
test('CameraImageData has ImageFormatGroup.yuv420', () {
final CameraImageData cameraImage =
cameraImageFromPlatformData(<dynamic, dynamic>{
'format': 35,
'height': 1,
'width': 4,
'lensAperture': 1.8,
'sensorExposureTime': 9991324,
'sensorSensitivity': 92.0,
'planes': <dynamic>[
<dynamic, dynamic>{
'bytes': Uint8List.fromList(<int>[1, 2, 3, 4]),
'bytesPerPixel': 1,
'bytesPerRow': 4,
'height': 1,
'width': 4
}
]
});
expect(cameraImage.format.group, ImageFormatGroup.yuv420);
});
}
| plugins/packages/camera/camera_android/test/type_conversion_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_android/test/type_conversion_test.dart",
"repo_id": "plugins",
"token_count": 793
} | 1,238 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.CameraInfo;
import androidx.camera.core.CameraSelector;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraSelectorHostApi;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class CameraSelectorHostApiImpl implements CameraSelectorHostApi {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
@VisibleForTesting public CameraXProxy cameraXProxy = new CameraXProxy();
public CameraSelectorHostApiImpl(
BinaryMessenger binaryMessenger, InstanceManager instanceManager) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
}
@Override
public void create(@NonNull Long identifier, Long lensFacing) {
CameraSelector.Builder cameraSelectorBuilder = cameraXProxy.createCameraSelectorBuilder();
CameraSelector cameraSelector;
if (lensFacing != null) {
cameraSelector = cameraSelectorBuilder.requireLensFacing(Math.toIntExact(lensFacing)).build();
} else {
cameraSelector = cameraSelectorBuilder.build();
}
instanceManager.addDartCreatedInstance(cameraSelector, identifier);
}
@Override
public List<Long> filter(@NonNull Long identifier, @NonNull List<Long> cameraInfoIds) {
CameraSelector cameraSelector =
(CameraSelector) Objects.requireNonNull(instanceManager.getInstance(identifier));
List<CameraInfo> cameraInfosForFilter = new ArrayList<CameraInfo>();
for (Number cameraInfoAsNumber : cameraInfoIds) {
Long cameraInfoId = cameraInfoAsNumber.longValue();
CameraInfo cameraInfo =
(CameraInfo) Objects.requireNonNull(instanceManager.getInstance(cameraInfoId));
cameraInfosForFilter.add(cameraInfo);
}
List<CameraInfo> filteredCameraInfos = cameraSelector.filter(cameraInfosForFilter);
List<Long> filteredCameraInfosIds = new ArrayList<Long>();
for (CameraInfo cameraInfo : filteredCameraInfos) {
Long filteredCameraInfoId = instanceManager.getIdentifierForStrongReference(cameraInfo);
filteredCameraInfosIds.add(filteredCameraInfoId);
}
return filteredCameraInfosIds;
}
}
| plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorHostApiImpl.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorHostApiImpl.java",
"repo_id": "plugins",
"token_count": 776
} | 1,239 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class InstanceManagerTest {
@Test
public void addDartCreatedInstance() {
final InstanceManager instanceManager = InstanceManager.open(identifier -> {});
final Object object = new Object();
instanceManager.addDartCreatedInstance(object, 0);
assertEquals(object, instanceManager.getInstance(0));
assertEquals((Long) 0L, instanceManager.getIdentifierForStrongReference(object));
assertTrue(instanceManager.containsInstance(object));
instanceManager.close();
}
@Test
public void addHostCreatedInstance() {
final InstanceManager instanceManager = InstanceManager.open(identifier -> {});
final Object object = new Object();
long identifier = instanceManager.addHostCreatedInstance(object);
assertNotNull(instanceManager.getInstance(identifier));
assertEquals(object, instanceManager.getInstance(identifier));
assertTrue(instanceManager.containsInstance(object));
instanceManager.close();
}
@Test
public void addHostCreatedInstance_createsSameInstanceTwice() {
final InstanceManager instanceManager = InstanceManager.open(identifier -> {});
final Object object = new Object();
long firstIdentifier = instanceManager.addHostCreatedInstance(object);
long secondIdentifier = instanceManager.addHostCreatedInstance(object);
assertNotEquals(firstIdentifier, secondIdentifier);
assertTrue(instanceManager.containsInstance(object));
instanceManager.close();
}
@Test
public void remove() {
final InstanceManager instanceManager = InstanceManager.open(identifier -> {});
Object object = new Object();
instanceManager.addDartCreatedInstance(object, 0);
assertEquals(object, instanceManager.remove(0));
// To allow for object to be garbage collected.
//noinspection UnusedAssignment
object = null;
Runtime.getRuntime().gc();
assertNull(instanceManager.getInstance(0));
instanceManager.close();
}
}
| plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/InstanceManagerTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/InstanceManagerTest.java",
"repo_id": "plugins",
"token_count": 701
} | 1,240 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(
PigeonOptions(
dartOut: 'lib/src/camerax_library.g.dart',
dartTestOut: 'test/test_camerax_library.g.dart',
dartOptions: DartOptions(copyrightHeader: <String>[
'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.',
]),
javaOut:
'android/src/main/java/io/flutter/plugins/camerax/GeneratedCameraXLibrary.java',
javaOptions: JavaOptions(
package: 'io.flutter.plugins.camerax',
className: 'GeneratedCameraXLibrary',
copyrightHeader: <String>[
'Copyright 2013 The Flutter Authors. All rights reserved.',
'Use of this source code is governed by a BSD-style license that can be',
'found in the LICENSE file.',
],
),
),
)
class ResolutionInfo {
ResolutionInfo({
required this.width,
required this.height,
});
int width;
int height;
}
class CameraPermissionsErrorData {
CameraPermissionsErrorData({
required this.errorCode,
required this.description,
});
String errorCode;
String description;
}
@HostApi(dartHostTestHandler: 'TestJavaObjectHostApi')
abstract class JavaObjectHostApi {
void dispose(int identifier);
}
@FlutterApi()
abstract class JavaObjectFlutterApi {
void dispose(int identifier);
}
@HostApi(dartHostTestHandler: 'TestCameraInfoHostApi')
abstract class CameraInfoHostApi {
int getSensorRotationDegrees(int identifier);
}
@FlutterApi()
abstract class CameraInfoFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestCameraSelectorHostApi')
abstract class CameraSelectorHostApi {
void create(int identifier, int? lensFacing);
List<int> filter(int identifier, List<int> cameraInfoIds);
}
@FlutterApi()
abstract class CameraSelectorFlutterApi {
void create(int identifier, int? lensFacing);
}
@HostApi(dartHostTestHandler: 'TestProcessCameraProviderHostApi')
abstract class ProcessCameraProviderHostApi {
@async
int getInstance();
List<int> getAvailableCameraInfos(int identifier);
int bindToLifecycle(
int identifier, int cameraSelectorIdentifier, List<int> useCaseIds);
void unbind(int identifier, List<int> useCaseIds);
void unbindAll(int identifier);
}
@FlutterApi()
abstract class ProcessCameraProviderFlutterApi {
void create(int identifier);
}
@FlutterApi()
abstract class CameraFlutterApi {
void create(int identifier);
}
@HostApi(dartHostTestHandler: 'TestSystemServicesHostApi')
abstract class SystemServicesHostApi {
@async
CameraPermissionsErrorData? requestCameraPermissions(bool enableAudio);
void startListeningForDeviceOrientationChange(
bool isFrontFacing, int sensorOrientation);
void stopListeningForDeviceOrientationChange();
}
@FlutterApi()
abstract class SystemServicesFlutterApi {
void onDeviceOrientationChanged(String orientation);
void onCameraError(String errorDescription);
}
@HostApi(dartHostTestHandler: 'TestPreviewHostApi')
abstract class PreviewHostApi {
void create(int identifier, int? rotation, ResolutionInfo? targetResolution);
int setSurfaceProvider(int identifier);
void releaseFlutterSurfaceTexture();
ResolutionInfo getResolutionInfo(int identifier);
}
| plugins/packages/camera/camera_android_camerax/pigeons/camerax_library.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/pigeons/camerax_library.dart",
"repo_id": "plugins",
"token_count": 1140
} | 1,241 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.2.9), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import
// ignore_for_file: avoid_relative_lib_imports
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:camera_android_camerax/src/camerax_library.g.dart';
class _TestJavaObjectHostApiCodec extends StandardMessageCodec {
const _TestJavaObjectHostApiCodec();
}
abstract class TestJavaObjectHostApi {
static const MessageCodec<Object?> codec = _TestJavaObjectHostApiCodec();
void dispose(int identifier);
static void setup(TestJavaObjectHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.JavaObjectHostApi.dispose', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.JavaObjectHostApi.dispose was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.JavaObjectHostApi.dispose was null, expected non-null int.');
api.dispose(arg_identifier!);
return <Object?, Object?>{};
});
}
}
}
}
class _TestCameraInfoHostApiCodec extends StandardMessageCodec {
const _TestCameraInfoHostApiCodec();
}
abstract class TestCameraInfoHostApi {
static const MessageCodec<Object?> codec = _TestCameraInfoHostApiCodec();
int getSensorRotationDegrees(int identifier);
static void setup(TestCameraInfoHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees was null, expected non-null int.');
final int output = api.getSensorRotationDegrees(arg_identifier!);
return <Object?, Object?>{'result': output};
});
}
}
}
}
class _TestCameraSelectorHostApiCodec extends StandardMessageCodec {
const _TestCameraSelectorHostApiCodec();
}
abstract class TestCameraSelectorHostApi {
static const MessageCodec<Object?> codec = _TestCameraSelectorHostApiCodec();
void create(int identifier, int? lensFacing);
List<int?> filter(int identifier, List<int?> cameraInfoIds);
static void setup(TestCameraSelectorHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraSelectorHostApi.create', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.CameraSelectorHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.CameraSelectorHostApi.create was null, expected non-null int.');
final int? arg_lensFacing = (args[1] as int?);
api.create(arg_identifier!, arg_lensFacing);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraSelectorHostApi.filter', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null, expected non-null int.');
final List<int?>? arg_cameraInfoIds =
(args[1] as List<Object?>?)?.cast<int?>();
assert(arg_cameraInfoIds != null,
'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null, expected non-null List<int?>.');
final List<int?> output =
api.filter(arg_identifier!, arg_cameraInfoIds!);
return <Object?, Object?>{'result': output};
});
}
}
}
}
class _TestProcessCameraProviderHostApiCodec extends StandardMessageCodec {
const _TestProcessCameraProviderHostApiCodec();
}
abstract class TestProcessCameraProviderHostApi {
static const MessageCodec<Object?> codec =
_TestProcessCameraProviderHostApiCodec();
Future<int> getInstance();
List<int?> getAvailableCameraInfos(int identifier);
int bindToLifecycle(
int identifier, int cameraSelectorIdentifier, List<int?> useCaseIds);
void unbind(int identifier, List<int?> useCaseIds);
void unbindAll(int identifier);
static void setup(TestProcessCameraProviderHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.getInstance', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
final int output = await api.getInstance();
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos was null, expected non-null int.');
final List<int?> output =
api.getAvailableCameraInfos(arg_identifier!);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null int.');
final int? arg_cameraSelectorIdentifier = (args[1] as int?);
assert(arg_cameraSelectorIdentifier != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null int.');
final List<int?>? arg_useCaseIds =
(args[2] as List<Object?>?)?.cast<int?>();
assert(arg_useCaseIds != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null List<int?>.');
final int output = api.bindToLifecycle(
arg_identifier!, arg_cameraSelectorIdentifier!, arg_useCaseIds!);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null, expected non-null int.');
final List<int?>? arg_useCaseIds =
(args[1] as List<Object?>?)?.cast<int?>();
assert(arg_useCaseIds != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null, expected non-null List<int?>.');
api.unbind(arg_identifier!, arg_useCaseIds!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll was null, expected non-null int.');
api.unbindAll(arg_identifier!);
return <Object?, Object?>{};
});
}
}
}
}
class _TestSystemServicesHostApiCodec extends StandardMessageCodec {
const _TestSystemServicesHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is CameraPermissionsErrorData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return CameraPermissionsErrorData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestSystemServicesHostApi {
static const MessageCodec<Object?> codec = _TestSystemServicesHostApiCodec();
Future<CameraPermissionsErrorData?> requestCameraPermissions(
bool enableAudio);
void startListeningForDeviceOrientationChange(
bool isFrontFacing, int sensorOrientation);
void stopListeningForDeviceOrientationChange();
static void setup(TestSystemServicesHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions was null.');
final List<Object?> args = (message as List<Object?>?)!;
final bool? arg_enableAudio = (args[0] as bool?);
assert(arg_enableAudio != null,
'Argument for dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions was null, expected non-null bool.');
final CameraPermissionsErrorData? output =
await api.requestCameraPermissions(arg_enableAudio!);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.SystemServicesHostApi.startListeningForDeviceOrientationChange',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.SystemServicesHostApi.startListeningForDeviceOrientationChange was null.');
final List<Object?> args = (message as List<Object?>?)!;
final bool? arg_isFrontFacing = (args[0] as bool?);
assert(arg_isFrontFacing != null,
'Argument for dev.flutter.pigeon.SystemServicesHostApi.startListeningForDeviceOrientationChange was null, expected non-null bool.');
final int? arg_sensorOrientation = (args[1] as int?);
assert(arg_sensorOrientation != null,
'Argument for dev.flutter.pigeon.SystemServicesHostApi.startListeningForDeviceOrientationChange was null, expected non-null int.');
api.startListeningForDeviceOrientationChange(
arg_isFrontFacing!, arg_sensorOrientation!);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.SystemServicesHostApi.stopListeningForDeviceOrientationChange',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
api.stopListeningForDeviceOrientationChange();
return <Object?, Object?>{};
});
}
}
}
}
class _TestPreviewHostApiCodec extends StandardMessageCodec {
const _TestPreviewHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is ResolutionInfo) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is ResolutionInfo) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return ResolutionInfo.decode(readValue(buffer)!);
case 129:
return ResolutionInfo.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestPreviewHostApi {
static const MessageCodec<Object?> codec = _TestPreviewHostApiCodec();
void create(int identifier, int? rotation, ResolutionInfo? targetResolution);
int setSurfaceProvider(int identifier);
void releaseFlutterSurfaceTexture();
ResolutionInfo getResolutionInfo(int identifier);
static void setup(TestPreviewHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PreviewHostApi.create', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.PreviewHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.PreviewHostApi.create was null, expected non-null int.');
final int? arg_rotation = (args[1] as int?);
final ResolutionInfo? arg_targetResolution =
(args[2] as ResolutionInfo?);
api.create(arg_identifier!, arg_rotation, arg_targetResolution);
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider was null, expected non-null int.');
final int output = api.setSurfaceProvider(arg_identifier!);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PreviewHostApi.releaseFlutterSurfaceTexture',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
// ignore message
api.releaseFlutterSurfaceTexture();
return <Object?, Object?>{};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PreviewHostApi.getResolutionInfo', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.PreviewHostApi.getResolutionInfo was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.PreviewHostApi.getResolutionInfo was null, expected non-null int.');
final ResolutionInfo output = api.getResolutionInfo(arg_identifier!);
return <Object?, Object?>{'result': output};
});
}
}
}
}
| plugins/packages/camera/camera_android_camerax/test/test_camerax_library.g.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/test/test_camerax_library.g.dart",
"repo_id": "plugins",
"token_count": 8213
} | 1,242 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import camera_avfoundation;
@import camera_avfoundation.Test;
@import XCTest;
@import AVFoundation;
#import <OCMock/OCMock.h>
#import "MockFLTThreadSafeFlutterResult.h"
@interface CameraPreviewPauseTests : XCTestCase
@end
@implementation CameraPreviewPauseTests
- (void)testPausePreviewWithResult_shouldPausePreview {
FLTCam *camera = [[FLTCam alloc] init];
MockFLTThreadSafeFlutterResult *resultObject = [[MockFLTThreadSafeFlutterResult alloc] init];
[camera pausePreviewWithResult:resultObject];
XCTAssertTrue(camera.isPreviewPaused);
}
- (void)testResumePreviewWithResult_shouldResumePreview {
FLTCam *camera = [[FLTCam alloc] init];
MockFLTThreadSafeFlutterResult *resultObject = [[MockFLTThreadSafeFlutterResult alloc] init];
[camera resumePreviewWithResult:resultObject];
XCTAssertFalse(camera.isPreviewPaused);
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPreviewPauseTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPreviewPauseTests.m",
"repo_id": "plugins",
"token_count": 315
} | 1,243 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import camera_avfoundation;
@import XCTest;
#import <OCMock/OCMock.h>
@interface ThreadSafeTextureRegistryTests : XCTestCase
@end
@implementation ThreadSafeTextureRegistryTests
- (void)testShouldStayOnMainThreadIfCalledFromMainThread {
NSObject<FlutterTextureRegistry> *mockTextureRegistry =
OCMProtocolMock(@protocol(FlutterTextureRegistry));
FLTThreadSafeTextureRegistry *threadSafeTextureRegistry =
[[FLTThreadSafeTextureRegistry alloc] initWithTextureRegistry:mockTextureRegistry];
XCTestExpectation *registerTextureExpectation =
[self expectationWithDescription:@"registerTexture must be called on the main thread"];
XCTestExpectation *unregisterTextureExpectation =
[self expectationWithDescription:@"unregisterTexture must be called on the main thread"];
XCTestExpectation *textureFrameAvailableExpectation =
[self expectationWithDescription:@"textureFrameAvailable must be called on the main thread"];
XCTestExpectation *registerTextureCompletionExpectation =
[self expectationWithDescription:
@"registerTexture's completion block must be called on the main thread"];
OCMStub([mockTextureRegistry registerTexture:[OCMArg any]]).andDo(^(NSInvocation *invocation) {
if (NSThread.isMainThread) {
[registerTextureExpectation fulfill];
}
});
OCMStub([mockTextureRegistry unregisterTexture:0]).andDo(^(NSInvocation *invocation) {
if (NSThread.isMainThread) {
[unregisterTextureExpectation fulfill];
}
});
OCMStub([mockTextureRegistry textureFrameAvailable:0]).andDo(^(NSInvocation *invocation) {
if (NSThread.isMainThread) {
[textureFrameAvailableExpectation fulfill];
}
});
NSObject<FlutterTexture> *anyTexture = OCMProtocolMock(@protocol(FlutterTexture));
[threadSafeTextureRegistry registerTexture:anyTexture
completion:^(int64_t textureId) {
if (NSThread.isMainThread) {
[registerTextureCompletionExpectation fulfill];
}
}];
[threadSafeTextureRegistry textureFrameAvailable:0];
[threadSafeTextureRegistry unregisterTexture:0];
[self waitForExpectationsWithTimeout:1 handler:nil];
}
- (void)testShouldDispatchToMainThreadIfCalledFromBackgroundThread {
NSObject<FlutterTextureRegistry> *mockTextureRegistry =
OCMProtocolMock(@protocol(FlutterTextureRegistry));
FLTThreadSafeTextureRegistry *threadSafeTextureRegistry =
[[FLTThreadSafeTextureRegistry alloc] initWithTextureRegistry:mockTextureRegistry];
XCTestExpectation *registerTextureExpectation =
[self expectationWithDescription:@"registerTexture must be called on the main thread"];
XCTestExpectation *unregisterTextureExpectation =
[self expectationWithDescription:@"unregisterTexture must be called on the main thread"];
XCTestExpectation *textureFrameAvailableExpectation =
[self expectationWithDescription:@"textureFrameAvailable must be called on the main thread"];
XCTestExpectation *registerTextureCompletionExpectation =
[self expectationWithDescription:
@"registerTexture's completion block must be called on the main thread"];
OCMStub([mockTextureRegistry registerTexture:[OCMArg any]]).andDo(^(NSInvocation *invocation) {
if (NSThread.isMainThread) {
[registerTextureExpectation fulfill];
}
});
OCMStub([mockTextureRegistry unregisterTexture:0]).andDo(^(NSInvocation *invocation) {
if (NSThread.isMainThread) {
[unregisterTextureExpectation fulfill];
}
});
OCMStub([mockTextureRegistry textureFrameAvailable:0]).andDo(^(NSInvocation *invocation) {
if (NSThread.isMainThread) {
[textureFrameAvailableExpectation fulfill];
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSObject<FlutterTexture> *anyTexture = OCMProtocolMock(@protocol(FlutterTexture));
[threadSafeTextureRegistry registerTexture:anyTexture
completion:^(int64_t textureId) {
if (NSThread.isMainThread) {
[registerTextureCompletionExpectation fulfill];
}
}];
[threadSafeTextureRegistry textureFrameAvailable:0];
[threadSafeTextureRegistry unregisterTexture:0];
});
[self waitForExpectationsWithTimeout:1 handler:nil];
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeTextureRegistryTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeTextureRegistryTests.m",
"repo_id": "plugins",
"token_count": 1754
} | 1,244 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FLTCam.h"
#import "FLTCam_Test.h"
#import "FLTSavePhotoDelegate.h"
#import "QueueUtils.h"
@import CoreMotion;
#import <libkern/OSAtomic.h>
@implementation FLTImageStreamHandler
- (instancetype)initWithCaptureSessionQueue:(dispatch_queue_t)captureSessionQueue {
self = [super init];
NSAssert(self, @"super init cannot be nil");
_captureSessionQueue = captureSessionQueue;
return self;
}
- (FlutterError *_Nullable)onCancelWithArguments:(id _Nullable)arguments {
__weak typeof(self) weakSelf = self;
dispatch_async(self.captureSessionQueue, ^{
weakSelf.eventSink = nil;
});
return nil;
}
- (FlutterError *_Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(nonnull FlutterEventSink)events {
__weak typeof(self) weakSelf = self;
dispatch_async(self.captureSessionQueue, ^{
weakSelf.eventSink = events;
});
return nil;
}
@end
@interface FLTCam () <AVCaptureVideoDataOutputSampleBufferDelegate,
AVCaptureAudioDataOutputSampleBufferDelegate>
@property(readonly, nonatomic) int64_t textureId;
@property BOOL enableAudio;
@property(nonatomic) FLTImageStreamHandler *imageStreamHandler;
@property(readonly, nonatomic) AVCaptureSession *captureSession;
@property(readonly, nonatomic) AVCaptureInput *captureVideoInput;
/// Tracks the latest pixel buffer sent from AVFoundation's sample buffer delegate callback.
/// Used to deliver the latest pixel buffer to the flutter engine via the `copyPixelBuffer` API.
@property(readwrite, nonatomic) CVPixelBufferRef latestPixelBuffer;
@property(readonly, nonatomic) CGSize captureSize;
@property(strong, nonatomic) AVAssetWriter *videoWriter;
@property(strong, nonatomic) AVAssetWriterInput *videoWriterInput;
@property(strong, nonatomic) AVAssetWriterInput *audioWriterInput;
@property(strong, nonatomic) AVAssetWriterInputPixelBufferAdaptor *assetWriterPixelBufferAdaptor;
@property(strong, nonatomic) AVCaptureVideoDataOutput *videoOutput;
@property(strong, nonatomic) AVCaptureAudioDataOutput *audioOutput;
@property(strong, nonatomic) NSString *videoRecordingPath;
@property(assign, nonatomic) BOOL isRecording;
@property(assign, nonatomic) BOOL isRecordingPaused;
@property(assign, nonatomic) BOOL videoIsDisconnected;
@property(assign, nonatomic) BOOL audioIsDisconnected;
@property(assign, nonatomic) BOOL isAudioSetup;
/// Number of frames currently pending processing.
@property(assign, nonatomic) int streamingPendingFramesCount;
/// Maximum number of frames pending processing.
@property(assign, nonatomic) int maxStreamingPendingFramesCount;
@property(assign, nonatomic) UIDeviceOrientation lockedCaptureOrientation;
@property(assign, nonatomic) CMTime lastVideoSampleTime;
@property(assign, nonatomic) CMTime lastAudioSampleTime;
@property(assign, nonatomic) CMTime videoTimeOffset;
@property(assign, nonatomic) CMTime audioTimeOffset;
@property(nonatomic) CMMotionManager *motionManager;
@property AVAssetWriterInputPixelBufferAdaptor *videoAdaptor;
/// All FLTCam's state access and capture session related operations should be on run on this queue.
@property(strong, nonatomic) dispatch_queue_t captureSessionQueue;
/// The queue on which `latestPixelBuffer` property is accessed.
/// To avoid unnecessary contention, do not access `latestPixelBuffer` on the `captureSessionQueue`.
@property(strong, nonatomic) dispatch_queue_t pixelBufferSynchronizationQueue;
/// The queue on which captured photos (not videos) are written to disk.
/// Videos are written to disk by `videoAdaptor` on an internal queue managed by AVFoundation.
@property(strong, nonatomic) dispatch_queue_t photoIOQueue;
@property(assign, nonatomic) UIDeviceOrientation deviceOrientation;
@end
@implementation FLTCam
NSString *const errorMethod = @"error";
- (instancetype)initWithCameraName:(NSString *)cameraName
resolutionPreset:(NSString *)resolutionPreset
enableAudio:(BOOL)enableAudio
orientation:(UIDeviceOrientation)orientation
captureSessionQueue:(dispatch_queue_t)captureSessionQueue
error:(NSError **)error {
return [self initWithCameraName:cameraName
resolutionPreset:resolutionPreset
enableAudio:enableAudio
orientation:orientation
captureSession:[[AVCaptureSession alloc] init]
captureSessionQueue:captureSessionQueue
error:error];
}
- (instancetype)initWithCameraName:(NSString *)cameraName
resolutionPreset:(NSString *)resolutionPreset
enableAudio:(BOOL)enableAudio
orientation:(UIDeviceOrientation)orientation
captureSession:(AVCaptureSession *)captureSession
captureSessionQueue:(dispatch_queue_t)captureSessionQueue
error:(NSError **)error {
self = [super init];
NSAssert(self, @"super init cannot be nil");
@try {
_resolutionPreset = FLTGetFLTResolutionPresetForString(resolutionPreset);
} @catch (NSError *e) {
*error = e;
}
_enableAudio = enableAudio;
_captureSessionQueue = captureSessionQueue;
_pixelBufferSynchronizationQueue =
dispatch_queue_create("io.flutter.camera.pixelBufferSynchronizationQueue", NULL);
_photoIOQueue = dispatch_queue_create("io.flutter.camera.photoIOQueue", NULL);
_captureSession = captureSession;
_captureDevice = [AVCaptureDevice deviceWithUniqueID:cameraName];
_flashMode = _captureDevice.hasFlash ? FLTFlashModeAuto : FLTFlashModeOff;
_exposureMode = FLTExposureModeAuto;
_focusMode = FLTFocusModeAuto;
_lockedCaptureOrientation = UIDeviceOrientationUnknown;
_deviceOrientation = orientation;
_videoFormat = kCVPixelFormatType_32BGRA;
_inProgressSavePhotoDelegates = [NSMutableDictionary dictionary];
// To limit memory consumption, limit the number of frames pending processing.
// After some testing, 4 was determined to be the best maximum value.
// https://github.com/flutter/plugins/pull/4520#discussion_r766335637
_maxStreamingPendingFramesCount = 4;
NSError *localError = nil;
_captureVideoInput = [AVCaptureDeviceInput deviceInputWithDevice:_captureDevice
error:&localError];
if (localError) {
*error = localError;
return nil;
}
_captureVideoOutput = [AVCaptureVideoDataOutput new];
_captureVideoOutput.videoSettings =
@{(NSString *)kCVPixelBufferPixelFormatTypeKey : @(_videoFormat)};
[_captureVideoOutput setAlwaysDiscardsLateVideoFrames:YES];
[_captureVideoOutput setSampleBufferDelegate:self queue:captureSessionQueue];
AVCaptureConnection *connection =
[AVCaptureConnection connectionWithInputPorts:_captureVideoInput.ports
output:_captureVideoOutput];
if ([_captureDevice position] == AVCaptureDevicePositionFront) {
connection.videoMirrored = YES;
}
[_captureSession addInputWithNoConnections:_captureVideoInput];
[_captureSession addOutputWithNoConnections:_captureVideoOutput];
[_captureSession addConnection:connection];
if (@available(iOS 10.0, *)) {
_capturePhotoOutput = [AVCapturePhotoOutput new];
[_capturePhotoOutput setHighResolutionCaptureEnabled:YES];
[_captureSession addOutput:_capturePhotoOutput];
}
_motionManager = [[CMMotionManager alloc] init];
[_motionManager startAccelerometerUpdates];
[self setCaptureSessionPreset:_resolutionPreset];
[self updateOrientation];
return self;
}
- (void)start {
[_captureSession startRunning];
}
- (void)stop {
[_captureSession stopRunning];
}
- (void)setVideoFormat:(OSType)videoFormat {
_videoFormat = videoFormat;
_captureVideoOutput.videoSettings =
@{(NSString *)kCVPixelBufferPixelFormatTypeKey : @(videoFormat)};
}
- (void)setDeviceOrientation:(UIDeviceOrientation)orientation {
if (_deviceOrientation == orientation) {
return;
}
_deviceOrientation = orientation;
[self updateOrientation];
}
- (void)updateOrientation {
if (_isRecording) {
return;
}
UIDeviceOrientation orientation = (_lockedCaptureOrientation != UIDeviceOrientationUnknown)
? _lockedCaptureOrientation
: _deviceOrientation;
[self updateOrientation:orientation forCaptureOutput:_capturePhotoOutput];
[self updateOrientation:orientation forCaptureOutput:_captureVideoOutput];
}
- (void)updateOrientation:(UIDeviceOrientation)orientation
forCaptureOutput:(AVCaptureOutput *)captureOutput {
if (!captureOutput) {
return;
}
AVCaptureConnection *connection = [captureOutput connectionWithMediaType:AVMediaTypeVideo];
if (connection && connection.isVideoOrientationSupported) {
connection.videoOrientation = [self getVideoOrientationForDeviceOrientation:orientation];
}
}
- (void)captureToFile:(FLTThreadSafeFlutterResult *)result API_AVAILABLE(ios(10)) {
AVCapturePhotoSettings *settings = [AVCapturePhotoSettings photoSettings];
if (_resolutionPreset == FLTResolutionPresetMax) {
[settings setHighResolutionPhotoEnabled:YES];
}
AVCaptureFlashMode avFlashMode = FLTGetAVCaptureFlashModeForFLTFlashMode(_flashMode);
if (avFlashMode != -1) {
[settings setFlashMode:avFlashMode];
}
NSError *error;
NSString *path = [self getTemporaryFilePathWithExtension:@"jpg"
subfolder:@"pictures"
prefix:@"CAP_"
error:error];
if (error) {
[result sendError:error];
return;
}
__weak typeof(self) weakSelf = self;
FLTSavePhotoDelegate *savePhotoDelegate = [[FLTSavePhotoDelegate alloc]
initWithPath:path
ioQueue:self.photoIOQueue
completionHandler:^(NSString *_Nullable path, NSError *_Nullable error) {
typeof(self) strongSelf = weakSelf;
if (!strongSelf) return;
dispatch_async(strongSelf.captureSessionQueue, ^{
// cannot use the outter `strongSelf`
typeof(self) strongSelf = weakSelf;
if (!strongSelf) return;
[strongSelf.inProgressSavePhotoDelegates removeObjectForKey:@(settings.uniqueID)];
});
if (error) {
[result sendError:error];
} else {
NSAssert(path, @"Path must not be nil if no error.");
[result sendSuccessWithData:path];
}
}];
NSAssert(dispatch_get_specific(FLTCaptureSessionQueueSpecific),
@"save photo delegate references must be updated on the capture session queue");
self.inProgressSavePhotoDelegates[@(settings.uniqueID)] = savePhotoDelegate;
[self.capturePhotoOutput capturePhotoWithSettings:settings delegate:savePhotoDelegate];
}
- (AVCaptureVideoOrientation)getVideoOrientationForDeviceOrientation:
(UIDeviceOrientation)deviceOrientation {
if (deviceOrientation == UIDeviceOrientationPortrait) {
return AVCaptureVideoOrientationPortrait;
} else if (deviceOrientation == UIDeviceOrientationLandscapeLeft) {
// Note: device orientation is flipped compared to video orientation. When UIDeviceOrientation
// is landscape left the video orientation should be landscape right.
return AVCaptureVideoOrientationLandscapeRight;
} else if (deviceOrientation == UIDeviceOrientationLandscapeRight) {
// Note: device orientation is flipped compared to video orientation. When UIDeviceOrientation
// is landscape right the video orientation should be landscape left.
return AVCaptureVideoOrientationLandscapeLeft;
} else if (deviceOrientation == UIDeviceOrientationPortraitUpsideDown) {
return AVCaptureVideoOrientationPortraitUpsideDown;
} else {
return AVCaptureVideoOrientationPortrait;
}
}
- (NSString *)getTemporaryFilePathWithExtension:(NSString *)extension
subfolder:(NSString *)subfolder
prefix:(NSString *)prefix
error:(NSError *)error {
NSString *docDir =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *fileDir =
[[docDir stringByAppendingPathComponent:@"camera"] stringByAppendingPathComponent:subfolder];
NSString *fileName = [prefix stringByAppendingString:[[NSUUID UUID] UUIDString]];
NSString *file =
[[fileDir stringByAppendingPathComponent:fileName] stringByAppendingPathExtension:extension];
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:fileDir]) {
[[NSFileManager defaultManager] createDirectoryAtPath:fileDir
withIntermediateDirectories:true
attributes:nil
error:&error];
if (error) {
return nil;
}
}
return file;
}
- (void)setCaptureSessionPreset:(FLTResolutionPreset)resolutionPreset {
switch (resolutionPreset) {
case FLTResolutionPresetMax:
case FLTResolutionPresetUltraHigh:
if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset3840x2160]) {
_captureSession.sessionPreset = AVCaptureSessionPreset3840x2160;
_previewSize = CGSizeMake(3840, 2160);
break;
}
if ([_captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
_captureSession.sessionPreset = AVCaptureSessionPresetHigh;
_previewSize =
CGSizeMake(_captureDevice.activeFormat.highResolutionStillImageDimensions.width,
_captureDevice.activeFormat.highResolutionStillImageDimensions.height);
break;
}
case FLTResolutionPresetVeryHigh:
if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset1920x1080]) {
_captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
_previewSize = CGSizeMake(1920, 1080);
break;
}
case FLTResolutionPresetHigh:
if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
_captureSession.sessionPreset = AVCaptureSessionPreset1280x720;
_previewSize = CGSizeMake(1280, 720);
break;
}
case FLTResolutionPresetMedium:
if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset640x480]) {
_captureSession.sessionPreset = AVCaptureSessionPreset640x480;
_previewSize = CGSizeMake(640, 480);
break;
}
case FLTResolutionPresetLow:
if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset352x288]) {
_captureSession.sessionPreset = AVCaptureSessionPreset352x288;
_previewSize = CGSizeMake(352, 288);
break;
}
default:
if ([_captureSession canSetSessionPreset:AVCaptureSessionPresetLow]) {
_captureSession.sessionPreset = AVCaptureSessionPresetLow;
_previewSize = CGSizeMake(352, 288);
} else {
NSError *error =
[NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorUnknown
userInfo:@{
NSLocalizedDescriptionKey :
@"No capture session available for current capture session."
}];
@throw error;
}
}
}
- (void)captureOutput:(AVCaptureOutput *)output
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection {
if (output == _captureVideoOutput) {
CVPixelBufferRef newBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CFRetain(newBuffer);
__block CVPixelBufferRef previousPixelBuffer = nil;
// Use `dispatch_sync` to avoid unnecessary context switch under common non-contest scenarios;
// Under rare contest scenarios, it will not block for too long since the critical section is
// quite lightweight.
dispatch_sync(self.pixelBufferSynchronizationQueue, ^{
// No need weak self because it's dispatch_sync.
previousPixelBuffer = self.latestPixelBuffer;
self.latestPixelBuffer = newBuffer;
});
if (previousPixelBuffer) {
CFRelease(previousPixelBuffer);
}
if (_onFrameAvailable) {
_onFrameAvailable();
}
}
if (!CMSampleBufferDataIsReady(sampleBuffer)) {
[_methodChannel invokeMethod:errorMethod
arguments:@"sample buffer is not ready. Skipping sample"];
return;
}
if (_isStreamingImages) {
FlutterEventSink eventSink = _imageStreamHandler.eventSink;
if (eventSink && (self.streamingPendingFramesCount < self.maxStreamingPendingFramesCount)) {
self.streamingPendingFramesCount++;
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Must lock base address before accessing the pixel data
CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
size_t imageWidth = CVPixelBufferGetWidth(pixelBuffer);
size_t imageHeight = CVPixelBufferGetHeight(pixelBuffer);
NSMutableArray *planes = [NSMutableArray array];
const Boolean isPlanar = CVPixelBufferIsPlanar(pixelBuffer);
size_t planeCount;
if (isPlanar) {
planeCount = CVPixelBufferGetPlaneCount(pixelBuffer);
} else {
planeCount = 1;
}
for (int i = 0; i < planeCount; i++) {
void *planeAddress;
size_t bytesPerRow;
size_t height;
size_t width;
if (isPlanar) {
planeAddress = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, i);
bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, i);
height = CVPixelBufferGetHeightOfPlane(pixelBuffer, i);
width = CVPixelBufferGetWidthOfPlane(pixelBuffer, i);
} else {
planeAddress = CVPixelBufferGetBaseAddress(pixelBuffer);
bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);
height = CVPixelBufferGetHeight(pixelBuffer);
width = CVPixelBufferGetWidth(pixelBuffer);
}
NSNumber *length = @(bytesPerRow * height);
NSData *bytes = [NSData dataWithBytes:planeAddress length:length.unsignedIntegerValue];
NSMutableDictionary *planeBuffer = [NSMutableDictionary dictionary];
planeBuffer[@"bytesPerRow"] = @(bytesPerRow);
planeBuffer[@"width"] = @(width);
planeBuffer[@"height"] = @(height);
planeBuffer[@"bytes"] = [FlutterStandardTypedData typedDataWithBytes:bytes];
[planes addObject:planeBuffer];
}
// Lock the base address before accessing pixel data, and unlock it afterwards.
// Done accessing the `pixelBuffer` at this point.
CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
NSMutableDictionary *imageBuffer = [NSMutableDictionary dictionary];
imageBuffer[@"width"] = [NSNumber numberWithUnsignedLong:imageWidth];
imageBuffer[@"height"] = [NSNumber numberWithUnsignedLong:imageHeight];
imageBuffer[@"format"] = @(_videoFormat);
imageBuffer[@"planes"] = planes;
imageBuffer[@"lensAperture"] = [NSNumber numberWithFloat:[_captureDevice lensAperture]];
Float64 exposureDuration = CMTimeGetSeconds([_captureDevice exposureDuration]);
Float64 nsExposureDuration = 1000000000 * exposureDuration;
imageBuffer[@"sensorExposureTime"] = [NSNumber numberWithInt:nsExposureDuration];
imageBuffer[@"sensorSensitivity"] = [NSNumber numberWithFloat:[_captureDevice ISO]];
dispatch_async(dispatch_get_main_queue(), ^{
eventSink(imageBuffer);
});
}
}
if (_isRecording && !_isRecordingPaused) {
if (_videoWriter.status == AVAssetWriterStatusFailed) {
[_methodChannel invokeMethod:errorMethod
arguments:[NSString stringWithFormat:@"%@", _videoWriter.error]];
return;
}
CFRetain(sampleBuffer);
CMTime currentSampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
if (_videoWriter.status != AVAssetWriterStatusWriting) {
[_videoWriter startWriting];
[_videoWriter startSessionAtSourceTime:currentSampleTime];
}
if (output == _captureVideoOutput) {
if (_videoIsDisconnected) {
_videoIsDisconnected = NO;
if (_videoTimeOffset.value == 0) {
_videoTimeOffset = CMTimeSubtract(currentSampleTime, _lastVideoSampleTime);
} else {
CMTime offset = CMTimeSubtract(currentSampleTime, _lastVideoSampleTime);
_videoTimeOffset = CMTimeAdd(_videoTimeOffset, offset);
}
return;
}
_lastVideoSampleTime = currentSampleTime;
CVPixelBufferRef nextBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CMTime nextSampleTime = CMTimeSubtract(_lastVideoSampleTime, _videoTimeOffset);
[_videoAdaptor appendPixelBuffer:nextBuffer withPresentationTime:nextSampleTime];
} else {
CMTime dur = CMSampleBufferGetDuration(sampleBuffer);
if (dur.value > 0) {
currentSampleTime = CMTimeAdd(currentSampleTime, dur);
}
if (_audioIsDisconnected) {
_audioIsDisconnected = NO;
if (_audioTimeOffset.value == 0) {
_audioTimeOffset = CMTimeSubtract(currentSampleTime, _lastAudioSampleTime);
} else {
CMTime offset = CMTimeSubtract(currentSampleTime, _lastAudioSampleTime);
_audioTimeOffset = CMTimeAdd(_audioTimeOffset, offset);
}
return;
}
_lastAudioSampleTime = currentSampleTime;
if (_audioTimeOffset.value != 0) {
CFRelease(sampleBuffer);
sampleBuffer = [self adjustTime:sampleBuffer by:_audioTimeOffset];
}
[self newAudioSample:sampleBuffer];
}
CFRelease(sampleBuffer);
}
}
- (CMSampleBufferRef)adjustTime:(CMSampleBufferRef)sample by:(CMTime)offset CF_RETURNS_RETAINED {
CMItemCount count;
CMSampleBufferGetSampleTimingInfoArray(sample, 0, nil, &count);
CMSampleTimingInfo *pInfo = malloc(sizeof(CMSampleTimingInfo) * count);
CMSampleBufferGetSampleTimingInfoArray(sample, count, pInfo, &count);
for (CMItemCount i = 0; i < count; i++) {
pInfo[i].decodeTimeStamp = CMTimeSubtract(pInfo[i].decodeTimeStamp, offset);
pInfo[i].presentationTimeStamp = CMTimeSubtract(pInfo[i].presentationTimeStamp, offset);
}
CMSampleBufferRef sout;
CMSampleBufferCreateCopyWithNewTiming(nil, sample, count, pInfo, &sout);
free(pInfo);
return sout;
}
- (void)newVideoSample:(CMSampleBufferRef)sampleBuffer {
if (_videoWriter.status != AVAssetWriterStatusWriting) {
if (_videoWriter.status == AVAssetWriterStatusFailed) {
[_methodChannel invokeMethod:errorMethod
arguments:[NSString stringWithFormat:@"%@", _videoWriter.error]];
}
return;
}
if (_videoWriterInput.readyForMoreMediaData) {
if (![_videoWriterInput appendSampleBuffer:sampleBuffer]) {
[_methodChannel
invokeMethod:errorMethod
arguments:[NSString stringWithFormat:@"%@", @"Unable to write to video input"]];
}
}
}
- (void)newAudioSample:(CMSampleBufferRef)sampleBuffer {
if (_videoWriter.status != AVAssetWriterStatusWriting) {
if (_videoWriter.status == AVAssetWriterStatusFailed) {
[_methodChannel invokeMethod:errorMethod
arguments:[NSString stringWithFormat:@"%@", _videoWriter.error]];
}
return;
}
if (_audioWriterInput.readyForMoreMediaData) {
if (![_audioWriterInput appendSampleBuffer:sampleBuffer]) {
[_methodChannel
invokeMethod:errorMethod
arguments:[NSString stringWithFormat:@"%@", @"Unable to write to audio input"]];
}
}
}
- (void)close {
[_captureSession stopRunning];
for (AVCaptureInput *input in [_captureSession inputs]) {
[_captureSession removeInput:input];
}
for (AVCaptureOutput *output in [_captureSession outputs]) {
[_captureSession removeOutput:output];
}
}
- (void)dealloc {
if (_latestPixelBuffer) {
CFRelease(_latestPixelBuffer);
}
[_motionManager stopAccelerometerUpdates];
}
- (CVPixelBufferRef)copyPixelBuffer {
__block CVPixelBufferRef pixelBuffer = nil;
// Use `dispatch_sync` because `copyPixelBuffer` API requires synchronous return.
dispatch_sync(self.pixelBufferSynchronizationQueue, ^{
// No need weak self because it's dispatch_sync.
pixelBuffer = self.latestPixelBuffer;
self.latestPixelBuffer = nil;
});
return pixelBuffer;
}
- (void)startVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result {
[self startVideoRecordingWithResult:result messengerForStreaming:nil];
}
- (void)startVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result
messengerForStreaming:(nullable NSObject<FlutterBinaryMessenger> *)messenger {
if (!_isRecording) {
if (messenger != nil) {
[self startImageStreamWithMessenger:messenger];
}
NSError *error;
_videoRecordingPath = [self getTemporaryFilePathWithExtension:@"mp4"
subfolder:@"videos"
prefix:@"REC_"
error:error];
if (error) {
[result sendError:error];
return;
}
if (![self setupWriterForPath:_videoRecordingPath]) {
[result sendErrorWithCode:@"IOError" message:@"Setup Writer Failed" details:nil];
return;
}
_isRecording = YES;
_isRecordingPaused = NO;
_videoTimeOffset = CMTimeMake(0, 1);
_audioTimeOffset = CMTimeMake(0, 1);
_videoIsDisconnected = NO;
_audioIsDisconnected = NO;
[result sendSuccess];
} else {
[result sendErrorWithCode:@"Error" message:@"Video is already recording" details:nil];
}
}
- (void)stopVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result {
if (_isRecording) {
_isRecording = NO;
if (_videoWriter.status != AVAssetWriterStatusUnknown) {
[_videoWriter finishWritingWithCompletionHandler:^{
if (self->_videoWriter.status == AVAssetWriterStatusCompleted) {
[self updateOrientation];
[result sendSuccessWithData:self->_videoRecordingPath];
self->_videoRecordingPath = nil;
} else {
[result sendErrorWithCode:@"IOError"
message:@"AVAssetWriter could not finish writing!"
details:nil];
}
}];
}
} else {
NSError *error =
[NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorResourceUnavailable
userInfo:@{NSLocalizedDescriptionKey : @"Video is not recording!"}];
[result sendError:error];
}
}
- (void)pauseVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result {
_isRecordingPaused = YES;
_videoIsDisconnected = YES;
_audioIsDisconnected = YES;
[result sendSuccess];
}
- (void)resumeVideoRecordingWithResult:(FLTThreadSafeFlutterResult *)result {
_isRecordingPaused = NO;
[result sendSuccess];
}
- (void)lockCaptureOrientationWithResult:(FLTThreadSafeFlutterResult *)result
orientation:(NSString *)orientationStr {
UIDeviceOrientation orientation;
@try {
orientation = FLTGetUIDeviceOrientationForString(orientationStr);
} @catch (NSError *e) {
[result sendError:e];
return;
}
if (_lockedCaptureOrientation != orientation) {
_lockedCaptureOrientation = orientation;
[self updateOrientation];
}
[result sendSuccess];
}
- (void)unlockCaptureOrientationWithResult:(FLTThreadSafeFlutterResult *)result {
_lockedCaptureOrientation = UIDeviceOrientationUnknown;
[self updateOrientation];
[result sendSuccess];
}
- (void)setFlashModeWithResult:(FLTThreadSafeFlutterResult *)result mode:(NSString *)modeStr {
FLTFlashMode mode;
@try {
mode = FLTGetFLTFlashModeForString(modeStr);
} @catch (NSError *e) {
[result sendError:e];
return;
}
if (mode == FLTFlashModeTorch) {
if (!_captureDevice.hasTorch) {
[result sendErrorWithCode:@"setFlashModeFailed"
message:@"Device does not support torch mode"
details:nil];
return;
}
if (!_captureDevice.isTorchAvailable) {
[result sendErrorWithCode:@"setFlashModeFailed"
message:@"Torch mode is currently not available"
details:nil];
return;
}
if (_captureDevice.torchMode != AVCaptureTorchModeOn) {
[_captureDevice lockForConfiguration:nil];
[_captureDevice setTorchMode:AVCaptureTorchModeOn];
[_captureDevice unlockForConfiguration];
}
} else {
if (!_captureDevice.hasFlash) {
[result sendErrorWithCode:@"setFlashModeFailed"
message:@"Device does not have flash capabilities"
details:nil];
return;
}
AVCaptureFlashMode avFlashMode = FLTGetAVCaptureFlashModeForFLTFlashMode(mode);
if (![_capturePhotoOutput.supportedFlashModes
containsObject:[NSNumber numberWithInt:((int)avFlashMode)]]) {
[result sendErrorWithCode:@"setFlashModeFailed"
message:@"Device does not support this specific flash mode"
details:nil];
return;
}
if (_captureDevice.torchMode != AVCaptureTorchModeOff) {
[_captureDevice lockForConfiguration:nil];
[_captureDevice setTorchMode:AVCaptureTorchModeOff];
[_captureDevice unlockForConfiguration];
}
}
_flashMode = mode;
[result sendSuccess];
}
- (void)setExposureModeWithResult:(FLTThreadSafeFlutterResult *)result mode:(NSString *)modeStr {
FLTExposureMode mode;
@try {
mode = FLTGetFLTExposureModeForString(modeStr);
} @catch (NSError *e) {
[result sendError:e];
return;
}
_exposureMode = mode;
[self applyExposureMode];
[result sendSuccess];
}
- (void)applyExposureMode {
[_captureDevice lockForConfiguration:nil];
switch (_exposureMode) {
case FLTExposureModeLocked:
[_captureDevice setExposureMode:AVCaptureExposureModeAutoExpose];
break;
case FLTExposureModeAuto:
if ([_captureDevice isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
[_captureDevice setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
} else {
[_captureDevice setExposureMode:AVCaptureExposureModeAutoExpose];
}
break;
}
[_captureDevice unlockForConfiguration];
}
- (void)setFocusModeWithResult:(FLTThreadSafeFlutterResult *)result mode:(NSString *)modeStr {
FLTFocusMode mode;
@try {
mode = FLTGetFLTFocusModeForString(modeStr);
} @catch (NSError *e) {
[result sendError:e];
return;
}
_focusMode = mode;
[self applyFocusMode];
[result sendSuccess];
}
- (void)applyFocusMode {
[self applyFocusMode:_focusMode onDevice:_captureDevice];
}
- (void)applyFocusMode:(FLTFocusMode)focusMode onDevice:(AVCaptureDevice *)captureDevice {
[captureDevice lockForConfiguration:nil];
switch (focusMode) {
case FLTFocusModeLocked:
if ([captureDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
[captureDevice setFocusMode:AVCaptureFocusModeAutoFocus];
}
break;
case FLTFocusModeAuto:
if ([captureDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
[captureDevice setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
} else if ([captureDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
[captureDevice setFocusMode:AVCaptureFocusModeAutoFocus];
}
break;
}
[captureDevice unlockForConfiguration];
}
- (void)pausePreviewWithResult:(FLTThreadSafeFlutterResult *)result {
_isPreviewPaused = true;
[result sendSuccess];
}
- (void)resumePreviewWithResult:(FLTThreadSafeFlutterResult *)result {
_isPreviewPaused = false;
[result sendSuccess];
}
- (CGPoint)getCGPointForCoordsWithOrientation:(UIDeviceOrientation)orientation
x:(double)x
y:(double)y {
double oldX = x, oldY = y;
switch (orientation) {
case UIDeviceOrientationPortrait: // 90 ccw
y = 1 - oldX;
x = oldY;
break;
case UIDeviceOrientationPortraitUpsideDown: // 90 cw
x = 1 - oldY;
y = oldX;
break;
case UIDeviceOrientationLandscapeRight: // 180
x = 1 - x;
y = 1 - y;
break;
case UIDeviceOrientationLandscapeLeft:
default:
// No rotation required
break;
}
return CGPointMake(x, y);
}
- (void)setExposurePointWithResult:(FLTThreadSafeFlutterResult *)result x:(double)x y:(double)y {
if (!_captureDevice.isExposurePointOfInterestSupported) {
[result sendErrorWithCode:@"setExposurePointFailed"
message:@"Device does not have exposure point capabilities"
details:nil];
return;
}
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
[_captureDevice lockForConfiguration:nil];
[_captureDevice setExposurePointOfInterest:[self getCGPointForCoordsWithOrientation:orientation
x:x
y:y]];
[_captureDevice unlockForConfiguration];
// Retrigger auto exposure
[self applyExposureMode];
[result sendSuccess];
}
- (void)setFocusPointWithResult:(FLTThreadSafeFlutterResult *)result x:(double)x y:(double)y {
if (!_captureDevice.isFocusPointOfInterestSupported) {
[result sendErrorWithCode:@"setFocusPointFailed"
message:@"Device does not have focus point capabilities"
details:nil];
return;
}
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
[_captureDevice lockForConfiguration:nil];
[_captureDevice setFocusPointOfInterest:[self getCGPointForCoordsWithOrientation:orientation
x:x
y:y]];
[_captureDevice unlockForConfiguration];
// Retrigger auto focus
[self applyFocusMode];
[result sendSuccess];
}
- (void)setExposureOffsetWithResult:(FLTThreadSafeFlutterResult *)result offset:(double)offset {
[_captureDevice lockForConfiguration:nil];
[_captureDevice setExposureTargetBias:offset completionHandler:nil];
[_captureDevice unlockForConfiguration];
[result sendSuccessWithData:@(offset)];
}
- (void)startImageStreamWithMessenger:(NSObject<FlutterBinaryMessenger> *)messenger {
[self startImageStreamWithMessenger:messenger
imageStreamHandler:[[FLTImageStreamHandler alloc]
initWithCaptureSessionQueue:_captureSessionQueue]];
}
- (void)startImageStreamWithMessenger:(NSObject<FlutterBinaryMessenger> *)messenger
imageStreamHandler:(FLTImageStreamHandler *)imageStreamHandler {
if (!_isStreamingImages) {
FlutterEventChannel *eventChannel = [FlutterEventChannel
eventChannelWithName:@"plugins.flutter.io/camera_avfoundation/imageStream"
binaryMessenger:messenger];
FLTThreadSafeEventChannel *threadSafeEventChannel =
[[FLTThreadSafeEventChannel alloc] initWithEventChannel:eventChannel];
_imageStreamHandler = imageStreamHandler;
__weak typeof(self) weakSelf = self;
[threadSafeEventChannel setStreamHandler:_imageStreamHandler
completion:^{
typeof(self) strongSelf = weakSelf;
if (!strongSelf) return;
dispatch_async(strongSelf.captureSessionQueue, ^{
// cannot use the outter strongSelf
typeof(self) strongSelf = weakSelf;
if (!strongSelf) return;
strongSelf.isStreamingImages = YES;
strongSelf.streamingPendingFramesCount = 0;
});
}];
} else {
[_methodChannel invokeMethod:errorMethod
arguments:@"Images from camera are already streaming!"];
}
}
- (void)stopImageStream {
if (_isStreamingImages) {
_isStreamingImages = NO;
_imageStreamHandler = nil;
} else {
[_methodChannel invokeMethod:errorMethod arguments:@"Images from camera are not streaming!"];
}
}
- (void)receivedImageStreamData {
self.streamingPendingFramesCount--;
}
- (void)getMaxZoomLevelWithResult:(FLTThreadSafeFlutterResult *)result {
CGFloat maxZoomFactor = [self getMaxAvailableZoomFactor];
[result sendSuccessWithData:[NSNumber numberWithFloat:maxZoomFactor]];
}
- (void)getMinZoomLevelWithResult:(FLTThreadSafeFlutterResult *)result {
CGFloat minZoomFactor = [self getMinAvailableZoomFactor];
[result sendSuccessWithData:[NSNumber numberWithFloat:minZoomFactor]];
}
- (void)setZoomLevel:(CGFloat)zoom Result:(FLTThreadSafeFlutterResult *)result {
CGFloat maxAvailableZoomFactor = [self getMaxAvailableZoomFactor];
CGFloat minAvailableZoomFactor = [self getMinAvailableZoomFactor];
if (maxAvailableZoomFactor < zoom || minAvailableZoomFactor > zoom) {
NSString *errorMessage = [NSString
stringWithFormat:@"Zoom level out of bounds (zoom level should be between %f and %f).",
minAvailableZoomFactor, maxAvailableZoomFactor];
[result sendErrorWithCode:@"ZOOM_ERROR" message:errorMessage details:nil];
return;
}
NSError *error = nil;
if (![_captureDevice lockForConfiguration:&error]) {
[result sendError:error];
return;
}
_captureDevice.videoZoomFactor = zoom;
[_captureDevice unlockForConfiguration];
[result sendSuccess];
}
- (CGFloat)getMinAvailableZoomFactor {
if (@available(iOS 11.0, *)) {
return _captureDevice.minAvailableVideoZoomFactor;
} else {
return 1.0;
}
}
- (CGFloat)getMaxAvailableZoomFactor {
if (@available(iOS 11.0, *)) {
return _captureDevice.maxAvailableVideoZoomFactor;
} else {
return _captureDevice.activeFormat.videoMaxZoomFactor;
}
}
- (BOOL)setupWriterForPath:(NSString *)path {
NSError *error = nil;
NSURL *outputURL;
if (path != nil) {
outputURL = [NSURL fileURLWithPath:path];
} else {
return NO;
}
if (_enableAudio && !_isAudioSetup) {
[self setUpCaptureSessionForAudio];
}
_videoWriter = [[AVAssetWriter alloc] initWithURL:outputURL
fileType:AVFileTypeMPEG4
error:&error];
NSParameterAssert(_videoWriter);
if (error) {
[_methodChannel invokeMethod:errorMethod arguments:error.description];
return NO;
}
NSDictionary *videoSettings = [_captureVideoOutput
recommendedVideoSettingsForAssetWriterWithOutputFileType:AVFileTypeMPEG4];
_videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
outputSettings:videoSettings];
_videoAdaptor = [AVAssetWriterInputPixelBufferAdaptor
assetWriterInputPixelBufferAdaptorWithAssetWriterInput:_videoWriterInput
sourcePixelBufferAttributes:@{
(NSString *)kCVPixelBufferPixelFormatTypeKey : @(_videoFormat)
}];
NSParameterAssert(_videoWriterInput);
_videoWriterInput.expectsMediaDataInRealTime = YES;
// Add the audio input
if (_enableAudio) {
AudioChannelLayout acl;
bzero(&acl, sizeof(acl));
acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
NSDictionary *audioOutputSettings = nil;
// Both type of audio inputs causes output video file to be corrupted.
audioOutputSettings = @{
AVFormatIDKey : [NSNumber numberWithInt:kAudioFormatMPEG4AAC],
AVSampleRateKey : [NSNumber numberWithFloat:44100.0],
AVNumberOfChannelsKey : [NSNumber numberWithInt:1],
AVChannelLayoutKey : [NSData dataWithBytes:&acl length:sizeof(acl)],
};
_audioWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio
outputSettings:audioOutputSettings];
_audioWriterInput.expectsMediaDataInRealTime = YES;
[_videoWriter addInput:_audioWriterInput];
[_audioOutput setSampleBufferDelegate:self queue:_captureSessionQueue];
}
if (_flashMode == FLTFlashModeTorch) {
[self.captureDevice lockForConfiguration:nil];
[self.captureDevice setTorchMode:AVCaptureTorchModeOn];
[self.captureDevice unlockForConfiguration];
}
[_videoWriter addInput:_videoWriterInput];
[_captureVideoOutput setSampleBufferDelegate:self queue:_captureSessionQueue];
return YES;
}
- (void)setUpCaptureSessionForAudio {
NSError *error = nil;
// Create a device input with the device and add it to the session.
// Setup the audio input.
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice
error:&error];
if (error) {
[_methodChannel invokeMethod:errorMethod arguments:error.description];
}
// Setup the audio output.
_audioOutput = [[AVCaptureAudioDataOutput alloc] init];
if ([_captureSession canAddInput:audioInput]) {
[_captureSession addInput:audioInput];
if ([_captureSession canAddOutput:_audioOutput]) {
[_captureSession addOutput:_audioOutput];
_isAudioSetup = YES;
} else {
[_methodChannel invokeMethod:errorMethod
arguments:@"Unable to add Audio input/output to session capture"];
_isAudioSetup = NO;
}
}
}
@end
| plugins/packages/camera/camera_avfoundation/ios/Classes/FLTCam.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTCam.m",
"repo_id": "plugins",
"token_count": 16601
} | 1,245 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'camera_avfoundation'
s.version = '0.0.1'
s.summary = 'Flutter Camera'
s.description = <<-DESC
A Flutter plugin to use the camera from your Flutter app.
DESC
s.homepage = 'https://github.com/flutter/plugins'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' }
s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/camera_avfoundation' }
s.documentation_url = 'https://pub.dev/packages/camera_avfoundation'
s.source_files = 'Classes/**/*.{h,m}'
s.public_header_files = 'Classes/**/*.h'
s.module_map = 'Classes/CameraPlugin.modulemap'
s.dependency 'Flutter'
s.platform = :ios, '9.0'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
end
| plugins/packages/camera/camera_avfoundation/ios/camera_avfoundation.podspec/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/camera_avfoundation.podspec",
"repo_id": "plugins",
"token_count": 437
} | 1,246 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show immutable;
import 'package:flutter/services.dart';
import '../utils/utils.dart';
/// Generic Event coming from the native side of Camera,
/// not related to a specific camera module.
///
/// This class is used as a base class for all the events that might be
/// triggered from a device, but it is never used directly as an event type.
///
/// Do NOT instantiate new events like `DeviceEvent()` directly,
/// use a specific class instead:
///
/// Do `class NewEvent extend DeviceEvent` when creating your own events.
/// See below for examples: `DeviceOrientationChangedEvent`...
/// These events are more semantic and more pleasant to use than raw generics.
/// They can be (and in fact, are) filtered by the `instanceof`-operator.
@immutable
abstract class DeviceEvent {
/// Creates a new device event.
const DeviceEvent();
}
/// The [DeviceOrientationChangedEvent] is fired every time the orientation of the device UI changes.
class DeviceOrientationChangedEvent extends DeviceEvent {
/// Build a new orientation changed event.
const DeviceOrientationChangedEvent(this.orientation);
/// Converts the supplied [Map] to an instance of the [DeviceOrientationChangedEvent]
/// class.
DeviceOrientationChangedEvent.fromJson(Map<String, dynamic> json)
: orientation =
deserializeDeviceOrientation(json['orientation']! as String);
/// The new orientation of the device
final DeviceOrientation orientation;
/// Converts the [DeviceOrientationChangedEvent] instance into a [Map] instance that
/// can be serialized to JSON.
Map<String, dynamic> toJson() => <String, Object>{
'orientation': serializeDeviceOrientation(orientation),
};
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is DeviceOrientationChangedEvent &&
runtimeType == other.runtimeType &&
orientation == other.orientation;
@override
int get hashCode => orientation.hashCode;
}
| plugins/packages/camera/camera_platform_interface/lib/src/events/device_event.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/lib/src/events/device_event.dart",
"repo_id": "plugins",
"token_count": 615
} | 1,247 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_platform_interface/src/method_channel/method_channel_camera.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$CameraPlatform', () {
test('$MethodChannelCamera is the default instance', () {
expect(CameraPlatform.instance, isA<MethodChannelCamera>());
});
test('Cannot be implemented with `implements`', () {
expect(() {
CameraPlatform.instance = ImplementsCameraPlatform();
// 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', () {
CameraPlatform.instance = ExtendsCameraPlatform();
});
test(
'Default implementation of availableCameras() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.availableCameras(),
throwsUnimplementedError,
);
});
test(
'Default implementation of onCameraInitialized() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onCameraInitialized(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of onResolutionChanged() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onCameraResolutionChanged(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of onCameraClosing() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onCameraClosing(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of onCameraError() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onCameraError(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of onDeviceOrientationChanged() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.onDeviceOrientationChanged(),
throwsUnimplementedError,
);
});
test(
'Default implementation of lockCaptureOrientation() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.lockCaptureOrientation(
1, DeviceOrientation.portraitUp),
throwsUnimplementedError,
);
});
test(
'Default implementation of unlockCaptureOrientation() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.unlockCaptureOrientation(1),
throwsUnimplementedError,
);
});
test('Default implementation of dispose() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.dispose(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of createCamera() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.createCamera(
const CameraDescription(
name: 'back',
lensDirection: CameraLensDirection.back,
sensorOrientation: 0,
),
ResolutionPreset.high,
),
throwsUnimplementedError,
);
});
test(
'Default implementation of initializeCamera() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.initializeCamera(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of pauseVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.pauseVideoRecording(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of prepareForVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.prepareForVideoRecording(),
throwsUnimplementedError,
);
});
test(
'Default implementation of resumeVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.resumeVideoRecording(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of setFlashMode() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setFlashMode(1, FlashMode.auto),
throwsUnimplementedError,
);
});
test(
'Default implementation of setExposureMode() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setExposureMode(1, ExposureMode.auto),
throwsUnimplementedError,
);
});
test(
'Default implementation of setExposurePoint() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setExposurePoint(1, null),
throwsUnimplementedError,
);
});
test(
'Default implementation of getMinExposureOffset() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getMinExposureOffset(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of getMaxExposureOffset() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getMaxExposureOffset(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of getExposureOffsetStepSize() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getExposureOffsetStepSize(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of setExposureOffset() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setExposureOffset(1, 2.0),
throwsUnimplementedError,
);
});
test(
'Default implementation of setFocusMode() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setFocusMode(1, FocusMode.auto),
throwsUnimplementedError,
);
});
test(
'Default implementation of setFocusPoint() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setFocusPoint(1, null),
throwsUnimplementedError,
);
});
test(
'Default implementation of startVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.startVideoRecording(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of stopVideoRecording() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.stopVideoRecording(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of takePicture() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.takePicture(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of getMaxZoomLevel() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getMaxZoomLevel(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of getMinZoomLevel() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.getMinZoomLevel(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of setZoomLevel() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.setZoomLevel(1, 1.0),
throwsUnimplementedError,
);
});
test(
'Default implementation of pausePreview() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.pausePreview(1),
throwsUnimplementedError,
);
});
test(
'Default implementation of resumePreview() should throw unimplemented error',
() {
// Arrange
final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform();
// Act & Assert
expect(
() => cameraPlatform.resumePreview(1),
throwsUnimplementedError,
);
});
});
group('exports', () {
test('CameraDescription is exported', () {
const CameraDescription(
name: 'abc-123',
sensorOrientation: 1,
lensDirection: CameraLensDirection.external);
});
test('CameraException is exported', () {
CameraException('1', 'error');
});
test('CameraImageData is exported', () {
const CameraImageData(
width: 1,
height: 1,
format: CameraImageFormat(ImageFormatGroup.bgra8888, raw: 1),
planes: <CameraImagePlane>[],
);
});
test('ExposureMode is exported', () {
// ignore: unnecessary_statements
ExposureMode.auto;
});
test('FlashMode is exported', () {
// ignore: unnecessary_statements
FlashMode.auto;
});
test('FocusMode is exported', () {
// ignore: unnecessary_statements
FocusMode.auto;
});
test('ResolutionPreset is exported', () {
// ignore: unnecessary_statements
ResolutionPreset.high;
});
test('VideoCaptureOptions is exported', () {
const VideoCaptureOptions(123);
});
});
}
class ImplementsCameraPlatform implements CameraPlatform {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class ExtendsCameraPlatform extends CameraPlatform {}
| plugins/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart",
"repo_id": "plugins",
"token_count": 5242
} | 1,248 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 0.3.1+1
* Updates code for stricter lint checks.
## 0.3.1
* Updates to latest camera platform interface, and fails if user attempts to use streaming with recording (since streaming is currently unsupported on web).
## 0.3.0+1
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316).
## 0.3.0
* **BREAKING CHANGE**: Renames error code `cameraPermission` to `CameraAccessDenied` to be consistent with other platforms.
## 0.2.1+6
* Minor fixes for new analysis options.
## 0.2.1+5
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.2.1+4
* Migrates from `ui.hash*` to `Object.hash*`.
* Updates minimum Flutter version for changes in 0.2.1+3.
## 0.2.1+3
* Internal code cleanup for stricter analysis options.
## 0.2.1+2
* Fixes cameraNotReadable error that prevented access to the camera on some Android devices when initializing a camera.
* Implemented support for new Dart SDKs with an async requestFullscreen API.
## 0.2.1+1
* Update usage documentation.
## 0.2.1
* Add video recording functionality.
* Fix cameraNotReadable error that prevented access to the camera on some Android devices.
## 0.2.0
* Initial release, adapted from the Flutter [I/O Photobooth](https://photobooth.flutter.dev/) project.
| plugins/packages/camera/camera_web/CHANGELOG.md/0 | {
"file_path": "plugins/packages/camera/camera_web/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 492
} | 1,249 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
/// A screen orientation type.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/type
abstract class OrientationType {
/// The primary portrait mode orientation.
/// Corresponds to [DeviceOrientation.portraitUp].
static const String portraitPrimary = 'portrait-primary';
/// The secondary portrait mode orientation.
/// Corresponds to [DeviceOrientation.portraitSecondary].
static const String portraitSecondary = 'portrait-secondary';
/// The primary landscape mode orientation.
/// Corresponds to [DeviceOrientation.landscapeLeft].
static const String landscapePrimary = 'landscape-primary';
/// The secondary landscape mode orientation.
/// Corresponds to [DeviceOrientation.landscapeRight].
static const String landscapeSecondary = 'landscape-secondary';
}
| plugins/packages/camera/camera_web/lib/src/types/orientation_type.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/lib/src/types/orientation_type.dart",
"repo_id": "plugins",
"token_count": 264
} | 1,250 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
/// Example app for Camera Windows plugin.
class MyApp extends StatefulWidget {
/// Default Constructor
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _cameraInfo = 'Unknown';
List<CameraDescription> _cameras = <CameraDescription>[];
int _cameraIndex = 0;
int _cameraId = -1;
bool _initialized = false;
bool _recording = false;
bool _recordingTimed = false;
bool _recordAudio = true;
bool _previewPaused = false;
Size? _previewSize;
ResolutionPreset _resolutionPreset = ResolutionPreset.veryHigh;
StreamSubscription<CameraErrorEvent>? _errorStreamSubscription;
StreamSubscription<CameraClosingEvent>? _cameraClosingStreamSubscription;
@override
void initState() {
super.initState();
WidgetsFlutterBinding.ensureInitialized();
_fetchCameras();
}
@override
void dispose() {
_disposeCurrentCamera();
_errorStreamSubscription?.cancel();
_errorStreamSubscription = null;
_cameraClosingStreamSubscription?.cancel();
_cameraClosingStreamSubscription = null;
super.dispose();
}
/// Fetches list of available cameras from camera_windows plugin.
Future<void> _fetchCameras() async {
String cameraInfo;
List<CameraDescription> cameras = <CameraDescription>[];
int cameraIndex = 0;
try {
cameras = await CameraPlatform.instance.availableCameras();
if (cameras.isEmpty) {
cameraInfo = 'No available cameras';
} else {
cameraIndex = _cameraIndex % cameras.length;
cameraInfo = 'Found camera: ${cameras[cameraIndex].name}';
}
} on PlatformException catch (e) {
cameraInfo = 'Failed to get cameras: ${e.code}: ${e.message}';
}
if (mounted) {
setState(() {
_cameraIndex = cameraIndex;
_cameras = cameras;
_cameraInfo = cameraInfo;
});
}
}
/// Initializes the camera on the device.
Future<void> _initializeCamera() async {
assert(!_initialized);
if (_cameras.isEmpty) {
return;
}
int cameraId = -1;
try {
final int cameraIndex = _cameraIndex % _cameras.length;
final CameraDescription camera = _cameras[cameraIndex];
cameraId = await CameraPlatform.instance.createCamera(
camera,
_resolutionPreset,
enableAudio: _recordAudio,
);
_errorStreamSubscription?.cancel();
_errorStreamSubscription = CameraPlatform.instance
.onCameraError(cameraId)
.listen(_onCameraError);
_cameraClosingStreamSubscription?.cancel();
_cameraClosingStreamSubscription = CameraPlatform.instance
.onCameraClosing(cameraId)
.listen(_onCameraClosing);
final Future<CameraInitializedEvent> initialized =
CameraPlatform.instance.onCameraInitialized(cameraId).first;
await CameraPlatform.instance.initializeCamera(
cameraId,
);
final CameraInitializedEvent event = await initialized;
_previewSize = Size(
event.previewWidth,
event.previewHeight,
);
if (mounted) {
setState(() {
_initialized = true;
_cameraId = cameraId;
_cameraIndex = cameraIndex;
_cameraInfo = 'Capturing camera: ${camera.name}';
});
}
} on CameraException catch (e) {
try {
if (cameraId >= 0) {
await CameraPlatform.instance.dispose(cameraId);
}
} on CameraException catch (e) {
debugPrint('Failed to dispose camera: ${e.code}: ${e.description}');
}
// Reset state.
if (mounted) {
setState(() {
_initialized = false;
_cameraId = -1;
_cameraIndex = 0;
_previewSize = null;
_recording = false;
_recordingTimed = false;
_cameraInfo =
'Failed to initialize camera: ${e.code}: ${e.description}';
});
}
}
}
Future<void> _disposeCurrentCamera() async {
if (_cameraId >= 0 && _initialized) {
try {
await CameraPlatform.instance.dispose(_cameraId);
if (mounted) {
setState(() {
_initialized = false;
_cameraId = -1;
_previewSize = null;
_recording = false;
_recordingTimed = false;
_previewPaused = false;
_cameraInfo = 'Camera disposed';
});
}
} on CameraException catch (e) {
if (mounted) {
setState(() {
_cameraInfo =
'Failed to dispose camera: ${e.code}: ${e.description}';
});
}
}
}
}
Widget _buildPreview() {
return CameraPlatform.instance.buildPreview(_cameraId);
}
Future<void> _takePicture() async {
final XFile file = await CameraPlatform.instance.takePicture(_cameraId);
_showInSnackBar('Picture captured to: ${file.path}');
}
Future<void> _recordTimed(int seconds) async {
if (_initialized && _cameraId > 0 && !_recordingTimed) {
CameraPlatform.instance
.onVideoRecordedEvent(_cameraId)
.first
.then((VideoRecordedEvent event) async {
if (mounted) {
setState(() {
_recordingTimed = false;
});
_showInSnackBar('Video captured to: ${event.file.path}');
}
});
await CameraPlatform.instance.startVideoRecording(
_cameraId,
maxVideoDuration: Duration(seconds: seconds),
);
if (mounted) {
setState(() {
_recordingTimed = true;
});
}
}
}
Future<void> _toggleRecord() async {
if (_initialized && _cameraId > 0) {
if (_recordingTimed) {
/// Request to stop timed recording short.
await CameraPlatform.instance.stopVideoRecording(_cameraId);
} else {
if (!_recording) {
await CameraPlatform.instance.startVideoRecording(_cameraId);
} else {
final XFile file =
await CameraPlatform.instance.stopVideoRecording(_cameraId);
_showInSnackBar('Video captured to: ${file.path}');
}
if (mounted) {
setState(() {
_recording = !_recording;
});
}
}
}
}
Future<void> _togglePreview() async {
if (_initialized && _cameraId >= 0) {
if (!_previewPaused) {
await CameraPlatform.instance.pausePreview(_cameraId);
} else {
await CameraPlatform.instance.resumePreview(_cameraId);
}
if (mounted) {
setState(() {
_previewPaused = !_previewPaused;
});
}
}
}
Future<void> _switchCamera() async {
if (_cameras.isNotEmpty) {
// select next index;
_cameraIndex = (_cameraIndex + 1) % _cameras.length;
if (_initialized && _cameraId >= 0) {
await _disposeCurrentCamera();
await _fetchCameras();
if (_cameras.isNotEmpty) {
await _initializeCamera();
}
} else {
await _fetchCameras();
}
}
}
Future<void> _onResolutionChange(ResolutionPreset newValue) async {
setState(() {
_resolutionPreset = newValue;
});
if (_initialized && _cameraId >= 0) {
// Re-inits camera with new resolution preset.
await _disposeCurrentCamera();
await _initializeCamera();
}
}
Future<void> _onAudioChange(bool recordAudio) async {
setState(() {
_recordAudio = recordAudio;
});
if (_initialized && _cameraId >= 0) {
// Re-inits camera with new record audio setting.
await _disposeCurrentCamera();
await _initializeCamera();
}
}
void _onCameraError(CameraErrorEvent event) {
if (mounted) {
_scaffoldMessengerKey.currentState?.showSnackBar(
SnackBar(content: Text('Error: ${event.description}')));
// Dispose camera on camera error as it can not be used anymore.
_disposeCurrentCamera();
_fetchCameras();
}
}
void _onCameraClosing(CameraClosingEvent event) {
if (mounted) {
_showInSnackBar('Camera is closing');
}
}
void _showInSnackBar(String message) {
_scaffoldMessengerKey.currentState?.showSnackBar(SnackBar(
content: Text(message),
duration: const Duration(seconds: 1),
));
}
final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
@override
Widget build(BuildContext context) {
final List<DropdownMenuItem<ResolutionPreset>> resolutionItems =
ResolutionPreset.values
.map<DropdownMenuItem<ResolutionPreset>>((ResolutionPreset value) {
return DropdownMenuItem<ResolutionPreset>(
value: value,
child: Text(value.toString()),
);
}).toList();
return MaterialApp(
scaffoldMessengerKey: _scaffoldMessengerKey,
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(
vertical: 5,
horizontal: 10,
),
child: Text(_cameraInfo),
),
if (_cameras.isEmpty)
ElevatedButton(
onPressed: _fetchCameras,
child: const Text('Re-check available cameras'),
),
if (_cameras.isNotEmpty)
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<ResolutionPreset>(
value: _resolutionPreset,
onChanged: (ResolutionPreset? value) {
if (value != null) {
_onResolutionChange(value);
}
},
items: resolutionItems,
),
const SizedBox(width: 20),
const Text('Audio:'),
Switch(
value: _recordAudio,
onChanged: (bool state) => _onAudioChange(state)),
const SizedBox(width: 20),
ElevatedButton(
onPressed: _initialized
? _disposeCurrentCamera
: _initializeCamera,
child:
Text(_initialized ? 'Dispose camera' : 'Create camera'),
),
const SizedBox(width: 5),
ElevatedButton(
onPressed: _initialized ? _takePicture : null,
child: const Text('Take picture'),
),
const SizedBox(width: 5),
ElevatedButton(
onPressed: _initialized ? _togglePreview : null,
child: Text(
_previewPaused ? 'Resume preview' : 'Pause preview',
),
),
const SizedBox(width: 5),
ElevatedButton(
onPressed: _initialized ? _toggleRecord : null,
child: Text(
(_recording || _recordingTimed)
? 'Stop recording'
: 'Record Video',
),
),
const SizedBox(width: 5),
ElevatedButton(
onPressed: (_initialized && !_recording && !_recordingTimed)
? () => _recordTimed(5)
: null,
child: const Text(
'Record 5 seconds',
),
),
if (_cameras.length > 1) ...<Widget>[
const SizedBox(width: 5),
ElevatedButton(
onPressed: _switchCamera,
child: const Text(
'Switch camera',
),
),
]
],
),
const SizedBox(height: 5),
if (_initialized && _cameraId > 0 && _previewSize != null)
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10,
),
child: Align(
child: Container(
constraints: const BoxConstraints(
maxHeight: 500,
),
child: AspectRatio(
aspectRatio: _previewSize!.width / _previewSize!.height,
child: _buildPreview(),
),
),
),
),
if (_previewSize != null)
Center(
child: Text(
'Preview size: ${_previewSize!.width.toStringAsFixed(0)}x${_previewSize!.height.toStringAsFixed(0)}',
),
),
],
),
),
);
}
}
| plugins/packages/camera/camera_windows/example/lib/main.dart/0 | {
"file_path": "plugins/packages/camera/camera_windows/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 6470
} | 1,251 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_LISTENER_H_
#define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_LISTENER_H_
#include <functional>
namespace camera_windows {
// Results that can occur when interacting with the camera.
enum class CameraResult {
// Camera operation succeeded.
kSuccess,
// Camera operation failed.
kError,
// Camera access permission is denied.
kAccessDenied,
};
// Interface for classes that receives callbacks on events from the associated
// |CaptureController|.
class CaptureControllerListener {
public:
virtual ~CaptureControllerListener() = default;
// Called by CaptureController on successful capture engine initialization.
//
// texture_id: A 64bit integer id registered by TextureRegistrar
virtual void OnCreateCaptureEngineSucceeded(int64_t texture_id) = 0;
// Called by CaptureController if initializing the capture engine fails.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnCreateCaptureEngineFailed(CameraResult result,
const std::string& error) = 0;
// Called by CaptureController on successfully started preview.
//
// width: Preview frame width.
// height: Preview frame height.
virtual void OnStartPreviewSucceeded(int32_t width, int32_t height) = 0;
// Called by CaptureController if starting the preview fails.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnStartPreviewFailed(CameraResult result,
const std::string& error) = 0;
// Called by CaptureController on successfully paused preview.
virtual void OnPausePreviewSucceeded() = 0;
// Called by CaptureController if pausing the preview fails.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnPausePreviewFailed(CameraResult result,
const std::string& error) = 0;
// Called by CaptureController on successfully resumed preview.
virtual void OnResumePreviewSucceeded() = 0;
// Called by CaptureController if resuming the preview fails.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnResumePreviewFailed(CameraResult result,
const std::string& error) = 0;
// Called by CaptureController on successfully started recording.
virtual void OnStartRecordSucceeded() = 0;
// Called by CaptureController if starting the recording fails.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnStartRecordFailed(CameraResult result,
const std::string& error) = 0;
// Called by CaptureController on successfully stopped recording.
//
// file_path: Filesystem path of the recorded video file.
virtual void OnStopRecordSucceeded(const std::string& file_path) = 0;
// Called by CaptureController if stopping the recording fails.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnStopRecordFailed(CameraResult result,
const std::string& error) = 0;
// Called by CaptureController on successfully captured picture.
//
// file_path: Filesystem path of the captured image.
virtual void OnTakePictureSucceeded(const std::string& file_path) = 0;
// Called by CaptureController if taking picture fails.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnTakePictureFailed(CameraResult result,
const std::string& error) = 0;
// Called by CaptureController when timed recording is successfully recorded.
//
// file_path: Filesystem path of the captured image.
// video_duration: Duration of recorded video in milliseconds.
virtual void OnVideoRecordSucceeded(const std::string& file_path,
int64_t video_duration_ms) = 0;
// Called by CaptureController if timed recording fails.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnVideoRecordFailed(CameraResult result,
const std::string& error) = 0;
// Called by CaptureController if capture engine returns error.
// For example when camera is disconnected while on use.
//
// result: The kind of result.
// error: A string describing the error.
virtual void OnCaptureError(CameraResult result,
const std::string& error) = 0;
};
} // namespace camera_windows
#endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_CAPTURE_CONTROLLER_LISTENER_H_
| plugins/packages/camera/camera_windows/windows/capture_controller_listener.h/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/capture_controller_listener.h",
"repo_id": "plugins",
"token_count": 1590
} | 1,252 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "camera.h"
#include <flutter/method_call.h>
#include <flutter/method_result_functions.h>
#include <flutter/standard_method_codec.h>
#include <flutter/texture_registrar.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <windows.h>
#include <functional>
#include <memory>
#include <string>
#include "mocks.h"
namespace camera_windows {
using ::testing::_;
using ::testing::Eq;
using ::testing::NiceMock;
using ::testing::Pointee;
using ::testing::Return;
namespace test {
TEST(Camera, InitCameraCreatesCaptureController) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockCaptureControllerFactory> capture_controller_factory =
std::make_unique<MockCaptureControllerFactory>();
EXPECT_CALL(*capture_controller_factory, CreateCaptureController)
.Times(1)
.WillOnce([]() {
std::unique_ptr<NiceMock<MockCaptureController>> capture_controller =
std::make_unique<NiceMock<MockCaptureController>>();
EXPECT_CALL(*capture_controller, InitCaptureDevice)
.Times(1)
.WillOnce(Return(true));
return capture_controller;
});
EXPECT_TRUE(camera->GetCaptureController() == nullptr);
// Init camera with mock capture controller factory
bool result =
camera->InitCamera(std::move(capture_controller_factory),
std::make_unique<MockTextureRegistrar>().get(),
std::make_unique<MockBinaryMessenger>().get(), false,
ResolutionPreset::kAuto);
EXPECT_TRUE(result);
EXPECT_TRUE(camera->GetCaptureController() != nullptr);
}
TEST(Camera, InitCameraReportsFailure) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockCaptureControllerFactory> capture_controller_factory =
std::make_unique<MockCaptureControllerFactory>();
EXPECT_CALL(*capture_controller_factory, CreateCaptureController)
.Times(1)
.WillOnce([]() {
std::unique_ptr<NiceMock<MockCaptureController>> capture_controller =
std::make_unique<NiceMock<MockCaptureController>>();
EXPECT_CALL(*capture_controller, InitCaptureDevice)
.Times(1)
.WillOnce(Return(false));
return capture_controller;
});
EXPECT_TRUE(camera->GetCaptureController() == nullptr);
// Init camera with mock capture controller factory
bool result =
camera->InitCamera(std::move(capture_controller_factory),
std::make_unique<MockTextureRegistrar>().get(),
std::make_unique<MockBinaryMessenger>().get(), false,
ResolutionPreset::kAuto);
EXPECT_FALSE(result);
EXPECT_TRUE(camera->GetCaptureController() != nullptr);
}
TEST(Camera, AddPendingResultReturnsErrorForDuplicates) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> first_pending_result =
std::make_unique<MockMethodResult>();
std::unique_ptr<MockMethodResult> second_pending_result =
std::make_unique<MockMethodResult>();
EXPECT_CALL(*first_pending_result, ErrorInternal).Times(0);
EXPECT_CALL(*first_pending_result, SuccessInternal);
EXPECT_CALL(*second_pending_result, ErrorInternal).Times(1);
camera->AddPendingResult(PendingResultType::kCreateCamera,
std::move(first_pending_result));
// This should fail
camera->AddPendingResult(PendingResultType::kCreateCamera,
std::move(second_pending_result));
// Mark pending result as succeeded
camera->OnCreateCaptureEngineSucceeded(0);
}
TEST(Camera, OnCreateCaptureEngineSucceededReturnsCameraId) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const int64_t texture_id = 12345;
EXPECT_CALL(*result, ErrorInternal).Times(0);
EXPECT_CALL(
*result,
SuccessInternal(Pointee(EncodableValue(EncodableMap(
{{EncodableValue("cameraId"), EncodableValue(texture_id)}})))));
camera->AddPendingResult(PendingResultType::kCreateCamera, std::move(result));
camera->OnCreateCaptureEngineSucceeded(texture_id);
}
TEST(Camera, CreateCaptureEngineReportsError) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kCreateCamera, std::move(result));
camera->OnCreateCaptureEngineFailed(CameraResult::kError, error_text);
}
TEST(Camera, CreateCaptureEngineReportsAccessDenied) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result,
ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kCreateCamera, std::move(result));
camera->OnCreateCaptureEngineFailed(CameraResult::kAccessDenied, error_text);
}
TEST(Camera, OnStartPreviewSucceededReturnsFrameSize) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const int32_t width = 123;
const int32_t height = 456;
EXPECT_CALL(*result, ErrorInternal).Times(0);
EXPECT_CALL(
*result,
SuccessInternal(Pointee(EncodableValue(EncodableMap({
{EncodableValue("previewWidth"), EncodableValue((float)width)},
{EncodableValue("previewHeight"), EncodableValue((float)height)},
})))));
camera->AddPendingResult(PendingResultType::kInitialize, std::move(result));
camera->OnStartPreviewSucceeded(width, height);
}
TEST(Camera, StartPreviewReportsError) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kInitialize, std::move(result));
camera->OnStartPreviewFailed(CameraResult::kError, error_text);
}
TEST(Camera, StartPreviewReportsAccessDenied) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result,
ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kInitialize, std::move(result));
camera->OnStartPreviewFailed(CameraResult::kAccessDenied, error_text);
}
TEST(Camera, OnPausePreviewSucceededReturnsSuccess) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
EXPECT_CALL(*result, ErrorInternal).Times(0);
EXPECT_CALL(*result, SuccessInternal(nullptr));
camera->AddPendingResult(PendingResultType::kPausePreview, std::move(result));
camera->OnPausePreviewSucceeded();
}
TEST(Camera, PausePreviewReportsError) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kPausePreview, std::move(result));
camera->OnPausePreviewFailed(CameraResult::kError, error_text);
}
TEST(Camera, PausePreviewReportsAccessDenied) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result,
ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kPausePreview, std::move(result));
camera->OnPausePreviewFailed(CameraResult::kAccessDenied, error_text);
}
TEST(Camera, OnResumePreviewSucceededReturnsSuccess) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
EXPECT_CALL(*result, ErrorInternal).Times(0);
EXPECT_CALL(*result, SuccessInternal(nullptr));
camera->AddPendingResult(PendingResultType::kResumePreview,
std::move(result));
camera->OnResumePreviewSucceeded();
}
TEST(Camera, ResumePreviewReportsError) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kResumePreview,
std::move(result));
camera->OnResumePreviewFailed(CameraResult::kError, error_text);
}
TEST(Camera, OnResumePreviewPermissionFailureReturnsError) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result,
ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kResumePreview,
std::move(result));
camera->OnResumePreviewFailed(CameraResult::kAccessDenied, error_text);
}
TEST(Camera, OnStartRecordSucceededReturnsSuccess) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
EXPECT_CALL(*result, ErrorInternal).Times(0);
EXPECT_CALL(*result, SuccessInternal(nullptr));
camera->AddPendingResult(PendingResultType::kStartRecord, std::move(result));
camera->OnStartRecordSucceeded();
}
TEST(Camera, StartRecordReportsError) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kStartRecord, std::move(result));
camera->OnStartRecordFailed(CameraResult::kError, error_text);
}
TEST(Camera, StartRecordReportsAccessDenied) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result,
ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kStartRecord, std::move(result));
camera->OnStartRecordFailed(CameraResult::kAccessDenied, error_text);
}
TEST(Camera, OnStopRecordSucceededReturnsSuccess) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string file_path = "C:\temp\filename.mp4";
EXPECT_CALL(*result, ErrorInternal).Times(0);
EXPECT_CALL(*result, SuccessInternal(Pointee(EncodableValue(file_path))));
camera->AddPendingResult(PendingResultType::kStopRecord, std::move(result));
camera->OnStopRecordSucceeded(file_path);
}
TEST(Camera, StopRecordReportsError) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kStopRecord, std::move(result));
camera->OnStopRecordFailed(CameraResult::kError, error_text);
}
TEST(Camera, StopRecordReportsAccessDenied) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result,
ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kStopRecord, std::move(result));
camera->OnStopRecordFailed(CameraResult::kAccessDenied, error_text);
}
TEST(Camera, OnTakePictureSucceededReturnsSuccess) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string file_path = "C:\\temp\\filename.jpeg";
EXPECT_CALL(*result, ErrorInternal).Times(0);
EXPECT_CALL(*result, SuccessInternal(Pointee(EncodableValue(file_path))));
camera->AddPendingResult(PendingResultType::kTakePicture, std::move(result));
camera->OnTakePictureSucceeded(file_path);
}
TEST(Camera, TakePictureReportsError) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kTakePicture, std::move(result));
camera->OnTakePictureFailed(CameraResult::kError, error_text);
}
TEST(Camera, TakePictureReportsAccessDenied) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockMethodResult> result =
std::make_unique<MockMethodResult>();
const std::string error_text = "error_text";
EXPECT_CALL(*result, SuccessInternal).Times(0);
EXPECT_CALL(*result,
ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));
camera->AddPendingResult(PendingResultType::kTakePicture, std::move(result));
camera->OnTakePictureFailed(CameraResult::kAccessDenied, error_text);
}
TEST(Camera, OnVideoRecordSucceededInvokesCameraChannelEvent) {
std::unique_ptr<CameraImpl> camera =
std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
std::unique_ptr<MockCaptureControllerFactory> capture_controller_factory =
std::make_unique<MockCaptureControllerFactory>();
std::unique_ptr<MockBinaryMessenger> binary_messenger =
std::make_unique<MockBinaryMessenger>();
const std::string file_path = "C:\\temp\\filename.mp4";
const int64_t camera_id = 12345;
std::string camera_channel =
std::string("plugins.flutter.io/camera_windows/camera") +
std::to_string(camera_id);
const int64_t video_duration = 1000000;
EXPECT_CALL(*capture_controller_factory, CreateCaptureController)
.Times(1)
.WillOnce(
[]() { return std::make_unique<NiceMock<MockCaptureController>>(); });
// TODO: test binary content.
// First time is video record success message,
// and second is camera closing message.
EXPECT_CALL(*binary_messenger, Send(Eq(camera_channel), _, _, _)).Times(2);
// Init camera with mock capture controller factory
camera->InitCamera(std::move(capture_controller_factory),
std::make_unique<MockTextureRegistrar>().get(),
binary_messenger.get(), false, ResolutionPreset::kAuto);
// Pass camera id for camera
camera->OnCreateCaptureEngineSucceeded(camera_id);
camera->OnVideoRecordSucceeded(file_path, video_duration);
// Dispose camera before message channel.
camera = nullptr;
}
} // namespace test
} // namespace camera_windows
| plugins/packages/camera/camera_windows/windows/test/camera_test.cpp/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/test/camera_test.cpp",
"repo_id": "plugins",
"token_count": 6302
} | 1,253 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.espresso">
</manifest>
| plugins/packages/espresso/android/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/espresso/android/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 42
} | 1,254 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.api;
import android.view.View;
import androidx.test.espresso.flutter.model.WidgetInfo;
import com.google.common.annotations.Beta;
/**
* Similar to a {@code ViewAssertion}, a {@link WidgetAssertion} is responsible for performing an
* assertion on a Flutter widget.
*/
@Beta
public interface WidgetAssertion {
/**
* Checks the state of the Flutter widget.
*
* @param flutterView the Flutter view that this widget lives in.
* @param widgetInfo the instance that represents a Flutter widget.
*/
void check(View flutterView, WidgetInfo widgetInfo);
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/WidgetAssertion.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/WidgetAssertion.java",
"repo_id": "plugins",
"token_count": 229
} | 1,255 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.internal.protocol.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.Futures.transform;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import android.graphics.Rect;
import android.util.Log;
import androidx.test.espresso.flutter.api.FlutterTestingProtocol;
import androidx.test.espresso.flutter.api.SyntheticAction;
import androidx.test.espresso.flutter.api.WidgetMatcher;
import androidx.test.espresso.flutter.internal.idgenerator.IdGenerator;
import androidx.test.espresso.flutter.internal.jsonrpc.JsonRpcClient;
import androidx.test.espresso.flutter.internal.jsonrpc.message.JsonRpcRequest;
import androidx.test.espresso.flutter.internal.jsonrpc.message.JsonRpcResponse;
import androidx.test.espresso.flutter.internal.protocol.impl.GetOffsetAction.OffsetType;
import androidx.test.espresso.flutter.model.WidgetInfo;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* An implementation of the Espresso-Flutter testing protocol by using the testing APIs exposed by
* Dart VM service protocol.
*
* @see <a href="https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md">Dart VM
* Service Protocol</a>.
*/
public final class DartVmService implements FlutterTestingProtocol {
private static final String TAG = DartVmService.class.getSimpleName();
private static final Gson gson =
new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
/** Prefix to be attached to the JSON-RPC message id. */
private static final String MESSAGE_ID_PREFIX = "message-";
/** The JSON-RPC method for testing extension APIs. */
private static final String TESTING_EXTENSION_METHOD = "ext.flutter.driver";
/** The JSON-RPC method for retrieving Dart isolate info. */
private static final String GET_ISOLATE_METHOD = "getIsolate";
/** The JSON-RPC method for retrieving Dart VM info. */
private static final String GET_VM_METHOD = "getVM";
/** Json property name for the Dart VM isolate id. */
private static final String ISOLATE_ID_TAG = "isolateId";
private final JsonRpcClient client;
private final IdGenerator<Integer> messageIdGenerator;
private final String isolateId;
private final ListeningExecutorService taskExecutor;
/**
* Constructs a {@code DartVmService} instance that can be used to talk to the testing protocol
* exposed by Dart VM service extension protocol. It uses the given {@code isolateId} in all the
* JSON-RPC requests. It waits until the service extension protocol is in a usable state before
* returning.
*
* @param isolateId the Dart isolate ID to be used in the JSON-RPC requests sent to Dart VM
* service protocol.
* @param jsonRpcClient a JSON-RPC web socket connection to send requests to the Dart VM service
* protocol.
* @param messageIdGenerator an ID generator for generating the JSON-RPC request IDs.
* @param taskExecutor an executor for running async tasks.
*/
public DartVmService(
String isolateId,
JsonRpcClient jsonRpcClient,
IdGenerator<Integer> messageIdGenerator,
ExecutorService taskExecutor) {
this.isolateId =
checkNotNull(
isolateId, "The ID of the Dart isolate that draws the Flutter UI shouldn't be null.");
this.client =
checkNotNull(
jsonRpcClient,
"The JsonRpcClient used to talk to Dart VM service protocol shouldn't be null.");
this.messageIdGenerator =
checkNotNull(
messageIdGenerator, "The id generator for generating request IDs shouldn't be null.");
this.taskExecutor = MoreExecutors.listeningDecorator(checkNotNull(taskExecutor));
}
/**
* {@inheritDoc}
*
* <p>This method ensures the Dart VM service is ready for use by checking:
*
* <ul>
* <li>Dart VM Observatory is up and running.
* <li>The Flutter testing API is registered with the running Dart VM service protocol.
* </ul>
*/
@Override
@SuppressWarnings("unchecked")
public Future<Void> connect() {
return (Future<Void>) taskExecutor.submit(new IsDartVmServiceReady(isolateId, this));
}
@Override
public Future<Void> perform(
@Nullable final WidgetMatcher widgetMatcher, final SyntheticAction action) {
// Assumes all the actions require a response.
ListenableFuture<JsonRpcResponse> responseFuture =
client.request(getActionRequest(widgetMatcher, action));
Function<JsonRpcResponse, Void> resultTransformFunc =
new Function<JsonRpcResponse, Void>() {
public Void apply(JsonRpcResponse response) {
if (response.getError() == null) {
return null;
} else {
// TODO(https://github.com/android/android-test/issues/251): Update error case handling
// like
// AmbiguousWidgetMatcherException, NoMatchingWidgetException after nailing down the
// design with
// Flutter team.
throw new RuntimeException(
String.format(
"Error occurred when performing the given action %s on widget matched %s",
action, widgetMatcher));
}
}
};
return transform(responseFuture, resultTransformFunc, directExecutor());
}
@Override
public Future<WidgetInfo> matchWidget(@Nonnull WidgetMatcher widgetMatcher) {
JsonRpcRequest request = getActionRequest(widgetMatcher, new GetWidgetDiagnosticsAction());
ListenableFuture<JsonRpcResponse> jsonResponseFuture = client.request(request);
Function<JsonRpcResponse, WidgetInfo> widgetInfoTransformer =
new Function<JsonRpcResponse, WidgetInfo>() {
public WidgetInfo apply(JsonRpcResponse jsonResponse) {
GetWidgetDiagnosticsResponse widgetDiagnostics =
GetWidgetDiagnosticsResponse.fromJsonRpcResponse(jsonResponse);
return WidgetInfoFactory.createWidgetInfo(widgetDiagnostics);
}
};
return transform(jsonResponseFuture, widgetInfoTransformer, directExecutor());
}
@Override
public Future<Rect> getLocalRect(@Nonnull WidgetMatcher widgetMatcher) {
ListenableFuture<JsonRpcResponse> topLeftFuture =
client.request(getActionRequest(widgetMatcher, new GetOffsetAction(OffsetType.TOP_LEFT)));
ListenableFuture<JsonRpcResponse> bottomRightFuture =
client.request(
getActionRequest(widgetMatcher, new GetOffsetAction(OffsetType.BOTTOM_RIGHT)));
ListenableFuture<List<JsonRpcResponse>> responses =
Futures.allAsList(topLeftFuture, bottomRightFuture);
Function<List<JsonRpcResponse>, Rect> rectTransformer =
new Function<List<JsonRpcResponse>, Rect>() {
public Rect apply(List<JsonRpcResponse> jsonResponses) {
GetOffsetResponse topLeft = GetOffsetResponse.fromJsonRpcResponse(jsonResponses.get(0));
GetOffsetResponse bottomRight =
GetOffsetResponse.fromJsonRpcResponse(jsonResponses.get(1));
checkState(
topLeft.getX() >= 0 && topLeft.getY() >= 0,
String.format(
"The relative coordinates [%.1f, %.1f] of a widget's top left vertex cannot be"
+ " negative (negative means it's off the outer Flutter view)!",
topLeft.getX(), topLeft.getY()));
checkState(
bottomRight.getX() >= 0 && bottomRight.getY() >= 0,
String.format(
"The relative coordinates [%.1f, %.1f] of a widget's bottom right vertex cannot"
+ " be negative (negative means it's off the outer Flutter view)!",
bottomRight.getX(), bottomRight.getY()));
checkState(
topLeft.getX() <= bottomRight.getX() && topLeft.getY() <= bottomRight.getY(),
String.format(
"The coordinates of the bottom right vertex [%.1f, %.1f] are not actually to the"
+ " bottom right of the top left vertex [%.1f, %.1f]!",
topLeft.getX(), topLeft.getY(), bottomRight.getX(), bottomRight.getY()));
return new Rect(
(int) topLeft.getX(),
(int) topLeft.getY(),
(int) bottomRight.getX(),
(int) bottomRight.getY());
}
};
return transform(responses, rectTransformer, directExecutor());
}
@Override
public Future<Void> waitUntilIdle() {
return perform(
null,
new WaitForConditionAction(
new NoPendingPlatformMessagesCondition(),
new NoTransientCallbacksCondition(),
new NoPendingFrameCondition()));
}
@Override
public void close() {
if (client != null) {
client.disconnect();
}
}
/** Queries the Dart isolate information. */
public ListenableFuture<JsonRpcResponse> getIsolateInfo() {
JsonRpcRequest getIsolateReq =
new JsonRpcRequest.Builder(GET_ISOLATE_METHOD)
.setId(getNextMessageId())
.addParam(ISOLATE_ID_TAG, isolateId)
.build();
return client.request(getIsolateReq);
}
/** Queries the Dart VM information. */
public ListenableFuture<GetVmResponse> getVmInfo() {
JsonRpcRequest getVmReq =
new JsonRpcRequest.Builder(GET_VM_METHOD).setId(getNextMessageId()).build();
ListenableFuture<JsonRpcResponse> jsonGetVmResp = client.request(getVmReq);
Function<JsonRpcResponse, GetVmResponse> jsonToResponse =
new Function<JsonRpcResponse, GetVmResponse>() {
public GetVmResponse apply(JsonRpcResponse jsonResp) {
return GetVmResponse.fromJsonRpcResponse(jsonResp);
}
};
return transform(jsonGetVmResp, jsonToResponse, directExecutor());
}
/** Gets the next usable message id. */
private String getNextMessageId() {
return MESSAGE_ID_PREFIX + messageIdGenerator.next();
}
/** Constructs a {@code JsonRpcRequest} based on the given matcher and action. */
private JsonRpcRequest getActionRequest(WidgetMatcher widgetMatcher, SyntheticAction action) {
checkNotNull(action, "Action cannot be null.");
// Assumes all the actions require a response.
return new JsonRpcRequest.Builder(TESTING_EXTENSION_METHOD)
.setId(getNextMessageId())
.setParams(constructParams(isolateId, widgetMatcher, action))
.build();
}
/** Constructs the JSON-RPC request params. */
private static JsonObject constructParams(
String isolateId, WidgetMatcher widgetMatcher, SyntheticAction action) {
JsonObject paramObject = new JsonObject();
paramObject.addProperty(ISOLATE_ID_TAG, isolateId);
if (widgetMatcher != null) {
paramObject = merge(paramObject, (JsonObject) gson.toJsonTree(widgetMatcher));
}
paramObject = merge(paramObject, (JsonObject) gson.toJsonTree(action));
return paramObject;
}
/**
* Returns a merged {@code JsonObject} of the two given {@code JsonObject}s, or an empty {@code
* JsonObject} if both of the objects to be merged are null.
*/
private static JsonObject merge(@Nullable JsonObject obj1, @Nullable JsonObject obj2) {
JsonObject result = new JsonObject();
mergeTo(result, obj1);
mergeTo(result, obj2);
return result;
}
private static void mergeTo(JsonObject obj, @Nullable JsonObject toBeMerged) {
if (toBeMerged != null) {
for (Map.Entry<String, JsonElement> entry : toBeMerged.entrySet()) {
obj.add(entry.getKey(), entry.getValue());
}
}
}
/** A {@link Runnable} that waits until the Dart VM testing extension is ready for use. */
static class IsDartVmServiceReady implements Runnable {
/** Maximum number of retries for checking extension APIs' availability. */
private static final int EXTENSION_API_CHECKING_RETRIES = 5;
/** Json param name for retrieving all the available extension APIs. */
private static final String EXTENSION_RPCS_TAG = "extensionRPCs";
private final String isolateId;
private final DartVmService dartVmService;
IsDartVmServiceReady(String isolateId, DartVmService dartVmService) {
this.isolateId = checkNotNull(isolateId);
this.dartVmService = checkNotNull(dartVmService);
}
@Override
public void run() {
waitForTestingApiRegistered();
}
/**
* Blocks until the Flutter testing/driver API is registered with the running Dart VM service
* protocol by querying whether it's listed in the isolate's 'extensionRPCs'.
*/
@VisibleForTesting
void waitForTestingApiRegistered() {
int retries = EXTENSION_API_CHECKING_RETRIES;
boolean isApiRegistered = false;
do {
retries--;
try {
JsonRpcResponse isolateResp = dartVmService.getIsolateInfo().get();
isApiRegistered = isTestingApiRegistered(isolateResp);
} catch (ExecutionException e) {
Log.d(
TAG,
"Error occurred during retrieving Dart isolate information. Retry.",
e.getCause());
continue;
} catch (InterruptedException e) {
Log.d(
TAG,
"InterruptedException occurred during retrieving Dart isolate information. Retry.",
e);
Thread.currentThread().interrupt(); // Restores the interrupted status.
continue;
}
} while (!isApiRegistered && retries > 0);
if (!isApiRegistered) {
throw new FlutterProtocolException(
String.format("Flutter testing APIs not registered with Dart isolate %s.", isolateId));
}
}
@VisibleForTesting
boolean isTestingApiRegistered(JsonRpcResponse isolateInfoResp) {
if (isolateInfoResp == null
|| isolateInfoResp.getError() != null
|| isolateInfoResp.getResult() == null) {
Log.w(
TAG,
String.format(
"Error occurred in JSON-RPC response when querying isolate info for %s: %s.",
isolateId, isolateInfoResp.getError()));
return false;
}
for (JsonElement jsonElement :
isolateInfoResp.getResult().get(EXTENSION_RPCS_TAG).getAsJsonArray()) {
String extensionApi = jsonElement.getAsString();
if (TESTING_EXTENSION_METHOD.equals(extensionApi)) {
Log.d(
TAG,
String.format("Flutter testing API registered with Dart isolate %s.", isolateId));
return true;
}
}
return false;
}
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmService.java",
"repo_id": "plugins",
"token_count": 5864
} | 1,256 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.matcher;
import androidx.test.espresso.flutter.model.WidgetInfo;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
/** A matcher that checks the existence of a Flutter widget. */
public final class IsExistingMatcher extends TypeSafeMatcher<WidgetInfo> {
/** Constructs the matcher. */
IsExistingMatcher() {}
@Override
public String toString() {
return "is existing";
}
@Override
protected boolean matchesSafely(WidgetInfo widget) {
return widget != null;
}
@Override
public void describeTo(Description description) {
description.appendText("should exist.");
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/IsExistingMatcher.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/IsExistingMatcher.java",
"repo_id": "plugins",
"token_count": 241
} | 1,257 |
name: espresso
description: Java classes for testing Flutter apps using Espresso.
Allows driving Flutter widgets from a native Espresso test.
repository: https://github.com/flutter/plugins/tree/main/packages/espresso
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+espresso%22
version: 0.2.0+8
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
package: com.example.espresso
pluginClass: EspressoPlugin
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/espresso/pubspec.yaml/0 | {
"file_path": "plugins/packages/espresso/pubspec.yaml",
"repo_id": "plugins",
"token_count": 248
} | 1,258 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// Screen that shows an example of getDirectoryPath
class GetDirectoryPage extends StatelessWidget {
/// Default Constructor
GetDirectoryPage({Key? key}) : super(key: key);
final bool _isIOS = !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS;
Future<void> _getDirectoryPath(BuildContext context) async {
const String confirmButtonText = 'Choose';
final String? directoryPath = await getDirectoryPath(
confirmButtonText: confirmButtonText,
);
if (directoryPath == null) {
// Operation was canceled by the user.
return;
}
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) => TextDisplay(directoryPath),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Open a text file'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: Colors.blue,
// ignore: deprecated_member_use
onPrimary: Colors.white,
),
onPressed: _isIOS ? null : () => _getDirectoryPath(context),
child: const Text(
'Press to ask user to choose a directory (not supported on iOS).',
),
),
],
),
),
);
}
}
/// Widget that displays a text file in a dialog
class TextDisplay extends StatelessWidget {
/// Default Constructor
const TextDisplay(this.directoryPath, {Key? key}) : super(key: key);
/// Directory path
final String directoryPath;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directory'),
content: Scrollbar(
child: SingleChildScrollView(
child: Text(directoryPath),
),
),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () => Navigator.pop(context),
),
],
);
}
}
| plugins/packages/file_selector/file_selector/example/lib/get_directory_page.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector/example/lib/get_directory_page.dart",
"repo_id": "plugins",
"token_count": 1052
} | 1,259 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
export 'package:file_selector_platform_interface/file_selector_platform_interface.dart'
show XFile, XTypeGroup;
/// Opens a file selection dialog and returns the path chosen by the user.
///
/// [acceptedTypeGroups] is a list of file type groups that can be selected in
/// the dialog. How this is displayed depends on the pltaform, for example:
/// - On Windows and Linux, each group will be an entry in a list of filter
/// options.
/// - On macOS, the union of all types allowed by all of the groups will be
/// allowed.
/// Throws an [ArgumentError] if any type groups do not include filters
/// supported by the current platform.
///
/// [initialDirectory] is the full path to the directory that will be displayed
/// when the dialog is opened. When not provided, the platform will pick an
/// initial location. This is ignored on the Web platform.
///
/// [confirmButtonText] is the text in the confirmation button of the dialog.
/// When not provided, the default OS label is used (for example, "Open").
/// This is ignored on the Web platform.
///
/// Returns `null` if the user cancels the operation.
Future<XFile?> openFile({
List<XTypeGroup> acceptedTypeGroups = const <XTypeGroup>[],
String? initialDirectory,
String? confirmButtonText,
}) {
return FileSelectorPlatform.instance.openFile(
acceptedTypeGroups: acceptedTypeGroups,
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText);
}
/// Opens a file selection dialog and returns the list of paths chosen by the
/// user.
///
/// [acceptedTypeGroups] is a list of file type groups that can be selected in
/// the dialog. How this is displayed depends on the pltaform, for example:
/// - On Windows and Linux, each group will be an entry in a list of filter
/// options.
/// - On macOS, the union of all types allowed by all of the groups will be
/// allowed.
/// Throws an [ArgumentError] if any type groups do not include filters
/// supported by the current platform.
///
/// [initialDirectory] is the full path to the directory that will be displayed
/// when the dialog is opened. When not provided, the platform will pick an
/// initial location.
///
/// [confirmButtonText] is the text in the confirmation button of the dialog.
/// When not provided, the default OS label is used (for example, "Open").
///
/// Returns an empty list if the user cancels the operation.
Future<List<XFile>> openFiles({
List<XTypeGroup> acceptedTypeGroups = const <XTypeGroup>[],
String? initialDirectory,
String? confirmButtonText,
}) {
return FileSelectorPlatform.instance.openFiles(
acceptedTypeGroups: acceptedTypeGroups,
initialDirectory: initialDirectory,
confirmButtonText: confirmButtonText);
}
/// Opens a save dialog and returns the target path chosen by the user.
///
/// [acceptedTypeGroups] is a list of file type groups that can be selected in
/// the dialog. How this is displayed depends on the pltaform, for example:
/// - On Windows and Linux, each group will be an entry in a list of filter
/// options.
/// - On macOS, the union of all types allowed by all of the groups will be
/// allowed.
/// Throws an [ArgumentError] if any type groups do not include filters
/// supported by the current platform.
///
/// [initialDirectory] is the full path to the directory that will be displayed
/// when the dialog is opened. When not provided, the platform will pick an
/// initial location.
///
/// [suggestedName] is initial value of file name.
///
/// [confirmButtonText] is the text in the confirmation button of the dialog.
/// When not provided, the default OS label is used (for example, "Save").
///
/// Returns `null` if the user cancels the operation.
Future<String?> getSavePath({
List<XTypeGroup> acceptedTypeGroups = const <XTypeGroup>[],
String? initialDirectory,
String? suggestedName,
String? confirmButtonText,
}) async {
return FileSelectorPlatform.instance.getSavePath(
acceptedTypeGroups: acceptedTypeGroups,
initialDirectory: initialDirectory,
suggestedName: suggestedName,
confirmButtonText: confirmButtonText);
}
/// Opens a directory selection dialog and returns the path chosen by the user.
/// This always returns `null` on the web.
///
/// [initialDirectory] is the full path to the directory that will be displayed
/// when the dialog is opened. When not provided, the platform will pick an
/// initial location.
///
/// [confirmButtonText] is the text in the confirmation button of the dialog.
/// When not provided, the default OS label is used (for example, "Open").
///
/// Returns `null` if the user cancels the operation.
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
}) async {
return FileSelectorPlatform.instance.getDirectoryPath(
initialDirectory: initialDirectory, confirmButtonText: confirmButtonText);
}
| plugins/packages/file_selector/file_selector/lib/file_selector.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector/lib/file_selector.dart",
"repo_id": "plugins",
"token_count": 1383
} | 1,260 |
framework module file_selector_ios {
umbrella header "file_selector_ios-umbrella.h"
export *
module * { export * }
explicit module Test {
header "FFSFileSelectorPlugin_Test.h"
}
}
| plugins/packages/file_selector/file_selector_ios/ios/Classes/FileSelectorPlugin.modulemap/0 | {
"file_path": "plugins/packages/file_selector/file_selector_ios/ios/Classes/FileSelectorPlugin.modulemap",
"repo_id": "plugins",
"token_count": 67
} | 1,261 |
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
file_selector_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
| plugins/packages/file_selector/file_selector_linux/example/linux/flutter/generated_plugins.cmake/0 | {
"file_path": "plugins/packages/file_selector/file_selector_linux/example/linux/flutter/generated_plugins.cmake",
"repo_id": "plugins",
"token_count": 320
} | 1,262 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v4.2.14), do not edit directly.
// See also: https://pub.dev/packages/pigeon
import Foundation
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#else
#error("Unsupported platform.")
#endif
/// Generated class from Pigeon.
/// A Pigeon representation of the macOS portion of an `XTypeGroup`.
///
/// Generated class from Pigeon that represents data sent in messages.
struct AllowedTypes {
var extensions: [String?]
var mimeTypes: [String?]
var utis: [String?]
static func fromList(_ list: [Any?]) -> AllowedTypes? {
let extensions = list[0] as! [String?]
let mimeTypes = list[1] as! [String?]
let utis = list[2] as! [String?]
return AllowedTypes(
extensions: extensions,
mimeTypes: mimeTypes,
utis: utis
)
}
func toList() -> [Any?] {
return [
extensions,
mimeTypes,
utis,
]
}
}
/// Options for save panels.
///
/// These correspond to NSSavePanel properties (which are, by extension
/// NSOpenPanel properties as well).
///
/// Generated class from Pigeon that represents data sent in messages.
struct SavePanelOptions {
var allowedFileTypes: AllowedTypes? = nil
var directoryPath: String? = nil
var nameFieldStringValue: String? = nil
var prompt: String? = nil
static func fromList(_ list: [Any?]) -> SavePanelOptions? {
var allowedFileTypes: AllowedTypes? = nil
if let allowedFileTypesList = list[0] as? [Any?] {
allowedFileTypes = AllowedTypes.fromList(allowedFileTypesList)
}
let directoryPath = list[1] as? String
let nameFieldStringValue = list[2] as? String
let prompt = list[3] as? String
return SavePanelOptions(
allowedFileTypes: allowedFileTypes,
directoryPath: directoryPath,
nameFieldStringValue: nameFieldStringValue,
prompt: prompt
)
}
func toList() -> [Any?] {
return [
allowedFileTypes?.toList(),
directoryPath,
nameFieldStringValue,
prompt,
]
}
}
/// Options for open panels.
///
/// These correspond to NSOpenPanel properties.
///
/// Generated class from Pigeon that represents data sent in messages.
struct OpenPanelOptions {
var allowsMultipleSelection: Bool
var canChooseDirectories: Bool
var canChooseFiles: Bool
var baseOptions: SavePanelOptions
static func fromList(_ list: [Any?]) -> OpenPanelOptions? {
let allowsMultipleSelection = list[0] as! Bool
let canChooseDirectories = list[1] as! Bool
let canChooseFiles = list[2] as! Bool
let baseOptions = SavePanelOptions.fromList(list[3] as! [Any?])!
return OpenPanelOptions(
allowsMultipleSelection: allowsMultipleSelection,
canChooseDirectories: canChooseDirectories,
canChooseFiles: canChooseFiles,
baseOptions: baseOptions
)
}
func toList() -> [Any?] {
return [
allowsMultipleSelection,
canChooseDirectories,
canChooseFiles,
baseOptions.toList(),
]
}
}
private class FileSelectorApiCodecReader: FlutterStandardReader {
override func readValue(ofType type: UInt8) -> Any? {
switch type {
case 128:
return AllowedTypes.fromList(self.readValue() as! [Any])
case 129:
return OpenPanelOptions.fromList(self.readValue() as! [Any])
case 130:
return SavePanelOptions.fromList(self.readValue() as! [Any])
default:
return super.readValue(ofType: type)
}
}
}
private class FileSelectorApiCodecWriter: FlutterStandardWriter {
override func writeValue(_ value: Any) {
if let value = value as? AllowedTypes {
super.writeByte(128)
super.writeValue(value.toList())
} else if let value = value as? OpenPanelOptions {
super.writeByte(129)
super.writeValue(value.toList())
} else if let value = value as? SavePanelOptions {
super.writeByte(130)
super.writeValue(value.toList())
} else {
super.writeValue(value)
}
}
}
private class FileSelectorApiCodecReaderWriter: FlutterStandardReaderWriter {
override func reader(with data: Data) -> FlutterStandardReader {
return FileSelectorApiCodecReader(data: data)
}
override func writer(with data: NSMutableData) -> FlutterStandardWriter {
return FileSelectorApiCodecWriter(data: data)
}
}
class FileSelectorApiCodec: FlutterStandardMessageCodec {
static let shared = FileSelectorApiCodec(readerWriter: FileSelectorApiCodecReaderWriter())
}
/// Generated protocol from Pigeon that represents a handler of messages from Flutter.
protocol FileSelectorApi {
/// Shows an open panel with the given [options], returning the list of
/// selected paths.
///
/// An empty list corresponds to a cancelled selection.
func displayOpenPanel(options: OpenPanelOptions, completion: @escaping ([String?]) -> Void)
/// Shows a save panel with the given [options], returning the selected path.
///
/// A null return corresponds to a cancelled save.
func displaySavePanel(options: SavePanelOptions, completion: @escaping (String?) -> Void)
}
/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`.
class FileSelectorApiSetup {
/// The codec used by FileSelectorApi.
static var codec: FlutterStandardMessageCodec { FileSelectorApiCodec.shared }
/// Sets up an instance of `FileSelectorApi` to handle messages through the `binaryMessenger`.
static func setUp(binaryMessenger: FlutterBinaryMessenger, api: FileSelectorApi?) {
/// Shows an open panel with the given [options], returning the list of
/// selected paths.
///
/// An empty list corresponds to a cancelled selection.
let displayOpenPanelChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.FileSelectorApi.displayOpenPanel", binaryMessenger: binaryMessenger, codec: codec)
if let api = api {
displayOpenPanelChannel.setMessageHandler { message, reply in
let args = message as! [Any?]
let optionsArg = args[0] as! OpenPanelOptions
api.displayOpenPanel(options: optionsArg) { result in
reply(wrapResult(result))
}
}
} else {
displayOpenPanelChannel.setMessageHandler(nil)
}
/// Shows a save panel with the given [options], returning the selected path.
///
/// A null return corresponds to a cancelled save.
let displaySavePanelChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.FileSelectorApi.displaySavePanel", binaryMessenger: binaryMessenger, codec: codec)
if let api = api {
displaySavePanelChannel.setMessageHandler { message, reply in
let args = message as! [Any?]
let optionsArg = args[0] as! SavePanelOptions
api.displaySavePanel(options: optionsArg) { result in
reply(wrapResult(result))
}
}
} else {
displaySavePanelChannel.setMessageHandler(nil)
}
}
}
private func wrapResult(_ result: Any?) -> [Any?] {
return [result]
}
private func wrapError(_ error: FlutterError) -> [Any?] {
return [
error.code,
error.message,
error.details
]
}
| plugins/packages/file_selector/file_selector_macos/macos/Classes/messages.g.swift/0 | {
"file_path": "plugins/packages/file_selector/file_selector_macos/macos/Classes/messages.g.swift",
"repo_id": "plugins",
"token_count": 2466
} | 1,263 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show immutable;
/// A set of allowed XTypes.
@immutable
class XTypeGroup {
/// Creates a new group with the given label and file extensions.
///
/// A group with none of the type options provided indicates that any type is
/// allowed.
const XTypeGroup({
this.label,
List<String>? extensions,
this.mimeTypes,
List<String>? macUTIs,
List<String>? uniformTypeIdentifiers,
this.webWildCards,
}) : _extensions = extensions,
assert(uniformTypeIdentifiers == null || macUTIs == null,
'Only one of uniformTypeIdentifiers or macUTIs can be non-null'),
uniformTypeIdentifiers = uniformTypeIdentifiers ?? macUTIs;
/// The 'name' or reference to this group of types.
final String? label;
/// The MIME types for this group.
final List<String>? mimeTypes;
/// The uniform type identifiers for this group
final List<String>? uniformTypeIdentifiers;
/// The web wild cards for this group (ex: image/*, video/*).
final List<String>? webWildCards;
final List<String>? _extensions;
/// The extensions for this group.
List<String>? get extensions {
return _removeLeadingDots(_extensions);
}
/// Converts this object into a JSON formatted object.
Map<String, dynamic> toJSON() {
return <String, dynamic>{
'label': label,
'extensions': extensions,
'mimeTypes': mimeTypes,
'macUTIs': macUTIs,
'webWildCards': webWildCards,
};
}
/// True if this type group should allow any file.
bool get allowsAny {
return (extensions?.isEmpty ?? true) &&
(mimeTypes?.isEmpty ?? true) &&
(macUTIs?.isEmpty ?? true) &&
(webWildCards?.isEmpty ?? true);
}
/// Returns the list of uniform type identifiers for this group
List<String>? get macUTIs => uniformTypeIdentifiers;
static List<String>? _removeLeadingDots(List<String>? exts) => exts
?.map((String ext) => ext.startsWith('.') ? ext.substring(1) : ext)
.toList();
}
| plugins/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group/x_type_group.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group/x_type_group.dart",
"repo_id": "plugins",
"token_count": 742
} | 1,264 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.2.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import
// ignore_for_file: avoid_relative_lib_imports
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
// ignore: directives_ordering
import 'package:file_selector_windows/src/messages.g.dart';
class _TestFileSelectorApiCodec extends StandardMessageCodec {
const _TestFileSelectorApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is SelectionOptions) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is TypeGroup) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return SelectionOptions.decode(readValue(buffer)!);
case 129:
return TypeGroup.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestFileSelectorApi {
static const MessageCodec<Object?> codec = _TestFileSelectorApiCodec();
List<String?> showOpenDialog(SelectionOptions options,
String? initialDirectory, String? confirmButtonText);
List<String?> showSaveDialog(
SelectionOptions options,
String? initialDirectory,
String? suggestedName,
String? confirmButtonText);
static void setup(TestFileSelectorApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.showOpenDialog', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.FileSelectorApi.showOpenDialog was null.');
final List<Object?> args = (message as List<Object?>?)!;
final SelectionOptions? arg_options = (args[0] as SelectionOptions?);
assert(arg_options != null,
'Argument for dev.flutter.pigeon.FileSelectorApi.showOpenDialog was null, expected non-null SelectionOptions.');
final String? arg_initialDirectory = (args[1] as String?);
final String? arg_confirmButtonText = (args[2] as String?);
final List<String?> output = api.showOpenDialog(
arg_options!, arg_initialDirectory, arg_confirmButtonText);
return <Object?, Object?>{'result': output};
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.showSaveDialog', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMockMessageHandler(null);
} else {
channel.setMockMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.FileSelectorApi.showSaveDialog was null.');
final List<Object?> args = (message as List<Object?>?)!;
final SelectionOptions? arg_options = (args[0] as SelectionOptions?);
assert(arg_options != null,
'Argument for dev.flutter.pigeon.FileSelectorApi.showSaveDialog was null, expected non-null SelectionOptions.');
final String? arg_initialDirectory = (args[1] as String?);
final String? arg_suggestedName = (args[2] as String?);
final String? arg_confirmButtonText = (args[3] as String?);
final List<String?> output = api.showSaveDialog(arg_options!,
arg_initialDirectory, arg_suggestedName, arg_confirmButtonText);
return <Object?, Object?>{'result': output};
});
}
}
}
}
| plugins/packages/file_selector/file_selector_windows/test/test_api.g.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_windows/test/test_api.g.dart",
"repo_id": "plugins",
"token_count": 1693
} | 1,265 |
// 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.embedding.engine.plugins.lifecycle;
import static org.junit.Assert.assertEquals;
import android.app.Activity;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.PluginRegistry;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class FlutterLifecycleAdapterTest {
@Mock Lifecycle lifecycle;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void getActivityLifecycle() {
TestActivityPluginBinding binding = new TestActivityPluginBinding(lifecycle);
Lifecycle parsedLifecycle = FlutterLifecycleAdapter.getActivityLifecycle(binding);
assertEquals(lifecycle, parsedLifecycle);
}
private static final class TestActivityPluginBinding implements ActivityPluginBinding {
private final Lifecycle lifecycle;
TestActivityPluginBinding(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
}
@NonNull
public Object getLifecycle() {
return new HiddenLifecycleReference(lifecycle);
}
@Override
public Activity getActivity() {
return null;
}
@Override
public void addRequestPermissionsResultListener(
@NonNull PluginRegistry.RequestPermissionsResultListener listener) {}
@Override
public void removeRequestPermissionsResultListener(
@NonNull PluginRegistry.RequestPermissionsResultListener listener) {}
@Override
public void addActivityResultListener(
@NonNull PluginRegistry.ActivityResultListener listener) {}
@Override
public void removeActivityResultListener(
@NonNull PluginRegistry.ActivityResultListener listener) {}
@Override
public void addOnNewIntentListener(@NonNull PluginRegistry.NewIntentListener listener) {}
@Override
public void removeOnNewIntentListener(@NonNull PluginRegistry.NewIntentListener listener) {}
@Override
public void addOnUserLeaveHintListener(
@NonNull PluginRegistry.UserLeaveHintListener listener) {}
@Override
public void removeOnUserLeaveHintListener(
@NonNull PluginRegistry.UserLeaveHintListener listener) {}
@Override
public void addOnSaveStateListener(
@NonNull ActivityPluginBinding.OnSaveInstanceStateListener listener) {}
@Override
public void removeOnSaveStateListener(
@NonNull ActivityPluginBinding.OnSaveInstanceStateListener listener) {}
}
}
| plugins/packages/flutter_plugin_android_lifecycle/android/src/test/java/io/flutter/embedding/engine/plugins/lifecycle/FlutterLifecycleAdapterTest.java/0 | {
"file_path": "plugins/packages/flutter_plugin_android_lifecycle/android/src/test/java/io/flutter/embedding/engine/plugins/lifecycle/FlutterLifecycleAdapterTest.java",
"repo_id": "plugins",
"token_count": 855
} | 1,266 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library google_maps_flutter;
import 'dart:async';
import 'dart:io';
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter_android/google_maps_flutter_android.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
export 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'
show
ArgumentCallbacks,
ArgumentCallback,
BitmapDescriptor,
CameraPosition,
CameraPositionCallback,
CameraTargetBounds,
CameraUpdate,
Cap,
Circle,
CircleId,
InfoWindow,
JointType,
LatLng,
LatLngBounds,
MapStyleException,
MapType,
Marker,
MarkerId,
MinMaxZoomPreference,
PatternItem,
Polygon,
PolygonId,
Polyline,
PolylineId,
ScreenCoordinate,
Tile,
TileOverlayId,
TileOverlay,
TileProvider;
part 'src/controller.dart';
part 'src/google_map.dart';
| plugins/packages/google_maps_flutter/google_maps_flutter/lib/google_maps_flutter.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/lib/google_maps_flutter.dart",
"repo_id": "plugins",
"token_count": 615
} | 1,267 |
group 'io.flutter.plugins.googlemaps'
version '1.0-SNAPSHOT'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.1'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
compileSdkVersion 31
defaultConfig {
minSdkVersion 20
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
dependencies {
implementation "androidx.annotation:annotation:1.1.0"
implementation 'com.google.android.gms:play-services-maps:18.1.0'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.4.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:5.1.1'
testImplementation 'androidx.test:core:1.2.0'
testImplementation "org.robolectric:robolectric:4.3.1"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/android/build.gradle/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/build.gradle",
"repo_id": "plugins",
"token_count": 753
} | 1,268 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.googlemaps;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.maps.model.Tile;
import com.google.android.gms.maps.model.TileProvider;
import io.flutter.plugin.common.MethodChannel;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
class TileProviderController implements TileProvider {
private static final String TAG = "TileProviderController";
private final String tileOverlayId;
private final MethodChannel methodChannel;
private final Handler handler = new Handler(Looper.getMainLooper());
TileProviderController(MethodChannel methodChannel, String tileOverlayId) {
this.tileOverlayId = tileOverlayId;
this.methodChannel = methodChannel;
}
@Override
public Tile getTile(final int x, final int y, final int zoom) {
Worker worker = new Worker(x, y, zoom);
return worker.getTile();
}
private final class Worker implements MethodChannel.Result {
private final CountDownLatch countDownLatch = new CountDownLatch(1);
private final int x;
private final int y;
private final int zoom;
private Map<String, ?> result;
Worker(int x, int y, int zoom) {
this.x = x;
this.y = y;
this.zoom = zoom;
}
@NonNull
Tile getTile() {
handler.post(
() ->
methodChannel.invokeMethod(
"tileOverlay#getTile",
Convert.tileOverlayArgumentsToJson(tileOverlayId, x, y, zoom),
this));
try {
// Because `methodChannel.invokeMethod` is async, we use a `countDownLatch` make it synchronized.
countDownLatch.await();
} catch (InterruptedException e) {
Log.e(
TAG,
String.format("countDownLatch: can't get tile: x = %d, y= %d, zoom = %d", x, y, zoom),
e);
return TileProvider.NO_TILE;
}
try {
return Convert.interpretTile(result);
} catch (Exception e) {
Log.e(TAG, "Can't parse tile data", e);
return TileProvider.NO_TILE;
}
}
@Override
@SuppressWarnings("unchecked")
public void success(Object data) {
result = (Map<String, ?>) data;
countDownLatch.countDown();
}
@Override
public void error(String errorCode, String errorMessage, Object data) {
Log.e(
TAG,
String.format(
"Can't get tile: errorCode = %s, errorMessage = %s, date = %s",
errorCode, errorCode, data));
result = null;
countDownLatch.countDown();
}
@Override
public void notImplemented() {
Log.e(TAG, "Can't get tile: notImplemented");
result = null;
countDownLatch.countDown();
}
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileProviderController.java/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileProviderController.java",
"repo_id": "plugins",
"token_count": 1166
} | 1,269 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:stream_transform/stream_transform.dart';
import 'google_map_inspector_android.dart';
// TODO(stuartmorgan): Remove the dependency on platform interface toJson
// methods. Channel serialization details should all be package-internal.
/// Error thrown when an unknown map ID is provided to a method channel API.
class UnknownMapIDError extends Error {
/// Creates an assertion error with the provided [mapId] and optional
/// [message].
UnknownMapIDError(this.mapId, [this.message]);
/// The unknown ID.
final int mapId;
/// Message describing the assertion error.
final Object? message;
@override
String toString() {
if (message != null) {
return 'Unknown map ID $mapId: ${Error.safeToString(message)}';
}
return 'Unknown map ID $mapId';
}
}
/// The possible android map renderer types that can be
/// requested from the native Google Maps SDK.
enum AndroidMapRenderer {
/// Latest renderer type.
latest,
/// Legacy renderer type.
legacy,
/// Requests the default map renderer type.
platformDefault,
}
/// An implementation of [GoogleMapsFlutterPlatform] for Android.
class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform {
/// Registers the Android implementation of GoogleMapsFlutterPlatform.
static void registerWith() {
GoogleMapsFlutterPlatform.instance = GoogleMapsFlutterAndroid();
}
/// The method channel used to initialize the native Google Maps SDK.
final MethodChannel _initializerChannel = const MethodChannel(
'plugins.flutter.dev/google_maps_android_initializer');
// Keep a collection of id -> channel
// Every method call passes the int mapId
final Map<int, MethodChannel> _channels = <int, MethodChannel>{};
/// Accesses the MethodChannel associated to the passed mapId.
MethodChannel _channel(int mapId) {
final MethodChannel? channel = _channels[mapId];
if (channel == null) {
throw UnknownMapIDError(mapId);
}
return channel;
}
// Keep a collection of mapId to a map of TileOverlays.
final Map<int, Map<TileOverlayId, TileOverlay>> _tileOverlays =
<int, Map<TileOverlayId, TileOverlay>>{};
/// Returns the channel for [mapId], creating it if it doesn't already exist.
@visibleForTesting
MethodChannel ensureChannelInitialized(int mapId) {
MethodChannel? channel = _channels[mapId];
if (channel == null) {
channel = MethodChannel('plugins.flutter.dev/google_maps_android_$mapId');
channel.setMethodCallHandler(
(MethodCall call) => _handleMethodCall(call, mapId));
_channels[mapId] = channel;
}
return channel;
}
@override
Future<void> init(int mapId) {
final MethodChannel channel = ensureChannelInitialized(mapId);
return channel.invokeMethod<void>('map#waitForMap');
}
@override
void dispose({required int mapId}) {
// Noop!
}
// The controller we need to broadcast the different events coming
// from handleMethodCall.
//
// It is a `broadcast` because multiple controllers will connect to
// different stream views of this Controller.
final StreamController<MapEvent<Object?>> _mapEventStreamController =
StreamController<MapEvent<Object?>>.broadcast();
// Returns a filtered view of the events in the _controller, by mapId.
Stream<MapEvent<Object?>> _events(int mapId) =>
_mapEventStreamController.stream
.where((MapEvent<Object?> event) => event.mapId == mapId);
@override
Stream<CameraMoveStartedEvent> onCameraMoveStarted({required int mapId}) {
return _events(mapId).whereType<CameraMoveStartedEvent>();
}
@override
Stream<CameraMoveEvent> onCameraMove({required int mapId}) {
return _events(mapId).whereType<CameraMoveEvent>();
}
@override
Stream<CameraIdleEvent> onCameraIdle({required int mapId}) {
return _events(mapId).whereType<CameraIdleEvent>();
}
@override
Stream<MarkerTapEvent> onMarkerTap({required int mapId}) {
return _events(mapId).whereType<MarkerTapEvent>();
}
@override
Stream<InfoWindowTapEvent> onInfoWindowTap({required int mapId}) {
return _events(mapId).whereType<InfoWindowTapEvent>();
}
@override
Stream<MarkerDragStartEvent> onMarkerDragStart({required int mapId}) {
return _events(mapId).whereType<MarkerDragStartEvent>();
}
@override
Stream<MarkerDragEvent> onMarkerDrag({required int mapId}) {
return _events(mapId).whereType<MarkerDragEvent>();
}
@override
Stream<MarkerDragEndEvent> onMarkerDragEnd({required int mapId}) {
return _events(mapId).whereType<MarkerDragEndEvent>();
}
@override
Stream<PolylineTapEvent> onPolylineTap({required int mapId}) {
return _events(mapId).whereType<PolylineTapEvent>();
}
@override
Stream<PolygonTapEvent> onPolygonTap({required int mapId}) {
return _events(mapId).whereType<PolygonTapEvent>();
}
@override
Stream<CircleTapEvent> onCircleTap({required int mapId}) {
return _events(mapId).whereType<CircleTapEvent>();
}
@override
Stream<MapTapEvent> onTap({required int mapId}) {
return _events(mapId).whereType<MapTapEvent>();
}
@override
Stream<MapLongPressEvent> onLongPress({required int mapId}) {
return _events(mapId).whereType<MapLongPressEvent>();
}
Future<dynamic> _handleMethodCall(MethodCall call, int mapId) async {
switch (call.method) {
case 'camera#onMoveStarted':
_mapEventStreamController.add(CameraMoveStartedEvent(mapId));
break;
case 'camera#onMove':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(CameraMoveEvent(
mapId,
CameraPosition.fromMap(arguments['position'])!,
));
break;
case 'camera#onIdle':
_mapEventStreamController.add(CameraIdleEvent(mapId));
break;
case 'marker#onTap':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(MarkerTapEvent(
mapId,
MarkerId(arguments['markerId']! as String),
));
break;
case 'marker#onDragStart':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(MarkerDragStartEvent(
mapId,
LatLng.fromJson(arguments['position'])!,
MarkerId(arguments['markerId']! as String),
));
break;
case 'marker#onDrag':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(MarkerDragEvent(
mapId,
LatLng.fromJson(arguments['position'])!,
MarkerId(arguments['markerId']! as String),
));
break;
case 'marker#onDragEnd':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(MarkerDragEndEvent(
mapId,
LatLng.fromJson(arguments['position'])!,
MarkerId(arguments['markerId']! as String),
));
break;
case 'infoWindow#onTap':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(InfoWindowTapEvent(
mapId,
MarkerId(arguments['markerId']! as String),
));
break;
case 'polyline#onTap':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(PolylineTapEvent(
mapId,
PolylineId(arguments['polylineId']! as String),
));
break;
case 'polygon#onTap':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(PolygonTapEvent(
mapId,
PolygonId(arguments['polygonId']! as String),
));
break;
case 'circle#onTap':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(CircleTapEvent(
mapId,
CircleId(arguments['circleId']! as String),
));
break;
case 'map#onTap':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(MapTapEvent(
mapId,
LatLng.fromJson(arguments['position'])!,
));
break;
case 'map#onLongPress':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
_mapEventStreamController.add(MapLongPressEvent(
mapId,
LatLng.fromJson(arguments['position'])!,
));
break;
case 'tileOverlay#getTile':
final Map<String, Object?> arguments = _getArgumentDictionary(call);
final Map<TileOverlayId, TileOverlay>? tileOverlaysForThisMap =
_tileOverlays[mapId];
final String tileOverlayId = arguments['tileOverlayId']! as String;
final TileOverlay? tileOverlay =
tileOverlaysForThisMap?[TileOverlayId(tileOverlayId)];
final TileProvider? tileProvider = tileOverlay?.tileProvider;
if (tileProvider == null) {
return TileProvider.noTile.toJson();
}
final Tile tile = await tileProvider.getTile(
arguments['x']! as int,
arguments['y']! as int,
arguments['zoom'] as int?,
);
return tile.toJson();
default:
throw MissingPluginException();
}
}
/// Returns the arguments of [call] as typed string-keyed Map.
///
/// This does not do any type validation, so is only safe to call if the
/// arguments are known to be a map.
Map<String, Object?> _getArgumentDictionary(MethodCall call) {
return (call.arguments as Map<Object?, Object?>).cast<String, Object?>();
}
@override
Future<void> updateMapOptions(
Map<String, dynamic> optionsUpdate, {
required int mapId,
}) {
assert(optionsUpdate != null);
return _channel(mapId).invokeMethod<void>(
'map#update',
<String, dynamic>{
'options': optionsUpdate,
},
);
}
@override
Future<void> updateMarkers(
MarkerUpdates markerUpdates, {
required int mapId,
}) {
assert(markerUpdates != null);
return _channel(mapId).invokeMethod<void>(
'markers#update',
markerUpdates.toJson(),
);
}
@override
Future<void> updatePolygons(
PolygonUpdates polygonUpdates, {
required int mapId,
}) {
assert(polygonUpdates != null);
return _channel(mapId).invokeMethod<void>(
'polygons#update',
polygonUpdates.toJson(),
);
}
@override
Future<void> updatePolylines(
PolylineUpdates polylineUpdates, {
required int mapId,
}) {
assert(polylineUpdates != null);
return _channel(mapId).invokeMethod<void>(
'polylines#update',
polylineUpdates.toJson(),
);
}
@override
Future<void> updateCircles(
CircleUpdates circleUpdates, {
required int mapId,
}) {
assert(circleUpdates != null);
return _channel(mapId).invokeMethod<void>(
'circles#update',
circleUpdates.toJson(),
);
}
@override
Future<void> updateTileOverlays({
required Set<TileOverlay> newTileOverlays,
required int mapId,
}) {
final Map<TileOverlayId, TileOverlay>? currentTileOverlays =
_tileOverlays[mapId];
final Set<TileOverlay> previousSet = currentTileOverlays != null
? currentTileOverlays.values.toSet()
: <TileOverlay>{};
final _TileOverlayUpdates updates =
_TileOverlayUpdates.from(previousSet, newTileOverlays);
_tileOverlays[mapId] = keyTileOverlayId(newTileOverlays);
return _channel(mapId).invokeMethod<void>(
'tileOverlays#update',
updates.toJson(),
);
}
@override
Future<void> clearTileCache(
TileOverlayId tileOverlayId, {
required int mapId,
}) {
return _channel(mapId)
.invokeMethod<void>('tileOverlays#clearTileCache', <String, Object>{
'tileOverlayId': tileOverlayId.value,
});
}
@override
Future<void> animateCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) {
return _channel(mapId)
.invokeMethod<void>('camera#animate', <String, Object>{
'cameraUpdate': cameraUpdate.toJson(),
});
}
@override
Future<void> moveCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) {
return _channel(mapId).invokeMethod<void>('camera#move', <String, dynamic>{
'cameraUpdate': cameraUpdate.toJson(),
});
}
@override
Future<void> setMapStyle(
String? mapStyle, {
required int mapId,
}) async {
final List<dynamic> successAndError = (await _channel(mapId)
.invokeMethod<List<dynamic>>('map#setStyle', mapStyle))!;
final bool success = successAndError[0] as bool;
if (!success) {
throw MapStyleException(successAndError[1] as String);
}
}
@override
Future<LatLngBounds> getVisibleRegion({
required int mapId,
}) async {
final Map<String, dynamic> latLngBounds = (await _channel(mapId)
.invokeMapMethod<String, dynamic>('map#getVisibleRegion'))!;
final LatLng southwest = LatLng.fromJson(latLngBounds['southwest'])!;
final LatLng northeast = LatLng.fromJson(latLngBounds['northeast'])!;
return LatLngBounds(northeast: northeast, southwest: southwest);
}
@override
Future<ScreenCoordinate> getScreenCoordinate(
LatLng latLng, {
required int mapId,
}) async {
final Map<String, int> point = (await _channel(mapId)
.invokeMapMethod<String, int>(
'map#getScreenCoordinate', latLng.toJson()))!;
return ScreenCoordinate(x: point['x']!, y: point['y']!);
}
@override
Future<LatLng> getLatLng(
ScreenCoordinate screenCoordinate, {
required int mapId,
}) async {
final List<dynamic> latLng = (await _channel(mapId)
.invokeMethod<List<dynamic>>(
'map#getLatLng', screenCoordinate.toJson()))!;
return LatLng(latLng[0] as double, latLng[1] as double);
}
@override
Future<void> showMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) {
assert(markerId != null);
return _channel(mapId).invokeMethod<void>(
'markers#showInfoWindow', <String, String>{'markerId': markerId.value});
}
@override
Future<void> hideMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) {
assert(markerId != null);
return _channel(mapId).invokeMethod<void>(
'markers#hideInfoWindow', <String, String>{'markerId': markerId.value});
}
@override
Future<bool> isMarkerInfoWindowShown(
MarkerId markerId, {
required int mapId,
}) async {
assert(markerId != null);
return (await _channel(mapId).invokeMethod<bool>(
'markers#isInfoWindowShown',
<String, String>{'markerId': markerId.value}))!;
}
@override
Future<double> getZoomLevel({
required int mapId,
}) async {
return (await _channel(mapId).invokeMethod<double>('map#getZoomLevel'))!;
}
@override
Future<Uint8List?> takeSnapshot({
required int mapId,
}) {
return _channel(mapId).invokeMethod<Uint8List>('map#takeSnapshot');
}
/// Set [GoogleMapsFlutterPlatform] to use [AndroidViewSurface] to build the
/// Google Maps widget.
///
/// See https://pub.dev/packages/google_maps_flutter_android#display-mode
/// for more information.
///
/// Currently defaults to true, but the default is subject to change.
bool useAndroidViewSurface = true;
/// Requests Google Map Renderer with [AndroidMapRenderer] type.
///
/// See https://pub.dev/packages/google_maps_flutter_android#map-renderer
/// for more information.
///
/// The renderer must be requested before creating GoogleMap instances as the
/// renderer can be initialized only once per application context.
/// Throws a [PlatformException] if method is called multiple times.
///
/// The returned [Future] completes after renderer has been initialized.
/// Initialized [AndroidMapRenderer] type is returned.
Future<AndroidMapRenderer> initializeWithRenderer(
AndroidMapRenderer? rendererType) async {
String preferredRenderer;
switch (rendererType) {
case AndroidMapRenderer.latest:
preferredRenderer = 'latest';
break;
case AndroidMapRenderer.legacy:
preferredRenderer = 'legacy';
break;
case AndroidMapRenderer.platformDefault:
case null:
preferredRenderer = 'default';
}
final String? initializedRenderer = await _initializerChannel
.invokeMethod<String>('initializer#preferRenderer',
<String, dynamic>{'value': preferredRenderer});
if (initializedRenderer == null) {
throw AndroidMapRendererException('Failed to initialize map renderer.');
}
// Returns mapped [AndroidMapRenderer] enum type.
switch (initializedRenderer) {
case 'latest':
return AndroidMapRenderer.latest;
case 'legacy':
return AndroidMapRenderer.legacy;
default:
throw AndroidMapRendererException(
'Failed to initialize latest or legacy renderer, got $initializedRenderer.');
}
}
Widget _buildView(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required MapWidgetConfiguration widgetConfiguration,
MapObjects mapObjects = const MapObjects(),
Map<String, dynamic> mapOptions = const <String, dynamic>{},
}) {
final Map<String, dynamic> creationParams = <String, dynamic>{
'initialCameraPosition':
widgetConfiguration.initialCameraPosition.toMap(),
'options': mapOptions,
'markersToAdd': serializeMarkerSet(mapObjects.markers),
'polygonsToAdd': serializePolygonSet(mapObjects.polygons),
'polylinesToAdd': serializePolylineSet(mapObjects.polylines),
'circlesToAdd': serializeCircleSet(mapObjects.circles),
'tileOverlaysToAdd': serializeTileOverlaySet(mapObjects.tileOverlays),
};
const String viewType = 'plugins.flutter.dev/google_maps_android';
if (useAndroidViewSurface) {
return PlatformViewLink(
viewType: viewType,
surfaceFactory: (
BuildContext context,
PlatformViewController controller,
) {
return AndroidViewSurface(
controller: controller as AndroidViewController,
gestureRecognizers: widgetConfiguration.gestureRecognizers,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
);
},
onCreatePlatformView: (PlatformViewCreationParams params) {
final AndroidViewController controller =
PlatformViewsService.initExpensiveAndroidView(
id: params.id,
viewType: viewType,
layoutDirection: widgetConfiguration.textDirection,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
onFocus: () => params.onFocusChanged(true),
);
controller.addOnPlatformViewCreatedListener(
params.onPlatformViewCreated,
);
controller.addOnPlatformViewCreatedListener(
onPlatformViewCreated,
);
controller.create();
return controller;
},
);
} else {
return AndroidView(
viewType: viewType,
onPlatformViewCreated: onPlatformViewCreated,
gestureRecognizers: widgetConfiguration.gestureRecognizers,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
}
}
@override
Widget buildViewWithConfiguration(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required MapWidgetConfiguration widgetConfiguration,
MapConfiguration mapConfiguration = const MapConfiguration(),
MapObjects mapObjects = const MapObjects(),
}) {
return _buildView(
creationId,
onPlatformViewCreated,
widgetConfiguration: widgetConfiguration,
mapObjects: mapObjects,
mapOptions: _jsonForMapConfiguration(mapConfiguration),
);
}
@override
Widget buildViewWithTextDirection(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required CameraPosition initialCameraPosition,
required TextDirection textDirection,
Set<Marker> markers = const <Marker>{},
Set<Polygon> polygons = const <Polygon>{},
Set<Polyline> polylines = const <Polyline>{},
Set<Circle> circles = const <Circle>{},
Set<TileOverlay> tileOverlays = const <TileOverlay>{},
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers,
Map<String, dynamic> mapOptions = const <String, dynamic>{},
}) {
return _buildView(
creationId,
onPlatformViewCreated,
widgetConfiguration: MapWidgetConfiguration(
initialCameraPosition: initialCameraPosition,
textDirection: textDirection),
mapObjects: MapObjects(
markers: markers,
polygons: polygons,
polylines: polylines,
circles: circles,
tileOverlays: tileOverlays),
mapOptions: mapOptions,
);
}
@override
Widget buildView(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required CameraPosition initialCameraPosition,
Set<Marker> markers = const <Marker>{},
Set<Polygon> polygons = const <Polygon>{},
Set<Polyline> polylines = const <Polyline>{},
Set<Circle> circles = const <Circle>{},
Set<TileOverlay> tileOverlays = const <TileOverlay>{},
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers,
Map<String, dynamic> mapOptions = const <String, dynamic>{},
}) {
return buildViewWithTextDirection(
creationId,
onPlatformViewCreated,
initialCameraPosition: initialCameraPosition,
textDirection: TextDirection.ltr,
markers: markers,
polygons: polygons,
polylines: polylines,
circles: circles,
tileOverlays: tileOverlays,
gestureRecognizers: gestureRecognizers,
mapOptions: mapOptions,
);
}
@override
@visibleForTesting
void enableDebugInspection() {
GoogleMapsInspectorPlatform.instance =
GoogleMapsInspectorAndroid((int mapId) => _channel(mapId));
}
}
Map<String, Object> _jsonForMapConfiguration(MapConfiguration config) {
final EdgeInsets? padding = config.padding;
return <String, Object>{
if (config.compassEnabled != null) 'compassEnabled': config.compassEnabled!,
if (config.mapToolbarEnabled != null)
'mapToolbarEnabled': config.mapToolbarEnabled!,
if (config.cameraTargetBounds != null)
'cameraTargetBounds': config.cameraTargetBounds!.toJson(),
if (config.mapType != null) 'mapType': config.mapType!.index,
if (config.minMaxZoomPreference != null)
'minMaxZoomPreference': config.minMaxZoomPreference!.toJson(),
if (config.rotateGesturesEnabled != null)
'rotateGesturesEnabled': config.rotateGesturesEnabled!,
if (config.scrollGesturesEnabled != null)
'scrollGesturesEnabled': config.scrollGesturesEnabled!,
if (config.tiltGesturesEnabled != null)
'tiltGesturesEnabled': config.tiltGesturesEnabled!,
if (config.zoomControlsEnabled != null)
'zoomControlsEnabled': config.zoomControlsEnabled!,
if (config.zoomGesturesEnabled != null)
'zoomGesturesEnabled': config.zoomGesturesEnabled!,
if (config.liteModeEnabled != null)
'liteModeEnabled': config.liteModeEnabled!,
if (config.trackCameraPosition != null)
'trackCameraPosition': config.trackCameraPosition!,
if (config.myLocationEnabled != null)
'myLocationEnabled': config.myLocationEnabled!,
if (config.myLocationButtonEnabled != null)
'myLocationButtonEnabled': config.myLocationButtonEnabled!,
if (padding != null)
'padding': <double>[
padding.top,
padding.left,
padding.bottom,
padding.right,
],
if (config.indoorViewEnabled != null)
'indoorEnabled': config.indoorViewEnabled!,
if (config.trafficEnabled != null) 'trafficEnabled': config.trafficEnabled!,
if (config.buildingsEnabled != null)
'buildingsEnabled': config.buildingsEnabled!,
};
}
/// Update specification for a set of [TileOverlay]s.
// TODO(stuartmorgan): Fix the missing export of this class in the platform
// interface, and remove this copy.
class _TileOverlayUpdates extends MapsObjectUpdates<TileOverlay> {
/// Computes [TileOverlayUpdates] given previous and current [TileOverlay]s.
_TileOverlayUpdates.from(Set<TileOverlay> previous, Set<TileOverlay> current)
: super.from(previous, current, objectName: 'tileOverlay');
/// Set of TileOverlays to be added in this update.
Set<TileOverlay> get tileOverlaysToAdd => objectsToAdd;
/// Set of TileOverlayIds to be removed in this update.
Set<TileOverlayId> get tileOverlayIdsToRemove =>
objectIdsToRemove.cast<TileOverlayId>();
/// Set of TileOverlays to be changed in this update.
Set<TileOverlay> get tileOverlaysToChange => objectsToChange;
}
/// Thrown to indicate that a platform interaction failed to initialize renderer.
class AndroidMapRendererException implements Exception {
/// Creates a [AndroidMapRendererException] with an optional human-readable
/// error message.
AndroidMapRendererException([this.message]);
/// A human-readable error message, possibly null.
final String? message;
@override
String toString() => 'AndroidMapRendererException($message)';
}
| plugins/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_maps_flutter_android.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_maps_flutter_android.dart",
"repo_id": "plugins",
"token_count": 9695
} | 1,270 |
// 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>
#import <GoogleMaps/GoogleMaps.h>
NS_ASSUME_NONNULL_BEGIN
@interface FLTGoogleMapTileOverlayController : NSObject
- (instancetype)initWithTileLayer:(GMSTileLayer *)tileLayer
mapView:(GMSMapView *)mapView
options:(NSDictionary *)optionsData;
- (void)removeTileOverlay;
- (void)clearTileCache;
- (NSDictionary *)getTileOverlayInfo;
@end
@interface FLTTileProviderController : GMSTileLayer
@property(copy, nonatomic, readonly) NSString *tileOverlayIdentifier;
- (instancetype)init:(FlutterMethodChannel *)methodChannel
withTileOverlayIdentifier:(NSString *)identifier;
@end
@interface FLTTileOverlaysController : NSObject
- (instancetype)init:(FlutterMethodChannel *)methodChannel
mapView:(GMSMapView *)mapView
registrar:(NSObject<FlutterPluginRegistrar> *)registrar;
- (void)addTileOverlays:(NSArray *)tileOverlaysToAdd;
- (void)changeTileOverlays:(NSArray *)tileOverlaysToChange;
- (void)removeTileOverlayWithIdentifiers:(NSArray *)identifiers;
- (void)clearTileCacheWithIdentifier:(NSString *)identifier;
- (nullable NSDictionary *)tileOverlayInfoWithIdentifier:(NSString *)identifier;
@end
NS_ASSUME_NONNULL_END
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapTileOverlayController.h/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/FLTGoogleMapTileOverlayController.h",
"repo_id": "plugins",
"token_count": 492
} | 1,271 |
framework module google_maps_flutter_ios {
umbrella header "google_maps_flutter_ios-umbrella.h"
export *
module * { export * }
explicit module Test {
header "GoogleMapController_Test.h"
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/google_maps_flutter_ios.modulemap/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/google_maps_flutter_ios.modulemap",
"repo_id": "plugins",
"token_count": 68
} | 1,272 |
// 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' show Future;
import 'dart:typed_data' show Uint8List;
import 'dart:ui' show Size;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart'
show ImageConfiguration, AssetImage, AssetBundleImageKey;
import 'package:flutter/services.dart' show AssetBundle;
/// Defines a bitmap image. For a marker, this class can be used to set the
/// image of the marker icon. For a ground overlay, it can be used to set the
/// image to place on the surface of the earth.
class BitmapDescriptor {
const BitmapDescriptor._(this._json);
/// The inverse of .toJson.
// TODO(stuartmorgan): Remove this in the next breaking change.
@Deprecated('No longer supported')
BitmapDescriptor.fromJson(Object json) : _json = json {
assert(_json is List<dynamic>);
final List<dynamic> jsonList = json as List<dynamic>;
assert(_validTypes.contains(jsonList[0]));
switch (jsonList[0]) {
case _defaultMarker:
assert(jsonList.length <= 2);
if (jsonList.length == 2) {
assert(jsonList[1] is num);
final num secondElement = jsonList[1] as num;
assert(0 <= secondElement && secondElement < 360);
}
break;
case _fromBytes:
assert(jsonList.length == 2);
assert(jsonList[1] != null && jsonList[1] is List<int>);
assert((jsonList[1] as List<int>).isNotEmpty);
break;
case _fromAsset:
assert(jsonList.length <= 3);
assert(jsonList[1] != null && jsonList[1] is String);
assert((jsonList[1] as String).isNotEmpty);
if (jsonList.length == 3) {
assert(jsonList[2] != null && jsonList[2] is String);
assert((jsonList[2] as String).isNotEmpty);
}
break;
case _fromAssetImage:
assert(jsonList.length <= 4);
assert(jsonList[1] != null && jsonList[1] is String);
assert((jsonList[1] as String).isNotEmpty);
assert(jsonList[2] != null && jsonList[2] is double);
if (jsonList.length == 4) {
assert(jsonList[3] != null && jsonList[3] is List<dynamic>);
assert((jsonList[3] as List<dynamic>).length == 2);
}
break;
default:
break;
}
}
static const String _defaultMarker = 'defaultMarker';
static const String _fromAsset = 'fromAsset';
static const String _fromAssetImage = 'fromAssetImage';
static const String _fromBytes = 'fromBytes';
static const Set<String> _validTypes = <String>{
_defaultMarker,
_fromAsset,
_fromAssetImage,
_fromBytes,
};
/// Convenience hue value representing red.
static const double hueRed = 0.0;
/// Convenience hue value representing orange.
static const double hueOrange = 30.0;
/// Convenience hue value representing yellow.
static const double hueYellow = 60.0;
/// Convenience hue value representing green.
static const double hueGreen = 120.0;
/// Convenience hue value representing cyan.
static const double hueCyan = 180.0;
/// Convenience hue value representing azure.
static const double hueAzure = 210.0;
/// Convenience hue value representing blue.
static const double hueBlue = 240.0;
/// Convenience hue value representing violet.
static const double hueViolet = 270.0;
/// Convenience hue value representing magenta.
static const double hueMagenta = 300.0;
/// Convenience hue value representing rose.
static const double hueRose = 330.0;
/// Creates a BitmapDescriptor that refers to the default marker image.
static const BitmapDescriptor defaultMarker =
BitmapDescriptor._(<Object>[_defaultMarker]);
/// Creates a BitmapDescriptor that refers to a colorization of the default
/// marker image. For convenience, there is a predefined set of hue values.
/// See e.g. [hueYellow].
static BitmapDescriptor defaultMarkerWithHue(double hue) {
assert(0.0 <= hue && hue < 360.0);
return BitmapDescriptor._(<Object>[_defaultMarker, hue]);
}
/// Creates a [BitmapDescriptor] from an asset image.
///
/// Asset images in flutter are stored per:
/// https://flutter.dev/docs/development/ui/assets-and-images#declaring-resolution-aware-image-assets
/// This method takes into consideration various asset resolutions
/// and scales the images to the right resolution depending on the dpi.
/// Set `mipmaps` to false to load the exact dpi version of the image, `mipmap` is true by default.
static Future<BitmapDescriptor> fromAssetImage(
ImageConfiguration configuration,
String assetName, {
AssetBundle? bundle,
String? package,
bool mipmaps = true,
}) async {
final double? devicePixelRatio = configuration.devicePixelRatio;
if (!mipmaps && devicePixelRatio != null) {
return BitmapDescriptor._(<Object>[
_fromAssetImage,
assetName,
devicePixelRatio,
]);
}
final AssetImage assetImage =
AssetImage(assetName, package: package, bundle: bundle);
final AssetBundleImageKey assetBundleImageKey =
await assetImage.obtainKey(configuration);
final Size? size = configuration.size;
return BitmapDescriptor._(<Object>[
_fromAssetImage,
assetBundleImageKey.name,
assetBundleImageKey.scale,
if (kIsWeb && size != null)
<Object>[
size.width,
size.height,
],
]);
}
/// Creates a BitmapDescriptor using an array of bytes that must be encoded
/// as PNG.
/// On the web, the [size] parameter represents the *physical size* of the
/// bitmap, regardless of the actual resolution of the encoded PNG.
/// This helps the browser to render High-DPI images at the correct size.
/// `size` is not required (and ignored, if passed) in other platforms.
static BitmapDescriptor fromBytes(Uint8List byteData, {Size? size}) {
assert(byteData.isNotEmpty,
'Cannot create BitmapDescriptor with empty byteData');
return BitmapDescriptor._(<Object>[
_fromBytes,
byteData,
if (kIsWeb && size != null)
<Object>[
size.width,
size.height,
]
]);
}
final Object _json;
/// Convert the object to a Json format.
Object toJson() => _json;
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart",
"repo_id": "plugins",
"token_count": 2279
} | 1,273 |
// 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:collection/collection.dart';
import 'package:flutter/foundation.dart'
show immutable, listEquals, VoidCallback;
import 'package:flutter/material.dart' show Color, Colors;
import 'types.dart';
/// Uniquely identifies a [Polygon] among [GoogleMap] polygons.
///
/// This does not have to be globally unique, only unique among the list.
@immutable
class PolygonId extends MapsObjectId<Polygon> {
/// Creates an immutable identifier for a [Polygon].
const PolygonId(String value) : super(value);
}
/// Draws a polygon through geographical locations on the map.
@immutable
class Polygon implements MapsObject<Polygon> {
/// Creates an immutable representation of a polygon through geographical locations on the map.
const Polygon({
required this.polygonId,
this.consumeTapEvents = false,
this.fillColor = Colors.black,
this.geodesic = false,
this.points = const <LatLng>[],
this.holes = const <List<LatLng>>[],
this.strokeColor = Colors.black,
this.strokeWidth = 10,
this.visible = true,
this.zIndex = 0,
this.onTap,
});
/// Uniquely identifies a [Polygon].
final PolygonId polygonId;
@override
PolygonId get mapsId => polygonId;
/// True if the [Polygon] consumes tap events.
///
/// If this is false, [onTap] callback will not be triggered.
final bool consumeTapEvents;
/// Fill color in ARGB format, the same format used by Color. The default value is black (0xff000000).
final Color fillColor;
/// Indicates whether the segments of the polygon should be drawn as geodesics, as opposed to straight lines
/// on the Mercator projection.
///
/// A geodesic is the shortest path between two points on the Earth's surface.
/// The geodesic curve is constructed assuming the Earth is a sphere
final bool geodesic;
/// The vertices of the polygon to be drawn.
///
/// Line segments are drawn between consecutive points. A polygon is not closed by
/// default; to form a closed polygon, the start and end points must be the same.
final List<LatLng> points;
/// To create an empty area within a polygon, you need to use holes.
/// To create the hole, the coordinates defining the hole path must be inside the polygon.
///
/// The vertices of the holes to be cut out of polygon.
///
/// Line segments of each points of hole are drawn inside polygon between consecutive hole points.
final List<List<LatLng>> holes;
/// True if the marker is visible.
final bool visible;
/// Line color in ARGB format, the same format used by Color. The default value is black (0xff000000).
final Color strokeColor;
/// Width of the polygon, used to define the width of the line to be drawn.
///
/// The width is constant and independent of the camera's zoom level.
/// The default value is 10.
final int strokeWidth;
/// The z-index of the polygon, used to determine relative drawing order of
/// map overlays.
///
/// Overlays are drawn in order of z-index, so that lower values means drawn
/// earlier, and thus appearing to be closer to the surface of the Earth.
final int zIndex;
/// Callbacks to receive tap events for polygon placed on this map.
final VoidCallback? onTap;
/// Creates a new [Polygon] object whose values are the same as this instance,
/// unless overwritten by the specified parameters.
Polygon copyWith({
bool? consumeTapEventsParam,
Color? fillColorParam,
bool? geodesicParam,
List<LatLng>? pointsParam,
List<List<LatLng>>? holesParam,
Color? strokeColorParam,
int? strokeWidthParam,
bool? visibleParam,
int? zIndexParam,
VoidCallback? onTapParam,
}) {
return Polygon(
polygonId: polygonId,
consumeTapEvents: consumeTapEventsParam ?? consumeTapEvents,
fillColor: fillColorParam ?? fillColor,
geodesic: geodesicParam ?? geodesic,
points: pointsParam ?? points,
holes: holesParam ?? holes,
strokeColor: strokeColorParam ?? strokeColor,
strokeWidth: strokeWidthParam ?? strokeWidth,
visible: visibleParam ?? visible,
onTap: onTapParam ?? onTap,
zIndex: zIndexParam ?? zIndex,
);
}
/// Creates a new [Polygon] object whose values are the same as this instance.
@override
Polygon clone() {
return copyWith(pointsParam: List<LatLng>.of(points));
}
/// Converts this object to something serializable in JSON.
@override
Object toJson() {
final Map<String, Object> json = <String, Object>{};
void addIfPresent(String fieldName, Object? value) {
if (value != null) {
json[fieldName] = value;
}
}
addIfPresent('polygonId', polygonId.value);
addIfPresent('consumeTapEvents', consumeTapEvents);
addIfPresent('fillColor', fillColor.value);
addIfPresent('geodesic', geodesic);
addIfPresent('strokeColor', strokeColor.value);
addIfPresent('strokeWidth', strokeWidth);
addIfPresent('visible', visible);
addIfPresent('zIndex', zIndex);
if (points != null) {
json['points'] = _pointsToJson();
}
if (holes != null) {
json['holes'] = _holesToJson();
}
return json;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is Polygon &&
polygonId == other.polygonId &&
consumeTapEvents == other.consumeTapEvents &&
fillColor == other.fillColor &&
geodesic == other.geodesic &&
listEquals(points, other.points) &&
const DeepCollectionEquality().equals(holes, other.holes) &&
visible == other.visible &&
strokeColor == other.strokeColor &&
strokeWidth == other.strokeWidth &&
zIndex == other.zIndex;
}
@override
int get hashCode => polygonId.hashCode;
Object _pointsToJson() {
final List<Object> result = <Object>[];
for (final LatLng point in points) {
result.add(point.toJson());
}
return result;
}
List<List<Object>> _holesToJson() {
final List<List<Object>> result = <List<Object>>[];
for (final List<LatLng> hole in holes) {
final List<Object> jsonHole = <Object>[];
for (final LatLng point in hole) {
jsonHole.add(point.toJson());
}
result.add(jsonHole);
}
return result;
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon.dart",
"repo_id": "plugins",
"token_count": 2160
} | 1,274 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../types.dart';
import 'maps_object.dart';
/// Converts an [Iterable] of Polylines in a Map of PolylineId -> Polyline.
Map<PolylineId, Polyline> keyByPolylineId(Iterable<Polyline> polylines) {
return keyByMapsObjectId<Polyline>(polylines).cast<PolylineId, Polyline>();
}
/// Converts a Set of Polylines into something serializable in JSON.
Object serializePolylineSet(Set<Polyline> polylines) {
return serializeMapsObjectSet(polylines);
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/polyline.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/polyline.dart",
"repo_id": "plugins",
"token_count": 186
} | 1,275 |
// 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_test/flutter_test.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps_flutter_web/google_maps_flutter_web.dart';
import 'package:integration_test/integration_test.dart';
/// Test Shapes (Circle, Polygon, Polyline)
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// Since onTap events happen asynchronously, we need to store when the event
// is fired. We use a completer so the test can wait for the future to be completed.
late Completer<bool> methodCalledCompleter;
/// This is the future value of the [methodCalledCompleter]. Reinitialized
/// in the [setUp] method, and completed (as `true`) by [onTap], when it gets
/// called by the corresponding Shape Controller.
late Future<bool> methodCalled;
void onTap() {
methodCalledCompleter.complete(true);
}
setUp(() {
methodCalledCompleter = Completer<bool>();
methodCalled = methodCalledCompleter.future;
});
group('CircleController', () {
late gmaps.Circle circle;
setUp(() {
circle = gmaps.Circle();
});
testWidgets('onTap gets called', (WidgetTester tester) async {
CircleController(circle: circle, consumeTapEvents: true, onTap: onTap);
// Trigger a click event...
gmaps.Event.trigger(circle, 'click', <Object?>[gmaps.MapMouseEvent()]);
// The event handling is now truly async. Wait for it...
expect(await methodCalled, isTrue);
});
testWidgets('update', (WidgetTester tester) async {
final CircleController controller = CircleController(circle: circle);
final gmaps.CircleOptions options = gmaps.CircleOptions()
..draggable = true;
expect(circle.draggable, isNull);
controller.update(options);
expect(circle.draggable, isTrue);
});
group('remove', () {
late CircleController controller;
setUp(() {
controller = CircleController(circle: circle);
});
testWidgets('drops gmaps instance', (WidgetTester tester) async {
controller.remove();
expect(controller.circle, isNull);
});
testWidgets('cannot call update after remove',
(WidgetTester tester) async {
final gmaps.CircleOptions options = gmaps.CircleOptions()
..draggable = true;
controller.remove();
expect(() {
controller.update(options);
}, throwsAssertionError);
});
});
});
group('PolygonController', () {
late gmaps.Polygon polygon;
setUp(() {
polygon = gmaps.Polygon();
});
testWidgets('onTap gets called', (WidgetTester tester) async {
PolygonController(polygon: polygon, consumeTapEvents: true, onTap: onTap);
// Trigger a click event...
gmaps.Event.trigger(polygon, 'click', <Object?>[gmaps.MapMouseEvent()]);
// The event handling is now truly async. Wait for it...
expect(await methodCalled, isTrue);
});
testWidgets('update', (WidgetTester tester) async {
final PolygonController controller = PolygonController(polygon: polygon);
final gmaps.PolygonOptions options = gmaps.PolygonOptions()
..draggable = true;
expect(polygon.draggable, isNull);
controller.update(options);
expect(polygon.draggable, isTrue);
});
group('remove', () {
late PolygonController controller;
setUp(() {
controller = PolygonController(polygon: polygon);
});
testWidgets('drops gmaps instance', (WidgetTester tester) async {
controller.remove();
expect(controller.polygon, isNull);
});
testWidgets('cannot call update after remove',
(WidgetTester tester) async {
final gmaps.PolygonOptions options = gmaps.PolygonOptions()
..draggable = true;
controller.remove();
expect(() {
controller.update(options);
}, throwsAssertionError);
});
});
});
group('PolylineController', () {
late gmaps.Polyline polyline;
setUp(() {
polyline = gmaps.Polyline();
});
testWidgets('onTap gets called', (WidgetTester tester) async {
PolylineController(
polyline: polyline,
consumeTapEvents: true,
onTap: onTap,
);
// Trigger a click event...
gmaps.Event.trigger(polyline, 'click', <Object?>[gmaps.MapMouseEvent()]);
// The event handling is now truly async. Wait for it...
expect(await methodCalled, isTrue);
});
testWidgets('update', (WidgetTester tester) async {
final PolylineController controller = PolylineController(
polyline: polyline,
);
final gmaps.PolylineOptions options = gmaps.PolylineOptions()
..draggable = true;
expect(polyline.draggable, isNull);
controller.update(options);
expect(polyline.draggable, isTrue);
});
group('remove', () {
late PolylineController controller;
setUp(() {
controller = PolylineController(polyline: polyline);
});
testWidgets('drops gmaps instance', (WidgetTester tester) async {
controller.remove();
expect(controller.line, isNull);
});
testWidgets('cannot call update after remove',
(WidgetTester tester) async {
final gmaps.PolylineOptions options = gmaps.PolylineOptions()
..draggable = true;
controller.remove();
expect(() {
controller.update(options);
}, throwsAssertionError);
});
});
});
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart",
"repo_id": "plugins",
"token_count": 2164
} | 1,276 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of google_maps_flutter_web;
/// The `PolygonController` class wraps a [gmaps.Polygon] and its `onTap` behavior.
class PolygonController {
/// Creates a `PolygonController` that wraps a [gmaps.Polygon] object and its `onTap` behavior.
PolygonController({
required gmaps.Polygon polygon,
bool consumeTapEvents = false,
ui.VoidCallback? onTap,
}) : _polygon = polygon,
_consumeTapEvents = consumeTapEvents {
if (onTap != null) {
polygon.onClick.listen((gmaps.PolyMouseEvent event) {
onTap.call();
});
}
}
gmaps.Polygon? _polygon;
final bool _consumeTapEvents;
/// Returns the wrapped [gmaps.Polygon]. Only used for testing.
@visibleForTesting
gmaps.Polygon? get polygon => _polygon;
/// Returns `true` if this Controller will use its own `onTap` handler to consume events.
bool get consumeTapEvents => _consumeTapEvents;
/// Updates the options of the wrapped [gmaps.Polygon] object.
///
/// This cannot be called after [remove].
void update(gmaps.PolygonOptions options) {
assert(_polygon != null, 'Cannot `update` Polygon after calling `remove`.');
_polygon!.options = options;
}
/// Disposes of the currently wrapped [gmaps.Polygon].
void remove() {
if (_polygon != null) {
_polygon!.visible = false;
_polygon!.map = null;
_polygon = null;
}
}
}
| plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polygon.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polygon.dart",
"repo_id": "plugins",
"token_count": 525
} | 1,277 |
name: google_sign_in
description: Flutter plugin for Google Sign-In, a secure authentication system
for signing in with a Google account on Android and iOS.
repository: https://github.com/flutter/plugins/tree/main/packages/google_sign_in/google_sign_in
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22
version: 6.0.0
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
default_package: google_sign_in_android
ios:
default_package: google_sign_in_ios
web:
default_package: google_sign_in_web
dependencies:
flutter:
sdk: flutter
google_sign_in_android: ^6.1.0
google_sign_in_ios: ^5.5.0
google_sign_in_platform_interface: ^2.2.0
google_sign_in_web: ^0.11.0
dev_dependencies:
build_runner: ^2.1.10
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
http: ^0.13.0
integration_test:
sdk: flutter
mockito: ^5.1.0
# The example deliberately includes limited-use secrets.
false_secrets:
- /example/android/app/google-services.json
- /example/ios/Runner/GoogleService-Info.plist
- /example/ios/RunnerTests/GoogleSignInTests.m
- /example/lib/main.dart
- /example/web/index.html
| plugins/packages/google_sign_in/google_sign_in/pubspec.yaml/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/pubspec.yaml",
"repo_id": "plugins",
"token_count": 530
} | 1,278 |
// 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.googlesignin;
import android.accounts.Account;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.RuntimeExecutionException;
import com.google.android.gms.tasks.Task;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/** Google sign-in plugin for Flutter. */
public class GoogleSignInPlugin implements MethodCallHandler, FlutterPlugin, ActivityAware {
private static final String CHANNEL_NAME = "plugins.flutter.io/google_sign_in_android";
private static final String METHOD_INIT = "init";
private static final String METHOD_SIGN_IN_SILENTLY = "signInSilently";
private static final String METHOD_SIGN_IN = "signIn";
private static final String METHOD_GET_TOKENS = "getTokens";
private static final String METHOD_SIGN_OUT = "signOut";
private static final String METHOD_DISCONNECT = "disconnect";
private static final String METHOD_IS_SIGNED_IN = "isSignedIn";
private static final String METHOD_CLEAR_AUTH_CACHE = "clearAuthCache";
private static final String METHOD_REQUEST_SCOPES = "requestScopes";
private Delegate delegate;
private MethodChannel channel;
private ActivityPluginBinding activityPluginBinding;
@SuppressWarnings("deprecation")
public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
GoogleSignInPlugin instance = new GoogleSignInPlugin();
instance.initInstance(registrar.messenger(), registrar.context(), new GoogleSignInWrapper());
instance.setUpRegistrar(registrar);
}
@VisibleForTesting
public void initInstance(
BinaryMessenger messenger, Context context, GoogleSignInWrapper googleSignInWrapper) {
channel = new MethodChannel(messenger, CHANNEL_NAME);
delegate = new Delegate(context, googleSignInWrapper);
channel.setMethodCallHandler(this);
}
@VisibleForTesting
@SuppressWarnings("deprecation")
public void setUpRegistrar(PluginRegistry.Registrar registrar) {
delegate.setUpRegistrar(registrar);
}
private void dispose() {
delegate = null;
channel.setMethodCallHandler(null);
channel = null;
}
private void attachToActivity(ActivityPluginBinding activityPluginBinding) {
this.activityPluginBinding = activityPluginBinding;
activityPluginBinding.addActivityResultListener(delegate);
delegate.setActivity(activityPluginBinding.getActivity());
}
private void disposeActivity() {
activityPluginBinding.removeActivityResultListener(delegate);
delegate.setActivity(null);
activityPluginBinding = null;
}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
initInstance(
binding.getBinaryMessenger(), binding.getApplicationContext(), new GoogleSignInWrapper());
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
dispose();
}
@Override
public void onAttachedToActivity(ActivityPluginBinding activityPluginBinding) {
attachToActivity(activityPluginBinding);
}
@Override
public void onDetachedFromActivityForConfigChanges() {
disposeActivity();
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding activityPluginBinding) {
attachToActivity(activityPluginBinding);
}
@Override
public void onDetachedFromActivity() {
disposeActivity();
}
@Override
public void onMethodCall(MethodCall call, Result result) {
switch (call.method) {
case METHOD_INIT:
String signInOption = call.argument("signInOption");
List<String> requestedScopes = call.argument("scopes");
String hostedDomain = call.argument("hostedDomain");
String clientId = call.argument("clientId");
String serverClientId = call.argument("serverClientId");
boolean forceCodeForRefreshToken = call.argument("forceCodeForRefreshToken");
delegate.init(
result,
signInOption,
requestedScopes,
hostedDomain,
clientId,
serverClientId,
forceCodeForRefreshToken);
break;
case METHOD_SIGN_IN_SILENTLY:
delegate.signInSilently(result);
break;
case METHOD_SIGN_IN:
delegate.signIn(result);
break;
case METHOD_GET_TOKENS:
String email = call.argument("email");
boolean shouldRecoverAuth = call.argument("shouldRecoverAuth");
delegate.getTokens(result, email, shouldRecoverAuth);
break;
case METHOD_SIGN_OUT:
delegate.signOut(result);
break;
case METHOD_CLEAR_AUTH_CACHE:
String token = call.argument("token");
delegate.clearAuthCache(result, token);
break;
case METHOD_DISCONNECT:
delegate.disconnect(result);
break;
case METHOD_IS_SIGNED_IN:
delegate.isSignedIn(result);
break;
case METHOD_REQUEST_SCOPES:
List<String> scopes = call.argument("scopes");
delegate.requestScopes(result, scopes);
break;
default:
result.notImplemented();
}
}
/**
* A delegate interface that exposes all of the sign-in functionality for other plugins to use.
* The below {@link Delegate} implementation should be used by any clients unless they need to
* override some of these functions, such as for testing.
*/
public interface IDelegate {
/** Initializes this delegate so that it is ready to perform other operations. */
public void init(
Result result,
String signInOption,
List<String> requestedScopes,
String hostedDomain,
String clientId,
String serverClientId,
boolean forceCodeForRefreshToken);
/**
* Returns the account information for the user who is signed in to this app. If no user is
* signed in, tries to sign the user in without displaying any user interface.
*/
public void signInSilently(Result result);
/**
* Signs the user in via the sign-in user interface, including the OAuth consent flow if scopes
* were requested.
*/
public void signIn(Result result);
/**
* Gets an OAuth access token with the scopes that were specified during initialization for the
* user with the specified email address.
*
* <p>If shouldRecoverAuth is set to true and user needs to recover authentication for method to
* complete, the method will attempt to recover authentication and rerun method.
*/
public void getTokens(final Result result, final String email, final boolean shouldRecoverAuth);
/**
* Clears the token from any client cache forcing the next {@link #getTokens} call to fetch a
* new one.
*/
public void clearAuthCache(final Result result, final String token);
/**
* Signs the user out. Their credentials may remain valid, meaning they'll be able to silently
* sign back in.
*/
public void signOut(Result result);
/** Signs the user out, and revokes their credentials. */
public void disconnect(Result result);
/** Checks if there is a signed in user. */
public void isSignedIn(Result result);
/** Prompts the user to grant an additional Oauth scopes. */
public void requestScopes(final Result result, final List<String> scopes);
}
/**
* Delegate class that does the work for the Google sign-in plugin. This is exposed as a dedicated
* class for use in other plugins that wrap basic sign-in functionality.
*
* <p>All methods in this class assume that they are run to completion before any other method is
* invoked. In this context, "run to completion" means that their {@link Result} argument has been
* completed (either successfully or in error). This class provides no synchronization constructs
* to guarantee such behavior; callers are responsible for providing such guarantees.
*/
public static class Delegate implements IDelegate, PluginRegistry.ActivityResultListener {
private static final int REQUEST_CODE_SIGNIN = 53293;
private static final int REQUEST_CODE_RECOVER_AUTH = 53294;
@VisibleForTesting static final int REQUEST_CODE_REQUEST_SCOPE = 53295;
private static final String ERROR_REASON_EXCEPTION = "exception";
private static final String ERROR_REASON_STATUS = "status";
// These error codes must match with ones declared on iOS and Dart sides.
private static final String ERROR_REASON_SIGN_IN_CANCELED = "sign_in_canceled";
private static final String ERROR_REASON_SIGN_IN_REQUIRED = "sign_in_required";
private static final String ERROR_REASON_NETWORK_ERROR = "network_error";
private static final String ERROR_REASON_SIGN_IN_FAILED = "sign_in_failed";
private static final String ERROR_FAILURE_TO_RECOVER_AUTH = "failed_to_recover_auth";
private static final String ERROR_USER_RECOVERABLE_AUTH = "user_recoverable_auth";
private static final String DEFAULT_SIGN_IN = "SignInOption.standard";
private static final String DEFAULT_GAMES_SIGN_IN = "SignInOption.games";
private final Context context;
// Only set registrar for v1 embedder.
@SuppressWarnings("deprecation")
private PluginRegistry.Registrar registrar;
// Only set activity for v2 embedder. Always access activity from getActivity() method.
private Activity activity;
private final BackgroundTaskRunner backgroundTaskRunner = new BackgroundTaskRunner(1);
private final GoogleSignInWrapper googleSignInWrapper;
private GoogleSignInClient signInClient;
private List<String> requestedScopes;
private PendingOperation pendingOperation;
public Delegate(Context context, GoogleSignInWrapper googleSignInWrapper) {
this.context = context;
this.googleSignInWrapper = googleSignInWrapper;
}
@SuppressWarnings("deprecation")
public void setUpRegistrar(PluginRegistry.Registrar registrar) {
this.registrar = registrar;
registrar.addActivityResultListener(this);
}
public void setActivity(Activity activity) {
this.activity = activity;
}
// Only access activity with this method.
public Activity getActivity() {
return registrar != null ? registrar.activity() : activity;
}
private void checkAndSetPendingOperation(String method, Result result) {
checkAndSetPendingOperation(method, result, null);
}
private void checkAndSetPendingOperation(String method, Result result, Object data) {
if (pendingOperation != null) {
throw new IllegalStateException(
"Concurrent operations detected: " + pendingOperation.method + ", " + method);
}
pendingOperation = new PendingOperation(method, result, data);
}
/**
* Initializes this delegate so that it is ready to perform other operations. The Dart code
* guarantees that this will be called and completed before any other methods are invoked.
*/
@Override
public void init(
Result result,
String signInOption,
List<String> requestedScopes,
String hostedDomain,
String clientId,
String serverClientId,
boolean forceCodeForRefreshToken) {
try {
GoogleSignInOptions.Builder optionsBuilder;
switch (signInOption) {
case DEFAULT_GAMES_SIGN_IN:
optionsBuilder =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
break;
case DEFAULT_SIGN_IN:
optionsBuilder =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail();
break;
default:
throw new IllegalStateException("Unknown signInOption");
}
// The clientId parameter is not supported on Android.
// Android apps are identified by their package name and the SHA-1 of their signing key.
// https://developers.google.com/android/guides/client-auth
// https://developers.google.com/identity/sign-in/android/start#configure-a-google-api-project
if (!Strings.isNullOrEmpty(clientId) && Strings.isNullOrEmpty(serverClientId)) {
Log.w(
"google_sign_in",
"clientId is not supported on Android and is interpreted as serverClientId. "
+ "Use serverClientId instead to suppress this warning.");
serverClientId = clientId;
}
if (Strings.isNullOrEmpty(serverClientId)) {
// Only requests a clientId if google-services.json was present and parsed
// by the google-services Gradle script.
// TODO(jackson): Perhaps we should provide a mechanism to override this
// behavior.
int webClientIdIdentifier =
context
.getResources()
.getIdentifier("default_web_client_id", "string", context.getPackageName());
if (webClientIdIdentifier != 0) {
serverClientId = context.getString(webClientIdIdentifier);
}
}
if (!Strings.isNullOrEmpty(serverClientId)) {
optionsBuilder.requestIdToken(serverClientId);
optionsBuilder.requestServerAuthCode(serverClientId, forceCodeForRefreshToken);
}
for (String scope : requestedScopes) {
optionsBuilder.requestScopes(new Scope(scope));
}
if (!Strings.isNullOrEmpty(hostedDomain)) {
optionsBuilder.setHostedDomain(hostedDomain);
}
this.requestedScopes = requestedScopes;
signInClient = googleSignInWrapper.getClient(context, optionsBuilder.build());
result.success(null);
} catch (Exception e) {
result.error(ERROR_REASON_EXCEPTION, e.getMessage(), null);
}
}
/**
* Returns the account information for the user who is signed in to this app. If no user is
* signed in, tries to sign the user in without displaying any user interface.
*/
@Override
public void signInSilently(Result result) {
checkAndSetPendingOperation(METHOD_SIGN_IN_SILENTLY, result);
Task<GoogleSignInAccount> task = signInClient.silentSignIn();
if (task.isComplete()) {
// There's immediate result available.
onSignInResult(task);
} else {
task.addOnCompleteListener(
new OnCompleteListener<GoogleSignInAccount>() {
@Override
public void onComplete(Task<GoogleSignInAccount> task) {
onSignInResult(task);
}
});
}
}
/**
* Signs the user in via the sign-in user interface, including the OAuth consent flow if scopes
* were requested.
*/
@Override
public void signIn(Result result) {
if (getActivity() == null) {
throw new IllegalStateException("signIn needs a foreground activity");
}
checkAndSetPendingOperation(METHOD_SIGN_IN, result);
Intent signInIntent = signInClient.getSignInIntent();
getActivity().startActivityForResult(signInIntent, REQUEST_CODE_SIGNIN);
}
/**
* Signs the user out. Their credentials may remain valid, meaning they'll be able to silently
* sign back in.
*/
@Override
public void signOut(Result result) {
checkAndSetPendingOperation(METHOD_SIGN_OUT, result);
signInClient
.signOut()
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
finishWithSuccess(null);
} else {
finishWithError(ERROR_REASON_STATUS, "Failed to signout.");
}
}
});
}
/** Signs the user out, and revokes their credentials. */
@Override
public void disconnect(Result result) {
checkAndSetPendingOperation(METHOD_DISCONNECT, result);
signInClient
.revokeAccess()
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
finishWithSuccess(null);
} else {
finishWithError(ERROR_REASON_STATUS, "Failed to disconnect.");
}
}
});
}
/** Checks if there is a signed in user. */
@Override
public void isSignedIn(final Result result) {
boolean value = GoogleSignIn.getLastSignedInAccount(context) != null;
result.success(value);
}
@Override
public void requestScopes(Result result, List<String> scopes) {
checkAndSetPendingOperation(METHOD_REQUEST_SCOPES, result);
GoogleSignInAccount account = googleSignInWrapper.getLastSignedInAccount(context);
if (account == null) {
finishWithError(ERROR_REASON_SIGN_IN_REQUIRED, "No account to grant scopes.");
return;
}
List<Scope> wrappedScopes = new ArrayList<>();
for (String scope : scopes) {
Scope wrappedScope = new Scope(scope);
if (!googleSignInWrapper.hasPermissions(account, wrappedScope)) {
wrappedScopes.add(wrappedScope);
}
}
if (wrappedScopes.isEmpty()) {
finishWithSuccess(true);
return;
}
googleSignInWrapper.requestPermissions(
getActivity(), REQUEST_CODE_REQUEST_SCOPE, account, wrappedScopes.toArray(new Scope[0]));
}
private void onSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
onSignInAccount(account);
} catch (ApiException e) {
// Forward all errors and let Dart decide how to handle.
String errorCode = errorCodeForStatus(e.getStatusCode());
finishWithError(errorCode, e.toString());
} catch (RuntimeExecutionException e) {
finishWithError(ERROR_REASON_EXCEPTION, e.toString());
}
}
private void onSignInAccount(GoogleSignInAccount account) {
Map<String, Object> response = new HashMap<>();
response.put("email", account.getEmail());
response.put("id", account.getId());
response.put("idToken", account.getIdToken());
response.put("serverAuthCode", account.getServerAuthCode());
response.put("displayName", account.getDisplayName());
if (account.getPhotoUrl() != null) {
response.put("photoUrl", account.getPhotoUrl().toString());
}
finishWithSuccess(response);
}
private String errorCodeForStatus(int statusCode) {
switch (statusCode) {
case GoogleSignInStatusCodes.SIGN_IN_CANCELLED:
return ERROR_REASON_SIGN_IN_CANCELED;
case CommonStatusCodes.SIGN_IN_REQUIRED:
return ERROR_REASON_SIGN_IN_REQUIRED;
case CommonStatusCodes.NETWORK_ERROR:
return ERROR_REASON_NETWORK_ERROR;
case GoogleSignInStatusCodes.SIGN_IN_CURRENTLY_IN_PROGRESS:
case GoogleSignInStatusCodes.SIGN_IN_FAILED:
case CommonStatusCodes.INVALID_ACCOUNT:
case CommonStatusCodes.INTERNAL_ERROR:
return ERROR_REASON_SIGN_IN_FAILED;
default:
return ERROR_REASON_SIGN_IN_FAILED;
}
}
private void finishWithSuccess(Object data) {
pendingOperation.result.success(data);
pendingOperation = null;
}
private void finishWithError(String errorCode, String errorMessage) {
pendingOperation.result.error(errorCode, errorMessage, null);
pendingOperation = null;
}
private static class PendingOperation {
final String method;
final Result result;
final Object data;
PendingOperation(String method, Result result, Object data) {
this.method = method;
this.result = result;
this.data = data;
}
}
/** Clears the token kept in the client side cache. */
@Override
public void clearAuthCache(final Result result, final String token) {
Callable<Void> clearTokenTask =
new Callable<Void>() {
@Override
public Void call() throws Exception {
GoogleAuthUtil.clearToken(context, token);
return null;
}
};
backgroundTaskRunner.runInBackground(
clearTokenTask,
new BackgroundTaskRunner.Callback<Void>() {
@Override
public void run(Future<Void> clearTokenFuture) {
try {
result.success(clearTokenFuture.get());
} catch (ExecutionException e) {
result.error(ERROR_REASON_EXCEPTION, e.getCause().getMessage(), null);
} catch (InterruptedException e) {
result.error(ERROR_REASON_EXCEPTION, e.getMessage(), null);
Thread.currentThread().interrupt();
}
}
});
}
/**
* Gets an OAuth access token with the scopes that were specified during initialization for the
* user with the specified email address.
*
* <p>If shouldRecoverAuth is set to true and user needs to recover authentication for method to
* complete, the method will attempt to recover authentication and rerun method.
*/
@Override
public void getTokens(
final Result result, final String email, final boolean shouldRecoverAuth) {
if (email == null) {
result.error(ERROR_REASON_EXCEPTION, "Email is null", null);
return;
}
Callable<String> getTokenTask =
new Callable<String>() {
@Override
public String call() throws Exception {
Account account = new Account(email, "com.google");
String scopesStr = "oauth2:" + Joiner.on(' ').join(requestedScopes);
return GoogleAuthUtil.getToken(context, account, scopesStr);
}
};
// Background task runner has a single thread effectively serializing
// the getToken calls. 1p apps can then enjoy the token cache if multiple
// getToken calls are coming in.
backgroundTaskRunner.runInBackground(
getTokenTask,
new BackgroundTaskRunner.Callback<String>() {
@Override
public void run(Future<String> tokenFuture) {
try {
String token = tokenFuture.get();
HashMap<String, String> tokenResult = new HashMap<>();
tokenResult.put("accessToken", token);
result.success(tokenResult);
} catch (ExecutionException e) {
if (e.getCause() instanceof UserRecoverableAuthException) {
if (shouldRecoverAuth && pendingOperation == null) {
Activity activity = getActivity();
if (activity == null) {
result.error(
ERROR_USER_RECOVERABLE_AUTH,
"Cannot recover auth because app is not in foreground. "
+ e.getLocalizedMessage(),
null);
} else {
checkAndSetPendingOperation(METHOD_GET_TOKENS, result, email);
Intent recoveryIntent =
((UserRecoverableAuthException) e.getCause()).getIntent();
activity.startActivityForResult(recoveryIntent, REQUEST_CODE_RECOVER_AUTH);
}
} else {
result.error(ERROR_USER_RECOVERABLE_AUTH, e.getLocalizedMessage(), null);
}
} else {
result.error(ERROR_REASON_EXCEPTION, e.getCause().getMessage(), null);
}
} catch (InterruptedException e) {
result.error(ERROR_REASON_EXCEPTION, e.getMessage(), null);
Thread.currentThread().interrupt();
}
}
});
}
@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (pendingOperation == null) {
return false;
}
switch (requestCode) {
case REQUEST_CODE_RECOVER_AUTH:
if (resultCode == Activity.RESULT_OK) {
// Recover the previous result and data and attempt to get tokens again.
Result result = pendingOperation.result;
String email = (String) pendingOperation.data;
pendingOperation = null;
getTokens(result, email, false);
} else {
finishWithError(
ERROR_FAILURE_TO_RECOVER_AUTH, "Failed attempt to recover authentication");
}
return true;
case REQUEST_CODE_SIGNIN:
// Whether resultCode is OK or not, the Task returned by GoogleSigIn will determine
// failure with better specifics which are extracted in onSignInResult method.
if (data != null) {
onSignInResult(GoogleSignIn.getSignedInAccountFromIntent(data));
} else {
// data is null which is highly unusual for a sign in result.
finishWithError(ERROR_REASON_SIGN_IN_FAILED, "Signin failed");
}
return true;
case REQUEST_CODE_REQUEST_SCOPE:
finishWithSuccess(resultCode == Activity.RESULT_OK);
return true;
default:
return false;
}
}
}
}
| plugins/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/GoogleSignInPlugin.java/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_android/android/src/main/java/io/flutter/plugins/googlesignin/GoogleSignInPlugin.java",
"repo_id": "plugins",
"token_count": 10470
} | 1,279 |
framework module google_sign_in_ios {
umbrella header "google_sign_in_ios-umbrella.h"
export *
module * { export * }
explicit module Test {
header "FLTGoogleSignInPlugin_Test.h"
}
}
| plugins/packages/google_sign_in/google_sign_in_ios/ios/Classes/FLTGoogleSignInPlugin.modulemap/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_ios/ios/Classes/FLTGoogleSignInPlugin.modulemap",
"repo_id": "plugins",
"token_count": 69
} | 1,280 |
name: google_sign_in_platform_interface
description: A common platform interface for the google_sign_in plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/google_sign_in/google_sign_in_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 2.3.0
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.0
quiver: ^3.0.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.0
| plugins/packages/google_sign_in/google_sign_in_platform_interface/pubspec.yaml/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_platform_interface/pubspec.yaml",
"repo_id": "plugins",
"token_count": 283
} | 1,281 |
// 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:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_identity_services_web/id.dart';
import 'package:google_identity_services_web/oauth2.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:google_sign_in_web/src/utils.dart';
import 'package:integration_test/integration_test.dart';
import 'src/jsify_as.dart';
import 'src/jwt_examples.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('gisResponsesToTokenData', () {
testWidgets('null objects -> no problem', (_) async {
final GoogleSignInTokenData tokens = gisResponsesToTokenData(null, null);
expect(tokens.accessToken, isNull);
expect(tokens.idToken, isNull);
expect(tokens.serverAuthCode, isNull);
});
testWidgets('non-null objects are correctly used', (_) async {
const String expectedIdToken = 'some-value-for-testing';
const String expectedAccessToken = 'another-value-for-testing';
final CredentialResponse credential =
jsifyAs<CredentialResponse>(<String, Object?>{
'credential': expectedIdToken,
});
final TokenResponse token = jsifyAs<TokenResponse>(<String, Object?>{
'access_token': expectedAccessToken,
});
final GoogleSignInTokenData tokens =
gisResponsesToTokenData(credential, token);
expect(tokens.accessToken, expectedAccessToken);
expect(tokens.idToken, expectedIdToken);
expect(tokens.serverAuthCode, isNull);
});
});
group('gisResponsesToUserData', () {
testWidgets('happy case', (_) async {
final GoogleSignInUserData data = gisResponsesToUserData(goodCredential)!;
expect(data.displayName, 'Vincent Adultman');
expect(data.id, '123456');
expect(data.email, 'adultman@example.com');
expect(data.photoUrl, 'https://thispersondoesnotexist.com/image?x=.jpg');
expect(data.idToken, goodJwtToken);
});
testWidgets('null response -> null', (_) async {
expect(gisResponsesToUserData(null), isNull);
});
testWidgets('null response.credential -> null', (_) async {
expect(gisResponsesToUserData(nullCredential), isNull);
});
testWidgets('invalid payload -> null', (_) async {
final CredentialResponse response =
jsifyAs<CredentialResponse>(<String, Object?>{
'credential': 'some-bogus.thing-that-is-not.valid-jwt',
});
expect(gisResponsesToUserData(response), isNull);
});
});
group('getJwtTokenPayload', () {
testWidgets('happy case -> data', (_) async {
final Map<String, Object?>? data = getJwtTokenPayload(goodJwtToken);
expect(data, isNotNull);
expect(data, containsPair('name', 'Vincent Adultman'));
expect(data, containsPair('email', 'adultman@example.com'));
expect(data, containsPair('sub', '123456'));
expect(
data,
containsPair(
'picture',
'https://thispersondoesnotexist.com/image?x=.jpg',
));
});
testWidgets('null Token -> null', (_) async {
final Map<String, Object?>? data = getJwtTokenPayload(null);
expect(data, isNull);
});
testWidgets('Token not matching the format -> null', (_) async {
final Map<String, Object?>? data = getJwtTokenPayload('1234.4321');
expect(data, isNull);
});
testWidgets('Bad token that matches the format -> null', (_) async {
final Map<String, Object?>? data = getJwtTokenPayload('1234.abcd.4321');
expect(data, isNull);
});
});
group('decodeJwtPayload', () {
testWidgets('Good payload -> data', (_) async {
final Map<String, Object?>? data = decodeJwtPayload(goodPayload);
expect(data, isNotNull);
expect(data, containsPair('name', 'Vincent Adultman'));
expect(data, containsPair('email', 'adultman@example.com'));
expect(data, containsPair('sub', '123456'));
expect(
data,
containsPair(
'picture',
'https://thispersondoesnotexist.com/image?x=.jpg',
));
});
testWidgets('Proper JSON payload -> data', (_) async {
final String payload = base64.encode(utf8.encode('{"properJson": true}'));
final Map<String, Object?>? data = decodeJwtPayload(payload);
expect(data, isNotNull);
expect(data, containsPair('properJson', true));
});
testWidgets('Not-normalized base-64 payload -> data', (_) async {
// This is the payload generated by the "Proper JSON payload" test, but
// we remove the leading "=" symbols so it's length is not a multiple of 4
// anymore!
final String payload = 'eyJwcm9wZXJKc29uIjogdHJ1ZX0='.replaceAll('=', '');
final Map<String, Object?>? data = decodeJwtPayload(payload);
expect(data, isNotNull);
expect(data, containsPair('properJson', true));
});
testWidgets('Invalid JSON payload -> null', (_) async {
final String payload = base64.encode(utf8.encode('{properJson: false}'));
final Map<String, Object?>? data = decodeJwtPayload(payload);
expect(data, isNull);
});
testWidgets('Non JSON payload -> null', (_) async {
final String payload = base64.encode(utf8.encode('not-json'));
final Map<String, Object?>? data = decodeJwtPayload(payload);
expect(data, isNull);
});
testWidgets('Non base-64 payload -> null', (_) async {
const String payload = 'not-base-64-at-all';
final Map<String, Object?>? data = decodeJwtPayload(payload);
expect(data, isNull);
});
});
}
| plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart",
"repo_id": "plugins",
"token_count": 2285
} | 1,282 |
// 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.
/*
* Copyright (C) 2007-2008 OpenIntents.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file was modified by the Flutter authors from the following original file:
* https://raw.githubusercontent.com/iPaulPro/aFileChooser/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
*/
package io.flutter.plugins.imagepicker;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
import io.flutter.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
class FileUtils {
/**
* Copies the file from the given content URI to a temporary directory, retaining the original
* file name if possible.
*
* <p>Each file is placed in its own directory to avoid conflicts according to the following
* scheme: {cacheDir}/{randomUuid}/{fileName}
*
* <p>If the original file name is unknown, a predefined "image_picker" filename is used and the
* file extension is deduced from the mime type (with fallback to ".jpg" in case of failure).
*/
String getPathFromUri(final Context context, final Uri uri) {
try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) {
String uuid = UUID.randomUUID().toString();
File targetDirectory = new File(context.getCacheDir(), uuid);
targetDirectory.mkdir();
// TODO(SynSzakala) according to the docs, `deleteOnExit` does not work reliably on Android; we should preferably
// just clear the picked files after the app startup.
targetDirectory.deleteOnExit();
String fileName = getImageName(context, uri);
if (fileName == null) {
Log.w("FileUtils", "Cannot get file name for " + uri);
fileName = "image_picker" + getImageExtension(context, uri);
}
File file = new File(targetDirectory, fileName);
try (OutputStream outputStream = new FileOutputStream(file)) {
copy(inputStream, outputStream);
return file.getPath();
}
} catch (IOException e) {
// If closing the output stream fails, we cannot be sure that the
// target file was written in full. Flushing the stream merely moves
// the bytes into the OS, not necessarily to the file.
return null;
}
}
/** @return extension of image with dot, or default .jpg if it none. */
private static String getImageExtension(Context context, Uri uriImage) {
String extension;
try {
if (uriImage.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uriImage));
} else {
extension =
MimeTypeMap.getFileExtensionFromUrl(
Uri.fromFile(new File(uriImage.getPath())).toString());
}
} catch (Exception e) {
extension = null;
}
if (extension == null || extension.isEmpty()) {
//default extension for matches the previous behavior of the plugin
extension = "jpg";
}
return "." + extension;
}
/** @return name of the image provided by ContentResolver; this may be null. */
private static String getImageName(Context context, Uri uriImage) {
try (Cursor cursor = queryImageName(context, uriImage)) {
if (cursor == null || !cursor.moveToFirst() || cursor.getColumnCount() < 1) return null;
return cursor.getString(0);
}
}
private static Cursor queryImageName(Context context, Uri uriImage) {
return context
.getContentResolver()
.query(uriImage, new String[] {MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
}
private static void copy(InputStream in, OutputStream out) throws IOException {
final byte[] buffer = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
}
}
| plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/FileUtils.java/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/FileUtils.java",
"repo_id": "plugins",
"token_count": 1587
} | 1,283 |
# image\_picker\_for\_web
A web implementation of [`image_picker`][1].
## Limitations on the web platform
Since Web Browsers don't offer direct access to their users' file system,
this plugin provides a `PickedFile` abstraction to make access uniform
across platforms.
The web version of the plugin puts network-accessible URIs as the `path`
in the returned `PickedFile`.
### URL.createObjectURL()
The `PickedFile` object in web is backed by [`URL.createObjectUrl` Web API](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL),
which is reasonably well supported across all browsers:
![Data on support for the bloburls feature across the major browsers from caniuse.com](https://caniuse.bitsofco.de/image/bloburls.png)
However, the returned `path` attribute of the `PickedFile` points to a `network` resource, and not a
local path in your users' drive. See **Use the plugin** below for some examples on how to use this
return value in a cross-platform way.
### input file "accept"
In order to filter only video/image content, some browsers offer an [`accept` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept) in their `input type="file"` form elements:
![Data on support for the input-file-accept feature across the major browsers from caniuse.com](https://caniuse.bitsofco.de/image/input-file-accept.png)
This feature is just a convenience for users, **not validation**.
Users can override this setting on their browsers. You must validate in your app (or server)
that the user has picked the file type that you can handle.
### input file "capture"
In order to "take a photo", some mobile browsers offer a [`capture` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/capture):
![Data on support for the html-media-capture feature across the major browsers from caniuse.com](https://caniuse.bitsofco.de/image/html-media-capture.png)
Each browser may implement `capture` any way they please, so it may (or may not) make a
difference in your users' experience.
### pickImage()
The arguments `maxWidth`, `maxHeight` and `imageQuality` are not supported for gif images.
The argument `imageQuality` only works for jpeg and webp images.
### pickVideo()
The argument `maxDuration` is not supported on the web.
## Usage
### Import the package
This package is [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin),
which means you can simply use `image_picker`
normally. This package will be automatically included in your app when you do.
### Use the plugin
You should be able to use `package:image_picker` _almost_ as normal.
Once the user has picked a file, the returned `PickedFile` instance will contain a
`network`-accessible URL (pointing to a location within the browser).
The instance will also let you retrieve the bytes of the selected file across all platforms.
If you want to use the path directly, your code would need look like this:
```dart
...
if (kIsWeb) {
Image.network(pickedFile.path);
} else {
Image.file(File(pickedFile.path));
}
...
```
Or, using bytes:
```dart
...
Image.memory(await pickedFile.readAsBytes())
...
```
[1]: https://pub.dev/packages/image_picker
| plugins/packages/image_picker/image_picker_for_web/README.md/0 | {
"file_path": "plugins/packages/image_picker/image_picker_for_web/README.md",
"repo_id": "plugins",
"token_count": 944
} | 1,284 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <XCTest/XCTest.h>
#import <os/log.h>
const int kLimitedElementWaitingTime = 30;
@interface ImagePickerFromLimitedGalleryUITests : XCTestCase
@property(nonatomic, strong) XCUIApplication *app;
@end
@implementation ImagePickerFromLimitedGalleryUITests
- (void)setUp {
[super setUp];
// Delete the app if already exists, to test permission popups
self.continueAfterFailure = NO;
self.app = [[XCUIApplication alloc] init];
[self.app launch];
__weak typeof(self) weakSelf = self;
[self addUIInterruptionMonitorWithDescription:@"Permission popups"
handler:^BOOL(XCUIElement *_Nonnull interruptingElement) {
XCUIElement *limitedPhotoPermission =
[interruptingElement.buttons elementBoundByIndex:0];
if (![limitedPhotoPermission
waitForExistenceWithTimeout:
kLimitedElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@",
weakSelf.app.debugDescription);
XCTFail(@"Failed due to not able to find "
@"selectPhotos button with %@ seconds",
@(kLimitedElementWaitingTime));
}
[limitedPhotoPermission tap];
return YES;
}];
}
- (void)tearDown {
[super tearDown];
[self.app terminate];
}
// Test the `Select Photos` button which is available after iOS 14.
- (void)testSelectingFromGallery API_AVAILABLE(ios(14)) {
// Find and tap on the pick from gallery button.
XCUIElement *imageFromGalleryButton =
self.app.otherElements[@"image_picker_example_from_gallery"].firstMatch;
if (![imageFromGalleryButton waitForExistenceWithTimeout:kLimitedElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find image from gallery button with %@ seconds",
@(kLimitedElementWaitingTime));
}
[imageFromGalleryButton tap];
// Find and tap on the `pick` button.
XCUIElement *pickButton = self.app.buttons[@"PICK"].firstMatch;
if (![pickButton waitForExistenceWithTimeout:kLimitedElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTSkip(@"Pick button isn't found so the test is skipped...");
}
[pickButton tap];
// There is a known bug where the permission popups interruption won't get fired until a tap
// happened in the app. We expect a permission popup so we do a tap here.
[self.app tap];
// Find an image and tap on it.
XCUIElement *aImage = [self.app.scrollViews.firstMatch.images elementBoundByIndex:1];
os_log_error(OS_LOG_DEFAULT, "description before picking image %@", self.app.debugDescription);
if (![aImage waitForExistenceWithTimeout:kLimitedElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find an image with %@ seconds",
@(kLimitedElementWaitingTime));
}
[aImage tap];
// Find and tap on the `Done` button.
XCUIElement *doneButton = self.app.buttons[@"Done"].firstMatch;
if (![doneButton waitForExistenceWithTimeout:kLimitedElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTSkip(@"Permissions popup could not fired so the test is skipped...");
}
[doneButton tap];
// Find an image and tap on it to have access to selected photos.
aImage = [self.app.scrollViews.firstMatch.images elementBoundByIndex:1];
os_log_error(OS_LOG_DEFAULT, "description before picking image %@", self.app.debugDescription);
if (![aImage waitForExistenceWithTimeout:kLimitedElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find an image with %@ seconds",
@(kLimitedElementWaitingTime));
}
[aImage tap];
// Find the picked image.
XCUIElement *pickedImage = self.app.images[@"image_picker_example_picked_image"].firstMatch;
if (![pickedImage waitForExistenceWithTimeout:kLimitedElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find pickedImage with %@ seconds",
@(kLimitedElementWaitingTime));
}
}
@end
| plugins/packages/image_picker/image_picker_ios/example/ios/RunnerUITests/ImagePickerFromLimitedGalleryUITests.m/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/example/ios/RunnerUITests/ImagePickerFromLimitedGalleryUITests.m",
"repo_id": "plugins",
"token_count": 2079
} | 1,285 |
name: image_picker_example
description: Demonstrates how to use the image_picker plugin.
publish_to: none
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
image_picker_ios:
# When depending on this package from a real application you should use:
# image_picker_ios: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
image_picker_platform_interface: ^2.6.1
video_player: ^2.1.4
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| plugins/packages/image_picker/image_picker_ios/example/pubspec.yaml/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/example/pubspec.yaml",
"repo_id": "plugins",
"token_count": 302
} | 1,286 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.0.3), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import <Foundation/Foundation.h>
@protocol FlutterBinaryMessenger;
@protocol FlutterMessageCodec;
@class FlutterError;
@class FlutterStandardTypedData;
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, FLTSourceCamera) {
FLTSourceCameraRear = 0,
FLTSourceCameraFront = 1,
};
typedef NS_ENUM(NSUInteger, FLTSourceType) {
FLTSourceTypeCamera = 0,
FLTSourceTypeGallery = 1,
};
@class FLTMaxSize;
@class FLTSourceSpecification;
@interface FLTMaxSize : NSObject
+ (instancetype)makeWithWidth:(nullable NSNumber *)width height:(nullable NSNumber *)height;
@property(nonatomic, strong, nullable) NSNumber *width;
@property(nonatomic, strong, nullable) NSNumber *height;
@end
@interface FLTSourceSpecification : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithType:(FLTSourceType)type camera:(FLTSourceCamera)camera;
@property(nonatomic, assign) FLTSourceType type;
@property(nonatomic, assign) FLTSourceCamera camera;
@end
/// The codec used by FLTImagePickerApi.
NSObject<FlutterMessageCodec> *FLTImagePickerApiGetCodec(void);
@protocol FLTImagePickerApi
- (void)pickImageWithSource:(FLTSourceSpecification *)source
maxSize:(FLTMaxSize *)maxSize
quality:(nullable NSNumber *)imageQuality
fullMetadata:(NSNumber *)requestFullMetadata
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
- (void)pickMultiImageWithMaxSize:(FLTMaxSize *)maxSize
quality:(nullable NSNumber *)imageQuality
fullMetadata:(NSNumber *)requestFullMetadata
completion:(void (^)(NSArray<NSString *> *_Nullable,
FlutterError *_Nullable))completion;
- (void)pickVideoWithSource:(FLTSourceSpecification *)source
maxDuration:(nullable NSNumber *)maxDurationSeconds
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
@end
extern void FLTImagePickerApiSetup(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FLTImagePickerApi> *_Nullable api);
NS_ASSUME_NONNULL_END
| plugins/packages/image_picker/image_picker_ios/ios/Classes/messages.g.h/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/ios/Classes/messages.g.h",
"repo_id": "plugins",
"token_count": 986
} | 1,287 |
// 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:cross_file/cross_file.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import '../method_channel/method_channel_image_picker.dart';
import '../types/types.dart';
/// The interface that implementations of image_picker must implement.
///
/// Platform implementations should extend this class rather than implement it as `image_picker`
/// does not consider newly added methods to be breaking changes. Extending this class
/// (using `extends`) ensures that the subclass will get the default implementation, while
/// platform implementations that `implements` this interface will be broken by newly added
/// [ImagePickerPlatform] methods.
abstract class ImagePickerPlatform extends PlatformInterface {
/// Constructs a ImagePickerPlatform.
ImagePickerPlatform() : super(token: _token);
static final Object _token = Object();
static ImagePickerPlatform _instance = MethodChannelImagePicker();
/// The default instance of [ImagePickerPlatform] to use.
///
/// Defaults to [MethodChannelImagePicker].
static ImagePickerPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [ImagePickerPlatform] when they register themselves.
// TODO(amirh): Extract common platform interface logic.
// https://github.com/flutter/flutter/issues/43368
static set instance(ImagePickerPlatform instance) {
PlatformInterface.verify(instance, _token);
_instance = instance;
}
// Next version of the API.
/// Returns a [PickedFile] with the image that was picked.
///
/// The `source` argument controls where the image comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and above only support HEIC images if used
/// in addition to a size modification, of which the usage is explained below.
///
/// If specified, the image will be at most `maxWidth` wide and
/// `maxHeight` tall. Otherwise the image will be returned at it's
/// original width and height.
///
/// The `imageQuality` argument modifies the quality of the image, ranging from 0-100
/// where 100 is the original/max quality. If `imageQuality` is null, the image with
/// the original quality will be returned. Compression is only supported for certain
/// image types such as JPEG. If compression is not supported for the image that is picked,
/// a warning message will be logged.
///
/// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera].
/// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device.
/// Defaults to [CameraDevice.rear]. Note that Android has no documented parameter for an intent to specify if
/// the front or rear camera should be opened, this function is not guaranteed
/// to work on an Android device.
///
/// In Android, the MainActivity can be destroyed for various reasons. If that happens, the result will be lost
/// in this call. You can then call [retrieveLostData] when your app relaunches to retrieve the lost data.
///
/// If no images were picked, the return value is null.
Future<PickedFile?> pickImage({
required ImageSource source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
CameraDevice preferredCameraDevice = CameraDevice.rear,
}) {
throw UnimplementedError('pickImage() has not been implemented.');
}
/// Returns a [List<PickedFile>] with the images that were picked.
///
/// The images come from the [ImageSource.gallery].
///
/// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and above only support HEIC images if used
/// in addition to a size modification, of which the usage is explained below.
///
/// If specified, the image will be at most `maxWidth` wide and
/// `maxHeight` tall. Otherwise the image will be returned at it's
/// original width and height.
///
/// The `imageQuality` argument modifies the quality of the images, ranging from 0-100
/// where 100 is the original/max quality. If `imageQuality` is null, the images with
/// the original quality will be returned. Compression is only supported for certain
/// image types such as JPEG. If compression is not supported for the image that is picked,
/// a warning message will be logged.
///
/// If no images were picked, the return value is null.
Future<List<PickedFile>?> pickMultiImage({
double? maxWidth,
double? maxHeight,
int? imageQuality,
}) {
throw UnimplementedError('pickMultiImage() has not been implemented.');
}
/// Returns a [PickedFile] containing the video that was picked.
///
/// The [source] argument controls where the video comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// The [maxDuration] argument specifies the maximum duration of the captured video. If no [maxDuration] is specified,
/// the maximum duration will be infinite.
///
/// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera].
/// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device.
/// Defaults to [CameraDevice.rear].
///
/// In Android, the MainActivity can be destroyed for various fo reasons. If that happens, the result will be lost
/// in this call. You can then call [retrieveLostData] when your app relaunches to retrieve the lost data.
///
/// If no images were picked, the return value is null.
Future<PickedFile?> pickVideo({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) {
throw UnimplementedError('pickVideo() has not been implemented.');
}
/// Retrieves any previously picked file, that was lost due to the MainActivity being destroyed.
/// In case multiple files were lost, only the last file will be recovered. (Android only).
///
/// Image or video can be lost if the MainActivity is destroyed. And there is no guarantee that the MainActivity is always alive.
/// Call this method to retrieve the lost data and process the data according to your APP's business logic.
///
/// Returns a [LostData] object if successfully retrieved the lost data. The [LostData] object can represent either a
/// successful image/video selection, or a failure.
///
/// Calling this on a non-Android platform will throw [UnimplementedError] exception.
///
/// See also:
/// * [LostData], for what's included in the response.
/// * [Android Activity Lifecycle](https://developer.android.com/reference/android/app/Activity.html), for more information on MainActivity destruction.
Future<LostData> retrieveLostData() {
throw UnimplementedError('retrieveLostData() has not been implemented.');
}
/// This method is deprecated in favor of [getImageFromSource] and will be removed in a future update.
///
/// Returns an [XFile] with the image that was picked.
///
/// The `source` argument controls where the image comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and above only support HEIC images if used
/// in addition to a size modification, of which the usage is explained below.
///
/// If specified, the image will be at most `maxWidth` wide and
/// `maxHeight` tall. Otherwise the image will be returned at it's
/// original width and height.
///
/// The `imageQuality` argument modifies the quality of the image, ranging from 0-100
/// where 100 is the original/max quality. If `imageQuality` is null, the image with
/// the original quality will be returned. Compression is only supported for certain
/// image types such as JPEG. If compression is not supported for the image that is picked,
/// a warning message will be logged.
///
/// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera].
/// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device.
/// Defaults to [CameraDevice.rear]. Note that Android has no documented parameter for an intent to specify if
/// the front or rear camera should be opened, this function is not guaranteed
/// to work on an Android device.
///
/// In Android, the MainActivity can be destroyed for various reasons. If that happens, the result will be lost
/// in this call. You can then call [getLostData] when your app relaunches to retrieve the lost data.
///
/// If no images were picked, the return value is null.
Future<XFile?> getImage({
required ImageSource source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
CameraDevice preferredCameraDevice = CameraDevice.rear,
}) {
throw UnimplementedError('getImage() has not been implemented.');
}
/// This method is deprecated in favor of [getMultiImageWithOptions] and will be removed in a future update.
///
/// Returns a [List<XFile>] with the images that were picked.
///
/// The images come from the [ImageSource.gallery].
///
/// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and above only support HEIC images if used
/// in addition to a size modification, of which the usage is explained below.
///
/// If specified, the image will be at most `maxWidth` wide and
/// `maxHeight` tall. Otherwise the image will be returned at it's
/// original width and height.
///
/// The `imageQuality` argument modifies the quality of the images, ranging from 0-100
/// where 100 is the original/max quality. If `imageQuality` is null, the images with
/// the original quality will be returned. Compression is only supported for certain
/// image types such as JPEG. If compression is not supported for the image that is picked,
/// a warning message will be logged.
///
/// If no images were picked, the return value is null.
Future<List<XFile>?> getMultiImage({
double? maxWidth,
double? maxHeight,
int? imageQuality,
}) {
throw UnimplementedError('getMultiImage() has not been implemented.');
}
/// Returns a [XFile] containing the video that was picked.
///
/// The [source] argument controls where the video comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// The [maxDuration] argument specifies the maximum duration of the captured video. If no [maxDuration] is specified,
/// the maximum duration will be infinite.
///
/// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera].
/// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device.
/// Defaults to [CameraDevice.rear].
///
/// In Android, the MainActivity can be destroyed for various fo reasons. If that happens, the result will be lost
/// in this call. You can then call [getLostData] when your app relaunches to retrieve the lost data.
///
/// If no images were picked, the return value is null.
Future<XFile?> getVideo({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) {
throw UnimplementedError('getVideo() has not been implemented.');
}
/// Retrieves any previously picked files, that were lost due to the MainActivity being destroyed. (Android only)
///
/// Image or video can be lost if the MainActivity is destroyed. And there is no guarantee that the MainActivity is
/// always alive. Call this method to retrieve the lost data and process the data according to your APP's business logic.
///
/// Returns a [LostDataResponse] object if successfully retrieved the lost data. The [LostDataResponse] object can
/// represent either a successful image/video selection, or a failure.
///
/// Calling this on a non-Android platform will throw [UnimplementedError] exception.
///
/// See also:
/// * [LostDataResponse], for what's included in the response.
/// * [Android Activity Lifecycle](https://developer.android.com/reference/android/app/Activity.html), for more
/// information on MainActivity destruction.
Future<LostDataResponse> getLostData() {
throw UnimplementedError('getLostData() has not been implemented.');
}
/// Returns an [XFile] with the image that was picked.
///
/// The `source` argument controls where the image comes from. This can
/// be either [ImageSource.camera] or [ImageSource.gallery].
///
/// The `options` argument controls additional settings that can be used when
/// picking an image. See [ImagePickerOptions] for more details.
///
/// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and
/// above only support HEIC images if used in addition to a size modification,
/// of which the usage is explained in [ImagePickerOptions].
///
/// In Android, the MainActivity can be destroyed for various reasons. If that
/// happens, the result will be lost in this call. You can then call [getLostData]
/// when your app relaunches to retrieve the lost data.
///
/// If no images were picked, the return value is null.
Future<XFile?> getImageFromSource({
required ImageSource source,
ImagePickerOptions options = const ImagePickerOptions(),
}) {
return getImage(
source: source,
maxHeight: options.maxHeight,
maxWidth: options.maxWidth,
imageQuality: options.imageQuality,
preferredCameraDevice: options.preferredCameraDevice,
);
}
/// Returns a [List<XFile>] with the images that were picked.
///
/// The images come from the [ImageSource.gallery].
///
/// The `options` argument controls additional settings that can be used when
/// picking an image. See [MultiImagePickerOptions] for more details.
///
/// If no images were picked, returns an empty list.
Future<List<XFile>> getMultiImageWithOptions({
MultiImagePickerOptions options = const MultiImagePickerOptions(),
}) async {
final List<XFile>? pickedImages = await getMultiImage(
maxWidth: options.imageOptions.maxWidth,
maxHeight: options.imageOptions.maxHeight,
imageQuality: options.imageOptions.imageQuality,
);
return pickedImages ?? <XFile>[];
}
}
| plugins/packages/image_picker/image_picker_platform_interface/lib/src/platform_interface/image_picker_platform.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_platform_interface/lib/src/platform_interface/image_picker_platform.dart",
"repo_id": "plugins",
"token_count": 3947
} | 1,288 |
## 3.1.4
* Updates iOS minimum version in README.
## 3.1.3
* Ignores a lint in the example app for backwards compatibility.
## 3.1.2
* Updates example code for `use_build_context_synchronously` lint.
* Updates minimum Flutter version to 3.0.
## 3.1.1
* Adds screenshots to pubspec.yaml.
## 3.1.0
* Adds macOS as a supported platform.
## 3.0.8
* Updates minimum Flutter version to 2.10.
* Bumps minimum in_app_purchase_android to 0.2.3.
## 3.0.7
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 3.0.6
* Ignores deprecation warnings for upcoming styleFrom button API changes.
## 3.0.5
* Updates references to the obsolete master branch.
## 3.0.4
* Minor fixes for new analysis options.
## 3.0.3
* Removes unnecessary imports.
* Adds OS version support information to README.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 3.0.2
* Adds additional explanation on why it is important to complete a purchase.
## 3.0.1
* Internal code cleanup for stricter analysis options.
## 3.0.0
* **BREAKING CHANGE** Updates `restorePurchases` to emit an empty list of purchases on StoreKit when there are no purchases to restore (same as Android).
* This change was listed in the CHANGELOG for 2.0.0, but the change was accidentally not included in 2.0.0.
## 2.0.1
* Removes the instructions on initializing the plugin since this functionality is deprecated.
## 2.0.0
* **BREAKING CHANGES**:
* Adds a new `PurchaseStatus` named `canceled`. This means developers can distinguish between an error and user cancellation.
* ~~Updates `restorePurchases` to emit an empty list of purchases on StoreKit when there are no purchases to restore (same as Android).~~
* Renames `in_app_purchase_ios` to `in_app_purchase_storekit`.
* Renames `InAppPurchaseIosPlatform` to `InAppPurchaseStoreKitPlatform`.
* Renames `InAppPurchaseIosPlatformAddition` to
`InAppPurchaseStoreKitPlatformAddition`.
* Deprecates the `InAppPurchaseAndroidPlatformAddition.enablePendingPurchases()` method and `InAppPurchaseAndroidPlatformAddition.enablePendingPurchase` property.
* Adds support for promotional offers on the store_kit_wrappers Dart API.
* Fixes integration tests.
* Updates example app Android compileSdkVersion to 31.
## 1.0.9
* Handle purchases with `PurchaseStatus.restored` correctly in the example App.
* Updated dependencies on `in_app_purchase_android` and `in_app_purchase_ios` to their latest versions (version 0.1.5 and 0.1.3+5 respectively).
## 1.0.8
* Fix repository link in pubspec.yaml.
## 1.0.7
* Remove references to the Android V1 embedding.
## 1.0.6
* Added import flutter foundation dependency in README.md to be able to use `defaultTargetPlatform`.
## 1.0.5
* Add explanation for casting `ProductDetails` and `PurchaseDetails` to platform specific implementations in the readme.
## 1.0.4
* Fix `Restoring previous purchases` link in the README.md.
## 1.0.3
* Added a "Restore purchases" button to conform to Apple's StoreKit guidelines on [restoring products](https://developer.apple.com/documentation/storekit/in-app_purchase/restoring_purchased_products?language=objc);
* Corrected an error in a example snippet displayed in the README.md.
## 1.0.2
* Fix ignoring "autoConsume" param in "InAppPurchase.instance.buyConsumable".
## 1.0.1
* Migrate maven repository from jcenter to mavenCentral.
## 1.0.0
* Stable release of in_app_purchase plugin.
## 0.6.0+1
* Added a reference to the in-app purchase codelab in the README.md.
## 0.6.0
As part of implementing federated architecture and making the interface compatible for other platforms this version contains the following **breaking changes**:
* Changes to the platform agnostic interface:
* If you used `InAppPurchaseConnection.instance` to access generic In App Purchase APIs, please use `InAppPurchase.instance` instead;
* The `InAppPurchaseConnection.purchaseUpdatedStream` has been renamed to `InAppPurchase.purchaseStream`;
* The `InAppPurchaseConnection.queryPastPurchases` method has been removed. Instead, you should use `InAppPurchase.restorePurchases`. This method emits each restored purchase on the `InAppPurchase.purchaseStream`, the `PurchaseDetails` object will be marked with a `status` of `PurchaseStatus.restored`;
* The `InAppPurchase.completePurchase` method no longer returns an instance `BillingWrapperResult` class (which was Android specific). Instead it will return a completed `Future` if the method executed successfully, in case of errors it will complete with an `InAppPurchaseException` describing the error.
* Android specific changes:
* The Android specific `InAppPurchaseConnection.consumePurchase` and `InAppPurchaseConnection.enablePendingPurchases` methods have been removed from the platform agnostic interface and moved to the Android specific `InAppPurchaseAndroidPlatformAddition` class:
* `InAppPurchaseAndroidPlatformAddition.enablePendingPurchases` is a static method that should be called when initializing your App. Access the method like this: `InAppPurchaseAndroidPlatformAddition.enablePendingPurchases()` (make sure to add the following import: `import 'package:in_app_purchase_android/in_app_purchase_android.dart';`);
* To use the `InAppPurchaseAndroidPlatformAddition.consumePurchase` method, acquire an instance using the `InAppPurchase.getPlatformAddition` method. For example:
```dart
// Acquire the InAppPurchaseAndroidPlatformAddition instance.
InAppPurchaseAndroidPlatformAddition androidAddition = InAppPurchase.instance.getPlatformAddition<InAppPurchaseAndroidPlatformAddition>();
// Consume an Android purchase.
BillingResultWrapper billingResult = await androidAddition.consumePurchase(purchase);
```
* The [billing_client_wrappers](https://pub.dev/documentation/in_app_purchase_android/latest/billing_client_wrappers/billing_client_wrappers-library.html) have been moved into the [in_app_purchase_android](https://pub.dev/packages/in_app_purchase_android) package. They are still available through the [in_app_purchase](https://pub.dev/packages/in_app_purchase) plugin but to use them it is necessary to import the correct package when using them: `import 'package:in_app_purchase_android/billing_client_wrappers.dart';`;
* iOS specific changes:
* The iOS specific methods `InAppPurchaseConnection.presentCodeRedemptionSheet` and `InAppPurchaseConnection.refreshPurchaseVerificationData` methods have been removed from the platform agnostic interface and moved into the iOS specific `InAppPurchaseIosPlatformAddition` class. To use them acquire an instance through the `InAppPurchase.getPlatformAddition` method like so:
```dart
// Acquire the InAppPurchaseIosPlatformAddition instance.
InAppPurchaseIosPlatformAddition iosAddition = InAppPurchase.instance.getPlatformAddition<InAppPurchaseIosPlatformAddition>();
// Present the code redemption sheet.
await iosAddition.presentCodeRedemptionSheet();
// Refresh purchase verification data.
PurchaseVerificationData? verificationData = await iosAddition.refreshPurchaseVerificationData();
```
* The [store_kit_wrappers](https://pub.dev/documentation/in_app_purchase_ios/latest/store_kit_wrappers/store_kit_wrappers-library.html) have been moved into the [in_app_purchase_ios](https://pub.dev/packages/in_app_purchase_ios) package. They are still available in the [in_app_purchase](https://pub.dev/packages/in_app_purchase) plugin, but to use them it is necessary to import the correct package when using them: `import 'package:in_app_purchase_ios/store_kit_wrappers.dart';`;
* Update the minimum supported Flutter version to 1.20.0.
## 0.5.2
* Added `rawPrice` and `currencyCode` to the ProductDetails model.
## 0.5.1+3
* Configured the iOS example App to make use of StoreKit Testing on iOS 14 and higher.
## 0.5.1+2
* Update README to provide a better instruction of the plugin.
## 0.5.1+1
* Fix error message when trying to consume purchase on iOS.
## 0.5.1
* [iOS] Introduce `SKPaymentQueueWrapper.presentCodeRedemptionSheet`
## 0.5.0
* Migrate to Google Billing Library 3.0
* Add `obfuscatedProfileId`, `purchaseToken` in [BillingClientWrapper.launchBillingFlow].
* **Breaking Change**
* Removed `developerPayload` in [BillingClientWrapper.acknowledgePurchase], [BillingClientWrapper.consumeAsync], [InAppPurchaseConnection.completePurchase], [InAppPurchaseConnection.consumePurchase].
* Removed `isRewarded` from [SkuDetailsWrapper].
* [SkuDetailsWrapper.introductoryPriceCycles] now returns `int` instead of `String`.
* Above breaking changes are inline with the breaking changes introduced in [Google Play Billing 3.0 release](https://developer.android.com/google/play/billing/release-notes#3-0).
* Additional information on some the changes:
* [Dropping reward SKU support](https://support.google.com/googleplay/android-developer/answer/9155268?hl=en)
* [Developer payload](https://developer.android.com/google/play/billing/developer-payload)
## 0.4.1
* Support InApp subscription upgrade/downgrade.
## 0.4.0
* Migrate to nullsafety.
* Deprecate `sandboxTesting`, introduce `simulatesAskToBuyInSandbox`.
* **Breaking Change:**
* Removed `callbackChannel` in `channels.dart`, see https://github.com/flutter/flutter/issues/69225.
## 0.3.5+2
* Migrate deprecated references.
## 0.3.5+1
* Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets.
## 0.3.5
* [Android] Fixed: added support for the SERVICE_TIMEOUT (-3) response code.
## 0.3.4+18
* Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276))
## 0.3.4+17
* Update Flutter SDK constraint.
## 0.3.4+16
* Add Dartdocs to all public APIs.
## 0.3.4+15
* Update android compileSdkVersion to 29.
## 0.3.4+14
* Add test target to iOS example app Podfile
## 0.3.4+13
* Android Code Inspection and Clean up.
## 0.3.4+12
* [iOS] Fixed: finishing purchases upon payment dialog cancellation.
## 0.3.4+11
* [iOS] Fixed: crash when sending null for simulatesAskToBuyInSandbox parameter.
## 0.3.4+10
* Fixed typo 'verity' for 'verify'.
## 0.3.4+9
* [iOS] Fixed: purchase dialog not showing always.
* [iOS] Fixed: completing purchases could fail.
* [iOS] Fixed: restorePurchases caused hang (call never returned).
## 0.3.4+8
* [iOS] Fixed: purchase dialog not showing always.
* [iOS] Fixed: completing purchases could fail.
* [iOS] Fixed: restorePurchases caused hang (call never returned).
## 0.3.4+7
* iOS: Fix typo of the `simulatesAskToBuyInSandbox` key.
## 0.3.4+6
* iOS: Fix the bug that prevent restored subscription transactions from being completed
## 0.3.4+5
* Added necessary README docs for getting started with Android.
## 0.3.4+4
* Update package:e2e -> package:integration_test
## 0.3.4+3
* Fixed typo 'manuelly' for 'manually'.
## 0.3.4+2
* Update package:e2e reference to use the local version in the flutter/plugins
repository.
## 0.3.4+1
* iOS: Fix the bug that `SKPaymentQueueWrapper.transactions` doesn't return all transactions.
* iOS: Fix the app crashes if `InAppPurchaseConnection.instance` is called in the `main()`.
## 0.3.4
* Expose SKError code to client apps.
## 0.3.3+2
* Post-v2 Android embedding cleanups.
## 0.3.3+1
* Update documentations for `InAppPurchase.completePurchase` and update README.
## 0.3.3
* Introduce `SKPaymentQueueWrapper.transactions`.
## 0.3.2+2
* Fix CocoaPods podspec lint warnings.
## 0.3.2+1
* iOS: Fix only transactions with SKPaymentTransactionStatePurchased and SKPaymentTransactionStateFailed can be finished.
* iOS: Only one pending transaction of a given product is allowed.
## 0.3.2
* Remove Android dependencies fallback.
* Require Flutter SDK 1.12.13+hotfix.5 or greater.
## 0.3.1+2
* Fix potential casting crash on Android v1 embedding when registering life cycle callbacks.
* Remove hard-coded legacy xcode build setting.
## 0.3.1+1
* Add `pedantic` to dev_dependency.
## 0.3.1
* Android: Fix a bug where the `BillingClient` is disconnected when app goes to the background.
* Android: Make sure the `BillingClient` object is disconnected before the activity is destroyed.
* Android: Fix minor compiler warning.
* Fix typo in CHANGELOG.
## 0.3.0+3
* Fix pendingCompletePurchase flag status to allow to complete purchases.
## 0.3.0+2
* Update te example app to avoid using deprecated api.
## 0.3.0+1
* Fixing usage example. No functional changes.
## 0.3.0
* Migrate the `Google Play Library` to 2.0.3.
* Introduce a new class `BillingResultWrapper` which contains a detailed result of a BillingClient operation.
* **[Breaking Change]:** All the BillingClient methods that previously return a `BillingResponse` now return a `BillingResultWrapper`, including: `launchBillingFlow`, `startConnection` and `consumeAsync`.
* **[Breaking Change]:** The `SkuDetailsResponseWrapper` now contains a `billingResult` field in place of `billingResponse` field.
* A `billingResult` field is added to the `PurchasesResultWrapper`.
* Other Updates to the "billing_client_wrappers":
* Updates to the `PurchaseWrapper`: Add `developerPayload`, `purchaseState` and `isAcknowledged` fields.
* Updates to the `SkuDetailsWrapper`: Add `originalPrice` and `originalPriceAmountMicros` fields.
* **[Breaking Change]:** The `BillingClient.queryPurchaseHistory` is updated to return a `PurchasesHistoryResult`, which contains a list of `PurchaseHistoryRecordWrapper` instead of `PurchaseWrapper`. A `PurchaseHistoryRecordWrapper` object has the same fields and values as A `PurchaseWrapper` object, except that a `PurchaseHistoryRecordWrapper` object does not contain `isAutoRenewing`, `orderId` and `packageName`.
* Add a new `BillingClient.acknowledgePurchase` API. Starting from this version, the developer has to acknowledge any purchase on Android using this API within 3 days of purchase, or the user will be refunded. Note that if a product is "consumed" via `BillingClient.consumeAsync`, it is implicitly acknowledged.
* **[Breaking Change]:** Added `enablePendingPurchases` in `BillingClientWrapper`. The application has to call this method before calling `BillingClientWrapper.startConnection`. See [enablePendingPurchases](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder.html#enablependingpurchases) for more information.
* Updates to the "InAppPurchaseConnection":
* **[Breaking Change]:** `InAppPurchaseConnection.completePurchase` now returns a `Future<BillingResultWrapper>` instead of `Future<void>`. A new optional parameter `{String developerPayload}` has also been added to the API. On Android, this API does not throw an exception anymore, it instead acknowledge the purchase. If a purchase is not completed within 3 days on Android, the user will be refunded.
* **[Breaking Change]:** `InAppPurchaseConnection.consumePurchase` now returns a `Future<BillingResultWrapper>` instead of `Future<BillingResponse>`. A new optional parameter `{String developerPayload}` has also been added to the API.
* A new boolean field `pendingCompletePurchase` has been added to the `PurchaseDetails` class. Which can be used as an indicator of whether to call `InAppPurchaseConnection.completePurchase` on the purchase.
* **[Breaking Change]:** Added `enablePendingPurchases` in `InAppPurchaseConnection`. The application has to call this method when initializing the `InAppPurchaseConnection` on Android. See [enablePendingPurchases](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.Builder.html#enablependingpurchases) for more information.
* Misc: Some documentation updates reflecting the `BillingClient` migration and some documentation fixes.
* Refer to [Google Play Billing Library Release Note](https://developer.android.com/google/play/billing/billing_library_releases_notes#release-2_0) for a detailed information on the update.
## 0.2.2+6
* Correct a comment.
## 0.2.2+5
* Update version of json_annotation to ^3.0.0 and json_serializable to ^3.2.0. Resolve conflicts with other packages e.g. flutter_tools from sdk.
## 0.2.2+4
* 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.2.2+3
* Fix failing pedantic lints. None of these fixes should have any change in
functionality.
## 0.2.2+2
* Include lifecycle dependency as a compileOnly one on Android to resolve
potential version conflicts with other transitive libraries.
## 0.2.2+1
* Android: Use android.arch.lifecycle instead of androidx.lifecycle:lifecycle in `build.gradle` to support apps that has not been migrated to AndroidX.
## 0.2.2
* Support the v2 Android embedder.
* Update to AndroidX.
* Migrate to using the new e2e test binding.
* Add a e2e test.
## 0.2.1+5
* Define clang module for iOS.
* Fix iOS build warning.
## 0.2.1+4
* Update and migrate iOS example project.
## 0.2.1+3
* Android : Improved testability.
## 0.2.1+2
* Android: Require a non-null Activity to use the `launchBillingFlow` method.
## 0.2.1+1
* Remove skipped driver test.
## 0.2.1
* iOS: Add currencyCode to priceLocale on productDetails.
## 0.2.0+8
* Add dependency on `androidx.annotation:annotation:1.0.0`.
## 0.2.0+7
* Make Gradle version compatible with the Android Gradle plugin version.
## 0.2.0+6
* Add missing `hashCode` implementations.
## 0.2.0+5
* iOS: Support unsupported UserInfo value types on NSError.
## 0.2.0+4
* Fixed code error in `README.md` and adjusted links to work on Pub.
## 0.2.0+3
* Update the `README.md` so that the code samples compile with the latest Flutter/Dart version.
## 0.2.0+2
* Fix a google_play_connection purchase update listener regression introduced in 0.2.0+1.
## 0.2.0+1
* Fix an issue the type is not casted before passing to `PurchasesResultWrapper.fromJson`.
## 0.2.0
* [Breaking Change] Rename 'PurchaseError' to 'IAPError'.
* [Breaking Change] Rename 'PurchaseSource' to 'IAPSource'.
## 0.1.1+3
* Expanded description in `pubspec.yaml` and fixed typo in `README.md`.
## 0.1.1+2
* Add missing template type parameter to `invokeMethod` calls.
* Bump minimum Flutter version to 1.5.0.
* Replace invokeMethod with invokeMapMethod wherever necessary.
## 0.1.1+1
* Make `AdditionalSteps`(Used in the unit test) a void function.
## 0.1.1
* Some error messages from iOS are slightly changed.
* `ProductDetailsResponse` returned by `queryProductDetails()` now contains an `PurchaseError` object that represents any error that might occurred during the request.
* If the device is not connected to the internet, `queryPastPurchases()` on iOS now have the error stored in the response instead of throwing.
* Clean up minor iOS warning.
* Example app shows how to handle error when calling `queryProductDetails()` and `queryProductDetails()`.
## 0.1.0+4
* Change the `buy` methods to return `Future<bool>` instead of `void` in order
to propagate `launchBillingFlow` failures up through `google_play_connection`.
## 0.1.0+3
* Guard against multiple onSetupFinished() calls.
## 0.1.0+2
* Fix bug where error only purchases updates weren't propagated correctly in
`google_play_connection.dart`.
## 0.1.0+1
* Add more consumable handling to the example app.
## 0.1.0
Beta release.
* Ability to list products, load previous purchases, and make purchases.
* Simplified Dart API that's been unified for ease of use.
* Platform-specific APIs more directly exposing `StoreKit` and `BillingClient`.
Includes:
* 5ba657dc [in_app_purchase] Remove extraneous download logic (#1560)
* 01bb8796 [in_app_purchase] Minor doc updates (#1555)
* 1a4d493f [in_app_purchase] Only fetch owned purchases (#1540)
* d63c51cf [in_app_purchase] Add auto-consume errors to PurchaseDetails (#1537)
* 959da97f [in_app_purchase] Minor doc updates (#1536)
* b82ae1a6 [in_app_purchase] Rename the unified API (#1517)
* d1ad723a [in_app_purchase]remove SKDownloadWrapper and related code. (#1474)
* 7c1e8b8a [in_app_purchase]make payment unified APIs (#1421)
* 80233db6 [in_app_purchase] Add references to the original object for PurchaseDetails and ProductDetails (#1448)
* 8c180f0d [in_app_purchase]load purchase (#1380)
* e9f141bc [in_app_purchase] Iap refactor (#1381)
* d3b3d60c add driver test command to cirrus (#1342)
* aee12523 [in_app_purchase] refactoring and tests (#1322)
* 6d7b4592 [in_app_purchase] Adds Dart BillingClient APIs for loading purchases (#1286)
* 5567a9c8 [in_app_purchase]retrieve receipt (#1303)
* 3475f1b7 [in_app_purchase]restore purchases (#1299)
* a533148d [in_app_purchase] payment queue dart ios (#1249)
* 10030840 [in_app_purchase] Minor bugfixes and code cleanup (#1284)
* 347f508d [in_app_purchase] Fix CI formatting errors. (#1281)
* fad02d87 [in_app_purchase] Java API for querying purchases (#1259)
* bc501915 [In_app_purchase]SKProduct related fixes (#1252)
* f92ba3a1 IAP make payment objc (#1231)
* 62b82522 [IAP] Add the Dart API for launchBillingFlow (#1232)
* b40a4acf [IAP] Add Java call for launchBillingFlow (#1230)
* 4ff06cd1 [In_app_purchase]remove categories (#1222)
* 0e72ca56 [In_app_purchase]fix requesthandler crash (#1199)
* 81dff2be Iap getproductlist basic draft (#1169)
* db139b28 Iap iOS add payment dart wrappers (#1178)
* 2e5fbb9b Fix the param map passed down to the platform channel when calling querySkuDetails (#1194)
* 4a84bac1 Mark some packages as unpublishable (#1193)
* 51696552 Add a gradle warning to the AndroidX plugins (#1138)
* 832ab832 Iap add payment objc translators (#1172)
* d0e615cf Revert "IAP add payment translators in objc (#1126)" (#1171)
* 09a5a36e IAP add payment translators in objc (#1126)
* a100fbf9 Expose nslocale and expose currencySymbol instead of currencyCode to match android (#1162)
* 1c982efd Using json serializer for skproduct wrapper and related classes (#1147)
* 3039a261 Iap productlist ios (#1068)
* 2a1593da [IAP] Update dev deps to match flutter_driver (#1118)
* 9f87cbe5 [IAP] Update README (#1112)
* 59e84d85 Migrate independent plugins to AndroidX (#1103)
* a027ccd6 [IAP] Generate boilerplate serializers (#1090)
* 909cf1c2 [IAP] Fetch SkuDetails from Google Play (#1084)
* 6bbaa7e5 [IAP] Add missing license headers (#1083)
* 5347e877 [IAP] Clean up Dart unit tests (#1082)
* fe03e407 [IAP] Check if the payment processor is available (#1057)
* 43ee28cf Fix `Manifest versionCode not found` (#1076)
* 4d702ad7 Supress `strong_mode_implicit_dynamic_method` for `invokeMethod` calls. (#1065)
* 809ccde7 Doc and build script updates to the IAP plugin (#1024)
* 052b71a9 Update the IAP README (#933)
* 54f9c4e2 Upgrade Android Gradle Plugin to 3.2.1 (#916)
* ced3e99d Set all gradle-wrapper versions to 4.10.2 (#915)
* eaa1388b Reconfigure Cirrus to use clang 7 (#905)
* 9b153920 Update gradle dependencies. (#881)
* 1aef7d92 Enable lint unnecessary_new (#701)
## 0.0.2
* Added missing flutter_test package dependency.
* Added missing flutter version requirements.
## 0.0.1
* Initial release.
| plugins/packages/in_app_purchase/in_app_purchase/CHANGELOG.md/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 7247
} | 1,289 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.inapppurchase;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import androidx.annotation.VisibleForTesting;
import com.android.billingclient.api.BillingClient;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;
/** Wraps a {@link BillingClient} instance and responds to Dart calls for it. */
public class InAppPurchasePlugin implements FlutterPlugin, ActivityAware {
static final String PROXY_PACKAGE_KEY = "PROXY_PACKAGE";
// The proxy value has to match the <package> value in library's AndroidManifest.xml.
// This is important that the <package> is not changed, so we hard code the value here then having
// a unit test to make sure. If there is a strong reason to change the <package> value, please inform the
// code owner of this package.
static final String PROXY_VALUE = "io.flutter.plugins.inapppurchase";
@VisibleForTesting
static final class MethodNames {
static final String IS_READY = "BillingClient#isReady()";
static final String START_CONNECTION =
"BillingClient#startConnection(BillingClientStateListener)";
static final String END_CONNECTION = "BillingClient#endConnection()";
static final String ON_DISCONNECT = "BillingClientStateListener#onBillingServiceDisconnected()";
static final String QUERY_SKU_DETAILS =
"BillingClient#querySkuDetailsAsync(SkuDetailsParams, SkuDetailsResponseListener)";
static final String LAUNCH_BILLING_FLOW =
"BillingClient#launchBillingFlow(Activity, BillingFlowParams)";
static final String ON_PURCHASES_UPDATED =
"PurchasesUpdatedListener#onPurchasesUpdated(int, List<Purchase>)";
static final String QUERY_PURCHASES = "BillingClient#queryPurchases(String)";
static final String QUERY_PURCHASES_ASYNC = "BillingClient#queryPurchasesAsync(String)";
static final String QUERY_PURCHASE_HISTORY_ASYNC =
"BillingClient#queryPurchaseHistoryAsync(String, PurchaseHistoryResponseListener)";
static final String CONSUME_PURCHASE_ASYNC =
"BillingClient#consumeAsync(String, ConsumeResponseListener)";
static final String ACKNOWLEDGE_PURCHASE =
"BillingClient#(AcknowledgePurchaseParams params, (AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)";
static final String IS_FEATURE_SUPPORTED = "BillingClient#isFeatureSupported(String)";
static final String LAUNCH_PRICE_CHANGE_CONFIRMATION_FLOW =
"BillingClient#launchPriceChangeConfirmationFlow (Activity, PriceChangeFlowParams, PriceChangeConfirmationListener)";
static final String GET_CONNECTION_STATE = "BillingClient#getConnectionState()";
private MethodNames() {};
}
private MethodChannel methodChannel;
private MethodCallHandlerImpl methodCallHandler;
/** Plugin registration. */
@SuppressWarnings("deprecation")
public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
InAppPurchasePlugin plugin = new InAppPurchasePlugin();
registrar.activity().getIntent().putExtra(PROXY_PACKAGE_KEY, PROXY_VALUE);
((Application) registrar.context().getApplicationContext())
.registerActivityLifecycleCallbacks(plugin.methodCallHandler);
}
@Override
public void onAttachedToEngine(FlutterPlugin.FlutterPluginBinding binding) {
setupMethodChannel(
/*activity=*/ null, binding.getBinaryMessenger(), binding.getApplicationContext());
}
@Override
public void onDetachedFromEngine(FlutterPlugin.FlutterPluginBinding binding) {
teardownMethodChannel();
}
@Override
public void onAttachedToActivity(ActivityPluginBinding binding) {
binding.getActivity().getIntent().putExtra(PROXY_PACKAGE_KEY, PROXY_VALUE);
methodCallHandler.setActivity(binding.getActivity());
}
@Override
public void onDetachedFromActivity() {
methodCallHandler.setActivity(null);
methodCallHandler.onDetachedFromActivity();
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
onAttachedToActivity(binding);
}
@Override
public void onDetachedFromActivityForConfigChanges() {
methodCallHandler.setActivity(null);
}
private void setupMethodChannel(Activity activity, BinaryMessenger messenger, Context context) {
methodChannel = new MethodChannel(messenger, "plugins.flutter.io/in_app_purchase");
methodCallHandler =
new MethodCallHandlerImpl(activity, context, methodChannel, new BillingClientFactoryImpl());
methodChannel.setMethodCallHandler(methodCallHandler);
}
private void teardownMethodChannel() {
methodChannel.setMethodCallHandler(null);
methodChannel = null;
methodCallHandler = null;
}
@VisibleForTesting
void setMethodCallHandler(MethodCallHandlerImpl methodCallHandler) {
this.methodCallHandler = methodCallHandler;
}
}
| plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/InAppPurchasePlugin.java/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/InAppPurchasePlugin.java",
"repo_id": "plugins",
"token_count": 1601
} | 1,290 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../../billing_client_wrappers.dart';
import '../in_app_purchase_android_platform.dart';
/// The class represents the information of a purchase made using Google Play.
class GooglePlayPurchaseDetails extends PurchaseDetails {
/// Creates a new Google Play specific purchase details object with the
/// provided details.
GooglePlayPurchaseDetails({
String? purchaseID,
required String productID,
required PurchaseVerificationData verificationData,
required String? transactionDate,
required this.billingClientPurchase,
required PurchaseStatus status,
}) : super(
productID: productID,
purchaseID: purchaseID,
transactionDate: transactionDate,
verificationData: verificationData,
status: status,
) {
pendingCompletePurchase = !billingClientPurchase.isAcknowledged;
}
/// Generate a [PurchaseDetails] object based on an Android [Purchase] object.
factory GooglePlayPurchaseDetails.fromPurchase(PurchaseWrapper purchase) {
final GooglePlayPurchaseDetails purchaseDetails = GooglePlayPurchaseDetails(
purchaseID: purchase.orderId,
productID: purchase.sku,
verificationData: PurchaseVerificationData(
localVerificationData: purchase.originalJson,
serverVerificationData: purchase.purchaseToken,
source: kIAPSource),
transactionDate: purchase.purchaseTime.toString(),
billingClientPurchase: purchase,
status: const PurchaseStateConverter()
.toPurchaseStatus(purchase.purchaseState),
);
if (purchaseDetails.status == PurchaseStatus.error) {
purchaseDetails.error = IAPError(
source: kIAPSource,
code: kPurchaseErrorCode,
message: '',
);
}
return purchaseDetails;
}
/// Points back to the [PurchaseWrapper] which was used to generate this
/// [GooglePlayPurchaseDetails] object.
final PurchaseWrapper billingClientPurchase;
}
| plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart",
"repo_id": "plugins",
"token_count": 703
} | 1,291 |
// 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:in_app_purchase_platform_interface/src/errors/in_app_purchase_error.dart';
void main() {
test('toString: Should return a description of the error', () {
final IAPError exceptionNoDetails = IAPError(
code: 'error_code',
message: 'dummy_message',
source: 'dummy_source',
);
expect(exceptionNoDetails.toString(),
'IAPError(code: error_code, source: dummy_source, message: dummy_message, details: null)');
final IAPError exceptionWithDetails = IAPError(
code: 'error_code',
message: 'dummy_message',
source: 'dummy_source',
details: 'dummy_details',
);
expect(exceptionWithDetails.toString(),
'IAPError(code: error_code, source: dummy_source, message: dummy_message, details: dummy_details)');
});
}
| plugins/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/errors/in_app_purchase_error_test.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/errors/in_app_purchase_error_test.dart",
"repo_id": "plugins",
"token_count": 360
} | 1,292 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
#import "FIATransactionCache.h"
@class SKPaymentTransaction;
NS_ASSUME_NONNULL_BEGIN
typedef void (^TransactionsUpdated)(NSArray<SKPaymentTransaction *> *transactions);
typedef void (^TransactionsRemoved)(NSArray<SKPaymentTransaction *> *transactions);
typedef void (^RestoreTransactionFailed)(NSError *error);
typedef void (^RestoreCompletedTransactionsFinished)(void);
typedef BOOL (^ShouldAddStorePayment)(SKPayment *payment, SKProduct *product);
typedef void (^UpdatedDownloads)(NSArray<SKDownload *> *downloads);
@interface FIAPaymentQueueHandler : NSObject <SKPaymentTransactionObserver>
@property(NS_NONATOMIC_IOSONLY, weak, nullable) id<SKPaymentQueueDelegate> delegate API_AVAILABLE(
ios(13.0), macos(10.15), watchos(6.2));
/// Creates a new FIAPaymentQueueHandler initialized with an empty
/// FIATransactionCache.
///
/// @param queue The SKPaymentQueue instance connected to the App Store and
/// responsible for processing transactions.
/// @param transactionsUpdated Callback method that is called each time the App
/// Store indicates transactions are updated.
/// @param transactionsRemoved Callback method that is called each time the App
/// Store indicates transactions are removed.
/// @param restoreTransactionFailed Callback method that is called each time
/// the App Store indicates transactions failed
/// to restore.
/// @param restoreCompletedTransactionsFinished Callback method that is called
/// each time the App Store
/// indicates restoring of
/// transactions has finished.
/// @param shouldAddStorePayment Callback method that is called each time an
/// in-app purchase has been initiated from the
/// App Store.
/// @param updatedDownloads Callback method that is called each time the App
/// Store indicates downloads are updated.
- (instancetype)initWithQueue:(nonnull SKPaymentQueue *)queue
transactionsUpdated:(nullable TransactionsUpdated)transactionsUpdated
transactionRemoved:(nullable TransactionsRemoved)transactionsRemoved
restoreTransactionFailed:(nullable RestoreTransactionFailed)restoreTransactionFailed
restoreCompletedTransactionsFinished:
(nullable RestoreCompletedTransactionsFinished)restoreCompletedTransactionsFinished
shouldAddStorePayment:(nullable ShouldAddStorePayment)shouldAddStorePayment
updatedDownloads:(nullable UpdatedDownloads)updatedDownloads
DEPRECATED_MSG_ATTRIBUTE(
"Use the "
"'initWithQueue:transactionsUpdated:transactionsRemoved:restoreTransactionsFinished:"
"shouldAddStorePayment:updatedDownloads:transactionCache:' message instead.");
/// Creates a new FIAPaymentQueueHandler.
///
/// The "transactionsUpdated", "transactionsRemoved" and "updatedDownloads"
/// callbacks are only called while actively observing transactions. To start
/// observing transactions send the "startObservingPaymentQueue" message.
/// Sending the "stopObservingPaymentQueue" message will stop actively
/// observing transactions. When transactions are not observed they are cached
/// to the "transactionCache" and will be delivered via the
/// "transactionsUpdated", "transactionsRemoved" and "updatedDownloads"
/// callbacks as soon as the "startObservingPaymentQueue" message arrives.
///
/// Note: cached transactions that are not processed when the application is
/// killed will be delivered again by the App Store as soon as the application
/// starts again.
///
/// @param queue The SKPaymentQueue instance connected to the App Store and
/// responsible for processing transactions.
/// @param transactionsUpdated Callback method that is called each time the App
/// Store indicates transactions are updated.
/// @param transactionsRemoved Callback method that is called each time the App
/// Store indicates transactions are removed.
/// @param restoreTransactionFailed Callback method that is called each time
/// the App Store indicates transactions failed
/// to restore.
/// @param restoreCompletedTransactionsFinished Callback method that is called
/// each time the App Store
/// indicates restoring of
/// transactions has finished.
/// @param shouldAddStorePayment Callback method that is called each time an
/// in-app purchase has been initiated from the
/// App Store.
/// @param updatedDownloads Callback method that is called each time the App
/// Store indicates downloads are updated.
/// @param transactionCache An empty [FIATransactionCache] instance that is
/// responsible for keeping track of transactions that
/// arrive when not actively observing transactions.
- (instancetype)initWithQueue:(nonnull SKPaymentQueue *)queue
transactionsUpdated:(nullable TransactionsUpdated)transactionsUpdated
transactionRemoved:(nullable TransactionsRemoved)transactionsRemoved
restoreTransactionFailed:(nullable RestoreTransactionFailed)restoreTransactionFailed
restoreCompletedTransactionsFinished:
(nullable RestoreCompletedTransactionsFinished)restoreCompletedTransactionsFinished
shouldAddStorePayment:(nullable ShouldAddStorePayment)shouldAddStorePayment
updatedDownloads:(nullable UpdatedDownloads)updatedDownloads
transactionCache:(nonnull FIATransactionCache *)transactionCache;
// Can throw exceptions if the transaction type is purchasing, should always used in a @try block.
- (void)finishTransaction:(nonnull SKPaymentTransaction *)transaction;
- (void)restoreTransactions:(nullable NSString *)applicationName;
- (void)presentCodeRedemptionSheet API_UNAVAILABLE(tvos, macos, watchos);
- (NSArray<SKPaymentTransaction *> *)getUnfinishedTransactions;
// This method needs to be called before any other methods.
- (void)startObservingPaymentQueue;
// Call this method when the Flutter app is no longer listening
- (void)stopObservingPaymentQueue;
// Appends a payment to the SKPaymentQueue.
//
// @param payment Payment object to be added to the payment queue.
// @return whether "addPayment" was successful.
- (BOOL)addPayment:(SKPayment *)payment;
// Displays the price consent sheet.
//
// The price consent sheet is only displayed when the following
// is true:
// - You have increased the price of the subscription in App Store Connect.
// - The subscriber has not yet responded to a price consent query.
// Otherwise the method has no effect.
- (void)showPriceConsentIfNeeded API_AVAILABLE(ios(13.4))API_UNAVAILABLE(tvos, macos, watchos);
@end
NS_ASSUME_NONNULL_END
| plugins/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAPaymentQueueHandler.h/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAPaymentQueueHandler.h",
"repo_id": "plugins",
"token_count": 2618
} | 1,293 |
// 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 <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#import "FIAPaymentQueueHandler.h"
#import "Stubs.h"
@import in_app_purchase_storekit;
@interface InAppPurchasePluginTest : XCTestCase
@property(strong, nonatomic) FIAPReceiptManagerStub *receiptManagerStub;
@property(strong, nonatomic) InAppPurchasePlugin *plugin;
@end
@implementation InAppPurchasePluginTest
- (void)setUp {
self.receiptManagerStub = [FIAPReceiptManagerStub new];
self.plugin = [[InAppPurchasePluginStub alloc] initWithReceiptManager:self.receiptManagerStub];
}
- (void)tearDown {
}
- (void)testInvalidMethodCall {
XCTestExpectation *expectation =
[self expectationWithDescription:@"expect result to be not implemented"];
FlutterMethodCall *call = [FlutterMethodCall methodCallWithMethodName:@"invalid" arguments:NULL];
__block id result;
[self.plugin handleMethodCall:call
result:^(id r) {
[expectation fulfill];
result = r;
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertEqual(result, FlutterMethodNotImplemented);
}
- (void)testCanMakePayments {
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result to be YES"];
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[SKPaymentQueue canMakePayments:]"
arguments:NULL];
__block id result;
[self.plugin handleMethodCall:call
result:^(id r) {
[expectation fulfill];
result = r;
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertEqual(result, @YES);
}
- (void)testGetProductResponse {
XCTestExpectation *expectation =
[self expectationWithDescription:@"expect response contains 1 item"];
FlutterMethodCall *call = [FlutterMethodCall
methodCallWithMethodName:@"-[InAppPurchasePlugin startProductRequest:result:]"
arguments:@[ @"123" ]];
__block id result;
[self.plugin handleMethodCall:call
result:^(id r) {
[expectation fulfill];
result = r;
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssert([result isKindOfClass:[NSDictionary class]]);
NSArray *resultArray = [result objectForKey:@"products"];
XCTAssertEqual(resultArray.count, 1);
XCTAssertTrue([resultArray.firstObject[@"productIdentifier"] isEqualToString:@"123"]);
}
- (void)testAddPaymentShouldReturnFlutterErrorWhenArgumentsAreInvalid {
XCTestExpectation *expectation =
[self expectationWithDescription:
@"Result should contain a FlutterError when invalid parameters are passed in."];
NSString *argument = @"Invalid argument";
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[InAppPurchasePlugin addPayment:result:]"
arguments:argument];
[self.plugin handleMethodCall:call
result:^(id _Nullable result) {
FlutterError *error = result;
XCTAssertEqualObjects(@"storekit_invalid_argument", error.code);
XCTAssertEqualObjects(@"Argument type of addPayment is not a Dictionary",
error.message);
XCTAssertEqualObjects(argument, error.details);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
}
- (void)testAddPaymentShouldReturnFlutterErrorWhenPaymentFails {
NSDictionary *arguments = @{
@"productIdentifier" : @"123",
@"quantity" : @(1),
@"simulatesAskToBuyInSandbox" : @YES,
};
XCTestExpectation *expectation =
[self expectationWithDescription:@"Result should return failed state."];
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[InAppPurchasePlugin addPayment:result:]"
arguments:arguments];
FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class);
OCMStub([mockHandler addPayment:[OCMArg any]]).andReturn(NO);
self.plugin.paymentQueueHandler = mockHandler;
[self.plugin handleMethodCall:call
result:^(id _Nullable result) {
FlutterError *error = result;
XCTAssertEqualObjects(@"storekit_duplicate_product_object", error.code);
XCTAssertEqualObjects(
@"There is a pending transaction for the same product identifier. "
@"Please either wait for it to be finished or finish it manually "
@"using `completePurchase` to avoid edge cases.",
error.message);
XCTAssertEqualObjects(arguments, error.details);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
OCMVerify(times(1), [mockHandler addPayment:[OCMArg any]]);
}
- (void)testAddPaymentSuccessWithoutPaymentDiscount {
XCTestExpectation *expectation =
[self expectationWithDescription:@"Result should return success state"];
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[InAppPurchasePlugin addPayment:result:]"
arguments:@{
@"productIdentifier" : @"123",
@"quantity" : @(1),
@"simulatesAskToBuyInSandbox" : @YES,
}];
FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class);
OCMStub([mockHandler addPayment:[OCMArg any]]).andReturn(YES);
self.plugin.paymentQueueHandler = mockHandler;
[self.plugin handleMethodCall:call
result:^(id _Nullable result) {
XCTAssertNil(result);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
}
- (void)testAddPaymentSuccessWithPaymentDiscount {
XCTestExpectation *expectation =
[self expectationWithDescription:@"Result should return success state"];
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[InAppPurchasePlugin addPayment:result:]"
arguments:@{
@"productIdentifier" : @"123",
@"quantity" : @(1),
@"simulatesAskToBuyInSandbox" : @YES,
@"paymentDiscount" : @{
@"identifier" : @"test_identifier",
@"keyIdentifier" : @"test_key_identifier",
@"nonce" : @"4a11a9cc-3bc3-11ec-8d3d-0242ac130003",
@"signature" : @"test_signature",
@"timestamp" : @(1635847102),
}
}];
FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class);
OCMStub([mockHandler addPayment:[OCMArg any]]).andReturn(YES);
self.plugin.paymentQueueHandler = mockHandler;
[self.plugin handleMethodCall:call
result:^(id _Nullable result) {
XCTAssertNil(result);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
OCMVerify(
times(1),
[mockHandler
addPayment:[OCMArg checkWithBlock:^BOOL(id obj) {
SKPayment *payment = obj;
if (@available(iOS 12.2, *)) {
SKPaymentDiscount *discount = payment.paymentDiscount;
return [discount.identifier isEqual:@"test_identifier"] &&
[discount.keyIdentifier isEqual:@"test_key_identifier"] &&
[discount.nonce
isEqual:[[NSUUID alloc]
initWithUUIDString:@"4a11a9cc-3bc3-11ec-8d3d-0242ac130003"]] &&
[discount.signature isEqual:@"test_signature"] &&
[discount.timestamp isEqual:@(1635847102)];
}
return YES;
}]]);
}
- (void)testAddPaymentFailureWithInvalidPaymentDiscount {
// Support for payment discount is only available on iOS 12.2 and higher.
if (@available(iOS 12.2, *)) {
XCTestExpectation *expectation =
[self expectationWithDescription:@"Result should return success state"];
NSDictionary *arguments = @{
@"productIdentifier" : @"123",
@"quantity" : @(1),
@"simulatesAskToBuyInSandbox" : @YES,
@"paymentDiscount" : @{
@"keyIdentifier" : @"test_key_identifier",
@"nonce" : @"4a11a9cc-3bc3-11ec-8d3d-0242ac130003",
@"signature" : @"test_signature",
@"timestamp" : @(1635847102),
}
};
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[InAppPurchasePlugin addPayment:result:]"
arguments:arguments];
FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class);
id translator = OCMClassMock(FIAObjectTranslator.class);
NSString *error = @"Some error occurred";
OCMStub(ClassMethod([translator
getSKPaymentDiscountFromMap:[OCMArg any]
withError:(NSString __autoreleasing **)[OCMArg setTo:error]]))
.andReturn(nil);
self.plugin.paymentQueueHandler = mockHandler;
[self.plugin
handleMethodCall:call
result:^(id _Nullable result) {
FlutterError *error = result;
XCTAssertEqualObjects(@"storekit_invalid_payment_discount_object", error.code);
XCTAssertEqualObjects(
@"You have requested a payment and specified a "
@"payment discount with invalid properties. Some error occurred",
error.message);
XCTAssertEqualObjects(arguments, error.details);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
OCMVerify(never(), [mockHandler addPayment:[OCMArg any]]);
}
}
- (void)testAddPaymentWithNullSandboxArgument {
XCTestExpectation *expectation =
[self expectationWithDescription:@"result should return success state"];
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[InAppPurchasePlugin addPayment:result:]"
arguments:@{
@"productIdentifier" : @"123",
@"quantity" : @(1),
@"simulatesAskToBuyInSandbox" : [NSNull null],
}];
FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class);
OCMStub([mockHandler addPayment:[OCMArg any]]).andReturn(YES);
self.plugin.paymentQueueHandler = mockHandler;
[self.plugin handleMethodCall:call
result:^(id _Nullable result) {
XCTAssertNil(result);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
OCMVerify(times(1), [mockHandler addPayment:[OCMArg checkWithBlock:^BOOL(id obj) {
SKPayment *payment = obj;
return !payment.simulatesAskToBuyInSandbox;
}]]);
}
- (void)testRestoreTransactions {
XCTestExpectation *expectation =
[self expectationWithDescription:@"result successfully restore transactions"];
FlutterMethodCall *call = [FlutterMethodCall
methodCallWithMethodName:@"-[InAppPurchasePlugin restoreTransactions:result:]"
arguments:nil];
SKPaymentQueueStub *queue = [SKPaymentQueueStub new];
queue.testState = SKPaymentTransactionStatePurchased;
__block BOOL callbackInvoked = NO;
self.plugin.paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
}
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:^() {
callbackInvoked = YES;
[expectation fulfill];
}
shouldAddStorePayment:nil
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
[queue addTransactionObserver:self.plugin.paymentQueueHandler];
[self.plugin handleMethodCall:call
result:^(id r){
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertTrue(callbackInvoked);
}
- (void)testRetrieveReceiptDataSuccess {
XCTestExpectation *expectation = [self expectationWithDescription:@"receipt data retrieved"];
FlutterMethodCall *call = [FlutterMethodCall
methodCallWithMethodName:@"-[InAppPurchasePlugin retrieveReceiptData:result:]"
arguments:nil];
__block NSDictionary *result;
[self.plugin handleMethodCall:call
result:^(id r) {
result = r;
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertNotNil(result);
XCTAssert([result isKindOfClass:[NSString class]]);
}
- (void)testRetrieveReceiptDataNil {
NSBundle *mockBundle = OCMPartialMock([NSBundle mainBundle]);
OCMStub(mockBundle.appStoreReceiptURL).andReturn(nil);
XCTestExpectation *expectation = [self expectationWithDescription:@"nil receipt data retrieved"];
FlutterMethodCall *call = [FlutterMethodCall
methodCallWithMethodName:@"-[InAppPurchasePlugin retrieveReceiptData:result:]"
arguments:nil];
__block NSDictionary *result;
[self.plugin handleMethodCall:call
result:^(id r) {
result = r;
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertNil(result);
}
- (void)testRetrieveReceiptDataError {
XCTestExpectation *expectation = [self expectationWithDescription:@"receipt data retrieved"];
FlutterMethodCall *call = [FlutterMethodCall
methodCallWithMethodName:@"-[InAppPurchasePlugin retrieveReceiptData:result:]"
arguments:nil];
__block NSDictionary *result;
self.receiptManagerStub.returnError = YES;
[self.plugin handleMethodCall:call
result:^(id r) {
result = r;
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertNotNil(result);
XCTAssert([result isKindOfClass:[FlutterError class]]);
NSDictionary *details = ((FlutterError *)result).details;
XCTAssertNotNil(details[@"error"]);
NSNumber *errorCode = (NSNumber *)details[@"error"][@"code"];
XCTAssertEqual(errorCode, [NSNumber numberWithInteger:99]);
}
- (void)testRefreshReceiptRequest {
XCTestExpectation *expectation = [self expectationWithDescription:@"expect success"];
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[InAppPurchasePlugin refreshReceipt:result:]"
arguments:nil];
__block BOOL result = NO;
[self.plugin handleMethodCall:call
result:^(id r) {
result = YES;
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertTrue(result);
}
- (void)testPresentCodeRedemptionSheet {
XCTestExpectation *expectation =
[self expectationWithDescription:@"expect successfully present Code Redemption Sheet"];
FlutterMethodCall *call = [FlutterMethodCall
methodCallWithMethodName:@"-[InAppPurchasePlugin presentCodeRedemptionSheet:result:]"
arguments:nil];
__block BOOL callbackInvoked = NO;
[self.plugin handleMethodCall:call
result:^(id r) {
callbackInvoked = YES;
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertTrue(callbackInvoked);
}
- (void)testGetPendingTransactions {
XCTestExpectation *expectation = [self expectationWithDescription:@"expect success"];
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[SKPaymentQueue transactions]" arguments:nil];
SKPaymentQueue *mockQueue = OCMClassMock(SKPaymentQueue.class);
NSDictionary *transactionMap = @{
@"transactionIdentifier" : [NSNull null],
@"transactionState" : @(SKPaymentTransactionStatePurchasing),
@"payment" : [NSNull null],
@"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub"
code:123
userInfo:@{}]],
@"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970),
@"originalTransaction" : [NSNull null],
};
OCMStub(mockQueue.transactions).andReturn(@[ [[SKPaymentTransactionStub alloc]
initWithMap:transactionMap] ]);
__block NSArray *resultArray;
self.plugin.paymentQueueHandler =
[[FIAPaymentQueueHandler alloc] initWithQueue:mockQueue
transactionsUpdated:nil
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:nil
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
[self.plugin handleMethodCall:call
result:^(id r) {
resultArray = r;
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertEqualObjects(resultArray, @[ transactionMap ]);
}
- (void)testStartObservingPaymentQueue {
XCTestExpectation *expectation =
[self expectationWithDescription:@"Should return success result"];
FlutterMethodCall *startCall = [FlutterMethodCall
methodCallWithMethodName:@"-[SKPaymentQueue startObservingTransactionQueue]"
arguments:nil];
FIAPaymentQueueHandler *mockHandler = OCMClassMock([FIAPaymentQueueHandler class]);
self.plugin.paymentQueueHandler = mockHandler;
[self.plugin handleMethodCall:startCall
result:^(id _Nullable result) {
XCTAssertNil(result);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
OCMVerify(times(1), [mockHandler startObservingPaymentQueue]);
}
- (void)testStopObservingPaymentQueue {
XCTestExpectation *expectation =
[self expectationWithDescription:@"Should return success result"];
FlutterMethodCall *stopCall =
[FlutterMethodCall methodCallWithMethodName:@"-[SKPaymentQueue stopObservingTransactionQueue]"
arguments:nil];
FIAPaymentQueueHandler *mockHandler = OCMClassMock([FIAPaymentQueueHandler class]);
self.plugin.paymentQueueHandler = mockHandler;
[self.plugin handleMethodCall:stopCall
result:^(id _Nullable result) {
XCTAssertNil(result);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:5];
OCMVerify(times(1), [mockHandler stopObservingPaymentQueue]);
}
#if TARGET_OS_IOS
- (void)testRegisterPaymentQueueDelegate {
if (@available(iOS 13, *)) {
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[SKPaymentQueue registerDelegate]"
arguments:nil];
self.plugin.paymentQueueHandler =
[[FIAPaymentQueueHandler alloc] initWithQueue:[SKPaymentQueueStub new]
transactionsUpdated:nil
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:nil
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
// Verify the delegate is nil before we register one.
XCTAssertNil(self.plugin.paymentQueueHandler.delegate);
[self.plugin handleMethodCall:call
result:^(id r){
}];
// Verify the delegate is not nil after we registered one.
XCTAssertNotNil(self.plugin.paymentQueueHandler.delegate);
}
}
#endif
- (void)testRemovePaymentQueueDelegate {
if (@available(iOS 13, *)) {
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[SKPaymentQueue removeDelegate]"
arguments:nil];
self.plugin.paymentQueueHandler =
[[FIAPaymentQueueHandler alloc] initWithQueue:[SKPaymentQueueStub new]
transactionsUpdated:nil
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:nil
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
self.plugin.paymentQueueHandler.delegate = OCMProtocolMock(@protocol(SKPaymentQueueDelegate));
// Verify the delegate is not nil before removing it.
XCTAssertNotNil(self.plugin.paymentQueueHandler.delegate);
[self.plugin handleMethodCall:call
result:^(id r){
}];
// Verify the delegate is nill after removing it.
XCTAssertNil(self.plugin.paymentQueueHandler.delegate);
}
}
#if TARGET_OS_IOS
- (void)testShowPriceConsentIfNeeded {
FlutterMethodCall *call =
[FlutterMethodCall methodCallWithMethodName:@"-[SKPaymentQueue showPriceConsentIfNeeded]"
arguments:nil];
FIAPaymentQueueHandler *mockQueueHandler = OCMClassMock(FIAPaymentQueueHandler.class);
self.plugin.paymentQueueHandler = mockQueueHandler;
[self.plugin handleMethodCall:call
result:^(id r){
}];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
if (@available(iOS 13.4, *)) {
OCMVerify(times(1), [mockQueueHandler showPriceConsentIfNeeded]);
} else {
OCMVerify(never(), [mockQueueHandler showPriceConsentIfNeeded]);
}
#pragma clang diagnostic pop
}
#endif
@end
| plugins/packages/in_app_purchase/in_app_purchase_storekit/example/ios/RunnerTests/InAppPurchasePluginTests.m/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/example/ios/RunnerTests/InAppPurchasePluginTests.m",
"repo_id": "plugins",
"token_count": 11421
} | 1,294 |
// 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 "FIAObjectTranslator.h"
#pragma mark - SKProduct Coders
@implementation FIAObjectTranslator
+ (NSDictionary *)getMapFromSKProduct:(SKProduct *)product {
if (!product) {
return nil;
}
NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{
@"localizedDescription" : product.localizedDescription ?: [NSNull null],
@"localizedTitle" : product.localizedTitle ?: [NSNull null],
@"productIdentifier" : product.productIdentifier ?: [NSNull null],
@"price" : product.price.description ?: [NSNull null]
}];
// TODO(cyanglaz): NSLocale is a complex object, want to see the actual need of getting this
// expanded to a map. Matching android to only get the currencySymbol for now.
// https://github.com/flutter/flutter/issues/26610
[map setObject:[FIAObjectTranslator getMapFromNSLocale:product.priceLocale] ?: [NSNull null]
forKey:@"priceLocale"];
if (@available(iOS 11.2, *)) {
[map setObject:[FIAObjectTranslator
getMapFromSKProductSubscriptionPeriod:product.subscriptionPeriod]
?: [NSNull null]
forKey:@"subscriptionPeriod"];
}
if (@available(iOS 11.2, *)) {
[map setObject:[FIAObjectTranslator getMapFromSKProductDiscount:product.introductoryPrice]
?: [NSNull null]
forKey:@"introductoryPrice"];
}
if (@available(iOS 12.2, *)) {
[map setObject:[FIAObjectTranslator getMapArrayFromSKProductDiscounts:product.discounts]
forKey:@"discounts"];
}
if (@available(iOS 12.0, *)) {
[map setObject:product.subscriptionGroupIdentifier ?: [NSNull null]
forKey:@"subscriptionGroupIdentifier"];
}
return map;
}
+ (NSDictionary *)getMapFromSKProductSubscriptionPeriod:(SKProductSubscriptionPeriod *)period {
if (!period) {
return nil;
}
return @{@"numberOfUnits" : @(period.numberOfUnits), @"unit" : @(period.unit)};
}
+ (nonnull NSArray *)getMapArrayFromSKProductDiscounts:
(nonnull NSArray<SKProductDiscount *> *)productDiscounts {
NSMutableArray *discountsMapArray = [[NSMutableArray alloc] init];
for (SKProductDiscount *productDiscount in productDiscounts) {
[discountsMapArray addObject:[FIAObjectTranslator getMapFromSKProductDiscount:productDiscount]];
}
return discountsMapArray;
}
+ (NSDictionary *)getMapFromSKProductDiscount:(SKProductDiscount *)discount {
if (!discount) {
return nil;
}
NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{
@"price" : discount.price.description ?: [NSNull null],
@"numberOfPeriods" : @(discount.numberOfPeriods),
@"subscriptionPeriod" :
[FIAObjectTranslator getMapFromSKProductSubscriptionPeriod:discount.subscriptionPeriod]
?: [NSNull null],
@"paymentMode" : @(discount.paymentMode),
}];
if (@available(iOS 12.2, *)) {
[map setObject:discount.identifier ?: [NSNull null] forKey:@"identifier"];
[map setObject:@(discount.type) forKey:@"type"];
}
// TODO(cyanglaz): NSLocale is a complex object, want to see the actual need of getting this
// expanded to a map. Matching android to only get the currencySymbol for now.
// https://github.com/flutter/flutter/issues/26610
[map setObject:[FIAObjectTranslator getMapFromNSLocale:discount.priceLocale] ?: [NSNull null]
forKey:@"priceLocale"];
return map;
}
+ (NSDictionary *)getMapFromSKProductsResponse:(SKProductsResponse *)productResponse {
if (!productResponse) {
return nil;
}
NSMutableArray *productsMapArray = [NSMutableArray new];
for (SKProduct *product in productResponse.products) {
[productsMapArray addObject:[FIAObjectTranslator getMapFromSKProduct:product]];
}
return @{
@"products" : productsMapArray,
@"invalidProductIdentifiers" : productResponse.invalidProductIdentifiers ?: @[]
};
}
+ (NSDictionary *)getMapFromSKPayment:(SKPayment *)payment {
if (!payment) {
return nil;
}
NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{
@"productIdentifier" : payment.productIdentifier ?: [NSNull null],
@"requestData" : payment.requestData ? [[NSString alloc] initWithData:payment.requestData
encoding:NSUTF8StringEncoding]
: [NSNull null],
@"quantity" : @(payment.quantity),
@"applicationUsername" : payment.applicationUsername ?: [NSNull null]
}];
[map setObject:@(payment.simulatesAskToBuyInSandbox) forKey:@"simulatesAskToBuyInSandbox"];
return map;
}
+ (NSDictionary *)getMapFromNSLocale:(NSLocale *)locale {
if (!locale) {
return nil;
}
NSMutableDictionary *map = [[NSMutableDictionary alloc] init];
[map setObject:[locale objectForKey:NSLocaleCurrencySymbol] ?: [NSNull null]
forKey:@"currencySymbol"];
[map setObject:[locale objectForKey:NSLocaleCurrencyCode] ?: [NSNull null]
forKey:@"currencyCode"];
[map setObject:[locale objectForKey:NSLocaleCountryCode] ?: [NSNull null] forKey:@"countryCode"];
return map;
}
+ (SKMutablePayment *)getSKMutablePaymentFromMap:(NSDictionary *)map {
if (!map) {
return nil;
}
SKMutablePayment *payment = [[SKMutablePayment alloc] init];
payment.productIdentifier = map[@"productIdentifier"];
NSString *utf8String = map[@"requestData"];
payment.requestData = [utf8String dataUsingEncoding:NSUTF8StringEncoding];
payment.quantity = [map[@"quantity"] integerValue];
payment.applicationUsername = map[@"applicationUsername"];
payment.simulatesAskToBuyInSandbox = [map[@"simulatesAskToBuyInSandbox"] boolValue];
return payment;
}
+ (NSDictionary *)getMapFromSKPaymentTransaction:(SKPaymentTransaction *)transaction {
if (!transaction) {
return nil;
}
NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{
@"error" : [FIAObjectTranslator getMapFromNSError:transaction.error] ?: [NSNull null],
@"payment" : transaction.payment ? [FIAObjectTranslator getMapFromSKPayment:transaction.payment]
: [NSNull null],
@"originalTransaction" : transaction.originalTransaction
? [FIAObjectTranslator getMapFromSKPaymentTransaction:transaction.originalTransaction]
: [NSNull null],
@"transactionTimeStamp" : transaction.transactionDate
? @(transaction.transactionDate.timeIntervalSince1970)
: [NSNull null],
@"transactionIdentifier" : transaction.transactionIdentifier ?: [NSNull null],
@"transactionState" : @(transaction.transactionState)
}];
return map;
}
+ (NSDictionary *)getMapFromNSError:(NSError *)error {
if (!error) {
return nil;
}
NSMutableDictionary *userInfo = [NSMutableDictionary new];
for (NSErrorUserInfoKey key in error.userInfo) {
id value = error.userInfo[key];
userInfo[key] = [FIAObjectTranslator encodeNSErrorUserInfo:value];
}
return @{@"code" : @(error.code), @"domain" : error.domain ?: @"", @"userInfo" : userInfo};
}
+ (id)encodeNSErrorUserInfo:(id)value {
if ([value isKindOfClass:[NSError class]]) {
return [FIAObjectTranslator getMapFromNSError:value];
} else if ([value isKindOfClass:[NSURL class]]) {
return [value absoluteString];
} else if ([value isKindOfClass:[NSNumber class]]) {
return value;
} else if ([value isKindOfClass:[NSString class]]) {
return value;
} else if ([value isKindOfClass:[NSArray class]]) {
NSMutableArray *errors = [[NSMutableArray alloc] init];
for (id error in value) {
[errors addObject:[FIAObjectTranslator encodeNSErrorUserInfo:error]];
}
return errors;
} else {
return [NSString
stringWithFormat:
@"Unable to encode native userInfo object of type %@ to map. Please submit an issue at "
@"https://github.com/flutter/flutter/issues/new with the title "
@"\"[in_app_purchase_storekit] "
@"Unable to encode userInfo of type %@\" and add reproduction steps and the error "
@"details in "
@"the description field.",
[value class], [value class]];
}
}
+ (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront {
if (!storefront) {
return nil;
}
NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{
@"countryCode" : storefront.countryCode,
@"identifier" : storefront.identifier
}];
return map;
}
+ (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront
andSKPaymentTransaction:(SKPaymentTransaction *)transaction {
if (!storefront || !transaction) {
return nil;
}
NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithDictionary:@{
@"storefront" : [FIAObjectTranslator getMapFromSKStorefront:storefront],
@"transaction" : [FIAObjectTranslator getMapFromSKPaymentTransaction:transaction]
}];
return map;
}
+ (SKPaymentDiscount *)getSKPaymentDiscountFromMap:(NSDictionary *)map
withError:(NSString **)error {
if (!map || map.count <= 0) {
return nil;
}
NSString *identifier = map[@"identifier"];
NSString *keyIdentifier = map[@"keyIdentifier"];
NSString *nonce = map[@"nonce"];
NSString *signature = map[@"signature"];
NSNumber *timestamp = map[@"timestamp"];
if (!identifier || ![identifier isKindOfClass:NSString.class] ||
[identifier isEqualToString:@""]) {
if (error) {
*error = @"When specifying a payment discount the 'identifier' field is mandatory.";
}
return nil;
}
if (!keyIdentifier || ![keyIdentifier isKindOfClass:NSString.class] ||
[keyIdentifier isEqualToString:@""]) {
if (error) {
*error = @"When specifying a payment discount the 'keyIdentifier' field is mandatory.";
}
return nil;
}
if (!nonce || ![nonce isKindOfClass:NSString.class] || [nonce isEqualToString:@""]) {
if (error) {
*error = @"When specifying a payment discount the 'nonce' field is mandatory.";
}
return nil;
}
if (!signature || ![signature isKindOfClass:NSString.class] || [signature isEqualToString:@""]) {
if (error) {
*error = @"When specifying a payment discount the 'signature' field is mandatory.";
}
return nil;
}
if (!timestamp || ![timestamp isKindOfClass:NSNumber.class] || [timestamp longLongValue] <= 0) {
if (error) {
*error = @"When specifying a payment discount the 'timestamp' field is mandatory.";
}
return nil;
}
SKPaymentDiscount *discount =
[[SKPaymentDiscount alloc] initWithIdentifier:identifier
keyIdentifier:keyIdentifier
nonce:[[NSUUID alloc] initWithUUIDString:nonce]
signature:signature
timestamp:timestamp];
return discount;
}
@end
| plugins/packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAObjectTranslator.m/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/ios/Classes/FIAObjectTranslator.m",
"repo_id": "plugins",
"token_count": 4249
} | 1,295 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../in_app_purchase_storekit.dart';
import '../store_kit_wrappers.dart';
/// [IAPError.code] code for failed purchases.
const String kPurchaseErrorCode = 'purchase_error';
/// Indicates store front is Apple AppStore.
const String kIAPSource = 'app_store';
/// An [InAppPurchasePlatform] that wraps StoreKit.
///
/// This translates various `StoreKit` calls and responses into the
/// generic plugin API.
class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform {
/// Creates an [InAppPurchaseStoreKitPlatform] object.
///
/// This constructor should only be used for testing, for any other purpose
/// get the connection from the [instance] getter.
@visibleForTesting
InAppPurchaseStoreKitPlatform();
static late SKPaymentQueueWrapper _skPaymentQueueWrapper;
static late _TransactionObserver _observer;
@override
Stream<List<PurchaseDetails>> get purchaseStream =>
_observer.purchaseUpdatedController.stream;
/// Callback handler for transaction status changes.
@visibleForTesting
static SKTransactionObserverWrapper get observer => _observer;
/// Registers this class as the default instance of [InAppPurchasePlatform].
static void registerPlatform() {
// Register the [InAppPurchaseStoreKitPlatformAddition] containing
// StoreKit-specific functionality.
InAppPurchasePlatformAddition.instance =
InAppPurchaseStoreKitPlatformAddition();
// Register the platform-specific implementation of the idiomatic
// InAppPurchase API.
InAppPurchasePlatform.instance = InAppPurchaseStoreKitPlatform();
_skPaymentQueueWrapper = SKPaymentQueueWrapper();
// Create a purchaseUpdatedController and notify the native side when to
// start of stop sending updates.
final StreamController<List<PurchaseDetails>> updateController =
StreamController<List<PurchaseDetails>>.broadcast(
onListen: () => _skPaymentQueueWrapper.startObservingTransactionQueue(),
onCancel: () => _skPaymentQueueWrapper.stopObservingTransactionQueue(),
);
_observer = _TransactionObserver(updateController);
_skPaymentQueueWrapper.setTransactionObserver(observer);
}
@override
Future<bool> isAvailable() => SKPaymentQueueWrapper.canMakePayments();
@override
Future<bool> buyNonConsumable({required PurchaseParam purchaseParam}) async {
await _skPaymentQueueWrapper.addPayment(SKPaymentWrapper(
productIdentifier: purchaseParam.productDetails.id,
quantity:
purchaseParam is AppStorePurchaseParam ? purchaseParam.quantity : 1,
applicationUsername: purchaseParam.applicationUserName,
simulatesAskToBuyInSandbox: purchaseParam is AppStorePurchaseParam &&
purchaseParam.simulatesAskToBuyInSandbox,
paymentDiscount: purchaseParam is AppStorePurchaseParam
? purchaseParam.discount
: null));
return true; // There's no error feedback from iOS here to return.
}
@override
Future<bool> buyConsumable(
{required PurchaseParam purchaseParam, bool autoConsume = true}) {
assert(autoConsume == true, 'On iOS, we should always auto consume');
return buyNonConsumable(purchaseParam: purchaseParam);
}
@override
Future<void> completePurchase(PurchaseDetails purchase) {
assert(
purchase is AppStorePurchaseDetails,
'On iOS, the `purchase` should always be of type `AppStorePurchaseDetails`.',
);
return _skPaymentQueueWrapper.finishTransaction(
(purchase as AppStorePurchaseDetails).skPaymentTransaction,
);
}
@override
Future<void> restorePurchases({String? applicationUserName}) async {
return _observer
.restoreTransactions(
queue: _skPaymentQueueWrapper,
applicationUserName: applicationUserName)
.whenComplete(() => _observer.cleanUpRestoredTransactions());
}
/// Query the product detail list.
///
/// This method only returns [ProductDetailsResponse].
/// To get detailed Store Kit product list, use [SkProductResponseWrapper.startProductRequest]
/// to get the [SKProductResponseWrapper].
@override
Future<ProductDetailsResponse> queryProductDetails(
Set<String> identifiers) async {
final SKRequestMaker requestMaker = SKRequestMaker();
SkProductResponseWrapper response;
PlatformException? exception;
try {
response = await requestMaker.startProductRequest(identifiers.toList());
} on PlatformException catch (e) {
exception = e;
response = SkProductResponseWrapper(
products: const <SKProductWrapper>[],
invalidProductIdentifiers: identifiers.toList());
}
List<AppStoreProductDetails> productDetails = <AppStoreProductDetails>[];
if (response.products != null) {
productDetails = response.products
.map((SKProductWrapper productWrapper) =>
AppStoreProductDetails.fromSKProduct(productWrapper))
.toList();
}
List<String> invalidIdentifiers = response.invalidProductIdentifiers;
if (productDetails.isEmpty) {
invalidIdentifiers = identifiers.toList();
}
final ProductDetailsResponse productDetailsResponse =
ProductDetailsResponse(
productDetails: productDetails,
notFoundIDs: invalidIdentifiers,
error: exception == null
? null
: IAPError(
source: kIAPSource,
code: exception.code,
message: exception.message ?? '',
details: exception.details),
);
return productDetailsResponse;
}
}
enum _TransactionRestoreState {
notRunning,
waitingForTransactions,
receivedTransaction,
}
class _TransactionObserver implements SKTransactionObserverWrapper {
_TransactionObserver(this.purchaseUpdatedController);
final StreamController<List<PurchaseDetails>> purchaseUpdatedController;
Completer<void>? _restoreCompleter;
late String _receiptData;
_TransactionRestoreState _transactionRestoreState =
_TransactionRestoreState.notRunning;
Future<void> restoreTransactions({
required SKPaymentQueueWrapper queue,
String? applicationUserName,
}) {
_transactionRestoreState = _TransactionRestoreState.waitingForTransactions;
_restoreCompleter = Completer<void>();
queue.restoreTransactions(applicationUserName: applicationUserName);
return _restoreCompleter!.future;
}
void cleanUpRestoredTransactions() {
_restoreCompleter = null;
}
@override
void updatedTransactions(
{required List<SKPaymentTransactionWrapper> transactions}) {
_handleTransationUpdates(transactions);
}
@override
void removedTransactions(
{required List<SKPaymentTransactionWrapper> transactions}) {}
/// Triggered when there is an error while restoring transactions.
@override
void restoreCompletedTransactionsFailed({required SKError error}) {
_restoreCompleter!.completeError(error);
_transactionRestoreState = _TransactionRestoreState.notRunning;
}
@override
void paymentQueueRestoreCompletedTransactionsFinished() {
_restoreCompleter!.complete();
// If no restored transactions were received during the restore session
// emit an empty list of purchase details to inform listeners that the
// restore session finished without any results.
if (_transactionRestoreState ==
_TransactionRestoreState.waitingForTransactions) {
purchaseUpdatedController.add(<PurchaseDetails>[]);
}
_transactionRestoreState = _TransactionRestoreState.notRunning;
}
@override
bool shouldAddStorePayment(
{required SKPaymentWrapper payment, required SKProductWrapper product}) {
// In this unified API, we always return true to keep it consistent with the behavior on Google Play.
return true;
}
Future<String> getReceiptData() async {
try {
_receiptData = await SKReceiptManager.retrieveReceiptData();
} catch (e) {
_receiptData = '';
}
return _receiptData;
}
Future<void> _handleTransationUpdates(
List<SKPaymentTransactionWrapper> transactions) async {
if (_transactionRestoreState ==
_TransactionRestoreState.waitingForTransactions &&
transactions.any((SKPaymentTransactionWrapper transaction) =>
transaction.transactionState ==
SKPaymentTransactionStateWrapper.restored)) {
_transactionRestoreState = _TransactionRestoreState.receivedTransaction;
}
final String receiptData = await getReceiptData();
final List<PurchaseDetails> purchases = transactions
.map((SKPaymentTransactionWrapper transaction) =>
AppStorePurchaseDetails.fromSKTransaction(transaction, receiptData))
.toList();
purchaseUpdatedController.add(purchases);
}
}
| plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform.dart",
"repo_id": "plugins",
"token_count": 2900
} | 1,296 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../../store_kit_wrappers.dart';
/// The class represents the information of a product as registered in the Apple
/// AppStore.
class AppStoreProductDetails extends ProductDetails {
/// Creates a new AppStore specific product details object with the provided
/// details.
AppStoreProductDetails({
required super.id,
required super.title,
required super.description,
required super.price,
required super.rawPrice,
required super.currencyCode,
required this.skProduct,
required super.currencySymbol,
});
/// Generate a [AppStoreProductDetails] object based on an iOS [SKProductWrapper] object.
factory AppStoreProductDetails.fromSKProduct(SKProductWrapper product) {
return AppStoreProductDetails(
id: product.productIdentifier,
title: product.localizedTitle,
description: product.localizedDescription,
price: product.priceLocale.currencySymbol + product.price,
rawPrice: double.parse(product.price),
currencyCode: product.priceLocale.currencyCode,
currencySymbol: product.priceLocale.currencySymbol.isNotEmpty
? product.priceLocale.currencySymbol
: product.priceLocale.currencyCode,
skProduct: product,
);
}
/// Points back to the [SKProductWrapper] object that was used to generate
/// this [AppStoreProductDetails] object.
final SKProductWrapper skProduct;
}
| plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/app_store_product_details.dart/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/app_store_product_details.dart",
"repo_id": "plugins",
"token_count": 505
} | 1,297 |
// 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 "FIATransactionCache.h"
@interface FIATransactionCache ()
/// A NSMutableDictionary storing the objects that are cached.
@property(nonatomic, strong, nonnull) NSMutableDictionary *cache;
@end
@implementation FIATransactionCache
- (instancetype)init {
self = [super init];
if (self) {
self.cache = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)addObjects:(NSArray *)objects forKey:(TransactionCacheKey)key {
NSArray *cachedObjects = self.cache[@(key)];
self.cache[@(key)] =
cachedObjects ? [cachedObjects arrayByAddingObjectsFromArray:objects] : objects;
}
- (NSArray *)getObjectsForKey:(TransactionCacheKey)key {
return self.cache[@(key)];
}
- (void)clear {
[self.cache removeAllObjects];
}
@end
| plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/FIATransactionCache.m/0 | {
"file_path": "plugins/packages/in_app_purchase/in_app_purchase_storekit/macos/Classes/FIATransactionCache.m",
"repo_id": "plugins",
"token_count": 309
} | 1,298 |
// 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:ios_platform_images/ios_platform_images.dart';
void main() => runApp(const MyApp());
/// Main widget for the example app.
class MyApp extends StatefulWidget {
/// Default Constructor
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
IosPlatformImages.resolveURL('textfile')
// ignore: avoid_print
.then((String? value) => print(value));
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
// "flutter" is a resource in Assets.xcassets.
child: Image(
image: IosPlatformImages.load('flutter'),
semanticLabel: 'Flutter logo',
),
),
),
);
}
}
| plugins/packages/ios_platform_images/example/lib/main.dart/0 | {
"file_path": "plugins/packages/ios_platform_images/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 450
} | 1,299 |
# local_auth
<?code-excerpt path-base="excerpts/packages/local_auth_example"?>
This Flutter plugin provides means to perform local, on-device authentication of
the user.
On supported devices, this includes authentication with biometrics such as
fingerprint or facial recognition.
| | Android | iOS | Windows |
|-------------|-----------|------|-------------|
| **Support** | SDK 16+\* | 9.0+ | Windows 10+ |
## Usage
### Device Capabilities
To check whether there is local authentication available on this device or not,
call `canCheckBiometrics` (if you need biometrics support) and/or
`isDeviceSupported()` (if you just need some device-level authentication):
<?code-excerpt "readme_excerpts.dart (CanCheck)"?>
```dart
import 'package:local_auth/local_auth.dart';
// ···
final LocalAuthentication auth = LocalAuthentication();
// ···
final bool canAuthenticateWithBiometrics = await auth.canCheckBiometrics;
final bool canAuthenticate =
canAuthenticateWithBiometrics || await auth.isDeviceSupported();
```
Currently the following biometric types are implemented:
- BiometricType.face
- BiometricType.fingerprint
- BiometricType.weak
- BiometricType.strong
### Enrolled Biometrics
`canCheckBiometrics` only indicates whether hardware support is available, not
whether the device has any biometrics enrolled. To get a list of enrolled
biometrics, call `getAvailableBiometrics()`.
The types are device-specific and platform-specific, and other types may be
added in the future, so when possible you should not rely on specific biometric
types and only check that some biometric is enrolled:
<?code-excerpt "readme_excerpts.dart (Enrolled)"?>
```dart
final List<BiometricType> availableBiometrics =
await auth.getAvailableBiometrics();
if (availableBiometrics.isNotEmpty) {
// Some biometrics are enrolled.
}
if (availableBiometrics.contains(BiometricType.strong) ||
availableBiometrics.contains(BiometricType.face)) {
// Specific types of biometrics are available.
// Use checks like this with caution!
}
```
### Options
The `authenticate()` method uses biometric authentication when possible, but
also allows fallback to pin, pattern, or passcode.
<?code-excerpt "readme_excerpts.dart (AuthAny)"?>
```dart
try {
final bool didAuthenticate = await auth.authenticate(
localizedReason: 'Please authenticate to show account balance');
// ···
} on PlatformException {
// ...
}
```
To require biometric authentication, pass `AuthenticationOptions` with
`biometricOnly` set to `true`.
<?code-excerpt "readme_excerpts.dart (AuthBioOnly)"?>
```dart
final bool didAuthenticate = await auth.authenticate(
localizedReason: 'Please authenticate to show account balance',
options: const AuthenticationOptions(biometricOnly: true));
```
*Note*: `biometricOnly` is not supported on Windows since the Windows implementation's underlying API (Windows Hello) doesn't support selecting the authentication method.
#### Dialogs
The plugin provides default dialogs for the following cases:
1. Passcode/PIN/Pattern Not Set: The user has not yet configured a passcode on
iOS or PIN/pattern on Android.
2. Biometrics Not Enrolled: The user has not enrolled any biometrics on the
device.
If a user does not have the necessary authentication enrolled when
`authenticate` is called, they will be given the option to enroll at that point,
or cancel authentication.
If you don't want to use the default dialogs, set the `useErrorDialogs` option
to `false` to have `authenticate` immediately return an error in those cases.
<?code-excerpt "readme_excerpts.dart (NoErrorDialogs)"?>
```dart
import 'package:local_auth/error_codes.dart' as auth_error;
// ···
try {
final bool didAuthenticate = await auth.authenticate(
localizedReason: 'Please authenticate to show account balance',
options: const AuthenticationOptions(useErrorDialogs: false));
// ···
} on PlatformException catch (e) {
if (e.code == auth_error.notAvailable) {
// Add handling of no hardware here.
} else if (e.code == auth_error.notEnrolled) {
// ...
} else {
// ...
}
}
```
If you want to customize the messages in the dialogs, you can pass
`AuthMessages` for each platform you support. These are platform-specific, so
you will need to import the platform-specific implementation packages. For
instance, to customize Android and iOS:
<?code-excerpt "readme_excerpts.dart (CustomMessages)"?>
```dart
import 'package:local_auth_android/local_auth_android.dart';
import 'package:local_auth_ios/local_auth_ios.dart';
// ···
final bool didAuthenticate = await auth.authenticate(
localizedReason: 'Please authenticate to show account balance',
authMessages: const <AuthMessages>[
AndroidAuthMessages(
signInTitle: 'Oops! Biometric authentication required!',
cancelButton: 'No thanks',
),
IOSAuthMessages(
cancelButton: 'No thanks',
),
]);
```
See the platform-specific classes for details about what can be customized on
each platform.
### Exceptions
`authenticate` throws `PlatformException`s in many error cases. See
`error_codes.dart` for known error codes that you may want to have specific
handling for. For example:
<?code-excerpt "readme_excerpts.dart (ErrorHandling)"?>
```dart
import 'package:flutter/services.dart';
import 'package:local_auth/error_codes.dart' as auth_error;
import 'package:local_auth/local_auth.dart';
// ···
final LocalAuthentication auth = LocalAuthentication();
// ···
try {
final bool didAuthenticate = await auth.authenticate(
localizedReason: 'Please authenticate to show account balance',
options: const AuthenticationOptions(useErrorDialogs: false));
// ···
} on PlatformException catch (e) {
if (e.code == auth_error.notEnrolled) {
// Add handling of no hardware here.
} else if (e.code == auth_error.lockedOut ||
e.code == auth_error.permanentlyLockedOut) {
// ...
} else {
// ...
}
}
```
## iOS Integration
Note that this plugin works with both Touch ID and Face ID. However, to use the latter,
you need to also add:
```xml
<key>NSFaceIDUsageDescription</key>
<string>Why is my app authenticating using face id?</string>
```
to your Info.plist file. Failure to do so results in a dialog that tells the user your
app has not been updated to use Face ID.
## Android Integration
\* The plugin will build and run on SDK 16+, but `isDeviceSupported()` will
always return false before SDK 23 (Android 6.0).
### Activity Changes
Note that `local_auth` requires the use of a `FragmentActivity` instead of an
`Activity`. To update your application:
* If you are using `FlutterActivity` directly, change it to
`FlutterFragmentActivity` in your `AndroidManifest.xml`.
* If you are using a custom activity, update your `MainActivity.java`:
```java
import io.flutter.embedding.android.FlutterFragmentActivity;
public class MainActivity extends FlutterFragmentActivity {
// ...
}
```
or MainActivity.kt:
```kotlin
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity: FlutterFragmentActivity() {
// ...
}
```
to inherit from `FlutterFragmentActivity`.
### Permissions
Update your project's `AndroidManifest.xml` file to include the
`USE_BIOMETRIC` permissions:
```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<manifest>
```
### Compatibility
On Android, you can check only for existence of fingerprint hardware prior
to API 29 (Android Q). Therefore, if you would like to support other biometrics
types (such as face scanning) and you want to support SDKs lower than Q,
_do not_ call `getAvailableBiometrics`. Simply call `authenticate` with `biometricOnly: true`.
This will return an error if there was no hardware available.
#### Android theme
Your `LaunchTheme`'s parent must be a valid `Theme.AppCompat` theme to prevent
crashes on Android 8 and below. For example, use `Theme.AppCompat.DayNight` to
enable light/dark modes for the biometric dialog. To do that go to
`android/app/src/main/res/values/styles.xml` and look for the style with name
`LaunchTheme`. Then change the parent for that style as follows:
```xml
...
<resources>
<style name="LaunchTheme" parent="Theme.AppCompat.DayNight">
...
</style>
...
</resources>
...
```
If you don't have a `styles.xml` file for your Android project you can set up
the Android theme directly in `android/app/src/main/AndroidManifest.xml`:
```xml
...
<application
...
<activity
...
android:theme="@style/Theme.AppCompat.DayNight"
...
>
</activity>
</application>
...
```
## Sticky Auth
You can set the `stickyAuth` option on the plugin to true so that plugin does not
return failure if the app is put to background by the system. This might happen
if the user receives a phone call before they get a chance to authenticate. With
`stickyAuth` set to false, this would result in plugin returning failure result
to the Dart app. If set to true, the plugin will retry authenticating when the
app resumes.
| plugins/packages/local_auth/local_auth/README.md/0 | {
"file_path": "plugins/packages/local_auth/local_auth/README.md",
"repo_id": "plugins",
"token_count": 2956
} | 1,300 |
include ':app'
| plugins/packages/local_auth/local_auth/example/android/settings_aar.gradle/0 | {
"file_path": "plugins/packages/local_auth/local_auth/example/android/settings_aar.gradle",
"repo_id": "plugins",
"token_count": 6
} | 1,301 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.localauth">
<uses-sdk android:targetSdkVersion="29"/>
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
</manifest>
| plugins/packages/local_auth/local_auth_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/android/src/main/AndroidManifest.xml",
"repo_id": "plugins",
"token_count": 89
} | 1,302 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs, avoid_print
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth_android/local_auth_android.dart';
import 'package:local_auth_platform_interface/local_auth_platform_interface.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
_SupportState _supportState = _SupportState.unknown;
bool? _deviceSupportsBiometrics;
List<BiometricType>? _enrolledBiometrics;
String _authorized = 'Not Authorized';
bool _isAuthenticating = false;
@override
void initState() {
super.initState();
LocalAuthPlatform.instance.isDeviceSupported().then(
(bool isSupported) => setState(() => _supportState = isSupported
? _SupportState.supported
: _SupportState.unsupported),
);
}
Future<void> _checkBiometrics() async {
late bool deviceSupportsBiometrics;
try {
deviceSupportsBiometrics =
await LocalAuthPlatform.instance.deviceSupportsBiometrics();
} on PlatformException catch (e) {
deviceSupportsBiometrics = false;
print(e);
}
if (!mounted) {
return;
}
setState(() {
_deviceSupportsBiometrics = deviceSupportsBiometrics;
});
}
Future<void> _getEnrolledBiometrics() async {
late List<BiometricType> availableBiometrics;
try {
availableBiometrics =
await LocalAuthPlatform.instance.getEnrolledBiometrics();
} on PlatformException catch (e) {
availableBiometrics = <BiometricType>[];
print(e);
}
if (!mounted) {
return;
}
setState(() {
_enrolledBiometrics = availableBiometrics;
});
}
Future<void> _authenticate() async {
bool authenticated = false;
try {
setState(() {
_isAuthenticating = true;
_authorized = 'Authenticating';
});
authenticated = await LocalAuthPlatform.instance.authenticate(
localizedReason: 'Let OS determine authentication method',
authMessages: <AuthMessages>[const AndroidAuthMessages()],
options: const AuthenticationOptions(
stickyAuth: true,
),
);
setState(() {
_isAuthenticating = false;
});
} on PlatformException catch (e) {
print(e);
setState(() {
_isAuthenticating = false;
_authorized = 'Error - ${e.message}';
});
return;
}
if (!mounted) {
return;
}
setState(
() => _authorized = authenticated ? 'Authorized' : 'Not Authorized');
}
Future<void> _authenticateWithBiometrics() async {
bool authenticated = false;
try {
setState(() {
_isAuthenticating = true;
_authorized = 'Authenticating';
});
authenticated = await LocalAuthPlatform.instance.authenticate(
localizedReason:
'Scan your fingerprint (or face or whatever) to authenticate',
authMessages: <AuthMessages>[const AndroidAuthMessages()],
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
setState(() {
_isAuthenticating = false;
_authorized = 'Authenticating';
});
} on PlatformException catch (e) {
print(e);
setState(() {
_isAuthenticating = false;
_authorized = 'Error - ${e.message}';
});
return;
}
if (!mounted) {
return;
}
final String message = authenticated ? 'Authorized' : 'Not Authorized';
setState(() {
_authorized = message;
});
}
Future<void> _cancelAuthentication() async {
await LocalAuthPlatform.instance.stopAuthentication();
setState(() => _isAuthenticating = false);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: ListView(
padding: const EdgeInsets.only(top: 30),
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_supportState == _SupportState.unknown)
const CircularProgressIndicator()
else if (_supportState == _SupportState.supported)
const Text('This device is supported')
else
const Text('This device is not supported'),
const Divider(height: 100),
Text(
'Device supports biometrics: $_deviceSupportsBiometrics\n'),
ElevatedButton(
onPressed: _checkBiometrics,
child: const Text('Check biometrics'),
),
const Divider(height: 100),
Text('Enrolled biometrics: $_enrolledBiometrics\n'),
ElevatedButton(
onPressed: _getEnrolledBiometrics,
child: const Text('Get enrolled biometrics'),
),
const Divider(height: 100),
Text('Current State: $_authorized\n'),
if (_isAuthenticating)
ElevatedButton(
onPressed: _cancelAuthentication,
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Text('Cancel Authentication'),
Icon(Icons.cancel),
],
),
)
else
Column(
children: <Widget>[
ElevatedButton(
onPressed: _authenticate,
// TODO(goderbauer): Make this const when this package requires Flutter 3.8 or later.
// ignore: prefer_const_constructors
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
Text('Authenticate'),
Icon(Icons.perm_device_information),
],
),
),
ElevatedButton(
onPressed: _authenticateWithBiometrics,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(_isAuthenticating
? 'Cancel'
: 'Authenticate: biometrics only'),
const Icon(Icons.fingerprint),
],
),
),
],
),
],
),
],
),
),
);
}
}
enum _SupportState {
unknown,
supported,
unsupported,
}
| plugins/packages/local_auth/local_auth_android/example/lib/main.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth_android/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 3614
} | 1,303 |
// 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.
/// Various types of biometric authentication.
/// Some platforms report specific biometric types, while others report only
/// classifications like strong and weak.
enum BiometricType {
/// Face authentication.
face,
/// Fingerprint authentication.
fingerprint,
/// Iris authentication.
iris,
/// Any biometric (e.g. fingerprint, iris, or face) on the device that the
/// platform API considers to be strong. For example, on Android this
/// corresponds to Class 3.
strong,
/// Any biometric (e.g. fingerprint, iris, or face) on the device that the
/// platform API considers to be weak. For example, on Android this
/// corresponds to Class 2.
weak,
}
| plugins/packages/local_auth/local_auth_platform_interface/lib/types/biometric_type.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth_platform_interface/lib/types/biometric_type.dart",
"repo_id": "plugins",
"token_count": 218
} | 1,304 |
// 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
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
class LocalAuthApi {
/// Constructor for [LocalAuthApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
LocalAuthApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Returns true if this device supports authentication.
Future<bool> isDeviceSupported() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.LocalAuthApi.isDeviceSupported', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(null) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as bool?)!;
}
}
/// Attempts to authenticate the user with the provided [localizedReason] as
/// the user-facing explanation for the authorization request.
///
/// Returns true if authorization succeeds, false if it is attempted but is
/// not successful, and an error if authorization could not be attempted.
Future<bool> authenticate(String arg_localizedReason) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.LocalAuthApi.authenticate', codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_localizedReason]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as bool?)!;
}
}
}
| plugins/packages/local_auth/local_auth_windows/lib/src/messages.g.dart/0 | {
"file_path": "plugins/packages/local_auth/local_auth_windows/lib/src/messages.g.dart",
"repo_id": "plugins",
"token_count": 1169
} | 1,305 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.0.12
* Switches to the new `path_provider_foundation` implementation package
for iOS and macOS.
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 2.0.11
* Updates references to the obsolete master branch.
* Fixes integration test permission issue on recent versions of macOS.
## 2.0.10
* Removes unnecessary imports.
* Adds OS version support information to README.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.0.9
* Updates documentation on README.md.
* Updates example application.
## 2.0.8
* Updates example app Android compileSdkVersion to 31.
* Removes obsolete manual registration of Windows and Linux implementations.
## 2.0.7
* Moved Android and iOS implementations to federated packages.
## 2.0.6
* Added support for Background Platform Channels on Android when it is
available.
## 2.0.5
* Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0.
## 2.0.4
* Updated Android lint settings.
* Specify Java 8 for Android build.
## 2.0.3
* Add iOS unit test target.
* Remove references to the Android V1 embedding.
## 2.0.2
* Migrate maven repository from jcenter to mavenCentral.
## 2.0.1
* Update platform_plugin_interface version requirement.
## 2.0.0
* Migrate to null safety.
* BREAKING CHANGE: Path accessors that return non-nullable results will throw
a `MissingPlatformDirectoryException` if the platform implementation is unable
to get the corresponding directory (except on platforms where the method is
explicitly unsupported, where they will continue to throw `UnsupportedError`).
## 1.6.28
* Drop unused UUID dependency for tests.
## 1.6.27
* Update the example app: remove the deprecated `RaisedButton` and `FlatButton` widgets.
## 1.6.26
* Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276))
## 1.6.25
* Update Flutter SDK constraint.
## 1.6.24
* Remove unused `test` dependency.
* Update Dart SDK constraint in example.
## 1.6.23
* Check in windows/ directory for example/
## 1.6.22
* Switch to guava-android dependency instead of full guava.
## 1.6.21
* Update android compileSdkVersion to 29.
## 1.6.20
* Check in linux/ directory for example/
## 1.6.19
* Android implementation does path queries in the background thread rather than UI thread.
## 1.6.18
* Keep handling deprecated Android v1 classes for backward compatibility.
## 1.6.17
* Update Windows endorsement verison again, to pick up the fix for
web compilation in projects that include path_provider.
## 1.6.16
* Update Windows endorsement verison
## 1.6.15
* Endorse Windows implementation.
* Remove the need to call disablePathProviderPlatformOverride in tests
## 1.6.14
* Update package:e2e -> package:integration_test
## 1.6.13
* Update package:e2e reference to use the local version in the flutter/plugins
repository.
## 1.6.12
* Fixed a Java lint in a test.
## 1.6.11
* Updated documentation to reflect the need for changes in testing for federated plugins
## 1.6.10
* Linux implementation endorsement
## 1.6.9
* Post-v2 Android embedding cleanups.
## 1.6.8
* Update lower bound of dart dependency to 2.1.0.
## 1.6.7
* Remove Android dependencies fallback.
* Require Flutter SDK 1.12.13+hotfix.5 or greater.
* Fix CocoaPods podspec lint warnings.
## 1.6.6
* Replace deprecated `getFlutterEngine` call on Android.
## 1.6.5
* Remove unused class name in pubspec.
## 1.6.4
* Endorsed macOS implementation.
## 1.6.3
* Use `path_provider_platform_interface` in core plugin.
## 1.6.2
* Move package contents into `path_provider` for platform federation.
## 1.6.1
* Make the pedantic dev_dependency explicit.
## 1.6.0
* Support for retrieving the downloads directory was added.
The call for this is `getDownloadsDirectory`.
## 1.5.1
* Remove the deprecated `author:` field from pubspec.yaml
* Migrate the plugin to the pubspec platforms manifest.
* Require Flutter SDK 1.10.0 or greater.
## 1.5.0
* Add macOS support.
## 1.4.5
* Add support for v2 plugins APIs.
## 1.4.4
* Update driver tests in the example app to e2e tests.
## 1.4.3
* Update driver tests in the example app to e2e tests.
* Add missing DartDocs and a lint to prevent further regressions.
## 1.4.2
* Update and migrate iOS example project by removing flutter_assets, change
"English" to "en", remove extraneous xcconfigs, update to Xcode 11 build
settings, remove ARCHS, and build pods as libraries instead of frameworks.
## 1.4.1
* Remove AndroidX warnings.
## 1.4.0
* Support retrieving storage paths on Android devices with multiple external
storage options. This adds a new class `AndroidEnvironment` that shadows the
directory names from Androids `android.os.Environment` class.
* Fixes `getLibraryDirectory` semantics & tests.
## 1.3.1
* Define clang module for iOS.
## 1.3.0
* Added iOS-only support for `getLibraryDirectory`.
* Update integration tests and example test.
* Update example app UI to use a `ListView` show the list of content.
* Update .gitignore to include Xcode build output folder `**/DerivedData/`
## 1.2.2
* Correct the integration test for Android's `getApplicationSupportDirectory` call.
* Introduce `setMockPathProviderPlatform` for API for tests.
* Adds missing unit and integration tests.
## 1.2.1
* Fix fall through bug.
## 1.2.0
* On Android, `getApplicationSupportDirectory` is now supported using `getFilesDir`.
* `getExternalStorageDirectory` now returns `null` instead of throwing an
exception if no external files directory is available.
## 1.1.2
* `getExternalStorageDirectory` now uses `getExternalFilesDir` on Android.
## 1.1.1
* Cast error codes as longs in iOS error strings to ensure compatibility
between arm32 and arm64.
## 1.1.0
* Added `getApplicationSupportDirectory`.
* Updated documentation for `getApplicationDocumentsDirectory` to suggest
using `getApplicationSupportDirectory` on iOS and
`getExternalStorageDirectory` on Android.
* Updated documentation for `getTemporaryDirectory` to suggest using it
for caches of files that do not need to be backed up.
* Updated integration tests and example to reflect the above changes.
## 1.0.0
* Added integration tests.
## 0.5.0+1
* Log a more detailed warning at build time about the previous AndroidX
migration.
## 0.5.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.4.1
* Updated Gradle tooling to match Android Studio 3.1.2.
## 0.4.0
* **Breaking change**. Set SDK constraints to match the Flutter beta release.
## 0.3.1
* Simplified and upgraded Android project template to Android SDK 27.
* Updated package description.
## 0.3.0
* **Breaking change**. Upgraded to Gradle 4.1 and Android Studio Gradle plugin
3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in
order to use this version of the plugin. Instructions can be found
[here](https://github.com/flutter/flutter/wiki/Updating-Flutter-projects-to-Gradle-4.1-and-Android-Studio-Gradle-plugin-3.0.1).
## 0.2.2
* Add FLT prefix to iOS types
## 0.2.1+1
* Updated README
## 0.2.1
* Add function to determine external storage directory.
## 0.2.0
* Upgrade to new plugin registration. (https://groups.google.com/forum/#!topic/flutter-dev/zba1Ynf2OKM)
## 0.1.3
* Upgrade Android SDK Build Tools to 25.0.3.
## 0.1.2
* Add test.
## 0.1.1
* Change to README.md.
## 0.1.0
* Initial Open Source release.
| plugins/packages/path_provider/path_provider/CHANGELOG.md/0 | {
"file_path": "plugins/packages/path_provider/path_provider/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 2427
} | 1,306 |
rootProject.name = 'path_provider_android'
| plugins/packages/path_provider/path_provider_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/path_provider/path_provider_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 14
} | 1,307 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v5.0.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
import Foundation
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#else
#error("Unsupported platform.")
#endif
/// Generated class from Pigeon.
enum DirectoryType: Int {
case applicationDocuments = 0
case applicationSupport = 1
case downloads = 2
case library = 3
case temp = 4
}
/// Generated protocol from Pigeon that represents a handler of messages from Flutter.
protocol PathProviderApi {
func getDirectoryPath(type: DirectoryType) -> String?
}
/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`.
class PathProviderApiSetup {
/// The codec used by PathProviderApi.
/// Sets up an instance of `PathProviderApi` to handle messages through the `binaryMessenger`.
static func setUp(binaryMessenger: FlutterBinaryMessenger, api: PathProviderApi?) {
let getDirectoryPathChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.PathProviderApi.getDirectoryPath", binaryMessenger: binaryMessenger)
if let api = api {
getDirectoryPathChannel.setMessageHandler { message, reply in
let args = message as! [Any?]
let typeArg = DirectoryType(rawValue: args[0] as! Int)!
let result = api.getDirectoryPath(type: typeArg)
reply(wrapResult(result))
}
} else {
getDirectoryPathChannel.setMessageHandler(nil)
}
}
}
private func wrapResult(_ result: Any?) -> [Any?] {
return [result]
}
private func wrapError(_ error: FlutterError) -> [Any?] {
return [
error.code,
error.message,
error.details
]
}
| plugins/packages/path_provider/path_provider_foundation/ios/Classes/messages.g.swift/0 | {
"file_path": "plugins/packages/path_provider/path_provider_foundation/ios/Classes/messages.g.swift",
"repo_id": "plugins",
"token_count": 581
} | 1,308 |
// 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.
/// Corresponds to constants defined in Androids `android.os.Environment` class.
///
/// https://developer.android.com/reference/android/os/Environment.html#fields_1
enum StorageDirectory {
/// Contains audio files that should be treated as music.
///
/// See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_MUSIC.
music,
/// Contains audio files that should be treated as podcasts.
///
/// See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_PODCASTS.
podcasts,
/// Contains audio files that should be treated as ringtones.
///
/// See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_RINGTONES.
ringtones,
/// Contains audio files that should be treated as alarm sounds.
///
/// See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_ALARMS.
alarms,
/// Contains audio files that should be treated as notification sounds.
///
/// See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_NOTIFICATIONS.
notifications,
/// Contains images. See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_PICTURES.
pictures,
/// Contains movies. See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_MOVIES.
movies,
/// Contains files of any type that have been downloaded by the user.
///
/// See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_DOWNLOADS.
downloads,
/// Used to hold both pictures and videos when the device filesystem is
/// treated like a camera's.
///
/// See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_DCIM.
dcim,
/// Holds user-created documents. See https://developer.android.com/reference/android/os/Environment.html#DIRECTORY_DOCUMENTS.
documents,
}
| plugins/packages/path_provider/path_provider_platform_interface/lib/src/enums.dart/0 | {
"file_path": "plugins/packages/path_provider/path_provider_platform_interface/lib/src/enums.dart",
"repo_id": "plugins",
"token_count": 590
} | 1,309 |
name: plugin_platform_interface
description: Reusable base class for platform interfaces of Flutter federated
plugins, to help enforce best practices.
repository: https://github.com/flutter/plugins/tree/main/packages/plugin_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+plugin_platform_interface%22
# DO NOT MAKE A BREAKING CHANGE TO THIS PACKAGE
# DO NOT INCREASE THE MAJOR VERSION OF THIS PACKAGE
#
# This package is used as a second level dependency for many plugins, a major version bump here
# is guaranteed to lead the ecosystem to a version lock (the first plugin that upgrades to version
# 3 of this package cannot be used with any other plugin that have not yet migrated).
#
# Please consider carefully before bumping the major version of this package, ideally it should only
# be done when absolutely necessary and after the ecosystem has already migrated to 2.X.Y version
# that is forward compatible with 3.0.0 (ideally the ecosystem have migrated to depend on:
# `plugin_platform_interface: >=2.X.Y <4.0.0`).
version: 2.1.3
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
meta: ^1.3.0
dev_dependencies:
mockito: ^5.0.0
test: ^1.16.0
| plugins/packages/plugin_platform_interface/pubspec.yaml/0 | {
"file_path": "plugins/packages/plugin_platform_interface/pubspec.yaml",
"repo_id": "plugins",
"token_count": 368
} | 1,310 |
name: quick_actions
description: Flutter plugin for creating shortcuts on home screen, also known as
Quick Actions on iOS and App Shortcuts on Android.
repository: https://github.com/flutter/plugins/tree/main/packages/quick_actions/quick_actions
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+quick_actions%22
version: 1.0.1
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
android:
default_package: quick_actions_android
ios:
default_package: quick_actions_ios
dependencies:
flutter:
sdk: flutter
quick_actions_android: ^1.0.0
quick_actions_ios: ^1.0.0
quick_actions_platform_interface: ^1.0.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: ^5.0.0
plugin_platform_interface: ^2.0.0
| plugins/packages/quick_actions/quick_actions/pubspec.yaml/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions/pubspec.yaml",
"repo_id": "plugins",
"token_count": 352
} | 1,311 |
// 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 QuickActionsPluginTests: XCTestCase {
func testHandleMethodCall_setShortcutItems() {
let rawItem = [
"type": "SearchTheThing",
"localizedTitle": "Search the thing",
"icon": "search_the_thing.png",
]
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let call = FlutterMethodCall(methodName: "setShortcutItems", arguments: [rawItem])
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let parseShortcutItemsExpectation = expectation(
description: "parseShortcutItems must be called.")
mockShortcutItemParser.parseShortcutItemsStub = { items in
XCTAssertEqual(items as? [[String: String]], [rawItem])
parseShortcutItemsExpectation.fulfill()
return [item]
}
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertNil(result, "result block must be called with nil.")
resultExpectation.fulfill()
}
XCTAssertEqual(mockShortcutItemProvider.shortcutItems, [item], "Must set shortcut items.")
waitForExpectations(timeout: 1)
}
func testHandleMethodCall_clearShortcutItems() {
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let call = FlutterMethodCall(methodName: "clearShortcutItems", arguments: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
mockShortcutItemProvider.shortcutItems = [item]
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertNil(result, "result block must be called with nil.")
resultExpectation.fulfill()
}
XCTAssertEqual(mockShortcutItemProvider.shortcutItems, [], "Must clear shortcut items.")
waitForExpectations(timeout: 1)
}
func testHandleMethodCall_getLaunchAction() {
let call = FlutterMethodCall(methodName: "getLaunchAction", arguments: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertNil(result, "result block must be called with nil.")
resultExpectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testHandleMethodCall_nonExistMethods() {
let call = FlutterMethodCall(methodName: "nonExist", arguments: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let resultExpectation = expectation(description: "result block must be called.")
plugin.handle(call) { result in
XCTAssertEqual(
result as? NSObject, FlutterMethodNotImplemented,
"result block must be called with FlutterMethodNotImplemented")
resultExpectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testApplicationPerformActionForShortcutItem() {
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let invokeMethodExpectation = expectation(description: "invokeMethod must be called.")
mockChannel.invokeMethodStub = { method, arguments in
XCTAssertEqual(method, "launch")
XCTAssertEqual(arguments as? String, item.type)
invokeMethodExpectation.fulfill()
}
let actionResult = plugin.application(
UIApplication.shared,
performActionFor: item
) { success in /* no-op */ }
XCTAssert(actionResult, "performActionForShortcutItem must return true.")
waitForExpectations(timeout: 1)
}
func testApplicationDidFinishLaunchingWithOptions_launchWithShortcut() {
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let launchResult = plugin.application(
UIApplication.shared,
didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item])
XCTAssertFalse(
launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.")
}
func testApplicationDidFinishLaunchingWithOptions_launchWithoutShortcut() {
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let launchResult = plugin.application(UIApplication.shared, didFinishLaunchingWithOptions: [:])
XCTAssert(
launchResult, "didFinishLaunchingWithOptions must return true if not launched from shortcut.")
}
func testApplicationDidBecomeActive_launchWithoutShortcut() {
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
mockChannel.invokeMethodStub = { _, _ in
XCTFail("invokeMethod should not be called if launch without shortcut.")
}
let launchResult = plugin.application(UIApplication.shared, didFinishLaunchingWithOptions: [:])
XCTAssert(
launchResult, "didFinishLaunchingWithOptions must return true if not launched from shortcut.")
plugin.applicationDidBecomeActive(UIApplication.shared)
}
func testApplicationDidBecomeActive_launchWithShortcut() {
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let invokeMethodExpectation = expectation(description: "invokeMethod must be called.")
mockChannel.invokeMethodStub = { method, arguments in
XCTAssertEqual(method, "launch")
XCTAssertEqual(arguments as? String, item.type)
invokeMethodExpectation.fulfill()
}
let launchResult = plugin.application(
UIApplication.shared,
didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item])
XCTAssertFalse(
launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.")
plugin.applicationDidBecomeActive(UIApplication.shared)
waitForExpectations(timeout: 1)
}
func testApplicationDidBecomeActive_launchWithShortcut_becomeActiveTwice() {
let item = UIApplicationShortcutItem(
type: "SearchTheThing",
localizedTitle: "Search the thing",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"),
userInfo: nil)
let mockChannel = MockMethodChannel()
let mockShortcutItemProvider = MockShortcutItemProvider()
let mockShortcutItemParser = MockShortcutItemParser()
let plugin = QuickActionsPlugin(
channel: mockChannel,
shortcutItemProvider: mockShortcutItemProvider,
shortcutItemParser: mockShortcutItemParser)
let invokeMethodExpectation = expectation(description: "invokeMethod must be called.")
var invokeMehtodCount = 0
mockChannel.invokeMethodStub = { method, arguments in
invokeMehtodCount += 1
invokeMethodExpectation.fulfill()
}
let launchResult = plugin.application(
UIApplication.shared,
didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item])
XCTAssertFalse(
launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.")
plugin.applicationDidBecomeActive(UIApplication.shared)
waitForExpectations(timeout: 1)
XCTAssertEqual(invokeMehtodCount, 1, "shortcut should only be handled once per launch.")
}
}
| plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift",
"repo_id": "plugins",
"token_count": 3518
} | 1,312 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 1.0.3
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
## 1.0.2
* Removes dependency on `meta`.
## 1.0.1
* Updates code for analyzer changes.
* Update to use the `verify` method introduced in plugin_platform_interface 2.1.0.
## 1.0.0
* Initial release of quick_actions_platform_interface
| plugins/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md/0 | {
"file_path": "plugins/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 132
} | 1,313 |
// 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:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('SharedPreferences', () {
const String testString = 'hello world';
const bool testBool = true;
const int testInt = 42;
const double testDouble = 3.14159;
const List<String> testList = <String>['foo', 'bar'];
const Map<String, Object> testValues = <String, Object>{
'flutter.String': testString,
'flutter.bool': testBool,
'flutter.int': testInt,
'flutter.double': testDouble,
'flutter.List': testList,
};
const String testString2 = 'goodbye world';
const bool testBool2 = false;
const int testInt2 = 1337;
const double testDouble2 = 2.71828;
const List<String> testList2 = <String>['baz', 'quox'];
const Map<String, dynamic> testValues2 = <String, dynamic>{
'flutter.String': testString2,
'flutter.bool': testBool2,
'flutter.int': testInt2,
'flutter.double': testDouble2,
'flutter.List': testList2,
};
late FakeSharedPreferencesStore store;
late SharedPreferences preferences;
setUp(() async {
store = FakeSharedPreferencesStore(testValues);
SharedPreferencesStorePlatform.instance = store;
preferences = await SharedPreferences.getInstance();
store.log.clear();
});
test('reading', () async {
expect(preferences.get('String'), testString);
expect(preferences.get('bool'), testBool);
expect(preferences.get('int'), testInt);
expect(preferences.get('double'), testDouble);
expect(preferences.get('List'), testList);
expect(preferences.getString('String'), testString);
expect(preferences.getBool('bool'), testBool);
expect(preferences.getInt('int'), testInt);
expect(preferences.getDouble('double'), testDouble);
expect(preferences.getStringList('List'), testList);
expect(store.log, <Matcher>[]);
});
test('writing', () async {
await Future.wait(<Future<bool>>[
preferences.setString('String', testString2),
preferences.setBool('bool', testBool2),
preferences.setInt('int', testInt2),
preferences.setDouble('double', testDouble2),
preferences.setStringList('List', testList2)
]);
expect(
store.log,
<Matcher>[
isMethodCall('setValue', arguments: <dynamic>[
'String',
'flutter.String',
testString2,
]),
isMethodCall('setValue', arguments: <dynamic>[
'Bool',
'flutter.bool',
testBool2,
]),
isMethodCall('setValue', arguments: <dynamic>[
'Int',
'flutter.int',
testInt2,
]),
isMethodCall('setValue', arguments: <dynamic>[
'Double',
'flutter.double',
testDouble2,
]),
isMethodCall('setValue', arguments: <dynamic>[
'StringList',
'flutter.List',
testList2,
]),
],
);
store.log.clear();
expect(preferences.getString('String'), testString2);
expect(preferences.getBool('bool'), testBool2);
expect(preferences.getInt('int'), testInt2);
expect(preferences.getDouble('double'), testDouble2);
expect(preferences.getStringList('List'), testList2);
expect(store.log, equals(<MethodCall>[]));
});
test('removing', () async {
const String key = 'testKey';
await preferences.remove(key);
expect(
store.log,
List<Matcher>.filled(
1,
isMethodCall(
'remove',
arguments: 'flutter.$key',
),
growable: true,
));
});
test('containsKey', () async {
const String key = 'testKey';
expect(false, preferences.containsKey(key));
await preferences.setString(key, 'test');
expect(true, preferences.containsKey(key));
});
test('clearing', () async {
await preferences.clear();
expect(preferences.getString('String'), null);
expect(preferences.getBool('bool'), null);
expect(preferences.getInt('int'), null);
expect(preferences.getDouble('double'), null);
expect(preferences.getStringList('List'), null);
expect(store.log, <Matcher>[isMethodCall('clear', arguments: null)]);
});
test('reloading', () async {
await preferences.setString('String', testString);
expect(preferences.getString('String'), testString);
SharedPreferences.setMockInitialValues(
testValues2.cast<String, Object>());
expect(preferences.getString('String'), testString);
await preferences.reload();
expect(preferences.getString('String'), testString2);
});
test('back to back calls should return same instance.', () async {
final Future<SharedPreferences> first = SharedPreferences.getInstance();
final Future<SharedPreferences> second = SharedPreferences.getInstance();
expect(await first, await second);
});
test('string list type is dynamic (usually from method channel)', () async {
SharedPreferences.setMockInitialValues(<String, Object>{
'dynamic_list': <dynamic>['1', '2']
});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final List<String>? value = prefs.getStringList('dynamic_list');
expect(value, <String>['1', '2']);
});
group('mocking', () {
const String key = 'dummy';
const String prefixedKey = 'flutter.$key';
test('test 1', () async {
SharedPreferences.setMockInitialValues(
<String, Object>{prefixedKey: 'my string'});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? value = prefs.getString(key);
expect(value, 'my string');
});
test('test 2', () async {
SharedPreferences.setMockInitialValues(
<String, Object>{prefixedKey: 'my other string'});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? value = prefs.getString(key);
expect(value, 'my other string');
});
});
test('writing copy of strings list', () async {
final List<String> myList = <String>[];
await preferences.setStringList('myList', myList);
myList.add('foobar');
final List<String> cachedList = preferences.getStringList('myList')!;
expect(cachedList, <String>[]);
cachedList.add('foobar2');
expect(preferences.getStringList('myList'), <String>[]);
});
});
test('calling mock initial values with non-prefixed keys succeeds', () async {
SharedPreferences.setMockInitialValues(<String, Object>{
'test': 'foo',
});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? value = prefs.getString('test');
expect(value, 'foo');
});
}
class FakeSharedPreferencesStore implements SharedPreferencesStorePlatform {
FakeSharedPreferencesStore(Map<String, Object> data)
: backend = InMemorySharedPreferencesStore.withData(data);
final InMemorySharedPreferencesStore backend;
final List<MethodCall> log = <MethodCall>[];
@override
bool get isMock => true;
@override
Future<bool> clear() {
log.add(const MethodCall('clear'));
return backend.clear();
}
@override
Future<Map<String, Object>> getAll() {
log.add(const MethodCall('getAll'));
return backend.getAll();
}
@override
Future<bool> remove(String key) {
log.add(MethodCall('remove', key));
return backend.remove(key);
}
@override
Future<bool> setValue(String valueType, String key, Object value) {
log.add(MethodCall('setValue', <dynamic>[valueType, key, value]));
return backend.setValue(valueType, key, value);
}
}
| plugins/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart",
"repo_id": "plugins",
"token_count": 3272
} | 1,314 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| plugins/packages/shared_preferences/shared_preferences_android/example/android/gradle.properties/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_android/example/android/gradle.properties",
"repo_id": "plugins",
"token_count": 30
} | 1,315 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import XCTest
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#endif
@testable import shared_preferences_foundation
class RunnerTests: XCTestCase {
func testSetAndGet() throws {
let plugin = SharedPreferencesPlugin()
plugin.setBool(key: "flutter.aBool", value: true)
plugin.setDouble(key: "flutter.aDouble", value: 3.14)
plugin.setValue(key: "flutter.anInt", value: 42)
plugin.setValue(key: "flutter.aString", value: "hello world")
plugin.setValue(key: "flutter.aStringList", value: ["hello", "world"])
let storedValues = plugin.getAll()
XCTAssertEqual(storedValues["flutter.aBool"] as? Bool, true)
XCTAssertEqual(storedValues["flutter.aDouble"] as! Double, 3.14, accuracy: 0.0001)
XCTAssertEqual(storedValues["flutter.anInt"] as? Int, 42)
XCTAssertEqual(storedValues["flutter.aString"] as? String, "hello world")
XCTAssertEqual(storedValues["flutter.aStringList"] as? Array<String>, ["hello", "world"])
}
func testRemove() throws {
let plugin = SharedPreferencesPlugin()
let testKey = "flutter.foo"
plugin.setValue(key: testKey, value: 42)
// Make sure there is something to remove, so the test can't pass due to a set failure.
let preRemovalValues = plugin.getAll()
XCTAssertEqual(preRemovalValues[testKey] as? Int, 42)
// Then verify that removing it works.
plugin.remove(key: testKey)
let finalValues = plugin.getAll()
XCTAssertNil(finalValues[testKey] as Any?)
}
func testClear() throws {
let plugin = SharedPreferencesPlugin()
let testKey = "flutter.foo"
plugin.setValue(key: testKey, value: 42)
// Make sure there is something to clear, so the test can't pass due to a set failure.
let preRemovalValues = plugin.getAll()
XCTAssertEqual(preRemovalValues[testKey] as? Int, 42)
// Then verify that clearing works.
plugin.clear()
let finalValues = plugin.getAll()
XCTAssertNil(finalValues[testKey] as Any?)
}
}
| plugins/packages/shared_preferences/shared_preferences_foundation/darwin/Tests/RunnerTests.swift/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/darwin/Tests/RunnerTests.swift",
"repo_id": "plugins",
"token_count": 769
} | 1,316 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| plugins/packages/shared_preferences/shared_preferences_foundation/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_foundation/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "plugins",
"token_count": 32
} | 1,317 |
## NEXT
* Updates minimum Flutter version to 3.0.
## 2.1.0
* Adopts `plugin_platform_interface`. As a result, `isMock` is deprecated in
favor of the now-standard `MockPlatformInterfaceMixin`.
## 2.0.0
* Migrate to null safety.
## 1.0.5
* Update Flutter SDK constraint.
## 1.0.4
* Update lower bound of dart dependency to 2.1.0.
## 1.0.3
* Make the pedantic dev_dependency explicit.
## 1.0.2
* Adds a `shared_preferences_macos` package.
## 1.0.1
* Remove the deprecated `author:` field from pubspec.yaml
## 1.0.0
* Initial release. Contains the interface and an implementation based on
method channels.
| plugins/packages/shared_preferences/shared_preferences_platform_interface/CHANGELOG.md/0 | {
"file_path": "plugins/packages/shared_preferences/shared_preferences_platform_interface/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 221
} | 1,318 |
// 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 'package:flutter/material.dart';
import 'package:url_launcher/link.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'URL Launcher',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'URL Launcher'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _hasCallSupport = false;
Future<void>? _launched;
String _phone = '';
@override
void initState() {
super.initState();
// Check for phone call support.
canLaunchUrl(Uri(scheme: 'tel', path: '123')).then((bool result) {
setState(() {
_hasCallSupport = result;
});
});
}
Future<void> _launchInBrowser(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.externalApplication,
)) {
throw Exception('Could not launch $url');
}
}
Future<void> _launchInWebViewOrVC(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.inAppWebView,
webViewConfiguration: const WebViewConfiguration(
headers: <String, String>{'my_header_key': 'my_header_value'}),
)) {
throw Exception('Could not launch $url');
}
}
Future<void> _launchInWebViewWithoutJavaScript(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.inAppWebView,
webViewConfiguration: const WebViewConfiguration(enableJavaScript: false),
)) {
throw Exception('Could not launch $url');
}
}
Future<void> _launchInWebViewWithoutDomStorage(Uri url) async {
if (!await launchUrl(
url,
mode: LaunchMode.inAppWebView,
webViewConfiguration: const WebViewConfiguration(enableDomStorage: false),
)) {
throw Exception('Could not launch $url');
}
}
Future<void> _launchUniversalLinkIos(Uri url) async {
final bool nativeAppLaunchSucceeded = await launchUrl(
url,
mode: LaunchMode.externalNonBrowserApplication,
);
if (!nativeAppLaunchSucceeded) {
await launchUrl(
url,
mode: LaunchMode.inAppWebView,
);
}
}
Widget _launchStatus(BuildContext context, AsyncSnapshot<void> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return const Text('');
}
}
Future<void> _makePhoneCall(String phoneNumber) async {
final Uri launchUri = Uri(
scheme: 'tel',
path: phoneNumber,
);
await launchUrl(launchUri);
}
@override
Widget build(BuildContext context) {
// onPressed calls using this URL are not gated on a 'canLaunch' check
// because the assumption is that every device can launch a web URL.
final Uri toLaunch =
Uri(scheme: 'https', host: 'www.cylog.org', path: 'headers/');
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
onChanged: (String text) => _phone = text,
decoration: const InputDecoration(
hintText: 'Input the phone number to launch')),
),
ElevatedButton(
onPressed: _hasCallSupport
? () => setState(() {
_launched = _makePhoneCall(_phone);
})
: null,
child: _hasCallSupport
? const Text('Make phone call')
: const Text('Calling not supported'),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(toLaunch.toString()),
),
ElevatedButton(
onPressed: () => setState(() {
_launched = _launchInBrowser(toLaunch);
}),
child: const Text('Launch in browser'),
),
const Padding(padding: EdgeInsets.all(16.0)),
ElevatedButton(
onPressed: () => setState(() {
_launched = _launchInWebViewOrVC(toLaunch);
}),
child: const Text('Launch in app'),
),
ElevatedButton(
onPressed: () => setState(() {
_launched = _launchInWebViewWithoutJavaScript(toLaunch);
}),
child: const Text('Launch in app (JavaScript OFF)'),
),
ElevatedButton(
onPressed: () => setState(() {
_launched = _launchInWebViewWithoutDomStorage(toLaunch);
}),
child: const Text('Launch in app (DOM storage OFF)'),
),
const Padding(padding: EdgeInsets.all(16.0)),
ElevatedButton(
onPressed: () => setState(() {
_launched = _launchUniversalLinkIos(toLaunch);
}),
child: const Text(
'Launch a universal link in a native app, fallback to Safari.(Youtube)'),
),
const Padding(padding: EdgeInsets.all(16.0)),
ElevatedButton(
onPressed: () => setState(() {
_launched = _launchInWebViewOrVC(toLaunch);
Timer(const Duration(seconds: 5), () {
closeInAppWebView();
});
}),
child: const Text('Launch in app + close after 5 seconds'),
),
const Padding(padding: EdgeInsets.all(16.0)),
Link(
uri: Uri.parse(
'https://pub.dev/documentation/url_launcher/latest/link/link-library.html'),
target: LinkTarget.blank,
builder: (BuildContext ctx, FollowLink? openLink) {
return TextButton.icon(
onPressed: openLink,
label: const Text('Link Widget documentation'),
icon: const Icon(Icons.read_more),
);
},
),
const Padding(padding: EdgeInsets.all(16.0)),
FutureBuilder<void>(future: _launched, builder: _launchStatus),
],
),
],
),
);
}
}
| plugins/packages/url_launcher/url_launcher/example/lib/main.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/example/lib/main.dart",
"repo_id": "plugins",
"token_count": 3385
} | 1,319 |
// 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:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../url_launcher_string.dart';
import 'type_conversion.dart';
/// Passes [url] to the underlying platform for handling.
///
/// [mode] support varies significantly by platform:
/// - [LaunchMode.platformDefault] is supported on all platforms:
/// - On iOS and Android, this treats web URLs as
/// [LaunchMode.inAppWebView], and all other URLs as
/// [LaunchMode.externalApplication].
/// - On Windows, macOS, and Linux this behaves like
/// [LaunchMode.externalApplication].
/// - On web, this uses `webOnlyWindowName` for web URLs, and behaves like
/// [LaunchMode.externalApplication] for any other content.
/// - [LaunchMode.inAppWebView] is currently only supported on iOS and
/// Android. If a non-web URL is passed with this mode, an [ArgumentError]
/// will be thrown.
/// - [LaunchMode.externalApplication] is supported on all platforms.
/// On iOS, this should be used in cases where sharing the cookies of the
/// user's browser is important, such as SSO flows, since Safari View
/// Controller does not share the browser's context.
/// - [LaunchMode.externalNonBrowserApplication] is supported on iOS 10+.
/// This setting is used to require universal links to open in a non-browser
/// application.
///
/// For web, [webOnlyWindowName] specifies a target for the launch. This
/// supports the standard special link target names. For example:
/// - "_blank" opens the new URL in a new tab.
/// - "_self" opens the new URL in the current tab.
/// Default behaviour when unset is to open the url in a new tab.
///
/// Returns true if the URL was launched successful, otherwise either returns
/// false or throws a [PlatformException] depending on the failure.
Future<bool> launchUrl(
Uri url, {
LaunchMode mode = LaunchMode.platformDefault,
WebViewConfiguration webViewConfiguration = const WebViewConfiguration(),
String? webOnlyWindowName,
}) async {
if (mode == LaunchMode.inAppWebView &&
!(url.scheme == 'https' || url.scheme == 'http')) {
throw ArgumentError.value(url, 'url',
'To use an in-app web view, you must provide an http(s) URL.');
}
return UrlLauncherPlatform.instance.launchUrl(
url.toString(),
LaunchOptions(
mode: convertLaunchMode(mode),
webViewConfiguration: convertConfiguration(webViewConfiguration),
webOnlyWindowName: webOnlyWindowName,
),
);
}
/// Checks whether the specified URL can be handled by some app installed on the
/// device.
///
/// Returns true if it is possible to verify that there is a handler available.
/// A false return value can indicate either that there is no handler available,
/// or that the application does not have permission to check. For example:
/// - On recent versions of Android and iOS, this will always return false
/// unless the application has been configuration to allow
/// querying the system for launch support. See
/// [the README](https://pub.dev/packages/url_launcher#configuration) for
/// details.
/// - On web, this will always return false except for a few specific schemes
/// that are always assumed to be supported (such as http(s)), as web pages
/// are never allowed to query installed applications.
Future<bool> canLaunchUrl(Uri url) async {
return UrlLauncherPlatform.instance.canLaunch(url.toString());
}
/// Closes the current in-app web view, if one was previously opened by
/// [launchUrl].
///
/// If [launchUrl] was never called with [LaunchMode.inAppWebView], then this
/// call will have no effect.
Future<void> closeInAppWebView() async {
return UrlLauncherPlatform.instance.closeWebView();
}
| plugins/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart",
"repo_id": "plugins",
"token_count": 1122
} | 1,320 |
// 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.urllauncher;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.urllauncher.UrlLauncher.LaunchStatus;
import java.util.Map;
/**
* Translates incoming UrlLauncher MethodCalls into well formed Java function calls for {@link
* UrlLauncher}.
*/
final class MethodCallHandlerImpl implements MethodCallHandler {
private static final String TAG = "MethodCallHandlerImpl";
private final UrlLauncher urlLauncher;
@Nullable private MethodChannel channel;
/** Forwards all incoming MethodChannel calls to the given {@code urlLauncher}. */
MethodCallHandlerImpl(UrlLauncher urlLauncher) {
this.urlLauncher = urlLauncher;
}
@Override
public void onMethodCall(MethodCall call, Result result) {
final String url = call.argument("url");
switch (call.method) {
case "canLaunch":
onCanLaunch(result, url);
break;
case "launch":
onLaunch(call, result, url);
break;
case "closeWebView":
onCloseWebView(result);
break;
default:
result.notImplemented();
break;
}
}
/**
* Registers this instance as a method call handler on the given {@code messenger}.
*
* <p>Stops any previously started and unstopped calls.
*
* <p>This should be cleaned with {@link #stopListening} once the messenger is disposed of.
*/
void startListening(BinaryMessenger messenger) {
if (channel != null) {
Log.wtf(TAG, "Setting a method call handler before the last was disposed.");
stopListening();
}
channel = new MethodChannel(messenger, "plugins.flutter.io/url_launcher_android");
channel.setMethodCallHandler(this);
}
/**
* Clears this instance from listening to method calls.
*
* <p>Does nothing if {@link #startListening} hasn't been called, or if we're already stopped.
*/
void stopListening() {
if (channel == null) {
Log.d(TAG, "Tried to stop listening when no MethodChannel had been initialized.");
return;
}
channel.setMethodCallHandler(null);
channel = null;
}
private void onCanLaunch(Result result, String url) {
result.success(urlLauncher.canLaunch(url));
}
private void onLaunch(MethodCall call, Result result, String url) {
final boolean useWebView = call.argument("useWebView");
final boolean enableJavaScript = call.argument("enableJavaScript");
final boolean enableDomStorage = call.argument("enableDomStorage");
final Map<String, String> headersMap = call.argument("headers");
final Bundle headersBundle = extractBundle(headersMap);
LaunchStatus launchStatus =
urlLauncher.launch(url, headersBundle, useWebView, enableJavaScript, enableDomStorage);
if (launchStatus == LaunchStatus.NO_ACTIVITY) {
result.error("NO_ACTIVITY", "Launching a URL requires a foreground activity.", null);
} else if (launchStatus == LaunchStatus.ACTIVITY_NOT_FOUND) {
result.error(
"ACTIVITY_NOT_FOUND",
String.format("No Activity found to handle intent { %s }", url),
null);
} else {
result.success(true);
}
}
private void onCloseWebView(Result result) {
urlLauncher.closeWebView();
result.success(null);
}
private static Bundle extractBundle(Map<String, String> headersMap) {
final Bundle headersBundle = new Bundle();
for (String key : headersMap.keySet()) {
final String value = headersMap.get(key);
headersBundle.putString(key, value);
}
return headersBundle;
}
}
| plugins/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/MethodCallHandlerImpl.java/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/MethodCallHandlerImpl.java",
"repo_id": "plugins",
"token_count": 1344
} | 1,321 |