text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
REM This file is used by
REM https://github.com/flutter/tests/tree/master/registry/flutter_packages.test
REM to run the tests of certain packages in this repository as a presubmit
REM for the flutter/flutter repository.
REM Changes to this file (and any tests in this repository) are only honored
REM after the commit hash in the "flutter_packages.test" mentioned above has
REM been updated.
REM Remember to also update the Posix version (customer_testing.sh) when
REM changing this file.
CD packages/animations
CALL flutter analyze --no-fatal-infos
CALL flutter test
REM We don't run the tests in packages/rfw because those tests are
REM platform-sensitive and only work reliably on Linux.
| packages/customer_testing.bat/0 | {
"file_path": "packages/customer_testing.bat",
"repo_id": "packages",
"token_count": 184
} | 1,100 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:label="example"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:exported="true"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
| packages/packages/animations/example/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/animations/example/android/app/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 480
} | 1,101 |
// 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:animations/src/shared_axis_transition.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vector_math/vector_math_64.dart' hide Colors;
void main() {
group('SharedAxisTransitionType.horizontal', () {
testWidgets(
'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition',
(WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
);
await tester.pumpWidget(
const SharedAxisPageTransitionsBuilder(
transitionType: SharedAxisTransitionType.horizontal,
).buildTransitions<void>(
null,
null,
animation,
secondaryAnimation,
const Placeholder(),
),
);
expect(find.byType(SharedAxisTransition), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition runs forward',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.horizontal,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
0.0,
);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
// Bottom route is not offset and fully visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
0.0,
);
expect(_getOpacity(bottomRoute, tester), 1.0);
// Top route is offset to the right by 30.0 pixels
// and not visible yet.
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
),
30.0,
);
expect(_getOpacity(topRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
// should be be completely faded out while the top route
// is also completely faded out.
// Transition time: 300ms, 3/10 * 300ms = 90ms
await tester.pump(const Duration(milliseconds: 90));
// Bottom route is now invisible
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is still invisible, but moving towards the left.
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
double? topOffset = _getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
);
expect(topOffset, lessThan(30.0));
expect(topOffset, greaterThan(0.0));
// Jump to the middle of fading in
await tester.pump(const Duration(milliseconds: 90));
// Bottom route is still invisible
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is fading in
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), greaterThan(0));
expect(_getOpacity(topRoute, tester), lessThan(1.0));
topOffset = _getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
);
expect(topOffset, greaterThan(0.0));
expect(topOffset, lessThan(30.0));
// Jump to the end of the transition
await tester.pump(const Duration(milliseconds: 120));
// Bottom route is not visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
-30.0,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route has no offset and is visible.
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
),
0.0,
);
expect(_getOpacity(topRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(bottomRoute), findsNothing);
expect(find.text(topRoute), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition runs in reverse',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.horizontal,
),
);
navigator.currentState!.pushNamed('/a');
await tester.pumpAndSettle();
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
),
0.0,
);
expect(_getOpacity(topRoute, tester), 1.0);
expect(find.text(bottomRoute), findsNothing);
navigator.currentState!.pop();
await tester.pump();
// Top route is is not offset and fully visible.
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
),
0.0,
);
expect(_getOpacity(topRoute, tester), 1.0);
// Bottom route is offset to the left and is not visible yet.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
-30.0,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
// should be be completely faded out while the top route
// is also completely faded out.
// Transition time: 300ms, 3/10 * 300ms = 90ms
await tester.pump(const Duration(milliseconds: 90));
// Top route is now invisible
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
// Bottom route is still invisible, but moving towards the right.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester),
moreOrLessEquals(0, epsilon: 0.005));
double? bottomOffset = _getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
);
expect(bottomOffset, lessThan(0.0));
expect(bottomOffset, greaterThan(-30.0));
// Jump to the middle of fading in
await tester.pump(const Duration(milliseconds: 90));
// Top route is still invisible
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
// Bottom route is fading in
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), greaterThan(0));
expect(_getOpacity(bottomRoute, tester), lessThan(1.0));
bottomOffset = _getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
);
expect(bottomOffset, lessThan(0.0));
expect(bottomOffset, greaterThan(-30.0));
// Jump to the end of the transition
await tester.pump(const Duration(milliseconds: 120));
// Top route is not visible and is offset to the right.
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
),
30.0,
);
expect(_getOpacity(topRoute, tester), 0.0);
// Bottom route is not offset and is visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
0.0,
);
expect(_getOpacity(bottomRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition does not jump when interrupted',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.horizontal,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
// Jump to halfway point of transition.
await tester.pump(const Duration(milliseconds: 150));
// Bottom route is fully faded out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
final double halfwayBottomOffset = _getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
);
expect(halfwayBottomOffset, lessThan(0.0));
expect(halfwayBottomOffset, greaterThan(-30.0));
// Top route is fading/coming in.
expect(find.text(topRoute), findsOneWidget);
final double halfwayTopOffset = _getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
);
final double halfwayTopOpacity = _getOpacity(topRoute, tester);
expect(halfwayTopOffset, greaterThan(0.0));
expect(halfwayTopOffset, lessThan(30.0));
expect(halfwayTopOpacity, greaterThan(0.0));
expect(halfwayTopOpacity, lessThan(1.0));
// Interrupt the transition with a pop.
navigator.currentState!.pop();
await tester.pump();
// Nothing should change.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
halfwayBottomOffset,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
),
halfwayTopOffset,
);
expect(_getOpacity(topRoute, tester), halfwayTopOpacity);
// Jump to the 1/4 (75 ms) point of transition
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
lessThan(0.0),
);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
greaterThan(-30.0),
);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
greaterThan(halfwayBottomOffset),
);
expect(_getOpacity(bottomRoute, tester), greaterThan(0.0));
expect(_getOpacity(bottomRoute, tester), lessThan(1.0));
// Jump to the end.
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.horizontal,
),
0.0,
);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.horizontal,
),
30.0,
);
expect(_getOpacity(topRoute, tester), 0.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
},
);
testWidgets(
'State is not lost when transitioning',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
contentBuilder: (RouteSettings settings) {
return _StatefulTestWidget(
key: ValueKey<String?>(settings.name),
name: settings.name!,
);
},
transitionType: SharedAxisTransitionType.horizontal,
),
);
final _StatefulTestWidgetState bottomState = tester.state(
find.byKey(const ValueKey<String?>(bottomRoute)),
);
expect(bottomState.widget.name, bottomRoute);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(
const ValueKey<String?>(bottomRoute),
skipOffstage: false,
)),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
navigator.currentState!.pop();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
},
);
testWidgets('default fill color', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
// The default fill color should be derived from ThemeData.canvasColor.
final Color defaultFillColor = ThemeData().canvasColor;
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.horizontal,
),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(tester.widget<ColoredBox>(fillContainerFinder).color,
defaultFillColor);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pumpAndSettle();
fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/a')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(tester.widget<ColoredBox>(fillContainerFinder).color,
defaultFillColor);
});
testWidgets('custom fill color', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
fillColor: Colors.green,
transitionType: SharedAxisTransitionType.horizontal,
),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(
tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pumpAndSettle();
fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/a')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(
tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
});
testWidgets('should keep state', (WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SharedAxisTransition(
transitionType: SharedAxisTransitionType.horizontal,
animation: animation,
secondaryAnimation: secondaryAnimation,
child: const _StatefulTestWidget(name: 'Foo'),
),
),
));
final State<StatefulWidget> state = tester.state(
find.byType(_StatefulTestWidget),
);
expect(state, isNotNull);
animation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
animation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
});
});
group('SharedAxisTransitionType.vertical', () {
testWidgets(
'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition',
(WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
);
await tester.pumpWidget(
const SharedAxisPageTransitionsBuilder(
transitionType: SharedAxisTransitionType.vertical,
).buildTransitions<void>(
null,
null,
animation,
secondaryAnimation,
const Placeholder(),
),
);
expect(find.byType(SharedAxisTransition), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition runs forward',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.vertical,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
0.0,
);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
// Bottom route is not offset and fully visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
0.0,
);
expect(_getOpacity(bottomRoute, tester), 1.0);
// Top route is offset down by 30.0 pixels
// and not visible yet.
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
),
30.0,
);
expect(_getOpacity(topRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
// should be be completely faded out while the top route
// is also completely faded out.
// Transition time: 300ms, 3/10 * 300ms = 90ms
await tester.pump(const Duration(milliseconds: 90));
// Bottom route is now invisible
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is still invisible, but moving up.
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
double? topOffset = _getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
);
expect(topOffset, lessThan(30.0));
expect(topOffset, greaterThan(0.0));
// Jump to the middle of fading in
await tester.pump(const Duration(milliseconds: 90));
// Bottom route is still invisible
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is fading in
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), greaterThan(0));
expect(_getOpacity(topRoute, tester), lessThan(1.0));
topOffset = _getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
);
expect(topOffset, greaterThan(0.0));
expect(topOffset, lessThan(30.0));
// Jump to the end of the transition
await tester.pump(const Duration(milliseconds: 120));
// Bottom route is not visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
-30.0,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route has no offset and is visible.
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
),
0.0,
);
expect(_getOpacity(topRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(bottomRoute), findsNothing);
expect(find.text(topRoute), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition runs in reverse',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.vertical,
),
);
navigator.currentState!.pushNamed('/a');
await tester.pumpAndSettle();
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
),
0.0,
);
expect(_getOpacity(topRoute, tester), 1.0);
expect(find.text(bottomRoute), findsNothing);
navigator.currentState!.pop();
await tester.pump();
// Top route is is not offset and fully visible.
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
),
0.0,
);
expect(_getOpacity(topRoute, tester), 1.0);
// Bottom route is offset up and is not visible yet.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
-30.0,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
// should be be completely faded out while the top route
// is also completely faded out.
// Transition time: 300ms, 3/10 * 300ms = 90ms
await tester.pump(const Duration(milliseconds: 90));
// Top route is now invisible
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
// Bottom route is still invisible, but moving down.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getOpacity(bottomRoute, tester),
moreOrLessEquals(0, epsilon: 0.005),
);
double? bottomOffset = _getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
);
expect(bottomOffset, lessThan(0.0));
expect(bottomOffset, greaterThan(-30.0));
// Jump to the middle of fading in
await tester.pump(const Duration(milliseconds: 90));
// Top route is still invisible
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
// Bottom route is fading in
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), greaterThan(0));
expect(_getOpacity(bottomRoute, tester), lessThan(1.0));
bottomOffset = _getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
);
expect(bottomOffset, lessThan(0.0));
expect(bottomOffset, greaterThan(-30.0));
// Jump to the end of the transition
await tester.pump(const Duration(milliseconds: 120));
// Top route is not visible and is offset down.
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
),
30.0,
);
expect(_getOpacity(topRoute, tester), 0.0);
// Bottom route is not offset and is visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
0.0,
);
expect(_getOpacity(bottomRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition does not jump when interrupted',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.vertical,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
// Jump to halfway point of transition.
await tester.pump(const Duration(milliseconds: 150));
// Bottom route is fully faded out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
final double halfwayBottomOffset = _getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
);
expect(halfwayBottomOffset, lessThan(0.0));
expect(halfwayBottomOffset, greaterThan(-30.0));
// Top route is fading/coming in.
expect(find.text(topRoute), findsOneWidget);
final double halfwayTopOffset = _getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
);
final double halfwayTopOpacity = _getOpacity(topRoute, tester);
expect(halfwayTopOffset, greaterThan(0.0));
expect(halfwayTopOffset, lessThan(30.0));
expect(halfwayTopOpacity, greaterThan(0.0));
expect(halfwayTopOpacity, lessThan(1.0));
// Interrupt the transition with a pop.
navigator.currentState!.pop();
await tester.pump();
// Nothing should change.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
halfwayBottomOffset,
);
expect(_getOpacity(bottomRoute, tester), 0.0);
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
),
halfwayTopOffset,
);
expect(_getOpacity(topRoute, tester), halfwayTopOpacity);
// Jump to the 1/4 (75 ms) point of transition
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
lessThan(0.0),
);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
greaterThan(-30.0),
);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
greaterThan(halfwayBottomOffset),
);
expect(_getOpacity(bottomRoute, tester), greaterThan(0.0));
expect(_getOpacity(bottomRoute, tester), lessThan(1.0));
// Jump to the end.
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getTranslationOffset(
bottomRoute,
tester,
SharedAxisTransitionType.vertical,
),
0.0,
);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsOneWidget);
expect(
_getTranslationOffset(
topRoute,
tester,
SharedAxisTransitionType.vertical,
),
30.0,
);
expect(_getOpacity(topRoute, tester), 0.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
},
);
testWidgets(
'State is not lost when transitioning',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
contentBuilder: (RouteSettings settings) {
return _StatefulTestWidget(
key: ValueKey<String?>(settings.name),
name: settings.name!,
);
},
transitionType: SharedAxisTransitionType.vertical,
),
);
final _StatefulTestWidgetState bottomState = tester.state(
find.byKey(const ValueKey<String?>(bottomRoute)),
);
expect(bottomState.widget.name, bottomRoute);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(
const ValueKey<String?>(bottomRoute),
skipOffstage: false,
)),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
navigator.currentState!.pop();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
},
);
testWidgets('default fill color', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
// The default fill color should be derived from ThemeData.canvasColor.
final Color defaultFillColor = ThemeData().canvasColor;
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.vertical,
),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(tester.widget<ColoredBox>(fillContainerFinder).color,
defaultFillColor);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pumpAndSettle();
fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/a')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(tester.widget<ColoredBox>(fillContainerFinder).color,
defaultFillColor);
});
testWidgets('custom fill color', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
fillColor: Colors.green,
transitionType: SharedAxisTransitionType.vertical,
),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(
tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pumpAndSettle();
fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/a')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(
tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
});
testWidgets('should keep state', (WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SharedAxisTransition(
transitionType: SharedAxisTransitionType.vertical,
animation: animation,
secondaryAnimation: secondaryAnimation,
child: const _StatefulTestWidget(name: 'Foo'),
),
),
));
final State<StatefulWidget> state = tester.state(
find.byType(_StatefulTestWidget),
);
expect(state, isNotNull);
animation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
animation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
});
});
group('SharedAxisTransitionType.scaled', () {
testWidgets(
'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition',
(WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
);
await tester.pumpWidget(
const SharedAxisPageTransitionsBuilder(
transitionType: SharedAxisTransitionType.scaled,
).buildTransitions<void>(
null,
null,
animation,
secondaryAnimation,
const Placeholder(),
),
);
expect(find.byType(SharedAxisTransition), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition runs forward',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.scaled,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
// Bottom route is full size and fully visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
// Top route is at 80% of full size and not visible yet.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.8);
expect(_getOpacity(topRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
// should be be completely faded out while the top route
// is also completely faded out.
// Transition time: 300ms, 3/10 * 300ms = 90ms
await tester.pump(const Duration(milliseconds: 90));
// Bottom route is now invisible
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is still invisible, but scaling up.
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
double topScale = _getScale(topRoute, tester);
expect(topScale, greaterThan(0.8));
expect(topScale, lessThan(1.0));
// Jump to the middle of fading in
await tester.pump(const Duration(milliseconds: 90));
// Bottom route is still invisible
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route is fading in
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), greaterThan(0));
expect(_getOpacity(topRoute, tester), lessThan(1.0));
topScale = _getScale(topRoute, tester);
expect(topScale, greaterThan(0.8));
expect(topScale, lessThan(1.0));
// Jump to the end of the transition
await tester.pump(const Duration(milliseconds: 120));
// Bottom route is not visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.1);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Top route fully scaled in and visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(bottomRoute), findsNothing);
expect(find.text(topRoute), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition runs in reverse',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.scaled,
),
);
navigator.currentState!.pushNamed(topRoute);
await tester.pumpAndSettle();
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
expect(find.text(bottomRoute), findsNothing);
navigator.currentState!.pop();
await tester.pump();
// Top route is full size and fully visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 1.0);
expect(_getOpacity(topRoute, tester), 1.0);
// Bottom route is at 110% of full size and not visible yet.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.1);
expect(_getOpacity(bottomRoute, tester), 0.0);
// Jump 3/10ths of the way through the transition, bottom route
// should be be completely faded out while the top route
// is also completely faded out.
// Transition time: 300ms, 3/10 * 300ms = 90ms
await tester.pump(const Duration(milliseconds: 90));
// Bottom route is now invisible
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
// Top route is still invisible, but scaling down.
expect(find.text(bottomRoute), findsOneWidget);
expect(
_getOpacity(bottomRoute, tester),
moreOrLessEquals(0, epsilon: 0.005),
);
double bottomScale = _getScale(bottomRoute, tester);
expect(bottomScale, greaterThan(1.0));
expect(bottomScale, lessThan(1.1));
// Jump to the middle of fading in
await tester.pump(const Duration(milliseconds: 90));
// Top route is still invisible
expect(find.text(topRoute), findsOneWidget);
expect(_getOpacity(topRoute, tester), 0.0);
// Bottom route is fading in
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), greaterThan(0));
expect(_getOpacity(bottomRoute, tester), lessThan(1.0));
bottomScale = _getScale(bottomRoute, tester);
expect(bottomScale, greaterThan(1.0));
expect(bottomScale, lessThan(1.1));
// Jump to the end of the transition
await tester.pump(const Duration(milliseconds: 120));
// Top route is not visible.
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.8);
expect(_getOpacity(topRoute, tester), 0.0);
// Bottom route fully scaled in and visible.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition does not jump when interrupted',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.scaled,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
// Jump to halfway point of transition.
await tester.pump(const Duration(milliseconds: 150));
// Bottom route is fully faded out.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getOpacity(bottomRoute, tester), 0.0);
final double halfwayBottomScale = _getScale(bottomRoute, tester);
expect(halfwayBottomScale, greaterThan(1.0));
expect(halfwayBottomScale, lessThan(1.1));
// Top route is fading/scaling in.
expect(find.text(topRoute), findsOneWidget);
final double halfwayTopScale = _getScale(topRoute, tester);
final double halfwayTopOpacity = _getOpacity(topRoute, tester);
expect(halfwayTopScale, greaterThan(0.8));
expect(halfwayTopScale, lessThan(1.0));
expect(halfwayTopOpacity, greaterThan(0.0));
expect(halfwayTopOpacity, lessThan(1.0));
// Interrupt the transition with a pop.
navigator.currentState!.pop();
await tester.pump();
// Nothing should change.
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), halfwayBottomScale);
expect(_getOpacity(bottomRoute, tester), 0.0);
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), halfwayTopScale);
expect(_getOpacity(topRoute, tester), halfwayTopOpacity);
// Jump to the 1/4 (75 ms) point of transition
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), greaterThan(1.0));
expect(_getScale(bottomRoute, tester), lessThan(1.1));
expect(_getScale(bottomRoute, tester), lessThan(halfwayBottomScale));
expect(_getOpacity(bottomRoute, tester), greaterThan(0.0));
expect(_getOpacity(bottomRoute, tester), lessThan(1.0));
// Jump to the end.
await tester.pump(const Duration(milliseconds: 75));
expect(find.text(bottomRoute), findsOneWidget);
expect(_getScale(bottomRoute, tester), 1.0);
expect(_getOpacity(bottomRoute, tester), 1.0);
expect(find.text(topRoute), findsOneWidget);
expect(_getScale(topRoute, tester), 0.80);
expect(_getOpacity(topRoute, tester), 0.0);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text(topRoute), findsNothing);
expect(find.text(bottomRoute), findsOneWidget);
},
);
testWidgets(
'SharedAxisTransition properly disposes animation',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.scaled,
),
);
expect(find.text(bottomRoute), findsOneWidget);
expect(find.text(topRoute), findsNothing);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
// Jump to halfway point of transition.
await tester.pump(const Duration(milliseconds: 150));
expect(find.byType(SharedAxisTransition), findsNWidgets(2));
// Rebuild the app without the transition.
await tester.pumpWidget(
MaterialApp(
navigatorKey: navigator,
home: const Material(
child: Text('abc'),
),
),
);
await tester.pump();
// Transitions should have been disposed of.
expect(find.byType(SharedAxisTransition), findsNothing);
},
);
testWidgets(
'State is not lost when transitioning',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.scaled,
contentBuilder: (RouteSettings settings) {
return _StatefulTestWidget(
key: ValueKey<String?>(settings.name),
name: settings.name!,
);
},
),
);
final _StatefulTestWidgetState bottomState = tester.state(
find.byKey(const ValueKey<String?>(bottomRoute)),
);
expect(bottomState.widget.name, bottomRoute);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
final _StatefulTestWidgetState topState = tester.state(
find.byKey(const ValueKey<String?>(topRoute)),
);
expect(topState.widget.name, topRoute);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(
const ValueKey<String?>(bottomRoute),
skipOffstage: false,
)),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
navigator.currentState!.pop();
await tester.pump();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pump(const Duration(milliseconds: 150));
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(
tester.state(find.byKey(const ValueKey<String?>(topRoute))),
topState,
);
await tester.pumpAndSettle();
expect(
tester.state(find.byKey(const ValueKey<String?>(bottomRoute))),
bottomState,
);
expect(find.byKey(const ValueKey<String?>(topRoute)), findsNothing);
},
);
testWidgets('default fill color', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
// The default fill color should be derived from ThemeData.canvasColor.
final Color defaultFillColor = ThemeData().canvasColor;
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
transitionType: SharedAxisTransitionType.scaled,
),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(tester.widget<ColoredBox>(fillContainerFinder).color,
defaultFillColor);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pumpAndSettle();
fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/a')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(tester.widget<ColoredBox>(fillContainerFinder).color,
defaultFillColor);
});
testWidgets('custom fill color', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
const String bottomRoute = '/';
const String topRoute = '/a';
await tester.pumpWidget(
_TestWidget(
navigatorKey: navigator,
fillColor: Colors.green,
transitionType: SharedAxisTransitionType.scaled,
),
);
expect(find.text(bottomRoute), findsOneWidget);
Finder fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(
tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
navigator.currentState!.pushNamed(topRoute);
await tester.pump();
await tester.pumpAndSettle();
fillContainerFinder = find
.ancestor(
matching: find.byType(ColoredBox),
of: find.byKey(const ValueKey<String?>('/a')),
)
.last;
expect(fillContainerFinder, findsOneWidget);
expect(
tester.widget<ColoredBox>(fillContainerFinder).color, Colors.green);
});
testWidgets('should keep state', (WidgetTester tester) async {
final AnimationController animation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
final AnimationController secondaryAnimation = AnimationController(
vsync: const TestVSync(),
duration: const Duration(milliseconds: 300),
);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SharedAxisTransition(
transitionType: SharedAxisTransitionType.scaled,
animation: animation,
secondaryAnimation: secondaryAnimation,
child: const _StatefulTestWidget(name: 'Foo'),
),
),
));
final State<StatefulWidget> state = tester.state(
find.byType(_StatefulTestWidget),
);
expect(state, isNotNull);
animation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.forward();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
secondaryAnimation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
animation.reverse();
await tester.pump();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pump(const Duration(milliseconds: 150));
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
await tester.pumpAndSettle();
expect(state, same(tester.state(find.byType(_StatefulTestWidget))));
});
});
}
double _getOpacity(String key, WidgetTester tester) {
final Finder finder = find.ancestor(
of: find.byKey(ValueKey<String?>(key)),
matching: find.byType(FadeTransition),
);
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final FadeTransition transition = widget as FadeTransition;
return a * transition.opacity.value;
});
}
double _getTranslationOffset(
String key,
WidgetTester tester,
SharedAxisTransitionType transitionType,
) {
final Finder finder = find.ancestor(
of: find.byKey(ValueKey<String?>(key)),
matching: find.byType(Transform),
);
switch (transitionType) {
case SharedAxisTransitionType.horizontal:
return tester.widgetList<Transform>(finder).fold<double>(0.0,
(double a, Widget widget) {
final Transform transition = widget as Transform;
final Vector3 translation = transition.transform.getTranslation();
return a + translation.x;
});
case SharedAxisTransitionType.vertical:
return tester.widgetList<Transform>(finder).fold<double>(0.0,
(double a, Widget widget) {
final Transform transition = widget as Transform;
final Vector3 translation = transition.transform.getTranslation();
return a + translation.y;
});
case SharedAxisTransitionType.scaled:
assert(
false,
'SharedAxisTransitionType.scaled does not have a translation offset',
);
return 0.0;
}
}
double _getScale(String key, WidgetTester tester) {
final Finder finder = find.ancestor(
of: find.byKey(ValueKey<String?>(key)),
matching: find.byType(ScaleTransition),
);
return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) {
final ScaleTransition transition = widget as ScaleTransition;
return a * transition.scale.value;
});
}
class _TestWidget extends StatelessWidget {
const _TestWidget({
required this.navigatorKey,
this.contentBuilder,
required this.transitionType,
this.fillColor,
});
final Key navigatorKey;
final _ContentBuilder? contentBuilder;
final SharedAxisTransitionType transitionType;
final Color? fillColor;
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey as GlobalKey<NavigatorState>?,
theme: ThemeData(
platform: TargetPlatform.android,
pageTransitionsTheme: PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: SharedAxisPageTransitionsBuilder(
fillColor: fillColor,
transitionType: transitionType,
),
},
),
),
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) {
return contentBuilder != null
? contentBuilder!(settings)
: Center(
key: ValueKey<String?>(settings.name),
child: Text(settings.name!),
);
},
);
},
);
}
}
class _StatefulTestWidget extends StatefulWidget {
const _StatefulTestWidget({super.key, required this.name});
final String name;
@override
State<_StatefulTestWidget> createState() => _StatefulTestWidgetState();
}
class _StatefulTestWidgetState extends State<_StatefulTestWidget> {
@override
Widget build(BuildContext context) {
return Text(widget.name);
}
}
typedef _ContentBuilder = Widget Function(RouteSettings settings);
| packages/packages/animations/test/shared_axis_transition_test.dart/0 | {
"file_path": "packages/packages/animations/test/shared_axis_transition_test.dart",
"repo_id": "packages",
"token_count": 29742
} | 1,102 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera;
import android.os.Build;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
/** Wraps BUILD device info, allowing for overriding it in unit tests. */
public class DeviceInfo {
@VisibleForTesting public static @Nullable String BRAND = Build.BRAND;
@VisibleForTesting public static @Nullable String MODEL = Build.MODEL;
public static @Nullable String getBrand() {
return BRAND;
}
public static @Nullable String getModel() {
return MODEL;
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/DeviceInfo.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/DeviceInfo.java",
"repo_id": "packages",
"token_count": 201
} | 1,103 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.flash;
import android.annotation.SuppressLint;
import android.hardware.camera2.CaptureRequest;
import androidx.annotation.NonNull;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.features.CameraFeature;
/** Controls the flash configuration on the {@link android.hardware.camera2} API. */
public class FlashFeature extends CameraFeature<FlashMode> {
@NonNull private FlashMode currentSetting = FlashMode.auto;
/**
* Creates a new instance of the {@link FlashFeature}.
*
* @param cameraProperties Collection of characteristics for the current camera device.
*/
public FlashFeature(@NonNull CameraProperties cameraProperties) {
super(cameraProperties);
}
@NonNull
@Override
public String getDebugName() {
return "FlashFeature";
}
@SuppressLint("KotlinPropertyAccess")
@NonNull
@Override
public FlashMode getValue() {
return currentSetting;
}
@Override
public void setValue(@NonNull FlashMode value) {
this.currentSetting = value;
}
@Override
public boolean checkIsSupported() {
Boolean available = cameraProperties.getFlashInfoAvailable();
return available != null && available;
}
@Override
public void updateBuilder(@NonNull CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
switch (currentSetting) {
case off:
requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
break;
case always:
requestBuilder.set(
CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
break;
case torch:
requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
break;
case auto:
requestBuilder.set(
CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
break;
}
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/flash/FlashFeature.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/flash/FlashFeature.java",
"repo_id": "packages",
"token_count": 853
} | 1,104 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.types;
import androidx.annotation.NonNull;
/**
* Wrapper class that provides a container for all {@link Timeout} instances that are required for
* the capture flow.
*/
public class CaptureTimeoutsWrapper {
private Timeout preCaptureFocusing;
private Timeout preCaptureMetering;
private final long preCaptureFocusingTimeoutMs;
private final long preCaptureMeteringTimeoutMs;
/**
* Create a new wrapper instance with the specified timeout values.
*
* @param preCaptureFocusingTimeoutMs focusing timeout milliseconds.
* @param preCaptureMeteringTimeoutMs metering timeout milliseconds.
*/
public CaptureTimeoutsWrapper(
long preCaptureFocusingTimeoutMs, long preCaptureMeteringTimeoutMs) {
this.preCaptureFocusingTimeoutMs = preCaptureFocusingTimeoutMs;
this.preCaptureMeteringTimeoutMs = preCaptureMeteringTimeoutMs;
this.preCaptureFocusing = Timeout.create(preCaptureFocusingTimeoutMs);
this.preCaptureMetering = Timeout.create(preCaptureMeteringTimeoutMs);
}
/** Reset all timeouts to the current timestamp. */
public void reset() {
this.preCaptureFocusing = Timeout.create(preCaptureFocusingTimeoutMs);
this.preCaptureMetering = Timeout.create(preCaptureMeteringTimeoutMs);
}
/**
* Returns the timeout instance related to precapture focusing.
*
* @return - The timeout object
*/
@NonNull
public Timeout getPreCaptureFocusing() {
return preCaptureFocusing;
}
/**
* Returns the timeout instance related to precapture metering.
*
* @return - The timeout object
*/
@NonNull
public Timeout getPreCaptureMetering() {
return preCaptureMetering;
}
}
| packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/CaptureTimeoutsWrapper.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/types/CaptureTimeoutsWrapper.java",
"repo_id": "packages",
"token_count": 537
} | 1,105 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.media.Image;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class ImageSaverTests {
Image mockImage;
File mockFile;
ImageSaver.Callback mockCallback;
ImageSaver imageSaver;
Image.Plane mockPlane;
ByteBuffer mockBuffer;
MockedStatic<ImageSaver.FileOutputStreamFactory> mockFileOutputStreamFactory;
FileOutputStream mockFileOutputStream;
@Before
public void setup() {
// Set up mocked file dependency
mockFile = mock(File.class);
when(mockFile.getAbsolutePath()).thenReturn("absolute/path");
mockPlane = mock(Image.Plane.class);
mockBuffer = mock(ByteBuffer.class);
when(mockBuffer.remaining()).thenReturn(3);
when(mockBuffer.get(any()))
.thenAnswer(
new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
byte[] bytes = invocation.getArgument(0);
bytes[0] = 0x42;
bytes[1] = 0x00;
bytes[2] = 0x13;
return mockBuffer;
}
});
// Set up mocked image dependency
mockImage = mock(Image.class);
when(mockPlane.getBuffer()).thenReturn(mockBuffer);
when(mockImage.getPlanes()).thenReturn(new Image.Plane[] {mockPlane});
// Set up mocked FileOutputStream
mockFileOutputStreamFactory = mockStatic(ImageSaver.FileOutputStreamFactory.class);
mockFileOutputStream = mock(FileOutputStream.class);
mockFileOutputStreamFactory
.when(() -> ImageSaver.FileOutputStreamFactory.create(any()))
.thenReturn(mockFileOutputStream);
// Set up testable ImageSaver instance
mockCallback = mock(ImageSaver.Callback.class);
imageSaver = new ImageSaver(mockImage, mockFile, mockCallback);
}
@After
public void teardown() {
mockFileOutputStreamFactory.close();
}
@Test
public void runWritesBytesToFileAndFinishesWithPath() throws IOException {
imageSaver.run();
verify(mockFileOutputStream, times(1)).write(new byte[] {0x42, 0x00, 0x13});
verify(mockCallback, times(1)).onComplete("absolute/path");
verify(mockCallback, never()).onError(any(), any());
}
@Test
public void runCallsErrorOnWriteIoexception() throws IOException {
doThrow(new IOException()).when(mockFileOutputStream).write(any());
imageSaver.run();
verify(mockCallback, times(1)).onError("IOError", "Failed saving image");
verify(mockCallback, never()).onComplete(any());
}
@Test
public void runCallsErrorOnCloseIoexception() throws IOException {
doThrow(new IOException("message")).when(mockFileOutputStream).close();
imageSaver.run();
verify(mockCallback, times(1)).onError("cameraAccess", "message");
}
}
| packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/ImageSaverTests.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/ImageSaverTests.java",
"repo_id": "packages",
"token_count": 1300
} | 1,106 |
// 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.zoomlevel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyFloat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.graphics.Rect;
import android.hardware.camera2.CaptureRequest;
import android.os.Build;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.SdkCapabilityChecker;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
public class ZoomLevelFeatureTest {
private MockedStatic<ZoomUtils> mockedStaticCameraZoom;
private CameraProperties mockCameraProperties;
private ZoomUtils mockCameraZoom;
private Rect mockZoomArea;
private Rect mockSensorArray;
@Before
public void before() {
mockedStaticCameraZoom = mockStatic(ZoomUtils.class);
mockCameraProperties = mock(CameraProperties.class);
mockCameraZoom = mock(ZoomUtils.class);
mockZoomArea = mock(Rect.class);
mockSensorArray = mock(Rect.class);
mockedStaticCameraZoom
.when(() -> ZoomUtils.computeZoomRect(anyFloat(), any(), anyFloat(), anyFloat()))
.thenReturn(mockZoomArea);
}
@After
public void after() {
mockedStaticCameraZoom.close();
}
@Test
public void ctor_whenParametersAreValid() {
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(mockSensorArray);
when(mockCameraProperties.getScalerAvailableMaxDigitalZoom()).thenReturn(42f);
final ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
verify(mockCameraProperties, times(1)).getSensorInfoActiveArraySize();
verify(mockCameraProperties, times(1)).getScalerAvailableMaxDigitalZoom();
assertNotNull(zoomLevelFeature);
assertEquals(42f, zoomLevelFeature.getMaximumZoomLevel(), 0);
}
@Test
public void ctor_whenSensorSizeIsNull() {
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(null);
when(mockCameraProperties.getScalerAvailableMaxDigitalZoom()).thenReturn(42f);
final ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
verify(mockCameraProperties, times(1)).getSensorInfoActiveArraySize();
verify(mockCameraProperties, never()).getScalerAvailableMaxDigitalZoom();
assertNotNull(zoomLevelFeature);
assertFalse(zoomLevelFeature.checkIsSupported());
assertEquals(zoomLevelFeature.getMaximumZoomLevel(), 1.0f, 0);
}
@Test
public void ctor_whenMaxZoomIsNull() {
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(mockSensorArray);
when(mockCameraProperties.getScalerAvailableMaxDigitalZoom()).thenReturn(null);
final ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
verify(mockCameraProperties, times(1)).getSensorInfoActiveArraySize();
verify(mockCameraProperties, times(1)).getScalerAvailableMaxDigitalZoom();
assertNotNull(zoomLevelFeature);
assertFalse(zoomLevelFeature.checkIsSupported());
assertEquals(zoomLevelFeature.getMaximumZoomLevel(), 1.0f, 0);
}
@Test
public void ctor_whenMaxZoomIsSmallerThenDefaultZoomFactor() {
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(mockSensorArray);
when(mockCameraProperties.getScalerAvailableMaxDigitalZoom()).thenReturn(0.5f);
final ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
verify(mockCameraProperties, times(1)).getSensorInfoActiveArraySize();
verify(mockCameraProperties, times(1)).getScalerAvailableMaxDigitalZoom();
assertNotNull(zoomLevelFeature);
assertFalse(zoomLevelFeature.checkIsSupported());
assertEquals(zoomLevelFeature.getMaximumZoomLevel(), 1.0f, 0);
}
@Test
public void getDebugName_shouldReturnTheNameOfTheFeature() {
ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
assertEquals("ZoomLevelFeature", zoomLevelFeature.getDebugName());
}
@Test
public void getValue_shouldReturnNullIfNotSet() {
ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
assertEquals(1.0, zoomLevelFeature.getValue(), 0);
}
@Test
public void getValue_shouldEchoSetValue() {
ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
zoomLevelFeature.setValue(2.3f);
assertEquals(2.3f, zoomLevelFeature.getValue(), 0);
}
@Test
public void checkIsSupport_returnsFalseByDefault() {
ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
assertFalse(zoomLevelFeature.checkIsSupported());
}
@Test
public void updateBuilder_shouldSetScalarCropRegionWhenCheckIsSupportIsTrue() {
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(mockSensorArray);
when(mockCameraProperties.getScalerAvailableMaxDigitalZoom()).thenReturn(42f);
ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
zoomLevelFeature.updateBuilder(mockBuilder);
verify(mockBuilder, times(1)).set(CaptureRequest.SCALER_CROP_REGION, mockZoomArea);
}
@Test
public void updateBuilder_shouldControlZoomRatioWhenCheckIsSupportIsTrue() throws Exception {
setSdkVersion(Build.VERSION_CODES.R);
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(mockSensorArray);
when(mockCameraProperties.getScalerMaxZoomRatio()).thenReturn(42f);
when(mockCameraProperties.getScalerMinZoomRatio()).thenReturn(1.0f);
ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
zoomLevelFeature.updateBuilder(mockBuilder);
verify(mockBuilder, times(1)).set(CaptureRequest.CONTROL_ZOOM_RATIO, 0.0f);
}
@Test
public void getMinimumZoomLevel() {
ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
assertEquals(1.0f, zoomLevelFeature.getMinimumZoomLevel(), 0);
}
@Test
public void getMaximumZoomLevel() {
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(mockSensorArray);
when(mockCameraProperties.getScalerAvailableMaxDigitalZoom()).thenReturn(42f);
ZoomLevelFeature zoomLevelFeature = new ZoomLevelFeature(mockCameraProperties);
assertEquals(42f, zoomLevelFeature.getMaximumZoomLevel(), 0);
}
@Test
public void checkZoomLevelFeature_callsMaxDigitalZoomOnAndroidQ() throws Exception {
setSdkVersion(Build.VERSION_CODES.Q);
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(mockSensorArray);
new ZoomLevelFeature(mockCameraProperties);
verify(mockCameraProperties, times(0)).getScalerMaxZoomRatio();
verify(mockCameraProperties, times(0)).getScalerMinZoomRatio();
verify(mockCameraProperties, times(1)).getScalerAvailableMaxDigitalZoom();
}
@Test
public void checkZoomLevelFeature_callsScalarMaxZoomRatioOnAndroidR() throws Exception {
setSdkVersion(Build.VERSION_CODES.R);
when(mockCameraProperties.getSensorInfoActiveArraySize()).thenReturn(mockSensorArray);
new ZoomLevelFeature(mockCameraProperties);
verify(mockCameraProperties, times(1)).getScalerMaxZoomRatio();
verify(mockCameraProperties, times(1)).getScalerMinZoomRatio();
verify(mockCameraProperties, times(0)).getScalerAvailableMaxDigitalZoom();
}
static void setSdkVersion(int sdkVersion) throws Exception {
SdkCapabilityChecker.SDK_VERSION = sdkVersion;
}
}
| packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/zoomlevel/ZoomLevelFeatureTest.java/0 | {
"file_path": "packages/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/zoomlevel/ZoomLevelFeatureTest.java",
"repo_id": "packages",
"token_count": 2625
} | 1,107 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_driver/flutter_driver.dart';
const String _examplePackage = 'io.flutter.plugins.cameraexample';
Future<void> main() async {
if (!(Platform.isLinux || Platform.isMacOS)) {
print('This test must be run on a POSIX host. Skipping...');
exit(0);
}
final bool adbExists =
Process.runSync('which', <String>['adb']).exitCode == 0;
if (!adbExists) {
print(r'This test needs ADB to exist on the $PATH. Skipping...');
exit(0);
}
print('Granting camera permissions...');
Process.runSync('adb', <String>[
'shell',
'pm',
'grant',
_examplePackage,
'android.permission.CAMERA'
]);
Process.runSync('adb', <String>[
'shell',
'pm',
'grant',
_examplePackage,
'android.permission.RECORD_AUDIO'
]);
print('Starting test.');
final FlutterDriver driver = await FlutterDriver.connect();
final String data = await driver.requestData(
null,
timeout: const Duration(minutes: 1),
);
await driver.close();
print('Test finished. Revoking camera permissions...');
Process.runSync('adb', <String>[
'shell',
'pm',
'revoke',
_examplePackage,
'android.permission.CAMERA'
]);
Process.runSync('adb', <String>[
'shell',
'pm',
'revoke',
_examplePackage,
'android.permission.RECORD_AUDIO'
]);
final Map<String, dynamic> result = jsonDecode(data) as Map<String, dynamic>;
exit(result['result'] == 'true' ? 0 : 1);
}
| packages/packages/camera/camera_android/example/test_driver/integration_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android/example/test_driver/integration_test.dart",
"repo_id": "packages",
"token_count": 637
} | 1,108 |
group 'io.flutter.plugins.camerax'
version '1.0'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'io.flutter.plugins.camerax'
}
// CameraX dependencies require compilation against version 33 or later.
compileSdk 34
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
// Many of the CameraX APIs require API 21.
minSdkVersion 21
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'AndroidGradlePluginVersion', 'GradleDependency', 'InvalidPackage'
}
}
dependencies {
// CameraX core library using the camera2 implementation must use same version number.
def camerax_version = "1.3.0-beta01"
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"
implementation "androidx.camera:camera-lifecycle:${camerax_version}"
implementation "androidx.camera:camera-video:${camerax_version}"
implementation 'com.google.guava:guava:32.0.1-android'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-inline:5.0.0'
testImplementation 'androidx.test:core:1.4.0'
testImplementation 'org.robolectric:robolectric:4.10.3'
// org.jetbrains.kotlin:kotlin-bom artifact purpose is to align kotlin stdlib and related code versions.
// See: https://youtrack.jetbrains.com/issue/KT-55297/kotlin-stdlib-should-declare-constraints-on-kotlin-stdlib-jdk8-and-kotlin-stdlib-jdk7
implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.8.10"))
}
| packages/packages/camera/camera_android_camerax/android/build.gradle/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/build.gradle",
"repo_id": "packages",
"token_count": 997
} | 1,109 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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 @NonNull CameraXProxy cameraXProxy = new CameraXProxy();
public CameraSelectorHostApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
}
@Override
public void create(@NonNull Long identifier, @Nullable Long lensFacing) {
CameraSelector.Builder cameraSelectorBuilder = cameraXProxy.createCameraSelectorBuilder();
if (lensFacing != null) {
cameraSelectorBuilder = cameraSelectorBuilder.requireLensFacing(lensFacing.intValue());
}
instanceManager.addDartCreatedInstance(cameraSelectorBuilder.build(), identifier);
}
@Override
public @NonNull List<Long> filter(@NonNull Long identifier, @NonNull List<Long> cameraInfoIds) {
CameraSelector cameraSelector =
(CameraSelector) Objects.requireNonNull(instanceManager.getInstance(identifier));
List<CameraInfo> cameraInfosForFilter = new ArrayList<>();
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<>();
for (CameraInfo cameraInfo : filteredCameraInfos) {
Long filteredCameraInfoId = instanceManager.getIdentifierForStrongReference(cameraInfo);
filteredCameraInfosIds.add(filteredCameraInfoId);
}
return filteredCameraInfosIds;
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorHostApiImpl.java",
"repo_id": "packages",
"token_count": 762
} | 1,110 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.ImageProxy;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageProxyFlutterApi;
/**
* Flutter API implementation for {@link ImageProxy}.
*
* <p>This class may handle adding native instances that are attached to a Dart instance or passing
* arguments of callbacks methods to a Dart instance.
*/
public class ImageProxyFlutterApiImpl {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
private ImageProxyFlutterApi api;
/**
* Constructs a {@link ImageProxyFlutterApiImpl}.
*
* @param binaryMessenger used to communicate with Dart over asynchronous messages
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public ImageProxyFlutterApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
api = new ImageProxyFlutterApi(binaryMessenger);
}
/**
* Stores the {@link ImageProxy} instance and notifies Dart to create and store a new {@link
* ImageProxy} instance that is attached to this one. If {@code instance} has already been added,
* this method does nothing.
*/
public void create(
@NonNull ImageProxy instance,
@NonNull Long imageFormat,
@NonNull Long imageHeight,
@NonNull Long imageWidth,
@NonNull ImageProxyFlutterApi.Reply<Void> callback) {
if (!instanceManager.containsInstance(instance)) {
api.create(
instanceManager.addHostCreatedInstance(instance),
imageFormat,
imageHeight,
imageWidth,
callback);
}
}
/**
* Sets the Flutter API used to send messages to Dart.
*
* <p>This is only visible for testing.
*/
@VisibleForTesting
void setApi(@NonNull ImageProxyFlutterApi api) {
this.api = api;
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyFlutterApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyFlutterApiImpl.java",
"repo_id": "packages",
"token_count": 714
} | 1,111 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import android.util.Size;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.video.FallbackStrategy;
import androidx.camera.video.Quality;
import androidx.camera.video.QualitySelector;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.QualitySelectorHostApi;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQuality;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQualityData;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Host API implementation for {@link QualitySelector}.
*
* <p>This class may handle instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
public class QualitySelectorHostApiImpl implements QualitySelectorHostApi {
private final InstanceManager instanceManager;
private final QualitySelectorProxy proxy;
/** Proxy for constructor of {@link QualitySelector}. */
@VisibleForTesting
public static class QualitySelectorProxy {
/** Creates an instance of {@link QualitySelector}. */
public @NonNull QualitySelector create(
@NonNull List<VideoQualityData> videoQualityDataList,
@Nullable FallbackStrategy fallbackStrategy) {
// Convert each index of VideoQuality to Quality.
List<Quality> qualityList = new ArrayList<Quality>();
for (VideoQualityData videoQualityData : videoQualityDataList) {
qualityList.add(getQualityFromVideoQuality(videoQualityData.getQuality()));
}
boolean fallbackStrategySpecified = fallbackStrategy != null;
if (qualityList.size() == 0) {
throw new IllegalArgumentException(
"List of at least one Quality must be supplied to create QualitySelector.");
} else if (qualityList.size() == 1) {
Quality quality = qualityList.get(0);
return fallbackStrategySpecified
? QualitySelector.from(quality, fallbackStrategy)
: QualitySelector.from(quality);
}
return fallbackStrategySpecified
? QualitySelector.fromOrderedList(qualityList, fallbackStrategy)
: QualitySelector.fromOrderedList(qualityList);
}
}
/**
* Constructs a {@link QualitySelectorHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public QualitySelectorHostApiImpl(@NonNull InstanceManager instanceManager) {
this(instanceManager, new QualitySelectorProxy());
}
/**
* Constructs a {@link QualitySelectorHostApiImpl}.
*
* @param instanceManager maintains instances stored to communicate with attached Dart objects
* @param proxy proxy for constructor of {@link QualitySelector}
*/
QualitySelectorHostApiImpl(
@NonNull InstanceManager instanceManager, @NonNull QualitySelectorProxy proxy) {
this.instanceManager = instanceManager;
this.proxy = proxy;
}
/**
* Creates a {@link QualitySelector} instance with the quality list and {@link FallbackStrategy}
* with the identifier specified.
*/
@Override
public void create(
@NonNull Long identifier,
@NonNull List<VideoQualityData> videoQualityDataList,
@Nullable Long fallbackStrategyIdentifier) {
instanceManager.addDartCreatedInstance(
proxy.create(
videoQualityDataList,
fallbackStrategyIdentifier == null
? null
: Objects.requireNonNull(instanceManager.getInstance(fallbackStrategyIdentifier))),
identifier);
}
/**
* Retrieves the corresponding resolution from the input quality for the camera represented by the
* {@link CameraInfo} represented by the identifier specified.
*/
@Override
public @NonNull ResolutionInfo getResolution(
@NonNull Long cameraInfoIdentifier, @NonNull VideoQuality quality) {
final Size result =
QualitySelector.getResolution(
Objects.requireNonNull(instanceManager.getInstance(cameraInfoIdentifier)),
getQualityFromVideoQuality(quality));
return new ResolutionInfo.Builder()
.setWidth(Long.valueOf(result.getWidth()))
.setHeight(Long.valueOf(result.getHeight()))
.build();
}
/**
* Converts the specified {@link VideoQuality to a {@link Quality} that is understood
* by CameraX.
*/
public static @NonNull Quality getQualityFromVideoQuality(@NonNull VideoQuality videoQuality) {
switch (videoQuality) {
case SD:
return Quality.SD;
case HD:
return Quality.HD;
case FHD:
return Quality.FHD;
case UHD:
return Quality.UHD;
case LOWEST:
return Quality.LOWEST;
case HIGHEST:
return Quality.HIGHEST;
}
throw new IllegalArgumentException(
"VideoQuality " + videoQuality + " is unhandled by QualitySelectorHostApiImpl.");
}
}
| packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorHostApiImpl.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorHostApiImpl.java",
"repo_id": "packages",
"token_count": 1746
} | 1,112 |
// 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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import androidx.camera.core.CameraControl;
import androidx.camera.core.FocusMeteringAction;
import androidx.camera.core.FocusMeteringResult;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.flutter.plugin.common.BinaryMessenger;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class CameraControlTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public CameraControl cameraControl;
InstanceManager testInstanceManager;
@Before
public void setUp() {
testInstanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
testInstanceManager.stopFinalizationListener();
}
@Test
public void enableTorch_turnsTorchModeOnAndOffAsExpected() {
try (MockedStatic<Futures> mockedFutures = Mockito.mockStatic(Futures.class)) {
final CameraControlHostApiImpl cameraControlHostApiImpl =
new CameraControlHostApiImpl(
mockBinaryMessenger, testInstanceManager, mock(Context.class));
final Long cameraControlIdentifier = 88L;
final boolean enableTorch = true;
@SuppressWarnings("unchecked")
final ListenableFuture<Void> enableTorchFuture = mock(ListenableFuture.class);
testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier);
when(cameraControl.enableTorch(true)).thenReturn(enableTorchFuture);
@SuppressWarnings("unchecked")
final ArgumentCaptor<FutureCallback<Void>> futureCallbackCaptor =
ArgumentCaptor.forClass(FutureCallback.class);
// Test successful behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Void> successfulMockResult =
mock(GeneratedCameraXLibrary.Result.class);
cameraControlHostApiImpl.enableTorch(
cameraControlIdentifier, enableTorch, successfulMockResult);
mockedFutures.verify(
() -> Futures.addCallback(eq(enableTorchFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<Void> successfulEnableTorchCallback = futureCallbackCaptor.getValue();
successfulEnableTorchCallback.onSuccess(mock(Void.class));
verify(successfulMockResult).success(null);
// Test failed behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Void> failedMockResult =
mock(GeneratedCameraXLibrary.Result.class);
final Throwable testThrowable = new Throwable();
cameraControlHostApiImpl.enableTorch(cameraControlIdentifier, enableTorch, failedMockResult);
mockedFutures.verify(
() -> Futures.addCallback(eq(enableTorchFuture), futureCallbackCaptor.capture(), any()));
FutureCallback<Void> failedEnableTorchCallback = futureCallbackCaptor.getValue();
failedEnableTorchCallback.onFailure(testThrowable);
verify(failedMockResult).error(testThrowable);
}
}
@Test
public void setZoomRatio_setsZoomAsExpected() {
try (MockedStatic<Futures> mockedFutures = Mockito.mockStatic(Futures.class)) {
final CameraControlHostApiImpl cameraControlHostApiImpl =
new CameraControlHostApiImpl(
mockBinaryMessenger, testInstanceManager, mock(Context.class));
final Long cameraControlIdentifier = 33L;
final Double zoomRatio = 0.2D;
@SuppressWarnings("unchecked")
final ListenableFuture<Void> setZoomRatioFuture = mock(ListenableFuture.class);
testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier);
when(cameraControl.setZoomRatio(zoomRatio.floatValue())).thenReturn(setZoomRatioFuture);
@SuppressWarnings("unchecked")
final ArgumentCaptor<FutureCallback<Void>> futureCallbackCaptor =
ArgumentCaptor.forClass(FutureCallback.class);
// Test successful behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Void> successfulMockResult =
mock(GeneratedCameraXLibrary.Result.class);
cameraControlHostApiImpl.setZoomRatio(
cameraControlIdentifier, zoomRatio, successfulMockResult);
mockedFutures.verify(
() -> Futures.addCallback(eq(setZoomRatioFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<Void> successfulSetZoomRatioCallback = futureCallbackCaptor.getValue();
successfulSetZoomRatioCallback.onSuccess(mock(Void.class));
verify(successfulMockResult).success(null);
// Test failed behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Void> failedMockResult =
mock(GeneratedCameraXLibrary.Result.class);
final Throwable testThrowable = new Throwable();
cameraControlHostApiImpl.setZoomRatio(cameraControlIdentifier, zoomRatio, failedMockResult);
mockedFutures.verify(
() -> Futures.addCallback(eq(setZoomRatioFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<Void> failedSetZoomRatioCallback = futureCallbackCaptor.getValue();
failedSetZoomRatioCallback.onFailure(testThrowable);
verify(failedMockResult).error(testThrowable);
// Test response to canceled operation.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Void> canceledOpResult =
mock(GeneratedCameraXLibrary.Result.class);
final CameraControl.OperationCanceledException canceledOpThrowable =
mock(CameraControl.OperationCanceledException.class);
cameraControlHostApiImpl.setZoomRatio(cameraControlIdentifier, zoomRatio, canceledOpResult);
mockedFutures.verify(
() -> Futures.addCallback(eq(setZoomRatioFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<Void> canceledOpCallback = futureCallbackCaptor.getValue();
canceledOpCallback.onFailure(canceledOpThrowable);
verify(canceledOpResult).success(null);
}
}
@Test
public void startFocusAndMetering_startsFocusAndMeteringAsExpected() {
try (MockedStatic<Futures> mockedFutures = Mockito.mockStatic(Futures.class)) {
final CameraControlHostApiImpl cameraControlHostApiImpl =
new CameraControlHostApiImpl(
mockBinaryMessenger, testInstanceManager, mock(Context.class));
final Long cameraControlIdentifier = 90L;
final FocusMeteringAction mockAction = mock(FocusMeteringAction.class);
final Long mockActionId = 44L;
final FocusMeteringResult mockResult = mock(FocusMeteringResult.class);
final Long mockResultId = 33L;
@SuppressWarnings("unchecked")
final ListenableFuture<FocusMeteringResult> startFocusAndMeteringFuture =
mock(ListenableFuture.class);
testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier);
testInstanceManager.addDartCreatedInstance(mockResult, mockResultId);
testInstanceManager.addDartCreatedInstance(mockAction, mockActionId);
when(cameraControl.startFocusAndMetering(mockAction)).thenReturn(startFocusAndMeteringFuture);
@SuppressWarnings("unchecked")
final ArgumentCaptor<FutureCallback<FocusMeteringResult>> futureCallbackCaptor =
ArgumentCaptor.forClass(FutureCallback.class);
// Test successful behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Long> successfulMockResult =
mock(GeneratedCameraXLibrary.Result.class);
cameraControlHostApiImpl.startFocusAndMetering(
cameraControlIdentifier, mockActionId, successfulMockResult);
mockedFutures.verify(
() ->
Futures.addCallback(
eq(startFocusAndMeteringFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<FocusMeteringResult> successfulCallback = futureCallbackCaptor.getValue();
successfulCallback.onSuccess(mockResult);
verify(successfulMockResult).success(mockResultId);
// Test failed behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Long> failedMockResult =
mock(GeneratedCameraXLibrary.Result.class);
final Throwable testThrowable = new Throwable();
cameraControlHostApiImpl.startFocusAndMetering(
cameraControlIdentifier, mockActionId, failedMockResult);
mockedFutures.verify(
() ->
Futures.addCallback(
eq(startFocusAndMeteringFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<FocusMeteringResult> failedCallback = futureCallbackCaptor.getValue();
failedCallback.onFailure(testThrowable);
verify(failedMockResult).error(testThrowable);
// Test response to canceled operation.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Long> canceledOpResult =
mock(GeneratedCameraXLibrary.Result.class);
final CameraControl.OperationCanceledException canceledOpThrowable =
mock(CameraControl.OperationCanceledException.class);
cameraControlHostApiImpl.startFocusAndMetering(
cameraControlIdentifier, mockActionId, canceledOpResult);
mockedFutures.verify(
() ->
Futures.addCallback(
eq(startFocusAndMeteringFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<FocusMeteringResult> canceledOpCallback = futureCallbackCaptor.getValue();
canceledOpCallback.onFailure(canceledOpThrowable);
verify(canceledOpResult).success(null);
}
}
@Test
public void cancelFocusAndMetering_cancelsFocusAndMeteringAsExpected() {
try (MockedStatic<Futures> mockedFutures = Mockito.mockStatic(Futures.class)) {
final CameraControlHostApiImpl cameraControlHostApiImpl =
new CameraControlHostApiImpl(
mockBinaryMessenger, testInstanceManager, mock(Context.class));
final Long cameraControlIdentifier = 8L;
@SuppressWarnings("unchecked")
final ListenableFuture<Void> cancelFocusAndMeteringFuture = mock(ListenableFuture.class);
testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier);
when(cameraControl.cancelFocusAndMetering()).thenReturn(cancelFocusAndMeteringFuture);
@SuppressWarnings("unchecked")
final ArgumentCaptor<FutureCallback<Void>> futureCallbackCaptor =
ArgumentCaptor.forClass(FutureCallback.class);
// Test successful behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Void> successfulMockResult =
mock(GeneratedCameraXLibrary.Result.class);
cameraControlHostApiImpl.cancelFocusAndMetering(
cameraControlIdentifier, successfulMockResult);
mockedFutures.verify(
() ->
Futures.addCallback(
eq(cancelFocusAndMeteringFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<Void> successfulCallback = futureCallbackCaptor.getValue();
successfulCallback.onSuccess(mock(Void.class));
verify(successfulMockResult).success(null);
// Test failed behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Void> failedMockResult =
mock(GeneratedCameraXLibrary.Result.class);
final Throwable testThrowable = new Throwable();
cameraControlHostApiImpl.cancelFocusAndMetering(cameraControlIdentifier, failedMockResult);
mockedFutures.verify(
() ->
Futures.addCallback(
eq(cancelFocusAndMeteringFuture), futureCallbackCaptor.capture(), any()));
FutureCallback<Void> failedCallback = futureCallbackCaptor.getValue();
failedCallback.onFailure(testThrowable);
verify(failedMockResult).error(testThrowable);
}
}
@Test
public void setExposureCompensationIndex_setsExposureCompensationIndexAsExpected() {
try (MockedStatic<Futures> mockedFutures = Mockito.mockStatic(Futures.class)) {
final CameraControlHostApiImpl cameraControlHostApiImpl =
new CameraControlHostApiImpl(
mockBinaryMessenger, testInstanceManager, mock(Context.class));
final Long cameraControlIdentifier = 53L;
final Long index = 2L;
@SuppressWarnings("unchecked")
final ListenableFuture<Integer> setExposureCompensationIndexFuture =
mock(ListenableFuture.class);
testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier);
when(cameraControl.setExposureCompensationIndex(index.intValue()))
.thenReturn(setExposureCompensationIndexFuture);
@SuppressWarnings("unchecked")
final ArgumentCaptor<FutureCallback<Integer>> futureCallbackCaptor =
ArgumentCaptor.forClass(FutureCallback.class);
// Test successful behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Long> successfulMockResult =
mock(GeneratedCameraXLibrary.Result.class);
cameraControlHostApiImpl.setExposureCompensationIndex(
cameraControlIdentifier, index, successfulMockResult);
mockedFutures.verify(
() ->
Futures.addCallback(
eq(setExposureCompensationIndexFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<Integer> successfulCallback = futureCallbackCaptor.getValue();
final Integer fakeResult = 4;
successfulCallback.onSuccess(fakeResult);
verify(successfulMockResult).success(fakeResult.longValue());
// Test failed behavior.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Long> failedMockResult =
mock(GeneratedCameraXLibrary.Result.class);
final Throwable testThrowable = new Throwable();
cameraControlHostApiImpl.setExposureCompensationIndex(
cameraControlIdentifier, index, failedMockResult);
mockedFutures.verify(
() ->
Futures.addCallback(
eq(setExposureCompensationIndexFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<Integer> failedCallback = futureCallbackCaptor.getValue();
failedCallback.onFailure(testThrowable);
verify(failedMockResult).error(testThrowable);
// Test response to canceled operation.
@SuppressWarnings("unchecked")
final GeneratedCameraXLibrary.Result<Long> canceledOpResult =
mock(GeneratedCameraXLibrary.Result.class);
final CameraControl.OperationCanceledException canceledOpThrowable =
mock(CameraControl.OperationCanceledException.class);
cameraControlHostApiImpl.setExposureCompensationIndex(
cameraControlIdentifier, index, canceledOpResult);
mockedFutures.verify(
() ->
Futures.addCallback(
eq(setExposureCompensationIndexFuture), futureCallbackCaptor.capture(), any()));
mockedFutures.clearInvocations();
FutureCallback<Integer> canceledOpCallback = futureCallbackCaptor.getValue();
canceledOpCallback.onFailure(canceledOpThrowable);
verify(canceledOpResult).success(null);
}
}
@Test
public void flutterApiCreate_makesCallToCreateInstanceOnDartSide() {
final CameraControlFlutterApiImpl spyFlutterApi =
spy(new CameraControlFlutterApiImpl(mockBinaryMessenger, testInstanceManager));
spyFlutterApi.create(cameraControl, reply -> {});
final long cameraControlIdentifier =
Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(cameraControl));
verify(spyFlutterApi).create(eq(cameraControlIdentifier), any());
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraControlTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraControlTest.java",
"repo_id": "packages",
"token_count": 6008
} | 1,113 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import androidx.camera.core.ImageProxy;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageProxyFlutterApi;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.annotation.Config;
public class ImageProxyTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public ImageProxy mockImageProxy;
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public ImageProxyFlutterApi mockFlutterApi;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Config(sdk = 21)
@Test
public void getPlanes_returnsExpectedPlanesFromExpectedImageProxyInstance() {
final ImageProxyHostApiImpl hostApi =
new ImageProxyHostApiImpl(mockBinaryMessenger, instanceManager);
final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class);
final PlaneProxyFlutterApiImpl mockPlaneProxyFlutterApiImpl =
mock(PlaneProxyFlutterApiImpl.class);
final long instanceIdentifier = 24;
final long mockPlaneProxyIdentifier = 45;
final ImageProxy.PlaneProxy mockPlaneProxy = mock(ImageProxy.PlaneProxy.class);
final ImageProxy.PlaneProxy[] returnValue = new ImageProxy.PlaneProxy[] {mockPlaneProxy};
final ByteBuffer mockByteBuffer = mock(ByteBuffer.class);
final int bufferRemaining = 23;
final byte[] buffer = new byte[bufferRemaining];
final int pixelStride = 2;
final int rowStride = 65;
instanceManager.addDartCreatedInstance(mockImageProxy, instanceIdentifier);
hostApi.cameraXProxy = mockCameraXProxy;
hostApi.planeProxyFlutterApiImpl = mockPlaneProxyFlutterApiImpl;
when(mockImageProxy.getPlanes()).thenReturn(returnValue);
when(mockPlaneProxy.getBuffer()).thenReturn(mockByteBuffer);
when(mockByteBuffer.remaining()).thenReturn(bufferRemaining);
when(mockCameraXProxy.getBytesFromBuffer(bufferRemaining)).thenReturn(buffer);
when(mockPlaneProxy.getPixelStride()).thenReturn(pixelStride);
when(mockPlaneProxy.getRowStride()).thenReturn(rowStride);
final List<Long> result = hostApi.getPlanes(instanceIdentifier);
verify(mockImageProxy).getPlanes();
verify(mockPlaneProxyFlutterApiImpl)
.create(
eq(mockPlaneProxy),
eq(buffer),
eq(Long.valueOf(pixelStride)),
eq(Long.valueOf(rowStride)),
any());
assertEquals(result.size(), 1);
}
@Test
public void close_makesCallToCloseExpectedImageProxyInstance() {
final ImageProxyHostApiImpl hostApi =
new ImageProxyHostApiImpl(mockBinaryMessenger, instanceManager);
final long instanceIdentifier = 9;
instanceManager.addDartCreatedInstance(mockImageProxy, instanceIdentifier);
hostApi.close(instanceIdentifier);
verify(mockImageProxy).close();
}
@Test
public void flutterApiCreate_makesCallToDartCreate() {
final ImageProxyFlutterApiImpl flutterApi =
new ImageProxyFlutterApiImpl(mockBinaryMessenger, instanceManager);
final long format = 3;
final long height = 2;
final long width = 1;
flutterApi.setApi(mockFlutterApi);
flutterApi.create(mockImageProxy, format, height, width, reply -> {});
final long instanceIdentifier =
Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockImageProxy));
verify(mockFlutterApi).create(eq(instanceIdentifier), eq(format), eq(height), eq(width), any());
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageProxyTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageProxyTest.java",
"repo_id": "packages",
"token_count": 1496
} | 1,114 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry;
import io.flutter.plugins.camerax.CameraPermissionsManager.ResultCallback;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraPermissionsErrorData;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Result;
import java.io.File;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class SystemServicesTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public InstanceManager mockInstanceManager;
@Mock public Context mockContext;
@Test
public void requestCameraPermissionsTest() {
final SystemServicesHostApiImpl systemServicesHostApi =
new SystemServicesHostApiImpl(mockBinaryMessenger, mockInstanceManager, mockContext);
final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class);
final CameraPermissionsManager mockCameraPermissionsManager =
mock(CameraPermissionsManager.class);
final Activity mockActivity = mock(Activity.class);
final PermissionsRegistry mockPermissionsRegistry = mock(PermissionsRegistry.class);
@SuppressWarnings("unchecked")
final Result<CameraPermissionsErrorData> mockResult = mock(Result.class);
final Boolean enableAudio = false;
systemServicesHostApi.cameraXProxy = mockCameraXProxy;
systemServicesHostApi.setActivity(mockActivity);
systemServicesHostApi.setPermissionsRegistry(mockPermissionsRegistry);
when(mockCameraXProxy.createCameraPermissionsManager())
.thenReturn(mockCameraPermissionsManager);
final ArgumentCaptor<ResultCallback> resultCallbackCaptor =
ArgumentCaptor.forClass(ResultCallback.class);
systemServicesHostApi.requestCameraPermissions(enableAudio, mockResult);
// Test camera permissions are requested.
verify(mockCameraPermissionsManager)
.requestPermissions(
eq(mockActivity),
eq(mockPermissionsRegistry),
eq(enableAudio),
resultCallbackCaptor.capture());
ResultCallback resultCallback = resultCallbackCaptor.getValue();
// Test no error data is sent upon permissions request success.
resultCallback.onResult(null, null);
verify(mockResult).success(null);
// Test expected error data is sent upon permissions request failure.
final String testErrorCode = "TestErrorCode";
final String testErrorDescription = "Test error description.";
final ArgumentCaptor<CameraPermissionsErrorData> cameraPermissionsErrorDataCaptor =
ArgumentCaptor.forClass(CameraPermissionsErrorData.class);
resultCallback.onResult(testErrorCode, testErrorDescription);
verify(mockResult, times(2)).success(cameraPermissionsErrorDataCaptor.capture());
CameraPermissionsErrorData cameraPermissionsErrorData =
cameraPermissionsErrorDataCaptor.getValue();
assertEquals(cameraPermissionsErrorData.getErrorCode(), testErrorCode);
assertEquals(cameraPermissionsErrorData.getDescription(), testErrorDescription);
}
@Test
public void getTempFilePath_returnsCorrectPath() {
final SystemServicesHostApiImpl systemServicesHostApi =
new SystemServicesHostApiImpl(mockBinaryMessenger, mockInstanceManager, mockContext);
final String prefix = "prefix";
final String suffix = ".suffix";
final MockedStatic<File> mockedStaticFile = mockStatic(File.class);
final File mockOutputDir = mock(File.class);
final File mockFile = mock(File.class);
when(mockContext.getCacheDir()).thenReturn(mockOutputDir);
mockedStaticFile
.when(() -> File.createTempFile(prefix, suffix, mockOutputDir))
.thenReturn(mockFile);
when(mockFile.toString()).thenReturn(prefix + suffix);
assertEquals(systemServicesHostApi.getTempFilePath(prefix, suffix), prefix + suffix);
mockedStaticFile.close();
}
@Test
public void getTempFilePath_throwsRuntimeExceptionOnIOException() {
final SystemServicesHostApiImpl systemServicesHostApi =
new SystemServicesHostApiImpl(mockBinaryMessenger, mockInstanceManager, mockContext);
final String prefix = "prefix";
final String suffix = ".suffix";
final MockedStatic<File> mockedStaticFile = mockStatic(File.class);
final File mockOutputDir = mock(File.class);
when(mockContext.getCacheDir()).thenReturn(mockOutputDir);
mockedStaticFile
.when(() -> File.createTempFile(prefix, suffix, mockOutputDir))
.thenThrow(IOException.class);
assertThrows(
GeneratedCameraXLibrary.FlutterError.class,
() -> systemServicesHostApi.getTempFilePath(prefix, suffix));
mockedStaticFile.close();
}
}
| packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/SystemServicesTest.java/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/SystemServicesTest.java",
"repo_id": "packages",
"token_count": 1768
} | 1,115 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:meta/meta.dart' show immutable;
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// A bundle of Camera2 capture request options.
///
/// See https://developer.android.com/reference/androidx/camera/camera2/interop/CaptureRequestOptions.
@immutable
class CaptureRequestOptions extends JavaObject {
/// Creates a [CaptureRequestOptions].
///
/// Any value specified as null for a particular
/// [CaptureRequestKeySupportedType] key will clear the pre-existing value.
CaptureRequestOptions({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
required this.requestedOptions,
}) : super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = _CaptureRequestOptionsHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
_api.createFromInstances(this, requestedOptions);
}
/// Constructs a [CaptureRequestOptions] that is not automatically attached to a
/// native object.
CaptureRequestOptions.detached({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
required this.requestedOptions,
}) : super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = _CaptureRequestOptionsHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
}
late final _CaptureRequestOptionsHostApiImpl _api;
/// Capture request options this instance will be used to request.
final List<(CaptureRequestKeySupportedType type, Object? value)>
requestedOptions;
/// Error message indicating a [CaptureRequestOption] was constructed with a
/// capture request key currently unsupported by the wrapping of this class.
static String getUnsupportedCaptureRequestKeyTypeErrorMessage(
CaptureRequestKeySupportedType captureRequestKeyType) =>
'The type of capture request key passed to this method ($captureRequestKeyType) is current unspported; please see CaptureRequestKeySupportedType in pigeons/camerax_library.dart if you wish to support a new type.';
}
/// Host API implementation of [CaptureRequestOptions].
class _CaptureRequestOptionsHostApiImpl extends CaptureRequestOptionsHostApi {
/// Constructs a [_CaptureRequestOptionsHostApiImpl].
///
/// If [binaryMessenger] is null, the default [BinaryMessenger] will be used,
/// which routes to the host platform.
///
/// An [instanceManager] is typically passed when a copy of an instance
/// contained by an [InstanceManager] is being created. If left null, it
/// will default to the global instance defined in [JavaObject].
_CaptureRequestOptionsHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default [BinaryMessenger] will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
/// Creates a [CaptureRequestOptions] instance based on the specified
/// capture request key and value pairs.
Future<void> createFromInstances(
CaptureRequestOptions instance,
List<(CaptureRequestKeySupportedType type, Object? value)> options,
) {
if (options.isEmpty) {
throw ArgumentError(
'At least one capture request option must be specified.');
}
final Map<int, Object?> captureRequestOptions = <int, Object?>{};
// Validate values have type that matches paired key that is supported by
// this plugin (CaptureRequestKeySupportedType).
for (final (CaptureRequestKeySupportedType key, Object? value) option
in options) {
final CaptureRequestKeySupportedType key = option.$1;
final Object? value = option.$2;
if (value == null) {
captureRequestOptions[key.index] = null;
continue;
}
final Type valueRuntimeType = value.runtimeType;
switch (key) {
case CaptureRequestKeySupportedType.controlAeLock:
if (valueRuntimeType != bool) {
throw ArgumentError(
'A controlAeLock value must be specified as a bool, but a $valueRuntimeType was specified.');
}
// This ignore statement is safe beause this error will be useful when
// a new CaptureRequestKeySupportedType is being added, but the logic in
// this method has not yet been updated.
// ignore: no_default_cases
default:
throw ArgumentError(CaptureRequestOptions
.getUnsupportedCaptureRequestKeyTypeErrorMessage(key));
}
captureRequestOptions[key.index] = value;
}
return create(
instanceManager.addDartCreatedInstance(
instance,
onCopy: (CaptureRequestOptions original) =>
CaptureRequestOptions.detached(
requestedOptions: original.requestedOptions,
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
),
captureRequestOptions,
);
}
}
| packages/packages/camera/camera_android_camerax/lib/src/capture_request_options.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/capture_request_options.dart",
"repo_id": "packages",
"token_count": 1720
} | 1,116 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart' show BinaryMessenger;
import 'package:meta/meta.dart' show immutable;
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
import 'resolution_selector.dart';
import 'use_case.dart';
/// Use case that provides a camera preview stream for display.
///
/// See https://developer.android.com/reference/androidx/camera/core/Preview.
@immutable
class Preview extends UseCase {
/// Creates a [Preview].
Preview(
{BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
this.initialTargetRotation,
this.resolutionSelector})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = PreviewHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
_api.createFromInstance(this, initialTargetRotation, resolutionSelector);
}
/// Constructs a [Preview] that is not automatically attached to a native object.
Preview.detached(
{BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
this.initialTargetRotation,
this.resolutionSelector})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = PreviewHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
}
late final PreviewHostApiImpl _api;
/// Target rotation of the camera used for the preview stream.
///
/// Should be specified in terms of one of the [Surface]
/// rotation constants that represents the counter-clockwise degrees of
/// rotation relative to [DeviceOrientation.portraitUp].
///
// TODO(camsim99): Remove this parameter. https://github.com/flutter/flutter/issues/140664
final int? initialTargetRotation;
/// Target resolution of the camera preview stream.
///
/// If not set, this [UseCase] will default to the behavior described in:
/// https://developer.android.com/reference/androidx/camera/core/Preview.Builder#setResolutionSelector(androidx.camera.core.resolutionselector.ResolutionSelector).
final ResolutionSelector? resolutionSelector;
/// Dynamically sets the target rotation of this instance.
///
/// [rotation] should be specified in terms of one of the [Surface]
/// rotation constants that represents the counter-clockwise degrees of
/// rotation relative to [DeviceOrientation.portraitUp].
Future<void> setTargetRotation(int rotation) =>
_api.setTargetRotationFromInstances(this, rotation);
/// Sets the surface provider for the preview stream.
///
/// Returns the ID of the FlutterSurfaceTextureEntry used on the native end
/// used to display the preview stream on a [Texture] of the same ID.
Future<int> setSurfaceProvider() {
return _api.setSurfaceProviderFromInstance(this);
}
/// Releases Flutter surface texture used to provide a surface for the preview
/// stream.
void releaseFlutterSurfaceTexture() {
_api.releaseFlutterSurfaceTextureFromInstance();
}
/// Retrieves the selected resolution information of this [Preview].
Future<ResolutionInfo> getResolutionInfo() {
return _api.getResolutionInfoFromInstance(this);
}
}
/// Host API implementation of [Preview].
class PreviewHostApiImpl extends PreviewHostApi {
/// Constructs an [PreviewHostApiImpl].
///
/// If [binaryMessenger] is null, the default [BinaryMessenger] will be used,
/// which routes to the host platform.
///
/// An [instanceManager] is typically passed when a copy of an instance
/// contained by an [InstanceManager] is being created. If left null, it
/// will default to the global instance defined in [JavaObject].
PreviewHostApiImpl({this.binaryMessenger, InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Receives binary data across the Flutter platform barrier.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Creates a [Preview] with the target rotation and target resolution if
/// specified.
void createFromInstance(Preview instance, int? targetRotation,
ResolutionSelector? resolutionSelector) {
final int identifier = instanceManager.addDartCreatedInstance(instance,
onCopy: (Preview original) {
return Preview.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
initialTargetRotation: original.initialTargetRotation,
resolutionSelector: original.resolutionSelector);
});
create(
identifier,
targetRotation,
resolutionSelector == null
? null
: instanceManager.getIdentifier(resolutionSelector));
}
/// Dynamically sets the target rotation of [instance] to [rotation].
Future<void> setTargetRotationFromInstances(Preview instance, int rotation) {
return setTargetRotation(
instanceManager.getIdentifier(instance)!, rotation);
}
/// Sets the surface provider of the specified [Preview] instance and returns
/// the ID corresponding to the surface it will provide.
Future<int> setSurfaceProviderFromInstance(Preview instance) async {
final int? identifier = instanceManager.getIdentifier(instance);
final int surfaceTextureEntryId = await setSurfaceProvider(identifier!);
return surfaceTextureEntryId;
}
/// Releases Flutter surface texture used to provide a surface for the preview
/// stream if a surface provider was set for a [Preview] instance.
void releaseFlutterSurfaceTextureFromInstance() {
releaseFlutterSurfaceTexture();
}
/// Gets the resolution information of the specified [Preview] instance.
Future<ResolutionInfo> getResolutionInfoFromInstance(Preview instance) async {
final int? identifier = instanceManager.getIdentifier(instance);
final ResolutionInfo resolutionInfo = await getResolutionInfo(identifier!);
return resolutionInfo;
}
}
| packages/packages/camera/camera_android_camerax/lib/src/preview.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/lib/src/preview.dart",
"repo_id": "packages",
"token_count": 1830
} | 1,117 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' show Point;
import 'package:async/async.dart';
import 'package:camera_android_camerax/camera_android_camerax.dart';
import 'package:camera_android_camerax/src/analyzer.dart';
import 'package:camera_android_camerax/src/camera.dart';
import 'package:camera_android_camerax/src/camera2_camera_control.dart';
import 'package:camera_android_camerax/src/camera_control.dart';
import 'package:camera_android_camerax/src/camera_info.dart';
import 'package:camera_android_camerax/src/camera_selector.dart';
import 'package:camera_android_camerax/src/camera_state.dart';
import 'package:camera_android_camerax/src/camera_state_error.dart';
import 'package:camera_android_camerax/src/camerax_library.g.dart';
import 'package:camera_android_camerax/src/camerax_proxy.dart';
import 'package:camera_android_camerax/src/capture_request_options.dart';
import 'package:camera_android_camerax/src/device_orientation_manager.dart';
import 'package:camera_android_camerax/src/exposure_state.dart';
import 'package:camera_android_camerax/src/fallback_strategy.dart';
import 'package:camera_android_camerax/src/focus_metering_action.dart';
import 'package:camera_android_camerax/src/focus_metering_result.dart';
import 'package:camera_android_camerax/src/image_analysis.dart';
import 'package:camera_android_camerax/src/image_capture.dart';
import 'package:camera_android_camerax/src/image_proxy.dart';
import 'package:camera_android_camerax/src/live_data.dart';
import 'package:camera_android_camerax/src/metering_point.dart';
import 'package:camera_android_camerax/src/observer.dart';
import 'package:camera_android_camerax/src/pending_recording.dart';
import 'package:camera_android_camerax/src/plane_proxy.dart';
import 'package:camera_android_camerax/src/preview.dart';
import 'package:camera_android_camerax/src/process_camera_provider.dart';
import 'package:camera_android_camerax/src/quality_selector.dart';
import 'package:camera_android_camerax/src/recorder.dart';
import 'package:camera_android_camerax/src/recording.dart';
import 'package:camera_android_camerax/src/resolution_selector.dart';
import 'package:camera_android_camerax/src/resolution_strategy.dart';
import 'package:camera_android_camerax/src/surface.dart';
import 'package:camera_android_camerax/src/system_services.dart';
import 'package:camera_android_camerax/src/use_case.dart';
import 'package:camera_android_camerax/src/video_capture.dart';
import 'package:camera_android_camerax/src/zoom_state.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/services.dart'
show DeviceOrientation, PlatformException, Uint8List;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'android_camera_camerax_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateNiceMocks(<MockSpec<Object>>[
MockSpec<Analyzer>(),
MockSpec<Camera>(),
MockSpec<CameraInfo>(),
MockSpec<CameraControl>(),
MockSpec<Camera2CameraControl>(),
MockSpec<CameraImageData>(),
MockSpec<CameraSelector>(),
MockSpec<ExposureState>(),
MockSpec<FallbackStrategy>(),
MockSpec<FocusMeteringResult>(),
MockSpec<ImageAnalysis>(),
MockSpec<ImageCapture>(),
MockSpec<ImageProxy>(),
MockSpec<Observer<CameraState>>(),
MockSpec<PendingRecording>(),
MockSpec<PlaneProxy>(),
MockSpec<Preview>(),
MockSpec<ProcessCameraProvider>(),
MockSpec<QualitySelector>(),
MockSpec<Recorder>(),
MockSpec<ResolutionSelector>(),
MockSpec<ResolutionStrategy>(),
MockSpec<Recording>(),
MockSpec<VideoCapture>(),
MockSpec<BuildContext>(),
MockSpec<TestInstanceManagerHostApi>(),
MockSpec<TestSystemServicesHostApi>(),
MockSpec<ZoomState>(),
])
@GenerateMocks(<Type>[], customMocks: <MockSpec<Object>>[
MockSpec<LiveData<CameraState>>(as: #MockLiveCameraState),
MockSpec<LiveData<ZoomState>>(as: #MockLiveZoomState),
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
/// Helper method for testing sending/receiving CameraErrorEvents.
Future<bool> testCameraClosingObserver(AndroidCameraCameraX camera,
int cameraId, Observer<dynamic> observer) async {
final CameraStateError testCameraStateError =
CameraStateError.detached(code: 0);
final Stream<CameraClosingEvent> cameraClosingEventStream =
camera.onCameraClosing(cameraId);
final StreamQueue<CameraClosingEvent> cameraClosingStreamQueue =
StreamQueue<CameraClosingEvent>(cameraClosingEventStream);
final Stream<CameraErrorEvent> cameraErrorEventStream =
camera.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> cameraErrorStreamQueue =
StreamQueue<CameraErrorEvent>(cameraErrorEventStream);
observer.onChanged(CameraState.detached(
type: CameraStateType.closing, error: testCameraStateError));
final bool cameraClosingEventSent =
await cameraClosingStreamQueue.next == CameraClosingEvent(cameraId);
final bool cameraErrorSent = await cameraErrorStreamQueue.next ==
CameraErrorEvent(cameraId, testCameraStateError.getDescription());
await cameraClosingStreamQueue.cancel();
await cameraErrorStreamQueue.cancel();
return cameraClosingEventSent && cameraErrorSent;
}
/// CameraXProxy for testing exposure and focus related controls.
///
/// Modifies the creation of [MeteringPoint]s and [FocusMeteringAction]s to
/// return objects detached from a native object.
CameraXProxy getProxyForExposureAndFocus() => CameraXProxy(
createMeteringPoint:
(double x, double y, double? size, CameraInfo cameraInfo) =>
MeteringPoint.detached(
x: x, y: y, size: size, cameraInfo: cameraInfo),
createFocusMeteringAction:
(List<(MeteringPoint, int?)> meteringPointInfos,
bool? disableAutoCancel) =>
FocusMeteringAction.detached(
meteringPointInfos: meteringPointInfos,
disableAutoCancel: disableAutoCancel),
);
/// CameraXProxy for testing setting focus and exposure points.
///
/// Modifies the retrieval of a [Camera2CameraControl] instance to depend on
/// interaction with expected [cameraControl] instance and modifies creation
/// of [CaptureRequestOptions] to return objects detached from a native object.
CameraXProxy getProxyForSettingFocusandExposurePoints(
CameraControl cameraControlForComparison,
Camera2CameraControl camera2cameraControl) {
final CameraXProxy proxy = getProxyForExposureAndFocus();
proxy.getCamera2CameraControl = (CameraControl cameraControl) =>
cameraControl == cameraControlForComparison
? camera2cameraControl
: Camera2CameraControl.detached(cameraControl: cameraControl);
proxy.createCaptureRequestOptions =
(List<(CaptureRequestKeySupportedType, Object?)> options) =>
CaptureRequestOptions.detached(requestedOptions: options);
return proxy;
}
test('Should fetch CameraDescription instances for available cameras',
() async {
// Arrange
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final List<dynamic> returnData = <dynamic>[
<String, dynamic>{
'name': 'Camera 0',
'lensFacing': 'back',
'sensorOrientation': 0
},
<String, dynamic>{
'name': 'Camera 1',
'lensFacing': 'front',
'sensorOrientation': 90
}
];
// Create mocks to use
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockCameraSelector mockFrontCameraSelector = MockCameraSelector();
final MockCameraSelector mockBackCameraSelector = MockCameraSelector();
final MockCameraInfo mockFrontCameraInfo = MockCameraInfo();
final MockCameraInfo mockBackCameraInfo = MockCameraInfo();
// Tell plugin to create mock CameraSelectors for testing.
camera.proxy = CameraXProxy(
getProcessCameraProvider: () =>
Future<ProcessCameraProvider>.value(mockProcessCameraProvider),
createCameraSelector: (int cameraSelectorLensDirection) {
switch (cameraSelectorLensDirection) {
case CameraSelector.lensFacingFront:
return mockFrontCameraSelector;
case CameraSelector.lensFacingBack:
default:
return mockBackCameraSelector;
}
},
);
// Mock calls to native platform
when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer(
(_) async => <MockCameraInfo>[mockBackCameraInfo, mockFrontCameraInfo]);
when(mockBackCameraSelector.filter(<MockCameraInfo>[mockFrontCameraInfo]))
.thenAnswer((_) async => <MockCameraInfo>[]);
when(mockBackCameraSelector.filter(<MockCameraInfo>[mockBackCameraInfo]))
.thenAnswer((_) async => <MockCameraInfo>[mockBackCameraInfo]);
when(mockFrontCameraSelector.filter(<MockCameraInfo>[mockBackCameraInfo]))
.thenAnswer((_) async => <MockCameraInfo>[]);
when(mockFrontCameraSelector.filter(<MockCameraInfo>[mockFrontCameraInfo]))
.thenAnswer((_) async => <MockCameraInfo>[mockFrontCameraInfo]);
when(mockBackCameraInfo.getSensorRotationDegrees())
.thenAnswer((_) async => 0);
when(mockFrontCameraInfo.getSensorRotationDegrees())
.thenAnswer((_) async => 90);
final List<CameraDescription> cameraDescriptions =
await camera.availableCameras();
expect(cameraDescriptions.length, returnData.length);
for (int i = 0; i < returnData.length; i++) {
final Map<String, Object?> typedData =
(returnData[i] as Map<dynamic, dynamic>).cast<String, Object?>();
final CameraDescription cameraDescription = CameraDescription(
name: typedData['name']! as String,
lensDirection: (typedData['lensFacing']! as String) == 'front'
? CameraLensDirection.front
: CameraLensDirection.back,
sensorOrientation: typedData['sensorOrientation']! as int,
);
expect(cameraDescriptions[i], cameraDescription);
}
});
test(
'createCamera requests permissions, starts listening for device orientation changes, updates camera state observers, and returns flutter surface texture ID',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const CameraLensDirection testLensDirection = CameraLensDirection.back;
const int testSensorOrientation = 90;
const CameraDescription testCameraDescription = CameraDescription(
name: 'cameraName',
lensDirection: testLensDirection,
sensorOrientation: testSensorOrientation);
const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh;
const bool enableAudio = true;
const int testSurfaceTextureId = 6;
// Mock/Detached objects for (typically attached) objects created by
// createCamera.
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockPreview mockPreview = MockPreview();
final MockCameraSelector mockBackCameraSelector = MockCameraSelector();
final MockImageCapture mockImageCapture = MockImageCapture();
final MockImageAnalysis mockImageAnalysis = MockImageAnalysis();
final MockRecorder mockRecorder = MockRecorder();
final MockVideoCapture mockVideoCapture = MockVideoCapture();
final MockCamera mockCamera = MockCamera();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final MockLiveCameraState mockLiveCameraState = MockLiveCameraState();
bool cameraPermissionsRequested = false;
bool startedListeningForDeviceOrientationChanges = false;
// Tell plugin to create mock/detached objects and stub method calls for the
// testing of createCamera.
camera.proxy = CameraXProxy(
getProcessCameraProvider: () =>
Future<ProcessCameraProvider>.value(mockProcessCameraProvider),
createCameraSelector: (int cameraSelectorLensDirection) {
switch (cameraSelectorLensDirection) {
case CameraSelector.lensFacingFront:
return MockCameraSelector();
case CameraSelector.lensFacingBack:
default:
return mockBackCameraSelector;
}
},
createPreview: (_, __) => mockPreview,
createImageCapture: (_, __) => mockImageCapture,
createRecorder: (_) => mockRecorder,
createVideoCapture: (_) => Future<VideoCapture>.value(mockVideoCapture),
createImageAnalysis: (_, __) => mockImageAnalysis,
createResolutionStrategy: (
{bool highestAvailable = false,
Size? boundSize,
int? fallbackRule}) =>
MockResolutionStrategy(),
createResolutionSelector: (_) => MockResolutionSelector(),
createFallbackStrategy: (
{required VideoQuality quality,
required VideoResolutionFallbackRule fallbackRule}) =>
MockFallbackStrategy(),
createQualitySelector: (
{required VideoQuality videoQuality,
required FallbackStrategy fallbackStrategy}) =>
MockQualitySelector(),
createCameraStateObserver: (void Function(Object) onChanged) =>
Observer<CameraState>.detached(onChanged: onChanged),
requestCameraPermissions: (_) {
cameraPermissionsRequested = true;
return Future<void>.value();
},
startListeningForDeviceOrientationChange: (_, __) {
startedListeningForDeviceOrientationChanges = true;
},
);
when(mockPreview.setSurfaceProvider())
.thenAnswer((_) async => testSurfaceTextureId);
when(mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector,
<UseCase>[mockPreview, mockImageCapture, mockImageAnalysis]))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => mockLiveCameraState);
camera.processCameraProvider = mockProcessCameraProvider;
expect(
await camera.createCamera(testCameraDescription, testResolutionPreset,
enableAudio: enableAudio),
equals(testSurfaceTextureId));
// Verify permissions are requested and the camera starts listening for device orientation changes.
expect(cameraPermissionsRequested, isTrue);
expect(startedListeningForDeviceOrientationChanges, isTrue);
// Verify CameraSelector is set with appropriate lens direction.
expect(camera.cameraSelector, equals(mockBackCameraSelector));
// Verify the camera's Preview instance is instantiated properly.
expect(camera.preview, equals(mockPreview));
// Verify the camera's ImageCapture instance is instantiated properly.
expect(camera.imageCapture, equals(mockImageCapture));
// Verify the camera's Recorder and VideoCapture instances are instantiated properly.
expect(camera.recorder, equals(mockRecorder));
expect(camera.videoCapture, equals(mockVideoCapture));
// Verify the camera's Preview instance has its surface provider set.
verify(camera.preview!.setSurfaceProvider());
// Verify the camera state observer is updated.
expect(
await testCameraClosingObserver(
camera,
testSurfaceTextureId,
verify(mockLiveCameraState.observe(captureAny)).captured.single
as Observer<CameraState>),
isTrue);
});
test(
'createCamera binds Preview and ImageCapture use cases to ProcessCameraProvider instance',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const CameraLensDirection testLensDirection = CameraLensDirection.back;
const int testSensorOrientation = 90;
const CameraDescription testCameraDescription = CameraDescription(
name: 'cameraName',
lensDirection: testLensDirection,
sensorOrientation: testSensorOrientation);
const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh;
const bool enableAudio = true;
// Mock/Detached objects for (typically attached) objects created by
// createCamera.
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockPreview mockPreview = MockPreview();
final MockCameraSelector mockBackCameraSelector = MockCameraSelector();
final MockImageCapture mockImageCapture = MockImageCapture();
final MockImageAnalysis mockImageAnalysis = MockImageAnalysis();
final MockRecorder mockRecorder = MockRecorder();
final MockVideoCapture mockVideoCapture = MockVideoCapture();
final MockCamera mockCamera = MockCamera();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final MockCameraControl mockCameraControl = MockCameraControl();
// Tell plugin to create mock/detached objects and stub method calls for the
// testing of createCamera.
camera.proxy = CameraXProxy(
getProcessCameraProvider: () =>
Future<ProcessCameraProvider>.value(mockProcessCameraProvider),
createCameraSelector: (int cameraSelectorLensDirection) {
switch (cameraSelectorLensDirection) {
case CameraSelector.lensFacingFront:
return MockCameraSelector();
case CameraSelector.lensFacingBack:
default:
return mockBackCameraSelector;
}
},
createPreview: (_, __) => mockPreview,
createImageCapture: (_, __) => mockImageCapture,
createRecorder: (_) => mockRecorder,
createVideoCapture: (_) => Future<VideoCapture>.value(mockVideoCapture),
createImageAnalysis: (_, __) => mockImageAnalysis,
createResolutionStrategy: (
{bool highestAvailable = false,
Size? boundSize,
int? fallbackRule}) =>
MockResolutionStrategy(),
createResolutionSelector: (_) => MockResolutionSelector(),
createFallbackStrategy: (
{required VideoQuality quality,
required VideoResolutionFallbackRule fallbackRule}) =>
MockFallbackStrategy(),
createQualitySelector: (
{required VideoQuality videoQuality,
required FallbackStrategy fallbackStrategy}) =>
MockQualitySelector(),
createCameraStateObserver: (void Function(Object) onChanged) =>
Observer<CameraState>.detached(onChanged: onChanged),
requestCameraPermissions: (_) => Future<void>.value(),
startListeningForDeviceOrientationChange: (_, __) {},
);
when(mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector,
<UseCase>[mockPreview, mockImageCapture, mockImageAnalysis]))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => MockLiveCameraState());
when(mockCamera.getCameraControl())
.thenAnswer((_) async => mockCameraControl);
camera.processCameraProvider = mockProcessCameraProvider;
await camera.createCamera(testCameraDescription, testResolutionPreset,
enableAudio: enableAudio);
// Verify expected UseCases were bound.
verify(camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!,
<UseCase>[mockPreview, mockImageCapture, mockImageAnalysis]));
// Verify the camera's CameraInfo instance got updated.
expect(camera.cameraInfo, equals(mockCameraInfo));
// Verify camera's CameraControl instance got updated.
expect(camera.cameraControl, equals(mockCameraControl));
// Verify preview has been marked as bound to the camera lifecycle by
// createCamera.
expect(camera.previewInitiallyBound, isTrue);
});
test(
'createCamera properly sets preset resolution for non-video capture use cases',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const CameraLensDirection testLensDirection = CameraLensDirection.back;
const int testSensorOrientation = 90;
const CameraDescription testCameraDescription = CameraDescription(
name: 'cameraName',
lensDirection: testLensDirection,
sensorOrientation: testSensorOrientation);
const bool enableAudio = true;
final MockCamera mockCamera = MockCamera();
// Mock/Detached objects for (typically attached) objects created by
// createCamera.
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final MockCameraSelector mockBackCameraSelector = MockCameraSelector();
final MockCameraSelector mockFrontCameraSelector = MockCameraSelector();
final MockVideoCapture mockVideoCapture = MockVideoCapture();
final MockRecorder mockRecorder = MockRecorder();
// Tell plugin to create mock/detached objects for testing createCamera
// as needed.
camera.proxy = CameraXProxy(
getProcessCameraProvider: () =>
Future<ProcessCameraProvider>.value(mockProcessCameraProvider),
createCameraSelector: (int cameraSelectorLensDirection) {
switch (cameraSelectorLensDirection) {
case CameraSelector.lensFacingFront:
return mockFrontCameraSelector;
case CameraSelector.lensFacingBack:
default:
return mockBackCameraSelector;
}
},
createPreview:
(ResolutionSelector? resolutionSelector, int? targetRotation) =>
Preview.detached(
initialTargetRotation: targetRotation,
resolutionSelector: resolutionSelector),
createImageCapture:
(ResolutionSelector? resolutionSelector, int? targetRotation) =>
ImageCapture.detached(
resolutionSelector: resolutionSelector,
initialTargetRotation: targetRotation),
createRecorder: (_) => mockRecorder,
createVideoCapture: (_) => Future<VideoCapture>.value(mockVideoCapture),
createImageAnalysis:
(ResolutionSelector? resolutionSelector, int? targetRotation) =>
ImageAnalysis.detached(
resolutionSelector: resolutionSelector,
initialTargetRotation: targetRotation),
createResolutionStrategy: (
{bool highestAvailable = false, Size? boundSize, int? fallbackRule}) {
if (highestAvailable) {
return ResolutionStrategy.detachedHighestAvailableStrategy();
}
return ResolutionStrategy.detached(
boundSize: boundSize, fallbackRule: fallbackRule);
},
createResolutionSelector: (ResolutionStrategy resolutionStrategy) =>
ResolutionSelector.detached(resolutionStrategy: resolutionStrategy),
createFallbackStrategy: (
{required VideoQuality quality,
required VideoResolutionFallbackRule fallbackRule}) =>
MockFallbackStrategy(),
createQualitySelector: (
{required VideoQuality videoQuality,
required FallbackStrategy fallbackStrategy}) =>
MockQualitySelector(),
createCameraStateObserver: (_) => MockObserver(),
requestCameraPermissions: (_) => Future<void>.value(),
startListeningForDeviceOrientationChange: (_, __) {},
setPreviewSurfaceProvider: (_) => Future<int>.value(
3), // 3 is a random Flutter SurfaceTexture ID for testing},
);
when(mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, any))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => MockLiveCameraState());
camera.processCameraProvider = mockProcessCameraProvider;
// Test non-null resolution presets.
for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) {
await camera.createCamera(testCameraDescription, resolutionPreset,
enableAudio: enableAudio);
Size? expectedBoundSize;
ResolutionStrategy? expectedResolutionStrategy;
switch (resolutionPreset) {
case ResolutionPreset.low:
expectedBoundSize = const Size(320, 240);
case ResolutionPreset.medium:
expectedBoundSize = const Size(720, 480);
case ResolutionPreset.high:
expectedBoundSize = const Size(1280, 720);
case ResolutionPreset.veryHigh:
expectedBoundSize = const Size(1920, 1080);
case ResolutionPreset.ultraHigh:
expectedBoundSize = const Size(3840, 2160);
case ResolutionPreset.max:
expectedResolutionStrategy =
ResolutionStrategy.detachedHighestAvailableStrategy();
}
// We expect the strategy to be the highest available or correspond to the
// expected bound size, with fallback to the closest and highest available
// resolution.
expectedResolutionStrategy ??= ResolutionStrategy.detached(
boundSize: expectedBoundSize,
fallbackRule: ResolutionStrategy.fallbackRuleClosestLowerThenHigher);
expect(camera.preview!.resolutionSelector!.resolutionStrategy!.boundSize,
equals(expectedResolutionStrategy.boundSize));
expect(
camera
.imageCapture!.resolutionSelector!.resolutionStrategy!.boundSize,
equals(expectedResolutionStrategy.boundSize));
expect(
camera
.imageAnalysis!.resolutionSelector!.resolutionStrategy!.boundSize,
equals(expectedResolutionStrategy.boundSize));
expect(
camera.preview!.resolutionSelector!.resolutionStrategy!.fallbackRule,
equals(expectedResolutionStrategy.fallbackRule));
expect(
camera.imageCapture!.resolutionSelector!.resolutionStrategy!
.fallbackRule,
equals(expectedResolutionStrategy.fallbackRule));
expect(
camera.imageAnalysis!.resolutionSelector!.resolutionStrategy!
.fallbackRule,
equals(expectedResolutionStrategy.fallbackRule));
}
// Test null case.
await camera.createCamera(testCameraDescription, null);
expect(camera.preview!.resolutionSelector, isNull);
expect(camera.imageCapture!.resolutionSelector, isNull);
expect(camera.imageAnalysis!.resolutionSelector, isNull);
});
test(
'createCamera properly sets preset resolution for video capture use case',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const CameraLensDirection testLensDirection = CameraLensDirection.back;
const int testSensorOrientation = 90;
const CameraDescription testCameraDescription = CameraDescription(
name: 'cameraName',
lensDirection: testLensDirection,
sensorOrientation: testSensorOrientation);
const bool enableAudio = true;
final MockCamera mockCamera = MockCamera();
// Mock/Detached objects for (typically attached) objects created by
// createCamera.
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final MockCameraSelector mockBackCameraSelector = MockCameraSelector();
final MockCameraSelector mockFrontCameraSelector = MockCameraSelector();
final MockPreview mockPreview = MockPreview();
final MockImageCapture mockImageCapture = MockImageCapture();
final MockVideoCapture mockVideoCapture = MockVideoCapture();
final MockImageAnalysis mockImageAnalysis = MockImageAnalysis();
// Tell plugin to create mock/detached objects for testing createCamera
// as needed.
camera.proxy = CameraXProxy(
getProcessCameraProvider: () =>
Future<ProcessCameraProvider>.value(mockProcessCameraProvider),
createCameraSelector: (int cameraSelectorLensDirection) {
switch (cameraSelectorLensDirection) {
case CameraSelector.lensFacingFront:
return mockFrontCameraSelector;
case CameraSelector.lensFacingBack:
default:
return mockBackCameraSelector;
}
},
createPreview: (_, __) => mockPreview,
createImageCapture: (_, __) => mockImageCapture,
createRecorder: (QualitySelector? qualitySelector) =>
Recorder.detached(qualitySelector: qualitySelector),
createVideoCapture: (_) => Future<VideoCapture>.value(mockVideoCapture),
createImageAnalysis: (_, __) => mockImageAnalysis,
createResolutionStrategy: (
{bool highestAvailable = false,
Size? boundSize,
int? fallbackRule}) =>
MockResolutionStrategy(),
createResolutionSelector: (_) => MockResolutionSelector(),
createFallbackStrategy: (
{required VideoQuality quality,
required VideoResolutionFallbackRule fallbackRule}) =>
FallbackStrategy.detached(
quality: quality, fallbackRule: fallbackRule),
createQualitySelector: (
{required VideoQuality videoQuality,
required FallbackStrategy fallbackStrategy}) =>
QualitySelector.detached(qualityList: <VideoQualityData>[
VideoQualityData(quality: videoQuality)
], fallbackStrategy: fallbackStrategy),
createCameraStateObserver: (void Function(Object) onChanged) =>
Observer<CameraState>.detached(onChanged: onChanged),
requestCameraPermissions: (_) => Future<void>.value(),
startListeningForDeviceOrientationChange: (_, __) {},
);
when(mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector,
<UseCase>[mockPreview, mockImageCapture, mockImageAnalysis]))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => MockLiveCameraState());
// Test non-null resolution presets.
for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) {
await camera.createCamera(testCameraDescription, resolutionPreset,
enableAudio: enableAudio);
VideoQuality? expectedVideoQuality;
switch (resolutionPreset) {
case ResolutionPreset.low:
// 240p is not supported by CameraX.
case ResolutionPreset.medium:
expectedVideoQuality = VideoQuality.SD;
case ResolutionPreset.high:
expectedVideoQuality = VideoQuality.HD;
case ResolutionPreset.veryHigh:
expectedVideoQuality = VideoQuality.FHD;
case ResolutionPreset.ultraHigh:
expectedVideoQuality = VideoQuality.UHD;
case ResolutionPreset.max:
expectedVideoQuality = VideoQuality.highest;
}
const VideoResolutionFallbackRule expectedFallbackRule =
VideoResolutionFallbackRule.lowerQualityOrHigherThan;
final FallbackStrategy expectedFallbackStrategy =
FallbackStrategy.detached(
quality: expectedVideoQuality,
fallbackRule: expectedFallbackRule);
expect(camera.recorder!.qualitySelector!.qualityList.length, equals(1));
expect(camera.recorder!.qualitySelector!.qualityList.first.quality,
equals(expectedVideoQuality));
expect(camera.recorder!.qualitySelector!.fallbackStrategy!.quality,
equals(expectedFallbackStrategy.quality));
expect(camera.recorder!.qualitySelector!.fallbackStrategy!.fallbackRule,
equals(expectedFallbackStrategy.fallbackRule));
}
// Test null case.
await camera.createCamera(testCameraDescription, null);
expect(camera.recorder!.qualitySelector, isNull);
});
test(
'initializeCamera throws a CameraException when createCamera has not been called before initializedCamera',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
await expectLater(() async {
await camera.initializeCamera(3);
}, throwsA(isA<CameraException>()));
});
test('initializeCamera sends expected CameraInitializedEvent', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 10;
const CameraLensDirection testLensDirection = CameraLensDirection.back;
const int testSensorOrientation = 90;
const CameraDescription testCameraDescription = CameraDescription(
name: 'cameraName',
lensDirection: testLensDirection,
sensorOrientation: testSensorOrientation);
const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh;
const bool enableAudio = true;
const int resolutionWidth = 350;
const int resolutionHeight = 750;
final Camera mockCamera = MockCamera();
final ResolutionInfo testResolutionInfo =
ResolutionInfo(width: resolutionWidth, height: resolutionHeight);
// Mocks for (typically attached) objects created by createCamera.
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final CameraInfo mockCameraInfo = MockCameraInfo();
final MockCameraSelector mockBackCameraSelector = MockCameraSelector();
final MockCameraSelector mockFrontCameraSelector = MockCameraSelector();
final MockPreview mockPreview = MockPreview();
final MockImageCapture mockImageCapture = MockImageCapture();
final MockImageAnalysis mockImageAnalysis = MockImageAnalysis();
// Tell plugin to create mock/detached objects for testing createCamera
// as needed.
camera.proxy = CameraXProxy(
getProcessCameraProvider: () =>
Future<ProcessCameraProvider>.value(mockProcessCameraProvider),
createCameraSelector: (int cameraSelectorLensDirection) {
switch (cameraSelectorLensDirection) {
case CameraSelector.lensFacingFront:
return mockFrontCameraSelector;
case CameraSelector.lensFacingBack:
default:
return mockBackCameraSelector;
}
},
createPreview: (_, __) => mockPreview,
createImageCapture: (_, __) => mockImageCapture,
createRecorder: (QualitySelector? qualitySelector) => MockRecorder(),
createVideoCapture: (_) => Future<VideoCapture>.value(MockVideoCapture()),
createImageAnalysis: (_, __) => mockImageAnalysis,
createResolutionStrategy: (
{bool highestAvailable = false,
Size? boundSize,
int? fallbackRule}) =>
MockResolutionStrategy(),
createResolutionSelector: (_) => MockResolutionSelector(),
createFallbackStrategy: (
{required VideoQuality quality,
required VideoResolutionFallbackRule fallbackRule}) =>
MockFallbackStrategy(),
createQualitySelector: (
{required VideoQuality videoQuality,
required FallbackStrategy fallbackStrategy}) =>
MockQualitySelector(),
createCameraStateObserver: (void Function(Object) onChanged) =>
Observer<CameraState>.detached(onChanged: onChanged),
requestCameraPermissions: (_) => Future<void>.value(),
startListeningForDeviceOrientationChange: (_, __) {},
);
final CameraInitializedEvent testCameraInitializedEvent =
CameraInitializedEvent(
cameraId,
resolutionWidth.toDouble(),
resolutionHeight.toDouble(),
ExposureMode.auto,
true,
FocusMode.auto,
true);
// Call createCamera.
when(mockPreview.setSurfaceProvider()).thenAnswer((_) async => cameraId);
when(mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector,
<UseCase>[mockPreview, mockImageCapture, mockImageAnalysis]))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => MockLiveCameraState());
when(mockPreview.getResolutionInfo())
.thenAnswer((_) async => testResolutionInfo);
await camera.createCamera(testCameraDescription, testResolutionPreset,
enableAudio: enableAudio);
// Start listening to camera events stream to verify the proper CameraInitializedEvent is sent.
camera.cameraEventStreamController.stream.listen((CameraEvent event) {
expect(event, const TypeMatcher<CameraInitializedEvent>());
expect(event, equals(testCameraInitializedEvent));
});
await camera.initializeCamera(cameraId);
// Check camera instance was received.
expect(camera.camera, isNotNull);
});
test(
'dispose releases Flutter surface texture, removes camera state observers, and unbinds all use cases',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
camera.preview = MockPreview();
camera.processCameraProvider = MockProcessCameraProvider();
camera.liveCameraState = MockLiveCameraState();
camera.imageAnalysis = MockImageAnalysis();
await camera.dispose(3);
verify(camera.preview!.releaseFlutterSurfaceTexture());
verify(camera.liveCameraState!.removeObservers());
verify(camera.processCameraProvider!.unbindAll());
verify(camera.imageAnalysis!.clearAnalyzer());
});
test('onCameraInitialized stream emits CameraInitializedEvents', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 16;
final Stream<CameraInitializedEvent> eventStream =
camera.onCameraInitialized(cameraId);
final StreamQueue<CameraInitializedEvent> streamQueue =
StreamQueue<CameraInitializedEvent>(eventStream);
const CameraInitializedEvent testEvent = CameraInitializedEvent(
cameraId, 320, 80, ExposureMode.auto, false, FocusMode.auto, false);
camera.cameraEventStreamController.add(testEvent);
expect(await streamQueue.next, testEvent);
await streamQueue.cancel();
});
test(
'onCameraClosing stream emits camera closing event when cameraEventStreamController emits a camera closing event',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 99;
const CameraClosingEvent cameraClosingEvent = CameraClosingEvent(cameraId);
final Stream<CameraClosingEvent> eventStream =
camera.onCameraClosing(cameraId);
final StreamQueue<CameraClosingEvent> streamQueue =
StreamQueue<CameraClosingEvent>(eventStream);
camera.cameraEventStreamController.add(cameraClosingEvent);
expect(await streamQueue.next, equals(cameraClosingEvent));
await streamQueue.cancel();
});
test(
'onCameraError stream emits errors caught by system services or added to stream within plugin',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 27;
const String firstTestErrorDescription = 'Test error description 1!';
const String secondTestErrorDescription = 'Test error description 2!';
const CameraErrorEvent secondCameraErrorEvent =
CameraErrorEvent(cameraId, secondTestErrorDescription);
final Stream<CameraErrorEvent> eventStream = camera.onCameraError(cameraId);
final StreamQueue<CameraErrorEvent> streamQueue =
StreamQueue<CameraErrorEvent>(eventStream);
SystemServices.cameraErrorStreamController.add(firstTestErrorDescription);
expect(await streamQueue.next,
equals(const CameraErrorEvent(cameraId, firstTestErrorDescription)));
camera.cameraEventStreamController.add(secondCameraErrorEvent);
expect(await streamQueue.next, equals(secondCameraErrorEvent));
await streamQueue.cancel();
});
test(
'onDeviceOrientationChanged stream emits changes in device oreintation detected by system services',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final Stream<DeviceOrientationChangedEvent> eventStream =
camera.onDeviceOrientationChanged();
final StreamQueue<DeviceOrientationChangedEvent> streamQueue =
StreamQueue<DeviceOrientationChangedEvent>(eventStream);
const DeviceOrientationChangedEvent testEvent =
DeviceOrientationChangedEvent(DeviceOrientation.portraitDown);
DeviceOrientationManager.deviceOrientationChangedStreamController
.add(testEvent);
expect(await streamQueue.next, testEvent);
await streamQueue.cancel();
});
test(
'pausePreview unbinds preview from lifecycle when preview is nonnull and has been bound to lifecycle',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
// Set directly for test versus calling createCamera.
camera.processCameraProvider = MockProcessCameraProvider();
camera.preview = MockPreview();
when(camera.processCameraProvider!.isBound(camera.preview!))
.thenAnswer((_) async => true);
await camera.pausePreview(579);
verify(camera.processCameraProvider!.unbind(<UseCase>[camera.preview!]));
});
test(
'pausePreview does not unbind preview from lifecycle when preview has not been bound to lifecycle',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
// Set directly for test versus calling createCamera.
camera.processCameraProvider = MockProcessCameraProvider();
camera.preview = MockPreview();
await camera.pausePreview(632);
verifyNever(
camera.processCameraProvider!.unbind(<UseCase>[camera.preview!]));
});
test(
'resumePreview does not bind preview to lifecycle or update camera state observers if already bound',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockCamera mockCamera = MockCamera();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final MockLiveCameraState mockLiveCameraState = MockLiveCameraState();
// Set directly for test versus calling createCamera.
camera.processCameraProvider = mockProcessCameraProvider;
camera.cameraSelector = MockCameraSelector();
camera.preview = MockPreview();
when(camera.processCameraProvider!.isBound(camera.preview!))
.thenAnswer((_) async => true);
when(mockProcessCameraProvider
.bindToLifecycle(camera.cameraSelector, <UseCase>[camera.preview!]))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => mockLiveCameraState);
await camera.resumePreview(78);
verifyNever(camera.processCameraProvider!
.bindToLifecycle(camera.cameraSelector!, <UseCase>[camera.preview!]));
verifyNever(mockLiveCameraState.observe(any));
expect(camera.cameraInfo, isNot(mockCameraInfo));
});
test(
'resumePreview binds preview to lifecycle and updates camera state observers if not already bound',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockCamera mockCamera = MockCamera();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final MockCameraControl mockCameraControl = MockCameraControl();
final MockLiveCameraState mockLiveCameraState = MockLiveCameraState();
// Set directly for test versus calling createCamera.
camera.processCameraProvider = mockProcessCameraProvider;
camera.cameraSelector = MockCameraSelector();
camera.preview = MockPreview();
// Tell plugin to create a detached Observer<CameraState>, that is created to
// track camera state once preview is bound to the lifecycle and needed to
// test for expected updates.
camera.proxy = CameraXProxy(
createCameraStateObserver:
(void Function(Object stateAsObject) onChanged) =>
Observer<CameraState>.detached(onChanged: onChanged));
when(mockProcessCameraProvider
.bindToLifecycle(camera.cameraSelector, <UseCase>[camera.preview!]))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => mockLiveCameraState);
when(mockCamera.getCameraControl())
.thenAnswer((_) async => mockCameraControl);
await camera.resumePreview(78);
verify(camera.processCameraProvider!
.bindToLifecycle(camera.cameraSelector!, <UseCase>[camera.preview!]));
expect(
await testCameraClosingObserver(
camera,
78,
verify(mockLiveCameraState.observe(captureAny)).captured.single
as Observer<dynamic>),
isTrue);
expect(camera.cameraInfo, equals(mockCameraInfo));
expect(camera.cameraControl, equals(mockCameraControl));
});
test(
'buildPreview throws an exception if the preview is not bound to the lifecycle',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 73;
// Tell camera that createCamera has not been called and thus, preview has
// not been bound to the lifecycle of the camera.
camera.previewInitiallyBound = false;
expect(
() => camera.buildPreview(cameraId), throwsA(isA<CameraException>()));
});
test(
'buildPreview returns a Texture once the preview is bound to the lifecycle',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 37;
// Tell camera that createCamera has been called and thus, preview has been
// bound to the lifecycle of the camera.
camera.previewInitiallyBound = true;
final Widget widget = camera.buildPreview(cameraId);
expect(widget is Texture, isTrue);
expect((widget as Texture).textureId, cameraId);
});
group('video recording', () {
test(
'startVideoCapturing binds video capture use case, updates saved camera instance and its properties, and starts the recording',
() async {
// Set up mocks and constants.
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockPendingRecording mockPendingRecording = MockPendingRecording();
final MockRecording mockRecording = MockRecording();
final MockCamera mockCamera = MockCamera();
final MockCamera newMockCamera = MockCamera();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final MockCameraControl mockCameraControl = MockCameraControl();
final MockLiveCameraState mockLiveCameraState = MockLiveCameraState();
final MockLiveCameraState newMockLiveCameraState = MockLiveCameraState();
final TestSystemServicesHostApi mockSystemServicesApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockSystemServicesApi);
// Set directly for test versus calling createCamera.
camera.processCameraProvider = MockProcessCameraProvider();
camera.camera = mockCamera;
camera.recorder = MockRecorder();
camera.videoCapture = MockVideoCapture();
camera.cameraSelector = MockCameraSelector();
camera.liveCameraState = mockLiveCameraState;
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
// Tell plugin to create detached Observer when camera info updated.
camera.proxy = CameraXProxy(
createCameraStateObserver: (void Function(Object) onChanged) =>
Observer<CameraState>.detached(onChanged: onChanged));
const int cameraId = 17;
const String outputPath = '/temp/MOV123.temp';
// Mock method calls.
when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp'))
.thenReturn(outputPath);
when(camera.recorder!.prepareRecording(outputPath))
.thenAnswer((_) async => mockPendingRecording);
when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording);
when(camera.processCameraProvider!.isBound(camera.videoCapture!))
.thenAnswer((_) async => false);
when(camera.processCameraProvider!.bindToLifecycle(
camera.cameraSelector!, <UseCase>[camera.videoCapture!]))
.thenAnswer((_) async => newMockCamera);
when(newMockCamera.getCameraInfo())
.thenAnswer((_) async => mockCameraInfo);
when(newMockCamera.getCameraControl())
.thenAnswer((_) async => mockCameraControl);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => newMockLiveCameraState);
await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
// Verify VideoCapture UseCase is bound and camera & its properties
// are updated.
verify(camera.processCameraProvider!.bindToLifecycle(
camera.cameraSelector!, <UseCase>[camera.videoCapture!]));
expect(camera.camera, equals(newMockCamera));
expect(camera.cameraInfo, equals(mockCameraInfo));
expect(camera.cameraControl, equals(mockCameraControl));
verify(mockLiveCameraState.removeObservers());
expect(
await testCameraClosingObserver(
camera,
cameraId,
verify(newMockLiveCameraState.observe(captureAny)).captured.single
as Observer<dynamic>),
isTrue);
// Verify recording is started.
expect(camera.pendingRecording, equals(mockPendingRecording));
expect(camera.recording, mockRecording);
});
test(
'startVideoCapturing binds video capture use case and starts the recording'
' on first call, and does nothing on second call', () async {
// Set up mocks and constants.
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockPendingRecording mockPendingRecording = MockPendingRecording();
final MockRecording mockRecording = MockRecording();
final MockCamera mockCamera = MockCamera();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final TestSystemServicesHostApi mockSystemServicesApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockSystemServicesApi);
// Set directly for test versus calling createCamera.
camera.processCameraProvider = MockProcessCameraProvider();
camera.recorder = MockRecorder();
camera.videoCapture = MockVideoCapture();
camera.cameraSelector = MockCameraSelector();
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
// Tell plugin to create detached Observer when camera info updated.
camera.proxy = CameraXProxy(
createCameraStateObserver: (void Function(Object) onChanged) =>
Observer<CameraState>.detached(onChanged: onChanged));
const int cameraId = 17;
const String outputPath = '/temp/MOV123.temp';
// Mock method calls.
when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp'))
.thenReturn(outputPath);
when(camera.recorder!.prepareRecording(outputPath))
.thenAnswer((_) async => mockPendingRecording);
when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording);
when(camera.processCameraProvider!.isBound(camera.videoCapture!))
.thenAnswer((_) async => false);
when(camera.processCameraProvider!.bindToLifecycle(
camera.cameraSelector!, <UseCase>[camera.videoCapture!]))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo())
.thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => MockLiveCameraState());
await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
verify(camera.processCameraProvider!.bindToLifecycle(
camera.cameraSelector!, <UseCase>[camera.videoCapture!]));
expect(camera.pendingRecording, equals(mockPendingRecording));
expect(camera.recording, mockRecording);
await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
// Verify that each of these calls happened only once.
verify(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp'))
.called(1);
verifyNoMoreInteractions(mockSystemServicesApi);
verify(camera.recorder!.prepareRecording(outputPath)).called(1);
verifyNoMoreInteractions(camera.recorder);
verify(mockPendingRecording.start()).called(1);
verifyNoMoreInteractions(mockPendingRecording);
});
test(
'startVideoCapturing called with stream options starts image streaming',
() async {
// Set up mocks and constants.
final AndroidCameraCameraX camera = AndroidCameraCameraX();
// Set directly for test versus calling createCamera.
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
camera.processCameraProvider = mockProcessCameraProvider;
camera.cameraSelector = MockCameraSelector();
camera.videoCapture = MockVideoCapture();
camera.imageAnalysis = MockImageAnalysis();
camera.camera = MockCamera();
final Recorder mockRecorder = MockRecorder();
camera.recorder = mockRecorder;
final MockPendingRecording mockPendingRecording = MockPendingRecording();
final TestSystemServicesHostApi mockSystemServicesApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockSystemServicesApi);
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
// Tell plugin to create detached Analyzer for testing.
camera.proxy = CameraXProxy(
createAnalyzer:
(Future<void> Function(ImageProxy imageProxy) analyze) =>
Analyzer.detached(analyze: analyze));
const int cameraId = 17;
const String outputPath = '/temp/MOV123.temp';
final Completer<CameraImageData> imageDataCompleter =
Completer<CameraImageData>();
final VideoCaptureOptions videoCaptureOptions = VideoCaptureOptions(
cameraId,
streamCallback: (CameraImageData imageData) =>
imageDataCompleter.complete(imageData));
// Mock method calls.
when(camera.processCameraProvider!.isBound(camera.videoCapture!))
.thenAnswer((_) async => true);
when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp'))
.thenReturn(outputPath);
when(camera.recorder!.prepareRecording(outputPath))
.thenAnswer((_) async => mockPendingRecording);
when(mockProcessCameraProvider.bindToLifecycle(any, any))
.thenAnswer((_) => Future<Camera>.value(camera.camera));
when(camera.camera!.getCameraInfo())
.thenAnswer((_) => Future<CameraInfo>.value(MockCameraInfo()));
await camera.startVideoCapturing(videoCaptureOptions);
final CameraImageData mockCameraImageData = MockCameraImageData();
camera.cameraImageDataStreamController!.add(mockCameraImageData);
expect(imageDataCompleter.future, isNotNull);
await camera.cameraImageDataStreamController!.close();
});
test(
'startVideoCapturing sets VideoCapture target rotation to current video orientation if orientation unlocked',
() async {
// Set up mocks and constants.
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockPendingRecording mockPendingRecording = MockPendingRecording();
final MockRecording mockRecording = MockRecording();
final MockVideoCapture mockVideoCapture = MockVideoCapture();
final TestSystemServicesHostApi mockSystemServicesApi =
MockTestSystemServicesHostApi();
TestSystemServicesHostApi.setup(mockSystemServicesApi);
const int defaultTargetRotation = Surface.ROTATION_270;
// Set directly for test versus calling createCamera.
camera.processCameraProvider = MockProcessCameraProvider();
camera.camera = MockCamera();
camera.recorder = MockRecorder();
camera.videoCapture = mockVideoCapture;
camera.cameraSelector = MockCameraSelector();
// Tell plugin to mock call to get current video orientation.
camera.proxy = CameraXProxy(
getDefaultDisplayRotation: () =>
Future<int>.value(defaultTargetRotation));
const int cameraId = 87;
const String outputPath = '/temp/MOV123.temp';
// Mock method calls.
when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp'))
.thenReturn(outputPath);
when(camera.recorder!.prepareRecording(outputPath))
.thenAnswer((_) async => mockPendingRecording);
when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording);
when(camera.processCameraProvider!.isBound(camera.videoCapture!))
.thenAnswer((_) async => true);
// Orientation is unlocked and plugin does not need to set default target
// rotation manually.
camera.recording = null;
await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
verifyNever(mockVideoCapture.setTargetRotation(any));
// Orientation is locked and plugin does not need to set default target
// rotation manually.
camera.recording = null;
camera.captureOrientationLocked = true;
await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
verifyNever(mockVideoCapture.setTargetRotation(any));
// Orientation is locked and plugin does need to set default target
// rotation manually.
camera.recording = null;
camera.captureOrientationLocked = true;
camera.shouldSetDefaultRotation = true;
await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
verifyNever(mockVideoCapture.setTargetRotation(any));
// Orientation is unlocked and plugin does need to set default target
// rotation manually.
camera.recording = null;
camera.captureOrientationLocked = false;
camera.shouldSetDefaultRotation = true;
await camera.startVideoCapturing(const VideoCaptureOptions(cameraId));
verify(mockVideoCapture.setTargetRotation(defaultTargetRotation));
});
test('pauseVideoRecording pauses the recording', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockRecording recording = MockRecording();
// Set directly for test versus calling startVideoCapturing.
camera.recording = recording;
await camera.pauseVideoRecording(0);
verify(recording.pause());
verifyNoMoreInteractions(recording);
});
test('resumeVideoRecording resumes the recording', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockRecording recording = MockRecording();
// Set directly for test versus calling startVideoCapturing.
camera.recording = recording;
await camera.resumeVideoRecording(0);
verify(recording.resume());
verifyNoMoreInteractions(recording);
});
test('stopVideoRecording stops the recording', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockRecording recording = MockRecording();
final MockProcessCameraProvider processCameraProvider =
MockProcessCameraProvider();
final MockVideoCapture videoCapture = MockVideoCapture();
const String videoOutputPath = '/test/output/path';
// Set directly for test versus calling createCamera and startVideoCapturing.
camera.processCameraProvider = processCameraProvider;
camera.recording = recording;
camera.videoCapture = videoCapture;
camera.videoOutputPath = videoOutputPath;
// Tell plugin that videoCapture use case was bound to start recording.
when(camera.processCameraProvider!.isBound(videoCapture))
.thenAnswer((_) async => true);
final XFile file = await camera.stopVideoRecording(0);
expect(file.path, videoOutputPath);
// Verify that recording stops.
verify(recording.close());
verifyNoMoreInteractions(recording);
});
test(
'stopVideoRecording throws a camera exception if '
'no recording is in progress', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const String videoOutputPath = '/test/output/path';
// Set directly for test versus calling startVideoCapturing.
camera.recording = null;
camera.videoOutputPath = videoOutputPath;
await expectLater(() async {
await camera.stopVideoRecording(0);
}, throwsA(isA<CameraException>()));
});
});
test(
'stopVideoRecording throws a camera exception if '
'videoOutputPath is null, and sets recording to null', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockRecording mockRecording = MockRecording();
final MockVideoCapture mockVideoCapture = MockVideoCapture();
// Set directly for test versus calling startVideoCapturing.
camera.processCameraProvider = MockProcessCameraProvider();
camera.recording = mockRecording;
camera.videoOutputPath = null;
camera.videoCapture = mockVideoCapture;
// Tell plugin that videoCapture use case was bound to start recording.
when(camera.processCameraProvider!.isBound(mockVideoCapture))
.thenAnswer((_) async => true);
await expectLater(() async {
await camera.stopVideoRecording(0);
}, throwsA(isA<CameraException>()));
expect(camera.recording, null);
});
test(
'calling stopVideoRecording twice stops the recording '
'and then throws a CameraException', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockRecording recording = MockRecording();
final MockProcessCameraProvider processCameraProvider =
MockProcessCameraProvider();
final MockVideoCapture videoCapture = MockVideoCapture();
const String videoOutputPath = '/test/output/path';
// Set directly for test versus calling createCamera and startVideoCapturing.
camera.processCameraProvider = processCameraProvider;
camera.recording = recording;
camera.videoCapture = videoCapture;
camera.videoOutputPath = videoOutputPath;
final XFile file = await camera.stopVideoRecording(0);
expect(file.path, videoOutputPath);
await expectLater(() async {
await camera.stopVideoRecording(0);
}, throwsA(isA<CameraException>()));
});
test(
'takePicture binds and unbinds ImageCapture to lifecycle and makes call to take a picture',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const String testPicturePath = 'test/absolute/path/to/picture';
// Set directly for test versus calling createCamera.
camera.imageCapture = MockImageCapture();
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
when(camera.imageCapture!.takePicture())
.thenAnswer((_) async => testPicturePath);
final XFile imageFile = await camera.takePicture(3);
expect(imageFile.path, equals(testPicturePath));
});
test(
'takePicture sets ImageCapture target rotation to currrent photo rotation when orientation unlocked',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockImageCapture mockImageCapture = MockImageCapture();
const int cameraId = 3;
const int defaultTargetRotation = Surface.ROTATION_180;
// Set directly for test versus calling createCamera.
camera.imageCapture = mockImageCapture;
// Tell plugin to mock call to get current photo orientation.
camera.proxy = CameraXProxy(
getDefaultDisplayRotation: () =>
Future<int>.value(defaultTargetRotation));
when(camera.imageCapture!.takePicture())
.thenAnswer((_) async => 'test/absolute/path/to/picture');
// Orientation is unlocked and plugin does not need to set default target
// rotation manually.
await camera.takePicture(cameraId);
verifyNever(mockImageCapture.setTargetRotation(any));
// Orientation is locked and plugin does not need to set default target
// rotation manually.
camera.captureOrientationLocked = true;
await camera.takePicture(cameraId);
verifyNever(mockImageCapture.setTargetRotation(any));
// Orientation is locked and plugin does need to set default target
// rotation manually.
camera.captureOrientationLocked = true;
camera.shouldSetDefaultRotation = true;
await camera.takePicture(cameraId);
verifyNever(mockImageCapture.setTargetRotation(any));
// Orientation is unlocked and plugin does need to set default target
// rotation manually.
camera.captureOrientationLocked = false;
camera.shouldSetDefaultRotation = true;
await camera.takePicture(cameraId);
verify(mockImageCapture.setTargetRotation(defaultTargetRotation));
});
test('takePicture turns non-torch flash mode off when torch mode enabled',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 77;
// Set directly for test versus calling createCamera.
camera.imageCapture = MockImageCapture();
camera.cameraControl = MockCameraControl();
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
await camera.setFlashMode(cameraId, FlashMode.torch);
await camera.takePicture(cameraId);
verify(camera.imageCapture!.setFlashMode(ImageCapture.flashModeOff));
});
test(
'setFlashMode configures ImageCapture with expected non-torch flash mode',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 22;
final MockCameraControl mockCameraControl = MockCameraControl();
// Set directly for test versus calling createCamera.
camera.imageCapture = MockImageCapture();
camera.cameraControl = mockCameraControl;
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
for (final FlashMode flashMode in FlashMode.values) {
await camera.setFlashMode(cameraId, flashMode);
int? expectedFlashMode;
switch (flashMode) {
case FlashMode.off:
expectedFlashMode = ImageCapture.flashModeOff;
case FlashMode.auto:
expectedFlashMode = ImageCapture.flashModeAuto;
case FlashMode.always:
expectedFlashMode = ImageCapture.flashModeOn;
case FlashMode.torch:
expectedFlashMode = null;
}
if (expectedFlashMode == null) {
// Torch mode enabled and won't be used for configuring image capture.
continue;
}
verifyNever(mockCameraControl.enableTorch(true));
expect(camera.torchEnabled, isFalse);
await camera.takePicture(cameraId);
verify(camera.imageCapture!.setFlashMode(expectedFlashMode));
}
});
test('setFlashMode turns on torch mode as expected', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 44;
final MockCameraControl mockCameraControl = MockCameraControl();
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
await camera.setFlashMode(cameraId, FlashMode.torch);
verify(mockCameraControl.enableTorch(true));
expect(camera.torchEnabled, isTrue);
});
test('setFlashMode turns off torch mode when non-torch flash modes set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 33;
final MockCameraControl mockCameraControl = MockCameraControl();
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
for (final FlashMode flashMode in FlashMode.values) {
camera.torchEnabled = true;
await camera.setFlashMode(cameraId, flashMode);
switch (flashMode) {
case FlashMode.off:
case FlashMode.auto:
case FlashMode.always:
verify(mockCameraControl.enableTorch(false));
expect(camera.torchEnabled, isFalse);
case FlashMode.torch:
verifyNever(mockCameraControl.enableTorch(true));
expect(camera.torchEnabled, true);
}
}
});
test('getMinExposureOffset returns expected exposure offset', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final ExposureState exposureState = ExposureState.detached(
exposureCompensationRange:
ExposureCompensationRange(minCompensation: 3, maxCompensation: 4),
exposureCompensationStep: 0.2);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
when(mockCameraInfo.getExposureState())
.thenAnswer((_) async => exposureState);
// We expect the minimum exposure to be the minimum exposure compensation * exposure compensation step.
// Delta is included due to avoid catching rounding errors.
expect(await camera.getMinExposureOffset(35), closeTo(0.6, 0.0000000001));
});
test('getMaxExposureOffset returns expected exposure offset', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final ExposureState exposureState = ExposureState.detached(
exposureCompensationRange:
ExposureCompensationRange(minCompensation: 3, maxCompensation: 4),
exposureCompensationStep: 0.2);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
when(mockCameraInfo.getExposureState())
.thenAnswer((_) async => exposureState);
// We expect the maximum exposure to be the maximum exposure compensation * exposure compensation step.
expect(await camera.getMaxExposureOffset(35), 0.8);
});
test('getExposureOffsetStepSize returns expected exposure offset', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final ExposureState exposureState = ExposureState.detached(
exposureCompensationRange:
ExposureCompensationRange(minCompensation: 3, maxCompensation: 4),
exposureCompensationStep: 0.2);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
when(mockCameraInfo.getExposureState())
.thenAnswer((_) async => exposureState);
expect(await camera.getExposureOffsetStepSize(55), 0.2);
});
test(
'getExposureOffsetStepSize returns -1 when exposure compensation not supported on device',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final ExposureState exposureState = ExposureState.detached(
exposureCompensationRange:
ExposureCompensationRange(minCompensation: 0, maxCompensation: 0),
exposureCompensationStep: 0);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
when(mockCameraInfo.getExposureState())
.thenAnswer((_) async => exposureState);
expect(await camera.getExposureOffsetStepSize(55), -1);
});
test('getMaxZoomLevel returns expected exposure offset', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
const double maxZoomRatio = 1;
final LiveData<ZoomState> mockLiveZoomState = MockLiveZoomState();
final ZoomState zoomState =
ZoomState.detached(maxZoomRatio: maxZoomRatio, minZoomRatio: 0);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
when(mockCameraInfo.getZoomState())
.thenAnswer((_) async => mockLiveZoomState);
when(mockLiveZoomState.getValue()).thenAnswer((_) async => zoomState);
expect(await camera.getMaxZoomLevel(55), maxZoomRatio);
});
test('getMinZoomLevel returns expected exposure offset', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
const double minZoomRatio = 0;
final LiveData<ZoomState> mockLiveZoomState = MockLiveZoomState();
final ZoomState zoomState =
ZoomState.detached(maxZoomRatio: 1, minZoomRatio: minZoomRatio);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
when(mockCameraInfo.getZoomState())
.thenAnswer((_) async => mockLiveZoomState);
when(mockLiveZoomState.getValue()).thenAnswer((_) async => zoomState);
expect(await camera.getMinZoomLevel(55), minZoomRatio);
});
test('setZoomLevel sets zoom ratio as expected', () async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 44;
const double zoomRatio = 0.3;
final MockCameraControl mockCameraControl = MockCameraControl();
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
await camera.setZoomLevel(cameraId, zoomRatio);
verify(mockCameraControl.setZoomRatio(zoomRatio));
});
test(
'onStreamedFrameAvailable emits CameraImageData when picked up from CameraImageData stream controller',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockCamera mockCamera = MockCamera();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
const int cameraId = 22;
// Tell plugin to create detached Analyzer for testing.
camera.proxy = CameraXProxy(
createAnalyzer:
(Future<void> Function(ImageProxy imageProxy) analyze) =>
Analyzer.detached(analyze: analyze));
// Set directly for test versus calling createCamera.
camera.processCameraProvider = mockProcessCameraProvider;
camera.cameraSelector = MockCameraSelector();
camera.imageAnalysis = MockImageAnalysis();
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
when(mockProcessCameraProvider.bindToLifecycle(any, any))
.thenAnswer((_) => Future<Camera>.value(mockCamera));
when(mockCamera.getCameraInfo())
.thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => MockLiveCameraState());
final CameraImageData mockCameraImageData = MockCameraImageData();
final Stream<CameraImageData> imageStream =
camera.onStreamedFrameAvailable(cameraId);
final StreamQueue<CameraImageData> streamQueue =
StreamQueue<CameraImageData>(imageStream);
camera.cameraImageDataStreamController!.add(mockCameraImageData);
expect(await streamQueue.next, equals(mockCameraImageData));
await streamQueue.cancel();
});
test(
'onStreamedFrameAvailable emits CameraImageData when listened to after cancelation',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
final MockProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final MockCamera mockCamera = MockCamera();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
const int cameraId = 22;
// Tell plugin to create detached Analyzer for testing.
camera.proxy = CameraXProxy(
createAnalyzer:
(Future<void> Function(ImageProxy imageProxy) analyze) =>
Analyzer.detached(analyze: analyze));
// Set directly for test versus calling createCamera.
camera.processCameraProvider = mockProcessCameraProvider;
camera.cameraSelector = MockCameraSelector();
camera.imageAnalysis = MockImageAnalysis();
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
when(mockProcessCameraProvider.bindToLifecycle(any, any))
.thenAnswer((_) => Future<Camera>.value(mockCamera));
when(mockCamera.getCameraInfo())
.thenAnswer((_) => Future<CameraInfo>.value(mockCameraInfo));
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => MockLiveCameraState());
final CameraImageData mockCameraImageData = MockCameraImageData();
final Stream<CameraImageData> imageStream =
camera.onStreamedFrameAvailable(cameraId);
// Listen to image stream.
final StreamSubscription<CameraImageData> imageStreamSubscription =
imageStream.listen((CameraImageData data) {});
// Cancel subscription to image stream.
await imageStreamSubscription.cancel();
final Stream<CameraImageData> imageStream2 =
camera.onStreamedFrameAvailable(cameraId);
// Listen to image stream again.
final StreamQueue<CameraImageData> streamQueue =
StreamQueue<CameraImageData>(imageStream2);
camera.cameraImageDataStreamController!.add(mockCameraImageData);
expect(await streamQueue.next, equals(mockCameraImageData));
await streamQueue.cancel();
});
test(
'onStreamedFrameAvailable returns stream that responds expectedly to being listened to',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 33;
final ProcessCameraProvider mockProcessCameraProvider =
MockProcessCameraProvider();
final CameraSelector mockCameraSelector = MockCameraSelector();
final MockImageAnalysis mockImageAnalysis = MockImageAnalysis();
final Camera mockCamera = MockCamera();
final CameraInfo mockCameraInfo = MockCameraInfo();
final MockImageProxy mockImageProxy = MockImageProxy();
final MockPlaneProxy mockPlane = MockPlaneProxy();
final List<MockPlaneProxy> mockPlanes = <MockPlaneProxy>[mockPlane];
final Uint8List buffer = Uint8List(0);
const int pixelStride = 27;
const int rowStride = 58;
const int imageFormat = 582;
const int imageHeight = 100;
const int imageWidth = 200;
// Tell plugin to create detached Analyzer for testing.
camera.proxy = CameraXProxy(
createAnalyzer:
(Future<void> Function(ImageProxy imageProxy) analyze) =>
Analyzer.detached(analyze: analyze));
// Set directly for test versus calling createCamera.
camera.processCameraProvider = mockProcessCameraProvider;
camera.cameraSelector = mockCameraSelector;
camera.imageAnalysis = mockImageAnalysis;
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
when(mockProcessCameraProvider.isBound(mockImageAnalysis))
.thenAnswer((_) async => Future<bool>.value(false));
when(mockProcessCameraProvider
.bindToLifecycle(mockCameraSelector, <UseCase>[mockImageAnalysis]))
.thenAnswer((_) async => mockCamera);
when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo);
when(mockCameraInfo.getCameraState())
.thenAnswer((_) async => MockLiveCameraState());
when(mockImageProxy.getPlanes())
.thenAnswer((_) => Future<List<PlaneProxy>>.value(mockPlanes));
when(mockPlane.buffer).thenReturn(buffer);
when(mockPlane.rowStride).thenReturn(rowStride);
when(mockPlane.pixelStride).thenReturn(pixelStride);
when(mockImageProxy.format).thenReturn(imageFormat);
when(mockImageProxy.height).thenReturn(imageHeight);
when(mockImageProxy.width).thenReturn(imageWidth);
final Completer<CameraImageData> imageDataCompleter =
Completer<CameraImageData>();
final StreamSubscription<CameraImageData>
onStreamedFrameAvailableSubscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData imageData) {
imageDataCompleter.complete(imageData);
});
// Test ImageAnalysis use case is bound to ProcessCameraProvider.
final Analyzer capturedAnalyzer =
verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single
as Analyzer;
await capturedAnalyzer.analyze(mockImageProxy);
final CameraImageData imageData = await imageDataCompleter.future;
// Test Analyzer correctly process ImageProxy instances.
expect(imageData.planes.length, equals(1));
expect(imageData.planes[0].bytes, equals(buffer));
expect(imageData.planes[0].bytesPerRow, equals(rowStride));
expect(imageData.planes[0].bytesPerPixel, equals(pixelStride));
expect(imageData.format.raw, equals(imageFormat));
expect(imageData.height, equals(imageHeight));
expect(imageData.width, equals(imageWidth));
await onStreamedFrameAvailableSubscription.cancel();
});
test(
'onStreamedFrameAvailable returns stream that responds expectedly to being canceled',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 32;
final MockImageAnalysis mockImageAnalysis = MockImageAnalysis();
// Set directly for test versus calling createCamera.
camera.imageAnalysis = mockImageAnalysis;
// Ignore setting target rotation for this test; tested seprately.
camera.captureOrientationLocked = true;
// Tell plugin to create a detached analyzer for testing purposes.
camera.proxy = CameraXProxy(createAnalyzer: (_) => MockAnalyzer());
final StreamSubscription<CameraImageData> imageStreamSubscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData data) {});
await imageStreamSubscription.cancel();
verify(mockImageAnalysis.clearAnalyzer());
});
test(
'onStreamedFrameAvailable sets ImageAnalysis target rotation to current photo orientation when orientation unlocked',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 35;
const int defaultTargetRotation = Surface.ROTATION_90;
final MockImageAnalysis mockImageAnalysis = MockImageAnalysis();
// Set directly for test versus calling createCamera.
camera.imageAnalysis = mockImageAnalysis;
// Tell plugin to create a detached analyzer for testing purposes and mock
// call to get current photo orientation.
camera.proxy = CameraXProxy(
createAnalyzer: (_) => MockAnalyzer(),
getDefaultDisplayRotation: () =>
Future<int>.value(defaultTargetRotation));
// Orientation is unlocked and plugin does not need to set default target
// rotation manually.
StreamSubscription<CameraImageData> imageStreamSubscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData data) {});
await untilCalled(mockImageAnalysis.setAnalyzer(any));
verifyNever(mockImageAnalysis.setTargetRotation(any));
await imageStreamSubscription.cancel();
// Orientation is locked and plugin does not need to set default target
// rotation manually.
camera.captureOrientationLocked = true;
imageStreamSubscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData data) {});
await untilCalled(mockImageAnalysis.setAnalyzer(any));
verifyNever(mockImageAnalysis.setTargetRotation(any));
await imageStreamSubscription.cancel();
// Orientation is locked and plugin does need to set default target
// rotation manually.
camera.captureOrientationLocked = true;
camera.shouldSetDefaultRotation = true;
imageStreamSubscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData data) {});
await untilCalled(mockImageAnalysis.setAnalyzer(any));
verifyNever(mockImageAnalysis.setTargetRotation(any));
await imageStreamSubscription.cancel();
// Orientation is unlocked and plugin does need to set default target
// rotation manually.
camera.captureOrientationLocked = false;
camera.shouldSetDefaultRotation = true;
imageStreamSubscription = camera
.onStreamedFrameAvailable(cameraId)
.listen((CameraImageData data) {});
await untilCalled(
mockImageAnalysis.setTargetRotation(defaultTargetRotation));
await imageStreamSubscription.cancel();
});
test(
'lockCaptureOrientation sets capture-related use case target rotations to correct orientation',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 44;
final MockImageAnalysis mockImageAnalysis = MockImageAnalysis();
final MockImageCapture mockImageCapture = MockImageCapture();
final MockVideoCapture mockVideoCapture = MockVideoCapture();
// Set directly for test versus calling createCamera.
camera.imageAnalysis = mockImageAnalysis;
camera.imageCapture = mockImageCapture;
camera.videoCapture = mockVideoCapture;
for (final DeviceOrientation orientation in DeviceOrientation.values) {
int? expectedTargetRotation;
switch (orientation) {
case DeviceOrientation.portraitUp:
expectedTargetRotation = Surface.ROTATION_0;
case DeviceOrientation.landscapeLeft:
expectedTargetRotation = Surface.ROTATION_90;
case DeviceOrientation.portraitDown:
expectedTargetRotation = Surface.ROTATION_180;
case DeviceOrientation.landscapeRight:
expectedTargetRotation = Surface.ROTATION_270;
}
await camera.lockCaptureOrientation(cameraId, orientation);
verify(mockImageAnalysis.setTargetRotation(expectedTargetRotation));
verify(mockImageCapture.setTargetRotation(expectedTargetRotation));
verify(mockVideoCapture.setTargetRotation(expectedTargetRotation));
expect(camera.captureOrientationLocked, isTrue);
expect(camera.shouldSetDefaultRotation, isTrue);
// Reset flags for testing.
camera.captureOrientationLocked = false;
camera.shouldSetDefaultRotation = false;
}
});
test(
'unlockCaptureOrientation sets capture-related use case target rotations to current photo/video orientation',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 57;
camera.captureOrientationLocked = true;
await camera.unlockCaptureOrientation(cameraId);
expect(camera.captureOrientationLocked, isFalse);
});
test('setExposureMode sets expected controlAeLock value via Camera2 interop',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 78;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
// Set directly for test versus calling createCamera.
camera.camera = MockCamera();
camera.cameraControl = mockCameraControl;
// Tell plugin to create detached Camera2CameraControl and
// CaptureRequestOptions instances for testing.
camera.proxy = CameraXProxy(
getCamera2CameraControl: (CameraControl cameraControl) =>
cameraControl == mockCameraControl
? mockCamera2CameraControl
: Camera2CameraControl.detached(cameraControl: cameraControl),
createCaptureRequestOptions:
(List<(CaptureRequestKeySupportedType, Object?)> options) =>
CaptureRequestOptions.detached(requestedOptions: options),
);
// Test auto mode.
await camera.setExposureMode(cameraId, ExposureMode.auto);
VerificationResult verificationResult =
verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny));
CaptureRequestOptions capturedCaptureRequestOptions =
verificationResult.captured.single as CaptureRequestOptions;
List<(CaptureRequestKeySupportedType, Object?)> requestedOptions =
capturedCaptureRequestOptions.requestedOptions;
expect(requestedOptions.length, equals(1));
expect(requestedOptions.first.$1,
equals(CaptureRequestKeySupportedType.controlAeLock));
expect(requestedOptions.first.$2, equals(false));
// Test locked mode.
clearInteractions(mockCamera2CameraControl);
await camera.setExposureMode(cameraId, ExposureMode.locked);
verificationResult =
verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny));
capturedCaptureRequestOptions =
verificationResult.captured.single as CaptureRequestOptions;
requestedOptions = capturedCaptureRequestOptions.requestedOptions;
expect(requestedOptions.length, equals(1));
expect(requestedOptions.first.$1,
equals(CaptureRequestKeySupportedType.controlAeLock));
expect(requestedOptions.first.$2, equals(true));
});
test(
'setExposurePoint clears current auto-exposure metering point as expected',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 93;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = mockCameraInfo;
camera.proxy = getProxyForExposureAndFocus();
// Verify nothing happens if no current focus and metering action has been
// enabled.
await camera.setExposurePoint(cameraId, null);
verifyNever(mockCameraControl.startFocusAndMetering(any));
verifyNever(mockCameraControl.cancelFocusAndMetering());
// Verify current auto-exposure metering point is removed if previously set.
final (MeteringPoint, int?) autofocusMeteringPointInfo = (
MeteringPoint.detached(x: 0.3, y: 0.7, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAf
);
List<(MeteringPoint, int?)> meteringPointInfos = <(MeteringPoint, int?)>[
(
MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAe
),
autofocusMeteringPointInfo
];
camera.currentFocusMeteringAction =
FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos);
await camera.setExposurePoint(cameraId, null);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(1));
expect(
capturedMeteringPointInfos.first, equals(autofocusMeteringPointInfo));
// Verify current focus and metering action is cleared if only previously
// set metering point was for auto-exposure.
meteringPointInfos = <(MeteringPoint, int?)>[
(
MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAe
)
];
camera.currentFocusMeteringAction =
FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos);
await camera.setExposurePoint(cameraId, null);
verify(mockCameraControl.cancelFocusAndMetering());
});
test('setExposurePoint throws CameraException if invalid point specified',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 23;
final MockCameraControl mockCameraControl = MockCameraControl();
const Point<double> invalidExposurePoint = Point<double>(3, -1);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForExposureAndFocus();
expect(() => camera.setExposurePoint(cameraId, invalidExposurePoint),
throwsA(isA<CameraException>()));
});
test(
'setExposurePoint adds new exposure point to focus metering action to start as expected when previous metering points have been set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 9;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = mockCameraInfo;
camera.proxy = getProxyForExposureAndFocus();
// Verify current auto-exposure metering point is removed if previously set.
double exposurePointX = 0.8;
double exposurePointY = 0.1;
Point<double> exposurePoint = Point<double>(exposurePointX, exposurePointY);
final (MeteringPoint, int?) autofocusMeteringPointInfo = (
MeteringPoint.detached(x: 0.3, y: 0.7, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAf
);
List<(MeteringPoint, int?)> meteringPointInfos = <(MeteringPoint, int?)>[
(
MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAe
),
autofocusMeteringPointInfo
];
camera.currentFocusMeteringAction =
FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos);
await camera.setExposurePoint(cameraId, exposurePoint);
VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(2));
expect(
capturedMeteringPointInfos.first, equals(autofocusMeteringPointInfo));
expect(capturedMeteringPointInfos[1].$1.x, equals(exposurePointX));
expect(capturedMeteringPointInfos[1].$1.y, equals(exposurePointY));
expect(
capturedMeteringPointInfos[1].$2, equals(FocusMeteringAction.flagAe));
// Verify exposure point is set when no auto-exposure metering point
// previously set, but an auto-focus point metering point has been.
exposurePointX = 0.2;
exposurePointY = 0.9;
exposurePoint = Point<double>(exposurePointX, exposurePointY);
meteringPointInfos = <(MeteringPoint, int?)>[autofocusMeteringPointInfo];
camera.currentFocusMeteringAction =
FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos);
await camera.setExposurePoint(cameraId, exposurePoint);
verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
capturedAction = verificationResult.captured.single as FocusMeteringAction;
capturedMeteringPointInfos = capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(2));
expect(
capturedMeteringPointInfos.first, equals(autofocusMeteringPointInfo));
expect(capturedMeteringPointInfos[1].$1.x, equals(exposurePointX));
expect(capturedMeteringPointInfos[1].$1.y, equals(exposurePointY));
expect(
capturedMeteringPointInfos[1].$2, equals(FocusMeteringAction.flagAe));
});
test(
'setExposurePoint adds new exposure point to focus metering action to start as expected when no previous metering points have been set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 19;
final MockCameraControl mockCameraControl = MockCameraControl();
const double exposurePointX = 0.8;
const double exposurePointY = 0.1;
const Point<double> exposurePoint =
Point<double>(exposurePointX, exposurePointY);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.currentFocusMeteringAction = null;
camera.proxy = getProxyForExposureAndFocus();
await camera.setExposurePoint(cameraId, exposurePoint);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(1));
expect(capturedMeteringPointInfos.first.$1.x, equals(exposurePointX));
expect(capturedMeteringPointInfos.first.$1.y, equals(exposurePointY));
expect(capturedMeteringPointInfos.first.$2,
equals(FocusMeteringAction.flagAe));
});
test(
'setExposurePoint disables auto-cancel for focus and metering as expected',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 2;
final MockCameraControl mockCameraControl = MockCameraControl();
final FocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
const Point<double> exposurePoint = Point<double>(0.1, 0.2);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Test not disabling auto cancel.
await camera.setFocusMode(cameraId, FocusMode.auto);
clearInteractions(mockCameraControl);
await camera.setExposurePoint(cameraId, exposurePoint);
VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isFalse);
clearInteractions(mockCameraControl);
// Test disabling auto cancel.
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
await camera.setExposurePoint(cameraId, exposurePoint);
verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isTrue);
});
test(
'setExposureOffset throws exception if exposure compensation not supported',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 6;
const double offset = 2;
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final ExposureState exposureState = ExposureState.detached(
exposureCompensationRange:
ExposureCompensationRange(minCompensation: 3, maxCompensation: 4),
exposureCompensationStep: 0);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
when(mockCameraInfo.getExposureState())
.thenAnswer((_) async => exposureState);
expect(() => camera.setExposureOffset(cameraId, offset),
throwsA(isA<CameraException>()));
});
test(
'setExposureOffset throws exception if exposure compensation could not be set for unknown reason',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 11;
const double offset = 3;
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final CameraControl mockCameraControl = MockCameraControl();
final ExposureState exposureState = ExposureState.detached(
exposureCompensationRange:
ExposureCompensationRange(minCompensation: 3, maxCompensation: 4),
exposureCompensationStep: 0.2);
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
camera.cameraControl = mockCameraControl;
when(mockCameraInfo.getExposureState())
.thenAnswer((_) async => exposureState);
when(mockCameraControl.setExposureCompensationIndex(15)).thenThrow(
PlatformException(
code: 'TEST_ERROR',
message:
'This is a test error message indicating exposure offset could not be set.'));
expect(() => camera.setExposureOffset(cameraId, offset),
throwsA(isA<CameraException>()));
});
test(
'setExposureOffset throws exception if exposure compensation could not be set due to camera being closed or newer value being set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 21;
const double offset = 5;
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final CameraControl mockCameraControl = MockCameraControl();
final ExposureState exposureState = ExposureState.detached(
exposureCompensationRange:
ExposureCompensationRange(minCompensation: 3, maxCompensation: 4),
exposureCompensationStep: 0.1);
final int expectedExposureCompensationIndex =
(offset / exposureState.exposureCompensationStep).round();
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
camera.cameraControl = mockCameraControl;
when(mockCameraInfo.getExposureState())
.thenAnswer((_) async => exposureState);
when(mockCameraControl
.setExposureCompensationIndex(expectedExposureCompensationIndex))
.thenAnswer((_) async => Future<int?>.value());
expect(() => camera.setExposureOffset(cameraId, offset),
throwsA(isA<CameraException>()));
});
test(
'setExposureOffset behaves as expected to successful attempt to set exposure compensation index',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 11;
const double offset = 3;
final MockCameraInfo mockCameraInfo = MockCameraInfo();
final CameraControl mockCameraControl = MockCameraControl();
final ExposureState exposureState = ExposureState.detached(
exposureCompensationRange:
ExposureCompensationRange(minCompensation: 3, maxCompensation: 4),
exposureCompensationStep: 0.2);
final int expectedExposureCompensationIndex =
(offset / exposureState.exposureCompensationStep).round();
// Set directly for test versus calling createCamera.
camera.cameraInfo = mockCameraInfo;
camera.cameraControl = mockCameraControl;
when(mockCameraInfo.getExposureState())
.thenAnswer((_) async => exposureState);
when(mockCameraControl
.setExposureCompensationIndex(expectedExposureCompensationIndex))
.thenAnswer((_) async => Future<int>.value(
(expectedExposureCompensationIndex *
exposureState.exposureCompensationStep)
.round()));
// Exposure index * exposure offset step size = exposure offset, i.e.
// 15 * 0.2 = 3.
expect(await camera.setExposureOffset(cameraId, offset), equals(3));
});
test('setFocusPoint clears current auto-exposure metering point as expected',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 93;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = mockCameraInfo;
camera.proxy = getProxyForExposureAndFocus();
// Verify nothing happens if no current focus and metering action has been
// enabled.
await camera.setFocusPoint(cameraId, null);
verifyNever(mockCameraControl.startFocusAndMetering(any));
verifyNever(mockCameraControl.cancelFocusAndMetering());
// Verify current auto-exposure metering point is removed if previously set.
final (MeteringPoint, int?) autoexposureMeteringPointInfo = (
MeteringPoint.detached(x: 0.3, y: 0.7, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAe
);
List<(MeteringPoint, int?)> meteringPointInfos = <(MeteringPoint, int?)>[
(
MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAf
),
autoexposureMeteringPointInfo
];
camera.currentFocusMeteringAction =
FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos);
await camera.setFocusPoint(cameraId, null);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(1));
expect(capturedMeteringPointInfos.first,
equals(autoexposureMeteringPointInfo));
// Verify current focus and metering action is cleared if only previously
// set metering point was for auto-exposure.
meteringPointInfos = <(MeteringPoint, int?)>[
(
MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAf
)
];
camera.currentFocusMeteringAction =
FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos);
await camera.setFocusPoint(cameraId, null);
verify(mockCameraControl.cancelFocusAndMetering());
});
test('setFocusPoint throws CameraException if invalid point specified',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 23;
final MockCameraControl mockCameraControl = MockCameraControl();
const Point<double> invalidFocusPoint = Point<double>(-3, 1);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForExposureAndFocus();
expect(() => camera.setFocusPoint(cameraId, invalidFocusPoint),
throwsA(isA<CameraException>()));
});
test(
'setFocusPoint adds new exposure point to focus metering action to start as expected when previous metering points have been set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 9;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCameraInfo mockCameraInfo = MockCameraInfo();
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = mockCameraInfo;
camera.proxy = getProxyForExposureAndFocus();
// Verify current auto-exposure metering point is removed if previously set.
double focusPointX = 0.8;
double focusPointY = 0.1;
Point<double> exposurePoint = Point<double>(focusPointX, focusPointY);
final (MeteringPoint, int?) autoExposureMeteringPointInfo = (
MeteringPoint.detached(x: 0.3, y: 0.7, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAe
);
List<(MeteringPoint, int?)> meteringPointInfos = <(MeteringPoint, int?)>[
(
MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo),
FocusMeteringAction.flagAf
),
autoExposureMeteringPointInfo
];
camera.currentFocusMeteringAction =
FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos);
await camera.setFocusPoint(cameraId, exposurePoint);
VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(2));
expect(capturedMeteringPointInfos.first,
equals(autoExposureMeteringPointInfo));
expect(capturedMeteringPointInfos[1].$1.x, equals(focusPointX));
expect(capturedMeteringPointInfos[1].$1.y, equals(focusPointY));
expect(
capturedMeteringPointInfos[1].$2, equals(FocusMeteringAction.flagAf));
// Verify exposure point is set when no auto-exposure metering point
// previously set, but an auto-focus point metering point has been.
focusPointX = 0.2;
focusPointY = 0.9;
exposurePoint = Point<double>(focusPointX, focusPointY);
meteringPointInfos = <(MeteringPoint, int?)>[autoExposureMeteringPointInfo];
camera.currentFocusMeteringAction =
FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos);
await camera.setFocusPoint(cameraId, exposurePoint);
verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
capturedAction = verificationResult.captured.single as FocusMeteringAction;
capturedMeteringPointInfos = capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(2));
expect(capturedMeteringPointInfos.first,
equals(autoExposureMeteringPointInfo));
expect(capturedMeteringPointInfos[1].$1.x, equals(focusPointX));
expect(capturedMeteringPointInfos[1].$1.y, equals(focusPointY));
expect(
capturedMeteringPointInfos[1].$2, equals(FocusMeteringAction.flagAf));
});
test(
'setFocusPoint adds new exposure point to focus metering action to start as expected when no previous metering points have been set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 19;
final MockCameraControl mockCameraControl = MockCameraControl();
const double focusPointX = 0.8;
const double focusPointY = 0.1;
const Point<double> exposurePoint = Point<double>(focusPointX, focusPointY);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.currentFocusMeteringAction = null;
camera.proxy = getProxyForExposureAndFocus();
await camera.setFocusPoint(cameraId, exposurePoint);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(1));
expect(capturedMeteringPointInfos.first.$1.x, equals(focusPointX));
expect(capturedMeteringPointInfos.first.$1.y, equals(focusPointY));
expect(capturedMeteringPointInfos.first.$2,
equals(FocusMeteringAction.flagAf));
});
test('setFocusPoint disables auto-cancel for focus and metering as expected',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 2;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockFocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
const Point<double> exposurePoint = Point<double>(0.1, 0.2);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Test not disabling auto cancel.
await camera.setFocusMode(cameraId, FocusMode.auto);
clearInteractions(mockCameraControl);
await camera.setFocusPoint(cameraId, exposurePoint);
VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isFalse);
clearInteractions(mockCameraControl);
// Test disabling auto cancel.
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
await camera.setFocusPoint(cameraId, exposurePoint);
verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
capturedAction = verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isTrue);
});
test(
'setFocusMode does nothing if setting auto-focus mode and is already using auto-focus mode',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 4;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockFocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set locked focus mode and then try to re-set it.
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
await camera.setFocusMode(cameraId, FocusMode.locked);
verifyNoMoreInteractions(mockCameraControl);
});
test(
'setFocusMode does nothing if setting locked focus mode and is already using locked focus mode',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 4;
final MockCameraControl mockCameraControl = MockCameraControl();
// Camera uses auto-focus by default, so try setting auto mode again.
await camera.setFocusMode(cameraId, FocusMode.auto);
verifyNoMoreInteractions(mockCameraControl);
});
test(
'setFocusMode removes default auto-focus point if previously set and setting auto-focus mode',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 5;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockFocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
const double exposurePointX = 0.2;
const double exposurePointY = 0.7;
// Set directly for test versus calling createCamera.
camera.cameraInfo = MockCameraInfo();
camera.cameraControl = mockCameraControl;
when(mockCamera2CameraControl.addCaptureRequestOptions(any))
.thenAnswer((_) async => Future<void>.value());
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, mockCamera2CameraControl);
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure points.
await camera.setExposurePoint(
cameraId, const Point<double>(exposurePointX, exposurePointY));
// Lock focus default focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
// Test removal of default focus point.
await camera.setFocusMode(cameraId, FocusMode.auto);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isFalse);
// We expect only the previously set exposure point to be re-set.
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(1));
expect(capturedMeteringPointInfos.first.$1.x, equals(exposurePointX));
expect(capturedMeteringPointInfos.first.$1.y, equals(exposurePointY));
expect(capturedMeteringPointInfos.first.$1.size, isNull);
expect(capturedMeteringPointInfos.first.$2,
equals(FocusMeteringAction.flagAe));
});
test(
'setFocusMode cancels focus and metering if only focus point previously set is a focus point',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 5;
final MockCameraControl mockCameraControl = MockCameraControl();
final FocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
// Set directly for test versus calling createCamera.
camera.cameraInfo = MockCameraInfo();
camera.cameraControl = mockCameraControl;
when(mockCamera2CameraControl.addCaptureRequestOptions(any))
.thenAnswer((_) async => Future<void>.value());
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, mockCamera2CameraControl);
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Lock focus default focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
// Test removal of default focus point.
await camera.setFocusMode(cameraId, FocusMode.auto);
verify(mockCameraControl.cancelFocusAndMetering());
});
test(
'setFocusMode re-focuses on previously set auto-focus point with auto-canceled enabled if setting auto-focus mode',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 6;
final MockCameraControl mockCameraControl = MockCameraControl();
final FocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
const double focusPointX = 0.1;
const double focusPointY = 0.2;
// Set directly for test versus calling createCamera.
camera.cameraInfo = MockCameraInfo();
camera.cameraControl = mockCameraControl;
when(mockCamera2CameraControl.addCaptureRequestOptions(any))
.thenAnswer((_) async => Future<void>.value());
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, mockCamera2CameraControl);
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Lock a focus point.
await camera.setFocusPoint(
cameraId, const Point<double>(focusPointX, focusPointY));
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
// Test re-focusing on previously set auto-focus point with auto-cancel enabled.
await camera.setFocusMode(cameraId, FocusMode.auto);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isFalse);
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(1));
expect(capturedMeteringPointInfos.first.$1.x, equals(focusPointX));
expect(capturedMeteringPointInfos.first.$1.y, equals(focusPointY));
expect(capturedMeteringPointInfos.first.$1.size, isNull);
expect(capturedMeteringPointInfos.first.$2,
equals(FocusMeteringAction.flagAf));
});
test(
'setFocusMode starts expected focus and metering action with previously set auto-focus point if setting locked focus mode and current focus and metering action has auto-focus point',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 7;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
const double focusPointX = 0.88;
const double focusPointY = 0.33;
// Set directly for test versus calling createCamera.
camera.cameraInfo = MockCameraInfo();
camera.cameraControl = mockCameraControl;
when(mockCamera2CameraControl.addCaptureRequestOptions(any))
.thenAnswer((_) async => Future<void>.value());
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, mockCamera2CameraControl);
// Set a focus point.
await camera.setFocusPoint(
cameraId, const Point<double>(focusPointX, focusPointY));
clearInteractions(mockCameraControl);
// Lock focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isTrue);
// We expect the set focus point to be locked.
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(1));
expect(capturedMeteringPointInfos.first.$1.x, equals(focusPointX));
expect(capturedMeteringPointInfos.first.$1.y, equals(focusPointY));
expect(capturedMeteringPointInfos.first.$1.size, isNull);
expect(capturedMeteringPointInfos.first.$2,
equals(FocusMeteringAction.flagAf));
});
test(
'setFocusMode starts expected focus and metering action with previously set auto-focus point if setting locked focus mode and current focus and metering action has auto-focus point amongst others',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 8;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
const double focusPointX = 0.38;
const double focusPointY = 0.38;
const double exposurePointX = 0.54;
const double exposurePointY = 0.45;
// Set directly for test versus calling createCamera.
camera.cameraInfo = MockCameraInfo();
camera.cameraControl = mockCameraControl;
when(mockCamera2CameraControl.addCaptureRequestOptions(any))
.thenAnswer((_) async => Future<void>.value());
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, mockCamera2CameraControl);
// Set focus and exposure points.
await camera.setFocusPoint(
cameraId, const Point<double>(focusPointX, focusPointY));
await camera.setExposurePoint(
cameraId, const Point<double>(exposurePointX, exposurePointY));
clearInteractions(mockCameraControl);
// Lock focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isTrue);
// We expect two MeteringPoints, the set focus point and the set exposure
// point.
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(2));
final List<(MeteringPoint, int?)> focusPoints = capturedMeteringPointInfos
.where(((MeteringPoint, int?) meteringPointInfo) =>
meteringPointInfo.$2 == FocusMeteringAction.flagAf)
.toList();
expect(focusPoints.length, equals(1));
expect(focusPoints.first.$1.x, equals(focusPointX));
expect(focusPoints.first.$1.y, equals(focusPointY));
expect(focusPoints.first.$1.size, isNull);
final List<(MeteringPoint, int?)> exposurePoints =
capturedMeteringPointInfos
.where(((MeteringPoint, int?) meteringPointInfo) =>
meteringPointInfo.$2 == FocusMeteringAction.flagAe)
.toList();
expect(exposurePoints.length, equals(1));
expect(exposurePoints.first.$1.x, equals(exposurePointX));
expect(exposurePoints.first.$1.y, equals(exposurePointY));
expect(exposurePoints.first.$1.size, isNull);
});
test(
'setFocusMode starts expected focus and metering action if setting locked focus mode and current focus and metering action does not contain an auto-focus point',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 9;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
const double exposurePointX = 0.8;
const double exposurePointY = 0.3;
const double defaultFocusPointX = 0.5;
const double defaultFocusPointY = 0.5;
const double defaultFocusPointSize = 1;
// Set directly for test versus calling createCamera.
camera.cameraInfo = MockCameraInfo();
camera.cameraControl = mockCameraControl;
when(mockCamera2CameraControl.addCaptureRequestOptions(any))
.thenAnswer((_) async => Future<void>.value());
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, mockCamera2CameraControl);
// Set an exposure point (creates a current focus and metering action
// without a focus point).
await camera.setExposurePoint(
cameraId, const Point<double>(exposurePointX, exposurePointY));
clearInteractions(mockCameraControl);
// Lock focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isTrue);
// We expect two MeteringPoints, the default focus point and the set
//exposure point.
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(2));
final List<(MeteringPoint, int?)> focusPoints = capturedMeteringPointInfos
.where(((MeteringPoint, int?) meteringPointInfo) =>
meteringPointInfo.$2 == FocusMeteringAction.flagAf)
.toList();
expect(focusPoints.length, equals(1));
expect(focusPoints.first.$1.x, equals(defaultFocusPointX));
expect(focusPoints.first.$1.y, equals(defaultFocusPointY));
expect(focusPoints.first.$1.size, equals(defaultFocusPointSize));
final List<(MeteringPoint, int?)> exposurePoints =
capturedMeteringPointInfos
.where(((MeteringPoint, int?) meteringPointInfo) =>
meteringPointInfo.$2 == FocusMeteringAction.flagAe)
.toList();
expect(exposurePoints.length, equals(1));
expect(exposurePoints.first.$1.x, equals(exposurePointX));
expect(exposurePoints.first.$1.y, equals(exposurePointY));
expect(exposurePoints.first.$1.size, isNull);
});
test(
'setFocusMode starts expected focus and metering action if there is no current focus and metering action',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 10;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
const double defaultFocusPointX = 0.5;
const double defaultFocusPointY = 0.5;
const double defaultFocusPointSize = 1;
// Set directly for test versus calling createCamera.
camera.cameraInfo = MockCameraInfo();
camera.cameraControl = mockCameraControl;
when(mockCamera2CameraControl.addCaptureRequestOptions(any))
.thenAnswer((_) async => Future<void>.value());
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, mockCamera2CameraControl);
// Lock focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isTrue);
// We expect only the default focus point to be set.
final List<(MeteringPoint, int?)> capturedMeteringPointInfos =
capturedAction.meteringPointInfos;
expect(capturedMeteringPointInfos.length, equals(1));
expect(capturedMeteringPointInfos.first.$1.x, equals(defaultFocusPointX));
expect(capturedMeteringPointInfos.first.$1.y, equals(defaultFocusPointY));
expect(capturedMeteringPointInfos.first.$1.size,
equals(defaultFocusPointSize));
expect(capturedMeteringPointInfos.first.$2,
equals(FocusMeteringAction.flagAf));
});
test(
'setFocusMode re-sets exposure mode if setting locked focus mode while using auto exposure mode',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 11;
final MockCameraControl mockCameraControl = MockCameraControl();
final FocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
final MockCamera2CameraControl mockCamera2CameraControl =
MockCamera2CameraControl();
// Set directly for test versus calling createCamera.
camera.cameraInfo = MockCameraInfo();
camera.cameraControl = mockCameraControl;
when(mockCamera2CameraControl.addCaptureRequestOptions(any))
.thenAnswer((_) async => Future<void>.value());
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, mockCamera2CameraControl);
// Make setting focus and metering action successful for test.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set auto exposure mode.
await camera.setExposureMode(cameraId, ExposureMode.auto);
clearInteractions(mockCamera2CameraControl);
// Lock focus point.
await camera.setFocusMode(cameraId, FocusMode.locked);
final VerificationResult verificationResult =
verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny));
final CaptureRequestOptions capturedCaptureRequestOptions =
verificationResult.captured.single as CaptureRequestOptions;
final List<(CaptureRequestKeySupportedType, Object?)> requestedOptions =
capturedCaptureRequestOptions.requestedOptions;
expect(requestedOptions.length, equals(1));
expect(requestedOptions.first.$1,
equals(CaptureRequestKeySupportedType.controlAeLock));
expect(requestedOptions.first.$2, equals(false));
});
test(
'setFocusPoint disables auto-cancel if auto focus mode fails to be set after locked focus mode is set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 22;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockFocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
const Point<double> focusPoint = Point<double>(0.21, 0.21);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action successful to set locked focus
// mode.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure point to later mock failed call to set an exposure point (
// otherwise, focus and metering will be canceled altogether, which is
//considered a successful call).
await camera.setExposurePoint(cameraId, const Point<double>(0.3, 0.4));
// Set locked focus mode so we can set auto mode (cannot set auto mode
// directly since it is the default).
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
// Make setting focus and metering action fail to test that auto-cancel is
// still disabled.
reset(mockFocusMeteringResult);
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(false));
// Test disabling auto cancel.
await camera.setFocusMode(cameraId, FocusMode.auto);
clearInteractions(mockCameraControl);
await camera.setFocusPoint(cameraId, focusPoint);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isTrue);
});
test(
'setExposurePoint disables auto-cancel if auto focus mode fails to be set after locked focus mode is set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 342;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockFocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
const Point<double> exposurePoint = Point<double>(0.23, 0.32);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action successful to set locked focus
// mode.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(true));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure point to later mock failed call to set an exposure point (
// otherwise, focus and metering will be canceled altogether, which is
//considered a successful call).
await camera.setExposurePoint(cameraId, const Point<double>(0.4, 0.3));
// Set locked focus mode so we can set auto mode (cannot set auto mode
// directly since it is the default).
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
// Make setting focus and metering action fail to test that auto-cancel is
// still disabled.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(false));
// Test disabling auto cancel.
await camera.setFocusMode(cameraId, FocusMode.auto);
clearInteractions(mockCameraControl);
await camera.setExposurePoint(cameraId, exposurePoint);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isTrue);
});
test(
'setFocusPoint enables auto-cancel if locked focus mode fails to be set after auto focus mode is set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 232;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockFocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
const Point<double> focusPoint = Point<double>(0.221, 0.211);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action fail to test auto-cancel is not
// disabled.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(false));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure point to later mock failed call to set an exposure point.
await camera.setExposurePoint(cameraId, const Point<double>(0.43, 0.34));
// Test failing to set locked focus mode.
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
await camera.setFocusPoint(cameraId, focusPoint);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isFalse);
});
test(
'setExposurePoint enables auto-cancel if locked focus mode fails to be set after auto focus mode is set',
() async {
final AndroidCameraCameraX camera = AndroidCameraCameraX();
const int cameraId = 323;
final MockCameraControl mockCameraControl = MockCameraControl();
final MockFocusMeteringResult mockFocusMeteringResult =
MockFocusMeteringResult();
const Point<double> exposurePoint = Point<double>(0.223, 0.332);
// Set directly for test versus calling createCamera.
camera.cameraControl = mockCameraControl;
camera.cameraInfo = MockCameraInfo();
camera.proxy = getProxyForSettingFocusandExposurePoints(
mockCameraControl, MockCamera2CameraControl());
// Make setting focus and metering action fail to test auto-cancel is not
// disabled.
when(mockFocusMeteringResult.isFocusSuccessful())
.thenAnswer((_) async => Future<bool>.value(false));
when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async =>
Future<FocusMeteringResult>.value(mockFocusMeteringResult));
// Set exposure point to later mock failed call to set an exposure point.
await camera.setExposurePoint(cameraId, const Point<double>(0.5, 0.2));
// Test failing to set locked focus mode.
await camera.setFocusMode(cameraId, FocusMode.locked);
clearInteractions(mockCameraControl);
await camera.setExposurePoint(cameraId, exposurePoint);
final VerificationResult verificationResult =
verify(mockCameraControl.startFocusAndMetering(captureAny));
final FocusMeteringAction capturedAction =
verificationResult.captured.single as FocusMeteringAction;
expect(capturedAction.disableAutoCancel, isFalse);
});
}
| packages/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart",
"repo_id": "packages",
"token_count": 46653
} | 1,118 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/camera.dart';
import 'package:camera_android_camerax/src/camera_control.dart';
import 'package:camera_android_camerax/src/camera_info.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'camera_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestCameraHostApi, TestInstanceManagerHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('Camera', () {
tearDown(() => TestCameraHostApi.setup(null));
test('getCameraInfo makes call to retrieve expected CameraInfo', () async {
final MockTestCameraHostApi mockApi = MockTestCameraHostApi();
TestCameraHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final Camera camera = Camera.detached(
instanceManager: instanceManager,
);
const int cameraIdentifier = 24;
final CameraInfo cameraInfo = CameraInfo.detached();
const int cameraInfoIdentifier = 88;
instanceManager.addHostCreatedInstance(
camera,
cameraIdentifier,
onCopy: (_) => Camera.detached(instanceManager: instanceManager),
);
instanceManager.addHostCreatedInstance(
cameraInfo,
cameraInfoIdentifier,
onCopy: (_) => CameraInfo.detached(instanceManager: instanceManager),
);
when(mockApi.getCameraInfo(cameraIdentifier))
.thenAnswer((_) => cameraInfoIdentifier);
expect(await camera.getCameraInfo(), equals(cameraInfo));
verify(mockApi.getCameraInfo(cameraIdentifier));
});
test('getCameraControl makes call to retrieve expected CameraControl',
() async {
final MockTestCameraHostApi mockApi = MockTestCameraHostApi();
TestCameraHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final Camera camera = Camera.detached(
instanceManager: instanceManager,
);
const int cameraIdentifier = 42;
final CameraControl cameraControl = CameraControl.detached();
const int cameraControlIdentifier = 8;
instanceManager.addHostCreatedInstance(
camera,
cameraIdentifier,
onCopy: (_) => Camera.detached(instanceManager: instanceManager),
);
instanceManager.addHostCreatedInstance(
cameraControl,
cameraControlIdentifier,
onCopy: (_) => CameraControl.detached(instanceManager: instanceManager),
);
when(mockApi.getCameraControl(cameraIdentifier))
.thenAnswer((_) => cameraControlIdentifier);
expect(await camera.getCameraControl(), equals(cameraControl));
verify(mockApi.getCameraControl(cameraIdentifier));
});
test('flutterApiCreate makes call to add instance to instance manager', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraFlutterApiImpl flutterApi = CameraFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(0);
expect(instanceManager.getInstanceWithWeakReference(0), isA<Camera>());
});
});
}
| packages/packages/camera/camera_android_camerax/test/camera_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/camera_test.dart",
"repo_id": "packages",
"token_count": 1312
} | 1,119 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/image_capture.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:camera_android_camerax/src/resolution_selector.dart';
import 'package:camera_android_camerax/src/surface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'image_capture_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[
TestImageCaptureHostApi,
TestInstanceManagerHostApi,
ResolutionSelector
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
group('ImageCapture', () {
tearDown(() => TestImageCaptureHostApi.setup(null));
test('detached create does not call create on the Java side', () async {
final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi();
TestImageCaptureHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
ImageCapture.detached(
instanceManager: instanceManager,
initialTargetRotation: Surface.ROTATION_180,
targetFlashMode: ImageCapture.flashModeOn,
resolutionSelector: MockResolutionSelector(),
);
verifyNever(mockApi.create(argThat(isA<int>()), argThat(isA<int>()),
argThat(isA<ResolutionSelector>()), argThat(isA<int>())));
});
test('create calls create on the Java side', () async {
final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi();
TestImageCaptureHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int targetRotation = Surface.ROTATION_270;
const int targetFlashMode = ImageCapture.flashModeAuto;
final MockResolutionSelector mockResolutionSelector =
MockResolutionSelector();
const int mockResolutionSelectorId = 24;
instanceManager.addHostCreatedInstance(
mockResolutionSelector, mockResolutionSelectorId,
onCopy: (ResolutionSelector original) {
return MockResolutionSelector();
});
ImageCapture(
instanceManager: instanceManager,
initialTargetRotation: targetRotation,
targetFlashMode: targetFlashMode,
resolutionSelector: mockResolutionSelector,
);
verify(mockApi.create(
argThat(isA<int>()),
argThat(equals(targetRotation)),
argThat(equals(targetFlashMode)),
argThat(equals(mockResolutionSelectorId))));
});
test('setFlashMode makes call to set flash mode for ImageCapture instance',
() async {
final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi();
TestImageCaptureHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int flashMode = ImageCapture.flashModeOff;
final ImageCapture imageCapture = ImageCapture.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(
imageCapture,
0,
onCopy: (_) => ImageCapture.detached(instanceManager: instanceManager),
);
await imageCapture.setFlashMode(flashMode);
verify(mockApi.setFlashMode(
instanceManager.getIdentifier(imageCapture), flashMode));
});
test(
'setTargetRotation makes call to set target rotation for ImageCapture instance',
() async {
final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi();
TestImageCaptureHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int targetRotation = Surface.ROTATION_180;
final ImageCapture imageCapture = ImageCapture.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(
imageCapture,
0,
onCopy: (_) => ImageCapture.detached(instanceManager: instanceManager),
);
await imageCapture.setTargetRotation(targetRotation);
verify(mockApi.setTargetRotation(
instanceManager.getIdentifier(imageCapture), targetRotation));
});
test('takePicture makes call to capture still image', () async {
final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi();
TestImageCaptureHostApi.setup(mockApi);
const String expectedPicturePath = 'test/path/to/picture';
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final ImageCapture imageCapture = ImageCapture.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(
imageCapture,
0,
onCopy: (_) => ImageCapture.detached(),
);
when(mockApi.takePicture(instanceManager.getIdentifier(imageCapture)))
.thenAnswer((_) async => expectedPicturePath);
expect(await imageCapture.takePicture(), equals(expectedPicturePath));
verify(mockApi.takePicture(instanceManager.getIdentifier(imageCapture)));
});
});
}
| packages/packages/camera/camera_android_camerax/test/image_capture_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/image_capture_test.dart",
"repo_id": "packages",
"token_count": 2026
} | 1,120 |
// Mocks generated by Mockito 5.4.4 from annotations
// in camera_android_camerax/test/preview_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2;
import 'package:camera_android_camerax/src/resolution_selector.dart' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'test_camerax_library.g.dart' as _i3;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeResolutionInfo_0 extends _i1.SmartFake
implements _i2.ResolutionInfo {
_FakeResolutionInfo_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [TestInstanceManagerHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestInstanceManagerHostApi extends _i1.Mock
implements _i3.TestInstanceManagerHostApi {
MockTestInstanceManagerHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void clear() => super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [TestPreviewHostApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestPreviewHostApi extends _i1.Mock
implements _i3.TestPreviewHostApi {
MockTestPreviewHostApi() {
_i1.throwOnMissingStub(this);
}
@override
void create(
int? identifier,
int? rotation,
int? resolutionSelectorId,
) =>
super.noSuchMethod(
Invocation.method(
#create,
[
identifier,
rotation,
resolutionSelectorId,
],
),
returnValueForMissingStub: null,
);
@override
int setSurfaceProvider(int? identifier) => (super.noSuchMethod(
Invocation.method(
#setSurfaceProvider,
[identifier],
),
returnValue: 0,
) as int);
@override
void releaseFlutterSurfaceTexture() => super.noSuchMethod(
Invocation.method(
#releaseFlutterSurfaceTexture,
[],
),
returnValueForMissingStub: null,
);
@override
_i2.ResolutionInfo getResolutionInfo(int? identifier) => (super.noSuchMethod(
Invocation.method(
#getResolutionInfo,
[identifier],
),
returnValue: _FakeResolutionInfo_0(
this,
Invocation.method(
#getResolutionInfo,
[identifier],
),
),
) as _i2.ResolutionInfo);
@override
void setTargetRotation(
int? identifier,
int? rotation,
) =>
super.noSuchMethod(
Invocation.method(
#setTargetRotation,
[
identifier,
rotation,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [ResolutionSelector].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockResolutionSelector extends _i1.Mock
implements _i4.ResolutionSelector {
MockResolutionSelector() {
_i1.throwOnMissingStub(this);
}
}
| packages/packages/camera/camera_android_camerax/test/preview_test.mocks.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/preview_test.mocks.dart",
"repo_id": "packages",
"token_count": 1560
} | 1,121 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/camerax_library.g.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:camera_android_camerax/src/recorder.dart';
import 'package:camera_android_camerax/src/surface.dart';
import 'package:camera_android_camerax/src/video_capture.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'test_camerax_library.g.dart';
import 'video_capture_test.mocks.dart';
@GenerateMocks(
<Type>[TestVideoCaptureHostApi, TestInstanceManagerHostApi, Recorder])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
test('withOutput calls the Java side and returns correct video capture',
() async {
final MockTestVideoCaptureHostApi mockApi = MockTestVideoCaptureHostApi();
TestVideoCaptureHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final Recorder mockRecorder = MockRecorder();
const int mockRecorderId = 2;
instanceManager.addHostCreatedInstance(mockRecorder, mockRecorderId,
onCopy: (_) => MockRecorder());
final VideoCapture videoCapture =
VideoCapture.detached(instanceManager: instanceManager);
const int videoCaptureId = 3;
instanceManager.addHostCreatedInstance(videoCapture, videoCaptureId,
onCopy: (_) => VideoCapture.detached(instanceManager: instanceManager));
when(mockApi.withOutput(mockRecorderId)).thenReturn(videoCaptureId);
expect(
await VideoCapture.withOutput(mockRecorder,
instanceManager: instanceManager),
videoCapture);
verify(mockApi.withOutput(mockRecorderId));
});
test(
'setTargetRotation makes call to set target rotation for VideoCapture instance',
() async {
final MockTestVideoCaptureHostApi mockApi = MockTestVideoCaptureHostApi();
TestVideoCaptureHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int targetRotation = Surface.ROTATION_180;
final VideoCapture videoCapture = VideoCapture.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(
videoCapture,
0,
onCopy: (_) => VideoCapture.detached(instanceManager: instanceManager),
);
await videoCapture.setTargetRotation(targetRotation);
verify(mockApi.setTargetRotation(
instanceManager.getIdentifier(videoCapture), targetRotation));
});
test('getOutput calls the Java side and returns correct Recorder', () async {
final MockTestVideoCaptureHostApi mockApi = MockTestVideoCaptureHostApi();
TestVideoCaptureHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final VideoCapture videoCapture =
VideoCapture.detached(instanceManager: instanceManager);
const int videoCaptureId = 2;
instanceManager.addHostCreatedInstance(videoCapture, videoCaptureId,
onCopy: (_) => VideoCapture.detached(instanceManager: instanceManager));
final Recorder mockRecorder = MockRecorder();
const int mockRecorderId = 3;
instanceManager.addHostCreatedInstance(mockRecorder, mockRecorderId,
onCopy: (_) => Recorder.detached(instanceManager: instanceManager));
when(mockApi.getOutput(videoCaptureId)).thenReturn(mockRecorderId);
expect(await videoCapture.getOutput(), mockRecorder);
verify(mockApi.getOutput(videoCaptureId));
});
test('flutterApiCreateTest', () async {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final VideoCaptureFlutterApi flutterApi = VideoCaptureFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(0);
expect(
instanceManager.getInstanceWithWeakReference(0), isA<VideoCapture>());
});
}
| packages/packages/camera/camera_android_camerax/test/video_capture_test.dart/0 | {
"file_path": "packages/packages/camera/camera_android_camerax/test/video_capture_test.dart",
"repo_id": "packages",
"token_count": 1429
} | 1,122 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import camera_avfoundation;
@import camera_avfoundation.Test;
@import XCTest;
@import AVFoundation;
#import <OCMock/OCMock.h>
#import "MockFLTThreadSafeFlutterResult.h"
@interface CameraMethodChannelTests : XCTestCase
@end
@implementation CameraMethodChannelTests
- (void)testCreate_ShouldCallResultOnMainThread {
CameraPlugin *camera = [[CameraPlugin alloc] initWithRegistry:nil messenger:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"Result finished"];
// Set up mocks for initWithCameraName method
id avCaptureDeviceInputMock = OCMClassMock([AVCaptureDeviceInput class]);
OCMStub([avCaptureDeviceInputMock deviceInputWithDevice:[OCMArg any] error:[OCMArg anyObjectRef]])
.andReturn([AVCaptureInput alloc]);
id avCaptureSessionMock = OCMClassMock([AVCaptureSession class]);
OCMStub([avCaptureSessionMock alloc]).andReturn(avCaptureSessionMock);
OCMStub([avCaptureSessionMock canSetSessionPreset:[OCMArg any]]).andReturn(YES);
MockFLTThreadSafeFlutterResult *resultObject =
[[MockFLTThreadSafeFlutterResult alloc] initWithExpectation:expectation];
// Set up method call
FlutterMethodCall *call = [FlutterMethodCall
methodCallWithMethodName:@"create"
arguments:@{@"resolutionPreset" : @"medium", @"enableAudio" : @(1)}];
[camera createCameraOnSessionQueueWithCreateMethodCall:call result:resultObject];
[self waitForExpectationsWithTimeout:1 handler:nil];
// Verify the result
NSDictionary *dictionaryResult = (NSDictionary *)resultObject.receivedResult;
XCTAssertNotNil(dictionaryResult);
XCTAssert([[dictionaryResult allKeys] containsObject:@"cameraId"]);
}
@end
| packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraMethodChannelTests.m/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraMethodChannelTests.m",
"repo_id": "packages",
"token_count": 582
} | 1,123 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import camera_avfoundation;
@import camera_avfoundation.Test;
@import XCTest;
@import AVFoundation;
#import <OCMock/OCMock.h>
#import "CameraTestUtils.h"
@interface StreamingTests : XCTestCase
@property(readonly, nonatomic) FLTCam *camera;
@property(readonly, nonatomic) CMSampleBufferRef sampleBuffer;
@end
@implementation StreamingTests
- (void)setUp {
dispatch_queue_t captureSessionQueue = dispatch_queue_create("testing", NULL);
_camera = FLTCreateCamWithCaptureSessionQueue(captureSessionQueue);
_sampleBuffer = FLTCreateTestSampleBuffer();
}
- (void)tearDown {
CFRelease(_sampleBuffer);
}
- (void)testExceedMaxStreamingPendingFramesCount {
XCTestExpectation *streamingExpectation = [self
expectationWithDescription:@"Must not call handler over maxStreamingPendingFramesCount"];
id handlerMock = OCMClassMock([FLTImageStreamHandler class]);
OCMStub([handlerMock eventSink]).andReturn(^(id event) {
[streamingExpectation fulfill];
});
id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
[_camera startImageStreamWithMessenger:messenger imageStreamHandler:handlerMock];
XCTKVOExpectation *expectation = [[XCTKVOExpectation alloc] initWithKeyPath:@"isStreamingImages"
object:_camera
expectedValue:@YES];
XCTWaiterResult result = [XCTWaiter waitForExpectations:@[ expectation ] timeout:1];
XCTAssertEqual(result, XCTWaiterResultCompleted);
streamingExpectation.expectedFulfillmentCount = 4;
for (int i = 0; i < 10; i++) {
[_camera captureOutput:nil didOutputSampleBuffer:self.sampleBuffer fromConnection:nil];
}
[self waitForExpectationsWithTimeout:1.0 handler:nil];
}
- (void)testReceivedImageStreamData {
XCTestExpectation *streamingExpectation =
[self expectationWithDescription:
@"Must be able to call the handler again when receivedImageStreamData is called"];
id handlerMock = OCMClassMock([FLTImageStreamHandler class]);
OCMStub([handlerMock eventSink]).andReturn(^(id event) {
[streamingExpectation fulfill];
});
id messenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
[_camera startImageStreamWithMessenger:messenger imageStreamHandler:handlerMock];
XCTKVOExpectation *expectation = [[XCTKVOExpectation alloc] initWithKeyPath:@"isStreamingImages"
object:_camera
expectedValue:@YES];
XCTWaiterResult result = [XCTWaiter waitForExpectations:@[ expectation ] timeout:1];
XCTAssertEqual(result, XCTWaiterResultCompleted);
streamingExpectation.expectedFulfillmentCount = 5;
for (int i = 0; i < 10; i++) {
[_camera captureOutput:nil didOutputSampleBuffer:self.sampleBuffer fromConnection:nil];
}
[_camera receivedImageStreamData];
[_camera captureOutput:nil didOutputSampleBuffer:self.sampleBuffer fromConnection:nil];
[self waitForExpectationsWithTimeout:1.0 handler:nil];
}
@end
| packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/StreamingTest.m/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/example/ios/RunnerTests/StreamingTest.m",
"repo_id": "packages",
"token_count": 1235
} | 1,124 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This header is available in the Test module. Import via "@import camera_avfoundation.Test;"
#import "CameraPlugin.h"
#import "FLTCam.h"
#import "FLTThreadSafeFlutterResult.h"
/// APIs exposed for unit testing.
@interface CameraPlugin ()
/// All FLTCam's state access and capture session related operations should be on run on this queue.
@property(nonatomic, strong) dispatch_queue_t captureSessionQueue;
/// An internal camera object that manages camera's state and performs camera operations.
@property(nonatomic, strong) FLTCam *camera;
/// A thread safe wrapper of the method channel used to send device events such as orientation
/// changes.
@property(nonatomic, strong) FLTThreadSafeMethodChannel *deviceEventMethodChannel;
/// Inject @p FlutterTextureRegistry and @p FlutterBinaryMessenger for unit testing.
- (instancetype)initWithRegistry:(NSObject<FlutterTextureRegistry> *)registry
messenger:(NSObject<FlutterBinaryMessenger> *)messenger
NS_DESIGNATED_INITIALIZER;
/// Hide the default public constructor.
- (instancetype)init NS_UNAVAILABLE;
/// Handles `FlutterMethodCall`s and ensures result is send on the main dispatch queue.
///
/// @param call The method call command object.
/// @param result A wrapper around the `FlutterResult` callback which ensures the callback is called
/// on the main dispatch queue.
- (void)handleMethodCallAsync:(FlutterMethodCall *)call result:(FLTThreadSafeFlutterResult *)result;
/// Called by the @c NSNotificationManager each time the device's orientation is changed.
///
/// @param notification @c NSNotification instance containing a reference to the `UIDevice` object
/// that triggered the orientation change.
- (void)orientationChanged:(NSNotification *)notification;
/// Creates FLTCam on session queue and reports the creation result.
/// @param createMethodCall the create method call
/// @param result a thread safe flutter result wrapper object to report creation result.
- (void)createCameraOnSessionQueueWithCreateMethodCall:(FlutterMethodCall *)createMethodCall
result:(FLTThreadSafeFlutterResult *)result;
@end
| packages/packages/camera/camera_avfoundation/ios/Classes/CameraPlugin_Test.h/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/ios/Classes/CameraPlugin_Test.h",
"repo_id": "packages",
"token_count": 655
} | 1,125 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FLTThreadSafeTextureRegistry.h"
#import "QueueUtils.h"
@interface FLTThreadSafeTextureRegistry ()
@property(nonatomic, strong) NSObject<FlutterTextureRegistry> *registry;
@end
@implementation FLTThreadSafeTextureRegistry
- (instancetype)initWithTextureRegistry:(NSObject<FlutterTextureRegistry> *)registry {
self = [super init];
if (self) {
_registry = registry;
}
return self;
}
- (void)registerTexture:(NSObject<FlutterTexture> *)texture
completion:(void (^)(int64_t))completion {
__weak typeof(self) weakSelf = self;
FLTEnsureToRunOnMainQueue(^{
typeof(self) strongSelf = weakSelf;
if (!strongSelf) return;
completion([strongSelf.registry registerTexture:texture]);
});
}
- (void)textureFrameAvailable:(int64_t)textureId {
__weak typeof(self) weakSelf = self;
FLTEnsureToRunOnMainQueue(^{
[weakSelf.registry textureFrameAvailable:textureId];
});
}
- (void)unregisterTexture:(int64_t)textureId {
__weak typeof(self) weakSelf = self;
FLTEnsureToRunOnMainQueue(^{
[weakSelf.registry unregisterTexture:textureId];
});
}
@end
| packages/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeTextureRegistry.m/0 | {
"file_path": "packages/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeTextureRegistry.m",
"repo_id": "packages",
"token_count": 435
} | 1,126 |
## 2.7.4
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
* Documents `getExposureOffsetStepSize` to return -1 if the device does not support
exposure compensation.
## 2.7.3
* Adds documentation to clarify that platform implementations of the plugin use
resolution presets as target resolutions.
## 2.7.2
* Updates minimum required plugin_platform_interface version to 2.1.7.
## 2.7.1
* Fixes new lint warnings.
## 2.7.0
* Adds support for setting the image file format. See `CameraPlatform.setImageFileFormat`.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 2.6.0
* Adds support to control video fps and bitrate. See `CameraPlatform.createCameraWithSettings`.
## 2.5.2
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.5.1
* Removes obsolete null checks on non-nullable values.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
## 2.5.0
* Adds NV21 as an image stream format (suitable for Android).
* Aligns Dart and Flutter SDK constraints.
## 2.4.1
* Updates links for the merge of flutter/plugins into flutter/packages.
## 2.4.0
* Allows camera to be switched while video recording.
* Updates minimum Flutter version to 3.0.
## 2.3.4
* Updates code for stricter lint checks.
## 2.3.3
* Updates code for stricter lint checks.
## 2.3.2
* Updates MethodChannelCamera to have startVideoRecording call the newer startVideoCapturing.
## 2.3.1
* Exports VideoCaptureOptions to allow dependencies to implement concurrent stream and record.
## 2.3.0
* Adds new capture method for a camera to allow concurrent streaming and recording.
## 2.2.2
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
## 2.2.1
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231).
* Ignores missing return warnings in preparation for [upcoming analysis changes](https://github.com/flutter/flutter/issues/105750).
## 2.2.0
* Adds image streaming to the platform interface.
* Removes unnecessary imports.
## 2.1.6
* Adopts `Object.hash`.
* Removes obsolete dependency on `pedantic`.
## 2.1.5
* Fixes asynchronous exceptions handling of the `initializeCamera` method.
## 2.1.4
* Removes dependency on `meta`.
## 2.1.3
* Update to use the `verify` method introduced in platform_plugin_interface 2.1.0.
## 2.1.2
* Adopts new analysis options and fixes all violations.
## 2.1.1
* Add web-relevant docs to platform interface code.
## 2.1.0
* Introduces interface methods for pausing and resuming the camera preview.
## 2.0.1
* Update platform_plugin_interface version requirement.
## 2.0.0
- Stable null safety release.
## 1.6.0
- Added VideoRecordedEvent to support ending a video recording in the native implementation.
## 1.5.0
- Introduces interface methods for locking and unlocking the capture orientation.
- Introduces interface method for listening to the device orientation.
## 1.4.0
- Added interface methods to support auto focus.
## 1.3.0
- Introduces an option to set the image format when initializing.
## 1.2.0
- Added interface to support automatic exposure.
## 1.1.0
- Added an optional `maxVideoDuration` parameter to the `startVideoRecording` method, which allows implementations to limit the duration of a video recording.
## 1.0.4
- Added the torch option to the FlashMode enum, which when implemented indicates the flash light should be turned on continuously.
## 1.0.3
- Update Flutter SDK constraint.
## 1.0.2
- Added interface methods to support zoom features.
## 1.0.1
- Added interface methods for setting flash mode.
## 1.0.0
- Initial open-source release
| packages/packages/camera/camera_platform_interface/CHANGELOG.md/0 | {
"file_path": "packages/packages/camera/camera_platform_interface/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1168
} | 1,127 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Group of image formats that are comparable across Android and iOS platforms.
enum ImageFormatGroup {
/// The image format does not fit into any specific group.
unknown,
/// Multi-plane YUV 420 format.
///
/// This format is a generic YCbCr format, capable of describing any 4:2:0
/// chroma-subsampled planar or semiplanar buffer (but not fully interleaved),
/// with 8 bits per color sample.
///
/// On Android, this is `android.graphics.ImageFormat.YUV_420_888`. See
/// https://developer.android.com/reference/android/graphics/ImageFormat.html#YUV_420_888
///
/// On iOS, this is `kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange`. See
/// https://developer.apple.com/documentation/corevideo/1563591-pixel_format_identifiers/kcvpixelformattype_420ypcbcr8biplanarvideorange?language=objc
yuv420,
/// 32-bit BGRA.
///
/// On iOS, this is `kCVPixelFormatType_32BGRA`. See
/// https://developer.apple.com/documentation/corevideo/1563591-pixel_format_identifiers/kcvpixelformattype_32bgra?language=objc
bgra8888,
/// 32-big RGB image encoded into JPEG bytes.
///
/// On Android, this is `android.graphics.ImageFormat.JPEG`. See
/// https://developer.android.com/reference/android/graphics/ImageFormat#JPEG
jpeg,
/// YCrCb format used for images, which uses the NV21 encoding format.
///
/// On Android, this is `android.graphics.ImageFormat.NV21`. See
/// https://developer.android.com/reference/android/graphics/ImageFormat#NV21
nv21,
}
/// Extension on [ImageFormatGroup] to stringify the enum
extension ImageFormatGroupName on ImageFormatGroup {
/// returns a String value for [ImageFormatGroup]
/// returns 'unknown' if platform is not supported
/// or if [ImageFormatGroup] is not supported for the platform
String name() {
switch (this) {
case ImageFormatGroup.bgra8888:
return 'bgra8888';
case ImageFormatGroup.yuv420:
return 'yuv420';
case ImageFormatGroup.jpeg:
return 'jpeg';
case ImageFormatGroup.nv21:
return 'nv21';
case ImageFormatGroup.unknown:
return 'unknown';
}
}
}
| packages/packages/camera/camera_platform_interface/lib/src/types/image_format_group.dart/0 | {
"file_path": "packages/packages/camera/camera_platform_interface/lib/src/types/image_format_group.dart",
"repo_id": "packages",
"token_count": 757
} | 1,128 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('FlashMode should contain 4 options', () {
const List<FlashMode> values = FlashMode.values;
expect(values.length, 4);
});
test('FlashMode enum should have items in correct index', () {
const List<FlashMode> values = FlashMode.values;
expect(values[0], FlashMode.off);
expect(values[1], FlashMode.auto);
expect(values[2], FlashMode.always);
expect(values[3], FlashMode.torch);
});
}
| packages/packages/camera/camera_platform_interface/test/types/flash_mode_test.dart/0 | {
"file_path": "packages/packages/camera/camera_platform_interface/test/types/flash_mode_test.dart",
"repo_id": "packages",
"token_count": 230
} | 1,129 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:html';
import 'dart:ui';
import 'package:async/async.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_web/src/camera.dart';
import 'package:camera_web/src/camera_service.dart';
import 'package:camera_web/src/types/types.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:mocktail/mocktail.dart';
import 'helpers/helpers.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('Camera', () {
const int textureId = 1;
late Window window;
late Navigator navigator;
late MediaDevices mediaDevices;
late MediaStream mediaStream;
late CameraService cameraService;
setUp(() {
window = MockWindow();
navigator = MockNavigator();
mediaDevices = MockMediaDevices();
when(() => window.navigator).thenReturn(navigator);
when(() => navigator.mediaDevices).thenReturn(mediaDevices);
cameraService = MockCameraService();
final VideoElement videoElement =
getVideoElementWithBlankStream(const Size(10, 10));
mediaStream = videoElement.captureStream();
when(
() => cameraService.getMediaStreamForOptions(
any(),
cameraId: any(named: 'cameraId'),
),
).thenAnswer((_) => Future<MediaStream>.value(mediaStream));
});
setUpAll(() {
registerFallbackValue(MockCameraOptions());
});
group('initialize', () {
testWidgets(
'calls CameraService.getMediaStreamForOptions '
'with provided options', (WidgetTester tester) async {
final CameraOptions options = CameraOptions(
video: VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.user),
width: const VideoSizeConstraint(ideal: 200),
),
);
final Camera camera = Camera(
textureId: textureId,
options: options,
cameraService: cameraService,
);
await camera.initialize();
verify(
() => cameraService.getMediaStreamForOptions(
options,
cameraId: textureId,
),
).called(1);
});
testWidgets(
'creates a video element '
'with correct properties', (WidgetTester tester) async {
const AudioConstraints audioConstraints =
AudioConstraints(enabled: true);
final VideoConstraints videoConstraints = VideoConstraints(
facingMode: FacingModeConstraint(
CameraType.user,
),
);
final Camera camera = Camera(
textureId: textureId,
options: CameraOptions(
audio: audioConstraints,
video: videoConstraints,
),
cameraService: cameraService,
);
await camera.initialize();
expect(camera.videoElement, isNotNull);
expect(camera.videoElement.autoplay, isFalse);
expect(camera.videoElement.muted, isTrue);
expect(camera.videoElement.srcObject, mediaStream);
expect(camera.videoElement.attributes.keys, contains('playsinline'));
expect(
camera.videoElement.style.transformOrigin, equals('center center'));
expect(camera.videoElement.style.pointerEvents, equals('none'));
expect(camera.videoElement.style.width, equals('100%'));
expect(camera.videoElement.style.height, equals('100%'));
expect(camera.videoElement.style.objectFit, equals('cover'));
});
testWidgets(
'flips the video element horizontally '
'for a back camera', (WidgetTester tester) async {
final VideoConstraints videoConstraints = VideoConstraints(
facingMode: FacingModeConstraint(
CameraType.environment,
),
);
final Camera camera = Camera(
textureId: textureId,
options: CameraOptions(
video: videoConstraints,
),
cameraService: cameraService,
);
await camera.initialize();
expect(camera.videoElement.style.transform, equals('scaleX(-1)'));
});
testWidgets(
'creates a wrapping div element '
'with correct properties', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
expect(camera.divElement, isNotNull);
expect(camera.divElement.style.objectFit, equals('cover'));
expect(camera.divElement.children, contains(camera.videoElement));
});
testWidgets('initializes the camera stream', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
expect(camera.stream, mediaStream);
});
testWidgets(
'throws an exception '
'when CameraService.getMediaStreamForOptions throws',
(WidgetTester tester) async {
final Exception exception =
Exception('A media stream exception occured.');
when(() => cameraService.getMediaStreamForOptions(any(),
cameraId: any(named: 'cameraId'))).thenThrow(exception);
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
expect(
camera.initialize,
throwsA(exception),
);
});
});
group('play', () {
testWidgets('starts playing the video element',
(WidgetTester tester) async {
bool startedPlaying = false;
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
final StreamSubscription<Event> cameraPlaySubscription = camera
.videoElement.onPlay
.listen((Event event) => startedPlaying = true);
await camera.play();
expect(startedPlaying, isTrue);
await cameraPlaySubscription.cancel();
});
testWidgets(
'initializes the camera stream '
'from CameraService.getMediaStreamForOptions '
'if it does not exist', (WidgetTester tester) async {
const CameraOptions options = CameraOptions(
video: VideoConstraints(
width: VideoSizeConstraint(ideal: 100),
),
);
final Camera camera = Camera(
textureId: textureId,
options: options,
cameraService: cameraService,
);
await camera.initialize();
/// Remove the video element's source
/// by stopping the camera.
camera.stop();
await camera.play();
// Should be called twice: for initialize and play.
verify(
() => cameraService.getMediaStreamForOptions(
options,
cameraId: textureId,
),
).called(2);
expect(camera.videoElement.srcObject, mediaStream);
expect(camera.stream, mediaStream);
});
});
group('pause', () {
testWidgets('pauses the camera stream', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
await camera.play();
expect(camera.videoElement.paused, isFalse);
camera.pause();
expect(camera.videoElement.paused, isTrue);
});
});
group('stop', () {
testWidgets('resets the camera stream', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
await camera.play();
camera.stop();
expect(camera.videoElement.srcObject, isNull);
expect(camera.stream, isNull);
});
});
group('takePicture', () {
testWidgets('returns a captured picture', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
await camera.play();
final XFile pictureFile = await camera.takePicture();
expect(pictureFile, isNotNull);
});
group(
'enables the torch mode '
'when taking a picture', () {
late List<MediaStreamTrack> videoTracks;
late MediaStream videoStream;
late VideoElement videoElement;
setUp(() {
videoTracks = <MediaStreamTrack>[
MockMediaStreamTrack(),
MockMediaStreamTrack()
];
videoStream = FakeMediaStream(videoTracks);
videoElement = getVideoElementWithBlankStream(const Size(100, 100))
..muted = true;
when(() => videoTracks.first.applyConstraints(any()))
.thenAnswer((_) async => <dynamic, dynamic>{});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'torch': true,
});
});
testWidgets('if the flash mode is auto', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)
..window = window
..stream = videoStream
..videoElement = videoElement
..flashMode = FlashMode.auto;
await camera.play();
final XFile _ = await camera.takePicture();
verify(
() => videoTracks.first.applyConstraints(<dynamic, dynamic>{
'advanced': <dynamic>[
<dynamic, dynamic>{
'torch': true,
}
]
}),
).called(1);
verify(
() => videoTracks.first.applyConstraints(<dynamic, dynamic>{
'advanced': <dynamic>[
<dynamic, dynamic>{
'torch': false,
}
]
}),
).called(1);
});
testWidgets('if the flash mode is always', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)
..window = window
..stream = videoStream
..videoElement = videoElement
..flashMode = FlashMode.always;
await camera.play();
final XFile _ = await camera.takePicture();
verify(
() => videoTracks.first.applyConstraints(<dynamic, dynamic>{
'advanced': <dynamic>[
<dynamic, dynamic>{
'torch': true,
}
]
}),
).called(1);
verify(
() => videoTracks.first.applyConstraints(<dynamic, dynamic>{
'advanced': <dynamic>[
<dynamic, dynamic>{
'torch': false,
}
]
}),
).called(1);
});
});
});
group('getVideoSize', () {
testWidgets(
'returns a size '
'based on the first video track settings',
(WidgetTester tester) async {
const Size videoSize = Size(1280, 720);
final VideoElement videoElement =
getVideoElementWithBlankStream(videoSize);
mediaStream = videoElement.captureStream();
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
expect(
camera.getVideoSize(),
equals(videoSize),
);
});
testWidgets(
'returns Size.zero '
'if the camera is missing video tracks', (WidgetTester tester) async {
// Create a video stream with no video tracks.
final VideoElement videoElement = VideoElement();
mediaStream = videoElement.captureStream();
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
expect(
camera.getVideoSize(),
equals(Size.zero),
);
});
});
group('setFlashMode', () {
late List<MediaStreamTrack> videoTracks;
late MediaStream videoStream;
setUp(() {
videoTracks = <MediaStreamTrack>[
MockMediaStreamTrack(),
MockMediaStreamTrack()
];
videoStream = FakeMediaStream(videoTracks);
when(() => videoTracks.first.applyConstraints(any()))
.thenAnswer((_) async => <dynamic, dynamic>{});
when(videoTracks.first.getCapabilities)
.thenReturn(<dynamic, dynamic>{});
});
testWidgets('sets the camera flash mode', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'torch': true,
});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'torch': true,
});
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)
..window = window
..stream = videoStream;
const FlashMode flashMode = FlashMode.always;
camera.setFlashMode(flashMode);
expect(
camera.flashMode,
equals(flashMode),
);
});
testWidgets(
'enables the torch mode '
'if the flash mode is torch', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'torch': true,
});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'torch': true,
});
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)
..window = window
..stream = videoStream;
camera.setFlashMode(FlashMode.torch);
verify(
() => videoTracks.first.applyConstraints(<dynamic, dynamic>{
'advanced': <dynamic>[
<dynamic, dynamic>{
'torch': true,
}
]
}),
).called(1);
});
testWidgets(
'disables the torch mode '
'if the flash mode is not torch', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'torch': true,
});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'torch': true,
});
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)
..window = window
..stream = videoStream;
camera.setFlashMode(FlashMode.auto);
verify(
() => videoTracks.first.applyConstraints(<dynamic, dynamic>{
'advanced': <dynamic>[
<dynamic, dynamic>{
'torch': false,
}
]
}),
).called(1);
});
group('throws a CameraWebException', () {
testWidgets(
'with torchModeNotSupported error '
'when there are no media devices', (WidgetTester tester) async {
when(() => navigator.mediaDevices).thenReturn(null);
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)
..window = window
..stream = videoStream;
expect(
() => camera.setFlashMode(FlashMode.always),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.torchModeNotSupported,
),
),
);
});
testWidgets(
'with torchModeNotSupported error '
'when the torch mode is not supported '
'in the browser', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'torch': false,
});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'torch': true,
});
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)
..window = window
..stream = videoStream;
expect(
() => camera.setFlashMode(FlashMode.always),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.torchModeNotSupported,
),
),
);
});
testWidgets(
'with torchModeNotSupported error '
'when the torch mode is not supported '
'by the camera', (WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'torch': true,
});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'torch': false,
});
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)
..window = window
..stream = videoStream;
expect(
() => camera.setFlashMode(FlashMode.always),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.torchModeNotSupported,
),
),
);
});
testWidgets(
'with notStarted error '
'when the camera stream has not been initialized',
(WidgetTester tester) async {
when(mediaDevices.getSupportedConstraints)
.thenReturn(<dynamic, dynamic>{
'torch': true,
});
when(videoTracks.first.getCapabilities).thenReturn(<dynamic, dynamic>{
'torch': true,
});
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)..window = window;
expect(
() => camera.setFlashMode(FlashMode.always),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.notStarted,
),
),
);
});
});
});
group('zoomLevel', () {
group('getMaxZoomLevel', () {
testWidgets(
'returns maximum '
'from CameraService.getZoomLevelCapabilityForCamera',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
videoTrack: MockMediaStreamTrack(),
);
when(() => cameraService.getZoomLevelCapabilityForCamera(camera))
.thenReturn(zoomLevelCapability);
final double maximumZoomLevel = camera.getMaxZoomLevel();
verify(() => cameraService.getZoomLevelCapabilityForCamera(camera))
.called(1);
expect(
maximumZoomLevel,
equals(zoomLevelCapability.maximum),
);
});
});
group('getMinZoomLevel', () {
testWidgets(
'returns minimum '
'from CameraService.getZoomLevelCapabilityForCamera',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
videoTrack: MockMediaStreamTrack(),
);
when(() => cameraService.getZoomLevelCapabilityForCamera(camera))
.thenReturn(zoomLevelCapability);
final double minimumZoomLevel = camera.getMinZoomLevel();
verify(() => cameraService.getZoomLevelCapabilityForCamera(camera))
.called(1);
expect(
minimumZoomLevel,
equals(zoomLevelCapability.minimum),
);
});
});
group('setZoomLevel', () {
testWidgets(
'applies zoom on the video track '
'from CameraService.getZoomLevelCapabilityForCamera',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
final MockMediaStreamTrack videoTrack = MockMediaStreamTrack();
final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
videoTrack: videoTrack,
);
when(() => videoTrack.applyConstraints(any()))
.thenAnswer((_) async {});
when(() => cameraService.getZoomLevelCapabilityForCamera(camera))
.thenReturn(zoomLevelCapability);
const double zoom = 75.0;
camera.setZoomLevel(zoom);
verify(
() => videoTrack.applyConstraints(<dynamic, dynamic>{
'advanced': <dynamic>[
<dynamic, dynamic>{
ZoomLevelCapability.constraintName: zoom,
}
]
}),
).called(1);
});
group('throws a CameraWebException', () {
testWidgets(
'with zoomLevelInvalid error '
'when the provided zoom level is below minimum',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
videoTrack: MockMediaStreamTrack(),
);
when(() => cameraService.getZoomLevelCapabilityForCamera(camera))
.thenReturn(zoomLevelCapability);
expect(
() => camera.setZoomLevel(45.0),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.zoomLevelInvalid,
),
));
});
testWidgets(
'with zoomLevelInvalid error '
'when the provided zoom level is below minimum',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability(
minimum: 50.0,
maximum: 100.0,
videoTrack: MockMediaStreamTrack(),
);
when(() => cameraService.getZoomLevelCapabilityForCamera(camera))
.thenReturn(zoomLevelCapability);
expect(
() => camera.setZoomLevel(105.0),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.zoomLevelInvalid,
),
),
);
});
});
});
});
group('getLensDirection', () {
testWidgets(
'returns a lens direction '
'based on the first video track settings',
(WidgetTester tester) async {
final MockVideoElement videoElement = MockVideoElement();
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)..videoElement = videoElement;
final MockMediaStreamTrack firstVideoTrack = MockMediaStreamTrack();
when(() => videoElement.srcObject).thenReturn(
FakeMediaStream(<MediaStreamTrack>[
firstVideoTrack,
MockMediaStreamTrack(),
]),
);
when(firstVideoTrack.getSettings)
.thenReturn(<dynamic, dynamic>{'facingMode': 'environment'});
when(() => cameraService.mapFacingModeToLensDirection('environment'))
.thenReturn(CameraLensDirection.external);
expect(
camera.getLensDirection(),
equals(CameraLensDirection.external),
);
});
testWidgets(
'returns null '
'if the first video track is missing the facing mode',
(WidgetTester tester) async {
final MockVideoElement videoElement = MockVideoElement();
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)..videoElement = videoElement;
final MockMediaStreamTrack firstVideoTrack = MockMediaStreamTrack();
when(() => videoElement.srcObject).thenReturn(
FakeMediaStream(<MediaStreamTrack>[
firstVideoTrack,
MockMediaStreamTrack(),
]),
);
when(firstVideoTrack.getSettings).thenReturn(<dynamic, dynamic>{});
expect(
camera.getLensDirection(),
isNull,
);
});
testWidgets(
'returns null '
'if the camera is missing video tracks', (WidgetTester tester) async {
// Create a video stream with no video tracks.
final VideoElement videoElement = VideoElement();
mediaStream = videoElement.captureStream();
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
expect(
camera.getLensDirection(),
isNull,
);
});
});
group('getViewType', () {
testWidgets('returns a correct view type', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
expect(
camera.getViewType(),
equals('plugins.flutter.io/camera_$textureId'),
);
});
});
group('video recording', () {
const String supportedVideoType = 'video/webm';
late MediaRecorder mediaRecorder;
bool isVideoTypeSupported(String type) => type == supportedVideoType;
setUp(() {
mediaRecorder = MockMediaRecorder();
when(() => mediaRecorder.onError)
.thenAnswer((_) => const Stream<Event>.empty());
});
group('startVideoRecording', () {
testWidgets(
'creates a media recorder '
'with appropriate options', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
await camera.startVideoRecording();
expect(
camera.mediaRecorder!.stream,
equals(camera.stream),
);
expect(
camera.mediaRecorder!.mimeType,
equals(supportedVideoType),
);
expect(
camera.mediaRecorder!.state,
equals('recording'),
);
});
testWidgets('listens to the media recorder data events',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
await camera.startVideoRecording();
verify(
() => mediaRecorder.addEventListener('dataavailable', any()),
).called(1);
});
testWidgets('listens to the media recorder stop events',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
await camera.startVideoRecording();
verify(
() => mediaRecorder.addEventListener('stop', any()),
).called(1);
});
testWidgets('starts a video recording', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
await camera.startVideoRecording();
verify(mediaRecorder.start).called(1);
});
testWidgets(
'starts a video recording '
'with maxVideoDuration', (WidgetTester tester) async {
const Duration maxVideoDuration = Duration(hours: 1);
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
await camera.startVideoRecording(maxVideoDuration: maxVideoDuration);
verify(() => mediaRecorder.start(maxVideoDuration.inMilliseconds))
.called(1);
});
group('throws a CameraWebException', () {
testWidgets(
'with notSupported error '
'when maxVideoDuration is 0 milliseconds or less',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
expect(
() => camera.startVideoRecording(maxVideoDuration: Duration.zero),
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.notSupported,
),
),
);
});
testWidgets(
'with notSupported error '
'when no video types are supported', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)..isVideoTypeSupported = (String type) => false;
await camera.initialize();
await camera.play();
expect(
camera.startVideoRecording,
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.notSupported,
),
),
);
});
});
});
group('pauseVideoRecording', () {
testWidgets('pauses a video recording', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)..mediaRecorder = mediaRecorder;
await camera.pauseVideoRecording();
verify(mediaRecorder.pause).called(1);
});
testWidgets(
'throws a CameraWebException '
'with videoRecordingNotStarted error '
'if the video recording was not started',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
);
expect(
camera.pauseVideoRecording,
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.videoRecordingNotStarted,
),
),
);
});
});
group('resumeVideoRecording', () {
testWidgets('resumes a video recording', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)..mediaRecorder = mediaRecorder;
await camera.resumeVideoRecording();
verify(mediaRecorder.resume).called(1);
});
testWidgets(
'throws a CameraWebException '
'with videoRecordingNotStarted error '
'if the video recording was not started',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
);
expect(
camera.resumeVideoRecording,
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.videoRecordingNotStarted,
),
),
);
});
});
group('stopVideoRecording', () {
testWidgets(
'stops a video recording and '
'returns the captured file '
'based on all video data parts', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
late void Function(Event) videoDataAvailableListener;
late void Function(Event) videoRecordingStoppedListener;
when(
() => mediaRecorder.addEventListener('dataavailable', any()),
).thenAnswer((Invocation invocation) {
videoDataAvailableListener =
invocation.positionalArguments[1] as void Function(Event);
});
when(
() => mediaRecorder.addEventListener('stop', any()),
).thenAnswer((Invocation invocation) {
videoRecordingStoppedListener =
invocation.positionalArguments[1] as void Function(Event);
});
Blob? finalVideo;
List<Blob>? videoParts;
camera.blobBuilder = (List<Blob> blobs, String videoType) {
videoParts = <Blob>[...blobs];
finalVideo = Blob(blobs, videoType);
return finalVideo!;
};
await camera.startVideoRecording();
final Future<XFile> videoFileFuture = camera.stopVideoRecording();
final Blob capturedVideoPartOne = Blob(<Object>[]);
final Blob capturedVideoPartTwo = Blob(<Object>[]);
final List<Blob> capturedVideoParts = <Blob>[
capturedVideoPartOne,
capturedVideoPartTwo,
];
videoDataAvailableListener(FakeBlobEvent(capturedVideoPartOne));
videoDataAvailableListener(FakeBlobEvent(capturedVideoPartTwo));
videoRecordingStoppedListener(Event('stop'));
final XFile videoFile = await videoFileFuture;
verify(mediaRecorder.stop).called(1);
expect(
videoFile,
isNotNull,
);
expect(
videoFile.mimeType,
equals(supportedVideoType),
);
expect(
videoFile.name,
equals(finalVideo.hashCode.toString()),
);
expect(
videoParts,
equals(capturedVideoParts),
);
});
testWidgets(
'throws a CameraWebException '
'with videoRecordingNotStarted error '
'if the video recording was not started',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
);
expect(
camera.stopVideoRecording,
throwsA(
isA<CameraWebException>()
.having(
(CameraWebException e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(CameraWebException e) => e.code,
'code',
CameraErrorCode.videoRecordingNotStarted,
),
),
);
});
});
group('on video data available', () {
late void Function(Event) videoDataAvailableListener;
setUp(() {
when(
() => mediaRecorder.addEventListener('dataavailable', any()),
).thenAnswer((Invocation invocation) {
videoDataAvailableListener =
invocation.positionalArguments[1] as void Function(Event);
});
});
testWidgets(
'stops a video recording '
'if maxVideoDuration is given and '
'the recording was not stopped manually',
(WidgetTester tester) async {
const Duration maxVideoDuration = Duration(hours: 1);
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
await camera.startVideoRecording(maxVideoDuration: maxVideoDuration);
when(() => mediaRecorder.state).thenReturn('recording');
videoDataAvailableListener(FakeBlobEvent(Blob(<Object>[])));
await Future<void>.microtask(() {});
verify(mediaRecorder.stop).called(1);
});
});
group('on video recording stopped', () {
late void Function(Event) videoRecordingStoppedListener;
setUp(() {
when(
() => mediaRecorder.addEventListener('stop', any()),
).thenAnswer((Invocation invocation) {
videoRecordingStoppedListener =
invocation.positionalArguments[1] as void Function(Event);
});
});
testWidgets('stops listening to the media recorder data events',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
await camera.startVideoRecording();
videoRecordingStoppedListener(Event('stop'));
await Future<void>.microtask(() {});
verify(
() => mediaRecorder.removeEventListener('dataavailable', any()),
).called(1);
});
testWidgets('stops listening to the media recorder stop events',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
await camera.initialize();
await camera.play();
await camera.startVideoRecording();
videoRecordingStoppedListener(Event('stop'));
await Future<void>.microtask(() {});
verify(
() => mediaRecorder.removeEventListener('stop', any()),
).called(1);
});
testWidgets('stops listening to the media recorder errors',
(WidgetTester tester) async {
final StreamController<ErrorEvent> onErrorStreamController =
StreamController<ErrorEvent>();
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = isVideoTypeSupported;
when(() => mediaRecorder.onError)
.thenAnswer((_) => onErrorStreamController.stream);
await camera.initialize();
await camera.play();
await camera.startVideoRecording();
videoRecordingStoppedListener(Event('stop'));
await Future<void>.microtask(() {});
expect(
onErrorStreamController.hasListener,
isFalse,
);
});
});
});
group('dispose', () {
testWidgets("resets the video element's source",
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
await camera.dispose();
expect(camera.videoElement.srcObject, isNull);
});
testWidgets('closes the onEnded stream', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
await camera.dispose();
expect(
camera.onEndedController.isClosed,
isTrue,
);
});
testWidgets('closes the onVideoRecordedEvent stream',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
await camera.dispose();
expect(
camera.videoRecorderController.isClosed,
isTrue,
);
});
testWidgets('closes the onVideoRecordingError stream',
(WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
await camera.initialize();
await camera.dispose();
expect(
camera.videoRecordingErrorController.isClosed,
isTrue,
);
});
});
group('events', () {
group('onVideoRecordedEvent', () {
testWidgets(
'emits a VideoRecordedEvent '
'when a video recording is created', (WidgetTester tester) async {
const Duration maxVideoDuration = Duration(hours: 1);
const String supportedVideoType = 'video/webm';
final MockMediaRecorder mediaRecorder = MockMediaRecorder();
when(() => mediaRecorder.onError)
.thenAnswer((_) => const Stream<Event>.empty());
final Camera camera = Camera(
textureId: 1,
cameraService: cameraService,
)
..mediaRecorder = mediaRecorder
..isVideoTypeSupported = (String type) => type == 'video/webm';
await camera.initialize();
await camera.play();
late void Function(Event) videoDataAvailableListener;
late void Function(Event) videoRecordingStoppedListener;
when(
() => mediaRecorder.addEventListener('dataavailable', any()),
).thenAnswer((Invocation invocation) {
videoDataAvailableListener =
invocation.positionalArguments[1] as void Function(Event);
});
when(
() => mediaRecorder.addEventListener('stop', any()),
).thenAnswer((Invocation invocation) {
videoRecordingStoppedListener =
invocation.positionalArguments[1] as void Function(Event);
});
final StreamQueue<VideoRecordedEvent> streamQueue =
StreamQueue<VideoRecordedEvent>(camera.onVideoRecordedEvent);
await camera.startVideoRecording(maxVideoDuration: maxVideoDuration);
Blob? finalVideo;
camera.blobBuilder = (List<Blob> blobs, String videoType) {
finalVideo = Blob(blobs, videoType);
return finalVideo!;
};
videoDataAvailableListener(FakeBlobEvent(Blob(<Object>[])));
videoRecordingStoppedListener(Event('stop'));
expect(
await streamQueue.next,
equals(
isA<VideoRecordedEvent>()
.having(
(VideoRecordedEvent e) => e.cameraId,
'cameraId',
textureId,
)
.having(
(VideoRecordedEvent e) => e.file,
'file',
isA<XFile>()
.having(
(XFile f) => f.mimeType,
'mimeType',
supportedVideoType,
)
.having(
(XFile f) => f.name,
'name',
finalVideo.hashCode.toString(),
),
)
.having(
(VideoRecordedEvent e) => e.maxVideoDuration,
'maxVideoDuration',
maxVideoDuration,
),
),
);
await streamQueue.cancel();
});
});
group('onEnded', () {
testWidgets(
'emits the default video track '
'when it emits an ended event', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
final StreamQueue<MediaStreamTrack> streamQueue =
StreamQueue<MediaStreamTrack>(camera.onEnded);
await camera.initialize();
final List<MediaStreamTrack> videoTracks =
camera.stream!.getVideoTracks();
final MediaStreamTrack defaultVideoTrack = videoTracks.first;
defaultVideoTrack.dispatchEvent(Event('ended'));
expect(
await streamQueue.next,
equals(defaultVideoTrack),
);
await streamQueue.cancel();
});
testWidgets(
'emits the default video track '
'when the camera is stopped', (WidgetTester tester) async {
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
);
final StreamQueue<MediaStreamTrack> streamQueue =
StreamQueue<MediaStreamTrack>(camera.onEnded);
await camera.initialize();
final List<MediaStreamTrack> videoTracks =
camera.stream!.getVideoTracks();
final MediaStreamTrack defaultVideoTrack = videoTracks.first;
camera.stop();
expect(
await streamQueue.next,
equals(defaultVideoTrack),
);
await streamQueue.cancel();
});
});
group('onVideoRecordingError', () {
testWidgets(
'emits an ErrorEvent '
'when the media recorder fails '
'when recording a video', (WidgetTester tester) async {
final MockMediaRecorder mediaRecorder = MockMediaRecorder();
final StreamController<ErrorEvent> errorController =
StreamController<ErrorEvent>();
final Camera camera = Camera(
textureId: textureId,
cameraService: cameraService,
)..mediaRecorder = mediaRecorder;
when(() => mediaRecorder.onError)
.thenAnswer((_) => errorController.stream);
final StreamQueue<ErrorEvent> streamQueue =
StreamQueue<ErrorEvent>(camera.onVideoRecordingError);
await camera.initialize();
await camera.play();
await camera.startVideoRecording();
final ErrorEvent errorEvent = ErrorEvent('type');
errorController.add(errorEvent);
expect(
await streamQueue.next,
equals(errorEvent),
);
await streamQueue.cancel();
});
});
});
});
}
| packages/packages/camera/camera_web/example/integration_test/camera_test.dart/0 | {
"file_path": "packages/packages/camera/camera_web/example/integration_test/camera_test.dart",
"repo_id": "packages",
"token_count": 24928
} | 1,130 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html' as html;
/// Error codes that may occur during the camera initialization,
/// configuration or video streaming.
class CameraErrorCode {
const CameraErrorCode._(this._type);
final String _type;
@override
String toString() => _type;
/// The camera is not supported.
static const CameraErrorCode notSupported =
CameraErrorCode._('cameraNotSupported');
/// The camera is not found.
static const CameraErrorCode notFound = CameraErrorCode._('cameraNotFound');
/// The camera is not readable.
static const CameraErrorCode notReadable =
CameraErrorCode._('cameraNotReadable');
/// The camera options are impossible to satisfy.
static const CameraErrorCode overconstrained =
CameraErrorCode._('cameraOverconstrained');
/// The camera cannot be used or the permission
/// to access the camera is not granted.
static const CameraErrorCode permissionDenied =
CameraErrorCode._('CameraAccessDenied');
/// The camera options are incorrect or attempted
/// to access the media input from an insecure context.
static const CameraErrorCode type = CameraErrorCode._('cameraType');
/// Some problem occurred that prevented the camera from being used.
static const CameraErrorCode abort = CameraErrorCode._('cameraAbort');
/// The user media support is disabled in the current browser.
static const CameraErrorCode security = CameraErrorCode._('cameraSecurity');
/// The camera metadata is missing.
static const CameraErrorCode missingMetadata =
CameraErrorCode._('cameraMissingMetadata');
/// The camera orientation is not supported.
static const CameraErrorCode orientationNotSupported =
CameraErrorCode._('orientationNotSupported');
/// The camera torch mode is not supported.
static const CameraErrorCode torchModeNotSupported =
CameraErrorCode._('torchModeNotSupported');
/// The camera zoom level is not supported.
static const CameraErrorCode zoomLevelNotSupported =
CameraErrorCode._('zoomLevelNotSupported');
/// The camera zoom level is invalid.
static const CameraErrorCode zoomLevelInvalid =
CameraErrorCode._('zoomLevelInvalid');
/// The camera has not been initialized or started.
static const CameraErrorCode notStarted =
CameraErrorCode._('cameraNotStarted');
/// The video recording was not started.
static const CameraErrorCode videoRecordingNotStarted =
CameraErrorCode._('videoRecordingNotStarted');
/// An unknown camera error.
static const CameraErrorCode unknown = CameraErrorCode._('cameraUnknown');
/// Returns a camera error code based on the media error.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/code
static CameraErrorCode fromMediaError(html.MediaError error) {
switch (error.code) {
case html.MediaError.MEDIA_ERR_ABORTED:
return const CameraErrorCode._('mediaErrorAborted');
case html.MediaError.MEDIA_ERR_NETWORK:
return const CameraErrorCode._('mediaErrorNetwork');
case html.MediaError.MEDIA_ERR_DECODE:
return const CameraErrorCode._('mediaErrorDecode');
case html.MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
return const CameraErrorCode._('mediaErrorSourceNotSupported');
default:
return const CameraErrorCode._('mediaErrorUnknown');
}
}
}
| packages/packages/camera/camera_web/lib/src/types/camera_error_code.dart/0 | {
"file_path": "packages/packages/camera/camera_web/lib/src/types/camera_error_code.dart",
"repo_id": "packages",
"token_count": 981
} | 1,131 |
# Camera Windows Plugin
The Windows implementation of [`camera`][camera].
*Note*: This plugin is under development.
See [missing implementations and limitations](#missing-features-on-the-windows-platform).
## Usage
### Depend on the package
This package is not an [endorsed][endorsed-federated-plugin]
implementation of the [`camera`][camera] plugin, so in addition to depending
on [`camera`][camera] you'll need to
[add `camera_windows` to your pubspec.yaml explicitly][install].
Once you do, you can use the [`camera`][camera] APIs as you normally would.
## Missing features on the Windows platform
### Device orientation
Device orientation detection
is not yet implemented: [issue #97540][device-orientation-issue].
### Pause and Resume video recording
Pausing and resuming the video recording
is not supported due to Windows API limitations.
### Exposure mode, point and offset
Support for explosure mode and offset
is not yet implemented: [issue #97537][camera-control-issue].
Exposure points are not supported due to
limitations of the Windows API.
### Focus mode and point
Support for explosure mode and offset
is not yet implemented: [issue #97537][camera-control-issue].
### Flash mode
Support for flash mode is not yet implemented: [issue #97537][camera-control-issue].
Focus points are not supported due to
current limitations of the Windows API.
### Streaming of frames
Support for image streaming is not yet implemented: [issue #97542][image-streams-issue].
## Error handling
Camera errors can be listened using the platform's `onCameraError` method.
Listening to errors is important, and in certain situations,
disposing of the camera is the only way to reset the situation.
<!-- Links -->
[camera]: https://pub.dev/packages/camera
[endorsed-federated-plugin]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
[install]: https://pub.dev/packages/camera_windows/install
[camera-control-issue]: https://github.com/flutter/flutter/issues/97537
[device-orientation-issue]: https://github.com/flutter/flutter/issues/97540
[image-streams-issue]: https://github.com/flutter/flutter/issues/97542
| packages/packages/camera/camera_windows/README.md/0 | {
"file_path": "packages/packages/camera/camera_windows/README.md",
"repo_id": "packages",
"token_count": 593
} | 1,132 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t* command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments = GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"camera_windows_example", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
| packages/packages/camera/camera_windows/example/windows/runner/main.cpp/0 | {
"file_path": "packages/packages/camera/camera_windows/example/windows/runner/main.cpp",
"repo_id": "packages",
"token_count": 506
} | 1,133 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "camera_plugin.h"
#include <flutter/flutter_view.h>
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <mfapi.h>
#include <mfidl.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <windows.h>
#include <cassert>
#include <chrono>
#include <memory>
#include "capture_device_info.h"
#include "com_heap_ptr.h"
#include "string_utils.h"
namespace camera_windows {
using flutter::EncodableList;
using flutter::EncodableMap;
using flutter::EncodableValue;
namespace {
// Channel events
constexpr char kChannelName[] = "plugins.flutter.io/camera_windows";
constexpr char kAvailableCamerasMethod[] = "availableCameras";
constexpr char kCreateMethod[] = "create";
constexpr char kInitializeMethod[] = "initialize";
constexpr char kTakePictureMethod[] = "takePicture";
constexpr char kStartVideoRecordingMethod[] = "startVideoRecording";
constexpr char kStopVideoRecordingMethod[] = "stopVideoRecording";
constexpr char kPausePreview[] = "pausePreview";
constexpr char kResumePreview[] = "resumePreview";
constexpr char kDisposeMethod[] = "dispose";
constexpr char kCameraNameKey[] = "cameraName";
constexpr char kResolutionPresetKey[] = "resolutionPreset";
constexpr char kEnableAudioKey[] = "enableAudio";
constexpr char kCameraIdKey[] = "cameraId";
constexpr char kMaxVideoDurationKey[] = "maxVideoDuration";
constexpr char kResolutionPresetValueLow[] = "low";
constexpr char kResolutionPresetValueMedium[] = "medium";
constexpr char kResolutionPresetValueHigh[] = "high";
constexpr char kResolutionPresetValueVeryHigh[] = "veryHigh";
constexpr char kResolutionPresetValueUltraHigh[] = "ultraHigh";
constexpr char kResolutionPresetValueMax[] = "max";
const std::string kPictureCaptureExtension = "jpeg";
const std::string kVideoCaptureExtension = "mp4";
// Looks for |key| in |map|, returning the associated value if it is present, or
// a nullptr if not.
const EncodableValue* ValueOrNull(const EncodableMap& map, const char* key) {
auto it = map.find(EncodableValue(key));
if (it == map.end()) {
return nullptr;
}
return &(it->second);
}
// Looks for |key| in |map|, returning the associated int64 value if it is
// present, or std::nullopt if not.
std::optional<int64_t> GetInt64ValueOrNull(const EncodableMap& map,
const char* key) {
auto value = ValueOrNull(map, key);
if (!value) {
return std::nullopt;
}
if (std::holds_alternative<int32_t>(*value)) {
return static_cast<int64_t>(std::get<int32_t>(*value));
}
auto val64 = std::get_if<int64_t>(value);
if (!val64) {
return std::nullopt;
}
return *val64;
}
// Parses resolution preset argument to enum value.
ResolutionPreset ParseResolutionPreset(const std::string& resolution_preset) {
if (resolution_preset.compare(kResolutionPresetValueLow) == 0) {
return ResolutionPreset::kLow;
} else if (resolution_preset.compare(kResolutionPresetValueMedium) == 0) {
return ResolutionPreset::kMedium;
} else if (resolution_preset.compare(kResolutionPresetValueHigh) == 0) {
return ResolutionPreset::kHigh;
} else if (resolution_preset.compare(kResolutionPresetValueVeryHigh) == 0) {
return ResolutionPreset::kVeryHigh;
} else if (resolution_preset.compare(kResolutionPresetValueUltraHigh) == 0) {
return ResolutionPreset::kUltraHigh;
} else if (resolution_preset.compare(kResolutionPresetValueMax) == 0) {
return ResolutionPreset::kMax;
}
return ResolutionPreset::kAuto;
}
// Builds CaptureDeviceInfo object from given device holding device name and id.
std::unique_ptr<CaptureDeviceInfo> GetDeviceInfo(IMFActivate* device) {
assert(device);
auto device_info = std::make_unique<CaptureDeviceInfo>();
ComHeapPtr<wchar_t> name;
UINT32 name_size;
HRESULT hr = device->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME,
&name, &name_size);
if (FAILED(hr)) {
return device_info;
}
ComHeapPtr<wchar_t> id;
UINT32 id_size;
hr = device->GetAllocatedString(
MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK, &id, &id_size);
if (FAILED(hr)) {
return device_info;
}
device_info->SetDisplayName(Utf8FromUtf16(std::wstring(name, name_size)));
device_info->SetDeviceID(Utf8FromUtf16(std::wstring(id, id_size)));
return device_info;
}
// Builds datetime string from current time.
// Used as part of the filenames for captured pictures and videos.
std::string GetCurrentTimeString() {
std::chrono::system_clock::duration now =
std::chrono::system_clock::now().time_since_epoch();
auto s = std::chrono::duration_cast<std::chrono::seconds>(now).count();
auto ms =
std::chrono::duration_cast<std::chrono::milliseconds>(now).count() % 1000;
struct tm newtime;
localtime_s(&newtime, &s);
std::string time_start = "";
time_start.resize(80);
size_t len =
strftime(&time_start[0], time_start.size(), "%Y_%m%d_%H%M%S_", &newtime);
if (len > 0) {
time_start.resize(len);
}
// Add milliseconds to make sure the filename is unique
return time_start + std::to_string(ms);
}
// Builds file path for picture capture.
std::optional<std::string> GetFilePathForPicture() {
ComHeapPtr<wchar_t> known_folder_path;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Pictures, KF_FLAG_CREATE, nullptr,
&known_folder_path);
if (FAILED(hr)) {
return std::nullopt;
}
std::string path = Utf8FromUtf16(std::wstring(known_folder_path));
return path + "\\" + "PhotoCapture_" + GetCurrentTimeString() + "." +
kPictureCaptureExtension;
}
// Builds file path for video capture.
std::optional<std::string> GetFilePathForVideo() {
ComHeapPtr<wchar_t> known_folder_path;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Videos, KF_FLAG_CREATE, nullptr,
&known_folder_path);
if (FAILED(hr)) {
return std::nullopt;
}
std::string path = Utf8FromUtf16(std::wstring(known_folder_path));
return path + "\\" + "VideoCapture_" + GetCurrentTimeString() + "." +
kVideoCaptureExtension;
}
} // namespace
// static
void CameraPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarWindows* registrar) {
auto channel = std::make_unique<flutter::MethodChannel<>>(
registrar->messenger(), kChannelName,
&flutter::StandardMethodCodec::GetInstance());
std::unique_ptr<CameraPlugin> plugin = std::make_unique<CameraPlugin>(
registrar->texture_registrar(), registrar->messenger());
channel->SetMethodCallHandler(
[plugin_pointer = plugin.get()](const auto& call, auto result) {
plugin_pointer->HandleMethodCall(call, std::move(result));
});
registrar->AddPlugin(std::move(plugin));
}
CameraPlugin::CameraPlugin(flutter::TextureRegistrar* texture_registrar,
flutter::BinaryMessenger* messenger)
: texture_registrar_(texture_registrar),
messenger_(messenger),
camera_factory_(std::make_unique<CameraFactoryImpl>()) {}
CameraPlugin::CameraPlugin(flutter::TextureRegistrar* texture_registrar,
flutter::BinaryMessenger* messenger,
std::unique_ptr<CameraFactory> camera_factory)
: texture_registrar_(texture_registrar),
messenger_(messenger),
camera_factory_(std::move(camera_factory)) {}
CameraPlugin::~CameraPlugin() {}
void CameraPlugin::HandleMethodCall(
const flutter::MethodCall<>& method_call,
std::unique_ptr<flutter::MethodResult<>> result) {
const std::string& method_name = method_call.method_name();
if (method_name.compare(kAvailableCamerasMethod) == 0) {
return AvailableCamerasMethodHandler(std::move(result));
} else if (method_name.compare(kCreateMethod) == 0) {
const auto* arguments =
std::get_if<flutter::EncodableMap>(method_call.arguments());
assert(arguments);
return CreateMethodHandler(*arguments, std::move(result));
} else if (method_name.compare(kInitializeMethod) == 0) {
const auto* arguments =
std::get_if<flutter::EncodableMap>(method_call.arguments());
assert(arguments);
return this->InitializeMethodHandler(*arguments, std::move(result));
} else if (method_name.compare(kTakePictureMethod) == 0) {
const auto* arguments =
std::get_if<flutter::EncodableMap>(method_call.arguments());
assert(arguments);
return TakePictureMethodHandler(*arguments, std::move(result));
} else if (method_name.compare(kStartVideoRecordingMethod) == 0) {
const auto* arguments =
std::get_if<flutter::EncodableMap>(method_call.arguments());
assert(arguments);
return StartVideoRecordingMethodHandler(*arguments, std::move(result));
} else if (method_name.compare(kStopVideoRecordingMethod) == 0) {
const auto* arguments =
std::get_if<flutter::EncodableMap>(method_call.arguments());
assert(arguments);
return StopVideoRecordingMethodHandler(*arguments, std::move(result));
} else if (method_name.compare(kPausePreview) == 0) {
const auto* arguments =
std::get_if<flutter::EncodableMap>(method_call.arguments());
assert(arguments);
return PausePreviewMethodHandler(*arguments, std::move(result));
} else if (method_name.compare(kResumePreview) == 0) {
const auto* arguments =
std::get_if<flutter::EncodableMap>(method_call.arguments());
assert(arguments);
return ResumePreviewMethodHandler(*arguments, std::move(result));
} else if (method_name.compare(kDisposeMethod) == 0) {
const auto* arguments =
std::get_if<flutter::EncodableMap>(method_call.arguments());
assert(arguments);
return DisposeMethodHandler(*arguments, std::move(result));
} else {
result->NotImplemented();
}
}
Camera* CameraPlugin::GetCameraByDeviceId(std::string& device_id) {
for (auto it = begin(cameras_); it != end(cameras_); ++it) {
if ((*it)->HasDeviceId(device_id)) {
return it->get();
}
}
return nullptr;
}
Camera* CameraPlugin::GetCameraByCameraId(int64_t camera_id) {
for (auto it = begin(cameras_); it != end(cameras_); ++it) {
if ((*it)->HasCameraId(camera_id)) {
return it->get();
}
}
return nullptr;
}
void CameraPlugin::DisposeCameraByCameraId(int64_t camera_id) {
for (auto it = begin(cameras_); it != end(cameras_); ++it) {
if ((*it)->HasCameraId(camera_id)) {
cameras_.erase(it);
return;
}
}
}
void CameraPlugin::AvailableCamerasMethodHandler(
std::unique_ptr<flutter::MethodResult<>> result) {
// Enumerate devices.
ComHeapPtr<IMFActivate*> devices;
UINT32 count = 0;
if (!this->EnumerateVideoCaptureDeviceSources(&devices, &count)) {
result->Error("System error", "Failed to get available cameras");
// No need to free devices here, cos allocation failed.
return;
}
if (count == 0) {
result->Success(EncodableValue(EncodableList()));
return;
}
// Format found devices to the response.
EncodableList devices_list;
for (UINT32 i = 0; i < count; ++i) {
auto device_info = GetDeviceInfo(devices[i]);
auto deviceName = device_info->GetUniqueDeviceName();
devices_list.push_back(EncodableMap({
{EncodableValue("name"), EncodableValue(deviceName)},
{EncodableValue("lensFacing"), EncodableValue("front")},
{EncodableValue("sensorOrientation"), EncodableValue(0)},
}));
}
result->Success(std::move(EncodableValue(devices_list)));
}
bool CameraPlugin::EnumerateVideoCaptureDeviceSources(IMFActivate*** devices,
UINT32* count) {
return CaptureControllerImpl::EnumerateVideoCaptureDeviceSources(devices,
count);
}
void CameraPlugin::CreateMethodHandler(
const EncodableMap& args, std::unique_ptr<flutter::MethodResult<>> result) {
// Parse enableAudio argument.
const auto* record_audio =
std::get_if<bool>(ValueOrNull(args, kEnableAudioKey));
if (!record_audio) {
return result->Error("argument_error",
std::string(kEnableAudioKey) + " argument missing");
}
// Parse cameraName argument.
const auto* camera_name =
std::get_if<std::string>(ValueOrNull(args, kCameraNameKey));
if (!camera_name) {
return result->Error("argument_error",
std::string(kCameraNameKey) + " argument missing");
}
auto device_info = std::make_unique<CaptureDeviceInfo>();
if (!device_info->ParseDeviceInfoFromCameraName(*camera_name)) {
return result->Error(
"camera_error", "Cannot parse argument " + std::string(kCameraNameKey));
}
auto device_id = device_info->GetDeviceId();
if (GetCameraByDeviceId(device_id)) {
return result->Error("camera_error",
"Camera with given device id already exists. Existing "
"camera must be disposed before creating it again.");
}
std::unique_ptr<camera_windows::Camera> camera =
camera_factory_->CreateCamera(device_id);
if (camera->HasPendingResultByType(PendingResultType::kCreateCamera)) {
return result->Error("camera_error",
"Pending camera creation request exists");
}
if (camera->AddPendingResult(PendingResultType::kCreateCamera,
std::move(result))) {
// Parse resolution preset argument.
const auto* resolution_preset_argument =
std::get_if<std::string>(ValueOrNull(args, kResolutionPresetKey));
ResolutionPreset resolution_preset;
if (resolution_preset_argument) {
resolution_preset = ParseResolutionPreset(*resolution_preset_argument);
} else {
resolution_preset = ResolutionPreset::kAuto;
}
bool initialized = camera->InitCamera(texture_registrar_, messenger_,
*record_audio, resolution_preset);
if (initialized) {
cameras_.push_back(std::move(camera));
}
}
}
void CameraPlugin::InitializeMethodHandler(
const EncodableMap& args, std::unique_ptr<flutter::MethodResult<>> result) {
auto camera_id = GetInt64ValueOrNull(args, kCameraIdKey);
if (!camera_id) {
return result->Error("argument_error",
std::string(kCameraIdKey) + " missing");
}
auto camera = GetCameraByCameraId(*camera_id);
if (!camera) {
return result->Error("camera_error", "Camera not created");
}
if (camera->HasPendingResultByType(PendingResultType::kInitialize)) {
return result->Error("camera_error",
"Pending initialization request exists");
}
if (camera->AddPendingResult(PendingResultType::kInitialize,
std::move(result))) {
auto cc = camera->GetCaptureController();
assert(cc);
cc->StartPreview();
}
}
void CameraPlugin::PausePreviewMethodHandler(
const EncodableMap& args, std::unique_ptr<flutter::MethodResult<>> result) {
auto camera_id = GetInt64ValueOrNull(args, kCameraIdKey);
if (!camera_id) {
return result->Error("argument_error",
std::string(kCameraIdKey) + " missing");
}
auto camera = GetCameraByCameraId(*camera_id);
if (!camera) {
return result->Error("camera_error", "Camera not created");
}
if (camera->HasPendingResultByType(PendingResultType::kPausePreview)) {
return result->Error("camera_error",
"Pending pause preview request exists");
}
if (camera->AddPendingResult(PendingResultType::kPausePreview,
std::move(result))) {
auto cc = camera->GetCaptureController();
assert(cc);
cc->PausePreview();
}
}
void CameraPlugin::ResumePreviewMethodHandler(
const EncodableMap& args, std::unique_ptr<flutter::MethodResult<>> result) {
auto camera_id = GetInt64ValueOrNull(args, kCameraIdKey);
if (!camera_id) {
return result->Error("argument_error",
std::string(kCameraIdKey) + " missing");
}
auto camera = GetCameraByCameraId(*camera_id);
if (!camera) {
return result->Error("camera_error", "Camera not created");
}
if (camera->HasPendingResultByType(PendingResultType::kResumePreview)) {
return result->Error("camera_error",
"Pending resume preview request exists");
}
if (camera->AddPendingResult(PendingResultType::kResumePreview,
std::move(result))) {
auto cc = camera->GetCaptureController();
assert(cc);
cc->ResumePreview();
}
}
void CameraPlugin::StartVideoRecordingMethodHandler(
const EncodableMap& args, std::unique_ptr<flutter::MethodResult<>> result) {
auto camera_id = GetInt64ValueOrNull(args, kCameraIdKey);
if (!camera_id) {
return result->Error("argument_error",
std::string(kCameraIdKey) + " missing");
}
auto camera = GetCameraByCameraId(*camera_id);
if (!camera) {
return result->Error("camera_error", "Camera not created");
}
if (camera->HasPendingResultByType(PendingResultType::kStartRecord)) {
return result->Error("camera_error",
"Pending start recording request exists");
}
int64_t max_video_duration_ms = -1;
auto requested_max_video_duration_ms =
std::get_if<std::int32_t>(ValueOrNull(args, kMaxVideoDurationKey));
if (requested_max_video_duration_ms != nullptr) {
max_video_duration_ms = *requested_max_video_duration_ms;
}
std::optional<std::string> path = GetFilePathForVideo();
if (path) {
if (camera->AddPendingResult(PendingResultType::kStartRecord,
std::move(result))) {
auto cc = camera->GetCaptureController();
assert(cc);
cc->StartRecord(*path, max_video_duration_ms);
}
} else {
return result->Error("system_error",
"Failed to get path for video capture");
}
}
void CameraPlugin::StopVideoRecordingMethodHandler(
const EncodableMap& args, std::unique_ptr<flutter::MethodResult<>> result) {
auto camera_id = GetInt64ValueOrNull(args, kCameraIdKey);
if (!camera_id) {
return result->Error("argument_error",
std::string(kCameraIdKey) + " missing");
}
auto camera = GetCameraByCameraId(*camera_id);
if (!camera) {
return result->Error("camera_error", "Camera not created");
}
if (camera->HasPendingResultByType(PendingResultType::kStopRecord)) {
return result->Error("camera_error",
"Pending stop recording request exists");
}
if (camera->AddPendingResult(PendingResultType::kStopRecord,
std::move(result))) {
auto cc = camera->GetCaptureController();
assert(cc);
cc->StopRecord();
}
}
void CameraPlugin::TakePictureMethodHandler(
const EncodableMap& args, std::unique_ptr<flutter::MethodResult<>> result) {
auto camera_id = GetInt64ValueOrNull(args, kCameraIdKey);
if (!camera_id) {
return result->Error("argument_error",
std::string(kCameraIdKey) + " missing");
}
auto camera = GetCameraByCameraId(*camera_id);
if (!camera) {
return result->Error("camera_error", "Camera not created");
}
if (camera->HasPendingResultByType(PendingResultType::kTakePicture)) {
return result->Error("camera_error", "Pending take picture request exists");
}
std::optional<std::string> path = GetFilePathForPicture();
if (path) {
if (camera->AddPendingResult(PendingResultType::kTakePicture,
std::move(result))) {
auto cc = camera->GetCaptureController();
assert(cc);
cc->TakePicture(*path);
}
} else {
return result->Error("system_error",
"Failed to get capture path for picture");
}
}
void CameraPlugin::DisposeMethodHandler(
const EncodableMap& args, std::unique_ptr<flutter::MethodResult<>> result) {
auto camera_id = GetInt64ValueOrNull(args, kCameraIdKey);
if (!camera_id) {
return result->Error("argument_error",
std::string(kCameraIdKey) + " missing");
}
DisposeCameraByCameraId(*camera_id);
result->Success();
}
} // namespace camera_windows
| packages/packages/camera/camera_windows/windows/camera_plugin.cpp/0 | {
"file_path": "packages/packages/camera/camera_windows/windows/camera_plugin.cpp",
"repo_id": "packages",
"token_count": 7766
} | 1,134 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "record_handler.h"
#include <mfapi.h>
#include <mfcaptureengine.h>
#include <cassert>
#include "string_utils.h"
namespace camera_windows {
using Microsoft::WRL::ComPtr;
// Initializes media type for video capture.
HRESULT BuildMediaTypeForVideoCapture(IMFMediaType* src_media_type,
IMFMediaType** video_record_media_type,
GUID capture_format) {
assert(src_media_type);
ComPtr<IMFMediaType> new_media_type;
HRESULT hr = MFCreateMediaType(&new_media_type);
if (FAILED(hr)) {
return hr;
}
// Clones everything from original media type.
hr = src_media_type->CopyAllItems(new_media_type.Get());
if (FAILED(hr)) {
return hr;
}
hr = new_media_type->SetGUID(MF_MT_SUBTYPE, capture_format);
if (FAILED(hr)) {
return hr;
}
new_media_type.CopyTo(video_record_media_type);
return S_OK;
}
// Queries interface object from collection.
template <class Q>
HRESULT GetCollectionObject(IMFCollection* pCollection, DWORD index,
Q** ppObj) {
ComPtr<IUnknown> pUnk;
HRESULT hr = pCollection->GetElement(index, pUnk.GetAddressOf());
if (FAILED(hr)) {
return hr;
}
return pUnk->QueryInterface(IID_PPV_ARGS(ppObj));
}
// Initializes media type for audo capture.
HRESULT BuildMediaTypeForAudioCapture(IMFMediaType** audio_record_media_type) {
ComPtr<IMFAttributes> audio_output_attributes;
ComPtr<IMFMediaType> src_media_type;
ComPtr<IMFMediaType> new_media_type;
ComPtr<IMFCollection> available_output_types;
DWORD mt_count = 0;
HRESULT hr = MFCreateAttributes(&audio_output_attributes, 1);
if (FAILED(hr)) {
return hr;
}
// Enumerates only low latency audio outputs.
hr = audio_output_attributes->SetUINT32(MF_LOW_LATENCY, TRUE);
if (FAILED(hr)) {
return hr;
}
DWORD mft_flags = (MFT_ENUM_FLAG_ALL & (~MFT_ENUM_FLAG_FIELDOFUSE)) |
MFT_ENUM_FLAG_SORTANDFILTER;
hr = MFTranscodeGetAudioOutputAvailableTypes(
MFAudioFormat_AAC, mft_flags, audio_output_attributes.Get(),
available_output_types.GetAddressOf());
if (FAILED(hr)) {
return hr;
}
hr = GetCollectionObject(available_output_types.Get(), 0,
src_media_type.GetAddressOf());
if (FAILED(hr)) {
return hr;
}
hr = available_output_types->GetElementCount(&mt_count);
if (FAILED(hr)) {
return hr;
}
if (mt_count == 0) {
// No sources found, mark process as failure.
return E_FAIL;
}
// Create new media type to copy original media type to.
hr = MFCreateMediaType(&new_media_type);
if (FAILED(hr)) {
return hr;
}
hr = src_media_type->CopyAllItems(new_media_type.Get());
if (FAILED(hr)) {
return hr;
}
new_media_type.CopyTo(audio_record_media_type);
return hr;
}
HRESULT RecordHandler::InitRecordSink(IMFCaptureEngine* capture_engine,
IMFMediaType* base_media_type) {
assert(!file_path_.empty());
assert(capture_engine);
assert(base_media_type);
HRESULT hr = S_OK;
if (record_sink_) {
// If record sink already exists, only update output filename.
hr = record_sink_->SetOutputFileName(Utf16FromUtf8(file_path_).c_str());
if (FAILED(hr)) {
record_sink_ = nullptr;
}
return hr;
}
ComPtr<IMFMediaType> video_record_media_type;
ComPtr<IMFCaptureSink> capture_sink;
// Gets sink from capture engine with record type.
hr = capture_engine->GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_RECORD,
&capture_sink);
if (FAILED(hr)) {
return hr;
}
hr = capture_sink.As(&record_sink_);
if (FAILED(hr)) {
return hr;
}
// Removes existing streams if available.
hr = record_sink_->RemoveAllStreams();
if (FAILED(hr)) {
return hr;
}
hr = BuildMediaTypeForVideoCapture(base_media_type,
video_record_media_type.GetAddressOf(),
MFVideoFormat_H264);
if (FAILED(hr)) {
return hr;
}
DWORD video_record_sink_stream_index;
hr = record_sink_->AddStream(
(DWORD)MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_VIDEO_RECORD,
video_record_media_type.Get(), nullptr, &video_record_sink_stream_index);
if (FAILED(hr)) {
return hr;
}
if (record_audio_) {
ComPtr<IMFMediaType> audio_record_media_type;
HRESULT audio_capture_hr = S_OK;
audio_capture_hr =
BuildMediaTypeForAudioCapture(audio_record_media_type.GetAddressOf());
if (SUCCEEDED(audio_capture_hr)) {
DWORD audio_record_sink_stream_index;
hr = record_sink_->AddStream(
(DWORD)MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_AUDIO,
audio_record_media_type.Get(), nullptr,
&audio_record_sink_stream_index);
}
if (FAILED(hr)) {
return hr;
}
}
hr = record_sink_->SetOutputFileName(Utf16FromUtf8(file_path_).c_str());
return hr;
}
HRESULT RecordHandler::StartRecord(const std::string& file_path,
int64_t max_duration,
IMFCaptureEngine* capture_engine,
IMFMediaType* base_media_type) {
assert(!file_path.empty());
assert(capture_engine);
assert(base_media_type);
type_ = max_duration < 0 ? RecordingType::kContinuous : RecordingType::kTimed;
max_video_duration_ms_ = max_duration;
file_path_ = file_path;
recording_start_timestamp_us_ = -1;
recording_duration_us_ = 0;
HRESULT hr = InitRecordSink(capture_engine, base_media_type);
if (FAILED(hr)) {
return hr;
}
recording_state_ = RecordState::kStarting;
return capture_engine->StartRecord();
}
HRESULT RecordHandler::StopRecord(IMFCaptureEngine* capture_engine) {
if (recording_state_ == RecordState::kRunning) {
recording_state_ = RecordState::kStopping;
return capture_engine->StopRecord(true, false);
}
return E_FAIL;
}
void RecordHandler::OnRecordStarted() {
if (recording_state_ == RecordState::kStarting) {
recording_state_ = RecordState::kRunning;
}
}
void RecordHandler::OnRecordStopped() {
if (recording_state_ == RecordState::kStopping) {
file_path_ = "";
recording_start_timestamp_us_ = -1;
recording_duration_us_ = 0;
max_video_duration_ms_ = -1;
recording_state_ = RecordState::kNotStarted;
type_ = RecordingType::kNone;
}
}
void RecordHandler::UpdateRecordingTime(uint64_t timestamp) {
if (recording_start_timestamp_us_ < 0) {
recording_start_timestamp_us_ = timestamp;
}
recording_duration_us_ = (timestamp - recording_start_timestamp_us_);
}
bool RecordHandler::ShouldStopTimedRecording() const {
return type_ == RecordingType::kTimed &&
recording_state_ == RecordState::kRunning &&
max_video_duration_ms_ > 0 &&
recording_duration_us_ >=
(static_cast<uint64_t>(max_video_duration_ms_) * 1000);
}
} // namespace camera_windows
| packages/packages/camera/camera_windows/windows/record_handler.cpp/0 | {
"file_path": "packages/packages/camera/camera_windows/windows/record_handler.cpp",
"repo_id": "packages",
"token_count": 2998
} | 1,135 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'package:cross_file/cross_file.dart';
/// Demonstrate instantiating an XFile for the README.
Future<XFile> instantiateXFile() async {
// #docregion Instantiate
final XFile file = XFile('assets/hello.txt');
print('File information:');
print('- Path: ${file.path}');
print('- Name: ${file.name}');
print('- MIME type: ${file.mimeType}');
final String fileContent = await file.readAsString();
print('Content of the file: $fileContent');
// #enddocregion Instantiate
return file;
}
| packages/packages/cross_file/example/lib/readme_excerpts.dart/0 | {
"file_path": "packages/packages/cross_file/example/lib/readme_excerpts.dart",
"repo_id": "packages",
"token_count": 216
} | 1,136 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 1.1.4
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Improves README example and updates it to use code excerpts.
## 1.1.3
- Adds pub topics to package metadata.
## 1.1.2
- Updates the `Color` documentation link in the README.
- Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
- Aligns Dart and Flutter SDK constraints.
- Updates package description.
## 1.1.1
- Moved source to flutter/packages
## 1.1.0
- Add support for null safety
- Update SDK constraints
## 1.0.0
- Add SDK constraints for Dart and Flutter
## 1.0.0
- Initial version
| packages/packages/css_colors/CHANGELOG.md/0 | {
"file_path": "packages/packages/css_colors/CHANGELOG.md",
"repo_id": "packages",
"token_count": 219
} | 1,137 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:dynamic_layouts/dynamic_layouts.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets(
'DynamicGridView generates children and checks if they are layed out',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
10,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
width: index.isEven ? 95 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView(
gridDelegate: const SliverGridDelegateWithWrapping(),
children: children,
),
),
),
);
// Check that the children are in the tree
for (int i = 0; i < 10; i++) {
expect(find.text('Item $i'), findsOneWidget);
}
// Check that the children are in the right position
expect(tester.getTopLeft(find.text('Item 0')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 1')), const Offset(95.0, 0.0));
expect(tester.getTopLeft(find.text('Item 2')), const Offset(275.0, 0.0));
expect(tester.getTopLeft(find.text('Item 3')), const Offset(370.0, 0.0));
expect(tester.getTopLeft(find.text('Item 4')), const Offset(550.0, 0.0));
expect(tester.getTopLeft(find.text('Item 5')), const Offset(0.0, 100.0));
expect(tester.getTopLeft(find.text('Item 6')), const Offset(180.0, 100.0));
expect(tester.getTopLeft(find.text('Item 7')), const Offset(275.0, 100.0));
expect(tester.getTopLeft(find.text('Item 8')), const Offset(455.0, 100.0));
expect(tester.getTopLeft(find.text('Item 9')), const Offset(550.0, 100.0));
});
testWidgets(
'Test for wrap that generates children and checks if they are layed out',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
10,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
width: index.isEven ? 95 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.wrap(
children: children,
),
),
),
);
for (int i = 0; i < 10; i++) {
expect(find.text('Item $i'), findsOneWidget);
}
// Check that the children are in the right position
expect(tester.getTopLeft(find.text('Item 0')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 1')), const Offset(95.0, 0.0));
expect(tester.getTopLeft(find.text('Item 2')), const Offset(275.0, 0.0));
expect(tester.getTopLeft(find.text('Item 3')), const Offset(370.0, 0.0));
expect(tester.getTopLeft(find.text('Item 4')), const Offset(550.0, 0.0));
expect(tester.getTopLeft(find.text('Item 5')), const Offset(0.0, 100.0));
expect(tester.getTopLeft(find.text('Item 6')), const Offset(180.0, 100.0));
expect(tester.getTopLeft(find.text('Item 7')), const Offset(275.0, 100.0));
expect(tester.getTopLeft(find.text('Item 8')), const Offset(455.0, 100.0));
expect(tester.getTopLeft(find.text('Item 9')), const Offset(550.0, 100.0));
});
testWidgets('Test for wrap to be laying child dynamically',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
20,
(int index) => SizedBox(
height: index.isEven ? 1000 : 50,
width: index.isEven ? 95 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.builder(
itemCount: children.length,
gridDelegate: const SliverGridDelegateWithWrapping(),
itemBuilder: (BuildContext context, int index) => children[index],
),
),
),
);
for (int i = 0; i < 5; i++) {
expect(find.text('Item $i'), findsOneWidget);
}
// Check that the children are in the right position
expect(tester.getTopLeft(find.text('Item 0')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 1')), const Offset(95.0, 0.0));
expect(tester.getTopLeft(find.text('Item 2')), const Offset(275.0, 0.0));
expect(tester.getTopLeft(find.text('Item 3')), const Offset(370.0, 0.0));
expect(tester.getTopLeft(find.text('Item 4')), const Offset(550.0, 0.0));
expect(find.text('Item 5'), findsNothing);
await tester.scrollUntilVisible(find.text('Item 19'), 500.0);
await tester.pumpAndSettle();
expect(find.text('Item 18'), findsOneWidget);
expect(tester.getTopLeft(find.text('Item 18')), const Offset(455.0, 0.0));
expect(find.text('Item 0'), findsNothing);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 2'), findsNothing);
expect(find.text('Item 3'), findsNothing);
});
testWidgets(
'Test for DynamicGridView.wrap to scrollDirection Axis.horizontal',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
20,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
width: index.isEven ? 100 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.wrap(
scrollDirection: Axis.horizontal,
children: children,
),
),
),
);
for (int i = 0; i < 20; i++) {
expect(find.text('Item $i'), findsOneWidget);
}
// Check that the children are in the right position
double dy = 0, dx = 0;
for (int i = 0; i < 20; i++) {
if (dy >= 600.0) {
dy = 0.0;
dx += 180.0;
}
expect(tester.getTopLeft(find.text('Item $i')), Offset(dx, dy));
dy += i.isEven ? 100 : 50;
}
});
testWidgets('Test DynamicGridView.builder for GridView.reverse to true',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
10,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
width: index.isEven ? 100 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.builder(
reverse: true,
itemCount: children.length,
gridDelegate: const SliverGridDelegateWithWrapping(),
itemBuilder: (BuildContext context, int index) => children[index],
),
),
),
);
for (int i = 0; i < 10; i++) {
expect(find.text('Item $i'), findsOneWidget);
}
double dx = 0.0, dy = 600.0;
for (int i = 0; i < 10; i++) {
if (dx >= 600.0) {
dx = 0.0;
dy -= 100.0;
}
expect(tester.getBottomLeft(find.text('Item $i')), Offset(dx, dy));
dx += i.isEven ? 100 : 180;
}
});
testWidgets('DynamicGridView.wrap for GridView.reverse to true',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
20,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
width: index.isEven ? 100 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.wrap(
reverse: true,
children: children,
),
),
),
);
for (int i = 0; i < 20; i++) {
expect(find.text('Item $i'), findsOneWidget);
}
// Check that the children are in the right position
double dx = 0.0, dy = 600.0;
for (int i = 0; i < 20; i++) {
if (dx >= 600.0) {
dx = 0.0;
dy -= 100.0;
}
expect(tester.getBottomLeft(find.text('Item $i')), Offset(dx, dy));
dx += i.isEven ? 100 : 180;
}
});
testWidgets('DynamicGridView.wrap dismiss keyboard onDrag test',
(WidgetTester tester) async {
final List<FocusNode> focusNodes =
List<FocusNode>.generate(50, (int i) => FocusNode());
await tester.pumpWidget(
textFieldBoilerplate(
child: GridView.extent(
padding: EdgeInsets.zero,
maxCrossAxisExtent: 300,
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
children: focusNodes.map((FocusNode focusNode) {
return Container(
height: 50,
color: Colors.green,
child: TextField(
focusNode: focusNode,
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
);
}).toList(),
),
),
);
final Finder finder = find.byType(TextField).first;
final TextField textField = tester.widget(finder);
await tester.showKeyboard(finder);
expect(textField.focusNode!.hasFocus, isTrue);
await tester.drag(finder, const Offset(0.0, -40.0));
await tester.pumpAndSettle();
expect(textField.focusNode!.hasFocus, isFalse);
});
testWidgets('ChildMainAxisExtent & childCrossAxisExtent are respected',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
10,
(int index) => SizedBox(
key: Key(index.toString()),
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.builder(
gridDelegate: const SliverGridDelegateWithWrapping(
childMainAxisExtent: 150,
childCrossAxisExtent: 200,
),
itemCount: children.length,
itemBuilder: (BuildContext context, int index) => children[index],
),
),
),
);
for (int i = 0; i < 10; i++) {
final Size sizeOfCurrent = tester.getSize(find.byKey(Key('$i')));
expect(sizeOfCurrent.width, equals(200));
expect(sizeOfCurrent.height, equals(150));
}
// Check that the children are in the right position
double dy = 0, dx = 0;
for (int i = 0; i < 10; i++) {
if (dx > 600.0) {
dx = 0.0;
dy += 150.0;
}
expect(tester.getTopLeft(find.text('Item $i')), Offset(dx, dy));
dx += 200;
}
});
testWidgets('ChildMainAxisExtent is respected', (WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
10,
(int index) => SizedBox(
key: Key(index.toString()),
width: index.isEven ? 100 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.builder(
gridDelegate: const SliverGridDelegateWithWrapping(
childMainAxisExtent: 200,
),
itemCount: children.length,
itemBuilder: (BuildContext context, int index) => children[index],
),
),
),
);
for (int i = 0; i < 10; i++) {
final Size sizeOfCurrent = tester.getSize(find.byKey(Key('$i')));
expect(sizeOfCurrent.height, equals(200));
}
// Check that the children are in the right position
double dy = 0, dx = 0;
for (int i = 0; i < 10; i++) {
if (dx >= 600.0) {
dx = 0.0;
dy += 200.0;
}
expect(tester.getTopLeft(find.text('Item $i')), Offset(dx, dy));
dx += i.isEven ? 100 : 180;
}
});
testWidgets('ChildCrossAxisExtent is respected', (WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
10,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
key: Key(index.toString()),
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.builder(
gridDelegate: const SliverGridDelegateWithWrapping(
childCrossAxisExtent: 150,
),
itemCount: children.length,
itemBuilder: (BuildContext context, int index) => children[index],
),
),
),
);
for (int i = 0; i < 10; i++) {
final Size sizeOfCurrent = tester.getSize(find.byKey(Key('$i')));
expect(sizeOfCurrent.width, equals(150));
}
// Check that the children are in the right position
double dy = 0, dx = 0;
for (int i = 0; i < 10; i++) {
if (dx >= 750.0) {
dx = 0.0;
dy += 100.0;
}
expect(tester.getTopLeft(find.text('Item $i')), Offset(dx, dy));
dx += 150;
}
});
testWidgets('Test wrap to see nothing affected if elements are deleted.',
(WidgetTester tester) async {
late StateSetter stateSetter;
final List<Widget> children = List<Widget>.generate(
10,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
width: index.isEven ? 100 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return DynamicGridView.builder(
gridDelegate: const SliverGridDelegateWithWrapping(),
itemCount: children.length,
itemBuilder: (BuildContext context, int index) => children[index],
);
}),
),
),
);
// See if the children are in the tree.
for (int i = 0; i < 10; i++) {
expect(find.text('Item $i'), findsOneWidget);
}
// See if they are layed properly.
double dx = 0.0, dy = 0.0;
for (int i = 0; i < 10; i++) {
if (dx >= 600) {
dx = 0.0;
dy += 100;
}
expect(tester.getTopLeft(find.text('Item $i')), Offset(dx, dy));
dx += i.isEven ? 100 : 180;
}
stateSetter(() {
// Remove children
children.removeAt(0);
children.removeAt(8);
children.removeAt(5);
});
await tester.pump();
// See if the proper widgets are in the tree.
expect(find.text('Item 0'), findsNothing);
expect(find.text('Item 6'), findsNothing);
expect(find.text('Item 9'), findsNothing);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 2'), findsOneWidget);
expect(find.text('Item 3'), findsOneWidget);
expect(find.text('Item 4'), findsOneWidget);
expect(find.text('Item 5'), findsOneWidget);
expect(find.text('Item 7'), findsOneWidget);
expect(find.text('Item 8'), findsOneWidget);
// See if the proper widgets are in the tree.
expect(tester.getTopLeft(find.text('Item 1')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 2')), const Offset(180.0, 0.0));
expect(tester.getTopLeft(find.text('Item 3')), const Offset(280.0, 0.0));
expect(tester.getTopLeft(find.text('Item 4')), const Offset(460.0, 0.0));
expect(tester.getTopLeft(find.text('Item 5')), const Offset(560.0, 0.0));
expect(tester.getTopLeft(find.text('Item 7')), const Offset(0.0, 100.0));
expect(tester.getTopLeft(find.text('Item 8')), const Offset(180.0, 100.0));
});
testWidgets('Test wrap in Axis.vertical direction',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
5,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
width: index.isEven ? 100 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.builder(
itemCount: children.length,
gridDelegate: const SliverGridDelegateWithWrapping(),
itemBuilder: (BuildContext context, int index) => children[index],
),
),
),
);
// Change the size of the screen
await tester.binding.setSurfaceSize(const Size(500, 100));
await tester.pumpAndSettle();
expect(find.text('Item 0'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 2'), findsOneWidget);
expect(tester.getTopLeft(find.text('Item 0')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 1')), const Offset(100.0, 0.0));
expect(tester.getTopLeft(find.text('Item 2')), const Offset(280.0, 0.0));
expect(find.text('Item 3'), findsNothing);
expect(find.text('Item 4'), findsNothing);
await tester.binding.setSurfaceSize(const Size(560, 100));
await tester.pumpAndSettle();
expect(find.text('Item 3'), findsOneWidget);
expect(tester.getTopLeft(find.text('Item 3')), const Offset(380.0, 0.0));
expect(find.text('Item 4'), findsNothing);
await tester.binding.setSurfaceSize(const Size(280, 100));
// resets the screen to its original size after the test end
addTearDown(tester.view.resetPhysicalSize);
await tester.pumpAndSettle();
expect(find.text('Item 0'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(tester.getTopLeft(find.text('Item 0')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 1')), const Offset(100.0, 0.0));
expect(find.text('Item 2'), findsNothing);
expect(find.text('Item 3'), findsNothing);
expect(find.text('Item 4'), findsNothing);
});
testWidgets('Test wrap in Axis.horizontal direction',
(WidgetTester tester) async {
final List<Widget> children = List<Widget>.generate(
5,
(int index) => SizedBox(
height: index.isEven ? 100 : 50,
width: index.isEven ? 100 : 180,
child: Text('Item $index'),
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DynamicGridView.wrap(
scrollDirection: Axis.horizontal,
children: children,
),
),
),
);
// Change the size of the screen
await tester.binding.setSurfaceSize(const Size(180, 150));
await tester.pumpAndSettle();
expect(find.text('Item 0'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(tester.getTopLeft(find.text('Item 0')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 1')), const Offset(0.0, 100.0));
expect(find.text('Item 2'), findsNothing);
expect(find.text('Item 3'), findsNothing);
await tester.binding.setSurfaceSize(const Size(180, 400));
await tester.pumpAndSettle();
expect(find.text('Item 0'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 2'), findsOneWidget);
expect(find.text('Item 3'), findsOneWidget);
expect(find.text('Item 4'), findsOneWidget);
expect(tester.getTopLeft(find.text('Item 0')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 1')), const Offset(0.0, 100.0));
expect(tester.getTopLeft(find.text('Item 2')), const Offset(0.0, 150.0));
expect(tester.getTopLeft(find.text('Item 3')), const Offset(0.0, 250.0));
expect(tester.getTopLeft(find.text('Item 4')), const Offset(0.0, 300.0));
await tester.binding.setSurfaceSize(const Size(560, 100));
// resets the screen to its original size after the test end
addTearDown(tester.view.resetPhysicalSize);
await tester.pumpAndSettle();
expect(find.text('Item 0'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 2'), findsOneWidget);
expect(find.text('Item 3'), findsOneWidget);
expect(find.text('Item 4'), findsNothing);
expect(tester.getTopLeft(find.text('Item 0')), Offset.zero);
expect(tester.getTopLeft(find.text('Item 1')), const Offset(100.0, 0.0));
expect(tester.getTopLeft(find.text('Item 2')), const Offset(280.0, 0.0));
expect(tester.getTopLeft(find.text('Item 3')), const Offset(380.0, 0.0));
});
}
Widget textFieldBoilerplate({required Widget child}) {
return MaterialApp(
home: Localizations(
locale: const Locale('en', 'US'),
delegates: <LocalizationsDelegate<dynamic>>[
WidgetsLocalizationsDelegate(),
MaterialLocalizationsDelegate(),
],
child: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(size: Size(800.0, 600.0)),
child: Center(
child: Material(
child: child,
),
),
),
),
),
);
}
class MaterialLocalizationsDelegate
extends LocalizationsDelegate<MaterialLocalizations> {
@override
bool isSupported(Locale locale) => true;
@override
Future<MaterialLocalizations> load(Locale locale) =>
DefaultMaterialLocalizations.load(locale);
@override
bool shouldReload(MaterialLocalizationsDelegate old) => false;
}
class WidgetsLocalizationsDelegate
extends LocalizationsDelegate<WidgetsLocalizations> {
@override
bool isSupported(Locale locale) => true;
@override
Future<WidgetsLocalizations> load(Locale locale) =>
DefaultWidgetsLocalizations.load(locale);
@override
bool shouldReload(WidgetsLocalizationsDelegate old) => false;
}
| packages/packages/dynamic_layouts/test/wrap_layout_test.dart/0 | {
"file_path": "packages/packages/dynamic_layouts/test/wrap_layout_test.dart",
"repo_id": "packages",
"token_count": 9164
} | 1,138 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.action;
import androidx.test.annotation.ExperimentalTestApi;
import androidx.test.espresso.flutter.api.WidgetAction;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.Nonnull;
/** A collection of actions that can be performed on {@code FlutterView}s or Flutter widgets. */
public final class FlutterActions {
private static final ExecutorService taskExecutor = Executors.newCachedThreadPool();
// Do not initialize.
private FlutterActions() {}
/**
* Returns a click action that can be performed on a Flutter widget.
*
* <p>The current implementation simply clicks at the center of the widget (with no visibility
* checks yet). Internally, it calculates the coordinates to click on screen based on the position
* of the matched Flutter widget and also its outer Flutter view, and injects gesture events to
* the Android system to mimic a human's click.
*
* <p>Try {@link #syntheticClick()} only when this action cannot handle your case properly, e.g.
* Flutter's internal state (only accessible within Flutter) affects how the action should
* performed.
*/
public static WidgetAction click() {
return new ClickAction(taskExecutor);
}
/**
* Returns a synthetic click action that can be performed on a Flutter widget.
*
* <p>Note, this is not a real click gesture event issued from Android system. Espresso delegates
* to Flutter engine to perform the action.
*
* <p>Always prefer {@link #click()} as it exercises the entire Flutter stack and your Flutter app
* by directly injecting key events to the Android system. Uses this {@link #syntheticClick()}
* only when there are special cases that {@link #click()} cannot handle properly.
*/
@ExperimentalTestApi()
public static WidgetAction syntheticClick() {
return new SyntheticClickAction();
}
/**
* Returns an action that focuses on the widget (by clicking on it) and types the provided string
* into the widget. Appending a \n to the end of the string translates to a ENTER key event. Note:
* this method performs a tap on the widget before typing to force the widget into focus, if the
* widget already contains text this tap may place the cursor at an arbitrary position within the
* text.
*
* <p>The Flutter widget must support input methods.
*
* @param stringToBeTyped the text String that shall be input to the matched widget. Cannot be
* {@code null}.
*/
public static WidgetAction typeText(@Nonnull String stringToBeTyped) {
return new FlutterTypeTextAction(stringToBeTyped, taskExecutor);
}
/**
* Returns an action that scrolls to the widget.
*
* <p>The widget must be a descendant of a scrollable widget like SingleChildScrollView.
*/
public static WidgetAction scrollTo() {
return new FlutterScrollToAction();
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/FlutterActions.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/action/FlutterActions.java",
"repo_id": "packages",
"token_count": 877
} | 1,139 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.common;
import java.util.concurrent.TimeUnit;
/** A utility class to hold various constants used by the Espresso-Flutter library. */
public final class Constants {
// Do not initialize.
private Constants() {}
/** Default timeout for actions and asserts like {@code WidgetAction}. */
public static final Duration DEFAULT_INTERACTION_TIMEOUT = new Duration(10, TimeUnit.SECONDS);
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/common/Constants.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/common/Constants.java",
"repo_id": "packages",
"token_count": 159
} | 1,140 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.internal.protocol.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import androidx.test.espresso.flutter.internal.jsonrpc.message.JsonRpcResponse;
import androidx.test.espresso.flutter.internal.protocol.impl.GetOffsetAction.OffsetType;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.Expose;
/**
* Represents the {@code result} section in a {@code JsonRpcResponse} that's the response of a
* {@code GetOffsetAction}.
*/
final class GetOffsetResponse {
private static final Gson gson = new Gson();
@Expose private boolean isError;
@Expose private Coordinates response;
@Expose private String type;
private GetOffsetResponse() {}
/**
* Builds the {@code GetOffsetResponse} out of the JSON-RPC response.
*
* @param jsonRpcResponse the JSON-RPC response. Cannot be {@code null}.
* @return a {@code GetOffsetResponse} instance that's parsed out from the JSON-RPC response.
*/
public static GetOffsetResponse fromJsonRpcResponse(JsonRpcResponse jsonRpcResponse) {
checkNotNull(jsonRpcResponse, "The JSON-RPC response cannot be null.");
if (jsonRpcResponse.getResult() == null) {
throw new FlutterProtocolException(
String.format(
"Error occurred during retrieving a Flutter widget's geometry info. Response"
+ " received: %s.",
jsonRpcResponse));
}
try {
return gson.fromJson(jsonRpcResponse.getResult(), GetOffsetResponse.class);
} catch (JsonSyntaxException e) {
throw new FlutterProtocolException(
String.format(
"Error occurred during retrieving a Flutter widget's geometry info. Response"
+ " received: %s.",
jsonRpcResponse),
e);
}
}
/** Returns whether this is an error response. */
public boolean isError() {
return isError;
}
/** Returns the vertex position. */
public OffsetType getType() {
return OffsetType.fromString(type);
}
/** Returns the X-Coordinate. */
public float getX() {
if (response == null) {
throw new FlutterProtocolException(
String.format(
"Error occurred during retrieving a Flutter widget's geometry info. Response"
+ " received: %s",
this));
} else {
return response.dx;
}
}
/** Returns the Y-Coordinate. */
public float getY() {
if (response == null) {
throw new FlutterProtocolException(
String.format(
"Error occurred during retrieving a Flutter widget's geometry info. Response"
+ " received: %s",
this));
} else {
return response.dy;
}
}
@Override
public String toString() {
return gson.toJson(this);
}
static class Coordinates {
@Expose private float dx;
@Expose private float dy;
Coordinates() {}
Coordinates(float dx, float dy) {
this.dx = dx;
this.dy = dy;
}
}
static class Builder {
private boolean isError;
private Coordinates coordinate;
private OffsetType type;
public Builder() {}
public Builder setIsError(boolean isError) {
this.isError = isError;
return this;
}
public Builder setCoordinates(float dx, float dy) {
this.coordinate = new Coordinates(dx, dy);
return this;
}
public Builder setType(OffsetType type) {
this.type = checkNotNull(type);
return this;
}
public GetOffsetResponse build() {
GetOffsetResponse response = new GetOffsetResponse();
response.isError = this.isError;
response.response = this.coordinate;
response.type = checkNotNull(type).toString();
return response;
}
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/GetOffsetResponse.java",
"repo_id": "packages",
"token_count": 1472
} | 1,141 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.matcher;
import static com.google.common.base.Preconditions.checkNotNull;
import androidx.test.espresso.flutter.api.WidgetMatcher;
import androidx.test.espresso.flutter.model.WidgetInfo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Nonnull;
import org.hamcrest.Description;
/** A matcher that matches a Flutter widget with a given value key. */
public final class WithValueKeyMatcher extends WidgetMatcher {
@Expose
@SerializedName("keyValueString")
private final String valueKey;
@Expose private final String keyValueType = "String";
/**
* Constructs the matcher with the given value key String to be matched with.
*
* @param valueKey the value key String to be matched with.
*/
public WithValueKeyMatcher(@Nonnull String valueKey) {
super("ByValueKey");
this.valueKey = checkNotNull(valueKey);
}
/** Returns the value key string that shall be matched for the widget. */
public String getValueKey() {
return valueKey;
}
@Override
public String toString() {
return "with value key: " + valueKey;
}
@Override
protected boolean matchesSafely(WidgetInfo widget) {
return valueKey.equals(widget.getValueKey());
}
@Override
public void describeTo(Description description) {
description.appendText("with value key: ").appendText(valueKey);
}
}
| packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/WithValueKeyMatcher.java/0 | {
"file_path": "packages/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/WithValueKeyMatcher.java",
"repo_id": "packages",
"token_count": 481
} | 1,142 |
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/packages/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.3.0+7
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
platforms:
android:
package: com.example.espresso
pluginClass: EspressoPlugin
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- android
- test
| packages/packages/espresso/pubspec.yaml/0 | {
"file_path": "packages/packages/espresso/pubspec.yaml",
"repo_id": "packages",
"token_count": 252
} | 1,143 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:googleapis_auth/googleapis_auth.dart' as gapis;
const String SOME_FAKE_ACCESS_TOKEN = 'this-is-something-not-null';
const List<String> DEBUG_FAKE_SCOPES = <String>['some-scope', 'another-scope'];
const List<String> SIGN_IN_FAKE_SCOPES = <String>[
'some-scope',
'another-scope'
];
class FakeGoogleSignIn extends Fake implements GoogleSignIn {
@override
final List<String> scopes = SIGN_IN_FAKE_SCOPES;
}
class FakeGoogleSignInAuthentication extends Fake
implements GoogleSignInAuthentication {
@override
final String accessToken = SOME_FAKE_ACCESS_TOKEN;
}
void main() {
final GoogleSignIn signIn = FakeGoogleSignIn();
final FakeGoogleSignInAuthentication authMock =
FakeGoogleSignInAuthentication();
test('authenticatedClient returns an authenticated client', () async {
final gapis.AuthClient client = (await signIn.authenticatedClient(
debugAuthentication: authMock,
))!;
expect(client, isA<gapis.AuthClient>());
});
test('authenticatedClient uses GoogleSignIn scopes by default', () async {
final gapis.AuthClient client = (await signIn.authenticatedClient(
debugAuthentication: authMock,
))!;
expect(client.credentials.accessToken.data, equals(SOME_FAKE_ACCESS_TOKEN));
expect(client.credentials.scopes, equals(SIGN_IN_FAKE_SCOPES));
});
test('authenticatedClient returned client contains the passed-in credentials',
() async {
final gapis.AuthClient client = (await signIn.authenticatedClient(
debugAuthentication: authMock,
debugScopes: DEBUG_FAKE_SCOPES,
))!;
expect(client.credentials.accessToken.data, equals(SOME_FAKE_ACCESS_TOKEN));
expect(client.credentials.scopes, equals(DEBUG_FAKE_SCOPES));
});
}
| packages/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart/0 | {
"file_path": "packages/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart",
"repo_id": "packages",
"token_count": 724
} | 1,144 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.packages.file_selector_android;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.OpenableColumns;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.PluginRegistry;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class FileSelectorAndroidPluginTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public Intent mockIntent;
@Mock public Activity mockActivity;
@Mock FileSelectorApiImpl.NativeObjectFactory mockObjectFactory;
@Mock public ActivityPluginBinding mockActivityBinding;
private void mockContentResolver(
@NonNull ContentResolver mockResolver,
@NonNull Uri uri,
@NonNull String displayName,
int size,
@NonNull String mimeType)
throws FileNotFoundException {
final Cursor mockCursor = mock(Cursor.class);
when(mockCursor.moveToFirst()).thenReturn(true);
when(mockCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)).thenReturn(0);
when(mockCursor.getString(0)).thenReturn(displayName);
when(mockCursor.getColumnIndex(OpenableColumns.SIZE)).thenReturn(1);
when(mockCursor.isNull(1)).thenReturn(false);
when(mockCursor.getInt(1)).thenReturn(size);
when(mockResolver.query(uri, null, null, null, null, null)).thenReturn(mockCursor);
when(mockResolver.getType(uri)).thenReturn(mimeType);
when(mockResolver.openInputStream(uri)).thenReturn(mock(InputStream.class));
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void openFileReturnsSuccessfully() throws FileNotFoundException {
final ContentResolver mockContentResolver = mock(ContentResolver.class);
final Uri mockUri = mock(Uri.class);
when(mockUri.toString()).thenReturn("some/path/");
mockContentResolver(mockContentResolver, mockUri, "filename", 30, "text/plain");
when(mockObjectFactory.newIntent(Intent.ACTION_OPEN_DOCUMENT)).thenReturn(mockIntent);
when(mockObjectFactory.newDataInputStream(any())).thenReturn(mock(DataInputStream.class));
when(mockActivity.getContentResolver()).thenReturn(mockContentResolver);
when(mockActivityBinding.getActivity()).thenReturn(mockActivity);
final FileSelectorApiImpl fileSelectorApi =
new FileSelectorApiImpl(
mockActivityBinding, mockObjectFactory, (version) -> Build.VERSION.SDK_INT >= version);
final GeneratedFileSelectorApi.Result mockResult = mock(GeneratedFileSelectorApi.Result.class);
fileSelectorApi.openFile(
null,
new GeneratedFileSelectorApi.FileTypes.Builder()
.setMimeTypes(Collections.emptyList())
.setExtensions(Collections.emptyList())
.build(),
mockResult);
verify(mockIntent).addCategory(Intent.CATEGORY_OPENABLE);
verify(mockActivity).startActivityForResult(mockIntent, 221);
final ArgumentCaptor<PluginRegistry.ActivityResultListener> listenerArgumentCaptor =
ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class);
verify(mockActivityBinding).addActivityResultListener(listenerArgumentCaptor.capture());
final Intent resultMockIntent = mock(Intent.class);
when(resultMockIntent.getData()).thenReturn(mockUri);
listenerArgumentCaptor.getValue().onActivityResult(221, Activity.RESULT_OK, resultMockIntent);
final ArgumentCaptor<GeneratedFileSelectorApi.FileResponse> fileCaptor =
ArgumentCaptor.forClass(GeneratedFileSelectorApi.FileResponse.class);
verify(mockResult).success(fileCaptor.capture());
final GeneratedFileSelectorApi.FileResponse file = fileCaptor.getValue();
assertEquals(file.getBytes().length, 30);
assertEquals(file.getMimeType(), "text/plain");
assertEquals(file.getName(), "filename");
assertEquals(file.getSize(), (Long) 30L);
assertEquals(file.getPath(), "some/path/");
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void openFilesReturnsSuccessfully() throws FileNotFoundException {
final ContentResolver mockContentResolver = mock(ContentResolver.class);
final Uri mockUri = mock(Uri.class);
when(mockUri.toString()).thenReturn("some/path/");
mockContentResolver(mockContentResolver, mockUri, "filename", 30, "text/plain");
final Uri mockUri2 = mock(Uri.class);
when(mockUri2.toString()).thenReturn("some/other/path/");
mockContentResolver(mockContentResolver, mockUri2, "filename2", 40, "image/jpg");
when(mockObjectFactory.newIntent(Intent.ACTION_OPEN_DOCUMENT)).thenReturn(mockIntent);
when(mockObjectFactory.newDataInputStream(any())).thenReturn(mock(DataInputStream.class));
when(mockActivity.getContentResolver()).thenReturn(mockContentResolver);
when(mockActivityBinding.getActivity()).thenReturn(mockActivity);
final FileSelectorApiImpl fileSelectorApi =
new FileSelectorApiImpl(
mockActivityBinding, mockObjectFactory, (version) -> Build.VERSION.SDK_INT >= version);
final GeneratedFileSelectorApi.Result mockResult = mock(GeneratedFileSelectorApi.Result.class);
fileSelectorApi.openFiles(
null,
new GeneratedFileSelectorApi.FileTypes.Builder()
.setMimeTypes(Collections.emptyList())
.setExtensions(Collections.emptyList())
.build(),
mockResult);
verify(mockIntent).addCategory(Intent.CATEGORY_OPENABLE);
verify(mockIntent).putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
verify(mockActivity).startActivityForResult(mockIntent, 222);
final ArgumentCaptor<PluginRegistry.ActivityResultListener> listenerArgumentCaptor =
ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class);
verify(mockActivityBinding).addActivityResultListener(listenerArgumentCaptor.capture());
final Intent resultMockIntent = mock(Intent.class);
final ClipData mockClipData = mock(ClipData.class);
when(mockClipData.getItemCount()).thenReturn(2);
final ClipData.Item mockClipDataItem = mock(ClipData.Item.class);
when(mockClipDataItem.getUri()).thenReturn(mockUri);
when(mockClipData.getItemAt(0)).thenReturn(mockClipDataItem);
final ClipData.Item mockClipDataItem2 = mock(ClipData.Item.class);
when(mockClipDataItem2.getUri()).thenReturn(mockUri2);
when(mockClipData.getItemAt(1)).thenReturn(mockClipDataItem2);
when(resultMockIntent.getClipData()).thenReturn(mockClipData);
listenerArgumentCaptor.getValue().onActivityResult(222, Activity.RESULT_OK, resultMockIntent);
final ArgumentCaptor<List> fileListCaptor = ArgumentCaptor.forClass(List.class);
verify(mockResult).success(fileListCaptor.capture());
final List<GeneratedFileSelectorApi.FileResponse> fileList = fileListCaptor.getValue();
assertEquals(fileList.get(0).getBytes().length, 30);
assertEquals(fileList.get(0).getMimeType(), "text/plain");
assertEquals(fileList.get(0).getName(), "filename");
assertEquals(fileList.get(0).getSize(), (Long) 30L);
assertEquals(fileList.get(0).getPath(), "some/path/");
assertEquals(fileList.get(1).getBytes().length, 40);
assertEquals(fileList.get(1).getMimeType(), "image/jpg");
assertEquals(fileList.get(1).getName(), "filename2");
assertEquals(fileList.get(1).getSize(), (Long) 40L);
assertEquals(fileList.get(1).getPath(), "some/other/path/");
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getDirectoryPathReturnsSuccessfully() {
final Uri mockUri = mock(Uri.class);
when(mockUri.toString()).thenReturn("some/path/");
when(mockObjectFactory.newIntent(Intent.ACTION_OPEN_DOCUMENT_TREE)).thenReturn(mockIntent);
when(mockActivityBinding.getActivity()).thenReturn(mockActivity);
final FileSelectorApiImpl fileSelectorApi =
new FileSelectorApiImpl(
mockActivityBinding,
mockObjectFactory,
(version) -> Build.VERSION_CODES.LOLLIPOP >= version);
final GeneratedFileSelectorApi.Result mockResult = mock(GeneratedFileSelectorApi.Result.class);
fileSelectorApi.getDirectoryPath(null, mockResult);
verify(mockActivity).startActivityForResult(mockIntent, 223);
final ArgumentCaptor<PluginRegistry.ActivityResultListener> listenerArgumentCaptor =
ArgumentCaptor.forClass(PluginRegistry.ActivityResultListener.class);
verify(mockActivityBinding).addActivityResultListener(listenerArgumentCaptor.capture());
final Intent resultMockIntent = mock(Intent.class);
when(resultMockIntent.getData()).thenReturn(mockUri);
listenerArgumentCaptor.getValue().onActivityResult(223, Activity.RESULT_OK, resultMockIntent);
verify(mockResult).success("some/path/");
}
@Test
public void getDirectoryPath_errorsForUnsupportedVersion() {
final FileSelectorApiImpl fileSelectorApi =
new FileSelectorApiImpl(
mockActivityBinding,
mockObjectFactory,
(version) -> Build.VERSION_CODES.KITKAT >= version);
@SuppressWarnings("unchecked")
final GeneratedFileSelectorApi.Result<String> mockResult =
mock(GeneratedFileSelectorApi.Result.class);
fileSelectorApi.getDirectoryPath(null, mockResult);
verify(mockResult).error(any());
}
}
| packages/packages/file_selector/file_selector_android/android/src/test/java/dev/flutter/packages/file_selector_android/FileSelectorAndroidPluginTest.java/0 | {
"file_path": "packages/packages/file_selector/file_selector_android/android/src/test/java/dev/flutter/packages/file_selector_android/FileSelectorAndroidPluginTest.java",
"repo_id": "packages",
"token_count": 3615
} | 1,145 |
name: file_selector_android_example
description: Demonstrates how to use the file_selector_android plugin.
publish_to: 'none'
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
file_selector_android:
# When depending on this package from a real application you should use:
# file_selector_android: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
file_selector_platform_interface: ^2.5.0
flutter:
sdk: flutter
flutter_driver:
sdk: flutter
dev_dependencies:
espresso: ^0.2.0
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/file_selector/file_selector_android/example/pubspec.yaml/0 | {
"file_path": "packages/packages/file_selector/file_selector_android/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 297
} | 1,146 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/material.dart';
/// Screen that allows the user to select a text file using `openFile`, then
/// displays its contents in a dialog.
class OpenTextPage extends StatelessWidget {
/// Default Constructor
const OpenTextPage({super.key});
Future<void> _openTextFile(BuildContext context) async {
const XTypeGroup typeGroup = XTypeGroup(
label: 'text',
extensions: <String>['txt', 'json'],
uniformTypeIdentifiers: <String>['public.text'],
);
final XFile? file = await FileSelectorPlatform.instance
.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
if (file == null) {
// Operation was canceled by the user.
return;
}
final String fileName = file.name;
final String fileContent = await file.readAsString();
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) => TextDisplay(fileName, fileContent),
);
}
}
@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(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
child: const Text('Press to open a text file (json, txt)'),
onPressed: () => _openTextFile(context),
),
],
),
),
);
}
}
/// Widget that displays a text file in a dialog.
class TextDisplay extends StatelessWidget {
/// Default Constructor.
const TextDisplay(this.fileName, this.fileContent, {super.key});
/// The name of the selected file.
final String fileName;
/// The contents of the text file.
final String fileContent;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
content: Scrollbar(
child: SingleChildScrollView(
child: Text(fileContent),
),
),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () => Navigator.pop(context),
),
],
);
}
}
| packages/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart",
"repo_id": "packages",
"token_count": 1008
} | 1,147 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Home Page of the application.
class HomePage extends StatelessWidget {
/// Default Constructor
const HomePage({super.key});
@override
Widget build(BuildContext context) {
final ButtonStyle style = ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
);
return Scaffold(
appBar: AppBar(
title: const Text('File Selector Demo Home Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: style,
child: const Text('Open a text file'),
onPressed: () => Navigator.pushNamed(context, '/open/text'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Open an image'),
onPressed: () => Navigator.pushNamed(context, '/open/image'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Open multiple images'),
onPressed: () => Navigator.pushNamed(context, '/open/images'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Save a file'),
onPressed: () => Navigator.pushNamed(context, '/save/text'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Open a get directory dialog'),
onPressed: () => Navigator.pushNamed(context, '/directory'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Open a get directories dialog'),
onPressed: () =>
Navigator.pushNamed(context, '/multi-directories'),
),
],
),
),
);
}
}
| packages/packages/file_selector/file_selector_linux/example/lib/home_page.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_linux/example/lib/home_page.dart",
"repo_id": "packages",
"token_count": 1049
} | 1,148 |
# Platform Implementation Test App
This is a test app for manual testing and automated integration testing
of this platform implementation. It is not intended to demonstrate actual use of
this package, since the intent is that plugin clients use the app-facing
package.
Unless you are making changes to this implementation package, this example is
very unlikely to be relevant.
| packages/packages/file_selector/file_selector_macos/example/README.md/0 | {
"file_path": "packages/packages/file_selector/file_selector_macos/example/README.md",
"repo_id": "packages",
"token_count": 76
} | 1,149 |
// Mocks generated by Mockito 5.4.4 from annotations
// in file_selector_macos/test/file_selector_macos_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:file_selector_macos/src/messages.g.dart' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'messages_test.g.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [TestFileSelectorApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockTestFileSelectorApi extends _i1.Mock
implements _i2.TestFileSelectorApi {
MockTestFileSelectorApi() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<List<String?>> displayOpenPanel(_i4.OpenPanelOptions? options) =>
(super.noSuchMethod(
Invocation.method(
#displayOpenPanel,
[options],
),
returnValue: _i3.Future<List<String?>>.value(<String?>[]),
) as _i3.Future<List<String?>>);
@override
_i3.Future<String?> displaySavePanel(_i4.SavePanelOptions? options) =>
(super.noSuchMethod(
Invocation.method(
#displaySavePanel,
[options],
),
returnValue: _i3.Future<String?>.value(),
) as _i3.Future<String?>);
}
| packages/packages/file_selector/file_selector_macos/test/file_selector_macos_test.mocks.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_macos/test/file_selector_macos_test.mocks.dart",
"repo_id": "packages",
"token_count": 712
} | 1,150 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:file_selector_platform_interface/src/method_channel/method_channel_file_selector.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$MethodChannelFileSelector()', () {
final MethodChannelFileSelector plugin = MethodChannelFileSelector();
final List<MethodCall> log = <MethodCall>[];
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
plugin.channel,
(MethodCall methodCall) async {
log.add(methodCall);
return null;
},
);
log.clear();
});
group('#openFile', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
uniformTypeIdentifiers: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
uniformTypeIdentifiers: <String>['public.image'],
webWildCards: <String>['image/*']);
await plugin
.openFile(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
group.toJSON(),
groupTwo.toJSON()
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': false,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.openFile(initialDirectory: '/example/directory');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': null,
'initialDirectory': '/example/directory',
'confirmButtonText': null,
'multiple': false,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.openFile(confirmButtonText: 'Open File');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': null,
'initialDirectory': null,
'confirmButtonText': 'Open File',
'multiple': false,
},
);
});
});
group('#openFiles', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
uniformTypeIdentifiers: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
uniformTypeIdentifiers: <String>['public.image'],
webWildCards: <String>['image/*']);
await plugin
.openFiles(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
group.toJSON(),
groupTwo.toJSON()
],
'initialDirectory': null,
'confirmButtonText': null,
'multiple': true,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.openFiles(initialDirectory: '/example/directory');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': null,
'initialDirectory': '/example/directory',
'confirmButtonText': null,
'multiple': true,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.openFiles(confirmButtonText: 'Open File');
expectMethodCall(
log,
'openFile',
arguments: <String, dynamic>{
'acceptedTypeGroups': null,
'initialDirectory': null,
'confirmButtonText': 'Open File',
'multiple': true,
},
);
});
});
group('#getSavePath', () {
test('passes the accepted type groups correctly', () async {
const XTypeGroup group = XTypeGroup(
label: 'text',
extensions: <String>['txt'],
mimeTypes: <String>['text/plain'],
uniformTypeIdentifiers: <String>['public.text'],
);
const XTypeGroup groupTwo = XTypeGroup(
label: 'image',
extensions: <String>['jpg'],
mimeTypes: <String>['image/jpg'],
uniformTypeIdentifiers: <String>['public.image'],
webWildCards: <String>['image/*']);
await plugin
.getSavePath(acceptedTypeGroups: <XTypeGroup>[group, groupTwo]);
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'acceptedTypeGroups': <Map<String, dynamic>>[
group.toJSON(),
groupTwo.toJSON()
],
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': null,
},
);
});
test('passes initialDirectory correctly', () async {
await plugin.getSavePath(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'acceptedTypeGroups': null,
'initialDirectory': '/example/directory',
'suggestedName': null,
'confirmButtonText': null,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getSavePath(confirmButtonText: 'Open File');
expectMethodCall(
log,
'getSavePath',
arguments: <String, dynamic>{
'acceptedTypeGroups': null,
'initialDirectory': null,
'suggestedName': null,
'confirmButtonText': 'Open File',
},
);
});
});
group('#getDirectoryPath', () {
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPath(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPath(confirmButtonText: 'Select Folder');
expectMethodCall(
log,
'getDirectoryPath',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Select Folder',
},
);
});
});
group('#getDirectoryPaths', () {
test('passes initialDirectory correctly', () async {
await plugin.getDirectoryPaths(initialDirectory: '/example/directory');
expectMethodCall(
log,
'getDirectoryPaths',
arguments: <String, dynamic>{
'initialDirectory': '/example/directory',
'confirmButtonText': null,
},
);
});
test('passes confirmButtonText correctly', () async {
await plugin.getDirectoryPaths(
confirmButtonText: 'Select one or more Folders');
expectMethodCall(
log,
'getDirectoryPaths',
arguments: <String, dynamic>{
'initialDirectory': null,
'confirmButtonText': 'Select one or more Folders',
},
);
});
});
});
}
void expectMethodCall(
List<MethodCall> log,
String methodName, {
Map<String, dynamic>? arguments,
}) {
expect(log, <Matcher>[isMethodCall(methodName, arguments: arguments)]);
}
| packages/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart",
"repo_id": "packages",
"token_count": 3957
} | 1,151 |
name: file_selector_web
description: Web platform implementation of file_selector
repository: https://github.com/flutter/packages/tree/main/packages/file_selector/file_selector_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22
version: 0.9.4+1
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
flutter:
plugin:
implements: file_selector
platforms:
web:
pluginClass: FileSelectorWeb
fileName: file_selector_web.dart
dependencies:
file_selector_platform_interface: ^2.6.0
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
web: ^0.5.0
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- files
- file-selection
- file-selector
| packages/packages/file_selector/file_selector_web/pubspec.yaml/0 | {
"file_path": "packages/packages/file_selector/file_selector_web/pubspec.yaml",
"repo_id": "packages",
"token_count": 320
} | 1,152 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// Screen that allows the user to select an image file using
/// `openFiles`, then displays the selected images in a gallery dialog.
class OpenImagePage extends StatelessWidget {
/// Default Constructor
const OpenImagePage({super.key});
Future<void> _openImageFile(BuildContext context) async {
const XTypeGroup typeGroup = XTypeGroup(
label: 'images',
extensions: <String>['jpg', 'png'],
);
final XFile? file = await FileSelectorPlatform.instance
.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
if (file == null) {
// Operation was canceled by the user.
return;
}
final String fileName = file.name;
final String filePath = file.path;
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) => ImageDisplay(fileName, filePath),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Open an image'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
child: const Text('Press to open an image file(png, jpg)'),
onPressed: () => _openImageFile(context),
),
],
),
),
);
}
}
/// Widget that displays an image in a dialog.
class ImageDisplay extends StatelessWidget {
/// Default Constructor.
const ImageDisplay(this.fileName, this.filePath, {super.key});
/// The name of the selected file.
final String fileName;
/// The path to the selected file.
final String filePath;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
// On web the filePath is a blob url
// while on other platforms it is a system path.
content: kIsWeb ? Image.network(filePath) : Image.file(File(filePath)),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
}
}
| packages/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart",
"repo_id": "packages",
"token_count": 1033
} | 1,153 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_DIALOG_CONTROLLER_H_
#define PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_DIALOG_CONTROLLER_H_
#include <comdef.h>
#include <comip.h>
#include <shobjidl.h>
#include <windows.h>
#include <memory>
_COM_SMARTPTR_TYPEDEF(IFileDialog, IID_IFileDialog);
namespace file_selector_windows {
// A thin wrapper for IFileDialog to allow for faking and inspection in tests.
//
// Since this class defines the end of what can be unit tested, it should
// contain as little logic as possible.
class FileDialogController {
public:
// Creates a controller managing |dialog|.
FileDialogController(IFileDialog* dialog);
virtual ~FileDialogController();
// Disallow copy and assign.
FileDialogController(const FileDialogController&) = delete;
FileDialogController& operator=(const FileDialogController&) = delete;
// IFileDialog wrappers:
virtual HRESULT SetFolder(IShellItem* folder);
virtual HRESULT SetFileName(const wchar_t* name);
virtual HRESULT SetFileTypes(UINT count, COMDLG_FILTERSPEC* filters);
virtual HRESULT SetOkButtonLabel(const wchar_t* text);
virtual HRESULT GetOptions(FILEOPENDIALOGOPTIONS* out_options) const;
virtual HRESULT SetOptions(FILEOPENDIALOGOPTIONS options);
virtual HRESULT Show(HWND parent);
virtual HRESULT GetResult(IShellItem** out_item) const;
virtual HRESULT GetFileTypeIndex(UINT* out_index) const;
// IFileOpenDialog wrapper. This will fail if the IFileDialog* provided to the
// constructor was not an IFileOpenDialog instance.
virtual HRESULT GetResults(IShellItemArray** out_items) const;
private:
IFileDialogPtr dialog_ = nullptr;
};
// Interface for creating FileDialogControllers, to allow for dependency
// injection.
class FileDialogControllerFactory {
public:
virtual ~FileDialogControllerFactory();
virtual std::unique_ptr<FileDialogController> CreateController(
IFileDialog* dialog) const = 0;
};
} // namespace file_selector_windows
#endif // PACKAGES_FILE_SELECTOR_FILE_SELECTOR_WINDOWS_WINDOWS_FILE_DIALOG_CONTROLLER_H_
| packages/packages/file_selector/file_selector_windows/windows/file_dialog_controller.h/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/windows/file_dialog_controller.h",
"repo_id": "packages",
"token_count": 696
} | 1,154 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_adaptive_scaffold_example/adaptive_scaffold_demo.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
final Finder smallBody = find.byKey(const Key('smallBody'));
final Finder body = find.byKey(const Key('body'));
final Finder largeBody = find.byKey(const Key('largeBody'));
final Finder bnav = find.byKey(const Key('bottomNavigation'));
final Finder pnav = find.byKey(const Key('primaryNavigation'));
final Finder pnav1 = find.byKey(const Key('primaryNavigation1'));
Future<void> updateScreen(double width, WidgetTester tester,
{int transitionDuration = 1000}) async {
await tester.binding.setSurfaceSize(Size(width, 800));
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: MediaQueryData(size: Size(width, 800)),
child: example.MyHomePage(
transitionDuration: transitionDuration,
)),
),
);
}
testWidgets('dislays correct item of config based on screen width',
(WidgetTester tester) async {
await updateScreen(300, tester);
await tester.pumpAndSettle();
expect(smallBody, findsOneWidget);
expect(bnav, findsOneWidget);
expect(tester.getTopLeft(smallBody), Offset.zero);
expect(tester.getTopLeft(bnav), const Offset(0, 720));
expect(body, findsNothing);
expect(largeBody, findsNothing);
expect(pnav, findsNothing);
expect(pnav1, findsNothing);
await updateScreen(800, tester);
await tester.pumpAndSettle();
expect(body, findsOneWidget);
expect(tester.getTopLeft(body), const Offset(88, 0));
expect(body, findsOneWidget);
expect(bnav, findsNothing);
expect(largeBody, findsNothing);
expect(pnav, findsOneWidget);
expect(tester.getTopLeft(pnav), Offset.zero);
expect(tester.getBottomRight(pnav), const Offset(88, 800));
expect(pnav1, findsNothing);
await updateScreen(1100, tester);
await tester.pumpAndSettle();
expect(body, findsOneWidget);
expect(pnav, findsNothing);
expect(pnav1, findsOneWidget);
expect(tester.getTopLeft(pnav1), Offset.zero);
expect(tester.getBottomRight(pnav1), const Offset(208, 800));
});
testWidgets('adaptive scaffold animations work correctly',
(WidgetTester tester) async {
final Finder b = find.byKey(const Key('body'));
final Finder sBody = find.byKey(const Key('sBody'));
await updateScreen(400, tester);
await updateScreen(800, tester);
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(tester.getTopLeft(b), const Offset(17.6, 0));
expect(tester.getBottomRight(b),
offsetMoreOrLessEquals(const Offset(778.2, 736), epsilon: 1.0));
expect(tester.getTopLeft(sBody),
offsetMoreOrLessEquals(const Offset(778.2, 0), epsilon: 1.0));
expect(tester.getBottomRight(sBody),
offsetMoreOrLessEquals(const Offset(1178.2, 736), epsilon: 1.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
expect(tester.getTopLeft(b), const Offset(70.4, 0));
expect(tester.getBottomRight(b),
offsetMoreOrLessEquals(const Offset(416.0, 784), epsilon: 1.0));
expect(tester.getTopLeft(sBody),
offsetMoreOrLessEquals(const Offset(416, 0), epsilon: 1.0));
expect(tester.getBottomRight(sBody),
offsetMoreOrLessEquals(const Offset(816, 784), epsilon: 1.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(tester.getTopLeft(b), const Offset(88, 0));
expect(tester.getBottomRight(b), const Offset(400, 800));
expect(tester.getTopLeft(sBody), const Offset(400, 0));
expect(tester.getBottomRight(sBody), const Offset(800, 800));
});
testWidgets('animation plays correctly in declared duration',
(WidgetTester tester) async {
final Finder b = find.byKey(const Key('body'));
final Finder sBody = find.byKey(const Key('sBody'));
await updateScreen(400, tester, transitionDuration: 500);
await updateScreen(800, tester, transitionDuration: 500);
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getTopLeft(b), const Offset(88, 0));
expect(tester.getBottomRight(b), const Offset(400, 800));
expect(tester.getTopLeft(sBody), const Offset(400, 0));
expect(tester.getBottomRight(sBody), const Offset(800, 800));
});
}
| packages/packages/flutter_adaptive_scaffold/example/test/adaptive_scaffold_demo_test.dart/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/example/test/adaptive_scaffold_demo_test.dart",
"repo_id": "packages",
"token_count": 1747
} | 1,155 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_adaptive_scaffold/src/adaptive_scaffold.dart';
import 'package:flutter_test/flutter_test.dart';
import 'simulated_layout.dart';
import 'test_breakpoints.dart';
void main() {
testWidgets('adaptive scaffold lays out slots as expected',
(WidgetTester tester) async {
final Finder smallBody = find.byKey(const Key('smallBody'));
final Finder body = find.byKey(const Key('body'));
final Finder largeBody = find.byKey(const Key('largeBody'));
final Finder smallSBody = find.byKey(const Key('smallSBody'));
final Finder sBody = find.byKey(const Key('sBody'));
final Finder largeSBody = find.byKey(const Key('largeSBody'));
final Finder bottomNav = find.byKey(const Key('bottomNavigation'));
final Finder primaryNav = find.byKey(const Key('primaryNavigation'));
final Finder primaryNav1 = find.byKey(const Key('primaryNavigation1'));
await tester.binding.setSurfaceSize(SimulatedLayout.small.size);
await tester.pumpWidget(SimulatedLayout.small.app());
await tester.pumpAndSettle();
expect(smallBody, findsOneWidget);
expect(smallSBody, findsOneWidget);
expect(bottomNav, findsOneWidget);
expect(primaryNav, findsNothing);
expect(tester.getTopLeft(smallBody), Offset.zero);
expect(tester.getTopLeft(smallSBody), const Offset(200, 0));
expect(tester.getTopLeft(bottomNav), const Offset(0, 720));
await tester.binding.setSurfaceSize(SimulatedLayout.medium.size);
await tester.pumpWidget(SimulatedLayout.medium.app());
await tester.pumpAndSettle();
expect(smallBody, findsNothing);
expect(body, findsOneWidget);
expect(smallSBody, findsNothing);
expect(sBody, findsOneWidget);
expect(bottomNav, findsNothing);
expect(primaryNav, findsOneWidget);
expect(tester.getTopLeft(body), const Offset(88, 0));
expect(tester.getTopLeft(sBody), const Offset(400, 0));
expect(tester.getTopLeft(primaryNav), Offset.zero);
expect(tester.getBottomRight(primaryNav), const Offset(88, 800));
await tester.binding.setSurfaceSize(SimulatedLayout.large.size);
await tester.pumpWidget(SimulatedLayout.large.app());
await tester.pumpAndSettle();
expect(body, findsNothing);
expect(largeBody, findsOneWidget);
expect(sBody, findsNothing);
expect(largeSBody, findsOneWidget);
expect(primaryNav, findsNothing);
expect(primaryNav1, findsOneWidget);
expect(tester.getTopLeft(largeBody), const Offset(208, 0));
expect(tester.getTopLeft(largeSBody), const Offset(550, 0));
expect(tester.getTopLeft(primaryNav1), Offset.zero);
expect(tester.getBottomRight(primaryNav1), const Offset(208, 800));
});
testWidgets('adaptive scaffold animations work correctly',
(WidgetTester tester) async {
final Finder b = find.byKey(const Key('body'));
final Finder sBody = find.byKey(const Key('sBody'));
await tester.binding.setSurfaceSize(SimulatedLayout.small.size);
await tester.pumpWidget(SimulatedLayout.small.app());
await tester.binding.setSurfaceSize(SimulatedLayout.medium.size);
await tester.pumpWidget(SimulatedLayout.medium.app());
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(tester.getTopLeft(b), const Offset(17.6, 0));
expect(tester.getBottomRight(b),
offsetMoreOrLessEquals(const Offset(778.2, 736), epsilon: 1.0));
expect(tester.getTopLeft(sBody),
offsetMoreOrLessEquals(const Offset(778.2, 0), epsilon: 1.0));
expect(tester.getBottomRight(sBody),
offsetMoreOrLessEquals(const Offset(1178.2, 736), epsilon: 1.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
expect(tester.getTopLeft(b), const Offset(70.4, 0));
expect(tester.getBottomRight(b),
offsetMoreOrLessEquals(const Offset(416.0, 784), epsilon: 1.0));
expect(tester.getTopLeft(sBody),
offsetMoreOrLessEquals(const Offset(416, 0), epsilon: 1.0));
expect(tester.getBottomRight(sBody),
offsetMoreOrLessEquals(const Offset(816, 784), epsilon: 1.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(tester.getTopLeft(b), const Offset(88.0, 0));
expect(tester.getBottomRight(b), const Offset(400, 800));
expect(tester.getTopLeft(sBody), const Offset(400, 0));
expect(tester.getBottomRight(sBody), const Offset(800, 800));
});
testWidgets('adaptive scaffold animations can be disabled',
(WidgetTester tester) async {
final Finder b = find.byKey(const Key('body'));
final Finder sBody = find.byKey(const Key('sBody'));
await tester.binding.setSurfaceSize(SimulatedLayout.small.size);
await tester.pumpWidget(SimulatedLayout.small.app(animations: false));
await tester.binding.setSurfaceSize(SimulatedLayout.medium.size);
await tester.pumpWidget(SimulatedLayout.medium.app(animations: false));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(tester.getTopLeft(b), const Offset(88.0, 0));
expect(tester.getBottomRight(b), const Offset(400, 800));
expect(tester.getTopLeft(sBody), const Offset(400, 0));
expect(tester.getBottomRight(sBody), const Offset(800, 800));
});
// The goal of this test is to run through each of the navigation elements
// and test whether tapping on that element will update the selected index
// globally
testWidgets('tapping navigation elements calls onSelectedIndexChange',
(WidgetTester tester) async {
// for each screen size there is a different navigational element that
// we want to test tapping to set the selected index
await Future.forEach(SimulatedLayout.values,
(SimulatedLayout region) async {
int selectedIndex = 0;
final MaterialApp app = region.app(initialIndex: selectedIndex);
await tester.binding.setSurfaceSize(region.size);
await tester.pumpWidget(app);
await tester.pumpAndSettle();
// tap on the next icon
selectedIndex = (selectedIndex + 1) % TestScaffold.destinations.length;
// Resolve the icon that should be found
final NavigationDestination destination =
TestScaffold.destinations[selectedIndex];
expect(destination.icon, isA<Icon>());
final Icon icon = destination.icon as Icon;
expect(icon.icon, isNotNull);
// Find the icon in the application to tap
final Widget navigationSlot =
tester.widget(find.byKey(Key(region.navSlotKey)));
final Finder target =
find.widgetWithIcon(navigationSlot.runtimeType, icon.icon!);
expect(target, findsOneWidget);
await tester.tap(target);
await tester.pumpAndSettle();
// Check that the state was set appropriately
final Finder scaffold = find.byType(TestScaffold);
final TestScaffoldState state = tester.state<TestScaffoldState>(scaffold);
expect(selectedIndex, state.index);
});
});
// Regression test for https://github.com/flutter/flutter/issues/111008
testWidgets(
'appBar parameter should have the type PreferredSizeWidget',
(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: MediaQuery(
data: const MediaQueryData(size: Size(500, 800)),
child: AdaptiveScaffold(
drawerBreakpoint: TestBreakpoint0(),
internalAnimations: false,
destinations: const <NavigationDestination>[
NavigationDestination(icon: Icon(Icons.inbox), label: 'Inbox'),
NavigationDestination(
icon: Icon(Icons.video_call), label: 'Video'),
],
appBar: const PreferredSizeWidgetImpl(),
),
),
));
expect(find.byType(PreferredSizeWidgetImpl), findsOneWidget);
},
);
// Verify that the leading navigation rail widget is displayed
// based on the screen size
testWidgets(
'adaptive scaffold displays leading widget in navigation rail',
(WidgetTester tester) async {
await Future.forEach(SimulatedLayout.values,
(SimulatedLayout region) async {
final MaterialApp app = region.app();
await tester.binding.setSurfaceSize(region.size);
await tester.pumpWidget(app);
await tester.pumpAndSettle();
if (region.size == SimulatedLayout.large.size) {
expect(find.text('leading_extended'), findsOneWidget);
expect(find.text('leading_unextended'), findsNothing);
expect(find.text('trailing'), findsOneWidget);
} else if (region.size == SimulatedLayout.medium.size) {
expect(find.text('leading_extended'), findsNothing);
expect(find.text('leading_unextended'), findsOneWidget);
expect(find.text('trailing'), findsOneWidget);
} else if (region.size == SimulatedLayout.small.size) {
expect(find.text('leading_extended'), findsNothing);
expect(find.text('leading_unextended'), findsNothing);
expect(find.text('trailing'), findsNothing);
}
});
},
);
/// Verify that selectedIndex of [AdaptiveScaffold.standardNavigationRail]
/// and [AdaptiveScaffold] can be set to null
testWidgets(
'adaptive scaffold selectedIndex can be set to null',
(WidgetTester tester) async {
await Future.forEach(SimulatedLayout.values,
(SimulatedLayout region) async {
int? selectedIndex;
final MaterialApp app = region.app(initialIndex: selectedIndex);
await tester.binding.setSurfaceSize(region.size);
await tester.pumpWidget(app);
await tester.pumpAndSettle();
});
},
);
testWidgets(
'when destinations passed with all data, it shall not be null',
(WidgetTester tester) async {
const List<NavigationDestination> destinations = <NavigationDestination>[
NavigationDestination(
icon: Icon(Icons.inbox_outlined),
selectedIcon: Icon(Icons.inbox),
label: 'Inbox',
),
NavigationDestination(
icon: Icon(Icons.video_call_outlined),
selectedIcon: Icon(Icons.video_call),
label: 'Video',
),
];
await tester.pumpWidget(
const MaterialApp(
home: MediaQuery(
data: MediaQueryData(size: Size(700, 900)),
child: AdaptiveScaffold(
destinations: destinations,
),
),
),
);
final Finder fNavigationRail = find.descendant(
of: find.byType(AdaptiveScaffold),
matching: find.byType(NavigationRail),
);
final NavigationRail navigationRail = tester.firstWidget(fNavigationRail);
expect(
navigationRail.destinations,
isA<List<NavigationRailDestination>>(),
);
expect(
navigationRail.destinations.length,
destinations.length,
);
for (final NavigationRailDestination destination
in navigationRail.destinations) {
expect(destination.label, isNotNull);
expect(destination.icon, isA<Icon>());
expect(destination.icon, isNotNull);
expect(destination.selectedIcon, isA<Icon?>());
expect(destination.selectedIcon, isNotNull);
}
final NavigationDestination firstDestinationFromListPassed =
destinations.first;
final NavigationRailDestination firstDestinationFromFinderView =
navigationRail.destinations.first;
expect(firstDestinationFromListPassed, isNotNull);
expect(firstDestinationFromFinderView, isNotNull);
expect(
firstDestinationFromListPassed.icon,
equals(firstDestinationFromFinderView.icon),
);
expect(
firstDestinationFromListPassed.selectedIcon,
equals(firstDestinationFromFinderView.selectedIcon),
);
},
);
testWidgets(
'when tap happens on any destination, its selected icon shall be visible',
(WidgetTester tester) async {
//region Keys
const ValueKey<String> firstDestinationIconKey = ValueKey<String>(
'first-normal-icon',
);
const ValueKey<String> firstDestinationSelectedIconKey = ValueKey<String>(
'first-selected-icon',
);
const ValueKey<String> lastDestinationIconKey = ValueKey<String>(
'last-normal-icon',
);
const ValueKey<String> lastDestinationSelectedIconKey = ValueKey<String>(
'last-selected-icon',
);
//endregion
//region Finder for destinations as per its icon.
final Finder firstDestinationWithSelectedIcon = find.byKey(
firstDestinationSelectedIconKey,
);
final Finder lastDestinationWithIcon = find.byKey(
lastDestinationIconKey,
);
final Finder firstDestinationWithIcon = find.byKey(
firstDestinationIconKey,
);
final Finder lastDestinationWithSelectedIcon = find.byKey(
lastDestinationSelectedIconKey,
);
//endregion
int selectedDestination = 0;
const List<NavigationDestination> destinations = <NavigationDestination>[
NavigationDestination(
icon: Icon(
Icons.inbox_outlined,
key: firstDestinationIconKey,
),
selectedIcon: Icon(
Icons.inbox,
key: firstDestinationSelectedIconKey,
),
label: 'Inbox',
),
NavigationDestination(
icon: Icon(
Icons.video_call_outlined,
key: lastDestinationIconKey,
),
selectedIcon: Icon(
Icons.video_call,
key: lastDestinationSelectedIconKey,
),
label: 'Video',
),
];
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(size: Size(700, 900)),
child: StatefulBuilder(
builder: (BuildContext context,
void Function(void Function()) setState) {
return AdaptiveScaffold(
destinations: destinations,
selectedIndex: selectedDestination,
onSelectedIndexChange: (int value) {
setState(() {
selectedDestination = value;
});
},
);
},
),
),
),
);
expect(selectedDestination, 0);
expect(firstDestinationWithSelectedIcon, findsOneWidget);
expect(lastDestinationWithIcon, findsOneWidget);
expect(firstDestinationWithIcon, findsNothing);
expect(lastDestinationWithSelectedIcon, findsNothing);
await tester.ensureVisible(lastDestinationWithIcon);
await tester.tap(lastDestinationWithIcon);
await tester.pumpAndSettle();
expect(selectedDestination, 1);
expect(firstDestinationWithSelectedIcon, findsNothing);
expect(lastDestinationWithIcon, findsNothing);
expect(firstDestinationWithIcon, findsOneWidget);
expect(lastDestinationWithSelectedIcon, findsOneWidget);
},
);
testWidgets(
'when view in medium screen, navigation rail must be visible as per theme data values.',
(WidgetTester tester) async {
await tester.binding.setSurfaceSize(SimulatedLayout.medium.size);
await tester.pumpWidget(SimulatedLayout.medium.app());
await tester.pumpAndSettle();
final Finder primaryNavigationMedium = find.byKey(
const Key('primaryNavigation'),
);
expect(primaryNavigationMedium, findsOneWidget);
final Finder navigationRailFinder = find.descendant(
of: primaryNavigationMedium,
matching: find.byType(NavigationRail),
);
expect(navigationRailFinder, findsOneWidget);
final NavigationRail navigationRailView = tester.firstWidget(
navigationRailFinder,
);
expect(navigationRailView, isNotNull);
expect(
navigationRailView.backgroundColor,
SimulatedLayout.navigationRailThemeBgColor,
);
expect(
navigationRailView.selectedIconTheme?.color,
SimulatedLayout.selectedIconThemeData.color,
);
expect(
navigationRailView.selectedIconTheme?.size,
SimulatedLayout.selectedIconThemeData.size,
);
expect(
navigationRailView.unselectedIconTheme?.color,
SimulatedLayout.unSelectedIconThemeData.color,
);
expect(
navigationRailView.unselectedIconTheme?.size,
SimulatedLayout.unSelectedIconThemeData.size,
);
},
);
testWidgets(
'when view in large screen, navigation rail must be visible as per theme data values.',
(WidgetTester tester) async {
await tester.binding.setSurfaceSize(SimulatedLayout.large.size);
await tester.pumpWidget(SimulatedLayout.large.app());
await tester.pumpAndSettle();
final Finder primaryNavigationLarge = find.byKey(
const Key('primaryNavigation1'),
);
expect(primaryNavigationLarge, findsOneWidget);
final Finder navigationRailFinder = find.descendant(
of: primaryNavigationLarge,
matching: find.byType(NavigationRail),
);
expect(navigationRailFinder, findsOneWidget);
final NavigationRail navigationRailView = tester.firstWidget(
navigationRailFinder,
);
expect(navigationRailView, isNotNull);
expect(
navigationRailView.backgroundColor,
SimulatedLayout.navigationRailThemeBgColor,
);
expect(
navigationRailView.selectedIconTheme?.color,
SimulatedLayout.selectedIconThemeData.color,
);
expect(
navigationRailView.selectedIconTheme?.size,
SimulatedLayout.selectedIconThemeData.size,
);
expect(
navigationRailView.unselectedIconTheme?.color,
SimulatedLayout.unSelectedIconThemeData.color,
);
expect(
navigationRailView.unselectedIconTheme?.size,
SimulatedLayout.unSelectedIconThemeData.size,
);
},
);
// This test checks whether AdaptiveScaffold.standardNavigationRail function
// creates a NavigationRail widget as expected with groupAlignment provided,
// and checks whether the NavigationRail's groupAlignment matches the expected value.
testWidgets(
'groupAligment parameter of AdaptiveScaffold.standardNavigationRail works correctly',
(WidgetTester tester) async {
const List<NavigationRailDestination> destinations =
<NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.home),
label: Text('Home'),
),
NavigationRailDestination(
icon: Icon(Icons.account_circle),
label: Text('Profile'),
),
NavigationRailDestination(
icon: Icon(Icons.settings),
label: Text('Settings'),
),
];
// Align to bottom.
const double groupAlignment = 1.0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return AdaptiveScaffold.standardNavigationRail(
destinations: destinations,
groupAlignment: groupAlignment,
);
},
),
),
),
);
final NavigationRail rail =
tester.widget<NavigationRail>(find.byType(NavigationRail));
expect(rail.groupAlignment, equals(groupAlignment));
});
testWidgets(
"doesn't override Directionality",
(WidgetTester tester) async {
const List<NavigationDestination> destinations = <NavigationDestination>[
NavigationDestination(
icon: Icon(Icons.home),
label: 'Home',
),
NavigationDestination(
icon: Icon(Icons.account_circle),
label: 'Profile',
),
];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Directionality(
textDirection: TextDirection.rtl,
child: AdaptiveScaffold(
destinations: destinations,
body: (BuildContext context) {
return const SizedBox.shrink();
},
),
),
),
),
);
final Finder body = find.byKey(const Key('body'));
expect(body, findsOneWidget);
final TextDirection dir = Directionality.of(body.evaluate().first);
expect(dir, TextDirection.rtl);
},
);
testWidgets(
'when appBarBreakpoint is provided validate an AppBar is showing without Drawer on larger than mobile',
(WidgetTester tester) async {
await tester.binding.setSurfaceSize(SimulatedLayout.medium.size);
await tester.pumpWidget(SimulatedLayout.medium
.app(appBarBreakpoint: AppBarAlwaysOnBreakpoint()));
await tester.pumpAndSettle();
final Finder appBar = find.byType(AppBar);
final Finder drawer = find.byType(Drawer);
expect(appBar, findsOneWidget);
expect(drawer, findsNothing);
await tester.binding.setSurfaceSize(SimulatedLayout.large.size);
await tester.pumpWidget(SimulatedLayout.large
.app(appBarBreakpoint: AppBarAlwaysOnBreakpoint()));
expect(drawer, findsNothing);
await tester.pumpAndSettle();
expect(appBar, findsOneWidget);
},
);
}
/// An empty widget that implements [PreferredSizeWidget] to ensure that
/// [PreferredSizeWidget] is used as [AdaptiveScaffold.appBar] parameter instead
/// of [AppBar].
class PreferredSizeWidgetImpl extends StatelessWidget
implements PreferredSizeWidget {
const PreferredSizeWidgetImpl({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
@override
Size get preferredSize => const Size(200, 200);
}
| packages/packages/flutter_adaptive_scaffold/test/adaptive_scaffold_test.dart/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/test/adaptive_scaffold_test.dart",
"repo_id": "packages",
"token_count": 8666
} | 1,156 |
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
| packages/packages/flutter_lints/example/analysis_options.yaml/0 | {
"file_path": "packages/packages/flutter_lints/example/analysis_options.yaml",
"repo_id": "packages",
"token_count": 399
} | 1,157 |
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdk flutter.compileSdkVersion
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "io.flutter.packages.flutter_markdown_example"
minSdkVersion flutter.minSdkVersion
targetSdkVersion 33
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
namespace 'io.flutter.packages.flutter_markdown_example'
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
| packages/packages/flutter_markdown/example/android/app/build.gradle/0 | {
"file_path": "packages/packages/flutter_markdown/example/android/app/build.gradle",
"repo_id": "packages",
"token_count": 672
} | 1,158 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(goderbauer): Restructure the examples to avoid this ignore, https://github.com/flutter/flutter/issues/110208.
// ignore_for_file: avoid_implementing_value_types
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../shared/markdown_demo_widget.dart';
// ignore_for_file: public_member_api_docs
const String _markdownData = """
# Markdown Example
Markdown allows you to easily include formatted text, images, and even formatted
Dart code in your app.
## Titles
Setext-style
```
This is an H1
=============
This is an H2
-------------
```
Atx-style
```
# This is an H1
## This is an H2
###### This is an H6
```
Select the valid headers:
- [x] `# hello`
- [ ] `#hello`
## Links
[Google's Homepage][Google]
```
[inline-style](https://www.google.com)
[reference-style][Google]
```
## Images

## Tables
|Syntax |Result |
|---------------------------------------|-------------------------------------|
|`*italic 1*` |*italic 1* |
|`_italic 2_` | _italic 2_ |
|`**bold 1**` |**bold 1** |
|`__bold 2__` |__bold 2__ |
|`This is a ~~strikethrough~~` |This is a ~~strikethrough~~ |
|`***italic bold 1***` |***italic bold 1*** |
|`___italic bold 2___` |___italic bold 2___ |
|`***~~italic bold strikethrough 1~~***`|***~~italic bold strikethrough 1~~***|
|`~~***italic bold strikethrough 2***~~`|~~***italic bold strikethrough 2***~~|
## Styling
Style text as _italic_, __bold__, ~~strikethrough~~, or `inline code`.
- Use bulleted lists
- To better clarify
- Your points
## Code blocks
Formatted Dart code looks really pretty too:
```
void main() {
runApp(MaterialApp(
home: Scaffold(
body: Markdown(data: markdownData),
),
));
}
```
## Center Title
###### ※ ※ ※
_* How to implement it see main.dart#L129 in example._
## Custom Syntax
NaOH + Al_2O_3 = NaAlO_2 + H_2O
C_4H_10 = C_2H_6 + C_2H_4
## Markdown widget
This is an example of how to create your own Markdown widget:
Markdown(data: 'Hello _world_!');
Enjoy!
[Google]: https://www.google.com/
## Line Breaks
This is an example of how to create line breaks (tab or two whitespaces):
line 1
line 2
line 3
""";
const String _notes = """
# Original Markdown Demo
---
## Overview
This is the original Flutter Markdown demo example that was created to
show how to use the flutter_markdown package. There were limitations in
the implementation of this demo example that didn't show the full potential
or extensibility of using the flutter_markdown package. This demo example
is being preserved for reference purposes.
## Comments
This demo example is being preserved for reference purposes.
""";
class OriginalMarkdownDemo extends StatelessWidget
implements MarkdownDemoWidget {
OriginalMarkdownDemo({super.key});
static const String _title = 'Original Markdown Demo';
@override
String get title => OriginalMarkdownDemo._title;
@override
String get description => 'The original demo example. This demo was '
'include with versions of the package prior to version 0.4.4.';
@override
Future<String> get data => Future<String>.value(_markdownData);
@override
Future<String> get notes => Future<String>.value(_notes);
final ScrollController controller = ScrollController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Markdown(
controller: controller,
selectable: true,
data: _markdownData,
imageDirectory: 'https://raw.githubusercontent.com',
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.arrow_upward),
onPressed: () => controller.animateTo(0,
duration: const Duration(seconds: 1), curve: Curves.easeOut),
),
);
}
}
| packages/packages/flutter_markdown/example/lib/demos/original_demo.dart/0 | {
"file_path": "packages/packages/flutter_markdown/example/lib/demos/original_demo.dart",
"repo_id": "packages",
"token_count": 1755
} | 1,159 |
<!DOCTYPE html>
<!-- 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. -->
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
Fore more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
-->
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="flutter_markdown_example">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>flutter_markdown_example</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('flutter-first-frame', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
| packages/packages/flutter_markdown/example/web/index.html/0 | {
"file_path": "packages/packages/flutter_markdown/example/web/index.html",
"repo_id": "packages",
"token_count": 569
} | 1,160 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:markdown/markdown.dart' as md;
import 'utils.dart';
void main() => defineTests();
void defineTests() {
group('Custom Syntax', () {
testWidgets(
'Subscript',
(WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
Markdown(
data: 'H_2O',
extensionSet: md.ExtensionSet.none,
inlineSyntaxes: <md.InlineSyntax>[SubscriptSyntax()],
builders: <String, MarkdownElementBuilder>{
'sub': SubscriptBuilder(),
},
),
),
);
final Iterable<Widget> widgets = tester.allWidgets;
expectTextStrings(widgets, <String>['H₂O']);
},
);
testWidgets(
'Custom block element',
(WidgetTester tester) async {
const String blockContent = 'note block';
await tester.pumpWidget(
boilerplate(
Markdown(
data: '[!NOTE] $blockContent',
extensionSet: md.ExtensionSet.none,
blockSyntaxes: <md.BlockSyntax>[NoteSyntax()],
builders: <String, MarkdownElementBuilder>{
'note': NoteBuilder(),
},
),
),
);
final ColoredBox container =
tester.widgetList(find.byType(ColoredBox)).first as ColoredBox;
expect(container.color, Colors.red);
expect(container.child, isInstanceOf<Text>());
expect((container.child! as Text).data, blockContent);
},
);
testWidgets(
'link for wikistyle',
(WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
Markdown(
data: 'This is a [[wiki link]]',
extensionSet: md.ExtensionSet.none,
inlineSyntaxes: <md.InlineSyntax>[WikilinkSyntax()],
builders: <String, MarkdownElementBuilder>{
'wikilink': WikilinkBuilder(),
},
),
),
);
final Text textWidget = tester.widget(find.byType(Text));
final TextSpan span =
(textWidget.textSpan! as TextSpan).children![1] as TextSpan;
expect(span.children, null);
expect(span.recognizer.runtimeType, equals(TapGestureRecognizer));
},
);
testWidgets(
'WidgetSpan in Text.rich is handled correctly',
(WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
Markdown(
data: 'container is a widget that allows to customize its child',
extensionSet: md.ExtensionSet.none,
inlineSyntaxes: <md.InlineSyntax>[ContainerSyntax()],
builders: <String, MarkdownElementBuilder>{
'container': ContainerBuilder(),
},
),
),
);
final Text textWidget = tester.widget(find.byType(Text));
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
final WidgetSpan widgetSpan = textSpan.children![0] as WidgetSpan;
expect(widgetSpan.child, isInstanceOf<Container>());
},
);
testWidgets(
'visitElementAfterWithContext is handled correctly',
(WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
Markdown(
data: r'# This is a header with some \color1{color} in it',
extensionSet: md.ExtensionSet.none,
inlineSyntaxes: <md.InlineSyntax>[InlineTextColorSyntax()],
builders: <String, MarkdownElementBuilder>{
'inlineTextColor': InlineTextColorElementBuilder(),
},
),
),
);
final Text textWidget = tester.widget(find.byType(Text));
final TextSpan rootSpan = textWidget.textSpan! as TextSpan;
final TextSpan firstSpan = rootSpan.children![0] as TextSpan;
final TextSpan secondSpan = rootSpan.children![1] as TextSpan;
final TextSpan thirdSpan = rootSpan.children![2] as TextSpan;
expect(secondSpan.style!.color, Colors.red);
expect(secondSpan.style!.fontSize, firstSpan.style!.fontSize);
expect(secondSpan.style!.fontSize, thirdSpan.style!.fontSize);
},
);
});
testWidgets(
'TextSpan and WidgetSpan as children in Text.rich are handled correctly',
(WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
Markdown(
data: 'this test replaces a string with a container',
extensionSet: md.ExtensionSet.none,
inlineSyntaxes: <md.InlineSyntax>[ContainerSyntax()],
builders: <String, MarkdownElementBuilder>{
'container': ContainerBuilder2(),
},
),
),
);
final Text textWidget = tester.widget(find.byType(Text));
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
final TextSpan start = textSpan.children![0] as TextSpan;
expect(start.text, 'this test replaces a string with a ');
final TextSpan foo = textSpan.children![1] as TextSpan;
expect(foo.text, 'foo');
final WidgetSpan widgetSpan = textSpan.children![2] as WidgetSpan;
expect(widgetSpan.child, isInstanceOf<Container>());
},
);
testWidgets(
'Custom rendering of tags without children',
(WidgetTester tester) async {
const String data = '';
await tester.pumpWidget(
boilerplate(
Markdown(
data: data,
builders: <String, MarkdownElementBuilder>{
'img': ImgBuilder(),
},
),
),
);
final Finder imageFinder = find.byType(Image);
expect(imageFinder, findsNothing);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = tester.widget(find.byType(Text));
expect(textWidget.data, 'foo');
},
);
}
class SubscriptSyntax extends md.InlineSyntax {
SubscriptSyntax() : super(_pattern);
static const String _pattern = r'_([0-9]+)';
@override
bool onMatch(md.InlineParser parser, Match match) {
parser.addNode(md.Element.text('sub', match[1]!));
return true;
}
}
class SubscriptBuilder extends MarkdownElementBuilder {
static const List<String> _subscripts = <String>[
'₀',
'₁',
'₂',
'₃',
'₄',
'₅',
'₆',
'₇',
'₈',
'₉'
];
@override
Widget visitElementAfter(md.Element element, _) {
// We don't currently have a way to control the vertical alignment of text spans.
// See https://github.com/flutter/flutter/issues/10906#issuecomment-385723664
final String textContent = element.textContent;
String text = '';
for (int i = 0; i < textContent.length; i++) {
text += _subscripts[int.parse(textContent[i])];
}
return Text.rich(TextSpan(text: text));
}
}
class WikilinkSyntax extends md.InlineSyntax {
WikilinkSyntax() : super(_pattern);
static const String _pattern = r'\[\[(.*?)\]\]';
@override
bool onMatch(md.InlineParser parser, Match match) {
final String link = match[1]!;
final md.Element el =
md.Element('wikilink', <md.Element>[md.Element.text('span', link)])
..attributes['href'] = link.replaceAll(' ', '_');
parser.addNode(el);
return true;
}
}
class WikilinkBuilder extends MarkdownElementBuilder {
@override
Widget visitElementAfter(md.Element element, _) {
return Text.rich(TextSpan(
text: element.textContent,
recognizer: TapGestureRecognizer()..onTap = () {}));
}
}
class ContainerSyntax extends md.InlineSyntax {
ContainerSyntax() : super(_pattern);
static const String _pattern = 'container';
@override
bool onMatch(md.InlineParser parser, Match match) {
parser.addNode(
md.Element.text('container', ''),
);
return true;
}
}
class ContainerBuilder extends MarkdownElementBuilder {
@override
Widget? visitElementAfter(md.Element element, _) {
return Text.rich(
TextSpan(
children: <InlineSpan>[
WidgetSpan(
child: Container(),
),
],
),
);
}
}
class ContainerBuilder2 extends MarkdownElementBuilder {
@override
Widget? visitElementAfter(md.Element element, _) {
return Text.rich(
TextSpan(
children: <InlineSpan>[
const TextSpan(text: 'foo'),
WidgetSpan(
child: Container(),
),
],
),
);
}
}
// Note: The implementation of inline span is incomplete, it does not handle
// bold, italic, ... text with a colored block.
// This would not work: `\color1{Text with *bold* text}`
class InlineTextColorSyntax extends md.InlineSyntax {
InlineTextColorSyntax() : super(r'\\color([1-9]){(.*?)}');
@override
bool onMatch(md.InlineParser parser, Match match) {
final String colorId = match.group(1)!;
final String textContent = match.group(2)!;
final md.Element node = md.Element.text(
'inlineTextColor',
textContent,
)..attributes['color'] = colorId;
parser.addNode(node);
parser.addNode(
md.Text(''),
);
return true;
}
}
class InlineTextColorElementBuilder extends MarkdownElementBuilder {
@override
Widget visitElementAfterWithContext(
BuildContext context,
md.Element element,
TextStyle? preferredStyle,
TextStyle? parentStyle,
) {
final String innerText = element.textContent;
final String color = element.attributes['color'] ?? '';
final Map<String, Color> contentColors = <String, Color>{
'1': Colors.red,
'2': Colors.green,
'3': Colors.blue,
};
final Color? contentColor = contentColors[color];
return Text.rich(
TextSpan(
text: innerText,
style: parentStyle?.copyWith(color: contentColor),
),
);
}
}
class ImgBuilder extends MarkdownElementBuilder {
@override
Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
return Text('foo', style: preferredStyle);
}
}
class NoteBuilder extends MarkdownElementBuilder {
@override
Widget? visitText(md.Text text, TextStyle? preferredStyle) {
return ColoredBox(
color: Colors.red, child: Text(text.text, style: preferredStyle));
}
@override
bool isBlockElement() {
return true;
}
}
class NoteSyntax extends md.BlockSyntax {
@override
md.Node? parse(md.BlockParser parser) {
final md.Line line = parser.current;
parser.advance();
return md.Element('note', <md.Node>[md.Text(line.content.substring(8))]);
}
@override
RegExp get pattern => RegExp(r'^\[!NOTE] ');
}
| packages/packages/flutter_markdown/test/custom_syntax_test.dart/0 | {
"file_path": "packages/packages/flutter_markdown/test/custom_syntax_test.dart",
"repo_id": "packages",
"token_count": 4738
} | 1,161 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_test/flutter_test.dart';
import 'utils.dart';
void main() => defineTests();
void defineTests() {
group('Style Sheet', () {
testWidgets(
'equality - Cupertino',
(WidgetTester tester) async {
const CupertinoThemeData theme =
CupertinoThemeData(brightness: Brightness.light);
final MarkdownStyleSheet style1 =
MarkdownStyleSheet.fromCupertinoTheme(theme);
final MarkdownStyleSheet style2 =
MarkdownStyleSheet.fromCupertinoTheme(theme);
expect(style1, equals(style2));
expect(style1.hashCode, equals(style2.hashCode));
},
);
testWidgets(
'equality - Material',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
final MarkdownStyleSheet style1 = MarkdownStyleSheet.fromTheme(theme);
final MarkdownStyleSheet style2 = MarkdownStyleSheet.fromTheme(theme);
expect(style1, equals(style2));
expect(style1.hashCode, equals(style2.hashCode));
},
);
testWidgets(
'MarkdownStyleSheet.fromCupertinoTheme',
(WidgetTester tester) async {
const CupertinoThemeData cTheme = CupertinoThemeData(
brightness: Brightness.dark,
);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromCupertinoTheme(cTheme);
// a
expect(style.a!.color, CupertinoColors.link.darkColor);
expect(style.a!.fontSize, cTheme.textTheme.textStyle.fontSize);
// p
expect(style.p, cTheme.textTheme.textStyle);
// code
expect(style.code!.color, cTheme.textTheme.textStyle.color);
expect(
style.code!.fontSize, cTheme.textTheme.textStyle.fontSize! * 0.85);
expect(style.code!.fontFamily, 'monospace');
expect(
style.code!.backgroundColor, CupertinoColors.systemGrey6.darkColor);
// H1
expect(style.h1!.color, cTheme.textTheme.textStyle.color);
expect(style.h1!.fontSize, cTheme.textTheme.textStyle.fontSize! + 10);
expect(style.h1!.fontWeight, FontWeight.w500);
// H2
expect(style.h2!.color, cTheme.textTheme.textStyle.color);
expect(style.h2!.fontSize, cTheme.textTheme.textStyle.fontSize! + 8);
expect(style.h2!.fontWeight, FontWeight.w500);
// H3
expect(style.h3!.color, cTheme.textTheme.textStyle.color);
expect(style.h3!.fontSize, cTheme.textTheme.textStyle.fontSize! + 6);
expect(style.h3!.fontWeight, FontWeight.w500);
// H4
expect(style.h4!.color, cTheme.textTheme.textStyle.color);
expect(style.h4!.fontSize, cTheme.textTheme.textStyle.fontSize! + 4);
expect(style.h4!.fontWeight, FontWeight.w500);
// H5
expect(style.h5!.color, cTheme.textTheme.textStyle.color);
expect(style.h5!.fontSize, cTheme.textTheme.textStyle.fontSize! + 2);
expect(style.h5!.fontWeight, FontWeight.w500);
// H6
expect(style.h6!.color, cTheme.textTheme.textStyle.color);
expect(style.h6!.fontSize, cTheme.textTheme.textStyle.fontSize);
expect(style.h6!.fontWeight, FontWeight.w500);
// em
expect(style.em!.color, cTheme.textTheme.textStyle.color);
expect(style.em!.fontSize, cTheme.textTheme.textStyle.fontSize);
expect(style.em!.fontStyle, FontStyle.italic);
// strong
expect(style.strong!.color, cTheme.textTheme.textStyle.color);
expect(style.strong!.fontSize, cTheme.textTheme.textStyle.fontSize);
expect(style.strong!.fontWeight, FontWeight.bold);
// del
expect(style.del!.color, cTheme.textTheme.textStyle.color);
expect(style.del!.fontSize, cTheme.textTheme.textStyle.fontSize);
expect(style.del!.decoration, TextDecoration.lineThrough);
// blockqoute
expect(style.blockquote, cTheme.textTheme.textStyle);
// img
expect(style.img, cTheme.textTheme.textStyle);
// checkbox
expect(style.checkbox!.color, cTheme.primaryColor);
expect(style.checkbox!.fontSize, cTheme.textTheme.textStyle.fontSize);
// tableHead
expect(style.tableHead!.color, cTheme.textTheme.textStyle.color);
expect(style.tableHead!.fontSize, cTheme.textTheme.textStyle.fontSize);
expect(style.tableHead!.fontWeight, FontWeight.w600);
// tableBody
expect(style.tableBody, cTheme.textTheme.textStyle);
},
);
testWidgets(
'MarkdownStyleSheet.fromTheme',
(WidgetTester tester) async {
final ThemeData theme = ThemeData.dark().copyWith(
textTheme: const TextTheme(
bodyMedium: TextStyle(fontSize: 12.0),
),
);
final MarkdownStyleSheet style = MarkdownStyleSheet.fromTheme(theme);
// a
expect(style.a!.color, Colors.blue);
// p
expect(style.p, theme.textTheme.bodyMedium);
// code
expect(style.code!.color, theme.textTheme.bodyMedium!.color);
expect(
style.code!.fontSize, theme.textTheme.bodyMedium!.fontSize! * 0.85);
expect(style.code!.fontFamily, 'monospace');
expect(style.code!.backgroundColor, theme.cardColor);
// H1
expect(style.h1, theme.textTheme.headlineSmall);
// H2
expect(style.h2, theme.textTheme.titleLarge);
// H3
expect(style.h3, theme.textTheme.titleMedium);
// H4
expect(style.h4, theme.textTheme.bodyLarge);
// H5
expect(style.h5, theme.textTheme.bodyLarge);
// H6
expect(style.h6, theme.textTheme.bodyLarge);
// em
expect(style.em!.fontStyle, FontStyle.italic);
expect(style.em!.color, theme.textTheme.bodyMedium!.color);
// strong
expect(style.strong!.fontWeight, FontWeight.bold);
expect(style.strong!.color, theme.textTheme.bodyMedium!.color);
// del
expect(style.del!.decoration, TextDecoration.lineThrough);
expect(style.del!.color, theme.textTheme.bodyMedium!.color);
// blockqoute
expect(style.blockquote, theme.textTheme.bodyMedium);
// img
expect(style.img, theme.textTheme.bodyMedium);
// checkbox
expect(style.checkbox!.color, theme.primaryColor);
expect(style.checkbox!.fontSize, theme.textTheme.bodyMedium!.fontSize);
// tableHead
expect(style.tableHead!.fontWeight, FontWeight.w600);
// tableBody
expect(style.tableBody, theme.textTheme.bodyMedium);
},
);
testWidgets(
'merge 2 style sheets',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
final MarkdownStyleSheet style1 = MarkdownStyleSheet.fromTheme(theme);
final MarkdownStyleSheet style2 = MarkdownStyleSheet(
p: const TextStyle(color: Colors.red),
blockquote: const TextStyle(fontSize: 16),
);
final MarkdownStyleSheet merged = style1.merge(style2);
expect(merged.p!.color, Colors.red);
expect(merged.blockquote!.fontSize, 16);
expect(merged.blockquote!.color, theme.textTheme.bodyMedium!.color);
},
);
testWidgets(
'create based on which theme',
(WidgetTester tester) async {
const String data = '[title](url)';
await tester.pumpWidget(
boilerplate(
const Markdown(
data: data,
styleSheetTheme: MarkdownStyleSheetBaseTheme.cupertino,
),
),
);
final Text widget = tester.widget(find.byType(Text));
expect(widget.textSpan!.style!.color, CupertinoColors.link.color);
},
);
testWidgets(
'apply 2 distinct style sheets',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
final MarkdownStyleSheet style1 = MarkdownStyleSheet.fromTheme(theme);
final MarkdownStyleSheet style2 =
MarkdownStyleSheet.largeFromTheme(theme);
expect(style1, isNot(style2));
await tester.pumpWidget(
boilerplate(
Markdown(
data: '# Test',
styleSheet: style1,
),
),
);
final RichText text1 = tester.widget(find.byType(RichText));
await tester.pumpWidget(
boilerplate(
Markdown(
data: '# Test',
styleSheet: style2,
),
),
);
final RichText text2 = tester.widget(find.byType(RichText));
expect(text1.text, isNot(text2.text));
},
);
testWidgets(
'use stylesheet option listBulletPadding',
(WidgetTester tester) async {
const double paddingX = 20.0;
final MarkdownStyleSheet style = MarkdownStyleSheet(
listBulletPadding:
const EdgeInsets.symmetric(horizontal: paddingX));
await tester.pumpWidget(
boilerplate(
Markdown(
data: '1. Bullet\n 2. Bullet\n * Bullet',
styleSheet: style,
),
),
);
final List<Padding> paddings =
tester.widgetList<Padding>(find.byType(Padding)).toList();
expect(paddings.length, 3);
expect(
paddings.every(
(Padding p) => p.padding.along(Axis.horizontal) == paddingX * 2,
),
true,
);
},
);
testWidgets(
'check widgets for use stylesheet option h1Padding',
(WidgetTester tester) async {
const String data = '# Header';
const double paddingX = 20.0;
final MarkdownStyleSheet style = MarkdownStyleSheet(
h1Padding: const EdgeInsets.symmetric(horizontal: paddingX),
);
await tester.pumpWidget(boilerplate(MarkdownBody(
data: data,
styleSheet: style,
)));
final Iterable<Widget> widgets = selfAndDescendantWidgetsOf(
find.byType(MarkdownBody),
tester,
);
expectWidgetTypes(widgets, <Type>[
MarkdownBody,
Column,
Padding,
Wrap,
Text,
RichText,
]);
expectTextStrings(widgets, <String>['Header']);
},
);
testWidgets(
'use stylesheet option pPadding',
(WidgetTester tester) async {
const double paddingX = 20.0;
final MarkdownStyleSheet style = MarkdownStyleSheet(
pPadding: const EdgeInsets.symmetric(horizontal: paddingX),
);
await tester.pumpWidget(
boilerplate(
Markdown(
data: 'Test line 1\n\nTest line 2\n\nTest line 3\n# H1',
styleSheet: style,
),
),
);
final List<Padding> paddings =
tester.widgetList<Padding>(find.byType(Padding)).toList();
expect(paddings.length, 3);
expect(
paddings.every(
(Padding p) => p.padding.along(Axis.horizontal) == paddingX * 2,
),
true,
);
},
);
testWidgets(
'use stylesheet option h1Padding-h6Padding',
(WidgetTester tester) async {
const double paddingX = 20.0;
final MarkdownStyleSheet style = MarkdownStyleSheet(
h1Padding: const EdgeInsets.symmetric(horizontal: paddingX),
h2Padding: const EdgeInsets.symmetric(horizontal: paddingX),
h3Padding: const EdgeInsets.symmetric(horizontal: paddingX),
h4Padding: const EdgeInsets.symmetric(horizontal: paddingX),
h5Padding: const EdgeInsets.symmetric(horizontal: paddingX),
h6Padding: const EdgeInsets.symmetric(horizontal: paddingX),
);
await tester.pumpWidget(
boilerplate(
Markdown(
data:
'Test\n\n# H1\n## H2\n### H3\n#### H4\n##### H5\n###### H6\n',
styleSheet: style,
),
),
);
final List<Padding> paddings =
tester.widgetList<Padding>(find.byType(Padding)).toList();
expect(paddings.length, 6);
expect(
paddings.every(
(Padding p) => p.padding.along(Axis.horizontal) == paddingX * 2,
),
true,
);
},
);
testWidgets(
'deprecated textScaleFactor is converted to linear scaler',
(WidgetTester tester) async {
const double scaleFactor = 2.0;
final MarkdownStyleSheet style = MarkdownStyleSheet(
textScaleFactor: scaleFactor,
);
expect(style.textScaler, const TextScaler.linear(scaleFactor));
expect(style.textScaleFactor, scaleFactor);
},
);
testWidgets(
'deprecated textScaleFactor is null when a scaler is provided',
(WidgetTester tester) async {
const TextScaler scaler = TextScaler.linear(2.0);
final MarkdownStyleSheet style = MarkdownStyleSheet(
textScaler: scaler,
);
expect(style.textScaler, scaler);
expect(style.textScaleFactor, null);
},
);
testWidgets(
'copyWith textScaler overwrites both textScaler and textScaleFactor',
(WidgetTester tester) async {
final MarkdownStyleSheet original = MarkdownStyleSheet(
textScaleFactor: 2.0,
);
const TextScaler newScaler = TextScaler.linear(3.0);
final MarkdownStyleSheet copy = original.copyWith(
textScaler: newScaler,
);
expect(copy.textScaler, newScaler);
expect(copy.textScaleFactor, null);
},
);
testWidgets(
'copyWith textScaleFactor overwrites both textScaler and textScaleFactor',
(WidgetTester tester) async {
final MarkdownStyleSheet original = MarkdownStyleSheet(
textScaleFactor: 2.0,
);
const double newScaleFactor = 3.0;
final MarkdownStyleSheet copy = original.copyWith(
textScaleFactor: newScaleFactor,
);
expect(copy.textScaler, const TextScaler.linear(newScaleFactor));
expect(copy.textScaleFactor, newScaleFactor);
},
);
});
}
| packages/packages/flutter_markdown/test/style_sheet_test.dart/0 | {
"file_path": "packages/packages/flutter_markdown/test/style_sheet_test.dart",
"repo_id": "packages",
"token_count": 6643
} | 1,162 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/command_runner.dart';
import 'logger.dart';
import 'project.dart';
enum ExitStatus {
success,
warning,
fail,
killed,
}
const String flutterNoPubspecMessage = 'Error: No pubspec.yaml file found.\n'
'This command should be run from the root of your Flutter project.';
class CommandResult {
const CommandResult(this.exitStatus);
/// A command that succeeded. It is used to log the result of a command invocation.
factory CommandResult.success() {
return const CommandResult(ExitStatus.success);
}
/// A command that exited with a warning. It is used to log the result of a command invocation.
factory CommandResult.warning() {
return const CommandResult(ExitStatus.warning);
}
/// A command that failed. It is used to log the result of a command invocation.
factory CommandResult.fail() {
return const CommandResult(ExitStatus.fail);
}
final ExitStatus exitStatus;
@override
String toString() {
switch (exitStatus) {
case ExitStatus.success:
return 'success';
case ExitStatus.warning:
return 'warning';
case ExitStatus.fail:
return 'fail';
case ExitStatus.killed:
return 'killed';
}
}
}
abstract class MigrateCommand extends Command<void> {
@override
Future<void> run() async {
await runCommand();
return;
}
Future<CommandResult> runCommand();
/// Gets the parsed command-line option named [name] as a `bool?`.
bool? boolArg(String name) {
if (!argParser.options.containsKey(name)) {
return null;
}
return argResults == null ? null : argResults![name] as bool;
}
String? stringArg(String name) {
if (!argParser.options.containsKey(name)) {
return null;
}
return argResults == null ? null : argResults![name] as String?;
}
/// Gets the parsed command-line option named [name] as an `int`.
int? intArg(String name) => argResults?[name] as int?;
bool validateWorkingDirectory(FlutterProject project, Logger logger) {
if (!project.pubspecFile.existsSync()) {
logger.printError(flutterNoPubspecMessage);
return false;
}
return true;
}
}
| packages/packages/flutter_migrate/lib/src/base/command.dart/0 | {
"file_path": "packages/packages/flutter_migrate/lib/src/base/command.dart",
"repo_id": "packages",
"token_count": 767
} | 1,163 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:process/process.dart';
import 'base/common.dart';
import 'base/logger.dart';
/// Polls the flutter tool for details about the environment and project and exposes it as
/// a mapping of String keys to values.
///
/// This class is based on the `flutter analyze --suggestions --machine` flutter_tools command
/// which dumps various variables as JSON.
class FlutterToolsEnvironment {
/// Constructs a tools environment out of a mapping of Strings to Object values.
///
/// Each key is the String URI-style description of a value in the Flutter tool
/// and is mapped to a String or boolean value. The mapping should align with the
/// JSON output of `flutter analyze --suggestions --machine`.
FlutterToolsEnvironment({
required Map<String, Object?> mapping,
}) : _mapping = mapping;
/// Creates a FlutterToolsEnvironment instance by calling `flutter analyze --suggestions --machine`
/// and parsing its output.
static Future<FlutterToolsEnvironment> initializeFlutterToolsEnvironment(
ProcessManager processManager, Logger logger) async {
final ProcessResult result = await processManager
.run(<String>['flutter', 'analyze', '--suggestions', '--machine']);
if (result.exitCode != 0) {
if ((result.stderr as String).contains(
'The "--machine" flag is only valid with the "--version" flag.')) {
logger.printError(
'The migrate tool is only compatible with flutter tools 3.4.0 or newer (git hash: 21861423f25ad03c2fdb33854b53f195bc117cb3).');
}
throwToolExit(
'Flutter tool exited while running `flutter analyze --suggestions --machine` with: ${result.stderr}');
}
String commandOutput = (result.stdout as String).trim();
Map<String, Object?> mapping = <String, Object?>{};
// minimally validate basic JSON format and trim away any accidental logging before.
if (commandOutput.contains(RegExp(r'[\s\S]*{[\s\S]+}[\s\S]*'))) {
commandOutput = commandOutput.substring(commandOutput.indexOf('{'));
mapping = jsonDecode(commandOutput.replaceAll(r'\', r'\\'))
as Map<String, Object?>;
}
return FlutterToolsEnvironment(mapping: mapping);
}
final Map<String, Object?> _mapping;
Object? operator [](String key) {
if (_mapping.containsKey(key)) {
return _mapping[key];
}
return null;
}
/// Returns the String stored at the key and null if
/// the key does not exist or is not a String.
String? getString(String key) {
final Object? value = _mapping[key];
return value is String? ? value : null;
}
/// Returns the bool stored at the key and null if
/// the key does not exist or is not a bool.
bool? getBool(String key) {
final Object? value = _mapping[key];
return value is bool? ? value : null;
}
bool containsKey(String key) {
return _mapping.containsKey(key);
}
}
| packages/packages/flutter_migrate/lib/src/environment.dart/0 | {
"file_path": "packages/packages/flutter_migrate/lib/src/environment.dart",
"repo_id": "packages",
"token_count": 1017
} | 1,164 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_migrate/src/base/common.dart';
import 'package:flutter_migrate/src/base/file_system.dart';
import 'package:flutter_migrate/src/base/logger.dart';
import 'package:flutter_migrate/src/base/project.dart';
import 'package:flutter_migrate/src/base/signals.dart';
import 'package:flutter_migrate/src/compute.dart';
import 'package:flutter_migrate/src/environment.dart';
import 'package:flutter_migrate/src/flutter_project_metadata.dart';
import 'package:flutter_migrate/src/migrate_logger.dart';
import 'package:flutter_migrate/src/result.dart';
import 'package:flutter_migrate/src/utils.dart';
import 'package:path/path.dart';
import 'package:process/process.dart';
import 'environment_test.dart';
import 'src/common.dart';
import 'src/context.dart';
import 'src/test_utils.dart';
import 'test_data/migrate_project.dart';
void main() {
late FileSystem fileSystem;
late BufferLogger logger;
late MigrateUtils utils;
late MigrateContext context;
late MigrateResult result;
late Directory targetFlutterDirectory;
late Directory newerTargetFlutterDirectory;
late Directory currentDir;
late FlutterToolsEnvironment environment;
late ProcessManager processManager;
late FakeProcessManager envProcessManager;
late String separator;
const String oldSdkRevision = '5391447fae6209bb21a89e6a5a6583cac1af9b4b';
const String newSdkRevision = '85684f9300908116a78138ea4c6036c35c9a1236';
Future<void> setUpFullEnv() async {
fileSystem = LocalFileSystem.test(signals: LocalSignals.instance);
currentDir = createResolvedTempDirectorySync('current_app.');
logger = BufferLogger.test();
processManager = const LocalProcessManager();
utils = MigrateUtils(
logger: logger,
fileSystem: fileSystem,
processManager: processManager,
);
await MigrateProject.installProject('version:1.22.6_stable', currentDir);
final FlutterProjectFactory flutterFactory = FlutterProjectFactory();
final FlutterProject flutterProject =
flutterFactory.fromDirectory(currentDir);
result = MigrateResult.empty();
final MigrateLogger migrateLogger =
MigrateLogger(logger: logger, verbose: true);
migrateLogger.start();
separator = isWindows ? r'\\' : '/';
envProcessManager = FakeProcessManager('''
{
"FlutterProject.directory": "/Users/test/flutter",
"FlutterProject.metadataFile": "/Users/test/flutter/.metadata",
"FlutterProject.android.exists": false,
"FlutterProject.ios.exists": false,
"FlutterProject.web.exists": false,
"FlutterProject.macos.exists": false,
"FlutterProject.linux.exists": false,
"FlutterProject.windows.exists": false,
"FlutterProject.fuchsia.exists": false,
"FlutterProject.android.isKotlin": false,
"FlutterProject.ios.isSwift": false,
"FlutterProject.isModule": false,
"FlutterProject.isPlugin": false,
"FlutterProject.manifest.appname": "test_app_name",
"FlutterVersion.frameworkRevision": "4e181f012c717777681862e4771af5a941774bb9",
"Platform.operatingSystem": "macos",
"Platform.isAndroid": true,
"Platform.isIOS": false,
"Platform.isWindows": ${isWindows ? 'true' : 'false'},
"Platform.isMacOS": ${isMacOS ? 'true' : 'false'},
"Platform.isFuchsia": false,
"Platform.pathSeparator": "$separator",
"Cache.flutterRoot": "/Users/test/flutter"
}
''');
environment =
await FlutterToolsEnvironment.initializeFlutterToolsEnvironment(
envProcessManager, logger);
context = MigrateContext(
flutterProject: flutterProject,
skippedPrefixes: <String>{},
fileSystem: fileSystem,
migrateLogger: migrateLogger,
migrateUtils: utils,
environment: environment,
);
targetFlutterDirectory =
createResolvedTempDirectorySync('targetFlutterDir.');
newerTargetFlutterDirectory =
createResolvedTempDirectorySync('newerTargetFlutterDir.');
await context.migrateUtils
.cloneFlutter(oldSdkRevision, targetFlutterDirectory.absolute.path);
await context.migrateUtils.cloneFlutter(
newSdkRevision, newerTargetFlutterDirectory.absolute.path);
}
group('MigrateFlutterProject', () {
setUp(() async {
await setUpFullEnv();
});
tearDown(() async {
tryToDelete(targetFlutterDirectory);
tryToDelete(newerTargetFlutterDirectory);
});
testUsingContext('MigrateTargetFlutterProject creates', () async {
final Directory workingDir =
createResolvedTempDirectorySync('migrate_working_dir.');
final Directory targetDir =
createResolvedTempDirectorySync('target_dir.');
result.generatedTargetTemplateDirectory = targetDir;
workingDir.createSync(recursive: true);
final MigrateTargetFlutterProject targetProject =
MigrateTargetFlutterProject(
path: null,
directory: targetDir,
name: 'base',
androidLanguage: 'java',
iosLanguage: 'objc',
);
await targetProject.createProject(
context,
result,
oldSdkRevision, //targetRevision
targetFlutterDirectory, //targetFlutterDirectory
);
expect(targetDir.childFile('pubspec.yaml').existsSync(), true);
expect(
targetDir
.childDirectory('android')
.childFile('build.gradle')
.existsSync(),
true);
}, timeout: const Timeout(Duration(seconds: 500)));
testUsingContext('MigrateBaseFlutterProject creates', () async {
final Directory workingDir =
createResolvedTempDirectorySync('migrate_working_dir.');
final Directory baseDir = createResolvedTempDirectorySync('base_dir.');
result.generatedBaseTemplateDirectory = baseDir;
workingDir.createSync(recursive: true);
final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject(
path: null,
directory: baseDir,
name: 'base',
androidLanguage: 'java',
iosLanguage: 'objc',
);
await baseProject.createProject(
context,
result,
<String>[oldSdkRevision], //revisionsList
<String, List<MigratePlatformConfig>>{
oldSdkRevision: <MigratePlatformConfig>[
MigratePlatformConfig(component: FlutterProjectComponent.android),
MigratePlatformConfig(component: FlutterProjectComponent.ios)
],
}, //revisionToConfigs
oldSdkRevision, //fallbackRevision
oldSdkRevision, //targetRevision
targetFlutterDirectory, //targetFlutterDirectory
);
expect(baseDir.childFile('pubspec.yaml').existsSync(), true);
expect(
baseDir
.childDirectory('android')
.childFile('build.gradle')
.existsSync(),
true);
}, timeout: const Timeout(Duration(seconds: 500)));
testUsingContext('Migrate___FlutterProject skips when path exists',
() async {
final Directory workingDir =
createResolvedTempDirectorySync('migrate_working_dir.');
final Directory targetDir =
createResolvedTempDirectorySync('target_dir.');
final Directory baseDir = createResolvedTempDirectorySync('base_dir.');
result.generatedTargetTemplateDirectory = targetDir;
result.generatedBaseTemplateDirectory = baseDir;
workingDir.createSync(recursive: true);
final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject(
path: 'some_existing_base_path',
directory: baseDir,
name: 'base',
androidLanguage: 'java',
iosLanguage: 'objc',
);
final MigrateTargetFlutterProject targetProject =
MigrateTargetFlutterProject(
path: 'some_existing_target_path',
directory: targetDir,
name: 'base',
androidLanguage: 'java',
iosLanguage: 'objc',
);
await baseProject.createProject(
context,
result,
<String>[oldSdkRevision], //revisionsList
<String, List<MigratePlatformConfig>>{
oldSdkRevision: <MigratePlatformConfig>[
MigratePlatformConfig(component: FlutterProjectComponent.android),
MigratePlatformConfig(component: FlutterProjectComponent.ios)
],
}, //revisionToConfigs
oldSdkRevision, //fallbackRevision
oldSdkRevision, //targetRevision
targetFlutterDirectory, //targetFlutterDirectory
);
expect(baseDir.childFile('pubspec.yaml').existsSync(), false);
expect(
baseDir
.childDirectory('android')
.childFile('build.gradle')
.existsSync(),
false);
await targetProject.createProject(
context,
result,
oldSdkRevision, //revisionsList
targetFlutterDirectory, //targetFlutterDirectory
);
expect(targetDir.childFile('pubspec.yaml').existsSync(), false);
expect(
targetDir
.childDirectory('android')
.childFile('build.gradle')
.existsSync(),
false);
}, timeout: const Timeout(Duration(seconds: 500)));
},
// TODO(stuartmorgan): These should not be unit tests, see
// https://github.com/flutter/flutter/issues/121257.
skip: 'TODO: Speed up, or move to another type of test');
group('MigrateRevisions', () {
setUp(() async {
fileSystem = LocalFileSystem.test(signals: LocalSignals.instance);
currentDir = createResolvedTempDirectorySync('current_app.');
logger = BufferLogger.test();
utils = MigrateUtils(
logger: logger,
fileSystem: fileSystem,
processManager: const LocalProcessManager(),
);
await MigrateProject.installProject('version:1.22.6_stable', currentDir);
final FlutterProjectFactory flutterFactory = FlutterProjectFactory();
final FlutterProject flutterProject =
flutterFactory.fromDirectory(currentDir);
result = MigrateResult.empty();
final MigrateLogger migrateLogger =
MigrateLogger(logger: logger, verbose: true);
migrateLogger.start();
context = MigrateContext(
flutterProject: flutterProject,
skippedPrefixes: <String>{},
fileSystem: fileSystem,
migrateLogger: migrateLogger,
migrateUtils: utils,
environment: environment,
);
});
testUsingContext('extracts revisions underpopulated metadata', () async {
final MigrateRevisions revisions = MigrateRevisions(
context: context,
baseRevision: oldSdkRevision,
allowFallbackBaseRevision: true,
platforms: <SupportedPlatform>[
SupportedPlatform.android,
SupportedPlatform.ios
],
environment: environment,
);
expect(revisions.revisionsList, <String>[oldSdkRevision]);
expect(revisions.fallbackRevision, oldSdkRevision);
expect(revisions.metadataRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(revisions.config.unmanagedFiles.isEmpty, false);
expect(revisions.config.platformConfigs.isEmpty, false);
expect(revisions.config.platformConfigs.length, 3);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.root),
true);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.android),
true);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.ios),
true);
});
testUsingContext('extracts revisions full metadata', () async {
final File metadataFile =
context.flutterProject.directory.childFile('.metadata');
if (metadataFile.existsSync()) {
if (!tryToDelete(metadataFile)) {
// TODO(garyq): Inaccessible .metadata on windows.
// Skip test for now. We should reneable.
return;
}
}
metadataFile.createSync(recursive: true);
metadataFile.writeAsStringSync('''
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
channel: unknown
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
base_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
- platform: android
create_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
base_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
- platform: ios
create_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
base_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
- platform: linux
create_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
base_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
- platform: macos
create_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
base_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
- platform: web
create_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
base_revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
- platform: windows
create_revision: 36427af29421f406ac95ff55ea31d1dc49a45b5f
base_revision: 36427af29421f406ac95ff55ea31d1dc49a45b5f
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'blah.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
''', flush: true);
final MigrateRevisions revisions = MigrateRevisions(
context: context,
baseRevision: oldSdkRevision,
allowFallbackBaseRevision: true,
platforms: <SupportedPlatform>[
SupportedPlatform.android,
SupportedPlatform.ios
],
environment: environment,
);
expect(revisions.revisionsList, <String>[oldSdkRevision]);
expect(revisions.fallbackRevision, oldSdkRevision);
expect(revisions.metadataRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(revisions.config.unmanagedFiles.isEmpty, false);
expect(revisions.config.unmanagedFiles.length, 3);
expect(revisions.config.unmanagedFiles.contains('lib/main.dart'), true);
expect(revisions.config.unmanagedFiles.contains('blah.dart'), true);
expect(
revisions.config.unmanagedFiles
.contains('ios/Runner.xcodeproj/project.pbxproj'),
true);
expect(revisions.config.platformConfigs.length, 7);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.root),
true);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.android),
true);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.ios),
true);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.linux),
true);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.macos),
true);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.web),
true);
expect(
revisions.config.platformConfigs
.containsKey(FlutterProjectComponent.windows),
true);
expect(
revisions.config.platformConfigs[FlutterProjectComponent.root]!
.createRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.android]!
.createRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.ios]!
.createRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.linux]!
.createRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.macos]!
.createRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.web]!
.createRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.windows]!
.createRevision,
'36427af29421f406ac95ff55ea31d1dc49a45b5f');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.root]!
.baseRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.android]!
.baseRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.ios]!
.baseRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.linux]!
.baseRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.macos]!
.baseRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.web]!
.baseRevision,
'9b2d32b605630f28625709ebd9d78ab3016b2bf6');
expect(
revisions.config.platformConfigs[FlutterProjectComponent.windows]!
.baseRevision,
'36427af29421f406ac95ff55ea31d1dc49a45b5f');
});
},
// TODO(stuartmorgan): These should not be unit tests, see
// https://github.com/flutter/flutter/issues/121257.
skip: 'TODO: Speed up, or move to another type of test');
group('project operations', () {
setUp(() async {
await setUpFullEnv();
});
tearDown(() async {
tryToDelete(targetFlutterDirectory);
tryToDelete(newerTargetFlutterDirectory);
});
testUsingContext('diff base and target', () async {
final Directory workingDir =
createResolvedTempDirectorySync('migrate_working_dir.');
final Directory targetDir =
createResolvedTempDirectorySync('target_dir.');
final Directory baseDir = createResolvedTempDirectorySync('base_dir.');
result.generatedTargetTemplateDirectory = targetDir;
result.generatedBaseTemplateDirectory = baseDir;
workingDir.createSync(recursive: true);
final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject(
path: null,
directory: baseDir,
name: 'base',
androidLanguage: 'java',
iosLanguage: 'objc',
);
final MigrateTargetFlutterProject targetProject =
MigrateTargetFlutterProject(
path: null,
directory: targetDir,
name: 'base',
androidLanguage: 'java',
iosLanguage: 'objc',
);
await baseProject.createProject(
context,
result,
<String>[oldSdkRevision], //revisionsList
<String, List<MigratePlatformConfig>>{
oldSdkRevision: <MigratePlatformConfig>[
MigratePlatformConfig(component: FlutterProjectComponent.android),
MigratePlatformConfig(component: FlutterProjectComponent.ios)
],
}, //revisionToConfigs
oldSdkRevision, //fallbackRevision
oldSdkRevision, //targetRevision
targetFlutterDirectory, //targetFlutterDirectory
);
expect(baseDir.childFile('pubspec.yaml').existsSync(), true);
expect(
baseDir
.childDirectory('android')
.childFile('build.gradle')
.existsSync(),
true);
await targetProject.createProject(
context,
result,
newSdkRevision, //revisionsList
newerTargetFlutterDirectory, //targetFlutterDirectory
);
expect(targetDir.childFile('pubspec.yaml').existsSync(), true);
expect(
targetDir
.childDirectory('android')
.childFile('build.gradle')
.existsSync(),
true);
final Map<String, DiffResult> diffResults =
await baseProject.diff(context, targetProject);
final Map<String, DiffResult> canonicalizedDiffResults =
<String, DiffResult>{};
for (final MapEntry<String, DiffResult> entry in diffResults.entries) {
canonicalizedDiffResults[canonicalize(entry.key)] = entry.value;
}
result.diffMap.addAll(diffResults);
List<String> expectedFiles = <String>[
'.metadata',
'ios/Runner.xcworkspace/contents.xcworkspacedata',
'ios/Runner/AppDelegate.h',
'ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected]',
'ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected]',
'ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md',
'ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json',
'ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]',
'ios/Runner/Base.lproj/LaunchScreen.storyboard',
'ios/Runner/Base.lproj/Main.storyboard',
'ios/Runner/main.m',
'ios/Runner/AppDelegate.m',
'ios/Runner/Info.plist',
'ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata',
'ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme',
'ios/Flutter/Debug.xcconfig',
'ios/Flutter/Release.xcconfig',
'ios/Flutter/AppFrameworkInfo.plist',
'pubspec.yaml',
'.gitignore',
'android/base_android.iml',
'android/app/build.gradle',
'android/app/src/main/res/mipmap-mdpi/ic_launcher.png',
'android/app/src/main/res/mipmap-hdpi/ic_launcher.png',
'android/app/src/main/res/drawable/launch_background.xml',
'android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png',
'android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png',
'android/app/src/main/res/values/styles.xml',
'android/app/src/main/res/mipmap-xhdpi/ic_launcher.png',
'android/app/src/main/AndroidManifest.xml',
'android/app/src/main/java/com/example/base/MainActivity.java',
'android/local.properties',
'android/gradle/wrapper/gradle-wrapper.jar',
'android/gradle/wrapper/gradle-wrapper.properties',
'android/gradlew',
'android/build.gradle',
'android/gradle.properties',
'android/gradlew.bat',
'android/settings.gradle',
'base.iml',
'.idea/runConfigurations/main_dart.xml',
'.idea/libraries/Dart_SDK.xml',
'.idea/libraries/KotlinJavaRuntime.xml',
'.idea/libraries/Flutter_for_Android.xml',
'.idea/workspace.xml',
'.idea/modules.xml',
];
expectedFiles =
List<String>.from(expectedFiles.map((String e) => canonicalize(e)));
expect(diffResults.length, 62);
expect(expectedFiles.length, 62);
for (final String diffResultPath in canonicalizedDiffResults.keys) {
expect(expectedFiles.contains(diffResultPath), true);
}
// Spot check diffs on key files:
expect(
canonicalizedDiffResults[canonicalize('android/build.gradle')]!.diff,
contains(r'''
@@ -1,18 +1,20 @@
buildscript {
+ ext.kotlin_version = '1.6.10'
repositories {
google()
- jcenter()
+ mavenCentral()
}'''));
expect(
canonicalizedDiffResults[canonicalize('android/build.gradle')]!.diff,
contains(r'''
dependencies {
- classpath 'com.android.tools.build:gradle:3.2.1'
+ classpath 'com.android.tools.build:gradle:7.1.2'
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}'''));
expect(
canonicalizedDiffResults[canonicalize('android/build.gradle')]!.diff,
contains(r'''
allprojects {
repositories {
google()
- jcenter()
+ mavenCentral()
}
}'''));
expect(
canonicalizedDiffResults[
canonicalize('android/app/src/main/AndroidManifest.xml')]!
.diff,
contains(r'''
@@ -1,39 +1,34 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.base">
-
- <!-- The INTERNET permission is required for development. Specifically,
- flutter needs it to communicate with the running application
- to allow setting breakpoints, to provide hot reload, etc.
- -->
- <uses-permission android:name="android.permission.INTERNET"/>
-
- <!-- io.flutter.app.FlutterApplication is an android.app.Application that
- calls FlutterMain.startInitialization(this); in its onCreate method.
- In most cases you can leave this as-is, but you if you want to provide
- additional functionality it is fine to subclass or reimplement
- FlutterApplication and put your custom class here. -->
- <application
- android:name="io.flutter.app.FlutterApplication"
+ <application
android:label="base"
+ android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
+ android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
- android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
- <!-- This keeps the window background of the activity showing
- until Flutter renders its first frame. It can be removed if
- there is no splash screen (such as the default splash screen
- defined in @style/LaunchTheme). -->
+ <!-- Specifies an Android theme to apply to this Activity as soon as
+ the Android process has started. This theme is visible to the user
+ while the Flutter UI initializes. After that, this theme continues
+ to determine the Window background behind the Flutter UI. -->
<meta-data
- android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
- android:value="true" />
+ android:name="io.flutter.embedding.android.NormalTheme"
+ android:resource="@style/NormalTheme"
+ />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
+ <!-- Don't delete the meta-data below.
+ This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
+ <meta-data
+ android:name="flutterEmbedding"
+ android:value="2" />
</application>
</manifest>'''));
}, timeout: const Timeout(Duration(seconds: 500)));
testUsingContext('Merge succeeds', () async {
final Directory workingDir =
createResolvedTempDirectorySync('migrate_working_dir.');
final Directory targetDir =
createResolvedTempDirectorySync('target_dir.');
final Directory baseDir = createResolvedTempDirectorySync('base_dir.');
result.generatedTargetTemplateDirectory = targetDir;
result.generatedBaseTemplateDirectory = baseDir;
workingDir.createSync(recursive: true);
final MigrateBaseFlutterProject baseProject = MigrateBaseFlutterProject(
path: null,
directory: baseDir,
name: 'base',
androidLanguage: 'java',
iosLanguage: 'objc',
);
final MigrateTargetFlutterProject targetProject =
MigrateTargetFlutterProject(
path: null,
directory: targetDir,
name: 'base',
androidLanguage: 'java',
iosLanguage: 'objc',
);
await baseProject.createProject(
context,
result,
<String>[oldSdkRevision], //revisionsList
<String, List<MigratePlatformConfig>>{
oldSdkRevision: <MigratePlatformConfig>[
MigratePlatformConfig(component: FlutterProjectComponent.android),
MigratePlatformConfig(component: FlutterProjectComponent.ios)
],
}, //revisionToConfigs
oldSdkRevision, //fallbackRevision
oldSdkRevision, //targetRevision
targetFlutterDirectory, //targetFlutterDirectory
);
expect(baseDir.childFile('pubspec.yaml').existsSync(), true);
expect(baseDir.childFile('.metadata').existsSync(), true);
expect(
baseDir
.childDirectory('android')
.childFile('build.gradle')
.existsSync(),
true);
await targetProject.createProject(
context,
result,
newSdkRevision, //revisionsList
newerTargetFlutterDirectory, //targetFlutterDirectory
);
expect(targetDir.childFile('pubspec.yaml').existsSync(), true);
expect(targetDir.childFile('.metadata').existsSync(), true);
expect(
targetDir
.childDirectory('android')
.childFile('build.gradle')
.existsSync(),
true);
result.diffMap.addAll(await baseProject.diff(context, targetProject));
await MigrateFlutterProject.merge(
context,
result,
baseProject,
targetProject,
<String>[], // unmanagedFiles
<String>[], // unmanagedDirectories
false, // preferTwoWayMerge
);
List<String> expectedMergedPaths = <String>[
'.metadata',
'ios/Runner/Info.plist',
'ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata',
'ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme',
'ios/Flutter/AppFrameworkInfo.plist',
'pubspec.yaml',
'.gitignore',
'android/app/build.gradle',
'android/app/src/main/res/values/styles.xml',
'android/app/src/main/AndroidManifest.xml',
'android/gradle/wrapper/gradle-wrapper.properties',
'android/build.gradle',
];
expectedMergedPaths = List<String>.from(
expectedMergedPaths.map((String e) => canonicalize(e)));
expect(result.mergeResults.length, 12);
expect(expectedMergedPaths.length, 12);
for (final MergeResult mergeResult in result.mergeResults) {
expect(
expectedMergedPaths.contains(canonicalize(mergeResult.localPath)),
true);
}
expect(result.mergeResults[0].exitCode, 0);
expect(result.mergeResults[1].exitCode, 0);
expect(result.mergeResults[2].exitCode, 0);
expect(result.mergeResults[3].exitCode, 0);
expect(result.mergeResults[4].exitCode, 0);
expect(result.mergeResults[5].exitCode, 0);
expect(result.mergeResults[6].exitCode, 0);
expect(result.mergeResults[7].exitCode, 0);
expect(result.mergeResults[8].exitCode, 0);
expect(result.mergeResults[9].exitCode, 0);
expect(result.mergeResults[10].exitCode, 0);
expect(result.mergeResults[11].exitCode, 0);
expect(result.mergeResults[0].hasConflict, false);
expect(result.mergeResults[1].hasConflict, false);
expect(result.mergeResults[2].hasConflict, false);
expect(result.mergeResults[3].hasConflict, false);
expect(result.mergeResults[4].hasConflict, false);
expect(result.mergeResults[5].hasConflict, false);
expect(result.mergeResults[6].hasConflict, false);
expect(result.mergeResults[7].hasConflict, false);
expect(result.mergeResults[8].hasConflict, false);
expect(result.mergeResults[9].hasConflict, false);
expect(result.mergeResults[10].hasConflict, false);
expect(result.mergeResults[11].hasConflict, false);
}, timeout: const Timeout(Duration(seconds: 500)));
},
// TODO(stuartmorgan): These should not be unit tests, see
// https://github.com/flutter/flutter/issues/121257.
skip: 'TODO: Speed up, or move to another type of test');
}
| packages/packages/flutter_migrate/test/compute_test.dart/0 | {
"file_path": "packages/packages/flutter_migrate/test/compute_test.dart",
"repo_id": "packages",
"token_count": 14607
} | 1,165 |
// 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_migrate/src/base/file_system.dart';
import 'package:flutter_migrate/src/base/io.dart';
import 'package:flutter_migrate/src/base/logger.dart';
import 'package:flutter_migrate/src/base/project.dart';
import 'package:flutter_migrate/src/base/signals.dart';
import 'package:flutter_migrate/src/base/terminal.dart';
import 'package:flutter_migrate/src/update_locks.dart';
import 'package:flutter_migrate/src/utils.dart';
import 'package:process/process.dart';
import 'package:yaml/yaml.dart';
import 'src/common.dart';
import 'src/test_utils.dart';
void main() {
late FileSystem fileSystem;
late BufferLogger logger;
late MigrateUtils utils;
late Directory currentDir;
late FlutterProject flutterProject;
late Terminal terminal;
late ProcessManager processManager;
setUp(() async {
fileSystem = LocalFileSystem.test(signals: LocalSignals.instance);
currentDir = createResolvedTempDirectorySync('current_app.');
logger = BufferLogger.test();
terminal = Terminal.test();
utils = MigrateUtils(
logger: logger,
fileSystem: fileSystem,
processManager: const LocalProcessManager(),
);
final FlutterProjectFactory flutterFactory = FlutterProjectFactory();
flutterProject = flutterFactory.fromDirectory(currentDir);
processManager = const LocalProcessManager();
});
tearDown(() async {
tryToDelete(currentDir);
});
testWithoutContext('updates pubspec locks', () async {
final ProcessResult result = await processManager.run(<String>[
'flutter',
'create',
currentDir.absolute.path,
'--project-name=testproject'
]);
expect(result.exitCode, 0);
final File pubspec = currentDir.childFile('pubspec.yaml');
pubspec.writeAsStringSync('''
name: testproject
description: A test flutter project.
environment:
sdk: ">=2.17.0-0 <3.0.0"
dependencies:
flutter:
sdk: flutter
characters: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
collection: 1.15.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
js: 0.6.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
material_color_utilities: 0.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
meta: 1.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vector_math: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
flutter:
uses-material-design: true
# PUBSPEC CHECKSUM: 1b91
''', flush: true);
await updatePubspecDependencies(flutterProject, utils, logger, terminal,
force: true);
final YamlMap pubspecYaml = loadYaml(pubspec.readAsStringSync()) as YamlMap;
final YamlMap dependenciesMap = pubspecYaml['dependencies'] as YamlMap;
expect(
_VersionCode.fromString(dependenciesMap['characters'] as String) >
_VersionCode.fromString('1.2.0'),
true);
expect(
_VersionCode.fromString(dependenciesMap['collection'] as String) >
_VersionCode.fromString('1.15.0'),
true);
expect(
_VersionCode.fromString(dependenciesMap['js'] as String) >
_VersionCode.fromString('0.6.3'),
true);
expect(
_VersionCode.fromString(
dependenciesMap['material_color_utilities'] as String) >
_VersionCode.fromString('0.1.0'),
true);
expect(
_VersionCode.fromString(dependenciesMap['meta'] as String) >
_VersionCode.fromString('1.7.0'),
true);
});
testWithoutContext('updates gradle locks', () async {
final ProcessResult result = await processManager.run(<String>[
'flutter',
'create',
currentDir.absolute.path,
'--project-name=testproject'
]);
expect(result.exitCode, 0);
final File projectAppLock =
currentDir.childDirectory('android').childFile('project-app.lockfile');
final File buildGradle =
currentDir.childDirectory('android').childFile('build.gradle');
final File gradleProperties =
currentDir.childDirectory('android').childFile('gradle.properties');
gradleProperties.writeAsStringSync('''
org.gradle.daemon=false
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
''', flush: true);
final File projectAppLockBackup = currentDir
.childDirectory('android')
.childFile('project-app.lockfile_backup_0');
expect(projectAppLockBackup.existsSync(), false);
projectAppLock.createSync(recursive: true);
projectAppLock.writeAsStringSync('''
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
androidx.activity:activity:1.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath
androidx.annotation:annotation-experimental:1.1.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath
androidx.annotation:annotation:1.2.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath
''', flush: true);
buildGradle.writeAsStringSync(r'''
buildscript {
ext.kotlin_version = '1.5.31'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
configurations.classpath {
resolutionStrategy.activateDependencyLocking()
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
dependencyLocking {
ignoredDependencies.add('io.flutter:*')
lockFile = file("${rootProject.projectDir}/project-${project.name}.lockfile")
if (!project.hasProperty('local-engine-repo')) {
lockAllConfigurations()
}
}
}
''', flush: true);
expect(
currentDir
.childDirectory('android')
.childFile('gradlew.bat')
.existsSync(),
true);
final Directory dotGradle =
currentDir.childDirectory('android').childDirectory('.gradle');
tryToDelete(dotGradle);
await updateGradleDependencyLocking(
flutterProject, utils, logger, terminal, true, fileSystem,
force: true);
expect(projectAppLockBackup.existsSync(), true);
expect(projectAppLock.existsSync(), true);
expect(projectAppLock.readAsStringSync(),
contains('# This is a Gradle generated file for dependency locking.'));
expect(projectAppLock.readAsStringSync(),
contains('# Manual edits can break the build and are not advised.'));
expect(projectAppLock.readAsStringSync(),
contains('# This file is expected to be part of source control.'));
}, timeout: const Timeout(Duration(seconds: 500)), skip: true);
}
class _VersionCode implements Comparable<_VersionCode> {
_VersionCode(this.first, this.second, this.third, this.caret);
_VersionCode.fromString(String str)
: first = 0,
second = 0,
third = 0,
caret = 0 {
caret = str.contains('^') ? 1 : 0;
str = str.replaceAll('^', '');
final List<String> splits = str.split('.');
assert(splits.length == 3);
first = int.parse(splits[0]);
second = int.parse(splits[1]);
third = int.parse(splits[2]);
}
int caret;
int first;
int second;
int third;
bool operator >(_VersionCode other) {
return compareTo(other) > 0;
}
bool operator <(_VersionCode other) {
return !(this > other);
}
@override
int compareTo(_VersionCode other) {
final int value = first * 10000000 + second * 100000 + third + caret;
final int otherValue =
other.first * 10000000 + other.second * 100000 + other.third + caret;
return value - otherValue;
}
}
| packages/packages/flutter_migrate/test/update_locks_test.dart/0 | {
"file_path": "packages/packages/flutter_migrate/test/update_locks_test.dart",
"repo_id": "packages",
"token_count": 3247
} | 1,166 |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
</resources>
| packages/packages/flutter_plugin_android_lifecycle/example/android/app/src/main/res/values/styles.xml/0 | {
"file_path": "packages/packages/flutter_plugin_android_lifecycle/example/android/app/src/main/res/values/styles.xml",
"repo_id": "packages",
"token_count": 125
} | 1,167 |
GoRouter allows you to customize the transition animation for each GoRoute. To
configure a custom transition animation, provide a `pageBuilder` parameter
to the GoRoute constructor:
```dart
GoRoute(
path: 'details',
pageBuilder: (context, state) {
return CustomTransitionPage(
key: state.pageKey,
child: DetailsScreen(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
// Change the opacity of the screen using a Curve based on the the animation's
// value
return FadeTransition(
opacity:
CurveTween(curve: Curves.easeInOutCirc).animate(animation),
child: child,
);
},
);
},
),
```
For a complete example, see the [transition animations
sample](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/transition_animations.dart).
For more information on animations in Flutter, visit the
[Animations](https://docs.flutter.dev/development/ui/animations) page on
flutter.dev. | packages/packages/go_router/doc/transition-animations.md/0 | {
"file_path": "packages/packages/go_router/doc/transition-animations.md",
"repo_id": "packages",
"token_count": 352
} | 1,168 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import '../data.dart';
/// The author list view.
class AuthorList extends StatelessWidget {
/// Creates an [AuthorList].
const AuthorList({
required this.authors,
this.onTap,
super.key,
});
/// The list of authors to be shown.
final List<Author> authors;
/// Called when the user taps an author.
final ValueChanged<Author>? onTap;
@override
Widget build(BuildContext context) => ListView.builder(
itemCount: authors.length,
itemBuilder: (BuildContext context, int index) => ListTile(
title: Text(
authors[index].name,
),
subtitle: Text(
'${authors[index].books.length} books',
),
onTap: onTap != null ? () => onTap!(authors[index]) : null,
),
);
}
| packages/packages/go_router/example/lib/books/src/widgets/author_list.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/books/src/widgets/author_list.dart",
"repo_id": "packages",
"token_count": 370
} | 1,169 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(App());
/// The main app.
class App extends StatelessWidget {
/// Creates an [App].
App({super.key});
/// The title of the app.
static const String title = 'GoRouter Example: Custom Transitions';
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
title: title,
);
final GoRouter _router = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
redirect: (_, __) => '/none',
),
GoRoute(
path: '/fade',
pageBuilder: (BuildContext context, GoRouterState state) =>
CustomTransitionPage<void>(
key: state.pageKey,
child: const ExampleTransitionsScreen(
kind: 'fade',
color: Colors.red,
),
transitionsBuilder: (BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) =>
FadeTransition(opacity: animation, child: child),
),
),
GoRoute(
path: '/scale',
pageBuilder: (BuildContext context, GoRouterState state) =>
CustomTransitionPage<void>(
key: state.pageKey,
child: const ExampleTransitionsScreen(
kind: 'scale',
color: Colors.green,
),
transitionsBuilder: (BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) =>
ScaleTransition(scale: animation, child: child),
),
),
GoRoute(
path: '/slide',
pageBuilder: (BuildContext context, GoRouterState state) =>
CustomTransitionPage<void>(
key: state.pageKey,
child: const ExampleTransitionsScreen(
kind: 'slide',
color: Colors.yellow,
),
transitionsBuilder: (BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) =>
SlideTransition(
position: animation.drive(
Tween<Offset>(
begin: const Offset(0.25, 0.25),
end: Offset.zero,
).chain(CurveTween(curve: Curves.easeIn)),
),
child: child,
),
),
),
GoRoute(
path: '/rotation',
pageBuilder: (BuildContext context, GoRouterState state) =>
CustomTransitionPage<void>(
key: state.pageKey,
child: const ExampleTransitionsScreen(
kind: 'rotation',
color: Colors.purple,
),
transitionsBuilder: (BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) =>
RotationTransition(turns: animation, child: child),
),
),
GoRoute(
path: '/none',
pageBuilder: (BuildContext context, GoRouterState state) =>
NoTransitionPage<void>(
key: state.pageKey,
child: const ExampleTransitionsScreen(
kind: 'none',
color: Colors.white,
),
),
),
],
);
}
/// An Example transitions screen.
class ExampleTransitionsScreen extends StatelessWidget {
/// Creates an [ExampleTransitionsScreen].
const ExampleTransitionsScreen({
required this.color,
required this.kind,
super.key,
});
/// The available transition kinds.
static final List<String> kinds = <String>[
'fade',
'scale',
'slide',
'rotation',
'none'
];
/// The color of the container.
final Color color;
/// The transition kind.
final String kind;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text('${App.title}: $kind')),
body: ColoredBox(
color: color,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for (final String kind in kinds)
Padding(
padding: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () => context.go('/$kind'),
child: Text('$kind transition'),
),
)
],
),
),
),
);
}
| packages/packages/go_router/example/lib/others/transitions.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/others/transitions.dart",
"repo_id": "packages",
"token_count": 2286
} | 1,170 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: diagnostic_describe_all_properties
import 'package:flutter/cupertino.dart';
import '../misc/extensions.dart';
/// Checks for CupertinoApp in the widget tree.
bool isCupertinoApp(BuildContext context) =>
context.findAncestorWidgetOfExactType<CupertinoApp>() != null;
/// Creates a Cupertino HeroController.
HeroController createCupertinoHeroController() =>
CupertinoApp.createCupertinoHeroController();
/// Builds a Cupertino page.
CupertinoPage<void> pageBuilderForCupertinoApp({
required LocalKey key,
required String? name,
required Object? arguments,
required String restorationId,
required Widget child,
}) =>
CupertinoPage<void>(
name: name,
arguments: arguments,
key: key,
restorationId: restorationId,
child: child,
);
/// Default error page implementation for Cupertino.
class CupertinoErrorScreen extends StatelessWidget {
/// Provide an exception to this page for it to be displayed.
const CupertinoErrorScreen(this.error, {super.key});
/// The exception to be displayed.
final Exception? error;
@override
Widget build(BuildContext context) => CupertinoPageScaffold(
navigationBar:
const CupertinoNavigationBar(middle: Text('Page Not Found')),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(error?.toString() ?? 'page not found'),
CupertinoButton(
onPressed: () => context.go('/'),
child: const Text('Home'),
),
],
),
),
);
}
| packages/packages/go_router/lib/src/pages/cupertino.dart/0 | {
"file_path": "packages/packages/go_router/lib/src/pages/cupertino.dart",
"repo_id": "packages",
"token_count": 671
} | 1,171 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/src/misc/error_screen.dart';
import 'helpers/error_screen_helpers.dart';
void main() {
testWidgets(
'shows "page not found" by default',
testPageNotFound(
widget: widgetsAppBuilder(
home: const ErrorScreen(null),
),
),
);
final Exception exception = Exception('Something went wrong!');
testWidgets(
'shows the exception message when provided',
testPageShowsExceptionMessage(
exception: exception,
widget: widgetsAppBuilder(
home: ErrorScreen(exception),
),
),
);
testWidgets(
'clicking the button should redirect to /',
testClickingTheButtonRedirectsToRoot(
buttonFinder:
find.byWidgetPredicate((Widget widget) => widget is GestureDetector),
widget: widgetsAppBuilder(
home: const ErrorScreen(null),
),
),
);
}
Widget widgetsAppBuilder({required Widget home}) {
return WidgetsApp(
onGenerateRoute: (_) {
return MaterialPageRoute<void>(
builder: (BuildContext _) => home,
);
},
color: Colors.white,
);
}
| packages/packages/go_router/test/error_page_test.dart/0 | {
"file_path": "packages/packages/go_router/test/error_page_test.dart",
"repo_id": "packages",
"token_count": 495
} | 1,172 |
// 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'test_helpers.dart';
void main() {
testWidgets('back button works synchronously', (WidgetTester tester) async {
bool allow = false;
final UniqueKey home = UniqueKey();
final UniqueKey page1 = UniqueKey();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: home),
routes: <GoRoute>[
GoRoute(
path: '1',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: page1),
onExit: (BuildContext context) {
return allow;
},
)
],
),
];
final GoRouter router =
await createRouter(routes, tester, initialLocation: '/1');
expect(find.byKey(page1), findsOneWidget);
router.pop();
await tester.pumpAndSettle();
expect(find.byKey(page1), findsOneWidget);
allow = true;
router.pop();
await tester.pumpAndSettle();
expect(find.byKey(home), findsOneWidget);
});
testWidgets('context.go works synchronously', (WidgetTester tester) async {
bool allow = false;
final UniqueKey home = UniqueKey();
final UniqueKey page1 = UniqueKey();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: home),
),
GoRoute(
path: '/1',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: page1),
onExit: (BuildContext context) {
return allow;
},
)
];
final GoRouter router =
await createRouter(routes, tester, initialLocation: '/1');
expect(find.byKey(page1), findsOneWidget);
router.go('/');
await tester.pumpAndSettle();
expect(find.byKey(page1), findsOneWidget);
allow = true;
router.go('/');
await tester.pumpAndSettle();
expect(find.byKey(home), findsOneWidget);
});
testWidgets('back button works asynchronously', (WidgetTester tester) async {
Completer<bool> allow = Completer<bool>();
final UniqueKey home = UniqueKey();
final UniqueKey page1 = UniqueKey();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: home),
routes: <GoRoute>[
GoRoute(
path: '1',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: page1),
onExit: (BuildContext context) async {
return allow.future;
},
)
],
),
];
final GoRouter router =
await createRouter(routes, tester, initialLocation: '/1');
expect(find.byKey(page1), findsOneWidget);
router.pop();
await tester.pumpAndSettle();
expect(find.byKey(page1), findsOneWidget);
allow.complete(false);
await tester.pumpAndSettle();
expect(find.byKey(page1), findsOneWidget);
allow = Completer<bool>();
router.pop();
await tester.pumpAndSettle();
expect(find.byKey(page1), findsOneWidget);
allow.complete(true);
await tester.pumpAndSettle();
expect(find.byKey(home), findsOneWidget);
});
testWidgets('context.go works asynchronously', (WidgetTester tester) async {
Completer<bool> allow = Completer<bool>();
final UniqueKey home = UniqueKey();
final UniqueKey page1 = UniqueKey();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: home),
),
GoRoute(
path: '/1',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: page1),
onExit: (BuildContext context) async {
return allow.future;
},
)
];
final GoRouter router =
await createRouter(routes, tester, initialLocation: '/1');
expect(find.byKey(page1), findsOneWidget);
router.go('/');
await tester.pumpAndSettle();
expect(find.byKey(page1), findsOneWidget);
allow.complete(false);
await tester.pumpAndSettle();
expect(find.byKey(page1), findsOneWidget);
allow = Completer<bool>();
router.go('/');
await tester.pumpAndSettle();
expect(find.byKey(page1), findsOneWidget);
allow.complete(true);
await tester.pumpAndSettle();
expect(find.byKey(home), findsOneWidget);
});
testWidgets('android back button respects the last route.',
(WidgetTester tester) async {
bool allow = false;
final UniqueKey home = UniqueKey();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: home),
onExit: (BuildContext context) {
return allow;
},
),
];
final GoRouter router = await createRouter(routes, tester);
expect(find.byKey(home), findsOneWidget);
// Not allow system pop.
expect(await router.routerDelegate.popRoute(), true);
allow = true;
expect(await router.routerDelegate.popRoute(), false);
});
testWidgets('android back button respects the last route. async',
(WidgetTester tester) async {
bool allow = false;
final UniqueKey home = UniqueKey();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: home),
onExit: (BuildContext context) async {
return allow;
},
),
];
final GoRouter router = await createRouter(routes, tester);
expect(find.byKey(home), findsOneWidget);
// Not allow system pop.
expect(await router.routerDelegate.popRoute(), true);
allow = true;
expect(await router.routerDelegate.popRoute(), false);
});
testWidgets('android back button respects the last route with shell route.',
(WidgetTester tester) async {
bool allow = false;
final UniqueKey home = UniqueKey();
final List<RouteBase> routes = <RouteBase>[
ShellRoute(builder: (_, __, Widget child) => child, routes: <RouteBase>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
DummyScreen(key: home),
onExit: (BuildContext context) {
return allow;
},
),
])
];
final GoRouter router = await createRouter(routes, tester);
expect(find.byKey(home), findsOneWidget);
// Not allow system pop.
expect(await router.routerDelegate.popRoute(), true);
allow = true;
expect(await router.routerDelegate.popRoute(), false);
});
}
| packages/packages/go_router/test/on_exit_test.dart/0 | {
"file_path": "packages/packages/go_router/test/on_exit_test.dart",
"repo_id": "packages",
"token_count": 2957
} | 1,173 |
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: always_specify_types, public_member_api_docs
part of 'shell_route_example.dart';
// **************************************************************************
// GoRouterGenerator
// **************************************************************************
List<RouteBase> get $appRoutes => [
$myShellRouteData,
$loginRoute,
];
RouteBase get $myShellRouteData => ShellRouteData.$route(
factory: $MyShellRouteDataExtension._fromState,
routes: [
GoRouteData.$route(
path: '/foo',
factory: $FooRouteDataExtension._fromState,
),
GoRouteData.$route(
path: '/bar',
factory: $BarRouteDataExtension._fromState,
),
],
);
extension $MyShellRouteDataExtension on MyShellRouteData {
static MyShellRouteData _fromState(GoRouterState state) =>
const MyShellRouteData();
}
extension $FooRouteDataExtension on FooRouteData {
static FooRouteData _fromState(GoRouterState state) => const FooRouteData();
String get location => GoRouteData.$location(
'/foo',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
extension $BarRouteDataExtension on BarRouteData {
static BarRouteData _fromState(GoRouterState state) => const BarRouteData();
String get location => GoRouteData.$location(
'/bar',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
RouteBase get $loginRoute => GoRouteData.$route(
path: '/login',
factory: $LoginRouteExtension._fromState,
);
extension $LoginRouteExtension on LoginRoute {
static LoginRoute _fromState(GoRouterState state) => const LoginRoute();
String get location => GoRouteData.$location(
'/login',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
| packages/packages/go_router_builder/example/lib/shell_route_example.g.dart/0 | {
"file_path": "packages/packages/go_router_builder/example/lib/shell_route_example.g.dart",
"repo_id": "packages",
"token_count": 839
} | 1,174 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router_builder_example/shared/data.dart';
import 'package:go_router_builder_example/simple_example.dart';
void main() {
testWidgets('App starts on HomeScreen and displays families',
(WidgetTester tester) async {
await tester.pumpWidget(App());
expect(find.byType(HomeScreen), findsOneWidget);
expect(find.byType(ListTile), findsNWidgets(familyData.length));
for (final Family family in familyData) {
expect(find.text(family.name), findsOneWidget);
}
});
}
| packages/packages/go_router_builder/example/test/simple_example_test.dart/0 | {
"file_path": "packages/packages/go_router_builder/example/test/simple_example_test.dart",
"repo_id": "packages",
"token_count": 252
} | 1,175 |
RouteBase get $enumParam => GoRouteData.$route(
path: '/:y',
factory: $EnumParamExtension._fromState,
);
extension $EnumParamExtension on EnumParam {
static EnumParam _fromState(GoRouterState state) => EnumParam(
y: _$EnumTestEnumMap._$fromName(state.pathParameters['y']!),
);
String get location => GoRouteData.$location(
'/${Uri.encodeComponent(_$EnumTestEnumMap[y]!)}',
);
void go(BuildContext context) => context.go(location);
Future<T?> push<T>(BuildContext context) => context.push<T>(location);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location);
void replace(BuildContext context) => context.replace(location);
}
const _$EnumTestEnumMap = {
EnumTest.a: 'a',
EnumTest.b: 'b',
EnumTest.c: 'c',
};
extension<T extends Enum> on Map<T, String> {
T _$fromName(String value) =>
entries.singleWhere((element) => element.value == value).key;
}
| packages/packages/go_router_builder/test_inputs/enum_parameter.dart.expect/0 | {
"file_path": "packages/packages/go_router_builder/test_inputs/enum_parameter.dart.expect",
"repo_id": "packages",
"token_count": 358
} | 1,176 |
RouteBase get $requiredExtraValueRoute => GoRouteData.$route(
path: '/default-value-route',
factory: $RequiredExtraValueRouteExtension._fromState,
);
extension $RequiredExtraValueRouteExtension on RequiredExtraValueRoute {
static RequiredExtraValueRoute _fromState(GoRouterState state) =>
RequiredExtraValueRoute(
$extra: state.extra as int,
);
String get location => GoRouteData.$location(
'/default-value-route',
);
void go(BuildContext context) => context.go(location, extra: $extra);
Future<T?> push<T>(BuildContext context) =>
context.push<T>(location, extra: $extra);
void pushReplacement(BuildContext context) =>
context.pushReplacement(location, extra: $extra);
void replace(BuildContext context) =>
context.replace(location, extra: $extra);
}
| packages/packages/go_router_builder/test_inputs/required_extra_value.dart.expect/0 | {
"file_path": "packages/packages/go_router_builder/test_inputs/required_extra_value.dart.expect",
"repo_id": "packages",
"token_count": 275
} | 1,177 |
The parameter type `Stopwatch` is not supported.
| packages/packages/go_router_builder/test_inputs/unsupported_type.dart.expect/0 | {
"file_path": "packages/packages/go_router_builder/test_inputs/unsupported_type.dart.expect",
"repo_id": "packages",
"token_count": 12
} | 1,178 |
// 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: avoid_print
import 'dart:convert';
import 'package:google_identity_services_web/id.dart';
import 'package:google_identity_services_web/loader.dart' as gis;
import 'package:google_identity_services_web/oauth2.dart';
import 'package:http/http.dart' as http;
/// People API to return my profile info...
const String MY_PROFILE =
'https://content-people.googleapis.com/v1/people/me?personFields=photos%2Cnames%2CemailAddresses';
/// People API to return all my connections.
const String MY_CONNECTIONS =
'https://people.googleapis.com/v1/people/me/connections?requestMask.includeField=person.names';
/// Basic scopes for self-id
const List<String> scopes = <String>[
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
];
/// Scopes for the people API (read contacts)
const List<String> myConnectionsScopes = <String>[
'https://www.googleapis.com/auth/contacts.readonly',
];
void main() async {
await gis.loadWebSdk(); // Load the GIS SDK
id.setLogLevel('debug');
final TokenClientConfig config = TokenClientConfig(
client_id: 'your-google-client-id-goes-here.apps.googleusercontent.com',
scope: scopes,
callback: onTokenResponse,
error_callback: onError,
);
final OverridableTokenClientConfig overridableCfg =
OverridableTokenClientConfig(
scope: scopes + myConnectionsScopes,
);
final TokenClient client = oauth2.initTokenClient(config);
// Disable the Popup Blocker for this to work, or move this to a Button press.
client.requestAccessToken(overridableCfg);
}
/// Triggers when there's an error with the OAuth2 popup.
///
/// We cannot use the proper type for `error` here yet, because of:
/// https://github.com/dart-lang/sdk/issues/50899
Future<void> onError(GoogleIdentityServicesError? error) async {
print('Error! ${error?.type} (${error?.message})');
}
/// Handles the returned (auth) token response.
/// See: https://developers.google.com/identity/oauth2/web/reference/js-reference#TokenResponse
Future<void> onTokenResponse(TokenResponse token) async {
if (token.error != null) {
print('Authorization error!');
print(token.error);
print(token.error_description);
print(token.error_uri);
return;
}
// Attempt to do a request to the `people` API
final Object? profile = await get(token, MY_PROFILE);
print(profile);
// Has granted all the scopes?
if (!oauth2.hasGrantedAllScopes(token, myConnectionsScopes)) {
print('The user has NOT granted all the required scopes!');
print('The next get will probably throw an exception!');
}
final Object? contacts = await get(token, MY_CONNECTIONS);
print(contacts);
print('Revoking token...');
oauth2.revoke(token.access_token!, (TokenRevocationResponse response) {
print(response.successful);
print(response.error);
print(response.error_description);
});
}
/// Gets from [url] with an authorization header defined by [token].
///
/// Attempts to [jsonDecode] the result.
Future<Object?> get(TokenResponse token, String url) async {
final Uri uri = Uri.parse(url);
final http.Response response = await http.get(uri, headers: <String, String>{
'Authorization': '${token.token_type} ${token.access_token}',
});
if (response.statusCode != 200) {
throw http.ClientException(response.body, uri);
}
return jsonDecode(response.body) as Object?;
}
| packages/packages/google_identity_services_web/example/lib/main_oauth.dart/0 | {
"file_path": "packages/packages/google_identity_services_web/example/lib/main_oauth.dart",
"repo_id": "packages",
"token_count": 1164
} | 1,179 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'page.dart';
class PlaceMarkerPage extends GoogleMapExampleAppPage {
const PlaceMarkerPage({Key? key})
: super(const Icon(Icons.place), 'Place marker', key: key);
@override
Widget build(BuildContext context) {
return const PlaceMarkerBody();
}
}
class PlaceMarkerBody extends StatefulWidget {
const PlaceMarkerBody({super.key});
@override
State<StatefulWidget> createState() => PlaceMarkerBodyState();
}
typedef MarkerUpdateAction = Marker Function(Marker marker);
class PlaceMarkerBodyState extends State<PlaceMarkerBody> {
PlaceMarkerBodyState();
static const LatLng center = LatLng(-33.86711, 151.1947171);
GoogleMapController? controller;
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
MarkerId? selectedMarker;
int _markerIdCounter = 1;
LatLng? markerPosition;
// ignore: use_setters_to_change_properties
void _onMapCreated(GoogleMapController controller) {
this.controller = controller;
}
@override
void dispose() {
super.dispose();
}
void _onMarkerTapped(MarkerId markerId) {
final Marker? tappedMarker = markers[markerId];
if (tappedMarker != null) {
setState(() {
final MarkerId? previousMarkerId = selectedMarker;
if (previousMarkerId != null && markers.containsKey(previousMarkerId)) {
final Marker resetOld = markers[previousMarkerId]!
.copyWith(iconParam: BitmapDescriptor.defaultMarker);
markers[previousMarkerId] = resetOld;
}
selectedMarker = markerId;
final Marker newMarker = tappedMarker.copyWith(
iconParam: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueGreen,
),
);
markers[markerId] = newMarker;
markerPosition = null;
});
}
}
Future<void> _onMarkerDrag(MarkerId markerId, LatLng newPosition) async {
setState(() {
markerPosition = newPosition;
});
}
Future<void> _onMarkerDragEnd(MarkerId markerId, LatLng newPosition) async {
final Marker? tappedMarker = markers[markerId];
if (tappedMarker != null) {
setState(() {
markerPosition = null;
});
await showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
actions: <Widget>[
TextButton(
child: const Text('OK'),
onPressed: () => Navigator.of(context).pop(),
)
],
content: Padding(
padding: const EdgeInsets.symmetric(vertical: 66),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text('Old position: ${tappedMarker.position}'),
Text('New position: $newPosition'),
],
)));
});
}
}
void _add() {
final int markerCount = markers.length;
if (markerCount == 12) {
return;
}
final String markerIdVal = 'marker_id_$_markerIdCounter';
_markerIdCounter++;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position: LatLng(
center.latitude + sin(_markerIdCounter * pi / 6.0) / 20.0,
center.longitude + cos(_markerIdCounter * pi / 6.0) / 20.0,
),
infoWindow: InfoWindow(title: markerIdVal, snippet: '*'),
onTap: () => _onMarkerTapped(markerId),
onDragEnd: (LatLng position) => _onMarkerDragEnd(markerId, position),
onDrag: (LatLng position) => _onMarkerDrag(markerId, position),
);
setState(() {
markers[markerId] = marker;
});
}
void _remove(MarkerId markerId) {
setState(() {
if (markers.containsKey(markerId)) {
markers.remove(markerId);
}
});
}
void _changePosition(MarkerId markerId) {
final Marker marker = markers[markerId]!;
final LatLng current = marker.position;
final Offset offset = Offset(
center.latitude - current.latitude,
center.longitude - current.longitude,
);
setState(() {
markers[markerId] = marker.copyWith(
positionParam: LatLng(
center.latitude + offset.dy,
center.longitude + offset.dx,
),
);
});
}
void _changeAnchor(MarkerId markerId) {
final Marker marker = markers[markerId]!;
final Offset currentAnchor = marker.anchor;
final Offset newAnchor = Offset(1.0 - currentAnchor.dy, currentAnchor.dx);
setState(() {
markers[markerId] = marker.copyWith(
anchorParam: newAnchor,
);
});
}
Future<void> _changeInfoAnchor(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final Offset currentAnchor = marker.infoWindow.anchor;
final Offset newAnchor = Offset(1.0 - currentAnchor.dy, currentAnchor.dx);
setState(() {
markers[markerId] = marker.copyWith(
infoWindowParam: marker.infoWindow.copyWith(
anchorParam: newAnchor,
),
);
});
}
Future<void> _toggleDraggable(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
setState(() {
markers[markerId] = marker.copyWith(
draggableParam: !marker.draggable,
);
});
}
Future<void> _toggleFlat(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
setState(() {
markers[markerId] = marker.copyWith(
flatParam: !marker.flat,
);
});
}
Future<void> _changeInfo(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final String newSnippet = '${marker.infoWindow.snippet!}*';
setState(() {
markers[markerId] = marker.copyWith(
infoWindowParam: marker.infoWindow.copyWith(
snippetParam: newSnippet,
),
);
});
}
Future<void> _changeAlpha(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final double current = marker.alpha;
setState(() {
markers[markerId] = marker.copyWith(
alphaParam: current < 0.1 ? 1.0 : current * 0.75,
);
});
}
Future<void> _changeRotation(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final double current = marker.rotation;
setState(() {
markers[markerId] = marker.copyWith(
rotationParam: current == 330.0 ? 0.0 : current + 30.0,
);
});
}
Future<void> _toggleVisible(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
setState(() {
markers[markerId] = marker.copyWith(
visibleParam: !marker.visible,
);
});
}
Future<void> _changeZIndex(MarkerId markerId) async {
final Marker marker = markers[markerId]!;
final double current = marker.zIndex;
setState(() {
markers[markerId] = marker.copyWith(
zIndexParam: current == 12.0 ? 0.0 : current + 1.0,
);
});
}
void _setMarkerIcon(MarkerId markerId, BitmapDescriptor assetIcon) {
final Marker marker = markers[markerId]!;
setState(() {
markers[markerId] = marker.copyWith(
iconParam: assetIcon,
);
});
}
Future<BitmapDescriptor> _getAssetIcon(BuildContext context) async {
final Completer<BitmapDescriptor> bitmapIcon =
Completer<BitmapDescriptor>();
final ImageConfiguration config = createLocalImageConfiguration(context);
const AssetImage('assets/red_square.png')
.resolve(config)
.addListener(ImageStreamListener((ImageInfo image, bool sync) async {
final ByteData? bytes =
await image.image.toByteData(format: ImageByteFormat.png);
if (bytes == null) {
bitmapIcon.completeError(Exception('Unable to encode icon'));
return;
}
final BitmapDescriptor bitmap =
BitmapDescriptor.fromBytes(bytes.buffer.asUint8List());
bitmapIcon.complete(bitmap);
}));
return bitmapIcon.future;
}
@override
Widget build(BuildContext context) {
final MarkerId? selectedId = selectedMarker;
return Stack(children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(
target: LatLng(-33.852, 151.211),
zoom: 11.0,
),
markers: Set<Marker>.of(markers.values),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
TextButton(
onPressed: _add,
child: const Text('Add'),
),
TextButton(
onPressed:
selectedId == null ? null : () => _remove(selectedId),
child: const Text('Remove'),
),
],
),
Wrap(
alignment: WrapAlignment.spaceEvenly,
children: <Widget>[
TextButton(
onPressed:
selectedId == null ? null : () => _changeInfo(selectedId),
child: const Text('change info'),
),
TextButton(
onPressed: selectedId == null
? null
: () => _changeInfoAnchor(selectedId),
child: const Text('change info anchor'),
),
TextButton(
onPressed:
selectedId == null ? null : () => _changeAlpha(selectedId),
child: const Text('change alpha'),
),
TextButton(
onPressed:
selectedId == null ? null : () => _changeAnchor(selectedId),
child: const Text('change anchor'),
),
TextButton(
onPressed: selectedId == null
? null
: () => _toggleDraggable(selectedId),
child: const Text('toggle draggable'),
),
TextButton(
onPressed:
selectedId == null ? null : () => _toggleFlat(selectedId),
child: const Text('toggle flat'),
),
TextButton(
onPressed: selectedId == null
? null
: () => _changePosition(selectedId),
child: const Text('change position'),
),
TextButton(
onPressed: selectedId == null
? null
: () => _changeRotation(selectedId),
child: const Text('change rotation'),
),
TextButton(
onPressed: selectedId == null
? null
: () => _toggleVisible(selectedId),
child: const Text('toggle visible'),
),
TextButton(
onPressed:
selectedId == null ? null : () => _changeZIndex(selectedId),
child: const Text('change zIndex'),
),
TextButton(
onPressed: selectedId == null
? null
: () {
_getAssetIcon(context).then(
(BitmapDescriptor icon) {
_setMarkerIcon(selectedId, icon);
},
);
},
child: const Text('set marker icon'),
),
],
),
],
),
Visibility(
visible: markerPosition != null,
child: Container(
color: Colors.white70,
height: 30,
padding: const EdgeInsets.only(left: 12, right: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
if (markerPosition == null)
Container()
else
Expanded(child: Text('lat: ${markerPosition!.latitude}')),
if (markerPosition == null)
Container()
else
Expanded(child: Text('lng: ${markerPosition!.longitude}')),
],
),
),
),
]);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart",
"repo_id": "packages",
"token_count": 6161
} | 1,180 |
// 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';
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
ArgumentCallback,
ArgumentCallbacks,
BitmapDescriptor,
CameraPosition,
CameraPositionCallback,
CameraTargetBounds,
CameraUpdate,
Cap,
Circle,
CircleId,
InfoWindow,
JointType,
LatLng,
LatLngBounds,
MapStyleException,
MapType,
Marker,
MarkerId,
MinMaxZoomPreference,
PatternItem,
Polygon,
PolygonId,
Polyline,
PolylineId,
ScreenCoordinate,
Tile,
TileOverlay,
TileOverlayId,
TileProvider,
WebGestureHandling;
part 'src/controller.dart';
part 'src/google_map.dart';
| packages/packages/google_maps_flutter/google_maps_flutter/lib/google_maps_flutter.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/lib/google_maps_flutter.dart",
"repo_id": "packages",
"token_count": 579
} | 1,181 |
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 {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'io.flutter.plugins.googlemaps'
}
compileSdk 34
defaultConfig {
minSdkVersion 20
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
dependencies {
implementation "androidx.annotation:annotation:1.7.0"
implementation 'com.google.android.gms:play-services-maps:18.2.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.10.3"
}
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
}
}
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/build.gradle/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/build.gradle",
"repo_id": "packages",
"token_count": 838
} | 1,182 |
// 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 com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
class MarkerBuilder implements MarkerOptionsSink {
private final MarkerOptions markerOptions;
private boolean consumeTapEvents;
MarkerBuilder() {
this.markerOptions = new MarkerOptions();
}
MarkerOptions build() {
return markerOptions;
}
boolean consumeTapEvents() {
return consumeTapEvents;
}
@Override
public void setAlpha(float alpha) {
markerOptions.alpha(alpha);
}
@Override
public void setAnchor(float u, float v) {
markerOptions.anchor(u, v);
}
@Override
public void setConsumeTapEvents(boolean consumeTapEvents) {
this.consumeTapEvents = consumeTapEvents;
}
@Override
public void setDraggable(boolean draggable) {
markerOptions.draggable(draggable);
}
@Override
public void setFlat(boolean flat) {
markerOptions.flat(flat);
}
@Override
public void setIcon(BitmapDescriptor bitmapDescriptor) {
markerOptions.icon(bitmapDescriptor);
}
@Override
public void setInfoWindowAnchor(float u, float v) {
markerOptions.infoWindowAnchor(u, v);
}
@Override
public void setInfoWindowText(String title, String snippet) {
markerOptions.title(title);
markerOptions.snippet(snippet);
}
@Override
public void setPosition(LatLng position) {
markerOptions.position(position);
}
@Override
public void setRotation(float rotation) {
markerOptions.rotation(rotation);
}
@Override
public void setVisible(boolean visible) {
markerOptions.visible(visible);
}
@Override
public void setZIndex(float zIndex) {
markerOptions.zIndex(zIndex);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/MarkerBuilder.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/MarkerBuilder.java",
"repo_id": "packages",
"token_count": 644
} | 1,183 |
// 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";
protected final String tileOverlayId;
protected final MethodChannel methodChannel;
protected 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,
"Can't get tile: errorCode = "
+ errorCode
+ ", errorMessage = "
+ errorCode
+ ", date = "
+ data);
result = null;
countDownLatch.countDown();
}
@Override
public void notImplemented() {
Log.e(TAG, "Can't get tile: notImplemented");
result = null;
countDownLatch.countDown();
}
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileProviderController.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/TileProviderController.java",
"repo_id": "packages",
"token_count": 1203
} | 1,184 |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/app/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/app/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "packages",
"token_count": 73
} | 1,185 |
// 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 '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';
import 'example_google_map.dart';
import 'main.dart';
import 'page.dart';
class MapIdPage extends GoogleMapExampleAppPage {
const MapIdPage({Key? key})
: super(const Icon(Icons.map), 'Cloud-based maps styling', key: key);
@override
Widget build(BuildContext context) {
return const MapIdBody();
}
}
class MapIdBody extends StatefulWidget {
const MapIdBody({super.key});
@override
State<StatefulWidget> createState() => MapIdBodyState();
}
const LatLng _kMapCenter = LatLng(52.4478, -3.5402);
class MapIdBodyState extends State<MapIdBody> {
ExampleGoogleMapController? controller;
Key _key = const Key('mapId#');
String? _mapId;
final TextEditingController _mapIdController = TextEditingController();
AndroidMapRenderer? _initializedRenderer;
@override
void initState() {
initializeMapRenderer()
.then<void>((AndroidMapRenderer? initializedRenderer) => setState(() {
_initializedRenderer = initializedRenderer;
}));
super.initState();
}
String _getInitializedsRendererType() {
switch (_initializedRenderer) {
case AndroidMapRenderer.latest:
return 'latest';
case AndroidMapRenderer.legacy:
return 'legacy';
case AndroidMapRenderer.platformDefault:
case null:
break;
}
return 'unknown';
}
void _setMapId() {
setState(() {
_mapId = _mapIdController.text;
// Change key to initialize new map instance for new mapId.
_key = Key(_mapId ?? 'mapId#');
});
}
@override
Widget build(BuildContext context) {
final ExampleGoogleMap googleMap = ExampleGoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(
target: _kMapCenter,
zoom: 7.0,
),
key: _key,
cloudMapId: _mapId,
);
final List<Widget> columnChildren = <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: googleMap,
),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
controller: _mapIdController,
decoration: const InputDecoration(
hintText: 'Map Id',
),
)),
Padding(
padding: const EdgeInsets.all(10.0),
child: ElevatedButton(
onPressed: () => _setMapId(),
child: const Text(
'Press to use specified map Id',
),
)),
if (_initializedRenderer != AndroidMapRenderer.latest)
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
'On Android, Cloud-based maps styling only works with "latest" renderer.\n\n'
'Current initialized renderer is "${_getInitializedsRendererType()}".'),
),
];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: columnChildren,
);
}
@override
void dispose() {
_mapIdController.dispose();
super.dispose();
}
void _onMapCreated(ExampleGoogleMapController controllerParam) {
setState(() {
controller = controllerParam;
});
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_map_id.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_map_id.dart",
"repo_id": "packages",
"token_count": 1531
} | 1,186 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:stream_transform/stream_transform.dart';
// A dummy implementation of the platform interface for tests.
class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform {
FakeGoogleMapsFlutterPlatform();
/// The IDs passed to each call to buildView, in call order.
List<int> createdIds = <int>[];
/// A map of creation IDs to fake map instances.
Map<int, PlatformMapStateRecorder> mapInstances =
<int, PlatformMapStateRecorder>{};
PlatformMapStateRecorder get lastCreatedMap => mapInstances[createdIds.last]!;
/// Whether to add a small delay to async calls to simulate more realistic
/// async behavior (simulating the platform channel calls most
/// implementations will do).
///
/// When true, requires tests to `pumpAndSettle` at the end of the test
/// to avoid exceptions.
bool simulatePlatformDelay = false;
/// Whether `dispose` has been called.
bool disposed = false;
/// Stream controller to inject events for testing.
final StreamController<MapEvent<dynamic>> mapEventStreamController =
StreamController<MapEvent<dynamic>>.broadcast();
@override
Future<void> init(int mapId) async {}
@override
Future<void> updateMapConfiguration(
MapConfiguration update, {
required int mapId,
}) async {
mapInstances[mapId]?.mapConfiguration = update;
await _fakeDelay();
}
@override
Future<void> updateMarkers(
MarkerUpdates markerUpdates, {
required int mapId,
}) async {
mapInstances[mapId]?.markerUpdates.add(markerUpdates);
await _fakeDelay();
}
@override
Future<void> updatePolygons(
PolygonUpdates polygonUpdates, {
required int mapId,
}) async {
mapInstances[mapId]?.polygonUpdates.add(polygonUpdates);
await _fakeDelay();
}
@override
Future<void> updatePolylines(
PolylineUpdates polylineUpdates, {
required int mapId,
}) async {
mapInstances[mapId]?.polylineUpdates.add(polylineUpdates);
await _fakeDelay();
}
@override
Future<void> updateCircles(
CircleUpdates circleUpdates, {
required int mapId,
}) async {
mapInstances[mapId]?.circleUpdates.add(circleUpdates);
await _fakeDelay();
}
@override
Future<void> updateTileOverlays({
required Set<TileOverlay> newTileOverlays,
required int mapId,
}) async {
mapInstances[mapId]?.tileOverlaySets.add(newTileOverlays);
await _fakeDelay();
}
@override
Future<void> clearTileCache(
TileOverlayId tileOverlayId, {
required int mapId,
}) async {}
@override
Future<void> animateCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) async {}
@override
Future<void> moveCamera(
CameraUpdate cameraUpdate, {
required int mapId,
}) async {}
@override
Future<void> setMapStyle(
String? mapStyle, {
required int mapId,
}) async {}
@override
Future<LatLngBounds> getVisibleRegion({
required int mapId,
}) async {
return LatLngBounds(
southwest: const LatLng(0, 0), northeast: const LatLng(0, 0));
}
@override
Future<ScreenCoordinate> getScreenCoordinate(
LatLng latLng, {
required int mapId,
}) async {
return const ScreenCoordinate(x: 0, y: 0);
}
@override
Future<LatLng> getLatLng(
ScreenCoordinate screenCoordinate, {
required int mapId,
}) async {
return const LatLng(0, 0);
}
@override
Future<void> showMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) async {}
@override
Future<void> hideMarkerInfoWindow(
MarkerId markerId, {
required int mapId,
}) async {}
@override
Future<bool> isMarkerInfoWindowShown(
MarkerId markerId, {
required int mapId,
}) async {
return false;
}
@override
Future<double> getZoomLevel({
required int mapId,
}) async {
return 0.0;
}
@override
Future<Uint8List?> takeSnapshot({
required int mapId,
}) async {
return null;
}
@override
Stream<CameraMoveStartedEvent> onCameraMoveStarted({required int mapId}) {
return mapEventStreamController.stream.whereType<CameraMoveStartedEvent>();
}
@override
Stream<CameraMoveEvent> onCameraMove({required int mapId}) {
return mapEventStreamController.stream.whereType<CameraMoveEvent>();
}
@override
Stream<CameraIdleEvent> onCameraIdle({required int mapId}) {
return mapEventStreamController.stream.whereType<CameraIdleEvent>();
}
@override
Stream<MarkerTapEvent> onMarkerTap({required int mapId}) {
return mapEventStreamController.stream.whereType<MarkerTapEvent>();
}
@override
Stream<InfoWindowTapEvent> onInfoWindowTap({required int mapId}) {
return mapEventStreamController.stream.whereType<InfoWindowTapEvent>();
}
@override
Stream<MarkerDragStartEvent> onMarkerDragStart({required int mapId}) {
return mapEventStreamController.stream.whereType<MarkerDragStartEvent>();
}
@override
Stream<MarkerDragEvent> onMarkerDrag({required int mapId}) {
return mapEventStreamController.stream.whereType<MarkerDragEvent>();
}
@override
Stream<MarkerDragEndEvent> onMarkerDragEnd({required int mapId}) {
return mapEventStreamController.stream.whereType<MarkerDragEndEvent>();
}
@override
Stream<PolylineTapEvent> onPolylineTap({required int mapId}) {
return mapEventStreamController.stream.whereType<PolylineTapEvent>();
}
@override
Stream<PolygonTapEvent> onPolygonTap({required int mapId}) {
return mapEventStreamController.stream.whereType<PolygonTapEvent>();
}
@override
Stream<CircleTapEvent> onCircleTap({required int mapId}) {
return mapEventStreamController.stream.whereType<CircleTapEvent>();
}
@override
Stream<MapTapEvent> onTap({required int mapId}) {
return mapEventStreamController.stream.whereType<MapTapEvent>();
}
@override
Stream<MapLongPressEvent> onLongPress({required int mapId}) {
return mapEventStreamController.stream.whereType<MapLongPressEvent>();
}
@override
void dispose({required int mapId}) {
disposed = true;
}
@override
Widget buildViewWithConfiguration(
int creationId,
PlatformViewCreatedCallback onPlatformViewCreated, {
required MapWidgetConfiguration widgetConfiguration,
MapObjects mapObjects = const MapObjects(),
MapConfiguration mapConfiguration = const MapConfiguration(),
}) {
final PlatformMapStateRecorder? instance = mapInstances[creationId];
if (instance == null) {
createdIds.add(creationId);
mapInstances[creationId] = PlatformMapStateRecorder(
widgetConfiguration: widgetConfiguration,
mapConfiguration: mapConfiguration,
mapObjects: mapObjects);
onPlatformViewCreated(creationId);
}
return Container();
}
Future<void> _fakeDelay() async {
if (!simulatePlatformDelay) {
return;
}
return Future<void>.delayed(const Duration(microseconds: 1));
}
}
/// A fake implementation of a native map, which stores all the updates it is
/// sent for inspection in tests.
class PlatformMapStateRecorder {
PlatformMapStateRecorder({
required this.widgetConfiguration,
this.mapObjects = const MapObjects(),
this.mapConfiguration = const MapConfiguration(),
}) {
markerUpdates.add(MarkerUpdates.from(const <Marker>{}, mapObjects.markers));
polygonUpdates
.add(PolygonUpdates.from(const <Polygon>{}, mapObjects.polygons));
polylineUpdates
.add(PolylineUpdates.from(const <Polyline>{}, mapObjects.polylines));
circleUpdates.add(CircleUpdates.from(const <Circle>{}, mapObjects.circles));
tileOverlaySets.add(mapObjects.tileOverlays);
}
MapWidgetConfiguration widgetConfiguration;
MapObjects mapObjects;
MapConfiguration mapConfiguration;
final List<MarkerUpdates> markerUpdates = <MarkerUpdates>[];
final List<PolygonUpdates> polygonUpdates = <PolygonUpdates>[];
final List<PolylineUpdates> polylineUpdates = <PolylineUpdates>[];
final List<CircleUpdates> circleUpdates = <CircleUpdates>[];
final List<Set<TileOverlay>> tileOverlaySets = <Set<TileOverlay>>[];
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/test/fake_google_maps_flutter_platform.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/test/fake_google_maps_flutter_platform.dart",
"repo_id": "packages",
"token_count": 2833
} | 1,187 |
[
{
"elementType": "geometry",
"stylers": [
{
"color": "#242f3e"
}
]
},
{
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#746855"
}
]
},
{
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#242f3e"
}
]
},
{
"featureType": "administrative.locality",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#d59563"
}
]
},
{
"featureType": "poi",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#d59563"
}
]
},
{
"featureType": "poi.park",
"elementType": "geometry",
"stylers": [
{
"color": "#263c3f"
}
]
},
{
"featureType": "poi.park",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#6b9a76"
}
]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{
"color": "#38414e"
}
]
},
{
"featureType": "road",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#212a37"
}
]
},
{
"featureType": "road",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#9ca5b3"
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry",
"stylers": [
{
"color": "#746855"
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#1f2835"
}
]
},
{
"featureType": "road.highway",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#f3d19c"
}
]
},
{
"featureType": "transit",
"elementType": "geometry",
"stylers": [
{
"color": "#2f3948"
}
]
},
{
"featureType": "transit.station",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#d59563"
}
]
},
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"color": "#17263c"
}
]
},
{
"featureType": "water",
"elementType": "labels.text.fill",
"stylers": [
{
"color": "#515c6d"
}
]
},
{
"featureType": "water",
"elementType": "labels.text.stroke",
"stylers": [
{
"color": "#17263c"
}
]
}
]
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios12/assets/night_mode.json/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios12/assets/night_mode.json",
"repo_id": "packages",
"token_count": 1383
} | 1,188 |
name: google_maps_flutter_example
description: Demonstrates how to use the google_maps_flutter plugin.
publish_to: none
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
dependencies:
cupertino_icons: ^1.0.5
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.1
google_maps_flutter_ios:
# When depending on this package from a real application you should use:
# google_maps_flutter_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: ../../
google_maps_flutter_platform_interface: ^2.5.0
maps_example_dart:
path: ../shared/maps_example_dart/
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios12/pubspec.yaml/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios12/pubspec.yaml",
"repo_id": "packages",
"token_count": 345
} | 1,189 |
// 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 "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
@import GoogleMaps;
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Provide the GoogleMaps API key.
NSString *mapsApiKey = [[NSProcessInfo processInfo] environment][@"MAPS_API_KEY"];
if ([mapsApiKey length] == 0) {
mapsApiKey = @"YOUR KEY HERE";
}
[GMSServices provideAPIKey:mapsApiKey];
// Register Flutter plugins.
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/ios/Runner/AppDelegate.m/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/ios/Runner/AppDelegate.m",
"repo_id": "packages",
"token_count": 249
} | 1,190 |
This directory contains shared code used by all of the example apps.
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/README.md/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/README.md",
"repo_id": "packages",
"token_count": 14
} | 1,191 |
// 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 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
class PlacePolylinePage extends GoogleMapExampleAppPage {
const PlacePolylinePage({Key? key})
: super(const Icon(Icons.linear_scale), 'Place polyline', key: key);
@override
Widget build(BuildContext context) {
return const PlacePolylineBody();
}
}
class PlacePolylineBody extends StatefulWidget {
const PlacePolylineBody({super.key});
@override
State<StatefulWidget> createState() => PlacePolylineBodyState();
}
class PlacePolylineBodyState extends State<PlacePolylineBody> {
PlacePolylineBodyState();
ExampleGoogleMapController? controller;
Map<PolylineId, Polyline> polylines = <PolylineId, Polyline>{};
int _polylineIdCounter = 0;
PolylineId? selectedPolyline;
// Values when toggling polyline color
int colorsIndex = 0;
List<Color> colors = <Color>[
Colors.purple,
Colors.red,
Colors.green,
Colors.pink,
];
// Values when toggling polyline width
int widthsIndex = 0;
List<int> widths = <int>[10, 20, 5];
int jointTypesIndex = 0;
List<JointType> jointTypes = <JointType>[
JointType.mitered,
JointType.bevel,
JointType.round
];
// Values when toggling polyline end cap type
int endCapsIndex = 0;
List<Cap> endCaps = <Cap>[Cap.buttCap, Cap.squareCap, Cap.roundCap];
// Values when toggling polyline start cap type
int startCapsIndex = 0;
List<Cap> startCaps = <Cap>[Cap.buttCap, Cap.squareCap, Cap.roundCap];
// Values when toggling polyline pattern
int patternsIndex = 0;
List<List<PatternItem>> patterns = <List<PatternItem>>[
<PatternItem>[],
<PatternItem>[
PatternItem.dash(30.0),
PatternItem.gap(20.0),
PatternItem.dot,
PatternItem.gap(20.0)
],
<PatternItem>[PatternItem.dash(30.0), PatternItem.gap(20.0)],
<PatternItem>[PatternItem.dot, PatternItem.gap(10.0)],
];
// ignore: use_setters_to_change_properties
void _onMapCreated(ExampleGoogleMapController controller) {
this.controller = controller;
}
@override
void dispose() {
super.dispose();
}
void _onPolylineTapped(PolylineId polylineId) {
setState(() {
selectedPolyline = polylineId;
});
}
void _remove(PolylineId polylineId) {
setState(() {
if (polylines.containsKey(polylineId)) {
polylines.remove(polylineId);
}
selectedPolyline = null;
});
}
void _add() {
final int polylineCount = polylines.length;
if (polylineCount == 12) {
return;
}
final String polylineIdVal = 'polyline_id_$_polylineIdCounter';
_polylineIdCounter++;
final PolylineId polylineId = PolylineId(polylineIdVal);
final Polyline polyline = Polyline(
polylineId: polylineId,
consumeTapEvents: true,
color: Colors.orange,
width: 5,
points: _createPoints(),
onTap: () {
_onPolylineTapped(polylineId);
},
);
setState(() {
polylines[polylineId] = polyline;
});
}
void _toggleGeodesic(PolylineId polylineId) {
final Polyline polyline = polylines[polylineId]!;
setState(() {
polylines[polylineId] = polyline.copyWith(
geodesicParam: !polyline.geodesic,
);
});
}
void _toggleVisible(PolylineId polylineId) {
final Polyline polyline = polylines[polylineId]!;
setState(() {
polylines[polylineId] = polyline.copyWith(
visibleParam: !polyline.visible,
);
});
}
void _changeColor(PolylineId polylineId) {
final Polyline polyline = polylines[polylineId]!;
setState(() {
polylines[polylineId] = polyline.copyWith(
colorParam: colors[++colorsIndex % colors.length],
);
});
}
void _changeWidth(PolylineId polylineId) {
final Polyline polyline = polylines[polylineId]!;
setState(() {
polylines[polylineId] = polyline.copyWith(
widthParam: widths[++widthsIndex % widths.length],
);
});
}
void _changeJointType(PolylineId polylineId) {
final Polyline polyline = polylines[polylineId]!;
setState(() {
polylines[polylineId] = polyline.copyWith(
jointTypeParam: jointTypes[++jointTypesIndex % jointTypes.length],
);
});
}
void _changeEndCap(PolylineId polylineId) {
final Polyline polyline = polylines[polylineId]!;
setState(() {
polylines[polylineId] = polyline.copyWith(
endCapParam: endCaps[++endCapsIndex % endCaps.length],
);
});
}
void _changeStartCap(PolylineId polylineId) {
final Polyline polyline = polylines[polylineId]!;
setState(() {
polylines[polylineId] = polyline.copyWith(
startCapParam: startCaps[++startCapsIndex % startCaps.length],
);
});
}
void _changePattern(PolylineId polylineId) {
final Polyline polyline = polylines[polylineId]!;
setState(() {
polylines[polylineId] = polyline.copyWith(
patternsParam: patterns[++patternsIndex % patterns.length],
);
});
}
@override
Widget build(BuildContext context) {
final bool isIOS = !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS;
final PolylineId? selectedId = selectedPolyline;
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: SizedBox(
width: 350.0,
height: 300.0,
child: ExampleGoogleMap(
initialCameraPosition: const CameraPosition(
target: LatLng(53.1721, -3.5402),
zoom: 7.0,
),
polylines: Set<Polyline>.of(polylines.values),
onMapCreated: _onMapCreated,
),
),
),
Expanded(
child: SingleChildScrollView(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
children: <Widget>[
Column(
children: <Widget>[
TextButton(
onPressed: _add,
child: const Text('add'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _remove(selectedId),
child: const Text('remove'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _toggleVisible(selectedId),
child: const Text('toggle visible'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _toggleGeodesic(selectedId),
child: const Text('toggle geodesic'),
),
],
),
Column(
children: <Widget>[
TextButton(
onPressed: (selectedId == null)
? null
: () => _changeWidth(selectedId),
child: const Text('change width'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _changeColor(selectedId),
child: const Text('change color'),
),
TextButton(
onPressed: isIOS || (selectedId == null)
? null
: () => _changeStartCap(selectedId),
child: const Text('change start cap [Android only]'),
),
TextButton(
onPressed: isIOS || (selectedId == null)
? null
: () => _changeEndCap(selectedId),
child: const Text('change end cap [Android only]'),
),
TextButton(
onPressed: isIOS || (selectedId == null)
? null
: () => _changeJointType(selectedId),
child: const Text('change joint type [Android only]'),
),
TextButton(
onPressed: isIOS || (selectedId == null)
? null
: () => _changePattern(selectedId),
child: const Text('change pattern [Android only]'),
),
],
)
],
)
],
),
),
),
],
);
}
List<LatLng> _createPoints() {
final List<LatLng> points = <LatLng>[];
final double offset = _polylineIdCounter.ceilToDouble();
points.add(_createLatLng(51.4816 + offset, -3.1791));
points.add(_createLatLng(53.0430 + offset, -2.9925));
points.add(_createLatLng(53.1396 + offset, -4.2739));
points.add(_createLatLng(52.4153 + offset, -4.0829));
return points;
}
LatLng _createLatLng(double lat, double lng) {
return LatLng(lat, lng);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polyline.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/place_polyline.dart",
"repo_id": "packages",
"token_count": 4955
} | 1,192 |
// 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>
#import "GoogleMapCircleController.h"
#import "GoogleMapMarkerController.h"
#import "GoogleMapPolygonController.h"
#import "GoogleMapPolylineController.h"
NS_ASSUME_NONNULL_BEGIN
// Defines map overlay controllable from Flutter.
@interface FLTGoogleMapController : NSObject <GMSMapViewDelegate, FlutterPlatformView>
- (instancetype)initWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(nullable id)args
registrar:(NSObject<FlutterPluginRegistrar> *)registrar;
- (void)showAtOrigin:(CGPoint)origin;
- (void)hide;
- (void)animateWithCameraUpdate:(GMSCameraUpdate *)cameraUpdate;
- (void)moveWithCameraUpdate:(GMSCameraUpdate *)cameraUpdate;
- (nullable GMSCameraPosition *)cameraPosition;
@end
// Allows the engine to create new Google Map instances.
@interface FLTGoogleMapFactory : NSObject <FlutterPlatformViewFactory>
- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar;
@end
NS_ASSUME_NONNULL_END
| packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapController.h/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapController.h",
"repo_id": "packages",
"token_count": 421
} | 1,193 |
name: google_maps_flutter_ios
description: iOS implementation of the google_maps_flutter plugin.
repository: https://github.com/flutter/packages/tree/main/packages/google_maps_flutter/google_maps_flutter_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+maps%22
version: 2.5.1
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
implements: google_maps_flutter
platforms:
ios:
pluginClass: FLTGoogleMapsPlugin
dartPluginClass: GoogleMapsFlutterIOS
dependencies:
flutter:
sdk: flutter
google_maps_flutter_platform_interface: ^2.5.0
stream_transform: ^2.0.0
dev_dependencies:
async: ^2.5.0
flutter_test:
sdk: flutter
plugin_platform_interface: ^2.1.7
topics:
- google-maps
- google-maps-flutter
- map
| packages/packages/google_maps_flutter/google_maps_flutter_ios/pubspec.yaml/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/pubspec.yaml",
"repo_id": "packages",
"token_count": 339
} | 1,194 |
// 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';
/// [Circle] update events to be applied to the [GoogleMap].
///
/// Used in [GoogleMapController] when the map is updated.
// (Do not re-export)
class CircleUpdates extends MapsObjectUpdates<Circle> {
/// Computes [CircleUpdates] given previous and current [Circle]s.
CircleUpdates.from(super.previous, super.current)
: super.from(objectName: 'circle');
/// Set of Circles to be added in this update.
Set<Circle> get circlesToAdd => objectsToAdd;
/// Set of CircleIds to be removed in this update.
Set<CircleId> get circleIdsToRemove => objectIdsToRemove.cast<CircleId>();
/// Set of Circles to be changed in this update.
Set<Circle> get circlesToChange => objectsToChange;
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle_updates.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle_updates.dart",
"repo_id": "packages",
"token_count": 269
} | 1,195 |
// 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 VoidCallback, immutable, listEquals;
import 'package:flutter/material.dart' show Color, Colors;
import 'types.dart';
/// Uniquely identifies a [Polyline] among [GoogleMap] polylines.
///
/// This does not have to be globally unique, only unique among the list.
@immutable
class PolylineId extends MapsObjectId<Polyline> {
/// Creates an immutable object representing a [PolylineId] among [GoogleMap] polylines.
///
/// An [AssertionError] will be thrown if [value] is null.
const PolylineId(super.value);
}
/// Draws a line through geographical locations on the map.
@immutable
class Polyline implements MapsObject<Polyline> {
/// Creates an immutable object representing a line drawn through geographical locations on the map.
const Polyline({
required this.polylineId,
this.consumeTapEvents = false,
this.color = Colors.black,
this.endCap = Cap.buttCap,
this.geodesic = false,
this.jointType = JointType.mitered,
this.points = const <LatLng>[],
this.patterns = const <PatternItem>[],
this.startCap = Cap.buttCap,
this.visible = true,
this.width = 10,
this.zIndex = 0,
this.onTap,
});
/// Uniquely identifies a [Polyline].
final PolylineId polylineId;
@override
PolylineId get mapsId => polylineId;
/// True if the [Polyline] consumes tap events.
///
/// If this is false, [onTap] callback will not be triggered.
final bool consumeTapEvents;
/// Line segment color in ARGB format, the same format used by Color. The default value is black (0xff000000).
final Color color;
/// Indicates whether the segments of the polyline 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;
/// Joint type of the polyline line segments.
///
/// The joint type defines the shape to be used when joining adjacent line segments at all vertices of the
/// polyline except the start and end vertices. See [JointType] for supported joint types. The default value is
/// mitered.
///
/// Supported on Android only.
final JointType jointType;
/// The stroke pattern for the polyline.
///
/// Solid or a sequence of PatternItem objects to be repeated along the line.
/// Available PatternItem types: Gap (defined by gap length in pixels), Dash (defined by line width and dash
/// length in pixels) and Dot (circular, centered on the line, diameter defined by line width in pixels).
final List<PatternItem> patterns;
/// The vertices of the polyline to be drawn.
///
/// Line segments are drawn between consecutive points. A polyline is not closed by
/// default; to form a closed polyline, the start and end points must be the same.
final List<LatLng> points;
/// The cap at the start vertex of the polyline.
///
/// The default start cap is ButtCap.
///
/// Supported on Android only.
final Cap startCap;
/// The cap at the end vertex of the polyline.
///
/// The default end cap is ButtCap.
///
/// Supported on Android only.
final Cap endCap;
/// True if the marker is visible.
final bool visible;
/// Width of the polyline, used to define the width of the line segment to be drawn.
///
/// The width is constant and independent of the camera's zoom level.
/// The default value is 10.
final int width;
/// The z-index of the polyline, 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 polyline placed on this map.
final VoidCallback? onTap;
/// Creates a new [Polyline] object whose values are the same as this instance,
/// unless overwritten by the specified parameters.
Polyline copyWith({
Color? colorParam,
bool? consumeTapEventsParam,
Cap? endCapParam,
bool? geodesicParam,
JointType? jointTypeParam,
List<PatternItem>? patternsParam,
List<LatLng>? pointsParam,
Cap? startCapParam,
bool? visibleParam,
int? widthParam,
int? zIndexParam,
VoidCallback? onTapParam,
}) {
return Polyline(
polylineId: polylineId,
color: colorParam ?? color,
consumeTapEvents: consumeTapEventsParam ?? consumeTapEvents,
endCap: endCapParam ?? endCap,
geodesic: geodesicParam ?? geodesic,
jointType: jointTypeParam ?? jointType,
patterns: patternsParam ?? patterns,
points: pointsParam ?? points,
startCap: startCapParam ?? startCap,
visible: visibleParam ?? visible,
width: widthParam ?? width,
onTap: onTapParam ?? onTap,
zIndex: zIndexParam ?? zIndex,
);
}
/// Creates a new [Polyline] object whose values are the same as this
/// instance.
@override
Polyline clone() {
return copyWith(
patternsParam: List<PatternItem>.of(patterns),
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('polylineId', polylineId.value);
addIfPresent('consumeTapEvents', consumeTapEvents);
addIfPresent('color', color.value);
addIfPresent('endCap', endCap.toJson());
addIfPresent('geodesic', geodesic);
addIfPresent('jointType', jointType.value);
addIfPresent('startCap', startCap.toJson());
addIfPresent('visible', visible);
addIfPresent('width', width);
addIfPresent('zIndex', zIndex);
json['points'] = _pointsToJson();
json['pattern'] = _patternToJson();
return json;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is Polyline &&
polylineId == other.polylineId &&
consumeTapEvents == other.consumeTapEvents &&
color == other.color &&
geodesic == other.geodesic &&
jointType == other.jointType &&
listEquals(patterns, other.patterns) &&
listEquals(points, other.points) &&
startCap == other.startCap &&
endCap == other.endCap &&
visible == other.visible &&
width == other.width &&
zIndex == other.zIndex;
}
@override
int get hashCode => polylineId.hashCode;
Object _pointsToJson() {
final List<Object> result = <Object>[];
for (final LatLng point in points) {
result.add(point.toJson());
}
return result;
}
Object _patternToJson() {
final List<Object> result = <Object>[];
for (final PatternItem patternItem in patterns) {
result.add(patternItem.toJson());
}
return result;
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline.dart",
"repo_id": "packages",
"token_count": 2373
} | 1,196 |
// 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 TileOverlay in a Map of TileOverlayId -> TileOverlay.
Map<TileOverlayId, TileOverlay> keyTileOverlayId(
Iterable<TileOverlay> tileOverlays) {
return keyByMapsObjectId<TileOverlay>(tileOverlays)
.cast<TileOverlayId, TileOverlay>();
}
/// Converts a Set of TileOverlays into something serializable in JSON.
Object serializeTileOverlaySet(Set<TileOverlay> tileOverlays) {
return serializeMapsObjectSet(tileOverlays);
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/tile_overlay.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/tile_overlay.dart",
"repo_id": "packages",
"token_count": 218
} | 1,197 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
class _TestTileProvider extends TileProvider {
@override
Future<Tile> getTile(int x, int y, int? zoom) async {
return const Tile(0, 0, null);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('tile overlay id tests', () {
test('equality', () async {
const TileOverlayId id1 = TileOverlayId('1');
const TileOverlayId id2 = TileOverlayId('1');
const TileOverlayId id3 = TileOverlayId('2');
expect(id1, id2);
expect(id1, isNot(id3));
});
test('toString', () async {
const TileOverlayId id1 = TileOverlayId('1');
expect(id1.toString(), 'TileOverlayId(1)');
});
});
group('tile overlay tests', () {
test('toJson returns correct format', () async {
const TileOverlay tileOverlay = TileOverlay(
tileOverlayId: TileOverlayId('id'),
fadeIn: false,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
final Object json = tileOverlay.toJson();
expect(json, <String, Object>{
'tileOverlayId': 'id',
'fadeIn': false,
'transparency': moreOrLessEquals(0.1),
'zIndex': 1,
'visible': false,
'tileSize': 128,
});
});
test('invalid transparency throws', () async {
expect(
() => TileOverlay(
tileOverlayId: const TileOverlayId('id1'), transparency: -0.1),
throwsAssertionError);
expect(
() => TileOverlay(
tileOverlayId: const TileOverlayId('id2'), transparency: 1.2),
throwsAssertionError);
});
test('equality', () async {
final TileProvider tileProvider = _TestTileProvider();
final TileOverlay tileOverlay1 = TileOverlay(
tileOverlayId: const TileOverlayId('id1'),
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
final TileOverlay tileOverlaySameValues = TileOverlay(
tileOverlayId: const TileOverlayId('id1'),
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
final TileOverlay tileOverlayDifferentId = TileOverlay(
tileOverlayId: const TileOverlayId('id2'),
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
const TileOverlay tileOverlayDifferentProvider = TileOverlay(
tileOverlayId: TileOverlayId('id1'),
fadeIn: false,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
expect(tileOverlay1, tileOverlaySameValues);
expect(tileOverlay1, isNot(tileOverlayDifferentId));
expect(tileOverlay1, isNot(tileOverlayDifferentProvider));
});
test('clone', () async {
final TileProvider tileProvider = _TestTileProvider();
// Set non-default values for every parameter.
final TileOverlay tileOverlay = TileOverlay(
tileOverlayId: const TileOverlayId('id1'),
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
expect(tileOverlay, tileOverlay.clone());
});
test('hashCode', () async {
final TileProvider tileProvider = _TestTileProvider();
const TileOverlayId id = TileOverlayId('id1');
final TileOverlay tileOverlay = TileOverlay(
tileOverlayId: id,
fadeIn: false,
tileProvider: tileProvider,
transparency: 0.1,
zIndex: 1,
visible: false,
tileSize: 128);
expect(
tileOverlay.hashCode,
Object.hash(
tileOverlay.tileOverlayId,
tileOverlay.fadeIn,
tileOverlay.tileProvider,
tileOverlay.transparency,
tileOverlay.zIndex,
tileOverlay.visible,
tileOverlay.tileSize));
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_test.dart",
"repo_id": "packages",
"token_count": 1994
} | 1,198 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:google_maps_flutter_web/google_maps_flutter_web.dart';
// ignore: implementation_imports
import 'package:google_maps_flutter_web/src/utils.dart';
import 'package:http/http.dart' as http;
import 'package:integration_test/integration_test.dart';
import 'package:web/web.dart';
import 'resources/icon_image_base64.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('MarkersController', () {
late StreamController<MapEvent<Object?>> events;
late MarkersController controller;
late gmaps.GMap map;
setUp(() {
events = StreamController<MapEvent<Object?>>();
controller = MarkersController(stream: events);
map = gmaps.GMap(createDivElement());
controller.bindToMap(123, map);
});
testWidgets('addMarkers', (WidgetTester tester) async {
final Set<Marker> markers = <Marker>{
const Marker(markerId: MarkerId('1')),
const Marker(markerId: MarkerId('2')),
};
controller.addMarkers(markers);
expect(controller.markers.length, 2);
expect(controller.markers, contains(const MarkerId('1')));
expect(controller.markers, contains(const MarkerId('2')));
expect(controller.markers, isNot(contains(const MarkerId('66'))));
});
testWidgets('changeMarkers', (WidgetTester tester) async {
gmaps.Marker? marker;
gmaps.LatLng? position;
final Set<Marker> markers = <Marker>{
const Marker(markerId: MarkerId('1')),
};
controller.addMarkers(markers);
marker = controller.markers[const MarkerId('1')]?.marker;
expect(marker, isNotNull);
expect(marker!.draggable, isFalse);
// By default, markers fall in LatLng(0, 0)
position = marker.position;
expect(position, isNotNull);
expect(position!.lat, equals(0));
expect(position.lng, equals(0));
// Update the marker with draggable and position
final Set<Marker> updatedMarkers = <Marker>{
const Marker(
markerId: MarkerId('1'),
draggable: true,
position: LatLng(42, 54),
),
};
controller.changeMarkers(updatedMarkers);
expect(controller.markers.length, 1);
marker = controller.markers[const MarkerId('1')]?.marker;
expect(marker, isNotNull);
expect(marker!.draggable, isTrue);
position = marker.position;
expect(position, isNotNull);
expect(position!.lat, equals(42));
expect(position.lng, equals(54));
});
testWidgets(
'changeMarkers resets marker position if not passed when updating!',
(WidgetTester tester) async {
gmaps.Marker? marker;
gmaps.LatLng? position;
final Set<Marker> markers = <Marker>{
const Marker(
markerId: MarkerId('1'),
position: LatLng(42, 54),
),
};
controller.addMarkers(markers);
marker = controller.markers[const MarkerId('1')]?.marker;
expect(marker, isNotNull);
expect(marker!.draggable, isFalse);
position = marker.position;
expect(position, isNotNull);
expect(position!.lat, equals(42));
expect(position.lng, equals(54));
// Update the marker without position
final Set<Marker> updatedMarkers = <Marker>{
const Marker(
markerId: MarkerId('1'),
draggable: true,
),
};
controller.changeMarkers(updatedMarkers);
expect(controller.markers.length, 1);
marker = controller.markers[const MarkerId('1')]?.marker;
expect(marker, isNotNull);
expect(marker!.draggable, isTrue);
position = marker.position;
expect(position, isNotNull);
expect(position!.lat, equals(0));
expect(position.lng, equals(0));
});
testWidgets('removeMarkers', (WidgetTester tester) async {
final Set<Marker> markers = <Marker>{
const Marker(markerId: MarkerId('1')),
const Marker(markerId: MarkerId('2')),
const Marker(markerId: MarkerId('3')),
};
controller.addMarkers(markers);
expect(controller.markers.length, 3);
// Remove some markers...
final Set<MarkerId> markerIdsToRemove = <MarkerId>{
const MarkerId('1'),
const MarkerId('3'),
};
controller.removeMarkers(markerIdsToRemove);
expect(controller.markers.length, 1);
expect(controller.markers, isNot(contains(const MarkerId('1'))));
expect(controller.markers, contains(const MarkerId('2')));
expect(controller.markers, isNot(contains(const MarkerId('3'))));
});
testWidgets('InfoWindow show/hide', (WidgetTester tester) async {
final Set<Marker> markers = <Marker>{
const Marker(
markerId: MarkerId('1'),
infoWindow: InfoWindow(title: 'Title', snippet: 'Snippet'),
),
};
controller.addMarkers(markers);
expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse);
controller.showMarkerInfoWindow(const MarkerId('1'));
expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isTrue);
controller.hideMarkerInfoWindow(const MarkerId('1'));
expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse);
});
// https://github.com/flutter/flutter/issues/67380
testWidgets('only single InfoWindow is visible',
(WidgetTester tester) async {
final Set<Marker> markers = <Marker>{
const Marker(
markerId: MarkerId('1'),
infoWindow: InfoWindow(title: 'Title', snippet: 'Snippet'),
),
const Marker(
markerId: MarkerId('2'),
infoWindow: InfoWindow(title: 'Title', snippet: 'Snippet'),
),
};
controller.addMarkers(markers);
expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse);
expect(controller.markers[const MarkerId('2')]?.infoWindowShown, isFalse);
controller.showMarkerInfoWindow(const MarkerId('1'));
expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isTrue);
expect(controller.markers[const MarkerId('2')]?.infoWindowShown, isFalse);
controller.showMarkerInfoWindow(const MarkerId('2'));
expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse);
expect(controller.markers[const MarkerId('2')]?.infoWindowShown, isTrue);
});
// https://github.com/flutter/flutter/issues/66622
testWidgets('markers with custom bitmap icon work',
(WidgetTester tester) async {
final Uint8List bytes = const Base64Decoder().convert(iconImageBase64);
final Set<Marker> markers = <Marker>{
Marker(
markerId: const MarkerId('1'),
icon: BitmapDescriptor.fromBytes(bytes),
),
};
controller.addMarkers(markers);
expect(controller.markers.length, 1);
final gmaps.Icon? icon =
controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?;
expect(icon, isNotNull);
final String blobUrl = icon!.url!;
expect(blobUrl, startsWith('blob:'));
final http.Response response = await http.get(Uri.parse(blobUrl));
expect(response.bodyBytes, bytes,
reason:
'Bytes from the Icon blob must match bytes used to create Marker');
});
// https://github.com/flutter/flutter/issues/73789
testWidgets('markers with custom bitmap icon pass size to sdk',
(WidgetTester tester) async {
final Uint8List bytes = const Base64Decoder().convert(iconImageBase64);
final Set<Marker> markers = <Marker>{
Marker(
markerId: const MarkerId('1'),
icon: BitmapDescriptor.fromBytes(bytes, size: const Size(20, 30)),
),
};
controller.addMarkers(markers);
expect(controller.markers.length, 1);
final gmaps.Icon? icon =
controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?;
expect(icon, isNotNull);
final gmaps.Size size = icon!.size!;
final gmaps.Size scaledSize = icon.scaledSize!;
expect(size.width, 20);
expect(size.height, 30);
expect(scaledSize.width, 20);
expect(scaledSize.height, 30);
});
// https://github.com/flutter/flutter/issues/67854
testWidgets('InfoWindow snippet can have links',
(WidgetTester tester) async {
final Set<Marker> markers = <Marker>{
const Marker(
markerId: MarkerId('1'),
infoWindow: InfoWindow(
title: 'title for test',
snippet: '<a href="https://www.google.com">Go to Google >>></a>',
),
),
};
controller.addMarkers(markers);
expect(controller.markers.length, 1);
final HTMLElement? content = controller
.markers[const MarkerId('1')]?.infoWindow?.content as HTMLElement?;
expect(content?.innerHTML, contains('title for test'));
expect(
content?.innerHTML,
contains(
'<a href="https://www.google.com">Go to Google >>></a>',
));
});
// https://github.com/flutter/flutter/issues/67289
testWidgets('InfoWindow content is clickable', (WidgetTester tester) async {
final Set<Marker> markers = <Marker>{
const Marker(
markerId: MarkerId('1'),
infoWindow: InfoWindow(
title: 'title for test',
snippet: 'some snippet',
),
),
};
controller.addMarkers(markers);
expect(controller.markers.length, 1);
final HTMLElement? content = controller
.markers[const MarkerId('1')]?.infoWindow?.content as HTMLElement?;
content?.click();
final MapEvent<Object?> event = await events.stream.first;
expect(event, isA<InfoWindowTapEvent>());
expect((event as InfoWindowTapEvent).value, equals(const MarkerId('1')));
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart",
"repo_id": "packages",
"token_count": 4312
} | 1,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.