text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import '../platform_webview_controller.dart';
/// Defines the supported HTTP methods for loading a page in [PlatformWebViewController].
enum LoadRequestMethod {
/// HTTP GET method.
get,
/// HTTP POST method.
post,
}
/// Extension methods on the [LoadRequestMethod] enum.
extension LoadRequestMethodExtensions on LoadRequestMethod {
/// Converts [LoadRequestMethod] to [String] format.
String serialize() {
switch (this) {
case LoadRequestMethod.get:
return 'get';
case LoadRequestMethod.post:
return 'post';
}
}
}
/// Defines the parameters that can be used to load a page with the [PlatformWebViewController].
///
/// Platform specific implementations can add additional fields by extending
/// this class.
///
/// {@tool sample}
/// This example demonstrates how to extend the [LoadRequestParams] to
/// provide additional platform specific parameters.
///
/// When extending [LoadRequestParams] additional parameters should always
/// accept `null` or have a default value to prevent breaking changes.
///
/// ```dart
/// class AndroidLoadRequestParams extends LoadRequestParams {
/// AndroidLoadRequestParams._({
/// required LoadRequestParams params,
/// this.historyUrl,
/// }) : super(
/// uri: params.uri,
/// method: params.method,
/// body: params.body,
/// headers: params.headers,
/// );
///
/// factory AndroidLoadRequestParams.fromLoadRequestParams(
/// LoadRequestParams params, {
/// Uri? historyUrl,
/// }) {
/// return AndroidLoadRequestParams._(params, historyUrl: historyUrl);
/// }
///
/// final Uri? historyUrl;
/// }
/// ```
/// {@end-tool}
@immutable
class LoadRequestParams {
/// Used by the platform implementation to create a new [LoadRequestParams].
const LoadRequestParams({
required this.uri,
this.method = LoadRequestMethod.get,
this.headers = const <String, String>{},
this.body,
});
/// URI for the request.
final Uri uri;
/// HTTP method used to make the request.
///
/// Defaults to [LoadRequestMethod.get].
final LoadRequestMethod method;
/// Headers for the request.
final Map<String, String> headers;
/// HTTP body for the request.
final Uint8List? body;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/load_request_params.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/load_request_params.dart",
"repo_id": "packages",
"token_count": 745
} | 1,069 |
// 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:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'package:webview_flutter_web/webview_flutter_web.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('WebWebViewWidget', () {
testWidgets('build returns a HtmlElementView', (WidgetTester tester) async {
final WebWebViewController controller =
WebWebViewController(WebWebViewControllerCreationParams());
final WebWebViewWidget widget = WebWebViewWidget(
PlatformWebViewWidgetCreationParams(
key: const Key('keyValue'),
controller: controller,
),
);
await tester.pumpWidget(
Builder(builder: (BuildContext context) => widget.build(context)),
);
expect(find.byType(HtmlElementView), findsOneWidget);
expect(find.byKey(const Key('keyValue')), findsOneWidget);
});
});
}
| packages/packages/webview_flutter/webview_flutter_web/test/web_webview_widget_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_web/test/web_webview_widget_test.dart",
"repo_id": "packages",
"token_count": 404
} | 1,070 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Flutter;
@import XCTest;
@import webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFURLProtectionSpaceHostApiTests : XCTestCase
@end
@implementation FWFURLProtectionSpaceHostApiTests
- (void)testFlutterApiCreate {
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
FWFURLProtectionSpaceFlutterApiImpl *flutterApi = [[FWFURLProtectionSpaceFlutterApiImpl alloc]
initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
instanceManager:instanceManager];
flutterApi.api = OCMClassMock([FWFNSUrlProtectionSpaceFlutterApi class]);
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:@"host"
port:0
protocol:nil
realm:@"realm"
authenticationMethod:nil];
[flutterApi createWithInstance:protectionSpace
host:@"host"
realm:@"realm"
authenticationMethod:@"method"
completion:^(FlutterError *error){
}];
long identifier = [instanceManager identifierWithStrongReferenceForInstance:protectionSpace];
OCMVerify([flutterApi.api createWithIdentifier:identifier
host:@"host"
realm:@"realm"
authenticationMethod:@"method"
completion:OCMOCK_ANY]);
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFURLProtectionSpaceHostApiTests.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFURLProtectionSpaceHostApiTests.m",
"repo_id": "packages",
"token_count": 989
} | 1,071 |
// 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 <Foundation/Foundation.h>
#import "FWFGeneratedWebKitApis.h"
#import "FWFInstanceManager.h"
NS_ASSUME_NONNULL_BEGIN
/// Host API implementation for `NSURL`.
///
/// This class may handle instantiating and adding native object instances that are attached to a
/// Dart instance or method calls on the associated native class or an instance of the class.
@interface FWFURLHostApiImpl : NSObject <FWFNSUrlHostApi>
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
/// Flutter API implementation for `NSURL`.
///
/// This class may handle instantiating and adding Dart instances that are attached to a native
/// instance or sending callback methods from an overridden native class.
@interface FWFURLFlutterApiImpl : NSObject
/// The Flutter API used to send messages back to Dart.
@property FWFNSUrlFlutterApi *api;
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
/// Sends a message to Dart to create a new Dart instance and add it to the `InstanceManager`.
- (void)create:(NSURL *)instance completion:(void (^)(FlutterError *_Nullable))completion;
@end
NS_ASSUME_NONNULL_END
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLHostApi.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLHostApi.h",
"repo_id": "packages",
"token_count": 459
} | 1,072 |
test_on: vm
| packages/packages/xdg_directories/dart_test.yaml/0 | {
"file_path": "packages/packages/xdg_directories/dart_test.yaml",
"repo_id": "packages",
"token_count": 6
} | 1,073 |
name: xdg_directories
description: A Dart package for reading XDG directory configuration information on Linux.
repository: https://github.com/flutter/packages/tree/main/packages/xdg_directories
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+xdg_directories%22
version: 1.0.4
environment:
sdk: ^3.1.0
platforms:
linux:
dependencies:
meta: ^1.3.0
path: ^1.8.0
dev_dependencies:
test: ^1.16.0
topics:
- paths
| packages/packages/xdg_directories/pubspec.yaml/0 | {
"file_path": "packages/packages/xdg_directories/pubspec.yaml",
"repo_id": "packages",
"token_count": 187
} | 1,074 |
# No need for unit tests:
- espresso
| packages/script/configs/exclude_native_unit_android.yaml/0 | {
"file_path": "packages/script/configs/exclude_native_unit_android.yaml",
"repo_id": "packages",
"token_count": 11
} | 1,075 |
// 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' as io;
import 'package:file/file.dart';
import 'package:uuid/uuid.dart';
import 'common/core.dart';
import 'common/gradle.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/plugin_utils.dart';
import 'common/repository_package.dart';
const int _exitGcloudAuthFailed = 3;
/// A command to run tests via Firebase test lab.
class FirebaseTestLabCommand extends PackageLoopingCommand {
/// Creates an instance of the test runner command.
FirebaseTestLabCommand(
super.packagesDir, {
super.processRunner,
super.platform,
}) {
argParser.addOption(
_gCloudProjectArg,
help: 'The Firebase project name.',
);
argParser.addOption(_gCloudServiceKeyArg,
help: 'The path to the service key for gcloud authentication.\n'
'If not provided, setup will be skipped, so testing will fail '
'unless gcloud is already configured.');
argParser.addOption('test-run-id',
defaultsTo: const Uuid().v4(),
help:
'Optional string to append to the results path, to avoid conflicts. '
'Randomly chosen on each invocation if none is provided. '
'The default shown here is just an example.');
argParser.addOption('build-id',
defaultsTo:
io.Platform.environment['CIRRUS_BUILD_ID'] ?? 'unknown_build',
help:
'Optional string to append to the results path, to avoid conflicts. '
r'Defaults to $CIRRUS_BUILD_ID if that is set.');
argParser.addMultiOption('device',
splitCommas: false,
defaultsTo: <String>[
'model=walleye,version=26',
'model=redfin,version=30'
],
help:
'Device model(s) to test. See https://cloud.google.com/sdk/gcloud/reference/firebase/test/android/run for more info');
argParser.addOption(_gCloudResultsBucketArg, mandatory: true);
argParser.addOption(
kEnableExperiment,
defaultsTo: '',
help: 'Enables the given Dart SDK experiments.',
);
}
static const String _gCloudServiceKeyArg = 'service-key';
static const String _gCloudProjectArg = 'project';
static const String _gCloudResultsBucketArg = 'results-bucket';
@override
final String name = 'firebase-test-lab';
@override
final String description = 'Runs the instrumentation tests of the example '
'apps on Firebase Test Lab.\n\n'
'Runs tests in test_instrumentation folder using the '
'instrumentation_test package.';
bool _firebaseProjectConfigured = false;
Future<void> _configureFirebaseProject() async {
if (_firebaseProjectConfigured) {
return;
}
final String serviceKey = getStringArg(_gCloudServiceKeyArg);
if (serviceKey.isEmpty) {
print(
'No --$_gCloudServiceKeyArg provided; skipping gcloud authorization');
} else {
final io.ProcessResult result = await processRunner.run(
'gcloud',
<String>[
'auth',
'activate-service-account',
'--key-file=$serviceKey',
],
logOnError: true,
);
if (result.exitCode != 0) {
printError('Unable to activate gcloud account.');
throw ToolExit(_exitGcloudAuthFailed);
}
}
final String project = getStringArg(_gCloudProjectArg);
if (project.isEmpty) {
print('No --$_gCloudProjectArg provided; skipping gcloud config');
} else {
final int exitCode = await processRunner.runAndStream('gcloud', <String>[
'config',
'set',
'project',
project,
]);
print('');
if (exitCode == 0) {
print('Firebase project configured.');
} else {
logWarning(
'Warning: gcloud config set returned a non-zero exit code. Continuing anyway.');
}
}
_firebaseProjectConfigured = true;
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
final List<PackageResult> results = <PackageResult>[];
for (final RepositoryPackage example in package.getExamples()) {
results.add(await _runForExample(example, package: package));
}
// If all results skipped, report skip overall.
if (results
.every((PackageResult result) => result.state == RunState.skipped)) {
return PackageResult.skip('No examples support Android.');
}
// Otherwise, report failure if there were any failures.
final List<String> allErrors = results
.map((PackageResult result) =>
result.state == RunState.failed ? result.details : <String>[])
.expand((List<String> list) => list)
.toList();
return allErrors.isEmpty
? PackageResult.success()
: PackageResult.fail(allErrors);
}
/// Runs the test for the given example of [package].
Future<PackageResult> _runForExample(
RepositoryPackage example, {
required RepositoryPackage package,
}) async {
final Directory androidDirectory =
example.platformDirectory(FlutterPlatform.android);
if (!androidDirectory.existsSync()) {
return PackageResult.skip(
'${example.displayName} does not support Android.');
}
final Directory uiTestDirectory = androidDirectory
.childDirectory('app')
.childDirectory('src')
.childDirectory('androidTest');
if (!uiTestDirectory.existsSync()) {
printError('No androidTest directory found.');
if (isFlutterPlugin(package)) {
return PackageResult.fail(
<String>['No tests ran (use --exclude if this is intentional).']);
} else {
return PackageResult.skip(
'${example.displayName} has no native Android tests.');
}
}
// Ensure that the Dart integration tests will be run, not just native UI
// tests.
if (!await _testsContainDartIntegrationTestRunner(uiTestDirectory)) {
printError('No integration_test runner found. '
'See the integration_test package README for setup instructions.');
return PackageResult.fail(<String>['No integration_test runner.']);
}
// Ensures that gradle wrapper exists
final GradleProject project = GradleProject(example,
processRunner: processRunner, platform: platform);
if (!await _ensureGradleWrapperExists(project)) {
return PackageResult.fail(<String>['Unable to build example apk']);
}
await _configureFirebaseProject();
if (!await _runGradle(project, 'app:assembleAndroidTest')) {
return PackageResult.fail(<String>['Unable to assemble androidTest']);
}
final List<String> errors = <String>[];
// Used within the loop to ensure a unique GCS output location for each
// test file's run.
int resultsCounter = 0;
for (final File test in _findIntegrationTestFiles(example)) {
final String testName =
getRelativePosixPath(test, from: package.directory);
print('Testing $testName...');
if (!await _runGradle(project, 'app:assembleDebug', testFile: test)) {
printError('Could not build $testName');
errors.add('$testName failed to build');
continue;
}
final String buildId = getStringArg('build-id');
final String testRunId = getStringArg('test-run-id');
final String resultsDir =
'plugins_android_test/${package.displayName}/$buildId/$testRunId/'
'${example.directory.basename}/${resultsCounter++}/';
// Automatically retry failures; there is significant flake with these
// tests whose cause isn't yet understood, and having to re-run the
// entire shard for a flake in any one test is extremely slow. This should
// be removed once the root cause of the flake is understood.
// See https://github.com/flutter/flutter/issues/95063
const int maxRetries = 2;
bool passing = false;
for (int i = 1; i <= maxRetries && !passing; ++i) {
if (i > 1) {
logWarning('$testName failed on attempt ${i - 1}. Retrying...');
}
passing = await _runFirebaseTest(example, test, resultsDir: resultsDir);
}
if (!passing) {
printError('Test failure for $testName after $maxRetries attempts');
errors.add('$testName failed tests');
}
}
if (errors.isEmpty && resultsCounter == 0) {
printError('No integration tests were run.');
errors.add('No tests ran (use --exclude if this is intentional).');
}
return errors.isEmpty
? PackageResult.success()
: PackageResult.fail(errors);
}
/// Checks that Gradle has been configured for [project], and if not runs a
/// Flutter build to generate it.
///
/// Returns true if either gradlew was already present, or the build succeeds.
Future<bool> _ensureGradleWrapperExists(GradleProject project) async {
if (!project.isConfigured()) {
print('Running flutter build apk...');
final String experiment = getStringArg(kEnableExperiment);
final int exitCode = await processRunner.runAndStream(
flutterCommand,
<String>[
'build',
'apk',
'--config-only',
if (experiment.isNotEmpty) '--enable-experiment=$experiment',
],
workingDir: project.androidDirectory);
if (exitCode != 0) {
return false;
}
}
return true;
}
/// Runs [test] from [example] as a Firebase Test Lab test, returning true if
/// the test passed.
///
/// [resultsDir] should be a unique-to-the-test-run directory to store the
/// results on the server.
Future<bool> _runFirebaseTest(
RepositoryPackage example,
File test, {
required String resultsDir,
}) async {
final List<String> args = <String>[
'firebase',
'test',
'android',
'run',
'--type',
'instrumentation',
'--app',
'build/app/outputs/apk/debug/app-debug.apk',
'--test',
'build/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk',
'--timeout',
'7m',
'--results-bucket=gs://${getStringArg(_gCloudResultsBucketArg)}',
'--results-dir=$resultsDir',
for (final String device in getStringListArg('device')) ...<String>[
'--device',
device
],
];
final int exitCode = await processRunner.runAndStream('gcloud', args,
workingDir: example.directory);
return exitCode == 0;
}
/// Builds [target] using Gradle in the given [project]. Assumes Gradle is
/// already configured.
///
/// [testFile] optionally does the Flutter build with the given test file as
/// the build target.
///
/// Returns true if the command succeeds.
Future<bool> _runGradle(
GradleProject project,
String target, {
File? testFile,
}) async {
final String experiment = getStringArg(kEnableExperiment);
final String? extraOptions = experiment.isNotEmpty
? Uri.encodeComponent('--enable-experiment=$experiment')
: null;
final int exitCode = await project.runCommand(
target,
arguments: <String>[
'-Pverbose=true',
if (testFile != null) '-Ptarget=${testFile.path}',
if (extraOptions != null) '-Pextra-front-end-options=$extraOptions',
if (extraOptions != null) '-Pextra-gen-snapshot-options=$extraOptions',
],
);
if (exitCode != 0) {
return false;
}
return true;
}
/// Finds and returns all integration test files for [example].
Iterable<File> _findIntegrationTestFiles(RepositoryPackage example) sync* {
final Directory integrationTestDir =
example.directory.childDirectory('integration_test');
if (!integrationTestDir.existsSync()) {
return;
}
yield* integrationTestDir
.listSync(recursive: true)
.where((FileSystemEntity file) =>
file is File && file.basename.endsWith('_test.dart'))
.cast<File>();
}
/// Returns true if any of the test files in [uiTestDirectory] contain the
/// annotation that means that the test will reports the results of running
/// the Dart integration tests.
Future<bool> _testsContainDartIntegrationTestRunner(
Directory uiTestDirectory) async {
return uiTestDirectory
.list(recursive: true, followLinks: false)
.where((FileSystemEntity entity) => entity is File)
.cast<File>()
.any((File file) {
if (file.basename.endsWith('.java')) {
return file
.readAsStringSync()
.contains('@RunWith(FlutterTestRunner.class)');
} else if (file.basename.endsWith('.kt')) {
return file
.readAsStringSync()
.contains('@RunWith(FlutterTestRunner::class)');
}
return false;
});
}
}
| packages/script/tool/lib/src/firebase_test_lab_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/firebase_test_lab_command.dart",
"repo_id": "packages",
"token_count": 4878
} | 1,076 |
// 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/file.dart';
import 'common/core.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/repository_package.dart';
const int _exitBadTableEntry = 3;
const int _exitUnknownPackageEntry = 4;
/// A command to verify repository-level metadata about packages, such as
/// repo README and CODEOWNERS entries.
class RepoPackageInfoCheckCommand extends PackageLoopingCommand {
/// Creates Dependabot check command instance.
RepoPackageInfoCheckCommand(super.packagesDir, {super.gitDir});
late Directory _repoRoot;
/// Data from the root README.md table of packages.
final Map<String, List<String>> _readmeTableEntries =
<String, List<String>>{};
/// Packages with entries in CODEOWNERS.
final List<String> _ownedPackages = <String>[];
@override
final String name = 'repo-package-info-check';
@override
List<String> get aliases => <String>['check-repo-package-info'];
@override
final String description =
'Checks that all packages are listed correctly in the repo README.';
@override
final bool hasLongOutput = false;
@override
Future<void> initializeRun() async {
_repoRoot = packagesDir.fileSystem.directory((await gitDir).path);
// Extract all of the README.md table entries.
final RegExp namePattern = RegExp(r'\[(.*?)\]\(');
for (final String line
in _repoRoot.childFile('README.md').readAsLinesSync()) {
// Find all the table entries, skipping the header.
if (line.startsWith('|') &&
!line.startsWith('| Package') &&
!line.startsWith('|-')) {
final List<String> cells = line
.split('|')
.map((String s) => s.trim())
.where((String s) => s.isNotEmpty)
.toList();
// Extract the name, removing any markdown escaping.
final String? name =
namePattern.firstMatch(cells[0])?.group(1)?.replaceAll(r'\_', '_');
if (name == null) {
printError('Unexpected README table line:\n $line');
throw ToolExit(_exitBadTableEntry);
}
_readmeTableEntries[name] = cells;
if (!(packagesDir.childDirectory(name).existsSync() ||
thirdPartyPackagesDir.childDirectory(name).existsSync())) {
printError('Unknown package "$name" in root README.md table.');
throw ToolExit(_exitUnknownPackageEntry);
}
}
}
// Extract all of the CODEOWNERS package entries.
final RegExp packageOwnershipPattern =
RegExp(r'^((?:third_party/)?packages/(?:[^/]*/)?([^/]*))/\*\*');
for (final String line
in _repoRoot.childFile('CODEOWNERS').readAsLinesSync()) {
final RegExpMatch? match = packageOwnershipPattern.firstMatch(line);
if (match == null) {
continue;
}
final String path = match.group(1)!;
final String name = match.group(2)!;
if (!_repoRoot.childDirectory(path).existsSync()) {
printError('Unknown directory "$path" in CODEOWNERS');
throw ToolExit(_exitUnknownPackageEntry);
}
_ownedPackages.add(name);
}
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
final String packageName = package.directory.basename;
final List<String> errors = <String>[];
// All packages should have an owner.
// Platform interface packages are considered to be owned by the app-facing
// package owner.
if (!(_ownedPackages.contains(packageName) ||
package.isPlatformInterface &&
_ownedPackages.contains(package.directory.parent.basename))) {
printError('${indentation}Missing CODEOWNERS entry.');
errors.add('Missing CODEOWNERS entry');
}
// Any published package should be in the README table.
// For federated plugins, only the app-facing package is listed.
if (package.isPublishable() &&
(!package.isFederated || package.isAppFacing)) {
final List<String>? cells = _readmeTableEntries[packageName];
if (cells == null) {
printError('${indentation}Missing repo root README.md table entry');
errors.add('Missing repo root README.md table entry');
} else {
// Extract the two parts of a "[label](link)" .md link.
final RegExp mdLinkPattern = RegExp(r'^\[(.*)\]\((.*)\)$');
// Possible link targets.
for (final String cell in cells) {
final RegExpMatch? match = mdLinkPattern.firstMatch(cell);
if (match == null) {
printError(
'${indentation}Invalid repo root README.md table entry: "$cell"');
errors.add('Invalid root README.md table entry');
} else {
final String encodedIssueTag =
Uri.encodeComponent(_issueTagForPackage(packageName));
final String encodedPRTag =
Uri.encodeComponent(_prTagForPackage(packageName));
final String anchor = match.group(1)!;
final String target = match.group(2)!;
// The anchor should be one of:
// - The package name (optionally with any underscores escaped)
// - An image with a name-based link
// - An image with a tag-based link
final RegExp packageLink =
RegExp(r'^!\[.*\]\(https://img.shields.io/pub/.*/'
'$packageName'
r'(?:\.svg)?\)$');
final RegExp issueTagLink = RegExp(
r'^!\[.*\]\(https://img.shields.io/github/issues/flutter/flutter/'
'$encodedIssueTag'
r'\?label=\)$');
final RegExp prTagLink = RegExp(
r'^!\[.*\]\(https://img.shields.io/github/issues-pr/flutter/packages/'
'$encodedPRTag'
r'\?label=\)$');
if (!(anchor == packageName ||
anchor == packageName.replaceAll('_', r'\_') ||
packageLink.hasMatch(anchor) ||
issueTagLink.hasMatch(anchor) ||
prTagLink.hasMatch(anchor))) {
printError(
'${indentation}Incorrect anchor in root README.md table: "$anchor"');
errors.add('Incorrect anchor in root README.md table');
}
// The link should be one of:
// - a relative link to the in-repo package
// - a pub.dev link to the package
// - a github label link to the package's label
final RegExp pubDevLink =
RegExp('^https://pub.dev/packages/$packageName(?:/score)?\$');
final RegExp gitHubIssueLink = RegExp(
'^https://github.com/flutter/flutter/labels/$encodedIssueTag\$');
final RegExp gitHubPRLink = RegExp(
'^https://github.com/flutter/packages/labels/$encodedPRTag\$');
if (!(target == './packages/$packageName/' ||
target == './third_party/packages/$packageName/' ||
pubDevLink.hasMatch(target) ||
gitHubIssueLink.hasMatch(target) ||
gitHubPRLink.hasMatch(target))) {
printError(
'${indentation}Incorrect link in root README.md table: "$target"');
errors.add('Incorrect link in root README.md table');
}
}
}
}
}
return errors.isEmpty
? PackageResult.success()
: PackageResult.fail(errors);
}
String _prTagForPackage(String packageName) => 'p: $packageName';
String _issueTagForPackage(String packageName) {
switch (packageName) {
case 'google_maps_flutter':
return 'p: maps';
case 'webview_flutter':
return 'p: webview';
default:
return 'p: $packageName';
}
}
}
| packages/script/tool/lib/src/repo_package_info_check_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/repo_package_info_check_command.dart",
"repo_id": "packages",
"token_count": 3358
} | 1,077 |
// 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:io' as io;
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/common/output_utils.dart';
import 'package:flutter_plugin_tools/src/common/package_looping_command.dart';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import '../mocks.dart';
import '../util.dart';
import 'package_command_test.mocks.dart';
// Constants for colorized output start and end.
const String _startElapsedTimeColor = '\x1B[90m';
const String _startErrorColor = '\x1B[31m';
const String _startHeadingColor = '\x1B[36m';
const String _startSkipColor = '\x1B[90m';
const String _startSkipWithWarningColor = '\x1B[93m';
const String _startSuccessColor = '\x1B[32m';
const String _startWarningColor = '\x1B[33m';
const String _endColor = '\x1B[0m';
// The filename within a package containing warnings to log during runForPackage.
enum _ResultFileType {
/// A file containing errors to return.
errors,
/// A file containing warnings that should be logged.
warns,
/// A file indicating that the package should be skipped, and why.
skips,
/// A file indicating that the package should throw.
throws,
}
// The filename within a package containing errors to return from runForPackage.
const String _errorFile = 'errors';
// The filename within a package indicating that it should be skipped.
const String _skipFile = 'skip';
// The filename within a package containing warnings to log during runForPackage.
const String _warningFile = 'warnings';
// The filename within a package indicating that it should throw.
const String _throwFile = 'throw';
/// Writes a file to [package] to control the behavior of
/// [TestPackageLoopingCommand] for that package.
void _addResultFile(RepositoryPackage package, _ResultFileType type,
{String? contents}) {
final File file = package.directory.childFile(_filenameForType(type));
file.createSync();
if (contents != null) {
file.writeAsStringSync(contents);
}
}
String _filenameForType(_ResultFileType type) {
switch (type) {
case _ResultFileType.errors:
return _errorFile;
case _ResultFileType.warns:
return _warningFile;
case _ResultFileType.skips:
return _skipFile;
case _ResultFileType.throws:
return _throwFile;
}
}
void main() {
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
late Directory thirdPartyPackagesDir;
setUp(() {
// Correct color handling is part of the behavior being tested here.
useColorForOutput = true;
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
thirdPartyPackagesDir = packagesDir.parent
.childDirectory('third_party')
.childDirectory('packages');
});
tearDown(() {
// Restore the default behavior.
useColorForOutput = io.stdout.supportsAnsiEscapes;
});
/// Creates a TestPackageLoopingCommand instance that uses [gitDiffResponse]
/// for git diffs, and logs output to [printOutput].
TestPackageLoopingCommand createTestCommand({
String gitDiffResponse = '',
bool hasLongOutput = true,
PackageLoopingType packageLoopingType = PackageLoopingType.topLevelOnly,
bool failsDuringInit = false,
bool warnsDuringInit = false,
bool captureOutput = false,
String? customFailureListHeader,
String? customFailureListFooter,
}) {
// Set up the git diff response.
final MockGitDir gitDir = MockGitDir();
when(gitDir.runCommand(any, throwOnError: anyNamed('throwOnError')))
.thenAnswer((Invocation invocation) {
final List<String> arguments =
invocation.positionalArguments[0]! as List<String>;
String? gitStdOut;
if (arguments[0] == 'diff') {
gitStdOut = gitDiffResponse;
}
return Future<io.ProcessResult>.value(
io.ProcessResult(0, 0, gitStdOut ?? '', ''));
});
return TestPackageLoopingCommand(
packagesDir,
platform: mockPlatform,
hasLongOutput: hasLongOutput,
packageLoopingType: packageLoopingType,
failsDuringInit: failsDuringInit,
warnsDuringInit: warnsDuringInit,
customFailureListHeader: customFailureListHeader,
customFailureListFooter: customFailureListFooter,
captureOutput: captureOutput,
gitDir: gitDir,
);
}
/// Runs [command] with the given [arguments], and returns its output.
Future<List<String>> runCommand(
TestPackageLoopingCommand command, {
List<String> arguments = const <String>[],
void Function(Error error)? errorHandler,
}) async {
late CommandRunner<void> runner;
runner = CommandRunner<void>('test_package_looping_command',
'Test for base package looping functionality');
runner.addCommand(command);
return runCapturingPrint(
runner,
<String>[command.name, ...arguments],
errorHandler: errorHandler,
);
}
group('tool exit', () {
test('is handled during initializeRun', () async {
final TestPackageLoopingCommand command =
createTestCommand(failsDuringInit: true);
expect(() => runCommand(command), throwsA(isA<ToolExit>()));
});
test('does not stop looping on error', () async {
createFakePackage('package_a', packagesDir);
final RepositoryPackage failingPackage =
createFakePlugin('package_b', packagesDir);
createFakePackage('package_c', packagesDir);
_addResultFile(failingPackage, _ResultFileType.errors);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
Error? commandError;
final List<String> output =
await runCommand(command, errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<String>[
'${_startHeadingColor}Running for package_a...$_endColor',
'${_startHeadingColor}Running for package_b...$_endColor',
'${_startHeadingColor}Running for package_c...$_endColor',
]));
});
test('does not stop looping on exceptions', () async {
createFakePackage('package_a', packagesDir);
final RepositoryPackage failingPackage =
createFakePlugin('package_b', packagesDir);
createFakePackage('package_c', packagesDir);
_addResultFile(failingPackage, _ResultFileType.throws);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
Error? commandError;
final List<String> output =
await runCommand(command, errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<String>[
'${_startHeadingColor}Running for package_a...$_endColor',
'${_startHeadingColor}Running for package_b...$_endColor',
'${_startHeadingColor}Running for package_c...$_endColor',
]));
});
});
group('package iteration', () {
test('includes plugins and packages', () async {
final RepositoryPackage plugin =
createFakePlugin('a_plugin', packagesDir);
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
final TestPackageLoopingCommand command = createTestCommand();
await runCommand(command);
expect(command.checkedPackages,
unorderedEquals(<String>[plugin.path, package.path]));
});
test('includes third_party/packages', () async {
final RepositoryPackage package1 =
createFakePackage('a_package', packagesDir);
final RepositoryPackage package2 =
createFakePackage('another_package', thirdPartyPackagesDir);
final TestPackageLoopingCommand command = createTestCommand();
await runCommand(command);
expect(command.checkedPackages,
unorderedEquals(<String>[package1.path, package2.path]));
});
test('includes all subpackages when requested', () async {
final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir,
examples: <String>['example1', 'example2']);
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
final RepositoryPackage subPackage = createFakePackage(
'sub_package', package.directory,
examples: <String>[]);
final TestPackageLoopingCommand command = createTestCommand(
packageLoopingType: PackageLoopingType.includeAllSubpackages);
await runCommand(command);
expect(
command.checkedPackages,
unorderedEquals(<String>[
plugin.path,
getExampleDir(plugin).childDirectory('example1').path,
getExampleDir(plugin).childDirectory('example2').path,
package.path,
getExampleDir(package).path,
subPackage.path,
]));
});
test('includes examples when requested', () async {
final RepositoryPackage plugin = createFakePlugin('a_plugin', packagesDir,
examples: <String>['example1', 'example2']);
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
final RepositoryPackage subPackage =
createFakePackage('sub_package', package.directory);
final TestPackageLoopingCommand command = createTestCommand(
packageLoopingType: PackageLoopingType.includeExamples);
await runCommand(command);
expect(
command.checkedPackages,
unorderedEquals(<String>[
plugin.path,
getExampleDir(plugin).childDirectory('example1').path,
getExampleDir(plugin).childDirectory('example2').path,
package.path,
getExampleDir(package).path,
]));
expect(command.checkedPackages, isNot(contains(subPackage.path)));
});
test('excludes subpackages when main package is excluded', () async {
final RepositoryPackage excluded = createFakePlugin(
'a_plugin', packagesDir,
examples: <String>['example1', 'example2']);
final RepositoryPackage included =
createFakePackage('a_package', packagesDir);
final RepositoryPackage subpackage =
createFakePackage('sub_package', excluded.directory);
final TestPackageLoopingCommand command = createTestCommand(
packageLoopingType: PackageLoopingType.includeAllSubpackages);
await runCommand(command, arguments: <String>['--exclude=a_plugin']);
final Iterable<RepositoryPackage> examples = excluded.getExamples();
expect(
command.checkedPackages,
unorderedEquals(<String>[
included.path,
getExampleDir(included).path,
]));
expect(command.checkedPackages, isNot(contains(excluded.path)));
expect(examples.length, 2);
for (final RepositoryPackage example in examples) {
expect(command.checkedPackages, isNot(contains(example.path)));
}
expect(command.checkedPackages, isNot(contains(subpackage.path)));
});
test('excludes examples when main package is excluded', () async {
final RepositoryPackage excluded = createFakePlugin(
'a_plugin', packagesDir,
examples: <String>['example1', 'example2']);
final RepositoryPackage included =
createFakePackage('a_package', packagesDir);
final TestPackageLoopingCommand command = createTestCommand(
packageLoopingType: PackageLoopingType.includeExamples);
await runCommand(command, arguments: <String>['--exclude=a_plugin']);
final Iterable<RepositoryPackage> examples = excluded.getExamples();
expect(
command.checkedPackages,
unorderedEquals(<String>[
included.path,
getExampleDir(included).path,
]));
expect(command.checkedPackages, isNot(contains(excluded.path)));
expect(examples.length, 2);
for (final RepositoryPackage example in examples) {
expect(command.checkedPackages, isNot(contains(example.path)));
}
});
test('skips unsupported Flutter versions when requested', () async {
final RepositoryPackage excluded = createFakePlugin(
'a_plugin', packagesDir,
flutterConstraint: '>=2.10.0');
final RepositoryPackage included =
createFakePackage('a_package', packagesDir);
final TestPackageLoopingCommand command = createTestCommand(
packageLoopingType: PackageLoopingType.includeAllSubpackages,
hasLongOutput: false);
final List<String> output = await runCommand(command, arguments: <String>[
'--skip-if-not-supporting-flutter-version=2.5.0'
]);
expect(
command.checkedPackages,
unorderedEquals(<String>[
included.path,
getExampleDir(included).path,
]));
expect(command.checkedPackages, isNot(contains(excluded.path)));
expect(
output,
containsAllInOrder(<String>[
'${_startHeadingColor}Running for a_package...$_endColor',
'${_startHeadingColor}Running for a_plugin...$_endColor',
'$_startSkipColor SKIPPING: Does not support Flutter 2.5.0$_endColor',
]));
});
test('skips unsupported Dart versions when requested', () async {
final RepositoryPackage excluded = createFakePackage(
'excluded_package', packagesDir,
dartConstraint: '>=2.18.0 <4.0.0');
final RepositoryPackage included =
createFakePackage('a_package', packagesDir);
final TestPackageLoopingCommand command = createTestCommand(
packageLoopingType: PackageLoopingType.includeAllSubpackages,
hasLongOutput: false);
final List<String> output = await runCommand(command, arguments: <String>[
'--skip-if-not-supporting-flutter-version=3.0.0' // Flutter 3.0.0 -> Dart 2.17.0
]);
expect(
command.checkedPackages,
unorderedEquals(<String>[
included.path,
getExampleDir(included).path,
]));
expect(command.checkedPackages, isNot(contains(excluded.path)));
expect(
output,
containsAllInOrder(<String>[
'${_startHeadingColor}Running for a_package...$_endColor',
'${_startHeadingColor}Running for excluded_package...$_endColor',
'$_startSkipColor SKIPPING: Does not support Dart 2.17.0$_endColor',
]));
});
});
group('output', () {
test('has the expected package headers for long-form output', () async {
createFakePlugin('package_a', packagesDir);
createFakePackage('package_b', packagesDir);
final TestPackageLoopingCommand command = createTestCommand();
final List<String> output = await runCommand(command);
const String separator =
'============================================================';
expect(
output,
containsAllInOrder(<String>[
'$_startHeadingColor\n$separator\n|| Running for package_a\n$separator\n$_endColor',
'$_startHeadingColor\n$separator\n|| Running for package_b\n$separator\n$_endColor',
]));
});
test('has the expected package headers for short-form output', () async {
createFakePlugin('package_a', packagesDir);
createFakePackage('package_b', packagesDir);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
final List<String> output = await runCommand(command);
expect(
output,
containsAllInOrder(<String>[
'${_startHeadingColor}Running for package_a...$_endColor',
'${_startHeadingColor}Running for package_b...$_endColor',
]));
});
test('prints timing info in long-form output when requested', () async {
createFakePlugin('package_a', packagesDir);
createFakePackage('package_b', packagesDir);
final TestPackageLoopingCommand command = createTestCommand();
final List<String> output =
await runCommand(command, arguments: <String>['--log-timing']);
const String separator =
'============================================================';
expect(
output,
containsAllInOrder(<String>[
'$_startHeadingColor\n$separator\n|| Running for package_a [@0:00]\n$separator\n$_endColor',
'$_startElapsedTimeColor\n[package_a completed in 0m 0s]$_endColor',
'$_startHeadingColor\n$separator\n|| Running for package_b [@0:00]\n$separator\n$_endColor',
'$_startElapsedTimeColor\n[package_b completed in 0m 0s]$_endColor',
]));
});
test('prints timing info in short-form output when requested', () async {
createFakePlugin('package_a', packagesDir);
createFakePackage('package_b', packagesDir);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
final List<String> output =
await runCommand(command, arguments: <String>['--log-timing']);
expect(
output,
containsAllInOrder(<String>[
'$_startHeadingColor[0:00] Running for package_a...$_endColor',
'$_startHeadingColor[0:00] Running for package_b...$_endColor',
]));
// Short-form output should not include elapsed time.
expect(output, isNot(contains('[package_a completed in 0m 0s]')));
});
test('shows the success message when nothing fails', () async {
createFakePackage('package_a', packagesDir);
createFakePackage('package_b', packagesDir);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
final List<String> output = await runCommand(command);
expect(
output,
containsAllInOrder(<String>[
'\n',
'${_startSuccessColor}No issues found!$_endColor',
]));
});
test('shows failure summaries when something fails without extra details',
() async {
createFakePackage('package_a', packagesDir);
final RepositoryPackage failingPackage1 =
createFakePlugin('package_b', packagesDir);
createFakePackage('package_c', packagesDir);
final RepositoryPackage failingPackage2 =
createFakePlugin('package_d', packagesDir);
_addResultFile(failingPackage1, _ResultFileType.errors);
_addResultFile(failingPackage2, _ResultFileType.errors);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
Error? commandError;
final List<String> output =
await runCommand(command, errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<String>[
'\n',
'${_startErrorColor}The following packages had errors:$_endColor',
'$_startErrorColor package_b$_endColor',
'$_startErrorColor package_d$_endColor',
'${_startErrorColor}See above for full details.$_endColor',
]));
});
test('uses custom summary header and footer if provided', () async {
createFakePackage('package_a', packagesDir);
final RepositoryPackage failingPackage1 =
createFakePlugin('package_b', packagesDir);
createFakePackage('package_c', packagesDir);
final RepositoryPackage failingPackage2 =
createFakePlugin('package_d', packagesDir);
_addResultFile(failingPackage1, _ResultFileType.errors);
_addResultFile(failingPackage2, _ResultFileType.errors);
final TestPackageLoopingCommand command = createTestCommand(
hasLongOutput: false,
customFailureListHeader: 'This is a custom header',
customFailureListFooter: 'And a custom footer!');
Error? commandError;
final List<String> output =
await runCommand(command, errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<String>[
'\n',
'${_startErrorColor}This is a custom header$_endColor',
'$_startErrorColor package_b$_endColor',
'$_startErrorColor package_d$_endColor',
'${_startErrorColor}And a custom footer!$_endColor',
]));
});
test('shows failure summaries when something fails with extra details',
() async {
createFakePackage('package_a', packagesDir);
final RepositoryPackage failingPackage1 =
createFakePlugin('package_b', packagesDir);
createFakePackage('package_c', packagesDir);
final RepositoryPackage failingPackage2 =
createFakePlugin('package_d', packagesDir);
_addResultFile(failingPackage1, _ResultFileType.errors,
contents: 'just one detail');
_addResultFile(failingPackage2, _ResultFileType.errors,
contents: 'first detail\nsecond detail');
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
Error? commandError;
final List<String> output =
await runCommand(command, errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<String>[
'\n',
'${_startErrorColor}The following packages had errors:$_endColor',
'$_startErrorColor package_b:\n just one detail$_endColor',
'$_startErrorColor package_d:\n first detail\n second detail$_endColor',
'${_startErrorColor}See above for full details.$_endColor',
]));
});
test('is captured, not printed, when requested', () async {
createFakePlugin('package_a', packagesDir);
createFakePackage('package_b', packagesDir);
final TestPackageLoopingCommand command =
createTestCommand(captureOutput: true);
final List<String> output = await runCommand(command);
expect(output, isEmpty);
// None of the output should be colorized when captured.
const String separator =
'============================================================';
expect(
command.capturedOutput,
containsAllInOrder(<String>[
'\n$separator\n|| Running for package_a\n$separator\n',
'\n$separator\n|| Running for package_b\n$separator\n',
'No issues found!',
]));
});
test('logs skips', () async {
createFakePackage('package_a', packagesDir);
final RepositoryPackage skipPackage =
createFakePackage('package_b', packagesDir);
_addResultFile(skipPackage, _ResultFileType.skips,
contents: 'For a reason');
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
final List<String> output = await runCommand(command);
expect(
output,
containsAllInOrder(<String>[
'${_startHeadingColor}Running for package_a...$_endColor',
'${_startHeadingColor}Running for package_b...$_endColor',
'$_startSkipColor SKIPPING: For a reason$_endColor',
]));
});
test('logs exclusions', () async {
createFakePackage('package_a', packagesDir);
createFakePackage('package_b', packagesDir);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
final List<String> output =
await runCommand(command, arguments: <String>['--exclude=package_b']);
expect(
output,
containsAllInOrder(<String>[
'${_startHeadingColor}Running for package_a...$_endColor',
'${_startSkipColor}Not running for package_b; excluded$_endColor',
]));
});
test('logs warnings', () async {
final RepositoryPackage warnPackage =
createFakePackage('package_a', packagesDir);
_addResultFile(warnPackage, _ResultFileType.warns,
contents: 'Warning 1\nWarning 2');
createFakePackage('package_b', packagesDir);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
final List<String> output = await runCommand(command);
expect(
output,
containsAllInOrder(<String>[
'${_startHeadingColor}Running for package_a...$_endColor',
'${_startWarningColor}Warning 1$_endColor',
'${_startWarningColor}Warning 2$_endColor',
'${_startHeadingColor}Running for package_b...$_endColor',
]));
});
test('logs unhandled exceptions as errors', () async {
createFakePackage('package_a', packagesDir);
final RepositoryPackage failingPackage =
createFakePlugin('package_b', packagesDir);
createFakePackage('package_c', packagesDir);
_addResultFile(failingPackage, _ResultFileType.throws);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
Error? commandError;
final List<String> output =
await runCommand(command, errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<String>[
'${_startErrorColor}Exception: Uh-oh$_endColor',
'${_startErrorColor}The following packages had errors:$_endColor',
'$_startErrorColor package_b:\n Unhandled exception$_endColor',
]));
});
test('prints run summary on success', () async {
final RepositoryPackage warnPackage1 =
createFakePackage('package_a', packagesDir);
_addResultFile(warnPackage1, _ResultFileType.warns,
contents: 'Warning 1\nWarning 2');
createFakePackage('package_b', packagesDir);
final RepositoryPackage skipPackage =
createFakePackage('package_c', packagesDir);
_addResultFile(skipPackage, _ResultFileType.skips,
contents: 'For a reason');
final RepositoryPackage skipAndWarnPackage =
createFakePackage('package_d', packagesDir);
_addResultFile(skipAndWarnPackage, _ResultFileType.warns,
contents: 'Warning');
_addResultFile(skipAndWarnPackage, _ResultFileType.skips,
contents: 'See warning');
final RepositoryPackage warnPackage2 =
createFakePackage('package_e', packagesDir);
_addResultFile(warnPackage2, _ResultFileType.warns,
contents: 'Warning 1\nWarning 2');
createFakePackage('package_f', packagesDir);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
final List<String> output = await runCommand(command);
expect(
output,
containsAllInOrder(<String>[
'------------------------------------------------------------',
'Ran for 4 package(s) (2 with warnings)',
'Skipped 2 package(s) (1 with warnings)',
'\n',
'${_startSuccessColor}No issues found!$_endColor',
]));
// The long-form summary should not be printed for short-form commands.
expect(output, isNot(contains('Run summary:')));
expect(output, isNot(contains(contains('package a - ran'))));
});
test('counts exclusions as skips in run summary', () async {
createFakePackage('package_a', packagesDir);
final TestPackageLoopingCommand command =
createTestCommand(hasLongOutput: false);
final List<String> output =
await runCommand(command, arguments: <String>['--exclude=package_a']);
expect(
output,
containsAllInOrder(<String>[
'------------------------------------------------------------',
'Skipped 1 package(s)',
'\n',
'${_startSuccessColor}No issues found!$_endColor',
]));
});
test('prints long-form run summary for long-output commands', () async {
final RepositoryPackage warnPackage1 =
createFakePackage('package_a', packagesDir);
_addResultFile(warnPackage1, _ResultFileType.warns,
contents: 'Warning 1\nWarning 2');
createFakePackage('package_b', packagesDir);
final RepositoryPackage skipPackage =
createFakePackage('package_c', packagesDir);
_addResultFile(skipPackage, _ResultFileType.skips,
contents: 'For a reason');
final RepositoryPackage skipAndWarnPackage =
createFakePackage('package_d', packagesDir);
_addResultFile(skipAndWarnPackage, _ResultFileType.warns,
contents: 'Warning');
_addResultFile(skipAndWarnPackage, _ResultFileType.skips,
contents: 'See warning');
final RepositoryPackage warnPackage2 =
createFakePackage('package_e', packagesDir);
_addResultFile(warnPackage2, _ResultFileType.warns,
contents: 'Warning 1\nWarning 2');
createFakePackage('package_f', packagesDir);
final TestPackageLoopingCommand command = createTestCommand();
final List<String> output = await runCommand(command);
expect(
output,
containsAllInOrder(<String>[
'------------------------------------------------------------',
'Run overview:',
' package_a - ${_startWarningColor}ran (with warning)$_endColor',
' package_b - ${_startSuccessColor}ran$_endColor',
' package_c - ${_startSkipColor}skipped$_endColor',
' package_d - ${_startSkipWithWarningColor}skipped (with warning)$_endColor',
' package_e - ${_startWarningColor}ran (with warning)$_endColor',
' package_f - ${_startSuccessColor}ran$_endColor',
'',
'Ran for 4 package(s) (2 with warnings)',
'Skipped 2 package(s) (1 with warnings)',
'\n',
'${_startSuccessColor}No issues found!$_endColor',
]));
});
test('prints exclusions as skips in long-form run summary', () async {
createFakePackage('package_a', packagesDir);
final TestPackageLoopingCommand command = createTestCommand();
final List<String> output =
await runCommand(command, arguments: <String>['--exclude=package_a']);
expect(
output,
containsAllInOrder(<String>[
' package_a - ${_startSkipColor}excluded$_endColor',
'',
'Skipped 1 package(s)',
'\n',
'${_startSuccessColor}No issues found!$_endColor',
]));
});
test('handles warnings outside of runForPackage', () async {
createFakePackage('package_a', packagesDir);
final TestPackageLoopingCommand command = createTestCommand(
hasLongOutput: false,
warnsDuringInit: true,
);
final List<String> output = await runCommand(command);
expect(
output,
containsAllInOrder(<String>[
'${_startWarningColor}Warning during initializeRun$_endColor',
'${_startHeadingColor}Running for package_a...$_endColor',
'${_startWarningColor}Warning during completeRun$_endColor',
'------------------------------------------------------------',
'Ran for 1 package(s)',
'2 warnings not associated with a package',
'\n',
'${_startSuccessColor}No issues found!$_endColor',
]));
});
});
}
class TestPackageLoopingCommand extends PackageLoopingCommand {
TestPackageLoopingCommand(
super.packagesDir, {
required super.platform,
this.hasLongOutput = true,
this.packageLoopingType = PackageLoopingType.topLevelOnly,
this.customFailureListHeader,
this.customFailureListFooter,
this.failsDuringInit = false,
this.warnsDuringInit = false,
this.captureOutput = false,
super.processRunner,
super.gitDir,
});
final List<String> checkedPackages = <String>[];
final List<String> capturedOutput = <String>[];
final String? customFailureListHeader;
final String? customFailureListFooter;
final bool failsDuringInit;
final bool warnsDuringInit;
@override
bool hasLongOutput;
@override
PackageLoopingType packageLoopingType;
@override
String get failureListHeader =>
customFailureListHeader ?? super.failureListHeader;
@override
String get failureListFooter =>
customFailureListFooter ?? super.failureListFooter;
@override
bool captureOutput;
@override
final String name = 'loop-test';
@override
final String description = 'sample package looping command';
@override
Future<void> initializeRun() async {
if (warnsDuringInit) {
logWarning('Warning during initializeRun');
}
if (failsDuringInit) {
throw ToolExit(2);
}
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
checkedPackages.add(package.path);
final File warningFile = package.directory.childFile(_warningFile);
if (warningFile.existsSync()) {
final List<String> warnings = warningFile.readAsLinesSync();
warnings.forEach(logWarning);
}
final File skipFile = package.directory.childFile(_skipFile);
if (skipFile.existsSync()) {
return PackageResult.skip(skipFile.readAsStringSync());
}
final File errorFile = package.directory.childFile(_errorFile);
if (errorFile.existsSync()) {
return PackageResult.fail(errorFile.readAsLinesSync());
}
final File throwFile = package.directory.childFile(_throwFile);
if (throwFile.existsSync()) {
throw Exception('Uh-oh');
}
return PackageResult.success();
}
@override
Future<void> completeRun() async {
if (warnsDuringInit) {
logWarning('Warning during completeRun');
}
}
@override
Future<void> handleCapturedOutput(List<String> output) async {
capturedOutput.addAll(output);
}
}
| packages/script/tool/test/common/package_looping_command_test.dart/0 | {
"file_path": "packages/script/tool/test/common/package_looping_command_test.dart",
"repo_id": "packages",
"token_count": 13204
} | 1,078 |
// 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 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/common/file_utils.dart';
import 'package:flutter_plugin_tools/src/format_command.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
late RecordingProcessRunner processRunner;
late FormatCommand analyzeCommand;
late CommandRunner<void> runner;
late String javaFormatPath;
late String kotlinFormatPath;
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
processRunner = RecordingProcessRunner();
analyzeCommand = FormatCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
// Create the Java and Kotlin formatter files that the command checks for,
// to avoid a download.
final p.Context path = analyzeCommand.path;
javaFormatPath = path.join(path.dirname(path.fromUri(mockPlatform.script)),
'google-java-format-1.3-all-deps.jar');
fileSystem.file(javaFormatPath).createSync(recursive: true);
kotlinFormatPath = path.join(
path.dirname(path.fromUri(mockPlatform.script)),
'ktfmt-0.46-jar-with-dependencies.jar');
fileSystem.file(kotlinFormatPath).createSync(recursive: true);
runner = CommandRunner<void>('format_command', 'Test for format_command');
runner.addCommand(analyzeCommand);
});
/// Returns a modified version of a list of [relativePaths] that are relative
/// to [package] to instead be relative to [packagesDir].
List<String> getPackagesDirRelativePaths(
RepositoryPackage package, List<String> relativePaths) {
final p.Context path = analyzeCommand.path;
final String relativeBase =
path.relative(package.path, from: packagesDir.path);
return relativePaths
.map((String relativePath) => path.join(relativeBase, relativePath))
.toList();
}
/// Returns a list of [count] relative paths to pass to [createFakePlugin]
/// or [createFakePackage] with name [packageName] such that each path will
/// be 99 characters long relative to [packagesDir].
///
/// This is for each of testing batching, since it means each file will
/// consume 100 characters of the batch length.
List<String> get99CharacterPathExtraFiles(String packageName, int count) {
final int padding = 99 -
packageName.length -
1 - // the path separator after the package name
1 - // the path separator after the padding
10; // the file name
const int filenameBase = 10000;
final p.Context path = analyzeCommand.path;
return <String>[
for (int i = filenameBase; i < filenameBase + count; ++i)
path.join('a' * padding, '$i.dart'),
];
}
test('formats .dart files', () async {
const List<String> files = <String>[
'lib/a.dart',
'lib/src/b.dart',
'lib/src/c.dart',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(runner, <String>['format']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'dart',
<String>['format', ...getPackagesDirRelativePaths(plugin, files)],
packagesDir.path),
]));
});
test('does not format .dart files with pragma', () async {
const List<String> formattedFiles = <String>[
'lib/a.dart',
'lib/src/b.dart',
'lib/src/c.dart',
];
const String unformattedFile = 'lib/src/d.dart';
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: <String>[
...formattedFiles,
unformattedFile,
],
);
final p.Context posixContext = p.posix;
childFileWithSubcomponents(
plugin.directory, posixContext.split(unformattedFile))
.writeAsStringSync(
'// copyright bla bla\n// This file is hand-formatted.\ncode...');
await runCapturingPrint(runner, <String>['format']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'dart',
<String>[
'format',
...getPackagesDirRelativePaths(plugin, formattedFiles)
],
packagesDir.path),
]));
});
test('fails if dart format fails', () async {
const List<String> files = <String>[
'lib/a.dart',
'lib/src/b.dart',
'lib/src/c.dart',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['format'])
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['format'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Failed to format Dart files: exit code 1.'),
]));
});
test('skips dart if --no-dart flag is provided', () async {
const List<String> files = <String>[
'lib/a.dart',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
await runCapturingPrint(runner, <String>['format', '--no-dart']);
expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[]));
});
test('formats .java files', () async {
const List<String> files = <String>[
'android/src/main/java/io/flutter/plugins/a_plugin/a.java',
'android/src/main/java/io/flutter/plugins/a_plugin/b.java',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(runner, <String>['format']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall('java', <String>['-version'], null),
ProcessCall(
'java',
<String>[
'-jar',
javaFormatPath,
'--replace',
...getPackagesDirRelativePaths(plugin, files)
],
packagesDir.path),
]));
});
test('fails with a clear message if Java is not in the path', () async {
const List<String> files = <String>[
'android/src/main/java/io/flutter/plugins/a_plugin/a.java',
'android/src/main/java/io/flutter/plugins/a_plugin/b.java',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['java'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['-version'])
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['format'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Unable to run "java". Make sure that it is in your path, or '
'provide a full path with --java-path.'),
]));
});
test('fails if Java formatter fails', () async {
const List<String> files = <String>[
'android/src/main/java/io/flutter/plugins/a_plugin/a.java',
'android/src/main/java/io/flutter/plugins/a_plugin/b.java',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['java'] = <FakeProcessInfo>[
FakeProcessInfo(
MockProcess(), <String>['-version']), // check for working java
FakeProcessInfo(MockProcess(exitCode: 1), <String>['-jar']), // format
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['format'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Failed to format Java files: exit code 1.'),
]));
});
test('honors --java-path flag', () async {
const List<String> files = <String>[
'android/src/main/java/io/flutter/plugins/a_plugin/a.java',
'android/src/main/java/io/flutter/plugins/a_plugin/b.java',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(
runner, <String>['format', '--java-path=/path/to/java']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall('/path/to/java', <String>['--version'], null),
ProcessCall(
'/path/to/java',
<String>[
'-jar',
javaFormatPath,
'--replace',
...getPackagesDirRelativePaths(plugin, files)
],
packagesDir.path),
]));
});
test('skips Java if --no-java flag is provided', () async {
const List<String> files = <String>[
'android/src/main/java/io/flutter/plugins/a_plugin/a.java',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
await runCapturingPrint(runner, <String>['format', '--no-java']);
expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[]));
});
test('formats c-ish files', () async {
const List<String> files = <String>[
'ios/Classes/Foo.h',
'ios/Classes/Foo.m',
'linux/foo_plugin.cc',
'macos/Classes/Foo.h',
'macos/Classes/Foo.mm',
'windows/foo_plugin.cpp',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(runner, <String>['format']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall('clang-format', <String>['--version'], null),
ProcessCall(
'clang-format',
<String>[
'-i',
'--style=file',
...getPackagesDirRelativePaths(plugin, files)
],
packagesDir.path),
]));
});
test('fails with a clear message if clang-format is not in the path',
() async {
const List<String> files = <String>[
'linux/foo_plugin.cc',
'macos/Classes/Foo.h',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['clang-format'] =
<FakeProcessInfo>[FakeProcessInfo(MockProcess(exitCode: 1))];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['format'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Unable to run "clang-format". Make sure that it is in your '
'path, or provide a full path with --clang-format-path.'),
]));
});
test('falls back to working clang-format in the path', () async {
const List<String> files = <String>[
'linux/foo_plugin.cc',
'macos/Classes/Foo.h',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
processRunner.mockProcessesForExecutable['clang-format'] =
<FakeProcessInfo>[FakeProcessInfo(MockProcess(exitCode: 1))];
processRunner.mockProcessesForExecutable['which'] = <FakeProcessInfo>[
FakeProcessInfo(
MockProcess(
stdout:
'/usr/local/bin/clang-format\n/path/to/working-clang-format'),
<String>['-a', 'clang-format'])
];
processRunner.mockProcessesForExecutable['/usr/local/bin/clang-format'] =
<FakeProcessInfo>[FakeProcessInfo(MockProcess(exitCode: 1))];
await runCapturingPrint(runner, <String>['format']);
expect(
processRunner.recordedCalls,
containsAll(<ProcessCall>[
const ProcessCall(
'/path/to/working-clang-format', <String>['--version'], null),
ProcessCall(
'/path/to/working-clang-format',
<String>[
'-i',
'--style=file',
...getPackagesDirRelativePaths(plugin, files)
],
packagesDir.path),
]));
});
test('honors --clang-format-path flag', () async {
const List<String> files = <String>[
'windows/foo_plugin.cpp',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(runner,
<String>['format', '--clang-format-path=/path/to/clang-format']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall(
'/path/to/clang-format', <String>['--version'], null),
ProcessCall(
'/path/to/clang-format',
<String>[
'-i',
'--style=file',
...getPackagesDirRelativePaths(plugin, files)
],
packagesDir.path),
]));
});
test('fails if clang-format fails', () async {
const List<String> files = <String>[
'linux/foo_plugin.cc',
'macos/Classes/Foo.h',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['clang-format'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(),
<String>['--version']), // check for working clang-format
FakeProcessInfo(MockProcess(exitCode: 1), <String>['-i']), // format
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['format'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Failed to format C, C++, and Objective-C files: exit code 1.'),
]));
});
test('skips clang-format if --no-clang-format flag is provided', () async {
const List<String> files = <String>[
'linux/foo_plugin.cc',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
await runCapturingPrint(runner, <String>['format', '--no-clang-format']);
expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[]));
});
group('kotlin-format', () {
test('formats .kt files', () async {
const List<String> files = <String>[
'android/src/main/kotlin/io/flutter/plugins/a_plugin/a.kt',
'android/src/main/kotlin/io/flutter/plugins/a_plugin/b.kt',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(runner, <String>['format']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall('java', <String>['-version'], null),
ProcessCall(
'java',
<String>[
'-jar',
kotlinFormatPath,
...getPackagesDirRelativePaths(plugin, files)
],
packagesDir.path),
]));
});
test('fails if Kotlin formatter fails', () async {
const List<String> files = <String>[
'android/src/main/kotlin/io/flutter/plugins/a_plugin/a.kt',
'android/src/main/kotlin/io/flutter/plugins/a_plugin/b.kt',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['java'] = <FakeProcessInfo>[
FakeProcessInfo(
MockProcess(), <String>['-version']), // check for working java
FakeProcessInfo(MockProcess(exitCode: 1), <String>['-jar']), // format
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['format'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Failed to format Kotlin files: exit code 1.'),
]));
});
test('skips Kotlin if --no-kotlin flag is provided', () async {
const List<String> files = <String>[
'android/src/main/kotlin/io/flutter/plugins/a_plugin/a.kt',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
await runCapturingPrint(runner, <String>['format', '--no-kotlin']);
expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[]));
});
});
group('swift-format', () {
test('formats Swift if --swift-format flag is provided', () async {
const List<String> files = <String>[
'macos/foo.swift',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(runner, <String>[
'format',
'--swift',
'--swift-format-path=/path/to/swift-format'
]);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall(
'/path/to/swift-format',
<String>['--version'],
null,
),
ProcessCall(
'/path/to/swift-format',
<String>['-i', ...getPackagesDirRelativePaths(plugin, files)],
packagesDir.path,
),
ProcessCall(
'/path/to/swift-format',
<String>[
'lint',
'--parallel',
'--strict',
...getPackagesDirRelativePaths(plugin, files),
],
packagesDir.path,
),
]));
});
test('skips Swift if --no-swift flag is provided', () async {
const List<String> files = <String>[
'macos/foo.swift',
];
createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(runner, <String>['format', '--no-swift']);
expect(processRunner.recordedCalls, orderedEquals(<ProcessCall>[]));
});
test('fails with a clear message if swift-format is not in the path',
() async {
const List<String> files = <String>[
'macos/foo.swift',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['swift-format'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['--version']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['format', '--swift'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Unable to run "swift-format". Make sure that it is in your path, or '
'provide a full path with --swift-format-path.'),
]));
});
test('fails if swift-format lint fails', () async {
const List<String> files = <String>[
'macos/foo.swift',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['swift-format'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(),
<String>['--version']), // check for working swift-format
FakeProcessInfo(MockProcess(), <String>['-i']),
FakeProcessInfo(MockProcess(exitCode: 1), <String>[
'lint',
'--parallel',
'--strict',
]),
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'format',
'--swift',
'--swift-format-path=swift-format'
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Failed to lint Swift files: exit code 1.'),
]));
});
test('fails if swift-format fails', () async {
const List<String> files = <String>[
'macos/foo.swift',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['swift-format'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(),
<String>['--version']), // check for working swift-format
FakeProcessInfo(MockProcess(exitCode: 1), <String>['-i']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'format',
'--swift',
'--swift-format-path=swift-format'
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Failed to format Swift files: exit code 1.'),
]));
});
});
test('skips known non-repo files', () async {
const List<String> skipFiles = <String>[
'/example/build/SomeFramework.framework/Headers/SomeFramework.h',
'/example/Pods/APod.framework/Headers/APod.h',
'.dart_tool/internals/foo.cc',
'.dart_tool/internals/Bar.java',
'.dart_tool/internals/baz.dart',
];
const List<String> clangFiles = <String>['ios/Classes/Foo.h'];
const List<String> dartFiles = <String>['lib/a.dart'];
const List<String> javaFiles = <String>[
'android/src/main/java/io/flutter/plugins/a_plugin/a.java'
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: <String>[
...skipFiles,
// Include some files that should be formatted to validate that it's
// correctly filtering even when running the commands.
...clangFiles,
...dartFiles,
...javaFiles,
],
);
await runCapturingPrint(runner, <String>['format']);
expect(
processRunner.recordedCalls,
containsAll(<ProcessCall>[
ProcessCall(
'clang-format',
<String>[
'-i',
'--style=file',
...getPackagesDirRelativePaths(plugin, clangFiles)
],
packagesDir.path),
ProcessCall(
'dart',
<String>[
'format',
...getPackagesDirRelativePaths(plugin, dartFiles)
],
packagesDir.path),
ProcessCall(
'java',
<String>[
'-jar',
javaFormatPath,
'--replace',
...getPackagesDirRelativePaths(plugin, javaFiles)
],
packagesDir.path),
]));
});
test('skips GeneratedPluginRegistrant.swift', () async {
const String sourceFile = 'macos/Classes/Foo.swift';
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: <String>[
sourceFile,
'example/macos/Flutter/GeneratedPluginRegistrant.swift',
],
);
await runCapturingPrint(runner, <String>[
'format',
'--swift',
'--swift-format-path=/path/to/swift-format'
]);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall(
'/path/to/swift-format',
<String>['--version'],
null,
),
ProcessCall(
'/path/to/swift-format',
<String>[
'-i',
...getPackagesDirRelativePaths(plugin, <String>[sourceFile])
],
packagesDir.path,
),
ProcessCall(
'/path/to/swift-format',
<String>[
'lint',
'--parallel',
'--strict',
...getPackagesDirRelativePaths(plugin, <String>[sourceFile]),
],
packagesDir.path,
),
]));
});
test('fails if files are changed with --fail-on-change', () async {
const List<String> files = <String>[
'linux/foo_plugin.cc',
'macos/Classes/Foo.h',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
const String changedFilePath = 'packages/a_plugin/linux/foo_plugin.cc';
processRunner.mockProcessesForExecutable['git'] = <FakeProcessInfo>[
FakeProcessInfo(
MockProcess(stdout: changedFilePath), <String>['ls-files']),
];
Error? commandError;
final List<String> output =
await runCapturingPrint(runner, <String>['format', '--fail-on-change'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('These files are not formatted correctly'),
contains(changedFilePath),
// Ensure the error message links to instructions.
contains(
'https://github.com/flutter/packages/blob/main/script/tool/README.md#format-code'),
contains('patch -p1 <<DONE'),
]));
});
test('fails if git ls-files fails', () async {
const List<String> files = <String>[
'linux/foo_plugin.cc',
'macos/Classes/Foo.h',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['git'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['ls-files'])
];
Error? commandError;
final List<String> output =
await runCapturingPrint(runner, <String>['format', '--fail-on-change'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Unable to determine changed files.'),
]));
});
test('reports git diff failures', () async {
const List<String> files = <String>[
'linux/foo_plugin.cc',
'macos/Classes/Foo.h',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
const String changedFilePath = 'packages/a_plugin/linux/foo_plugin.cc';
processRunner.mockProcessesForExecutable['git'] = <FakeProcessInfo>[
FakeProcessInfo(
MockProcess(stdout: changedFilePath), <String>['ls-files']),
FakeProcessInfo(MockProcess(exitCode: 1), <String>['diff']),
];
Error? commandError;
final List<String> output =
await runCapturingPrint(runner, <String>['format', '--fail-on-change'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('These files are not formatted correctly'),
contains(changedFilePath),
contains('Unable to determine diff.'),
]));
});
test('Batches moderately long file lists on Windows', () async {
mockPlatform.isWindows = true;
const String pluginName = 'a_plugin';
// -1 since the command itself takes some length.
const int batchSize = (windowsCommandLineMax ~/ 100) - 1;
// Make the file list one file longer than would fit in the batch.
final List<String> batch1 =
get99CharacterPathExtraFiles(pluginName, batchSize + 1);
final String extraFile = batch1.removeLast();
createFakePlugin(
pluginName,
packagesDir,
extraFiles: <String>[...batch1, extraFile],
);
await runCapturingPrint(runner, <String>['format']);
// Ensure that it was batched...
expect(processRunner.recordedCalls.length, 2);
// ... and that the spillover into the second batch was only one file.
expect(
processRunner.recordedCalls,
contains(
ProcessCall(
'dart',
<String>[
'format',
'$pluginName\\$extraFile',
],
packagesDir.path),
));
});
// Validates that the Windows limit--which is much lower than the limit on
// other platforms--isn't being used on all platforms, as that would make
// formatting slower on Linux and macOS.
test('Does not batch moderately long file lists on non-Windows', () async {
const String pluginName = 'a_plugin';
// -1 since the command itself takes some length.
const int batchSize = (windowsCommandLineMax ~/ 100) - 1;
// Make the file list one file longer than would fit in a Windows batch.
final List<String> batch =
get99CharacterPathExtraFiles(pluginName, batchSize + 1);
createFakePlugin(
pluginName,
packagesDir,
extraFiles: batch,
);
await runCapturingPrint(runner, <String>['format']);
expect(processRunner.recordedCalls.length, 1);
});
test('Batches extremely long file lists on non-Windows', () async {
const String pluginName = 'a_plugin';
// -1 since the command itself takes some length.
const int batchSize = (nonWindowsCommandLineMax ~/ 100) - 1;
// Make the file list one file longer than would fit in the batch.
final List<String> batch1 =
get99CharacterPathExtraFiles(pluginName, batchSize + 1);
final String extraFile = batch1.removeLast();
createFakePlugin(
pluginName,
packagesDir,
extraFiles: <String>[...batch1, extraFile],
);
await runCapturingPrint(runner, <String>['format']);
// Ensure that it was batched...
expect(processRunner.recordedCalls.length, 2);
// ... and that the spillover into the second batch was only one file.
expect(
processRunner.recordedCalls,
contains(
ProcessCall(
'dart',
<String>[
'format',
'$pluginName/$extraFile',
],
packagesDir.path),
));
});
}
| packages/script/tool/test/format_command_test.dart/0 | {
"file_path": "packages/script/tool/test/format_command_test.dart",
"repo_id": "packages",
"token_count": 13357
} | 1,079 |
// 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 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/update_excerpts_command.dart';
import 'package:test/test.dart';
import 'common/package_command_test.mocks.dart';
import 'mocks.dart';
import 'util.dart';
void runAllTests(MockPlatform platform) {
late FileSystem fileSystem;
late Directory packagesDir;
late CommandRunner<void> runner;
setUp(() {
fileSystem = MemoryFileSystem(
style: platform.isWindows
? FileSystemStyle.windows
: FileSystemStyle.posix);
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
runner = CommandRunner<void>('', '')
..addCommand(UpdateExcerptsCommand(
packagesDir,
platform: platform,
processRunner: RecordingProcessRunner(),
gitDir: MockGitDir(),
));
});
Future<void> testInjection(
{required String before,
required String source,
required String after,
required String filename,
bool failOnChange = false}) async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync(before);
package.directory.childFile(filename).writeAsStringSync(source);
Object? errorObject;
final List<String> output = await runCapturingPrint(
runner,
<String>[
'update-excerpts',
if (failOnChange) '--fail-on-change',
],
errorHandler: (Object error) {
errorObject = error;
},
);
if (errorObject != null) {
fail('Failed: $errorObject\n\nOutput from excerpt command:\n$output');
}
expect(package.readmeFile.readAsStringSync(), after);
}
test('succeeds when nothing has changed', () async {
const String filename = 'main.dart';
const String readme = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
A B C
```
''';
const String source = '''
FAIL
// #docregion SomeSection
A B C
// #enddocregion SomeSection
FAIL
''';
await testInjection(
before: readme, source: source, after: readme, filename: filename);
});
test('fails if example injection fails', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync('''
Example:
<?code-excerpt "main.dart (UnknownSection)"?>
```dart
A B C
```
''');
package.directory.childFile('main.dart').writeAsStringSync('''
FAIL
// #docregion SomeSection
A B C
// #enddocregion SomeSection
FAIL
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['update-excerpts'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Injecting excerpts failed:'),
contains(
'main.dart: did not find a "// #docregion UnknownSection" pragma'),
]),
);
});
test('updates files', () async {
const String filename = 'main.dart';
const String before = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
X Y Z
```
''';
const String source = '''
FAIL
// #docregion SomeSection
A B C
// #enddocregion SomeSection
FAIL
''';
const String after = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
A B C
```
''';
await testInjection(
before: before, source: source, after: after, filename: filename);
});
test('fails if READMEs are changed with --fail-on-change', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync('''
Example:
<?code-excerpt "main.dart (SomeSection)"?>
```dart
X Y Z
```
''');
package.directory.childFile('main.dart').writeAsStringSync('''
FAIL
// #docregion SomeSection
A B C
// #enddocregion SomeSection
FAIL
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['update-excerpts', '--fail-on-change'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output.join('\n'),
contains('The following files have out of date excerpts:'),
);
});
test('does not fail if READMEs are not changed with --fail-on-change',
() async {
const String filename = 'main.dart';
const String readme = '''
Example:
<?code-excerpt "$filename (aa)"?>
```dart
A
```
<?code-excerpt "$filename (bb)"?>
```dart
B
```
''';
const String source = '''
// #docregion aa
A
// #enddocregion aa
// #docregion bb
B
// #enddocregion bb
''';
await testInjection(
before: readme,
source: source,
after: readme,
filename: filename,
failOnChange: true,
);
});
test('indents the plaster', () async {
const String filename = 'main.dart';
const String before = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
```
''';
const String source = '''
// #docregion SomeSection
A
// #enddocregion SomeSection
// #docregion SomeSection
B
// #enddocregion SomeSection
''';
const String after = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
A
// ···
B
```
''';
await testInjection(
before: before, source: source, after: after, filename: filename);
});
test('does not unindent blocks if plaster will not unindent', () async {
const String filename = 'main.dart';
const String before = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
```
''';
const String source = '''
// #docregion SomeSection
A
// #enddocregion SomeSection
// #docregion SomeSection
B
// #enddocregion SomeSection
''';
const String after = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
A
// ···
B
```
''';
await testInjection(
before: before, source: source, after: after, filename: filename);
});
test('unindents blocks', () async {
const String filename = 'main.dart';
const String before = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
```
''';
const String source = '''
// #docregion SomeSection
A
// #enddocregion SomeSection
// #docregion SomeSection
B
// #enddocregion SomeSection
''';
const String after = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
A
// ···
B
```
''';
await testInjection(
before: before, source: source, after: after, filename: filename);
});
test('unindents blocks and plaster', () async {
const String filename = 'main.dart';
const String before = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
```
''';
const String source = '''
// #docregion SomeSection
A
// #enddocregion SomeSection
// #docregion SomeSection
B
// #enddocregion SomeSection
''';
const String after = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```dart
A
// ···
B
```
''';
await testInjection(
before: before, source: source, after: after, filename: filename);
});
test('relative path bases', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync('''
<?code-excerpt "main.dart (a)"?>
```dart
```
<?code-excerpt "test/main.dart (a)"?>
```dart
```
<?code-excerpt "test/test/main.dart (a)"?>
```dart
```
<?code-excerpt path-base="test"?>
<?code-excerpt "main.dart (a)"?>
```dart
```
<?code-excerpt "../main.dart (a)"?>
```dart
```
<?code-excerpt "test/main.dart (a)"?>
```dart
```
<?code-excerpt path-base="/packages/a_package"?>
<?code-excerpt "main.dart (a)"?>
```dart
```
<?code-excerpt "test/main.dart (a)"?>
```dart
```
''');
package.directory.childFile('main.dart').writeAsStringSync('''
// #docregion a
X
// #enddocregion a
''');
package.directory.childDirectory('test').createSync();
package.directory
.childDirectory('test')
.childFile('main.dart')
.writeAsStringSync('''
// #docregion a
Y
// #enddocregion a
''');
package.directory
.childDirectory('test')
.childDirectory('test')
.createSync();
package.directory
.childDirectory('test')
.childDirectory('test')
.childFile('main.dart')
.writeAsStringSync('''
// #docregion a
Z
// #enddocregion a
''');
await runCapturingPrint(runner, <String>['update-excerpts']);
expect(package.readmeFile.readAsStringSync(), '''
<?code-excerpt "main.dart (a)"?>
```dart
X
```
<?code-excerpt "test/main.dart (a)"?>
```dart
Y
```
<?code-excerpt "test/test/main.dart (a)"?>
```dart
Z
```
<?code-excerpt path-base="test"?>
<?code-excerpt "main.dart (a)"?>
```dart
Y
```
<?code-excerpt "../main.dart (a)"?>
```dart
X
```
<?code-excerpt "test/main.dart (a)"?>
```dart
Z
```
<?code-excerpt path-base="/packages/a_package"?>
<?code-excerpt "main.dart (a)"?>
```dart
X
```
<?code-excerpt "test/main.dart (a)"?>
```dart
Y
```
''');
});
test('logs snippets checked', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.readmeFile.writeAsStringSync('''
Example:
<?code-excerpt "main.dart (SomeSection)"?>
```dart
A B C
```
''');
package.directory.childFile('main.dart').writeAsStringSync('''
FAIL
// #docregion SomeSection
A B C
// #enddocregion SomeSection
FAIL
''');
final List<String> output =
await runCapturingPrint(runner, <String>['update-excerpts']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checked 1 snippet(s) in README.md.'),
]),
);
});
group('File type tests', () {
const List<Map<String, String>> testCases = <Map<String, String>>[
<String, String>{'filename': 'main.cc', 'language': 'c++'},
<String, String>{'filename': 'main.cpp', 'language': 'c++'},
<String, String>{'filename': 'main.dart'},
<String, String>{'filename': 'main.js'},
<String, String>{'filename': 'main.kt', 'language': 'kotlin'},
<String, String>{'filename': 'main.java'},
<String, String>{'filename': 'main.gradle', 'language': 'groovy'},
<String, String>{'filename': 'main.m', 'language': 'objectivec'},
<String, String>{'filename': 'main.swift'},
<String, String>{
'filename': 'main.css',
'prefix': '/* ',
'suffix': ' */'
},
<String, String>{
'filename': 'main.html',
'prefix': '<!--',
'suffix': '-->'
},
<String, String>{
'filename': 'main.xml',
'prefix': '<!--',
'suffix': '-->'
},
<String, String>{'filename': 'main.yaml', 'prefix': '# '},
<String, String>{'filename': 'main.sh', 'prefix': '# '},
<String, String>{'filename': 'main', 'language': 'txt', 'prefix': ''},
];
void runTest(Map<String, String> testCase) {
test('updates ${testCase['filename']} files', () async {
final String filename = testCase['filename']!;
final String language = testCase['language'] ?? filename.split('.')[1];
final String prefix = testCase['prefix'] ?? '// ';
final String suffix = testCase['suffix'] ?? '';
final String before = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```$language
X Y Z
```
''';
final String source = '''
FAIL
$prefix#docregion SomeSection$suffix
A B C
$prefix#enddocregion SomeSection$suffix
FAIL
''';
final String after = '''
Example:
<?code-excerpt "$filename (SomeSection)"?>
```$language
A B C
```
''';
await testInjection(
before: before, source: source, after: after, filename: filename);
});
}
testCases.forEach(runTest);
});
}
void main() {
runAllTests(MockPlatform());
runAllTests(MockPlatform(isWindows: true));
}
| packages/script/tool/test/update_excerpts_command_test.dart/0 | {
"file_path": "packages/script/tool/test/update_excerpts_command_test.dart",
"repo_id": "packages",
"token_count": 4784
} | 1,080 |
{
"development": {
"app_url": "https://io-photobooth.web.app"
}
} | photobooth/functions/.runtimeconfig.json/0 | {
"file_path": "photobooth/functions/.runtimeconfig.json",
"repo_id": "photobooth",
"token_count": 34
} | 1,081 |
import 'package:authentication_repository/authentication_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/landing/landing.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:photos_repository/photos_repository.dart';
class App extends StatelessWidget {
const App({
required this.authenticationRepository,
required this.photosRepository,
super.key,
});
final AuthenticationRepository authenticationRepository;
final PhotosRepository photosRepository;
@override
Widget build(BuildContext context) {
return MultiRepositoryProvider(
providers: [
RepositoryProvider.value(value: authenticationRepository),
RepositoryProvider.value(value: photosRepository),
],
child: AnimatedFadeIn(
child: ResponsiveLayoutBuilder(
small: (_, __) => _App(theme: PhotoboothTheme.small),
medium: (_, __) => _App(theme: PhotoboothTheme.medium),
large: (_, __) => _App(theme: PhotoboothTheme.standard),
),
),
);
}
}
class _App extends StatelessWidget {
const _App({required this.theme});
final ThemeData theme;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'I/O Photo Booth',
theme: theme,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: const LandingPage(),
);
}
}
| photobooth/lib/app/app.dart/0 | {
"file_path": "photobooth/lib/app/app.dart",
"repo_id": "photobooth",
"token_count": 616
} | 1,082 |
{
"@@locale": "te",
"landingPageHeading": "గూగుల్ I∕O ఫోటో బూత్ కి స్వాగతం ",
"landingPageSubheading": "ఒక చిత్రం తీస్కొని సమాజం తో పంచుకోండి!",
"landingPageTakePhotoButtonText": "మొదలు పెట్టండి",
"footerMadeWithText": "తయారు చెయ్యబడింది ",
"footerMadeWithFlutterLinkText": "ఫ్లట్టర్ ",
"footerMadeWithFirebaseLinkText": "ఫైర్బేస్ తో ",
"footerGoogleIOLinkText": "గూగుల్ I∕O",
"footerCodelabLinkText": "కోడ్ ల్యాబ్ ",
"footerHowItsMadeLinkText": "ఎలా తయారు చేయబడింది",
"footerTermsOfServiceLinkText": "నిబంధనలు మరియు సేవలు",
"footerPrivacyPolicyLinkText": "ప్రైవసి పాలసీ",
"sharePageHeading": "మీ చిత్రం సమాజం తో పంచుకోండి!",
"sharePageSubheading": "మీ చిత్రం సమాజం తో పంచుకోండి!",
"sharePageSuccessHeading": "చిత్రం పంచబడినది!",
"sharePageSuccessSubheading": "ఫ్లట్టర్ వెబ్ యాప్ను ఉపయోగించినందుకు కృతఙ్ఞతలు ! మీ చిత్రం ఈ ఏకైక యు.ఆర్.ఎల్ వద్ద ప్రచురింపబడినది",
"sharePageSuccessCaption1": "మీ చిత్రం ఈ యు.ఆర్.ఎల్ వద్ద నుండి 30 రోజుల్లో స్వయంగా చెరపబడుతుంది. త్వరగా చెరపవలెను అంటే సంప్రదించండి ",
"sharePageSuccessCaption2": "[email protected]",
"sharePageSuccessCaption3": " మీ ఏకైక యు.ఆర్.ఎల్ ని చేర్చడం మరవకండి.",
"sharePageRetakeButtonText": "కొత్త చిత్రం తీయుము",
"sharePageShareButtonText": "పంచుము",
"sharePageDownloadButtonText": "డౌన్లోడ్",
"socialMediaShareLinkText": "ఇప్పుడే #IOPhotoBooth వద్ద ఒక సెల్ఫీ తీసుకున్నా. #GoogleIO లో కలుద్దాం!",
"previewPageCameraNotAllowedText": "మీరు అనుమతి తిరస్కరించారు. అప్ ని ఉపయోగించాలి అంటే అనుమతి ఇవ్వండి",
"sharePageSocialMediaShareClarification1": "సోషల్ మీడియాపై మీ చిత్రాన్ని పంచుకోవాలి అంటే , మీ చిత్రం ఒక ఏకైక యు.ఆర్.ఎల్ వద్ద నుండి 30 రోజులు ఉండును, ఆ తర్వాత స్వయంగా చెరపబడుతుంది. త్వరగా చెరపవలెను అంటే సంప్రదించండి ",
"sharePageSocialMediaShareClarification2": "[email protected]",
"sharePageSocialMediaShareClarification3": " మీ ఏకైక యు.ఆర్.ఎల్ ని చేర్చడం మరవకండి.",
"sharePageCopyLinkButton": "కాపీ",
"sharePageLinkedCopiedButton": "కాపీ అయ్యింది",
"sharePageErrorHeading": "మీ చిత్రాన్ని ప్రాసెస్ చెయ్యడంలో మాకు ఇబ్బందులు వస్తున్నాయి",
"sharePageErrorSubheading": "మీ డివైస్ మరియు బ్రౌసర్ తాజాగా ఉన్నట్టు చూసుకోండి. ఈ ఇబ్బంది కొనసాగితే [email protected] ను సంప్రదించండి.",
"shareDialogHeading": "మీ చిత్రాన్ని పంచుకోండి!",
"shareDialogSubheading": "ఈవెంట్ జరుగుతున్నప్పుడు మీ చిత్రాన్ని పంచుకొని మరియు మీ ప్రొఫైల్ చిత్రాన్ని మార్చుకొని, మీరు గూగుల్ I∕O వద్ద ఉన్నట్టు అందరికి తెలియచేయండి!",
"shareErrorDialogHeading": "అయ్యాయో!",
"shareErrorDialogTryAgainButton": "వెనుకకు వెళ్ళండి",
"shareErrorDialogSubheading": "ఎదో తప్పు జరిగినందువల్ల మీ చిత్రాన్ని లోడ్ చెయ్యలేకపోతున్నాం.",
"sharePageProgressOverlayHeading": "మీ చిత్రాన్ని ఫ్లట్టర్తో పిక్సెల్ పర్ఫెక్ట్ చేస్తున్నాం! ",
"sharePageProgressOverlaySubheading": "ఈ ట్యాబ్ను మూయవద్దు.",
"shareDialogTwitterButtonText": "ట్విట్టర్",
"shareDialogFacebookButtonText": "ఫేస్బుక్",
"photoBoothCameraAccessDeniedHeadline": "కెమెరా అనుమతి తిరస్కరించబడినది",
"photoBoothCameraAccessDeniedSubheadline": "చిత్రాన్ని తీయాలంటే బ్రౌసర్కి కెమెరా అనుమతి ఇవ్వవలెను.",
"photoBoothCameraNotFoundHeadline": "కెమెరా ని కనిబెట్టలేకపోతున్నాము",
"photoBoothCameraNotFoundSubheadline1": "మీ డెవిస్లో కెమెరా లేనట్టు లేక పనిచేయడం లేనట్లు ఉంది.",
"photoBoothCameraNotFoundSubheadline2": "చిత్రం తీయాలంటే I∕O ఫోటో బూత్ను కెమెరా ఉన్న డివైస్ నుండి సందర్శించండి",
"photoBoothCameraErrorHeadline": "అయ్యాయో! ఎదో పొరపాటు జరిగింది.",
"photoBoothCameraErrorSubheadline1": "మీ బ్రౌజర్ను రిఫ్రెష్ చేసి మల్లి ప్రయత్నించండి.",
"photoBoothCameraErrorSubheadline2": "ఈ ఇబ్బంది కొనసాగినట్లైతే [email protected] ను సంప్రదించండి.",
"photoBoothCameraNotSupportedHeadline": "అయ్యాయో! ఎదో పొరపాటు జరిగింది.",
"photoBoothCameraNotSupportedSubheadline": "మీ డివైస్ మరియు బ్రౌసర్ తాజాగా ఉన్నట్టు చూసుకోండి.",
"stickersDrawerTitle": "ప్రాప్స్ ను జోడించండి",
"openStickersTooltip": "ప్రాప్స్ ను జోడించండి",
"retakeButtonTooltip": "మళ్ళీ తీయండి",
"clearStickersButtonTooltip": "ప్రాప్స్ ను తీసేయండి",
"charactersCaptionText": "స్నేహితులను కలపండి",
"sharePageLearnMoreAboutTextPart1": "ఇంకా తెలుసుకోండి ",
"sharePageLearnMoreAboutTextPart2": " మరియు ",
"sharePageLearnMoreAboutTextPart3": " లేదా నేరుగా దూకండి ",
"sharePageLearnMoreAboutTextPart4": "ఓపెన్ సోర్స్ కోడ్",
"goToGoogleIOButtonText": "గూగుల్ I∕O కి వెళ్ళండి",
"clearStickersDialogHeading": "అన్ని ప్రాప్స్ ను తొలగించాలా?",
"clearStickersDialogSubheading": "స్క్రీన్ పైనుండి అన్ని ప్రాప్స్ ను తొలగించాలి అనుకుంటున్నారా?",
"clearStickersDialogCancelButtonText": "వద్దు,వెనుకకు తీసుకెళ్లండి",
"clearStickersDialogConfirmButtonText": "అవును,తొలగించండి",
"propsReminderText": "కొన్ని ప్రాప్స్ ను జోడించండి",
"stickersNextConfirmationHeading": "చివరి చిత్రం చూడటానికి సిద్ధంగా ఉన్నారా?",
"stickersNextConfirmationSubheading": "ఈ స్క్రీన్ ను విడిస్తే మళ్ళీ ఏ రకమైన మార్పులు చెయ్యలేరు",
"stickersNextConfirmationCancelButtonText": "లేదు, నేను ఇంకా తయారుచేస్తున్నాను",
"stickersNextConfirmationConfirmButtonText": "అవును, చూపించండి",
"stickersRetakeConfirmationHeading": "మీరు ఖచ్చితంగా ఉన్నారా ?",
"stickersRetakeConfirmationSubheading": "చిత్రాన్ని మళ్ళీ తీస్తే మీరు జోడించిన ప్రాప్స్ పోతాయి",
"stickersRetakeConfirmationCancelButtonText": "వద్దు, ఇక్కడే ఉండండి",
"stickersRetakeConfirmationConfirmButtonText": "అవును, చిత్రం మళ్ళీ తీయండి",
"shareRetakeConfirmationHeading": "కొత్త చిత్రం తీయటానికి సిద్ధంగా ఉన్నారా?",
"shareRetakeConfirmationSubheading": "ముందు దీనిని డౌన్లోడ్ లేక పంచుకోవడం గుర్తుంచుకోండి",
"shareRetakeConfirmationCancelButtonText": "వద్దు, ఇక్కడే ఉండండి",
"shareRetakeConfirmationConfirmButtonText": "అవును, చిత్రం మళ్ళీ తీయండి",
"shutterButtonLabelText": "ఫోటో తీయండి",
"stickersNextButtonLabelText": "చివరి ఫోటో తయారుచేయండి",
"dashButtonLabelText": "డ్యాష్ మిత్రుడిని కలపండి",
"sparkyButtonLabelText": "స్పార్కి మిత్రుడిని కలపండి",
"dinoButtonLabelText": "డైనో మిత్రుడిని కలపండి",
"androidButtonLabelText": "ఆండ్రాయిడ్ జెట్ప్యాక్ మిత్రుడిని కలపండి",
"addStickersButtonLabelText": "ప్రాప్స్ జోడించండి",
"retakePhotoButtonLabelText": "చిత్రాన్ని మళ్ళీ తీయండి",
"clearAllStickersButtonLabelText": "అన్నీ ప్రాప్స్ ను తొలగించండి"
} | photobooth/lib/l10n/arb/app_te.arb/0 | {
"file_path": "photobooth/lib/l10n/arb/app_te.arb",
"repo_id": "photobooth",
"token_count": 8815
} | 1,083 |
part of 'photobooth_bloc.dart';
abstract class PhotoboothEvent extends Equatable {
const PhotoboothEvent();
@override
List<Object> get props => [];
}
class PhotoCaptured extends PhotoboothEvent {
const PhotoCaptured({required this.aspectRatio, required this.image});
final double aspectRatio;
final CameraImage image;
@override
List<Object> get props => [aspectRatio, image];
}
class PhotoCharacterToggled extends PhotoboothEvent {
const PhotoCharacterToggled({required this.character});
final Asset character;
@override
List<Object> get props => [character];
}
class PhotoCharacterDragged extends PhotoboothEvent {
const PhotoCharacterDragged({required this.character, required this.update});
final PhotoAsset character;
final DragUpdate update;
@override
List<Object> get props => [character, update];
}
class PhotoStickerTapped extends PhotoboothEvent {
const PhotoStickerTapped({required this.sticker});
final Asset sticker;
@override
List<Object> get props => [sticker];
}
class PhotoStickerDragged extends PhotoboothEvent {
const PhotoStickerDragged({required this.sticker, required this.update});
final PhotoAsset sticker;
final DragUpdate update;
@override
List<Object> get props => [sticker, update];
}
class PhotoClearStickersTapped extends PhotoboothEvent {
const PhotoClearStickersTapped();
}
class PhotoClearAllTapped extends PhotoboothEvent {
const PhotoClearAllTapped();
}
class PhotoDeleteSelectedStickerTapped extends PhotoboothEvent {
const PhotoDeleteSelectedStickerTapped();
}
class PhotoTapped extends PhotoboothEvent {
const PhotoTapped();
}
| photobooth/lib/photobooth/bloc/photobooth_event.dart/0 | {
"file_path": "photobooth/lib/photobooth/bloc/photobooth_event.dart",
"repo_id": "photobooth",
"token_count": 471
} | 1,084 |
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:just_audio/just_audio.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
const _shutterCountdownDuration = Duration(seconds: 3);
AudioPlayer _getAudioPlayer() => AudioPlayer();
class ShutterButton extends StatefulWidget {
const ShutterButton({
required this.onCountdownComplete,
super.key,
ValueGetter<AudioPlayer>? audioPlayer,
}) : _audioPlayer = audioPlayer ?? _getAudioPlayer;
final VoidCallback onCountdownComplete;
final ValueGetter<AudioPlayer> _audioPlayer;
@override
State<ShutterButton> createState() => _ShutterButtonState();
}
class _ShutterButtonState extends State<ShutterButton>
with TickerProviderStateMixin {
late final AnimationController controller;
late final AudioPlayer audioPlayer;
void _onAnimationStatusChanged(AnimationStatus status) {
if (status == AnimationStatus.dismissed) {
widget.onCountdownComplete();
}
}
@override
void initState() {
super.initState();
audioPlayer = widget._audioPlayer()..setAsset('assets/audio/camera.mp3');
controller = AnimationController(
vsync: this,
duration: _shutterCountdownDuration,
)..addStatusListener(_onAnimationStatusChanged);
unawaited(audioPlayer.play());
audioPlayer.playerStateStream.listen((event) {
if (event.processingState == ProcessingState.ready) {
audioPlayer.pause();
}
});
}
@override
void dispose() {
controller
..removeStatusListener(_onAnimationStatusChanged)
..dispose();
audioPlayer.dispose();
super.dispose();
}
Future<void> _onShutterPressed() async {
await audioPlayer.seek(null);
unawaited(audioPlayer.play());
unawaited(controller.reverse(from: 1));
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (context, child) {
return controller.isAnimating
? CountdownTimer(controller: controller)
: CameraButton(onPressed: _onShutterPressed);
},
);
}
}
class CountdownTimer extends StatelessWidget {
const CountdownTimer({required this.controller, super.key});
final AnimationController controller;
@override
Widget build(BuildContext context) {
final seconds =
(_shutterCountdownDuration.inSeconds * controller.value).ceil();
final theme = Theme.of(context);
return Container(
height: 70,
width: 70,
margin: const EdgeInsets.only(bottom: 15),
child: Stack(
children: [
Align(
child: Text(
'$seconds',
style: theme.textTheme.displayLarge?.copyWith(
color: PhotoboothColors.white,
fontWeight: FontWeight.w500,
),
),
),
Positioned.fill(
child: CustomPaint(
painter: TimerPainter(animation: controller, countdown: seconds),
),
)
],
),
);
}
}
class CameraButton extends StatelessWidget {
const CameraButton({required this.onPressed, super.key});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Semantics(
focusable: true,
button: true,
label: l10n.shutterButtonLabelText,
child: Material(
clipBehavior: Clip.hardEdge,
shape: const CircleBorder(),
color: PhotoboothColors.transparent,
child: InkWell(
onTap: onPressed,
child: Image.asset(
'assets/icons/camera_button_icon.png',
height: 100,
width: 100,
),
),
),
);
}
}
class TimerPainter extends CustomPainter {
const TimerPainter({
required this.animation,
required this.countdown,
}) : super(repaint: animation);
final Animation<double> animation;
final int countdown;
@visibleForTesting
Color calculateColor() {
if (countdown == 3) return PhotoboothColors.blue;
if (countdown == 2) return PhotoboothColors.orange;
return PhotoboothColors.green;
}
@override
void paint(Canvas canvas, Size size) {
final progressColor = calculateColor();
final progress = ((1 - animation.value) * (2 * math.pi) * 3) -
((3 - countdown) * (2 * math.pi));
final paint = Paint()
..color = progressColor
..strokeWidth = 5.0
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke;
canvas.drawCircle(size.center(Offset.zero), size.width / 2.0, paint);
paint.color = PhotoboothColors.white;
canvas.drawArc(Offset.zero & size, math.pi * 1.5, progress, false, paint);
}
@override
bool shouldRepaint(TimerPainter oldDelegate) => false;
}
| photobooth/lib/photobooth/widgets/shutter_button.dart/0 | {
"file_path": "photobooth/lib/photobooth/widgets/shutter_button.dart",
"repo_id": "photobooth",
"token_count": 1881
} | 1,085 |
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class ShareBackground extends StatelessWidget {
const ShareBackground({super.key});
@override
Widget build(BuildContext context) {
return Stack(
children: [
SizedBox.expand(
child: Image.asset(
'assets/backgrounds/photobooth_background.jpg',
repeat: ImageRepeat.repeat,
filterQuality: FilterQuality.high,
),
),
Container(
width: double.infinity,
height: double.infinity,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
PhotoboothColors.transparent,
PhotoboothColors.black54,
],
),
),
),
ResponsiveLayoutBuilder(
large: (_, __) => Align(
alignment: Alignment.bottomLeft,
child: Image.asset(
'assets/backgrounds/yellow_bar.png',
filterQuality: FilterQuality.high,
),
),
small: (_, __) => const SizedBox(),
),
ResponsiveLayoutBuilder(
large: (_, __) => Align(
alignment: Alignment.topRight,
child: Image.asset(
'assets/backgrounds/circle_object.png',
filterQuality: FilterQuality.high,
),
),
small: (_, __) => const SizedBox(),
),
],
);
}
}
| photobooth/lib/share/widgets/share_background.dart/0 | {
"file_path": "photobooth/lib/share/widgets/share_background.dart",
"repo_id": "photobooth",
"token_count": 807
} | 1,086 |
part of 'stickers_bloc.dart';
class StickersState extends Equatable {
const StickersState({
this.isDrawerActive = false,
this.shouldDisplayPropsReminder = true,
this.tabIndex = 0,
});
final bool isDrawerActive;
final bool shouldDisplayPropsReminder;
final int tabIndex;
@override
List<Object> get props => [
isDrawerActive,
shouldDisplayPropsReminder,
tabIndex,
];
StickersState copyWith({
bool? isDrawerActive,
bool? shouldDisplayPropsReminder,
int? tabIndex,
}) {
return StickersState(
isDrawerActive: isDrawerActive ?? this.isDrawerActive,
shouldDisplayPropsReminder:
shouldDisplayPropsReminder ?? this.shouldDisplayPropsReminder,
tabIndex: tabIndex ?? this.tabIndex,
);
}
}
| photobooth/lib/stickers/bloc/stickers_state.dart/0 | {
"file_path": "photobooth/lib/stickers/bloc/stickers_state.dart",
"repo_id": "photobooth",
"token_count": 303
} | 1,087 |
/// A Flutter package which adds analytics support.
library analytics;
export 'src/analytics_io.dart' if (dart.library.html) 'src/analytics_web.dart';
| photobooth/packages/analytics/lib/analytics.dart/0 | {
"file_path": "photobooth/packages/analytics/lib/analytics.dart",
"repo_id": "photobooth",
"token_count": 49
} | 1,088 |
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_platform_interface/src/method_channel/method_channel_camera.dart';
import 'package:flutter/widgets.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
abstract class CameraPlatform extends PlatformInterface {
/// Constructs a CameraPlatform.
CameraPlatform() : super(token: _token);
static final Object _token = Object();
static CameraPlatform _instance = MethodChannelCamera();
/// The default instance of [CameraPlatform] to use.
///
/// Defaults to [MethodChannelCamera].
static CameraPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own platform-specific
/// class that extends [CameraPlatform] when they register themselves.
static set instance(CameraPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
/// Initializes the platform interface and disposes all existing cameras.
///
/// This method is called when the plugin is first initialized
/// and on every full restart.
Future<void> init() {
throw UnimplementedError('init() has not been implemented.');
}
/// Clears one camera.
Future<void> dispose(int textureId) {
throw UnimplementedError('dispose() has not been implemented.');
}
/// Creates an instance of a camera and returns its textureId.
Future<int> create(CameraOptions options) {
throw UnimplementedError('create() has not been implemented.');
}
/// Starts the camera stream.
Future<void> play(int textureId) {
throw UnimplementedError('play() has not been implemented.');
}
/// Stops the camera stream.
Future<void> stop(int textureId) {
throw UnimplementedError('stop() has not been implemented.');
}
Widget buildView(int textureId) {
throw UnimplementedError('buildView() has not been implemented.');
}
Future<CameraImage> takePicture(int textureId) {
throw UnimplementedError('takePicture() has not been implemented.');
}
Future<List<MediaDeviceInfo>> getMediaDevices() {
throw UnimplementedError('getDevicesIds() has not been implemented.');
}
Future<String?> getDefaultDeviceId() {
throw UnimplementedError('getDefaultDeviceId() has not been implemented.');
}
}
| photobooth/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart/0 | {
"file_path": "photobooth/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart",
"repo_id": "photobooth",
"token_count": 652
} | 1,089 |
import 'dart:async';
import 'dart:html' as html;
import 'dart:js_util' as js_util;
final bool _supportsDecode = js_util.getProperty<dynamic>(
js_util.getProperty(
js_util.getProperty(html.window, 'Image'),
'prototype',
),
'decode',
) !=
null;
/// {@template html_image}
/// Dart wrapper around an [html.ImageElement] and the element's
/// width and height.
/// {@endtemplate}
class HtmlImage {
/// {@macro html_image}
const HtmlImage(this.imageElement, this.width, this.height);
/// The image element.
final html.ImageElement imageElement;
/// The width of the [imageElement].
final int width;
/// The height of the [imageElement].
final int height;
}
/// {@macro html_image_loader}
/// Loads an [HtmlImage] given the `src` of the image.
/// {@endtemplate}
class HtmlImageLoader {
/// {@macro html_image_loader}
const HtmlImageLoader(this.src);
/// The image `src`.
final String src;
/// {@macro html_image_loader}
Future<HtmlImage> loadImage() async {
final completer = Completer<HtmlImage>();
if (_supportsDecode) {
final imgElement = html.ImageElement()..src = src;
js_util.setProperty(imgElement, 'decoding', 'async');
unawaited(
imgElement.decode().then((dynamic _) {
var naturalWidth = imgElement.naturalWidth;
var naturalHeight = imgElement.naturalHeight;
// Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=700533.
if (naturalWidth == 0 && naturalHeight == 0) {
const kDefaultImageSizeFallback = 300;
naturalWidth = kDefaultImageSizeFallback;
naturalHeight = kDefaultImageSizeFallback;
}
final image = HtmlImage(
imgElement,
naturalWidth,
naturalHeight,
);
completer.complete(image);
}).catchError((dynamic e) {
// This code path is hit on Chrome 80.0.3987.16 when too many
// images are on the page (~1000).
// Fallback here is to load using onLoad instead.
_decodeUsingOnLoad(completer);
}),
);
} else {
_decodeUsingOnLoad(completer);
}
return completer.future;
}
void _decodeUsingOnLoad(Completer<HtmlImage> completer) {
StreamSubscription<html.Event>? loadSubscription;
late StreamSubscription<html.Event> errorSubscription;
final imgElement = html.ImageElement();
// If the browser doesn't support asynchronous decoding of an image,
// then use the `onload` event to decide when it's ready to paint to the
// DOM. Unfortunately, this will cause the image to be decoded synchronously
// on the main thread, and may cause dropped frames.
errorSubscription = imgElement.onError.listen((html.Event event) {
loadSubscription?.cancel();
errorSubscription.cancel();
completer.completeError(event);
});
loadSubscription = imgElement.onLoad.listen((html.Event event) {
loadSubscription!.cancel();
errorSubscription.cancel();
final image = HtmlImage(
imgElement,
imgElement.naturalWidth,
imgElement.naturalHeight,
);
completer.complete(image);
});
imgElement.src = src;
}
}
| photobooth/packages/image_compositor/lib/src/image_loader.dart/0 | {
"file_path": "photobooth/packages/image_compositor/lib/src/image_loader.dart",
"repo_id": "photobooth",
"token_count": 1262
} | 1,090 |
import 'package:flutter/widgets.dart';
import 'package:photobooth_ui/src/layout/layout.dart';
/// Signature for the individual builders (`small`, `large`, etc.).
typedef ResponsiveLayoutWidgetBuilder = Widget Function(BuildContext, Widget?);
/// {@template responsive_layout_builder}
/// A wrapper around [LayoutBuilder] which exposes builders for
/// various responsive breakpoints.
/// {@endtemplate}
class ResponsiveLayoutBuilder extends StatelessWidget {
/// {@macro responsive_layout_builder}
const ResponsiveLayoutBuilder({
required this.small,
required this.large,
this.medium,
this.xLarge,
this.child,
super.key,
});
/// [ResponsiveLayoutWidgetBuilder] for small layout.
final ResponsiveLayoutWidgetBuilder small;
/// [ResponsiveLayoutWidgetBuilder] for medium layout.
final ResponsiveLayoutWidgetBuilder? medium;
/// [ResponsiveLayoutWidgetBuilder] for large layout.
final ResponsiveLayoutWidgetBuilder large;
/// [ResponsiveLayoutWidgetBuilder] for xLarge layout.
final ResponsiveLayoutWidgetBuilder? xLarge;
/// Optional child widget which will be passed
/// to the `small`, `large` and `xLarge`
/// builders as a way to share/optimize shared layout.
final Widget? child;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth <= PhotoboothBreakpoints.small) {
return small(context, child);
}
if (constraints.maxWidth <= PhotoboothBreakpoints.medium) {
return (medium ?? large).call(context, child);
}
if (constraints.maxWidth <= PhotoboothBreakpoints.large) {
return large(context, child);
}
return (xLarge ?? large).call(context, child);
},
);
}
}
| photobooth/packages/photobooth_ui/lib/src/widgets/responsive_layout_builder.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/responsive_layout_builder.dart",
"repo_id": "photobooth",
"token_count": 587
} | 1,091 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
void main() {
group('AppAnimatedCrossFade', () {
testWidgets('renders both children', (tester) async {
await tester.pumpWidget(
AppAnimatedCrossFade(
firstChild: SizedBox(key: Key('first')),
secondChild: SizedBox(key: Key('second')),
crossFadeState: CrossFadeState.showFirst,
),
);
expect(find.byKey(Key('first')), findsOneWidget);
expect(find.byKey(Key('second')), findsOneWidget);
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/app_animated_cross_fade_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/widgets/app_animated_cross_fade_test.dart",
"repo_id": "photobooth",
"token_count": 274
} | 1,092 |
name: photos_repository
description: repository that manages the photo domain
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
firebase_core: ^2.4.1
firebase_storage: ^11.0.10
flutter:
sdk: flutter
image_compositor:
path: ../image_compositor
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
very_good_analysis: ^4.0.0+1
| photobooth/packages/photos_repository/pubspec.yaml/0 | {
"file_path": "photobooth/packages/photos_repository/pubspec.yaml",
"repo_id": "photobooth",
"token_count": 174
} | 1,093 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/external_links/external_links.dart';
import 'package:io_photobooth/footer/footer.dart';
import 'package:mocktail/mocktail.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../../helpers/helpers.dart';
class MockUrlLauncher extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
bool findTextAndTap(InlineSpan visitor, String text) {
if (visitor is TextSpan && visitor.text == text) {
(visitor.recognizer! as TapGestureRecognizer).onTap?.call();
return false;
}
return true;
}
bool tapTextSpan(RichText richText, String text) {
final isTapped = !richText.text.visitChildren(
(visitor) => findTextAndTap(visitor, text),
);
return isTapped;
}
void main() {
setUpAll(() {
registerFallbackValue(LaunchOptions());
});
group('FooterLink', () {
late UrlLauncherPlatform originalUrlLauncher;
setUp(() {
originalUrlLauncher = UrlLauncherPlatform.instance;
});
tearDown(() {
UrlLauncherPlatform.instance = originalUrlLauncher;
});
testWidgets('opens link when tapped', (tester) async {
final mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await tester.pumpApp(
FooterLink(
link: 'https://example.com',
text: 'Link',
),
);
await tester.tap(find.byType(FooterLink));
await tester.pumpAndSettle();
verify(() => mock.launchUrl('https://example.com', any())).called(1);
});
group('MadeWith', () {
late UrlLauncherPlatform mock;
setUp(() {
mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
});
testWidgets('opens the Flutter website when tapped', (tester) async {
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await tester.pumpApp(FooterMadeWithLink());
final flutterTextFinder = find.byWidgetPredicate(
(widget) => widget is RichText && tapTextSpan(widget, 'Flutter'),
);
await tester.tap(flutterTextFinder);
await tester.pumpAndSettle();
verify(() => mock.launchUrl(flutterDevExternalLink, any()));
});
testWidgets('opens the Firebase website when tapped', (tester) async {
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await tester.pumpApp(FooterMadeWithLink());
final flutterTextFinder = find.byWidgetPredicate(
(widget) => widget is RichText && tapTextSpan(widget, 'Firebase'),
);
await tester.tap(flutterTextFinder);
await tester.pumpAndSettle();
verify(() => mock.launchUrl(firebaseExternalLink, any()));
});
});
group('Google IO', () {
testWidgets('renders FooterLink with a proper link', (tester) async {
await tester.pumpApp(FooterGoogleIOLink());
final widget = tester.widget<FooterLink>(
find.byType(FooterLink),
);
expect(widget.link, equals(googleIOExternalLink));
});
});
group('Codelab', () {
testWidgets('renders FooterLink with a proper link', (tester) async {
await tester.pumpApp(FooterCodelabLink());
final widget = tester.widget<FooterLink>(
find.byType(FooterLink),
);
expect(
widget.link,
equals(
'https://firebase.google.com/codelabs/firebase-get-to-know-flutter#0',
),
);
});
});
group('How Its Made', () {
testWidgets('renders FooterLink with a proper link', (tester) async {
await tester.pumpApp(FooterHowItsMadeLink());
final widget = tester.widget<FooterLink>(
find.byType(FooterLink),
);
expect(
widget.link,
equals(
'https://medium.com/flutter/how-its-made-i-o-photo-booth-3b8355d35883',
),
);
});
});
group('Terms of Service', () {
testWidgets('renders FooterLink with a proper link', (tester) async {
await tester.pumpApp(FooterTermsOfServiceLink());
final widget = tester.widget<FooterLink>(
find.byType(FooterLink),
);
expect(
widget.link,
equals(
'https://policies.google.com/terms',
),
);
});
});
group('Privacy Policy', () {
testWidgets('renders FooterLink with a proper link', (tester) async {
await tester.pumpApp(FooterPrivacyPolicyLink());
final widget = tester.widget<FooterLink>(
find.byType(FooterLink),
);
expect(
widget.link,
equals(
'https://policies.google.com/privacy',
),
);
});
});
});
}
| photobooth/test/app/widgets/footer_link_test.dart/0 | {
"file_path": "photobooth/test/app/widgets/footer_link_test.dart",
"repo_id": "photobooth",
"token_count": 2277
} | 1,094 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/assets.g.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class FakePhotoboothEvent extends Fake implements PhotoboothEvent {}
class FakePhotoboothState extends Fake implements PhotoboothState {}
class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState>
implements PhotoboothBloc {}
void main() {
const width = 1;
const height = 1;
const data = '';
const image = CameraImage(width: width, height: height, data: data);
late PhotoboothBloc photoboothBloc;
group('CharactersLayer', () {
setUpAll(() {
registerFallbackValue(FakePhotoboothEvent());
registerFallbackValue(FakePhotoboothState());
});
setUp(() {
photoboothBloc = MockPhotoboothBloc();
});
testWidgets('renders Android character assert', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: const [PhotoAsset(id: '0', asset: Assets.android)],
image: image,
),
);
await tester.pumpApp(
CharactersLayer(),
photoboothBloc: photoboothBloc,
);
expect(
find.byKey(const Key('charactersLayer_android_positioned')),
findsOneWidget,
);
});
testWidgets('renders Dash character assert', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: const [PhotoAsset(id: '0', asset: Assets.dash)],
image: image,
),
);
await tester.pumpApp(
CharactersLayer(),
photoboothBloc: photoboothBloc,
);
expect(
find.byKey(const Key('charactersLayer_dash_positioned')),
findsOneWidget,
);
});
testWidgets('renders Sparky character assert', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: const [PhotoAsset(id: '0', asset: Assets.sparky)],
image: image,
),
);
await tester.pumpApp(
CharactersLayer(),
photoboothBloc: photoboothBloc,
);
expect(
find.byKey(const Key('charactersLayer_sparky_positioned')),
findsOneWidget,
);
});
});
}
| photobooth/test/photobooth/widgets/characters_layer_test.dart/0 | {
"file_path": "photobooth/test/photobooth/widgets/characters_layer_test.dart",
"repo_id": "photobooth",
"token_count": 1047
} | 1,095 |
// ignore_for_file: prefer_const_constructors
import 'dart:typed_data';
import 'package:cross_file/cross_file.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class MockXFile extends Mock implements XFile {}
void main() {
final bytes = Uint8List.fromList([]);
late ShareBloc shareBloc;
late XFile file;
setUpAll(() {
registerFallbackValue(FakeShareEvent());
registerFallbackValue(FakeShareState());
});
setUp(() {
shareBloc = MockShareBloc();
file = MockXFile();
when(() => shareBloc.state).thenReturn(ShareState());
});
group('ShareProgressOverlay', () {
testWidgets(
'displays loading overlay '
'when ShareBloc upload status is loading', (tester) async {
tester.setDisplaySize(const Size(1920, 1080));
when(() => shareBloc.state).thenReturn(
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.loading,
file: file,
bytes: bytes,
),
);
await tester.pumpApp(ShareProgressOverlay(), shareBloc: shareBloc);
expect(find.byKey(Key('shareProgressOverlay_loading')), findsOneWidget);
});
testWidgets(
'displays mobile loading overlay '
'when ShareBloc upload status is loading '
'and resolution is mobile', (tester) async {
tester.setDisplaySize(const Size(320, 800));
when(() => shareBloc.state).thenReturn(
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.loading,
file: file,
bytes: bytes,
),
);
await tester.pumpApp(ShareProgressOverlay(), shareBloc: shareBloc);
expect(find.byKey(Key('shareProgressOverlay_mobile')), findsOneWidget);
});
testWidgets(
'displays desktop loading overlay '
'when ShareBloc upload status is loading '
'and resolution is desktop', (tester) async {
tester.setDisplaySize(const Size(1920, 1080));
when(() => shareBloc.state).thenReturn(
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.loading,
file: file,
bytes: bytes,
),
);
await tester.pumpApp(ShareProgressOverlay(), shareBloc: shareBloc);
expect(find.byKey(Key('shareProgressOverlay_desktop')), findsOneWidget);
});
testWidgets(
'displays nothing '
'when ShareBloc state is not loading', (tester) async {
await tester.pumpApp(ShareProgressOverlay(), shareBloc: shareBloc);
expect(find.byKey(Key('shareProgressOverlay_nothing')), findsOneWidget);
});
});
}
| photobooth/test/share/widgets/share_progress_overlay_test.dart/0 | {
"file_path": "photobooth/test/share/widgets/share_progress_overlay_test.dart",
"repo_id": "photobooth",
"token_count": 1121
} | 1,096 |
{
"version": "0.2",
"enabled": true,
"language": "en",
"words": [
"animatronic",
"argb",
"audioplayers",
"backbox",
"bezier",
"contador",
"cupertino",
"dashbook",
"deserialization",
"dpad",
"endtemplate",
"firestore",
"gapless",
"genhtml",
"goldens",
"lcov",
"leaderboard",
"loadables",
"localizable",
"mixins",
"mocktail",
"mostrado",
"multiball",
"multiballs",
"occluder",
"página",
"pixelated",
"pixeloid",
"rects",
"rrect",
"serializable",
"sparky's",
"tappable",
"tappables",
"texto",
"theming",
"unawaited",
"unfocus",
"unlayered",
"vsync"
],
"ignorePaths": [
".github/workflows/**"
]
}
| pinball/.vscode/cspell.json/0 | {
"file_path": "pinball/.vscode/cspell.json",
"repo_id": "pinball",
"token_count": 576
} | 1,097 |
import 'package:flame/components.dart';
import 'package:pinball_flame/pinball_flame.dart';
class AnimatronicLoopingBehavior extends TimerComponent
with ParentIsA<SpriteAnimationComponent> {
AnimatronicLoopingBehavior({
required double animationCoolDown,
}) : super(period: animationCoolDown);
@override
Future<void> onLoad() async {
await super.onLoad();
parent.animation?.onComplete = () {
parent.animation?.reset();
parent.playing = false;
timer
..reset()
..start();
};
}
@override
void onTick() {
parent.playing = true;
}
}
| pinball/lib/game/behaviors/animatronic_looping_behavior.dart/0 | {
"file_path": "pinball/lib/game/behaviors/animatronic_looping_behavior.dart",
"repo_id": "pinball",
"token_count": 224
} | 1,098 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Adds a [GameBonus.androidSpaceship] when [AndroidSpaceship] has a bonus.
class AndroidSpaceshipBonusBehavior extends Component {
@override
Future<void> onLoad() async {
await super.onLoad();
await add(
FlameBlocListener<AndroidSpaceshipCubit, AndroidSpaceshipState>(
listenWhen: (_, state) => state == AndroidSpaceshipState.withBonus,
onNewState: (state) {
readBloc<GameBloc, GameState>().add(
const BonusActivated(GameBonus.androidSpaceship),
);
readBloc<AndroidSpaceshipCubit, AndroidSpaceshipState>()
.onBonusAwarded();
},
),
);
}
}
| pinball/lib/game/components/android_acres/behaviors/android_spaceship_bonus_behavior.dart/0 | {
"file_path": "pinball/lib/game/components/android_acres/behaviors/android_spaceship_bonus_behavior.dart",
"repo_id": "pinball",
"token_count": 356
} | 1,099 |
// cSpell:ignore sublist
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flutter/material.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/leaderboard/models/leader_board_entry.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_ui/pinball_ui.dart';
final _titleTextPaint = TextPaint(
style: const TextStyle(
fontSize: 2,
color: PinballColors.red,
fontFamily: PinballFonts.pixeloidSans,
),
);
final _bodyTextPaint = TextPaint(
style: const TextStyle(
fontSize: 1.8,
color: PinballColors.white,
fontFamily: PinballFonts.pixeloidSans,
),
);
double _calcY(int i) => (i * 3.2) + 3.2;
const _columns = [-14.0, 0.0, 14.0];
String _rank(int number) {
switch (number) {
case 1:
return '${number}st';
case 2:
return '${number}nd';
case 3:
return '${number}rd';
default:
return '${number}th';
}
}
/// {@template leaderboard_display}
/// Component that builds the leaderboard list of the Backbox.
/// {@endtemplate}
class LeaderboardDisplay extends PositionComponent with HasGameRef {
/// {@macro leaderboard_display}
LeaderboardDisplay({required List<LeaderboardEntryData> entries})
: _entries = entries;
final List<LeaderboardEntryData> _entries;
_MovePageArrow _findArrow({required bool active}) {
return descendants()
.whereType<_MovePageArrow>()
.firstWhere((arrow) => arrow.active == active);
}
void _changePage(List<LeaderboardEntryData> ranking, int offset) {
final current = descendants().whereType<_RankingPage>().single;
final activeArrow = _findArrow(active: true);
final inactiveArrow = _findArrow(active: false);
activeArrow.active = false;
current.add(
ScaleEffect.to(
Vector2(0, 1),
EffectController(
duration: 0.5,
curve: Curves.easeIn,
),
)..onFinishCallback = () {
current.removeFromParent();
inactiveArrow.active = true;
firstChild<PositionComponent>()?.add(
_RankingPage(
ranking: ranking,
offset: offset,
)
..scale = Vector2(0, 1)
..add(
ScaleEffect.to(
Vector2(1, 1),
EffectController(
duration: 0.5,
curve: Curves.easeIn,
),
),
),
);
},
);
}
@override
Future<void> onLoad() async {
position = Vector2(0, -30);
final l10n = readProvider<AppLocalizations>();
final ranking = _entries.take(5).toList();
await add(
PositionComponent(
position: Vector2(0, 4),
children: [
_MovePageArrow(
position: Vector2(20, 9),
onTap: () {
_changePage(_entries.sublist(5), 5);
},
),
_MovePageArrow(
position: Vector2(-20, 9),
direction: ArrowIconDirection.left,
active: false,
onTap: () {
_changePage(_entries.take(5).toList(), 0);
},
),
PositionComponent(
children: [
TextComponent(
text: l10n.rank,
textRenderer: _titleTextPaint,
position: Vector2(_columns[0], 0),
anchor: Anchor.center,
),
TextComponent(
text: l10n.score,
textRenderer: _titleTextPaint,
position: Vector2(_columns[1], 0),
anchor: Anchor.center,
),
TextComponent(
text: l10n.name,
textRenderer: _titleTextPaint,
position: Vector2(_columns[2], 0),
anchor: Anchor.center,
),
],
),
_RankingPage(
ranking: ranking,
offset: 0,
),
],
),
);
}
}
class _RankingPage extends PositionComponent with HasGameRef {
_RankingPage({
required this.ranking,
required this.offset,
}) : super(children: []);
final List<LeaderboardEntryData> ranking;
final int offset;
@override
Future<void> onLoad() async {
await addAll([
for (var i = 0; i < ranking.length; i++)
PositionComponent(
children: [
TextComponent(
text: _rank(i + 1 + offset),
textRenderer: _bodyTextPaint,
position: Vector2(_columns[0], _calcY(i)),
anchor: Anchor.center,
),
TextComponent(
text: ranking[i].score.formatScore(),
textRenderer: _bodyTextPaint,
position: Vector2(_columns[1], _calcY(i)),
anchor: Anchor.center,
),
SpriteComponent.fromImage(
gameRef.images.fromCache(
ranking[i].character.toTheme.leaderboardIcon.keyName,
),
anchor: Anchor.center,
size: Vector2(1.8, 1.8),
position: Vector2(_columns[2] - 3, _calcY(i) + .25),
),
TextComponent(
text: ranking[i].playerInitials,
textRenderer: _bodyTextPaint,
position: Vector2(_columns[2] + 1, _calcY(i)),
anchor: Anchor.center,
),
],
),
]);
}
}
class _MovePageArrow extends PositionComponent {
_MovePageArrow({
required Vector2 position,
required this.onTap,
this.direction = ArrowIconDirection.right,
bool active = true,
}) : super(
position: position,
children: [
if (active)
ArrowIcon(
position: Vector2.zero(),
direction: direction,
onTap: onTap,
),
SequenceEffect(
[
ScaleEffect.to(
Vector2.all(1.2),
EffectController(duration: 1),
),
ScaleEffect.to(Vector2.all(1), EffectController(duration: 1)),
],
infinite: true,
),
],
);
final ArrowIconDirection direction;
final VoidCallback onTap;
bool get active => children.whereType<ArrowIcon>().isNotEmpty;
set active(bool value) {
if (value) {
add(
ArrowIcon(
position: Vector2.zero(),
direction: direction,
onTap: onTap,
),
);
} else {
firstChild<ArrowIcon>()?.removeFromParent();
}
}
}
| pinball/lib/game/components/backbox/displays/leaderboard_display.dart/0 | {
"file_path": "pinball/lib/game/components/backbox/displays/leaderboard_display.dart",
"repo_id": "pinball",
"token_count": 3407
} | 1,100 |
export 'google_word_bonus_behavior.dart';
| pinball/lib/game/components/google_gallery/behaviors/behaviors.dart/0 | {
"file_path": "pinball/lib/game/components/google_gallery/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 15
} | 1,101 |
import 'package:flame/game.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/assets_manager/assets_manager.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/more_information/more_information.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball/start_game/start_game.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_ui/pinball_ui.dart';
import 'package:platform_helper/platform_helper.dart';
import 'package:share_repository/share_repository.dart';
class PinballGamePage extends StatelessWidget {
const PinballGamePage({
Key? key,
this.isDebugMode = kDebugMode,
}) : super(key: key);
final bool isDebugMode;
@override
Widget build(BuildContext context) {
final characterThemeBloc = context.read<CharacterThemeCubit>();
final audioPlayer = context.read<PinballAudioPlayer>();
final leaderboardRepository = context.read<LeaderboardRepository>();
final shareRepository = context.read<ShareRepository>();
final platformHelper = context.read<PlatformHelper>();
final gameBloc = context.read<GameBloc>();
final game = isDebugMode
? DebugPinballGame(
characterThemeBloc: characterThemeBloc,
audioPlayer: audioPlayer,
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
l10n: context.l10n,
platformHelper: platformHelper,
gameBloc: gameBloc,
)
: PinballGame(
characterThemeBloc: characterThemeBloc,
audioPlayer: audioPlayer,
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
l10n: context.l10n,
platformHelper: platformHelper,
gameBloc: gameBloc,
);
return Scaffold(
backgroundColor: PinballColors.black,
body: BlocProvider(
create: (_) => AssetsManagerCubit(game, audioPlayer)..load(),
child: PinballGameView(game),
),
);
}
}
class PinballGameView extends StatelessWidget {
const PinballGameView(this.game, {Key? key}) : super(key: key);
final PinballGame game;
@override
Widget build(BuildContext context) {
return BlocBuilder<AssetsManagerCubit, AssetsManagerState>(
builder: (context, state) {
return state.isLoading
? const AssetsLoadingPage()
: PinballGameLoadedView(game);
},
);
}
}
@visibleForTesting
class PinballGameLoadedView extends StatelessWidget {
const PinballGameLoadedView(this.game, {Key? key}) : super(key: key);
final PinballGame game;
@override
Widget build(BuildContext context) {
return StartGameListener(
child: Stack(
children: [
Positioned.fill(
child: MouseRegion(
onHover: (_) {
if (!game.focusNode.hasFocus) {
game.focusNode.requestFocus();
}
},
child: GameWidget<PinballGame>(
game: game,
focusNode: game.focusNode,
initialActiveOverlays: const [PinballGame.playButtonOverlay],
overlayBuilderMap: {
PinballGame.playButtonOverlay: (_, game) => const Positioned(
bottom: 20,
right: 0,
left: 0,
child: PlayButtonOverlay(),
),
PinballGame.mobileControlsOverlay: (_, game) => Positioned(
bottom: 0,
left: 0,
right: 0,
child: MobileControls(game: game),
),
PinballGame.replayButtonOverlay: (context, game) =>
const Positioned(
bottom: 20,
right: 0,
left: 0,
child: ReplayButtonOverlay(),
)
},
),
),
),
const _PositionedGameHud(),
const _PositionedInfoIcon(),
],
),
);
}
}
class _PositionedGameHud extends StatelessWidget {
const _PositionedGameHud({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final isPlaying = context.select(
(StartGameBloc bloc) => bloc.state.status == StartGameStatus.play,
);
final isGameOver = context.select(
(GameBloc bloc) => bloc.state.status.isGameOver,
);
final gameWidgetWidth = MediaQuery.of(context).size.height * 9 / 16;
final screenWidth = MediaQuery.of(context).size.width;
final leftMargin = (screenWidth / 2) - (gameWidgetWidth / 1.8);
final clampedMargin = leftMargin > 0 ? leftMargin : 0.0;
return Positioned(
top: 0,
left: clampedMargin,
child: Visibility(
visible: isPlaying && !isGameOver,
child: const GameHud(),
),
);
}
}
class _PositionedInfoIcon extends StatelessWidget {
const _PositionedInfoIcon({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Positioned(
top: 0,
left: 0,
child: BlocBuilder<GameBloc, GameState>(
builder: (context, state) {
return Visibility(
visible: state.status.isGameOver,
child: IconButton(
iconSize: 50,
icon: const Icon(Icons.info, color: PinballColors.white),
onPressed: () => showMoreInformationDialog(context),
),
);
},
),
);
}
}
| pinball/lib/game/view/pinball_game_page.dart/0 | {
"file_path": "pinball/lib/game/view/pinball_game_page.dart",
"repo_id": "pinball",
"token_count": 2674
} | 1,102 |
{
"@@locale": "en",
"play": "Play",
"@play": {
"description": "Text displayed on the landing page play button"
},
"howToPlay": "How to Play",
"@howToPlay": {
"description": "Text displayed on the landing page how to play button"
},
"tipsForFlips": "Tips for flips",
"@tipsForFlips": {
"description": "Text displayed on the landing page how to play button"
},
"launchControls": "Launch Controls",
"@launchControls": {
"description": "Text displayed on the how to play dialog with the launch controls"
},
"flipperControls": "Flipper Controls",
"@flipperControls": {
"description": "Text displayed on the how to play dialog with the flipper controls"
},
"tapAndHoldRocket": "Tap Rocket",
"@tapAndHoldRocket": {
"description": "Text displayed on the how to launch on mobile"
},
"to": "to",
"@to": {
"description": "Text displayed for the word to"
},
"launch": "LAUNCH",
"@launch": {
"description": "Text displayed for the word launch"
},
"tapLeftRightScreen": "Tap left/right screen",
"@tapLeftRightScreen": {
"description": "Text displayed on the how to flip on mobile"
},
"flip": "FLIP",
"@flip": {
"description": "Text displayed for the word FLIP"
},
"start": "Start",
"@start": {
"description": "Text displayed on the character selection page start button"
},
"select": "Select",
"@select": {
"description": "Text displayed on the character selection dialog - select button"
},
"space": "Space",
"@space": {
"description": "Text displayed on space control button"
},
"characterSelectionTitle": "Select a Character",
"@characterSelectionTitle": {
"description": "Title text displayed on the character selection dialog"
},
"characterSelectionSubtitle": "There’s no wrong choice!",
"@characterSelectionSubtitle": {
"description": "Subtitle text displayed on the character selection dialog"
},
"gameOver": "Game Over",
"@gameOver": {
"description": "Text displayed on the ending dialog when game finishes"
},
"rounds": "Ball Ct:",
"@rounds": {
"description": "Text displayed on the scoreboard widget to indicate rounds left"
},
"topPlayers": "Top Players",
"@topPlayers": {
"description": "Title text displayed on leaderboard screen"
},
"rank": "rank",
"@rank": {
"description": "Label text displayed above player's rank"
},
"name": "name",
"@name": {
"description": "Label text displayed above player's initials"
},
"score": "score",
"@score": {
"description": "Label text displayed above player's score"
},
"enterInitials": "Enter your initials using the",
"@enterInitials": {
"description": "Informational text displayed on initials input screen"
},
"arrows": "arrows",
"@arrows": {
"description": "Text displayed on initials input screen indicating arrow keys"
},
"andPress": "and press",
"@andPress": {
"description": "Connecting text displayed on initials input screen informational text span"
},
"enterReturn": "enter/return",
"@enterReturn": {
"description": "Text displayed on initials input screen indicating return key"
},
"toSubmit": "to submit",
"@toSubmit": {
"description": "Ending text displayed on initials input screen informational text span"
},
"linkBoxTitle": "Resources",
"@linkBoxTitle": {
"description": "Text shown on the link box title section."
},
"linkBoxMadeWithText": "Made with ",
"@linkBoxMadeWithText": {
"description": "Text shown on the link box which mentions technologies used to build the app."
},
"linkBoxFlutterLinkText": "Flutter",
"@linkBoxFlutterLinkText": {
"description": "Text on the link shown on the link box which navigates to the Flutter page"
},
"linkBoxFirebaseLinkText": "Firebase",
"@linkBoxFirebaseLinkText": {
"description": "Text on the link shown on the link box which navigates to the Firebase page"
},
"linkBoxOpenSourceCode": "Open Source Code",
"@linkBoxOpenSourceCode": {
"description": "Text shown on the link box which redirects to github project"
},
"linkBoxGoogleIOText": "Google I/O",
"@linkBoxGoogleIOText": {
"description": "Text shown on the link box which mentions Google I/O"
},
"linkBoxFlutterGames": "Flutter Games",
"@linkBoxFlutterGames": {
"description": "Text shown on the link box which redirects to flutter games article"
},
"linkBoxHowItsMade": "How it’s made",
"@linkBoxHowItsMade": {
"description": "Text shown on the link box which redirects to Very Good Blog article"
},
"linkBoxTermsOfService": "Terms of Service",
"@linkBoxTermsOfService": {
"description": "Text shown on the link box which redirect to terms of service"
},
"linkBoxPrivacyPolicy": "Privacy Policy",
"@linkBoxPrivacyPolicy": {
"description": "Text shown on the link box which redirect to privacy policy"
},
"loading": "Loading",
"@loading": {
"description": "Text shown to indicate loading times"
},
"replay": "Replay",
"@replay": {
"description": "Text displayed on the share page for replay button"
},
"ioPinball": "I/O Pinball",
"@ioPinball": {
"description": "I/O Pinball - Name of the game"
},
"shareYourScore": "Share your score",
"@shareYourScore": {
"description": "Text shown on title of info screen"
},
"andChallengeYourFriends": "AND CHALLENGE YOUR FRIENDS",
"@challengeYourFriends": {
"description": "Text shown on title of info screen"
},
"share": "SHARE",
"@share": {
"description": "Text for share link on info screen."
},
"gotoIO": "GO TO I/O",
"@gotoIO": {
"description": "Text for going to I/O site link on info screen."
},
"learnMore": "Learn more about building games in Flutter with",
"@learnMore": {
"description": "Text shown on description of info screen"
},
"firebaseOr": "Firebase or dive right into the",
"@firebaseOr": {
"description": "Text shown on description of info screen"
},
"openSourceCode": "open source code.",
"@openSourceCode": {
"description": "Text shown on description of info screen"
},
"enter": "Enter",
"@enter": {
"description": "Text shown on the mobile controls enter button"
},
"initialsErrorTitle": "Uh-oh... well, that didn’t work",
"@initialsErrorTitle": {
"description": "Title shown when the initials submission fails"
},
"initialsErrorMessage": "Please try a different combination of letters",
"@initialsErrorMessage": {
"description": "Message on shown when the initials submission fails"
},
"leaderboardErrorMessage": "No connection. Leaderboard and sharing functionality is unavailable.",
"@leaderboardErrorMessage": {
"description": "Text shown when the leaderboard had an error while loading"
}
,
"letEveryone": "Let everyone know about I/O Pinball",
"@letEveryone": {
"description": "Text displayed on share screen for description"
},
"bySharingYourScore": "by sharing your score to your preferred",
"@bySharingYourScore": {
"description": "Text displayed on share screen for description"
},
"socialMediaAccount": "social media account!",
"@socialMediaAccount": {
"description": "Text displayed on share screen for description"
},
"iGotScoreAtPinball": "I got {score} points in #IOPinball, can you beat my score? \nSee you at #GoogleIO!",
"@iGotScoreAtPinball": {
"description": "Text to share score on Social Network",
"placeholders": {
"score": {
"type": "String"
}
}
}
}
| pinball/lib/l10n/arb/app_en.arb/0 | {
"file_path": "pinball/lib/l10n/arb/app_en.arb",
"repo_id": "pinball",
"token_count": 2344
} | 1,103 |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/how_to_play/how_to_play.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball/start_game/start_game.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// {@template start_game_listener}
/// Listener that manages the display of dialogs for [StartGameStatus].
///
/// It's responsible for starting the game after pressing play button
/// and playing a sound after the 'how to play' dialog.
/// {@endtemplate}
class StartGameListener extends StatelessWidget {
/// {@macro start_game_listener}
const StartGameListener({
Key? key,
required Widget child,
}) : _child = child,
super(key: key);
final Widget _child;
@override
Widget build(BuildContext context) {
return BlocListener<StartGameBloc, StartGameState>(
listener: (context, state) {
switch (state.status) {
case StartGameStatus.initial:
break;
case StartGameStatus.selectCharacter:
_onSelectCharacter(context);
context.read<GameBloc>().add(const GameStarted());
break;
case StartGameStatus.howToPlay:
_onHowToPlay(context);
break;
case StartGameStatus.play:
break;
}
},
child: _child,
);
}
void _onSelectCharacter(BuildContext context) {
_showPinballDialog(
context: context,
child: const CharacterSelectionDialog(),
barrierDismissible: false,
);
}
void _onHowToPlay(BuildContext context) {
_showPinballDialog(
context: context,
child: HowToPlayDialog(
onDismissCallback: () {
context.read<StartGameBloc>().add(const HowToPlayFinished());
},
),
);
}
void _showPinballDialog({
required BuildContext context,
required Widget child,
bool barrierDismissible = true,
}) {
final gameWidgetWidth = MediaQuery.of(context).size.height * 9 / 16;
showDialog<void>(
context: context,
barrierColor: PinballColors.transparent,
barrierDismissible: barrierDismissible,
builder: (_) {
return Center(
child: SizedBox(
height: gameWidgetWidth * 0.87,
width: gameWidgetWidth,
child: child,
),
);
},
);
}
}
| pinball/lib/start_game/widgets/start_game_listener.dart/0 | {
"file_path": "pinball/lib/start_game/widgets/start_game_listener.dart",
"repo_id": "pinball",
"token_count": 1003
} | 1,104 |
# leaderboard_repository
[![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link]
[![License: MIT][license_badge]][license_link]
Repository to access leaderboard data in Firebase Cloud Firestore.
[license_badge]: https://img.shields.io/badge/license-MIT-blue.svg
[license_link]: https://opensource.org/licenses/MIT
[very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg
[very_good_analysis_link]: https://pub.dev/packages/very_good_analysis | pinball/packages/leaderboard_repository/README.md/0 | {
"file_path": "pinball/packages/leaderboard_repository/README.md",
"repo_id": "pinball",
"token_count": 176
} | 1,105 |
import 'dart:math';
import 'package:audioplayers/audioplayers.dart';
import 'package:clock/clock.dart';
import 'package:flame_audio/audio_pool.dart';
import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/material.dart';
import 'package:pinball_audio/gen/assets.gen.dart';
/// Sounds available to play.
enum PinballAudio {
/// Google.
google,
/// Bumper.
bumper,
/// Cow moo.
cowMoo,
/// Background music.
backgroundMusic,
/// IO Pinball voice over.
ioPinballVoiceOver,
/// Game over.
gameOverVoiceOver,
/// Launcher.
launcher,
/// Kicker.
kicker,
/// Rollover.
rollover,
/// Sparky.
sparky,
/// Android.
android,
/// Dino.
dino,
/// Dash.
dash,
/// Flipper.
flipper,
}
/// Defines the contract of the creation of an [AudioPool].
typedef CreateAudioPool = Future<AudioPool> Function(
String sound, {
bool? repeating,
int? maxPlayers,
int? minPlayers,
String? prefix,
});
/// Defines the contract for playing a single audio.
typedef PlaySingleAudio = Future<void> Function(String, {double volume});
/// Defines the contract for looping a single audio.
typedef LoopSingleAudio = Future<void> Function(String, {double volume});
/// Defines the contract for pre fetching an audio.
typedef PreCacheSingleAudio = Future<void> Function(String);
/// Defines the contract for configuring an [AudioCache] instance.
typedef ConfigureAudioCache = void Function(AudioCache);
abstract class _Audio {
void play();
Future<void> load();
String prefixFile(String file) {
return 'packages/pinball_audio/$file';
}
}
class _SimplePlayAudio extends _Audio {
_SimplePlayAudio({
required this.preCacheSingleAudio,
required this.playSingleAudio,
required this.path,
this.volume,
});
final PreCacheSingleAudio preCacheSingleAudio;
final PlaySingleAudio playSingleAudio;
final String path;
final double? volume;
@override
Future<void> load() => preCacheSingleAudio(prefixFile(path));
@override
void play() {
playSingleAudio(prefixFile(path), volume: volume ?? 1);
}
}
class _LoopAudio extends _Audio {
_LoopAudio({
required this.preCacheSingleAudio,
required this.loopSingleAudio,
required this.path,
this.volume,
});
final PreCacheSingleAudio preCacheSingleAudio;
final LoopSingleAudio loopSingleAudio;
final String path;
final double? volume;
@override
Future<void> load() => preCacheSingleAudio(prefixFile(path));
@override
void play() {
loopSingleAudio(prefixFile(path), volume: volume ?? 1);
}
}
class _SingleLoopAudio extends _LoopAudio {
_SingleLoopAudio({
required PreCacheSingleAudio preCacheSingleAudio,
required LoopSingleAudio loopSingleAudio,
required String path,
double? volume,
}) : super(
preCacheSingleAudio: preCacheSingleAudio,
loopSingleAudio: loopSingleAudio,
path: path,
volume: volume,
);
bool _playing = false;
@override
void play() {
if (!_playing) {
super.play();
_playing = true;
}
}
}
class _SingleAudioPool extends _Audio {
_SingleAudioPool({
required this.path,
required this.createAudioPool,
required this.maxPlayers,
});
final String path;
final CreateAudioPool createAudioPool;
final int maxPlayers;
late AudioPool pool;
@override
Future<void> load() async {
pool = await createAudioPool(
prefixFile(path),
maxPlayers: maxPlayers,
prefix: '',
);
}
@override
void play() => pool.start();
}
class _RandomABAudio extends _Audio {
_RandomABAudio({
required this.createAudioPool,
required this.seed,
required this.audioAssetA,
required this.audioAssetB,
this.volume,
});
final CreateAudioPool createAudioPool;
final Random seed;
final String audioAssetA;
final String audioAssetB;
final double? volume;
late AudioPool audioA;
late AudioPool audioB;
@override
Future<void> load() async {
await Future.wait(
[
createAudioPool(
prefixFile(audioAssetA),
maxPlayers: 4,
prefix: '',
).then((pool) => audioA = pool),
createAudioPool(
prefixFile(audioAssetB),
maxPlayers: 4,
prefix: '',
).then((pool) => audioB = pool),
],
);
}
@override
void play() {
(seed.nextBool() ? audioA : audioB).start(volume: volume ?? 1);
}
}
class _ThrottledAudio extends _Audio {
_ThrottledAudio({
required this.preCacheSingleAudio,
required this.playSingleAudio,
required this.path,
required this.duration,
});
final PreCacheSingleAudio preCacheSingleAudio;
final PlaySingleAudio playSingleAudio;
final String path;
final Duration duration;
DateTime? _lastPlayed;
@override
Future<void> load() => preCacheSingleAudio(prefixFile(path));
@override
void play() {
final now = clock.now();
if (_lastPlayed == null ||
(_lastPlayed != null && now.difference(_lastPlayed!) > duration)) {
_lastPlayed = now;
playSingleAudio(prefixFile(path));
}
}
}
/// {@template pinball_audio_player}
/// Sound manager for the pinball game.
/// {@endtemplate}
class PinballAudioPlayer {
/// {@macro pinball_audio_player}
PinballAudioPlayer({
CreateAudioPool? createAudioPool,
PlaySingleAudio? playSingleAudio,
LoopSingleAudio? loopSingleAudio,
PreCacheSingleAudio? preCacheSingleAudio,
ConfigureAudioCache? configureAudioCache,
Random? seed,
}) : _createAudioPool = createAudioPool ?? AudioPool.create,
_playSingleAudio = playSingleAudio ?? FlameAudio.audioCache.play,
_loopSingleAudio = loopSingleAudio ?? FlameAudio.audioCache.loop,
_preCacheSingleAudio =
preCacheSingleAudio ?? FlameAudio.audioCache.load,
_configureAudioCache = configureAudioCache ??
((AudioCache a) {
a.prefix = '';
}),
_seed = seed ?? Random() {
audios = {
PinballAudio.google: _SimplePlayAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.google,
),
PinballAudio.sparky: _SimplePlayAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.sparky,
),
PinballAudio.dino: _ThrottledAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.dino,
duration: const Duration(seconds: 6),
),
PinballAudio.dash: _SimplePlayAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.dash,
),
PinballAudio.android: _SimplePlayAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.android,
),
PinballAudio.launcher: _SimplePlayAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.launcher,
),
PinballAudio.rollover: _SimplePlayAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.rollover,
volume: 0.3,
),
PinballAudio.flipper: _SingleAudioPool(
path: Assets.sfx.flipper,
createAudioPool: _createAudioPool,
maxPlayers: 2,
),
PinballAudio.ioPinballVoiceOver: _SimplePlayAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.ioPinballVoiceOver,
),
PinballAudio.gameOverVoiceOver: _SimplePlayAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.gameOverVoiceOver,
),
PinballAudio.bumper: _RandomABAudio(
createAudioPool: _createAudioPool,
seed: _seed,
audioAssetA: Assets.sfx.bumperA,
audioAssetB: Assets.sfx.bumperB,
volume: 0.6,
),
PinballAudio.kicker: _RandomABAudio(
createAudioPool: _createAudioPool,
seed: _seed,
audioAssetA: Assets.sfx.kickerA,
audioAssetB: Assets.sfx.kickerB,
volume: 0.6,
),
PinballAudio.cowMoo: _ThrottledAudio(
preCacheSingleAudio: _preCacheSingleAudio,
playSingleAudio: _playSingleAudio,
path: Assets.sfx.cowMoo,
duration: const Duration(seconds: 2),
),
PinballAudio.backgroundMusic: _SingleLoopAudio(
preCacheSingleAudio: _preCacheSingleAudio,
loopSingleAudio: _loopSingleAudio,
path: Assets.music.background,
volume: .6,
),
};
}
final CreateAudioPool _createAudioPool;
final PlaySingleAudio _playSingleAudio;
final LoopSingleAudio _loopSingleAudio;
final PreCacheSingleAudio _preCacheSingleAudio;
final ConfigureAudioCache _configureAudioCache;
final Random _seed;
/// Registered audios on the Player.
@visibleForTesting
// ignore: library_private_types_in_public_api
late final Map<PinballAudio, _Audio> audios;
/// Loads the sounds effects into the memory.
List<Future<void> Function()> load() {
_configureAudioCache(FlameAudio.audioCache);
return audios.values.map((a) => a.load).toList();
}
/// Plays the received audio.
void play(PinballAudio audio) {
assert(
audios.containsKey(audio),
'Tried to play unregistered audio $audio',
);
audios[audio]?.play();
}
}
| pinball/packages/pinball_audio/lib/src/pinball_audio.dart/0 | {
"file_path": "pinball/packages/pinball_audio/lib/src/pinball_audio.dart",
"repo_id": "pinball",
"token_count": 3621
} | 1,106 |
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/android_animatronic/behaviors/behaviors.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template android_animatronic}
/// Animated Android that sits on top of the [AndroidSpaceship].
/// {@endtemplate}
class AndroidAnimatronic extends BodyComponent
with InitialPosition, Layered, ZIndex {
/// {@macro android_animatronic}
AndroidAnimatronic({Iterable<Component>? children})
: super(
children: [
_AndroidAnimatronicSpriteAnimationComponent(),
AndroidAnimatronicBallContactBehavior(),
...?children,
],
renderBody: false,
) {
layer = Layer.spaceship;
zIndex = ZIndexes.androidHead;
}
/// Creates an [AndroidAnimatronic] without any children.
///
/// This can be used for testing [AndroidAnimatronic]'s behaviors in
/// isolation.
@visibleForTesting
AndroidAnimatronic.test();
@override
Body createBody() {
final shape = EllipseShape(
center: Vector2.zero(),
majorRadius: 3.1,
minorRadius: 2,
)..rotate(1.4);
final bodyDef = BodyDef(position: initialPosition);
return world.createBody(bodyDef)..createFixtureFromShape(shape);
}
}
class _AndroidAnimatronicSpriteAnimationComponent
extends SpriteAnimationComponent with HasGameRef {
_AndroidAnimatronicSpriteAnimationComponent()
: super(
anchor: Anchor.center,
position: Vector2(-0.24, -2.6),
);
@override
Future<void> onLoad() async {
await super.onLoad();
final spriteSheet = gameRef.images.fromCache(
Assets.images.android.spaceship.animatronic.keyName,
);
const amountPerRow = 18;
const amountPerColumn = 4;
final textureSize = Vector2(
spriteSheet.width / amountPerRow,
spriteSheet.height / amountPerColumn,
);
size = textureSize / 10;
animation = SpriteAnimation.fromFrameData(
spriteSheet,
SpriteAnimationData.sequenced(
amount: amountPerRow * amountPerColumn,
amountPerRow: amountPerRow,
stepTime: 1 / 24,
textureSize: textureSize,
),
);
}
}
| pinball/packages/pinball_components/lib/src/components/android_animatronic/android_animatronic.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/android_animatronic/android_animatronic.dart",
"repo_id": "pinball",
"token_count": 889
} | 1,107 |
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_theme/pinball_theme.dart' as theme;
export 'behaviors/behaviors.dart';
export 'cubit/ball_cubit.dart';
/// {@template ball}
/// A solid, [BodyType.dynamic] sphere that rolls and bounces around.
/// {@endtemplate}
class Ball extends BodyComponent with Layered, InitialPosition, ZIndex {
/// {@macro ball}
Ball({String? assetPath}) : this._(bloc: BallCubit(), assetPath: assetPath);
Ball._({required this.bloc, String? assetPath})
: super(
renderBody: false,
children: [
FlameBlocProvider<BallCubit, BallState>.value(
value: bloc,
children: [BallSpriteComponent(assetPath: assetPath)],
),
BallScalingBehavior(),
BallGravitatingBehavior(),
],
) {
layer = Layer.board;
}
/// Creates a [Ball] without any behaviors.
///
/// This can be used for testing [Ball]'s behaviors in isolation.
@visibleForTesting
Ball.test({
BallCubit? bloc,
String? assetPath,
}) : bloc = bloc ?? BallCubit(),
super(
children: [
FlameBlocProvider<BallCubit, BallState>.value(
value: bloc ?? BallCubit(),
children: [BallSpriteComponent(assetPath: assetPath)],
)
],
);
/// Bloc to update the ball sprite when a new character is selected.
final BallCubit bloc;
/// The size of the [Ball].
static final Vector2 size = Vector2.all(4.13);
@override
Body createBody() {
final shape = CircleShape()..radius = size.x / 2;
final bodyDef = BodyDef(
position: initialPosition,
type: BodyType.dynamic,
userData: this,
bullet: true,
);
return world.createBody(bodyDef)..createFixtureFromShape(shape, 1);
}
/// Immediately and completely [stop]s the ball.
///
/// The [Ball] will no longer be affected by any forces, including it's
/// weight and those emitted from collisions.
void stop() {
body
..gravityScale = Vector2.zero()
..linearVelocity = Vector2.zero()
..angularVelocity = 0;
}
/// Allows the [Ball] to be affected by forces.
///
/// If previously [stop]ped, the previous ball's velocity is not kept.
void resume() {
body.gravityScale = Vector2(1, 1);
}
}
/// {@template ball_sprite_component}
/// Visual representation of the [Ball].
/// {@endtemplate}
@visibleForTesting
class BallSpriteComponent extends SpriteComponent
with HasGameRef, FlameBlocListenable<BallCubit, BallState> {
/// {@macro ball_sprite_component}
BallSpriteComponent({required String? assetPath})
: _assetPath = assetPath,
super(anchor: Anchor.center);
final String? _assetPath;
@override
void onNewState(BallState state) {
sprite = Sprite(
gameRef.images.fromCache(state.characterTheme.ball.keyName),
);
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images
.fromCache(_assetPath ?? theme.Assets.images.dash.ball.keyName),
);
this.sprite = sprite;
size = sprite.originalSize / 12.5;
}
}
| pinball/packages/pinball_components/lib/src/components/ball/ball.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/ball/ball.dart",
"repo_id": "pinball",
"token_count": 1315
} | 1,108 |
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template chrome_dino_chomping_behavior}
/// Chomps a [Ball] after it has entered the [ChromeDino]'s mouth.
///
/// The chomped [Ball] is hidden in the mouth until it is spit out.
/// {@endtemplate}
class ChromeDinoChompingBehavior extends ContactBehavior<ChromeDino> {
@override
void beginContact(Object other, Contact contact) {
super.beginContact(other, contact);
if (other is! Ball) return;
other.descendants().whereType<SpriteComponent>().single.setOpacity(0);
parent.bloc.onChomp(other);
}
}
| pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_chomping_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_chomping_behavior.dart",
"repo_id": "pinball",
"token_count": 250
} | 1,109 |
export 'flapper_spinning_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/flapper/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/flapper/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 14
} | 1,110 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball_components/pinball_components.dart';
class GoogleWordAnimatingBehavior extends TimerComponent
with FlameBlocReader<GoogleWordCubit, GoogleWordState> {
GoogleWordAnimatingBehavior() : super(period: 0.35, repeat: true);
final _maxBlinks = 7;
int _blinks = 0;
@override
void onTick() {
super.onTick();
if (_blinks != _maxBlinks * 2) {
bloc.switched();
_blinks++;
} else {
timer.stop();
bloc.onReset();
shouldRemove = true;
}
}
}
| pinball/packages/pinball_components/lib/src/components/google_word/behaviors/google_word_animating_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/google_word/behaviors/google_word_animating_behavior.dart",
"repo_id": "pinball",
"token_count": 236
} | 1,111 |
export 'multiball_blinking_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/multiball/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/multiball/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 15
} | 1,112 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
export 'behaviors/behaviors.dart';
export 'cubit/plunger_cubit.dart';
/// {@template plunger}
/// [Plunger] serves as a spring, that shoots the ball on the right side of the
/// play field.
///
/// [Plunger] ignores gravity so the player controls its downward movement.
/// {@endtemplate}
class Plunger extends BodyComponent with InitialPosition, Layered, ZIndex {
/// {@macro plunger}
Plunger()
: super(
renderBody: false,
children: [
FlameBlocProvider<PlungerCubit, PlungerState>(
create: PlungerCubit.new,
children: [
_PlungerSpriteAnimationGroupComponent(),
PlungerReleasingBehavior(strength: 11),
PlungerNoiseBehavior(),
],
),
PlungerJointingBehavior(compressionDistance: 9.2),
],
) {
zIndex = ZIndexes.plunger;
layer = Layer.launcher;
}
/// Creates a [Plunger] without any children.
///
/// This can be used for testing [Plunger]'s behaviors in isolation.
@visibleForTesting
Plunger.test();
List<FixtureDef> _createFixtureDefs() {
final leftShapeVertices = [
Vector2(0, 0),
Vector2(-1.8, 0),
Vector2(-1.8, -2.2),
Vector2(0, -0.3),
]..forEach((vector) => vector.rotate(BoardDimensions.perspectiveAngle));
final leftTriangleShape = PolygonShape()..set(leftShapeVertices);
final rightShapeVertices = [
Vector2(0, 0),
Vector2(1.8, 0),
Vector2(1.8, -2.2),
Vector2(0, -0.3),
]..forEach((vector) => vector.rotate(BoardDimensions.perspectiveAngle));
final rightTriangleShape = PolygonShape()..set(rightShapeVertices);
return [
FixtureDef(
leftTriangleShape,
density: 80,
),
FixtureDef(
rightTriangleShape,
density: 80,
),
];
}
@override
Body createBody() {
final bodyDef = BodyDef(
position: initialPosition,
type: BodyType.dynamic,
gravityScale: Vector2.zero(),
);
final body = world.createBody(bodyDef);
_createFixtureDefs().forEach(body.createFixture);
return body;
}
}
class _PlungerSpriteAnimationGroupComponent
extends SpriteAnimationGroupComponent<PlungerState>
with HasGameRef, FlameBlocListenable<PlungerCubit, PlungerState> {
_PlungerSpriteAnimationGroupComponent()
: super(
anchor: Anchor.center,
position: Vector2(1.87, 14.9),
);
@override
void onNewState(PlungerState state) {
super.onNewState(state);
final startedReleasing = state.isReleasing && !current!.isReleasing;
final startedPulling = state.isPulling && !current!.isPulling;
if (startedReleasing || startedPulling) {
animation?.reset();
}
current = state;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final spriteSheet = gameRef.images.fromCache(
Assets.images.plunger.plunger.keyName,
);
const amountPerRow = 20;
const amountPerColumn = 1;
final textureSize = Vector2(
spriteSheet.width / amountPerRow,
spriteSheet.height / amountPerColumn,
);
size = textureSize / 10;
final pullAnimation = SpriteAnimation.fromFrameData(
spriteSheet,
SpriteAnimationData.sequenced(
amount: amountPerRow * amountPerColumn ~/ 2,
amountPerRow: amountPerRow ~/ 2,
stepTime: 1 / 24,
textureSize: textureSize,
texturePosition: Vector2.zero(),
loop: false,
),
);
animations = {
PlungerState.releasing: pullAnimation.reversed(),
PlungerState.pulling: pullAnimation,
PlungerState.autoPulling: pullAnimation,
};
current = readBloc<PlungerCubit, PlungerState>().state;
}
}
| pinball/packages/pinball_components/lib/src/components/plunger/plunger.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/plunger/plunger.dart",
"repo_id": "pinball",
"token_count": 1678
} | 1,113 |
export 'ramp_ball_ascending_contact_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/spaceship_ramp/behavior/behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/spaceship_ramp/behavior/behavior.dart",
"repo_id": "pinball",
"token_count": 18
} | 1,114 |
// ignore_for_file: avoid_renaming_method_parameters
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/sparky_computer/behaviors/behaviors.dart';
import 'package:pinball_flame/pinball_flame.dart';
export 'cubit/sparky_computer_cubit.dart';
/// {@template sparky_computer}
/// A computer owned by Sparky.
/// {@endtemplate}
class SparkyComputer extends BodyComponent {
/// {@macro sparky_computer}
SparkyComputer({Iterable<Component>? children})
: bloc = SparkyComputerCubit(),
super(
renderBody: false,
children: [
SparkyComputerSensorBallContactBehavior()
..applyTo(['turbo_charge_sensor']),
_ComputerBaseSpriteComponent(),
_ComputerTopSpriteComponent(),
_ComputerGlowSpriteComponent(),
...?children,
],
);
/// Creates a [SparkyComputer] without any children.
///
/// This can be used for testing [SparkyComputer]'s behaviors in isolation.
@visibleForTesting
SparkyComputer.test({
required this.bloc,
Iterable<Component>? children,
}) : super(children: children);
final SparkyComputerCubit bloc;
@override
void onRemove() {
bloc.close();
super.onRemove();
}
List<FixtureDef> _createFixtureDefs() {
final leftEdge = EdgeShape()
..set(
Vector2(-15.3, -45.9),
Vector2(-15.7, -49.5),
);
final topEdge = EdgeShape()
..set(
leftEdge.vertex2,
Vector2(-11.1, -50.5),
);
final rightEdge = EdgeShape()
..set(
topEdge.vertex2,
Vector2(-9.4, -47.1),
);
final turboChargeSensor = PolygonShape()
..setAsBox(
1,
0.1,
Vector2(-13.1, -49.7),
-0.18,
);
return [
FixtureDef(leftEdge),
FixtureDef(topEdge),
FixtureDef(rightEdge),
FixtureDef(
turboChargeSensor,
isSensor: true,
userData: 'turbo_charge_sensor',
),
];
}
@override
Body createBody() {
final body = world.createBody(BodyDef());
_createFixtureDefs().forEach(body.createFixture);
return body;
}
}
class _ComputerBaseSpriteComponent extends SpriteComponent
with HasGameRef, ZIndex {
_ComputerBaseSpriteComponent()
: super(
anchor: Anchor.center,
position: Vector2(-12.44, -48.15),
) {
zIndex = ZIndexes.computerBase;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(
Assets.images.sparky.computer.base.keyName,
),
);
this.sprite = sprite;
size = sprite.originalSize / 10;
}
}
class _ComputerTopSpriteComponent extends SpriteComponent
with HasGameRef, ZIndex {
_ComputerTopSpriteComponent()
: super(
anchor: Anchor.center,
position: Vector2(-12.86, -49.37),
) {
zIndex = ZIndexes.computerTop;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(
Assets.images.sparky.computer.top.keyName,
),
);
this.sprite = sprite;
size = sprite.originalSize / 10;
}
}
class _ComputerGlowSpriteComponent extends SpriteComponent
with HasGameRef, ZIndex {
_ComputerGlowSpriteComponent()
: super(
anchor: Anchor.center,
position: Vector2(4, 11),
) {
zIndex = ZIndexes.computerGlow;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(
Assets.images.sparky.computer.glow.keyName,
),
);
this.sprite = sprite;
size = sprite.originalSize / 10;
}
}
| pinball/packages/pinball_components/lib/src/components/sparky_computer/sparky_computer.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/sparky_computer/sparky_computer.dart",
"repo_id": "pinball",
"token_count": 1676
} | 1,115 |
import 'package:dashbook/dashbook.dart';
import 'package:flutter/material.dart';
import 'package:sandbox/stories/stories.dart';
void main() {
final dashbook = Dashbook(theme: ThemeData.dark());
addBallStories(dashbook);
addLayerStories(dashbook);
addEffectsStories(dashbook);
addErrorComponentStories(dashbook);
addFlutterForestStories(dashbook);
addSparkyScorchStories(dashbook);
addAndroidAcresStories(dashbook);
addDinoDesertStories(dashbook);
addBottomGroupStories(dashbook);
addPlungerStories(dashbook);
addBoundariesStories(dashbook);
addGoogleWordStories(dashbook);
addLaunchRampStories(dashbook);
addScoreStories(dashbook);
addMultiballStories(dashbook);
addMultipliersStories(dashbook);
addArrowIconStories(dashbook);
runApp(dashbook);
}
| pinball/packages/pinball_components/sandbox/lib/main.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/main.dart",
"repo_id": "pinball",
"token_count": 270
} | 1,116 |
import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class KickerGame extends BallGame {
KickerGame()
: super(
imagesFileNames: [
Assets.images.kicker.left.lit.keyName,
Assets.images.kicker.left.dimmed.keyName,
Assets.images.kicker.right.lit.keyName,
Assets.images.kicker.right.dimmed.keyName,
],
);
static const description = '''
Shows how Kickers are rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a ball into the game.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
final center = screenToWorld(camera.viewport.canvasSize! / 2);
await addAll(
[
Kicker(side: BoardSide.left)
..initialPosition = Vector2(center.x - 8.8, center.y),
Kicker(side: BoardSide.right)
..initialPosition = Vector2(center.x + 8.8, center.y),
],
);
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/bottom_group/kicker_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/bottom_group/kicker_game.dart",
"repo_id": "pinball",
"token_count": 461
} | 1,117 |
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/flutter_forest/dash_bumper_a_game.dart';
import 'package:sandbox/stories/flutter_forest/dash_bumper_b_game.dart';
import 'package:sandbox/stories/flutter_forest/dash_bumper_main_game.dart';
import 'package:sandbox/stories/flutter_forest/signpost_game.dart';
void addFlutterForestStories(Dashbook dashbook) {
dashbook.storiesOf('Flutter Forest')
..addGame(
title: 'Signpost',
description: SignpostGame.description,
gameBuilder: (_) => SignpostGame(),
)
..addGame(
title: 'Main Dash Bumper',
description: DashBumperMainGame.description,
gameBuilder: (_) => DashBumperMainGame(),
)
..addGame(
title: 'Dash Bumper A',
description: DashBumperAGame.description,
gameBuilder: (_) => DashBumperAGame(),
)
..addGame(
title: 'Dash Bumper B',
description: DashBumperBGame.description,
gameBuilder: (_) => DashBumperBGame(),
);
}
| pinball/packages/pinball_components/sandbox/lib/stories/flutter_forest/stories.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/flutter_forest/stories.dart",
"repo_id": "pinball",
"token_count": 401
} | 1,118 |
import 'dart:async';
import 'package:flame/input.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class SparkyComputerGame extends BallGame {
static const description = '''
Shows how the SparkyComputer is rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a ball into the game.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
await images.loadAll([
Assets.images.sparky.computer.base.keyName,
Assets.images.sparky.computer.top.keyName,
Assets.images.sparky.computer.glow.keyName,
]);
camera.followVector2(Vector2(-10, -40));
await add(SparkyComputer());
await ready();
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/sparky_scorch/sparky_computer_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/sparky_scorch/sparky_computer_game.dart",
"repo_id": "pinball",
"token_count": 290
} | 1,119 |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/android_bumper/behaviors/behaviors.dart';
import 'package:pinball_components/src/components/bumping_behavior.dart';
import '../../../helpers/helpers.dart';
class _MockAndroidBumperCubit extends Mock implements AndroidBumperCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.android.bumper.a.lit.keyName,
Assets.images.android.bumper.a.dimmed.keyName,
Assets.images.android.bumper.b.lit.keyName,
Assets.images.android.bumper.b.dimmed.keyName,
Assets.images.android.bumper.cow.lit.keyName,
Assets.images.android.bumper.cow.dimmed.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('AndroidBumper', () {
flameTester.test('"a" loads correctly', (game) async {
final androidBumper = AndroidBumper.a();
await game.ensureAdd(androidBumper);
expect(game.contains(androidBumper), isTrue);
});
flameTester.test('"b" loads correctly', (game) async {
final androidBumper = AndroidBumper.b();
await game.ensureAdd(androidBumper);
expect(game.contains(androidBumper), isTrue);
});
flameTester.test('"cow" loads correctly', (game) async {
final androidBumper = AndroidBumper.cow();
await game.ensureAdd(androidBumper);
expect(game.contains(androidBumper), isTrue);
});
flameTester.test('closes bloc when removed', (game) async {
final bloc = _MockAndroidBumperCubit();
whenListen(
bloc,
const Stream<AndroidBumperState>.empty(),
initialState: AndroidBumperState.lit,
);
when(bloc.close).thenAnswer((_) async {});
final androidBumper = AndroidBumper.test(bloc: bloc);
await game.ensureAdd(androidBumper);
game.remove(androidBumper);
await game.ready();
verify(bloc.close).called(1);
});
group('adds', () {
flameTester.test('an AndroidBumperBallContactBehavior', (game) async {
final androidBumper = AndroidBumper.a();
await game.ensureAdd(androidBumper);
expect(
androidBumper.children
.whereType<AndroidBumperBallContactBehavior>()
.single,
isNotNull,
);
});
flameTester.test('an AndroidBumperBlinkingBehavior', (game) async {
final androidBumper = AndroidBumper.a();
await game.ensureAdd(androidBumper);
expect(
androidBumper.children
.whereType<AndroidBumperBlinkingBehavior>()
.single,
isNotNull,
);
});
});
group("'a' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final androidBumper = AndroidBumper.a(
children: [component],
);
await game.ensureAdd(androidBumper);
expect(androidBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final androidBumper = AndroidBumper.a();
await game.ensureAdd(androidBumper);
expect(
androidBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
group("'b' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final androidBumper = AndroidBumper.b(
children: [component],
);
await game.ensureAdd(androidBumper);
expect(androidBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final androidBumper = AndroidBumper.b();
await game.ensureAdd(androidBumper);
expect(
androidBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
group("'cow' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final androidBumper = AndroidBumper.cow(
children: [component],
);
await game.ensureAdd(androidBumper);
expect(androidBumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final androidBumper = AndroidBumper.cow();
await game.ensureAdd(androidBumper);
expect(
androidBumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
});
}
| pinball/packages/pinball_components/test/src/components/android_bumper/android_bumper_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/android_bumper/android_bumper_test.dart",
"repo_id": "pinball",
"token_count": 1986
} | 1,120 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_theme/pinball_theme.dart';
void main() {
group('BallState', () {
test('supports value equality', () {
expect(
BallState(characterTheme: DashTheme()),
equals(const BallState(characterTheme: DashTheme())),
);
});
group('constructor', () {
test('can be instantiated', () {
expect(const BallState(characterTheme: DashTheme()), isNotNull);
});
});
});
}
| pinball/packages/pinball_components/test/src/components/ball/cubit/ball_state_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/ball/cubit/ball_state_test.dart",
"repo_id": "pinball",
"token_count": 226
} | 1,121 |
// ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_theme/pinball_theme.dart' as theme;
import '../../../helpers/helpers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.flipper.left.keyName,
Assets.images.flipper.right.keyName,
theme.Assets.images.dash.ball.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('Flipper', () {
flameTester.testGameWidget(
'renders correctly',
setUp: (game, tester) async {
await game.images.loadAll(assets);
final leftFlipper = Flipper(
side: BoardSide.left,
)..initialPosition = Vector2(-10, 0);
final rightFlipper = Flipper(
side: BoardSide.right,
)..initialPosition = Vector2(10, 0);
await game.ensureAddAll([leftFlipper, rightFlipper]);
game.camera.followVector2(Vector2.zero());
await tester.pump();
},
verify: (game, tester) async {
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('../golden/flipper.png'),
);
},
);
flameTester.test(
'loads correctly',
(game) async {
final leftFlipper = Flipper(side: BoardSide.left);
final rightFlipper = Flipper(side: BoardSide.right);
await game.ready();
await game.ensureAddAll([leftFlipper, rightFlipper]);
expect(game.contains(leftFlipper), isTrue);
expect(game.contains(rightFlipper), isTrue);
},
);
group('constructor', () {
test('sets BoardSide', () {
final leftFlipper = Flipper(side: BoardSide.left);
expect(leftFlipper.side, equals(leftFlipper.side));
final rightFlipper = Flipper(side: BoardSide.right);
expect(rightFlipper.side, equals(rightFlipper.side));
});
});
group('body', () {
flameTester.test(
'is dynamic',
(game) async {
final flipper = Flipper(side: BoardSide.left);
await game.ensureAdd(flipper);
expect(flipper.body.bodyType, equals(BodyType.dynamic));
},
);
flameTester.test(
'ignores gravity',
(game) async {
final flipper = Flipper(side: BoardSide.left);
await game.ensureAdd(flipper);
expect(flipper.body.gravityScale, equals(Vector2.zero()));
},
);
flameTester.test(
'has greater mass than Ball',
(game) async {
final flipper = Flipper(side: BoardSide.left);
final ball = Ball();
await game.ready();
await game.ensureAddAll([flipper, ball]);
expect(
flipper.body.getMassData().mass,
greaterThan(ball.body.getMassData().mass),
);
},
);
});
group('fixtures', () {
flameTester.test(
'has three',
(game) async {
final flipper = Flipper(side: BoardSide.left);
await game.ensureAdd(flipper);
expect(flipper.body.fixtures.length, equals(3));
},
);
flameTester.test(
'has density',
(game) async {
final flipper = Flipper(side: BoardSide.left);
await game.ensureAdd(flipper);
final fixtures = flipper.body.fixtures;
final density = fixtures.fold<double>(
0,
(sum, fixture) => sum + fixture.density,
);
expect(density, greaterThan(0));
},
);
});
});
}
| pinball/packages/pinball_components/test/src/components/flipper/flipper_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/flipper/flipper_test.dart",
"repo_id": "pinball",
"token_count": 1692
} | 1,122 |
// ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/layer_sensor/behaviors/behaviors.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../../helpers/helpers.dart';
class TestLayerSensor extends LayerSensor {
TestLayerSensor({
required LayerEntranceOrientation orientation,
required int insideZIndex,
required Layer insideLayer,
}) : super(
insideLayer: insideLayer,
insideZIndex: insideZIndex,
orientation: orientation,
);
@override
Shape get shape => PolygonShape()..setAsBoxXY(1, 1);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
const insidePriority = 1;
group('LayerSensor', () {
flameTester.test(
'loads correctly',
(game) async {
final layerSensor = TestLayerSensor(
orientation: LayerEntranceOrientation.down,
insideZIndex: insidePriority,
insideLayer: Layer.spaceshipEntranceRamp,
);
await game.ensureAdd(layerSensor);
expect(game.contains(layerSensor), isTrue);
},
);
group('body', () {
flameTester.test(
'is static',
(game) async {
final layerSensor = TestLayerSensor(
orientation: LayerEntranceOrientation.down,
insideZIndex: insidePriority,
insideLayer: Layer.spaceshipEntranceRamp,
);
await game.ensureAdd(layerSensor);
expect(layerSensor.body.bodyType, equals(BodyType.static));
},
);
group('first fixture', () {
const pathwayLayer = Layer.spaceshipEntranceRamp;
const openingLayer = Layer.opening;
flameTester.test(
'exists',
(game) async {
final layerSensor = TestLayerSensor(
orientation: LayerEntranceOrientation.down,
insideZIndex: insidePriority,
insideLayer: pathwayLayer,
)..layer = openingLayer;
await game.ensureAdd(layerSensor);
expect(layerSensor.body.fixtures[0], isA<Fixture>());
},
);
flameTester.test(
'shape is a polygon',
(game) async {
final layerSensor = TestLayerSensor(
orientation: LayerEntranceOrientation.down,
insideZIndex: insidePriority,
insideLayer: pathwayLayer,
)..layer = openingLayer;
await game.ensureAdd(layerSensor);
final fixture = layerSensor.body.fixtures[0];
expect(fixture.shape.shapeType, equals(ShapeType.polygon));
},
);
flameTester.test(
'is sensor',
(game) async {
final layerSensor = TestLayerSensor(
orientation: LayerEntranceOrientation.down,
insideZIndex: insidePriority,
insideLayer: pathwayLayer,
)..layer = openingLayer;
await game.ensureAdd(layerSensor);
final fixture = layerSensor.body.fixtures[0];
expect(fixture.isSensor, isTrue);
},
);
});
});
flameTester.test(
'adds a LayerFilteringBehavior',
(game) async {
final layerSensor = TestLayerSensor(
orientation: LayerEntranceOrientation.down,
insideZIndex: insidePriority,
insideLayer: Layer.spaceshipEntranceRamp,
);
await game.ensureAdd(layerSensor);
expect(
layerSensor.children.whereType<LayerFilteringBehavior>().length,
equals(1),
);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/layer_sensor/layer_sensor_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/layer_sensor/layer_sensor_test.dart",
"repo_id": "pinball",
"token_count": 1713
} | 1,123 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/score_component/behaviors/behaviors.dart';
import '../../../../helpers/helpers.dart';
void main() {
group('ScoreComponentScalingBehavior', () {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(
() => TestGame([
Assets.images.score.fiveThousand.keyName,
Assets.images.score.twentyThousand.keyName,
Assets.images.score.twoHundredThousand.keyName,
Assets.images.score.oneMillion.keyName,
]),
);
test('can be instantiated', () {
expect(
ScoreComponentScalingBehavior(),
isA<ScoreComponentScalingBehavior>(),
);
});
flameTester.test('can be loaded', (game) async {
final parent = ScoreComponent.test(
points: Points.fiveThousand,
position: Vector2.zero(),
effectController: EffectController(duration: 1),
);
final behavior = ScoreComponentScalingBehavior();
await game.ensureAdd(parent);
await parent.ensureAdd(behavior);
expect(parent.children, contains(behavior));
});
flameTester.test(
'scales the sprite',
(game) async {
final parent1 = ScoreComponent.test(
points: Points.fiveThousand,
position: Vector2(0, 10),
effectController: EffectController(duration: 1),
);
final parent2 = ScoreComponent.test(
points: Points.fiveThousand,
position: Vector2(0, -10),
effectController: EffectController(duration: 1),
);
await game.ensureAddAll([parent1, parent2]);
await parent1.ensureAdd(ScoreComponentScalingBehavior());
await parent2.ensureAdd(ScoreComponentScalingBehavior());
game.update(1);
expect(
parent1.scale.x,
greaterThan(parent2.scale.x),
);
expect(
parent1.scale.y,
greaterThan(parent2.scale.y),
);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/score_component/behaviors/score_component_scaling_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/score_component/behaviors/score_component_scaling_behavior_test.dart",
"repo_id": "pinball",
"token_count": 936
} | 1,124 |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/sparky_bumper/behaviors/behaviors.dart';
import '../../../../helpers/helpers.dart';
class _MockSparkyBumperCubit extends Mock implements SparkyBumperCubit {}
class _MockBall extends Mock implements Ball {}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
group(
'SparkyBumperBallContactBehavior',
() {
test('can be instantiated', () {
expect(
SparkyBumperBallContactBehavior(),
isA<SparkyBumperBallContactBehavior>(),
);
});
flameTester.test(
'beginContact emits onBallContacted when contacts with a ball',
(game) async {
final behavior = SparkyBumperBallContactBehavior();
final bloc = _MockSparkyBumperCubit();
whenListen(
bloc,
const Stream<SparkyBumperState>.empty(),
initialState: SparkyBumperState.lit,
);
final sparkyBumper = SparkyBumper.test(bloc: bloc);
await sparkyBumper.add(behavior);
await game.ensureAdd(sparkyBumper);
behavior.beginContact(_MockBall(), _MockContact());
verify(sparkyBumper.bloc.onBallContacted).called(1);
},
);
},
);
}
| pinball/packages/pinball_components/test/src/components/sparky_bumper/behaviors/sparky_bumper_ball_contact_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/sparky_bumper/behaviors/sparky_bumper_ball_contact_behavior_test.dart",
"repo_id": "pinball",
"token_count": 694
} | 1,125 |
export 'canvas_component.dart';
export 'z_canvas_component.dart';
| pinball/packages/pinball_flame/lib/src/canvas/canvas.dart/0 | {
"file_path": "pinball/packages/pinball_flame/lib/src/canvas/canvas.dart",
"repo_id": "pinball",
"token_count": 24
} | 1,126 |
// ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestBodyComponent extends BodyComponent {
@override
Body createBody() => world.createBody(BodyDef());
}
class _TestContactBehavior extends ContactBehavior {
int beginContactCallsCount = 0;
@override
void beginContact(Object other, Contact contact) {
beginContactCallsCount++;
super.beginContact(other, contact);
}
int endContactCallsCount = 0;
@override
void endContact(Object other, Contact contact) {
endContactCallsCount++;
super.endContact(other, contact);
}
int preSolveContactCallsCount = 0;
@override
void preSolve(Object other, Contact contact, Manifold oldManifold) {
preSolveContactCallsCount++;
super.preSolve(other, contact, oldManifold);
}
int postSolveContactCallsCount = 0;
@override
void postSolve(Object other, Contact contact, ContactImpulse impulse) {
postSolveContactCallsCount++;
super.postSolve(other, contact, impulse);
}
}
class _MockContactCallbacks extends Mock implements ContactCallbacks {}
class _MockContact extends Mock implements Contact {}
class _MockManifold extends Mock implements Manifold {}
class _MockContactImpulse extends Mock implements ContactImpulse {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(Forge2DGame.new);
group('ContactBehavior', () {
late Object other;
late Contact contact;
late Manifold manifold;
late ContactImpulse contactImpulse;
late FixtureDef fixtureDef;
setUp(() {
other = Object();
contact = _MockContact();
manifold = _MockManifold();
contactImpulse = _MockContactImpulse();
fixtureDef = FixtureDef(CircleShape());
});
flameTester.test(
"should add a new ContactCallbacks to the parent's body userData "
'when not applied to fixtures',
(game) async {
final parent = _TestBodyComponent();
final contactBehavior = ContactBehavior();
await parent.add(contactBehavior);
await game.ensureAdd(parent);
expect(parent.body.userData, isA<ContactCallbacks>());
},
);
flameTester.test(
'should add a new ContactCallbacks to the targeted fixture ',
(game) async {
final parent = _TestBodyComponent();
await game.ensureAdd(parent);
final fixture1 =
parent.body.createFixture(fixtureDef..userData = 'foo');
final fixture2 = parent.body.createFixture(fixtureDef..userData = null);
final contactBehavior = ContactBehavior()
..applyTo(
[fixture1.userData!],
);
await parent.ensureAdd(contactBehavior);
expect(parent.body.userData, isNull);
expect(fixture1.userData, isA<ContactCallbacks>());
expect(fixture2.userData, isNull);
},
);
flameTester.test(
'should add a new ContactCallbacks to the targeted fixtures ',
(game) async {
final parent = _TestBodyComponent();
await game.ensureAdd(parent);
final fixture1 =
parent.body.createFixture(fixtureDef..userData = 'foo');
final fixture2 =
parent.body.createFixture(fixtureDef..userData = 'boo');
final contactBehavior = ContactBehavior()
..applyTo([
fixture1.userData!,
fixture2.userData!,
]);
await parent.ensureAdd(contactBehavior);
expect(parent.body.userData, isNull);
expect(fixture1.userData, isA<ContactCallbacks>());
expect(fixture2.userData, isA<ContactCallbacks>());
},
);
flameTester.test(
"should respect the previous ContactCallbacks in the parent's userData "
'when not applied to fixtures',
(game) async {
final parent = _TestBodyComponent();
await game.ensureAdd(parent);
final contactCallbacks1 = _MockContactCallbacks();
parent.body.userData = contactCallbacks1;
final contactBehavior = ContactBehavior();
await parent.ensureAdd(contactBehavior);
final contactCallbacks = parent.body.userData! as ContactCallbacks;
contactCallbacks.beginContact(other, contact);
verify(
() => contactCallbacks1.beginContact(other, contact),
).called(1);
contactCallbacks.endContact(other, contact);
verify(
() => contactCallbacks1.endContact(other, contact),
).called(1);
contactCallbacks.preSolve(other, contact, manifold);
verify(
() => contactCallbacks1.preSolve(other, contact, manifold),
).called(1);
contactCallbacks.postSolve(other, contact, contactImpulse);
verify(
() => contactCallbacks1.postSolve(other, contact, contactImpulse),
).called(1);
},
);
flameTester.test(
'can group multiple ContactBehaviors and keep listening',
(game) async {
final parent = _TestBodyComponent();
await game.ensureAdd(parent);
final contactBehavior1 = _TestContactBehavior();
final contactBehavior2 = _TestContactBehavior();
final contactBehavior3 = _TestContactBehavior();
await parent.ensureAddAll([
contactBehavior1,
contactBehavior2,
contactBehavior3,
]);
final contactCallbacks = parent.body.userData! as ContactCallbacks;
contactCallbacks.beginContact(other, contact);
expect(contactBehavior1.beginContactCallsCount, equals(1));
expect(contactBehavior2.beginContactCallsCount, equals(1));
expect(contactBehavior3.beginContactCallsCount, equals(1));
contactCallbacks.endContact(other, contact);
expect(contactBehavior1.endContactCallsCount, equals(1));
expect(contactBehavior2.endContactCallsCount, equals(1));
expect(contactBehavior3.endContactCallsCount, equals(1));
contactCallbacks.preSolve(other, contact, manifold);
expect(contactBehavior1.preSolveContactCallsCount, equals(1));
expect(contactBehavior2.preSolveContactCallsCount, equals(1));
expect(contactBehavior3.preSolveContactCallsCount, equals(1));
contactCallbacks.postSolve(other, contact, contactImpulse);
expect(contactBehavior1.postSolveContactCallsCount, equals(1));
expect(contactBehavior2.postSolveContactCallsCount, equals(1));
expect(contactBehavior3.postSolveContactCallsCount, equals(1));
},
);
flameTester.test(
'can group multiple ContactBehaviors and keep listening '
'when applied to a fixture',
(game) async {
final parent = _TestBodyComponent();
await game.ensureAdd(parent);
final fixture = parent.body.createFixture(fixtureDef..userData = 'foo');
final contactBehavior1 = _TestContactBehavior()
..applyTo(
[fixture.userData!],
);
final contactBehavior2 = _TestContactBehavior()
..applyTo(
[fixture.userData!],
);
final contactBehavior3 = _TestContactBehavior()
..applyTo(
[fixture.userData!],
);
await parent.ensureAddAll([
contactBehavior1,
contactBehavior2,
contactBehavior3,
]);
final contactCallbacks = fixture.userData! as ContactCallbacks;
contactCallbacks.beginContact(other, contact);
expect(contactBehavior1.beginContactCallsCount, equals(1));
expect(contactBehavior2.beginContactCallsCount, equals(1));
expect(contactBehavior3.beginContactCallsCount, equals(1));
contactCallbacks.endContact(other, contact);
expect(contactBehavior1.endContactCallsCount, equals(1));
expect(contactBehavior2.endContactCallsCount, equals(1));
expect(contactBehavior3.endContactCallsCount, equals(1));
contactCallbacks.preSolve(other, contact, manifold);
expect(contactBehavior1.preSolveContactCallsCount, equals(1));
expect(contactBehavior2.preSolveContactCallsCount, equals(1));
expect(contactBehavior3.preSolveContactCallsCount, equals(1));
contactCallbacks.postSolve(other, contact, contactImpulse);
expect(contactBehavior1.postSolveContactCallsCount, equals(1));
expect(contactBehavior2.postSolveContactCallsCount, equals(1));
expect(contactBehavior3.postSolveContactCallsCount, equals(1));
},
);
});
}
| pinball/packages/pinball_flame/test/src/behaviors/contact_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_flame/test/src/behaviors/contact_behavior_test.dart",
"repo_id": "pinball",
"token_count": 3380
} | 1,127 |
import 'package:flame/components.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _MockSpriteAnimationController extends Mock
implements SpriteAnimationController {}
class _MockSpriteAnimation extends Mock implements SpriteAnimation {}
class _MockSprite extends Mock implements Sprite {}
void main() {
group('PinballSpriteAnimationWidget', () {
late SpriteAnimationController controller;
late SpriteAnimation animation;
late Sprite sprite;
setUp(() {
controller = _MockSpriteAnimationController();
animation = _MockSpriteAnimation();
sprite = _MockSprite();
when(() => controller.animation).thenAnswer((_) => animation);
when(() => animation.totalDuration()).thenAnswer((_) => 1);
when(() => animation.getSprite()).thenAnswer((_) => sprite);
when(() => sprite.srcSize).thenAnswer((_) => Vector2(1, 1));
when(() => sprite.srcSize).thenAnswer((_) => Vector2(1, 1));
});
testWidgets('renders correctly', (tester) async {
await tester.pumpWidget(
SpriteAnimationWidget(
controller: controller,
),
);
await tester.pumpAndSettle();
await tester.pumpAndSettle();
expect(find.byType(SpriteAnimationWidget), findsOneWidget);
});
test('SpriteAnimationController is updating animations', () {
SpriteAnimationController(
vsync: const TestVSync(),
animation: animation,
).notifyListeners();
verify(() => animation.update(any())).called(1);
});
testWidgets('SpritePainter shouldRepaint returns true when Sprite changed',
(tester) async {
final spritePainter = SpritePainter(
sprite,
Anchor.center,
angle: 45,
);
final anotherPainter = SpritePainter(
sprite,
Anchor.center,
angle: 30,
);
expect(spritePainter.shouldRepaint(anotherPainter), isTrue);
});
});
}
| pinball/packages/pinball_flame/test/src/sprite_animation_test.dart/0 | {
"file_path": "pinball/packages/pinball_flame/test/src/sprite_animation_test.dart",
"repo_id": "pinball",
"token_count": 757
} | 1,128 |
import 'package:pinball_theme/pinball_theme.dart';
/// {@template dino_theme}
/// Defines Dino character theme assets and attributes.
/// {@endtemplate}
class DinoTheme extends CharacterTheme {
/// {@macro dino_theme}
const DinoTheme();
@override
String get name => 'Dino';
@override
AssetGenImage get ball => Assets.images.dino.ball;
@override
AssetGenImage get background => Assets.images.dino.background;
@override
AssetGenImage get icon => Assets.images.dino.icon;
@override
AssetGenImage get leaderboardIcon => Assets.images.dino.leaderboardIcon;
@override
AssetGenImage get animation => Assets.images.dino.animation;
}
| pinball/packages/pinball_theme/lib/src/themes/dino_theme.dart/0 | {
"file_path": "pinball/packages/pinball_theme/lib/src/themes/dino_theme.dart",
"repo_id": "pinball",
"token_count": 205
} | 1,129 |
import 'dart:async';
import 'package:flutter/material.dart';
/// {@template animated_ellipsis_text}
/// Every 500 milliseconds, it will add a new `.` at the end of the given
/// [text]. Once 3 `.` have been added (e.g. `Loading...`), it will reset to
/// zero ellipsis and start over again.
/// {@endtemplate}
class AnimatedEllipsisText extends StatefulWidget {
/// {@macro animated_ellipsis_text}
const AnimatedEllipsisText(
this.text, {
Key? key,
this.style,
}) : super(key: key);
/// The text that will be animated.
final String text;
/// Optional [TextStyle] of the given [text].
final TextStyle? style;
@override
State<StatefulWidget> createState() => _AnimatedEllipsisText();
}
class _AnimatedEllipsisText extends State<AnimatedEllipsisText>
with SingleTickerProviderStateMixin {
late final Timer timer;
var _numberOfEllipsis = 0;
@override
void initState() {
super.initState();
timer = Timer.periodic(const Duration(milliseconds: 500), (_) {
setState(() {
_numberOfEllipsis++;
_numberOfEllipsis = _numberOfEllipsis % 4;
});
});
}
@override
void dispose() {
if (timer.isActive) timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Text(
'${widget.text}${_numberOfEllipsis.toEllipsis()}',
style: widget.style,
);
}
}
extension on int {
String toEllipsis() => '.' * this;
}
| pinball/packages/pinball_ui/lib/src/widgets/animated_ellipsis_text.dart/0 | {
"file_path": "pinball/packages/pinball_ui/lib/src/widgets/animated_ellipsis_text.dart",
"repo_id": "pinball",
"token_count": 535
} | 1,130 |
// ignore_for_file: one_member_abstracts
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_ui/gen/gen.dart';
import 'package:pinball_ui/pinball_ui.dart';
extension _WidgetTesterX on WidgetTester {
Future<void> pumpButton({
required PinballDpadDirection direction,
required VoidCallback onTap,
}) async {
await pumpWidget(
MaterialApp(
home: Scaffold(
body: PinballDpadButton(
direction: direction,
onTap: onTap,
),
),
),
);
}
}
extension _CommonFindersX on CommonFinders {
Finder byImagePath(String path) {
return find.byWidgetPredicate(
(widget) {
if (widget is Image) {
final image = widget.image;
if (image is AssetImage) {
return image.keyName == path;
}
return false;
}
return false;
},
);
}
}
abstract class _VoidCallbackStubBase {
void onCall();
}
class _VoidCallbackStub extends Mock implements _VoidCallbackStubBase {}
void main() {
group('PinballDpadButton', () {
testWidgets('can be tapped', (tester) async {
final stub = _VoidCallbackStub();
await tester.pumpButton(
direction: PinballDpadDirection.up,
onTap: stub.onCall,
);
await tester.tap(find.byType(Image));
verify(stub.onCall).called(1);
});
group('up', () {
testWidgets('renders the correct image', (tester) async {
await tester.pumpButton(
direction: PinballDpadDirection.up,
onTap: () {},
);
expect(
find.byImagePath(Assets.images.button.dpadUp.keyName),
findsOneWidget,
);
});
});
group('down', () {
testWidgets('renders the correct image', (tester) async {
await tester.pumpButton(
direction: PinballDpadDirection.down,
onTap: () {},
);
expect(
find.byImagePath(Assets.images.button.dpadDown.keyName),
findsOneWidget,
);
});
});
group('left', () {
testWidgets('renders the correct image', (tester) async {
await tester.pumpButton(
direction: PinballDpadDirection.left,
onTap: () {},
);
expect(
find.byImagePath(Assets.images.button.dpadLeft.keyName),
findsOneWidget,
);
});
});
group('right', () {
testWidgets('renders the correct image', (tester) async {
await tester.pumpButton(
direction: PinballDpadDirection.right,
onTap: () {},
);
expect(
find.byImagePath(Assets.images.button.dpadRight.keyName),
findsOneWidget,
);
});
});
});
}
| pinball/packages/pinball_ui/test/src/widgets/pinball_dpad_button_test.dart/0 | {
"file_path": "pinball/packages/pinball_ui/test/src/widgets/pinball_dpad_button_test.dart",
"repo_id": "pinball",
"token_count": 1318
} | 1,131 |
name: share_repository
description: Repository to facilitate sharing scores.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.16.0 <3.0.0"
dev_dependencies:
coverage: ^1.1.0
mocktail: ^0.2.0
test: ^1.19.2
very_good_analysis: ^2.4.0
| pinball/packages/share_repository/pubspec.yaml/0 | {
"file_path": "pinball/packages/share_repository/pubspec.yaml",
"repo_id": "pinball",
"token_count": 111
} | 1,132 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/game/components/backbox/bloc/backbox_bloc.dart';
import 'package:pinball_theme/pinball_theme.dart';
void main() {
group('BackboxState', () {
group('LoadingState', () {
test('can be instantiated', () {
expect(LoadingState(), isNotNull);
});
test('supports value comparison', () {
expect(LoadingState(), equals(LoadingState()));
});
});
group('LeaderboardSuccessState', () {
test('can be instantiated', () {
expect(
LeaderboardSuccessState(entries: const []),
isNotNull,
);
});
test('supports value comparison', () {
expect(
LeaderboardSuccessState(entries: const []),
equals(
LeaderboardSuccessState(entries: const []),
),
);
expect(
LeaderboardSuccessState(entries: const []),
isNot(
equals(
LeaderboardSuccessState(
entries: const [LeaderboardEntryData.empty],
),
),
),
);
});
});
group('LeaderboardFailureState', () {
test('can be instantiated', () {
expect(LeaderboardFailureState(), isNotNull);
});
test('supports value comparison', () {
expect(LeaderboardFailureState(), equals(LeaderboardFailureState()));
});
});
group('InitialsFormState', () {
test('can be instantiated', () {
expect(
InitialsFormState(
score: 0,
character: AndroidTheme(),
),
isNotNull,
);
});
test('supports value comparison', () {
expect(
InitialsFormState(
score: 0,
character: AndroidTheme(),
),
equals(
InitialsFormState(
score: 0,
character: AndroidTheme(),
),
),
);
expect(
InitialsFormState(
score: 0,
character: AndroidTheme(),
),
isNot(
equals(
InitialsFormState(
score: 1,
character: AndroidTheme(),
),
),
),
);
expect(
InitialsFormState(
score: 0,
character: AndroidTheme(),
),
isNot(
equals(
InitialsFormState(
score: 0,
character: SparkyTheme(),
),
),
),
);
});
});
group('InitialsSuccessState', () {
test('can be instantiated', () {
expect(
InitialsSuccessState(score: 0),
isNotNull,
);
});
test('supports value comparison', () {
expect(
InitialsSuccessState(score: 0),
equals(
InitialsSuccessState(score: 0),
),
);
});
group('InitialsFailureState', () {
test('can be instantiated', () {
expect(
InitialsFailureState(
score: 10,
character: AndroidTheme(),
),
isNotNull,
);
});
test('supports value comparison', () {
expect(
InitialsFailureState(
score: 10,
character: AndroidTheme(),
),
equals(
InitialsFailureState(
score: 10,
character: AndroidTheme(),
),
),
);
expect(
InitialsFailureState(
score: 10,
character: AndroidTheme(),
),
isNot(
equals(
InitialsFailureState(
score: 12,
character: AndroidTheme(),
),
),
),
);
expect(
InitialsFailureState(
score: 10,
character: AndroidTheme(),
),
isNot(
equals(
InitialsFailureState(
score: 10,
character: DashTheme(),
),
),
),
);
});
});
group('ShareState', () {
test('can be instantiated', () {
expect(
ShareState(score: 0),
isNotNull,
);
});
test('supports value comparison', () {
expect(
ShareState(score: 0),
equals(
ShareState(score: 0),
),
);
});
});
});
group('ShareState', () {
test('can be instantiated', () {
expect(
ShareState(score: 0),
isNotNull,
);
});
test('supports value comparison', () {
expect(
ShareState(score: 0),
equals(
ShareState(score: 0),
),
);
});
});
});
}
| pinball/test/game/components/backbox/bloc/backbox_state_test.dart/0 | {
"file_path": "pinball/test/game/components/backbox/bloc/backbox_state_test.dart",
"repo_id": "pinball",
"token_count": 2847
} | 1,133 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_theme/pinball_theme.dart' as theme;
import 'package:platform_helper/platform_helper.dart';
import 'package:share_repository/share_repository.dart';
class _TestGame extends Forge2DGame with HasTappables {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll(
[
const theme.DashTheme().leaderboardIcon.keyName,
Assets.images.backbox.marquee.keyName,
Assets.images.backbox.displayDivider.keyName,
Assets.images.displayArrows.arrowLeft.keyName,
Assets.images.displayArrows.arrowRight.keyName,
],
);
}
Future<void> pump(
Iterable<Component> children, {
PinballAudioPlayer? pinballAudioPlayer,
GoogleWordCubit? googleWordBloc,
DashBumpersCubit? dashBumpersBloc,
SignpostCubit? signpostBloc,
}) async {
return ensureAdd(
FlameMultiBlocProvider(
providers: [
FlameBlocProvider<GameBloc, GameState>.value(
value: GameBloc(),
),
FlameBlocProvider<CharacterThemeCubit, CharacterThemeState>.value(
value: CharacterThemeCubit(),
),
FlameBlocProvider<GoogleWordCubit, GoogleWordState>.value(
value: googleWordBloc ?? GoogleWordCubit(),
),
FlameBlocProvider<DashBumpersCubit, DashBumpersState>.value(
value: dashBumpersBloc ?? DashBumpersCubit(),
),
FlameBlocProvider<SignpostCubit, SignpostState>.value(
value: signpostBloc ?? SignpostCubit(),
),
],
children: [
MultiFlameProvider(
providers: [
FlameProvider<PinballAudioPlayer>.value(
pinballAudioPlayer ?? _MockPinballAudioPlayer(),
),
FlameProvider<AppLocalizations>.value(
_MockAppLocalizations(),
),
FlameProvider<PlatformHelper>.value(
PlatformHelper(),
),
],
children: children,
),
],
),
);
}
}
class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {}
class _MockLeaderboardRepository extends Mock implements LeaderboardRepository {
}
class _MockShareRepository extends Mock implements ShareRepository {}
class _MockPlungerCubit extends Mock implements PlungerCubit {}
class _MockGoogleWordCubit extends Mock implements GoogleWordCubit {}
class _MockDashBumpersCubit extends Mock implements DashBumpersCubit {}
class _MockSignpostCubit extends Mock implements SignpostCubit {}
class _MockFlipperCubit extends Mock implements FlipperCubit {}
class _MockAppLocalizations extends Mock implements AppLocalizations {
@override
String get score => '';
@override
String get name => '';
@override
String get rank => '';
@override
String get enterInitials => '';
@override
String get arrows => '';
@override
String get andPress => '';
@override
String get enterReturn => '';
@override
String get toSubmit => '';
@override
String get loading => '';
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('GameBlocStatusListener', () {
test('can be instantiated', () {
expect(
GameBlocStatusListener(),
isA<GameBlocStatusListener>(),
);
});
final flameTester = FlameTester(_TestGame.new);
flameTester.test(
'can be loaded',
(game) async {
final component = GameBlocStatusListener();
await game.pump([component]);
expect(game.descendants(), contains(component));
},
);
group('listenWhen', () {
test('is true when the game over state has changed', () {
const state = GameState(
totalScore: 0,
roundScore: 10,
multiplier: 1,
rounds: 0,
bonusHistory: [],
status: GameStatus.playing,
);
const previous = GameState.initial();
expect(
GameBlocStatusListener().listenWhen(previous, state),
isTrue,
);
});
});
group('onNewState', () {
group('on game over', () {
late GameState state;
setUp(() {
state = const GameState.initial().copyWith(
status: GameStatus.gameOver,
);
});
flameTester.test(
'changes the backbox display',
(game) async {
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
await game.pump([component, backbox]);
expect(() => component.onNewState(state), returnsNormally);
},
);
flameTester.test(
'removes FlipperKeyControllingBehavior from Flipper',
(game) async {
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
final flipper = Flipper.test(side: BoardSide.left);
final behavior = FlipperKeyControllingBehavior();
await game.pump([component, backbox, flipper]);
await flipper.ensureAdd(
FlameBlocProvider<FlipperCubit, FlipperState>(
create: _MockFlipperCubit.new,
children: [behavior],
),
);
expect(state.status, GameStatus.gameOver);
component.onNewState(state);
await game.ready();
expect(
flipper.children.whereType<FlipperKeyControllingBehavior>(),
isEmpty,
);
},
);
flameTester.test(
'removes PlungerKeyControllingBehavior from Plunger',
(game) async {
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
final plunger = Plunger.test();
await game.pump(
[component, backbox, plunger],
);
await plunger.ensureAdd(
FlameBlocProvider<PlungerCubit, PlungerState>(
create: PlungerCubit.new,
children: [PlungerKeyControllingBehavior()],
),
);
expect(state.status, GameStatus.gameOver);
component.onNewState(state);
await game.ready();
expect(
plunger.children.whereType<PlungerKeyControllingBehavior>(),
isEmpty,
);
},
);
flameTester.test(
'removes PlungerPullingBehavior from Plunger',
(game) async {
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
final plunger = Plunger.test();
await game.pump(
[component, backbox, plunger],
);
await plunger.ensureAdd(
FlameBlocProvider<PlungerCubit, PlungerState>(
create: PlungerCubit.new,
children: [
PlungerPullingBehavior(strength: 0),
PlungerAutoPullingBehavior()
],
),
);
expect(state.status, GameStatus.gameOver);
component.onNewState(state);
await game.ready();
expect(
plunger.children.whereType<PlungerPullingBehavior>(),
isEmpty,
);
},
);
flameTester.test(
'plays the game over voice over',
(game) async {
final audioPlayer = _MockPinballAudioPlayer();
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
await game.pump(
[component, backbox],
pinballAudioPlayer: audioPlayer,
);
component.onNewState(state);
verify(
() => audioPlayer.play(
PinballAudio.gameOverVoiceOver,
),
).called(1);
},
);
});
group('on playing', () {
late GameState state;
setUp(() {
state = const GameState.initial().copyWith(
status: GameStatus.playing,
);
});
flameTester.test(
'plays the background music on start',
(game) async {
final audioPlayer = _MockPinballAudioPlayer();
final component = GameBlocStatusListener();
await game.pump(
[component],
pinballAudioPlayer: audioPlayer,
);
expect(state.status, equals(GameStatus.playing));
component.onNewState(state);
verify(
() => audioPlayer.play(
PinballAudio.backgroundMusic,
),
).called(1);
},
);
flameTester.test(
'resets the GoogleWordCubit',
(game) async {
final googleWordBloc = _MockGoogleWordCubit();
final component = GameBlocStatusListener();
await game.pump(
[component],
googleWordBloc: googleWordBloc,
);
expect(state.status, equals(GameStatus.playing));
component.onNewState(state);
verify(googleWordBloc.onReset).called(1);
},
);
flameTester.test(
'resets the DashBumpersCubit',
(game) async {
final dashBumpersBloc = _MockDashBumpersCubit();
final component = GameBlocStatusListener();
await game.pump(
[component],
dashBumpersBloc: dashBumpersBloc,
);
expect(state.status, equals(GameStatus.playing));
component.onNewState(state);
verify(dashBumpersBloc.onReset).called(1);
},
);
flameTester.test(
'resets the SignpostCubit',
(game) async {
final signpostBloc = _MockSignpostCubit();
final component = GameBlocStatusListener();
await game.pump([component], signpostBloc: signpostBloc);
expect(state.status, equals(GameStatus.playing));
component.onNewState(state);
verify(signpostBloc.onReset).called(1);
},
);
flameTester.test(
'adds FlipperKeyControllingBehavior to Flippers',
(game) async {
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
final flipper = Flipper.test(side: BoardSide.left);
await game.pump([component, backbox, flipper]);
await flipper.ensureAdd(
FlameBlocProvider<FlipperCubit, FlipperState>(
create: _MockFlipperCubit.new,
),
);
component.onNewState(state);
await game.ready();
expect(
flipper
.descendants()
.whereType<FlipperKeyControllingBehavior>()
.length,
equals(1),
);
},
);
flameTester.test(
'adds PlungerKeyControllingBehavior to Plunger',
(game) async {
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
final plunger = Plunger.test();
await game.pump([component, backbox, plunger]);
await plunger.ensureAdd(
FlameBlocProvider<PlungerCubit, PlungerState>(
create: _MockPlungerCubit.new,
),
);
expect(state.status, GameStatus.playing);
component.onNewState(state);
await game.ready();
expect(
plunger
.descendants()
.whereType<PlungerKeyControllingBehavior>()
.length,
equals(1),
);
},
);
flameTester.test(
'adds PlungerPullingBehavior to Plunger',
(game) async {
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
final plunger = Plunger.test();
await game.pump([component, backbox, plunger]);
await plunger.ensureAdd(
FlameBlocProvider<PlungerCubit, PlungerState>(
create: _MockPlungerCubit.new,
),
);
expect(state.status, GameStatus.playing);
component.onNewState(state);
await game.ready();
expect(
plunger.descendants().whereType<PlungerPullingBehavior>().length,
equals(1),
);
},
);
flameTester.test(
'adds PlungerAutoPullingBehavior to Plunger',
(game) async {
final component = GameBlocStatusListener();
final leaderboardRepository = _MockLeaderboardRepository();
final shareRepository = _MockShareRepository();
final backbox = Backbox(
leaderboardRepository: leaderboardRepository,
shareRepository: shareRepository,
entries: const [],
);
final plunger = Plunger.test();
await game.pump([component, backbox, plunger]);
await plunger.ensureAdd(
FlameBlocProvider<PlungerCubit, PlungerState>(
create: _MockPlungerCubit.new,
),
);
expect(state.status, GameStatus.playing);
component.onNewState(state);
await game.ready();
expect(
plunger
.descendants()
.whereType<PlungerAutoPullingBehavior>()
.length,
equals(1),
);
},
);
});
});
});
}
| pinball/test/game/components/game_bloc_status_listener_test.dart/0 | {
"file_path": "pinball/test/game/components/game_bloc_status_listener_test.dart",
"repo_id": "pinball",
"token_count": 8094
} | 1,134 |
// ignore_for_file: one_member_abstracts
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_ui/pinball_ui.dart';
extension _WidgetTesterX on WidgetTester {
Future<void> pumpDpad({
required VoidCallback onTapUp,
required VoidCallback onTapDown,
required VoidCallback onTapLeft,
required VoidCallback onTapRight,
}) async {
await pumpWidget(
MaterialApp(
home: Scaffold(
body: MobileDpad(
onTapUp: onTapUp,
onTapDown: onTapDown,
onTapLeft: onTapLeft,
onTapRight: onTapRight,
),
),
),
);
}
}
extension _CommonFindersX on CommonFinders {
Finder byPinballDpadDirection(PinballDpadDirection direction) {
return byWidgetPredicate((widget) {
return widget is PinballDpadButton && widget.direction == direction;
});
}
}
abstract class _VoidCallbackStubBase {
void onCall();
}
class _VoidCallbackStub extends Mock implements _VoidCallbackStubBase {}
void main() {
group('MobileDpad', () {
testWidgets('renders correctly', (tester) async {
await tester.pumpDpad(
onTapUp: () {},
onTapDown: () {},
onTapLeft: () {},
onTapRight: () {},
);
expect(
find.byType(PinballDpadButton),
findsNWidgets(4),
);
});
testWidgets('can tap up', (tester) async {
final stub = _VoidCallbackStub();
await tester.pumpDpad(
onTapUp: stub.onCall,
onTapDown: () {},
onTapLeft: () {},
onTapRight: () {},
);
await tester.tap(find.byPinballDpadDirection(PinballDpadDirection.up));
verify(stub.onCall).called(1);
});
testWidgets('can tap down', (tester) async {
final stub = _VoidCallbackStub();
await tester.pumpDpad(
onTapUp: () {},
onTapDown: stub.onCall,
onTapLeft: () {},
onTapRight: () {},
);
await tester.tap(find.byPinballDpadDirection(PinballDpadDirection.down));
verify(stub.onCall).called(1);
});
testWidgets('can tap left', (tester) async {
final stub = _VoidCallbackStub();
await tester.pumpDpad(
onTapUp: () {},
onTapDown: () {},
onTapLeft: stub.onCall,
onTapRight: () {},
);
await tester.tap(find.byPinballDpadDirection(PinballDpadDirection.left));
verify(stub.onCall).called(1);
});
testWidgets('can tap left', (tester) async {
final stub = _VoidCallbackStub();
await tester.pumpDpad(
onTapUp: () {},
onTapDown: () {},
onTapLeft: () {},
onTapRight: stub.onCall,
);
await tester.tap(find.byPinballDpadDirection(PinballDpadDirection.right));
verify(stub.onCall).called(1);
});
});
}
| pinball/test/game/view/widgets/mobile_dpad_test.dart/0 | {
"file_path": "pinball/test/game/view/widgets/mobile_dpad_test.dart",
"repo_id": "pinball",
"token_count": 1320
} | 1,135 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/start_game/bloc/start_game_bloc.dart';
void main() {
group('StartGameState', () {
final testState = StartGameState(
status: StartGameStatus.selectCharacter,
);
test('initial state has correct values', () {
final state = StartGameState(
status: StartGameStatus.initial,
);
expect(state, StartGameState.initial());
});
test('supports value equality', () {
final secondState = StartGameState(
status: StartGameStatus.selectCharacter,
);
expect(testState, secondState);
});
group('copyWith', () {
test(
'copies correctly '
'when no argument specified',
() {
const state = StartGameState(
status: StartGameStatus.initial,
);
expect(
state.copyWith(),
equals(state),
);
},
);
test(
'copies correctly '
'when all arguments specified',
() {
const state = StartGameState(
status: StartGameStatus.initial,
);
final otherState = StartGameState(
status: StartGameStatus.play,
);
expect(state, isNot(equals(otherState)));
expect(
state.copyWith(
status: otherState.status,
),
equals(otherState),
);
},
);
});
test('has correct props', () {
expect(
testState.props,
equals([
StartGameStatus.selectCharacter,
]),
);
});
});
}
| pinball/test/start_game/bloc/start_game_state_test.dart/0 | {
"file_path": "pinball/test/start_game/bloc/start_game_state_test.dart",
"repo_id": "pinball",
"token_count": 789
} | 1,136 |
// 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;
/** Represents a point on an x/y axis. */
public class Point {
public final Double x;
public final Double y;
public Point(Double x, Double y) {
this.x = x;
this.y = y;
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/Point.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/Point.java",
"repo_id": "plugins",
"token_count": 126
} | 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.
package io.flutter.plugins.camera.features.sensororientation;
import android.app.Activity;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.DartMessenger;
import io.flutter.plugins.camera.features.CameraFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionFeature;
/** Provides access to the sensor orientation of the camera devices. */
public class SensorOrientationFeature extends CameraFeature<Integer> {
private Integer currentSetting = 0;
private final DeviceOrientationManager deviceOrientationListener;
private PlatformChannel.DeviceOrientation lockedCaptureOrientation;
/**
* Creates a new instance of the {@link ResolutionFeature}.
*
* @param cameraProperties Collection of characteristics for the current camera device.
* @param activity Current Android {@link android.app.Activity}, used to detect UI orientation
* changes.
* @param dartMessenger Instance of a {@link DartMessenger} used to communicate orientation
* updates back to the client.
*/
public SensorOrientationFeature(
@NonNull CameraProperties cameraProperties,
@NonNull Activity activity,
@NonNull DartMessenger dartMessenger) {
super(cameraProperties);
setValue(cameraProperties.getSensorOrientation());
boolean isFrontFacing = cameraProperties.getLensFacing() == CameraMetadata.LENS_FACING_FRONT;
deviceOrientationListener =
DeviceOrientationManager.create(activity, dartMessenger, isFrontFacing, currentSetting);
deviceOrientationListener.start();
}
@Override
public String getDebugName() {
return "SensorOrientationFeature";
}
@Override
public Integer getValue() {
return currentSetting;
}
@Override
public void setValue(Integer value) {
this.currentSetting = value;
}
@Override
public boolean checkIsSupported() {
return true;
}
@Override
public void updateBuilder(CaptureRequest.Builder requestBuilder) {
// Noop: when setting the sensor orientation there is no need to update the request builder.
}
/**
* Gets the instance of the {@link DeviceOrientationManager} used to detect orientation changes.
*
* @return The instance of the {@link DeviceOrientationManager}.
*/
public DeviceOrientationManager getDeviceOrientationManager() {
return this.deviceOrientationListener;
}
/**
* Lock the capture orientation, indicating that the device orientation should not influence the
* capture orientation.
*
* @param orientation The orientation in which to lock the capture orientation.
*/
public void lockCaptureOrientation(PlatformChannel.DeviceOrientation orientation) {
this.lockedCaptureOrientation = orientation;
}
/**
* Unlock the capture orientation, indicating that the device orientation should be used to
* configure the capture orientation.
*/
public void unlockCaptureOrientation() {
this.lockedCaptureOrientation = null;
}
/**
* Gets the configured locked capture orientation.
*
* @return The configured locked capture orientation.
*/
public PlatformChannel.DeviceOrientation getLockedCaptureOrientation() {
return this.lockedCaptureOrientation;
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/sensororientation/SensorOrientationFeature.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/sensororientation/SensorOrientationFeature.java",
"repo_id": "plugins",
"token_count": 1006
} | 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 io.flutter.plugins.camera;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
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 android.util.Size;
import io.flutter.plugins.camera.utils.TestUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.stubbing.Answer;
public class CameraRegionUtils_getCameraBoundariesTest {
Size mockCameraBoundaries;
@Before
public void setUp() {
this.mockCameraBoundaries = mock(Size.class);
when(this.mockCameraBoundaries.getWidth()).thenReturn(100);
when(this.mockCameraBoundaries.getHeight()).thenReturn(100);
}
@Test
public void getCameraBoundaries_shouldReturnSensorInfoPixelArraySizeWhenRunningPreAndroidP() {
updateSdkVersion(Build.VERSION_CODES.O_MR1);
try {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
when(mockCameraProperties.getSensorInfoPixelArraySize()).thenReturn(mockCameraBoundaries);
Size result = CameraRegionUtils.getCameraBoundaries(mockCameraProperties, mockBuilder);
assertEquals(mockCameraBoundaries, result);
verify(mockCameraProperties, never()).getSensorInfoPreCorrectionActiveArraySize();
verify(mockCameraProperties, never()).getSensorInfoActiveArraySize();
} finally {
updateSdkVersion(0);
}
}
@Test
public void
getCameraBoundaries_shouldReturnSensorInfoPixelArraySizeWhenDistortionCorrectionIsNull() {
updateSdkVersion(Build.VERSION_CODES.P);
try {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
when(mockCameraProperties.getDistortionCorrectionAvailableModes()).thenReturn(null);
when(mockCameraProperties.getSensorInfoPixelArraySize()).thenReturn(mockCameraBoundaries);
Size result = CameraRegionUtils.getCameraBoundaries(mockCameraProperties, mockBuilder);
assertEquals(mockCameraBoundaries, result);
verify(mockCameraProperties, never()).getSensorInfoPreCorrectionActiveArraySize();
verify(mockCameraProperties, never()).getSensorInfoActiveArraySize();
} finally {
updateSdkVersion(0);
}
}
@Test
public void
getCameraBoundaries_shouldReturnSensorInfoPixelArraySizeWhenDistortionCorrectionIsOff() {
updateSdkVersion(Build.VERSION_CODES.P);
try {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
when(mockCameraProperties.getDistortionCorrectionAvailableModes())
.thenReturn(new int[] {CaptureRequest.DISTORTION_CORRECTION_MODE_OFF});
when(mockCameraProperties.getSensorInfoPixelArraySize()).thenReturn(mockCameraBoundaries);
Size result = CameraRegionUtils.getCameraBoundaries(mockCameraProperties, mockBuilder);
assertEquals(mockCameraBoundaries, result);
verify(mockCameraProperties, never()).getSensorInfoPreCorrectionActiveArraySize();
verify(mockCameraProperties, never()).getSensorInfoActiveArraySize();
} finally {
updateSdkVersion(0);
}
}
@Test
public void
getCameraBoundaries_shouldReturnInfoPreCorrectionActiveArraySizeWhenDistortionCorrectionModeIsSetToNull() {
updateSdkVersion(Build.VERSION_CODES.P);
try {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
Rect mockSensorInfoPreCorrectionActiveArraySize = mock(Rect.class);
when(mockSensorInfoPreCorrectionActiveArraySize.width()).thenReturn(100);
when(mockSensorInfoPreCorrectionActiveArraySize.height()).thenReturn(100);
when(mockCameraProperties.getDistortionCorrectionAvailableModes())
.thenReturn(
new int[] {
CaptureRequest.DISTORTION_CORRECTION_MODE_OFF,
CaptureRequest.DISTORTION_CORRECTION_MODE_FAST
});
when(mockBuilder.get(CaptureRequest.DISTORTION_CORRECTION_MODE)).thenReturn(null);
when(mockCameraProperties.getSensorInfoPreCorrectionActiveArraySize())
.thenReturn(mockSensorInfoPreCorrectionActiveArraySize);
try (MockedStatic<CameraRegionUtils.SizeFactory> mockedSizeFactory =
mockStatic(CameraRegionUtils.SizeFactory.class)) {
mockedSizeFactory
.when(() -> CameraRegionUtils.SizeFactory.create(anyInt(), anyInt()))
.thenAnswer(
(Answer<Size>)
invocation -> {
Size mockSize = mock(Size.class);
when(mockSize.getWidth()).thenReturn(invocation.getArgument(0));
when(mockSize.getHeight()).thenReturn(invocation.getArgument(1));
return mockSize;
});
Size result = CameraRegionUtils.getCameraBoundaries(mockCameraProperties, mockBuilder);
assertEquals(100, result.getWidth());
assertEquals(100, result.getHeight());
verify(mockCameraProperties, never()).getSensorInfoPixelArraySize();
verify(mockCameraProperties, never()).getSensorInfoActiveArraySize();
}
} finally {
updateSdkVersion(0);
}
}
@Test
public void
getCameraBoundaries_shouldReturnInfoPreCorrectionActiveArraySizeWhenDistortionCorrectionModeIsSetToOff() {
updateSdkVersion(Build.VERSION_CODES.P);
try {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
Rect mockSensorInfoPreCorrectionActiveArraySize = mock(Rect.class);
when(mockSensorInfoPreCorrectionActiveArraySize.width()).thenReturn(100);
when(mockSensorInfoPreCorrectionActiveArraySize.height()).thenReturn(100);
when(mockCameraProperties.getDistortionCorrectionAvailableModes())
.thenReturn(
new int[] {
CaptureRequest.DISTORTION_CORRECTION_MODE_OFF,
CaptureRequest.DISTORTION_CORRECTION_MODE_FAST
});
when(mockBuilder.get(CaptureRequest.DISTORTION_CORRECTION_MODE))
.thenReturn(CaptureRequest.DISTORTION_CORRECTION_MODE_OFF);
when(mockCameraProperties.getSensorInfoPreCorrectionActiveArraySize())
.thenReturn(mockSensorInfoPreCorrectionActiveArraySize);
try (MockedStatic<CameraRegionUtils.SizeFactory> mockedSizeFactory =
mockStatic(CameraRegionUtils.SizeFactory.class)) {
mockedSizeFactory
.when(() -> CameraRegionUtils.SizeFactory.create(anyInt(), anyInt()))
.thenAnswer(
(Answer<Size>)
invocation -> {
Size mockSize = mock(Size.class);
when(mockSize.getWidth()).thenReturn(invocation.getArgument(0));
when(mockSize.getHeight()).thenReturn(invocation.getArgument(1));
return mockSize;
});
Size result = CameraRegionUtils.getCameraBoundaries(mockCameraProperties, mockBuilder);
assertEquals(100, result.getWidth());
assertEquals(100, result.getHeight());
verify(mockCameraProperties, never()).getSensorInfoPixelArraySize();
verify(mockCameraProperties, never()).getSensorInfoActiveArraySize();
}
} finally {
updateSdkVersion(0);
}
}
@Test
public void
getCameraBoundaries_shouldReturnSensorInfoActiveArraySizeWhenDistortionCorrectionModeIsSet() {
updateSdkVersion(Build.VERSION_CODES.P);
try {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
Rect mockSensorInfoActiveArraySize = mock(Rect.class);
when(mockSensorInfoActiveArraySize.width()).thenReturn(100);
when(mockSensorInfoActiveArraySize.height()).thenReturn(100);
when(mockCameraProperties.getDistortionCorrectionAvailableModes())
.thenReturn(
new int[] {
CaptureRequest.DISTORTION_CORRECTION_MODE_OFF,
CaptureRequest.DISTORTION_CORRECTION_MODE_FAST
});
when(mockBuilder.get(CaptureRequest.DISTORTION_CORRECTION_MODE))
.thenReturn(CaptureRequest.DISTORTION_CORRECTION_MODE_FAST);
when(mockCameraProperties.getSensorInfoActiveArraySize())
.thenReturn(mockSensorInfoActiveArraySize);
try (MockedStatic<CameraRegionUtils.SizeFactory> mockedSizeFactory =
mockStatic(CameraRegionUtils.SizeFactory.class)) {
mockedSizeFactory
.when(() -> CameraRegionUtils.SizeFactory.create(anyInt(), anyInt()))
.thenAnswer(
(Answer<Size>)
invocation -> {
Size mockSize = mock(Size.class);
when(mockSize.getWidth()).thenReturn(invocation.getArgument(0));
when(mockSize.getHeight()).thenReturn(invocation.getArgument(1));
return mockSize;
});
Size result = CameraRegionUtils.getCameraBoundaries(mockCameraProperties, mockBuilder);
assertEquals(100, result.getWidth());
assertEquals(100, result.getHeight());
verify(mockCameraProperties, never()).getSensorInfoPixelArraySize();
verify(mockCameraProperties, never()).getSensorInfoPreCorrectionActiveArraySize();
}
} finally {
updateSdkVersion(0);
}
}
private static void updateSdkVersion(int version) {
TestUtils.setFinalStatic(Build.VERSION.class, "SDK_INT", version);
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraRegionUtils_getCameraBoundariesTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraRegionUtils_getCameraBoundariesTest.java",
"repo_id": "plugins",
"token_count": 3912
} | 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 io.flutter.plugins.camera.features.fpsrange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.hardware.camera2.CaptureRequest;
import android.os.Build;
import android.util.Range;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.utils.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class FpsRangeFeatureTest {
@Before
public void before() {
TestUtils.setFinalStatic(Build.class, "BRAND", "Test Brand");
TestUtils.setFinalStatic(Build.class, "MODEL", "Test Model");
}
@After
public void after() {
TestUtils.setFinalStatic(Build.class, "BRAND", null);
TestUtils.setFinalStatic(Build.class, "MODEL", null);
}
@Test
public void ctor_shouldInitializeFpsRangeWithHighestUpperValueFromRangeArray() {
FpsRangeFeature fpsRangeFeature = createTestInstance();
assertEquals(13, (int) fpsRangeFeature.getValue().getUpper());
}
@Test
public void getDebugName_shouldReturnTheNameOfTheFeature() {
FpsRangeFeature fpsRangeFeature = createTestInstance();
assertEquals("FpsRangeFeature", fpsRangeFeature.getDebugName());
}
@Test
public void getValue_shouldReturnHighestUpperRangeIfNotSet() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FpsRangeFeature fpsRangeFeature = createTestInstance();
assertEquals(13, (int) fpsRangeFeature.getValue().getUpper());
}
@Test
public void getValue_shouldEchoTheSetValue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
FpsRangeFeature fpsRangeFeature = new FpsRangeFeature(mockCameraProperties);
@SuppressWarnings("unchecked")
Range<Integer> expectedValue = mock(Range.class);
fpsRangeFeature.setValue(expectedValue);
Range<Integer> actualValue = fpsRangeFeature.getValue();
assertEquals(expectedValue, actualValue);
}
@Test
public void checkIsSupported_shouldReturnTrue() {
FpsRangeFeature fpsRangeFeature = createTestInstance();
assertTrue(fpsRangeFeature.checkIsSupported());
}
@Test
@SuppressWarnings("unchecked")
public void updateBuilder_shouldSetAeTargetFpsRange() {
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
FpsRangeFeature fpsRangeFeature = createTestInstance();
fpsRangeFeature.updateBuilder(mockBuilder);
verify(mockBuilder).set(eq(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE), any(Range.class));
}
private static FpsRangeFeature createTestInstance() {
@SuppressWarnings("unchecked")
Range<Integer> rangeOne = mock(Range.class);
@SuppressWarnings("unchecked")
Range<Integer> rangeTwo = mock(Range.class);
@SuppressWarnings("unchecked")
Range<Integer> rangeThree = mock(Range.class);
when(rangeOne.getUpper()).thenReturn(11);
when(rangeTwo.getUpper()).thenReturn(12);
when(rangeThree.getUpper()).thenReturn(13);
@SuppressWarnings("unchecked")
Range<Integer>[] ranges = new Range[] {rangeOne, rangeTwo, rangeThree};
CameraProperties cameraProperties = mock(CameraProperties.class);
when(cameraProperties.getControlAutoExposureAvailableTargetFpsRanges()).thenReturn(ranges);
return new FpsRangeFeature(cameraProperties);
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/fpsrange/FpsRangeFeatureTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/fpsrange/FpsRangeFeatureTest.java",
"repo_id": "plugins",
"token_count": 1192
} | 1,140 |
# camera_android_camerax
An implementation of the camera plugin on Android using CameraX.
| plugins/packages/camera/camera_android_camerax/README.md/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/README.md",
"repo_id": "plugins",
"token_count": 23
} | 1,141 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import android.graphics.SurfaceTexture;
import android.util.Size;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.camera.core.Preview;
import androidx.camera.core.SurfaceRequest;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PreviewHostApi;
import io.flutter.view.TextureRegistry;
import java.util.Objects;
import java.util.concurrent.Executors;
public class PreviewHostApiImpl implements PreviewHostApi {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
private final TextureRegistry textureRegistry;
@VisibleForTesting public CameraXProxy cameraXProxy = new CameraXProxy();
@VisibleForTesting public TextureRegistry.SurfaceTextureEntry flutterSurfaceTexture;
public PreviewHostApiImpl(
@NonNull BinaryMessenger binaryMessenger,
@NonNull InstanceManager instanceManager,
@NonNull TextureRegistry textureRegistry) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
this.textureRegistry = textureRegistry;
}
/** Creates a {@link Preview} with the target rotation and resolution if specified. */
@Override
public void create(
@NonNull Long identifier,
@Nullable Long rotation,
@Nullable GeneratedCameraXLibrary.ResolutionInfo targetResolution) {
Preview.Builder previewBuilder = cameraXProxy.createPreviewBuilder();
if (rotation != null) {
previewBuilder.setTargetRotation(rotation.intValue());
}
if (targetResolution != null) {
previewBuilder.setTargetResolution(
new Size(
targetResolution.getWidth().intValue(), targetResolution.getHeight().intValue()));
}
Preview preview = previewBuilder.build();
instanceManager.addDartCreatedInstance(preview, identifier);
}
/**
* Sets the {@link Preview.SurfaceProvider} that will be used to provide a {@code Surface} backed
* by a Flutter {@link TextureRegistry.SurfaceTextureEntry} used to build the {@link Preview}.
*/
@Override
public Long setSurfaceProvider(@NonNull Long identifier) {
Preview preview = (Preview) Objects.requireNonNull(instanceManager.getInstance(identifier));
flutterSurfaceTexture = textureRegistry.createSurfaceTexture();
SurfaceTexture surfaceTexture = flutterSurfaceTexture.surfaceTexture();
Preview.SurfaceProvider surfaceProvider = createSurfaceProvider(surfaceTexture);
preview.setSurfaceProvider(surfaceProvider);
return flutterSurfaceTexture.id();
}
/**
* Creates a {@link Preview.SurfaceProvider} that specifies how to provide a {@link Surface} to a
* {@code Preview} that is backed by a Flutter {@link TextureRegistry.SurfaceTextureEntry}.
*/
@VisibleForTesting
public Preview.SurfaceProvider createSurfaceProvider(@NonNull SurfaceTexture surfaceTexture) {
return new Preview.SurfaceProvider() {
@Override
public void onSurfaceRequested(SurfaceRequest request) {
surfaceTexture.setDefaultBufferSize(
request.getResolution().getWidth(), request.getResolution().getHeight());
Surface flutterSurface = cameraXProxy.createSurface(surfaceTexture);
request.provideSurface(
flutterSurface,
Executors.newSingleThreadExecutor(),
(result) -> {
// See https://developer.android.com/reference/androidx/camera/core/SurfaceRequest.Result for documentation.
// Always attempt a release.
flutterSurface.release();
int resultCode = result.getResultCode();
switch (resultCode) {
case SurfaceRequest.Result.RESULT_REQUEST_CANCELLED:
case SurfaceRequest.Result.RESULT_WILL_NOT_PROVIDE_SURFACE:
case SurfaceRequest.Result.RESULT_SURFACE_ALREADY_PROVIDED:
case SurfaceRequest.Result.RESULT_SURFACE_USED_SUCCESSFULLY:
// Only need to release, do nothing.
break;
case SurfaceRequest.Result.RESULT_INVALID_SURFACE: // Intentional fall through.
default:
// Release and send error.
SystemServicesFlutterApiImpl systemServicesFlutterApi =
cameraXProxy.createSystemServicesFlutterApiImpl(binaryMessenger);
systemServicesFlutterApi.sendCameraError(
getProvideSurfaceErrorDescription(resultCode), reply -> {});
break;
}
});
};
};
}
/**
* Returns an error description for each {@link SurfaceRequest.Result} that represents an error
* with providing a surface.
*/
private String getProvideSurfaceErrorDescription(@Nullable int resultCode) {
switch (resultCode) {
case SurfaceRequest.Result.RESULT_INVALID_SURFACE:
return resultCode + ": Provided surface could not be used by the camera.";
default:
return resultCode + ": Attempt to provide a surface resulted with unrecognizable code.";
}
}
/**
* Releases the Flutter {@link TextureRegistry.SurfaceTextureEntry} if used to provide a surface
* for a {@link Preview}.
*/
@Override
public void releaseFlutterSurfaceTexture() {
if (flutterSurfaceTexture != null) {
flutterSurfaceTexture.release();
}
}
/** Returns the resolution information for the specified {@link Preview}. */
@Override
public GeneratedCameraXLibrary.ResolutionInfo getResolutionInfo(@NonNull Long identifier) {
Preview preview = (Preview) Objects.requireNonNull(instanceManager.getInstance(identifier));
Size resolution = preview.getResolutionInfo().getResolution();
GeneratedCameraXLibrary.ResolutionInfo.Builder resolutionInfo =
new GeneratedCameraXLibrary.ResolutionInfo.Builder()
.setWidth(Long.valueOf(resolution.getWidth()))
.setHeight(Long.valueOf(resolution.getHeight()));
return resolutionInfo.build();
}
}
| plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewHostApiImpl.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewHostApiImpl.java",
"repo_id": "plugins",
"token_count": 2177
} | 1,142 |
buildscript {
ext.kotlin_version = '1.8.0'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| plugins/packages/camera/camera_android_camerax/example/android/build.gradle/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/example/android/build.gradle",
"repo_id": "plugins",
"token_count": 258
} | 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:flutter/services.dart' show BinaryMessenger;
import 'android_camera_camerax_flutter_api_impls.dart';
import 'camerax_library.g.dart';
import 'instance_manager.dart';
import 'java_object.dart';
/// Represents the metadata of a camera.
///
/// See https://developer.android.com/reference/androidx/camera/core/CameraInfo.
class CameraInfo extends JavaObject {
/// Constructs a [CameraInfo] that is not automatically attached to a native object.
CameraInfo.detached(
{BinaryMessenger? binaryMessenger, InstanceManager? instanceManager})
: super.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager) {
_api = CameraInfoHostApiImpl(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
AndroidCameraXCameraFlutterApis.instance.ensureSetUp();
}
late final CameraInfoHostApiImpl _api;
/// Gets sensor orientation degrees of camera.
Future<int> getSensorRotationDegrees() =>
_api.getSensorRotationDegreesFromInstance(this);
}
/// Host API implementation of [CameraInfo].
class CameraInfoHostApiImpl extends CameraInfoHostApi {
/// Constructs a [CameraInfoHostApiImpl].
CameraInfoHostApiImpl(
{super.binaryMessenger, InstanceManager? instanceManager}) {
this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
}
/// Maintains instances stored to communicate with native language objects.
late final InstanceManager instanceManager;
/// Gets sensor orientation degrees of [CameraInfo].
Future<int> getSensorRotationDegreesFromInstance(
CameraInfo instance,
) async {
final int sensorRotationDegrees = await getSensorRotationDegrees(
instanceManager.getIdentifier(instance)!);
return sensorRotationDegrees;
}
}
/// Flutter API implementation of [CameraInfo].
class CameraInfoFlutterApiImpl extends CameraInfoFlutterApi {
/// Constructs a [CameraInfoFlutterApiImpl].
CameraInfoFlutterApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void create(int identifier) {
instanceManager.addHostCreatedInstance(
CameraInfo.detached(
binaryMessenger: binaryMessenger, instanceManager: instanceManager),
identifier,
onCopy: (CameraInfo original) {
return CameraInfo.detached(
binaryMessenger: binaryMessenger, instanceManager: instanceManager);
},
);
}
}
| plugins/packages/camera/camera_android_camerax/lib/src/camera_info.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/lib/src/camera_info.dart",
"repo_id": "plugins",
"token_count": 912
} | 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.
import 'package:camera_android_camerax/src/camera_info.dart';
import 'package:camera_android_camerax/src/camera_selector.dart';
import 'package:camera_android_camerax/src/camerax_library.g.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_selector_test.mocks.dart';
import 'test_camerax_library.g.dart';
@GenerateMocks(<Type>[TestCameraSelectorHostApi])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('CameraSelector', () {
tearDown(() => TestCameraSelectorHostApi.setup(null));
test('detachedCreateTest', () async {
final MockTestCameraSelectorHostApi mockApi =
MockTestCameraSelectorHostApi();
TestCameraSelectorHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
CameraSelector.detached(
instanceManager: instanceManager,
);
verifyNever(mockApi.create(argThat(isA<int>()), null));
});
test('createTestWithoutLensSpecified', () async {
final MockTestCameraSelectorHostApi mockApi =
MockTestCameraSelectorHostApi();
TestCameraSelectorHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
CameraSelector(
instanceManager: instanceManager,
);
verify(mockApi.create(argThat(isA<int>()), null));
});
test('createTestWithLensSpecified', () async {
final MockTestCameraSelectorHostApi mockApi =
MockTestCameraSelectorHostApi();
TestCameraSelectorHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
CameraSelector(
instanceManager: instanceManager,
lensFacing: CameraSelector.lensFacingBack);
verify(
mockApi.create(argThat(isA<int>()), CameraSelector.lensFacingBack));
});
test('filterTest', () async {
final MockTestCameraSelectorHostApi mockApi =
MockTestCameraSelectorHostApi();
TestCameraSelectorHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraSelector cameraSelector = CameraSelector.detached(
instanceManager: instanceManager,
);
const int cameraInfoId = 3;
final CameraInfo cameraInfo =
CameraInfo.detached(instanceManager: instanceManager);
instanceManager.addHostCreatedInstance(
cameraSelector,
0,
onCopy: (_) => CameraSelector.detached(),
);
instanceManager.addHostCreatedInstance(
cameraInfo,
cameraInfoId,
onCopy: (_) => CameraInfo.detached(),
);
when(mockApi.filter(instanceManager.getIdentifier(cameraSelector),
<int>[cameraInfoId])).thenReturn(<int>[cameraInfoId]);
expect(await cameraSelector.filter(<CameraInfo>[cameraInfo]),
equals(<CameraInfo>[cameraInfo]));
verify(mockApi.filter(0, <int>[cameraInfoId]));
});
test('flutterApiCreateTest', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraSelectorFlutterApi flutterApi = CameraSelectorFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(0, CameraSelector.lensFacingBack);
expect(instanceManager.getInstanceWithWeakReference(0),
isA<CameraSelector>());
expect(
(instanceManager.getInstanceWithWeakReference(0)! as CameraSelector)
.lensFacing,
equals(CameraSelector.lensFacingBack));
});
});
}
| plugins/packages/camera/camera_android_camerax/test/camera_selector_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/test/camera_selector_test.dart",
"repo_id": "plugins",
"token_count": 1573
} | 1,145 |
// 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 AVFoundation;
@import XCTest;
#import <OCMock/OCMock.h>
#import "CameraTestUtils.h"
/// Includes test cases related to sample buffer handling for FLTCam class.
@interface FLTCamSampleBufferTests : XCTestCase
@end
@implementation FLTCamSampleBufferTests
- (void)testSampleBufferCallbackQueueMustBeCaptureSessionQueue {
dispatch_queue_t captureSessionQueue = dispatch_queue_create("testing", NULL);
FLTCam *cam = FLTCreateCamWithCaptureSessionQueue(captureSessionQueue);
XCTAssertEqual(captureSessionQueue, cam.captureVideoOutput.sampleBufferCallbackQueue,
@"Sample buffer callback queue must be the capture session queue.");
}
- (void)testCopyPixelBuffer {
FLTCam *cam = FLTCreateCamWithCaptureSessionQueue(dispatch_queue_create("test", NULL));
CMSampleBufferRef capturedSampleBuffer = FLTCreateTestSampleBuffer();
CVPixelBufferRef capturedPixelBuffer = CMSampleBufferGetImageBuffer(capturedSampleBuffer);
// Mimic sample buffer callback when captured a new video sample
[cam captureOutput:cam.captureVideoOutput
didOutputSampleBuffer:capturedSampleBuffer
fromConnection:OCMClassMock([AVCaptureConnection class])];
CVPixelBufferRef deliveriedPixelBuffer = [cam copyPixelBuffer];
XCTAssertEqual(deliveriedPixelBuffer, capturedPixelBuffer,
@"FLTCam must deliver the latest captured pixel buffer to copyPixelBuffer API.");
CFRelease(capturedSampleBuffer);
CFRelease(deliveriedPixelBuffer);
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSampleBufferTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSampleBufferTests.m",
"repo_id": "plugins",
"token_count": 518
} | 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 "FLTThreadSafeEventChannel.h"
#import "QueueUtils.h"
@interface FLTThreadSafeEventChannel ()
@property(nonatomic, strong) FlutterEventChannel *channel;
@end
@implementation FLTThreadSafeEventChannel
- (instancetype)initWithEventChannel:(FlutterEventChannel *)channel {
self = [super init];
if (self) {
_channel = channel;
}
return self;
}
- (void)setStreamHandler:(NSObject<FlutterStreamHandler> *)handler
completion:(void (^)(void))completion {
// WARNING: Should not use weak self, because FLTThreadSafeEventChannel is a local variable
// (retained within call stack, but not in the heap). FLTEnsureToRunOnMainQueue may trigger a
// context switch (when calling from background thread), in which case using weak self will always
// result in a nil self. Alternative to using strong self, we can also create a local strong
// variable to be captured by this block.
FLTEnsureToRunOnMainQueue(^{
[self.channel setStreamHandler:handler];
completion();
});
}
@end
| plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeEventChannel.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeEventChannel.m",
"repo_id": "plugins",
"token_count": 351
} | 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.
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import '../../camera_platform_interface.dart';
/// Options for configuring camera streaming.
///
/// Currently unused; this exists for future-proofing of the platform interface
/// API.
@immutable
class CameraImageStreamOptions {}
/// A single color plane of image data.
///
/// The number and meaning of the planes in an image are determined by its
/// format.
@immutable
class CameraImagePlane {
/// Creates a new instance with the given bytes and optional metadata.
const CameraImagePlane({
required this.bytes,
required this.bytesPerRow,
this.bytesPerPixel,
this.height,
this.width,
});
/// Bytes representing this plane.
final Uint8List bytes;
/// The row stride for this color plane, in bytes.
final int bytesPerRow;
/// The distance between adjacent pixel samples in bytes, when available.
final int? bytesPerPixel;
/// Height of the pixel buffer, when available.
final int? height;
/// Width of the pixel buffer, when available.
final int? width;
}
/// Describes how pixels are represented in an image.
@immutable
class CameraImageFormat {
/// Create a new format with the given cross-platform group and raw underyling
/// platform identifier.
const CameraImageFormat(this.group, {required this.raw});
/// Describes the format group the raw image format falls into.
final ImageFormatGroup group;
/// Raw version of the format from the underlying platform.
///
/// On Android, this should be an `int` from class
/// `android.graphics.ImageFormat`. See
/// https://developer.android.com/reference/android/graphics/ImageFormat
///
/// On iOS, this should be a `FourCharCode` constant from Pixel Format
/// Identifiers. See
/// https://developer.apple.com/documentation/corevideo/1563591-pixel_format_identifiers
final dynamic raw;
}
/// A single complete image buffer from the platform camera.
///
/// This class allows for direct application access to the pixel data of an
/// Image through one or more [Uint8List]. Each buffer is encapsulated in a
/// [CameraImagePlane] that describes the layout of the pixel data in that
/// plane. [CameraImageData] is not directly usable as a UI resource.
///
/// Although not all image formats are planar on all platforms, this class
/// treats 1-dimensional images as single planar images.
@immutable
class CameraImageData {
/// Creates a new instance with the given format, planes, and metadata.
const CameraImageData({
required this.format,
required this.planes,
required this.height,
required this.width,
this.lensAperture,
this.sensorExposureTime,
this.sensorSensitivity,
});
/// Format of the image provided.
///
/// Determines the number of planes needed to represent the image, and
/// the general layout of the pixel data in each [Uint8List].
final CameraImageFormat format;
/// Height of the image in pixels.
///
/// For formats where some color channels are subsampled, this is the height
/// of the largest-resolution plane.
final int height;
/// Width of the image in pixels.
///
/// For formats where some color channels are subsampled, this is the width
/// of the largest-resolution plane.
final int width;
/// The pixels planes for this image.
///
/// The number of planes is determined by the format of the image.
final List<CameraImagePlane> planes;
/// The aperture settings for this image.
///
/// Represented as an f-stop value.
final double? lensAperture;
/// The sensor exposure time for this image in nanoseconds.
final int? sensorExposureTime;
/// The sensor sensitivity in standard ISO arithmetic units.
final double? sensorSensitivity;
}
| plugins/packages/camera/camera_platform_interface/lib/src/types/camera_image_data.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/lib/src/types/camera_image_data.dart",
"repo_id": "plugins",
"token_count": 1102
} | 1,148 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('constructor should initialize properties', () {
const String code = 'TEST_ERROR';
const String description = 'This is a test error';
final CameraException exception = CameraException(code, description);
expect(exception.code, code);
expect(exception.description, description);
});
test('toString: Should return a description of the exception', () {
const String code = 'TEST_ERROR';
const String description = 'This is a test error';
const String expected = 'CameraException($code, $description)';
final CameraException exception = CameraException(code, description);
final String actual = exception.toString();
expect(actual, expected);
});
}
| plugins/packages/camera/camera_platform_interface/test/types/camera_exception_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/test/types/camera_exception_test.dart",
"repo_id": "plugins",
"token_count": 280
} | 1,149 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_web/src/types/types.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('CameraOptions', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
final CameraOptions cameraOptions = CameraOptions(
audio: const AudioConstraints(enabled: true),
video: VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.user),
),
);
expect(
cameraOptions.toJson(),
equals(<String, Object>{
'audio': cameraOptions.audio.toJson(),
'video': cameraOptions.video.toJson(),
}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
CameraOptions(
audio: const AudioConstraints(),
video: VideoConstraints(
facingMode: FacingModeConstraint(CameraType.environment),
width:
const VideoSizeConstraint(minimum: 10, ideal: 15, maximum: 20),
height:
const VideoSizeConstraint(minimum: 15, ideal: 20, maximum: 25),
deviceId: 'deviceId',
),
),
equals(
CameraOptions(
audio: const AudioConstraints(),
video: VideoConstraints(
facingMode: FacingModeConstraint(CameraType.environment),
width: const VideoSizeConstraint(
minimum: 10, ideal: 15, maximum: 20),
height: const VideoSizeConstraint(
minimum: 15, ideal: 20, maximum: 25),
deviceId: 'deviceId',
),
),
),
);
});
});
group('AudioConstraints', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
expect(
const AudioConstraints(enabled: true).toJson(),
equals(true),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
const AudioConstraints(enabled: true),
equals(const AudioConstraints(enabled: true)),
);
});
});
group('VideoConstraints', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
final VideoConstraints videoConstraints = VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.user),
width: const VideoSizeConstraint(ideal: 100, maximum: 100),
height: const VideoSizeConstraint(ideal: 50, maximum: 50),
deviceId: 'deviceId',
);
expect(
videoConstraints.toJson(),
equals(<String, Object>{
'facingMode': videoConstraints.facingMode!.toJson(),
'width': videoConstraints.width!.toJson(),
'height': videoConstraints.height!.toJson(),
'deviceId': <String, Object>{
'exact': 'deviceId',
}
}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.environment),
width:
const VideoSizeConstraint(minimum: 90, ideal: 100, maximum: 100),
height:
const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50),
deviceId: 'deviceId',
),
equals(
VideoConstraints(
facingMode: FacingModeConstraint.exact(CameraType.environment),
width: const VideoSizeConstraint(
minimum: 90, ideal: 100, maximum: 100),
height:
const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50),
deviceId: 'deviceId',
),
),
);
});
});
group('FacingModeConstraint', () {
group('ideal', () {
testWidgets(
'serializes correctly '
'for environment camera type', (WidgetTester tester) async {
expect(
FacingModeConstraint(CameraType.environment).toJson(),
equals(<String, Object>{'ideal': 'environment'}),
);
});
testWidgets(
'serializes correctly '
'for user camera type', (WidgetTester tester) async {
expect(
FacingModeConstraint(CameraType.user).toJson(),
equals(<String, Object>{'ideal': 'user'}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
FacingModeConstraint(CameraType.user),
equals(FacingModeConstraint(CameraType.user)),
);
});
});
group('exact', () {
testWidgets(
'serializes correctly '
'for environment camera type', (WidgetTester tester) async {
expect(
FacingModeConstraint.exact(CameraType.environment).toJson(),
equals(<String, Object>{'exact': 'environment'}),
);
});
testWidgets(
'serializes correctly '
'for user camera type', (WidgetTester tester) async {
expect(
FacingModeConstraint.exact(CameraType.user).toJson(),
equals(<String, Object>{'exact': 'user'}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
FacingModeConstraint.exact(CameraType.environment),
equals(FacingModeConstraint.exact(CameraType.environment)),
);
});
});
});
group('VideoSizeConstraint ', () {
testWidgets('serializes correctly', (WidgetTester tester) async {
expect(
const VideoSizeConstraint(
minimum: 200,
ideal: 400,
maximum: 400,
).toJson(),
equals(<String, Object>{
'min': 200,
'ideal': 400,
'max': 400,
}),
);
});
testWidgets('supports value equality', (WidgetTester tester) async {
expect(
const VideoSizeConstraint(
minimum: 100,
ideal: 200,
maximum: 300,
),
equals(
const VideoSizeConstraint(
minimum: 100,
ideal: 200,
maximum: 300,
),
),
);
});
});
}
| plugins/packages/camera/camera_web/example/integration_test/camera_options_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/example/integration_test/camera_options_test.dart",
"repo_id": "plugins",
"token_count": 2942
} | 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 'dart:async';
import 'dart:html' as html;
import 'dart:math';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:stream_transform/stream_transform.dart';
import 'camera.dart';
import 'camera_service.dart';
import 'types/types.dart';
// The default error message, when the error is an empty string.
// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/message
const String _kDefaultErrorMessage =
'No further diagnostic information can be determined or provided.';
/// The web implementation of [CameraPlatform].
///
/// This class implements the `package:camera` functionality for the web.
class CameraPlugin extends CameraPlatform {
/// Creates a new instance of [CameraPlugin]
/// with the given [cameraService].
CameraPlugin({required CameraService cameraService})
: _cameraService = cameraService;
/// Registers this class as the default instance of [CameraPlatform].
static void registerWith(Registrar registrar) {
CameraPlatform.instance = CameraPlugin(
cameraService: CameraService(),
);
}
final CameraService _cameraService;
/// The cameras managed by the [CameraPlugin].
@visibleForTesting
final Map<int, Camera> cameras = <int, Camera>{};
int _textureCounter = 1;
/// Metadata associated with each camera description.
/// Populated in [availableCameras].
@visibleForTesting
final Map<CameraDescription, CameraMetadata> camerasMetadata =
<CameraDescription, CameraMetadata>{};
/// The controller used to broadcast different camera events.
///
/// It is `broadcast` as multiple controllers may subscribe
/// to different stream views of this controller.
@visibleForTesting
final StreamController<CameraEvent> cameraEventStreamController =
StreamController<CameraEvent>.broadcast();
final Map<int, StreamSubscription<html.Event>>
_cameraVideoErrorSubscriptions = <int, StreamSubscription<html.Event>>{};
final Map<int, StreamSubscription<html.Event>>
_cameraVideoAbortSubscriptions = <int, StreamSubscription<html.Event>>{};
final Map<int, StreamSubscription<html.MediaStreamTrack>>
_cameraEndedSubscriptions =
<int, StreamSubscription<html.MediaStreamTrack>>{};
final Map<int, StreamSubscription<html.ErrorEvent>>
_cameraVideoRecordingErrorSubscriptions =
<int, StreamSubscription<html.ErrorEvent>>{};
/// Returns a stream of camera events for the given [cameraId].
Stream<CameraEvent> _cameraEvents(int cameraId) =>
cameraEventStreamController.stream
.where((CameraEvent event) => event.cameraId == cameraId);
/// The current browser window used to access media devices.
@visibleForTesting
html.Window? window = html.window;
@override
Future<List<CameraDescription>> availableCameras() async {
try {
final html.MediaDevices? mediaDevices = window?.navigator.mediaDevices;
final List<CameraDescription> cameras = <CameraDescription>[];
// Throw a not supported exception if the current browser window
// does not support any media devices.
if (mediaDevices == null) {
throw PlatformException(
code: CameraErrorCode.notSupported.toString(),
message: 'The camera is not supported on this device.',
);
}
// Request video and audio permissions.
final html.MediaStream cameraStream =
await _cameraService.getMediaStreamForOptions(
const CameraOptions(
audio: AudioConstraints(enabled: true),
),
);
// Release the camera stream used to request video and audio permissions.
cameraStream
.getVideoTracks()
.forEach((html.MediaStreamTrack videoTrack) => videoTrack.stop());
// Request available media devices.
final List<dynamic> devices = await mediaDevices.enumerateDevices();
// Filter video input devices.
final Iterable<html.MediaDeviceInfo> videoInputDevices = devices
.whereType<html.MediaDeviceInfo>()
.where((html.MediaDeviceInfo device) =>
device.kind == MediaDeviceKind.videoInput)
/// The device id property is currently not supported on Internet Explorer:
/// https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/deviceId#browser_compatibility
.where(
(html.MediaDeviceInfo device) =>
device.deviceId != null && device.deviceId!.isNotEmpty,
);
// Map video input devices to camera descriptions.
for (final html.MediaDeviceInfo videoInputDevice in videoInputDevices) {
// Get the video stream for the current video input device
// to later use for the available video tracks.
final html.MediaStream videoStream = await _getVideoStreamForDevice(
videoInputDevice.deviceId!,
);
// Get all video tracks in the video stream
// to later extract the lens direction from the first track.
final List<html.MediaStreamTrack> videoTracks =
videoStream.getVideoTracks();
if (videoTracks.isNotEmpty) {
// Get the facing mode from the first available video track.
final String? facingMode =
_cameraService.getFacingModeForVideoTrack(videoTracks.first);
// Get the lens direction based on the facing mode.
// Fallback to the external lens direction
// if the facing mode is not available.
final CameraLensDirection lensDirection = facingMode != null
? _cameraService.mapFacingModeToLensDirection(facingMode)
: CameraLensDirection.external;
// Create a camera description.
//
// The name is a camera label which might be empty
// if no permissions to media devices have been granted.
//
// MediaDeviceInfo.label:
// https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/label
//
// Sensor orientation is currently not supported.
final String cameraLabel = videoInputDevice.label ?? '';
final CameraDescription camera = CameraDescription(
name: cameraLabel,
lensDirection: lensDirection,
sensorOrientation: 0,
);
final CameraMetadata cameraMetadata = CameraMetadata(
deviceId: videoInputDevice.deviceId!,
facingMode: facingMode,
);
cameras.add(camera);
camerasMetadata[camera] = cameraMetadata;
// Release the camera stream of the current video input device.
for (final html.MediaStreamTrack videoTrack in videoTracks) {
videoTrack.stop();
}
} else {
// Ignore as no video tracks exist in the current video input device.
continue;
}
}
return cameras;
} on html.DomException catch (e) {
throw CameraException(e.name, e.message);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw CameraException(e.code.toString(), e.description);
}
}
@override
Future<int> createCamera(
CameraDescription cameraDescription,
ResolutionPreset? resolutionPreset, {
bool enableAudio = false,
}) async {
try {
if (!camerasMetadata.containsKey(cameraDescription)) {
throw PlatformException(
code: CameraErrorCode.missingMetadata.toString(),
message:
'Missing camera metadata. Make sure to call `availableCameras` before creating a camera.',
);
}
final int textureId = _textureCounter++;
final CameraMetadata cameraMetadata = camerasMetadata[cameraDescription]!;
final CameraType? cameraType = cameraMetadata.facingMode != null
? _cameraService.mapFacingModeToCameraType(cameraMetadata.facingMode!)
: null;
// Use the highest resolution possible
// if the resolution preset is not specified.
final Size videoSize = _cameraService
.mapResolutionPresetToSize(resolutionPreset ?? ResolutionPreset.max);
// Create a camera with the given audio and video constraints.
// Sensor orientation is currently not supported.
final Camera camera = Camera(
textureId: textureId,
cameraService: _cameraService,
options: CameraOptions(
audio: AudioConstraints(enabled: enableAudio),
video: VideoConstraints(
facingMode:
cameraType != null ? FacingModeConstraint(cameraType) : null,
width: VideoSizeConstraint(
ideal: videoSize.width.toInt(),
),
height: VideoSizeConstraint(
ideal: videoSize.height.toInt(),
),
deviceId: cameraMetadata.deviceId,
),
),
);
cameras[textureId] = camera;
return textureId;
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
@override
Future<void> initializeCamera(
int cameraId, {
// The image format group is currently not supported.
ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown,
}) async {
try {
final Camera camera = getCamera(cameraId);
await camera.initialize();
// Add camera's video error events to the camera events stream.
// The error event fires when the video element's source has failed to load, or can't be used.
_cameraVideoErrorSubscriptions[cameraId] =
camera.videoElement.onError.listen((html.Event _) {
// The Event itself (_) doesn't contain information about the actual error.
// We need to look at the HTMLMediaElement.error.
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error
final html.MediaError error = camera.videoElement.error!;
final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(error);
final String? errorMessage =
error.message != '' ? error.message : _kDefaultErrorMessage;
cameraEventStreamController.add(
CameraErrorEvent(
cameraId,
'Error code: $errorCode, error message: $errorMessage',
),
);
});
// Add camera's video abort events to the camera events stream.
// The abort event fires when the video element's source has not fully loaded.
_cameraVideoAbortSubscriptions[cameraId] =
camera.videoElement.onAbort.listen((html.Event _) {
cameraEventStreamController.add(
CameraErrorEvent(
cameraId,
"Error code: ${CameraErrorCode.abort}, error message: The video element's source has not fully loaded.",
),
);
});
await camera.play();
// Add camera's closing events to the camera events stream.
// The onEnded stream fires when there is no more camera stream data.
_cameraEndedSubscriptions[cameraId] =
camera.onEnded.listen((html.MediaStreamTrack _) {
cameraEventStreamController.add(
CameraClosingEvent(cameraId),
);
});
final Size cameraSize = camera.getVideoSize();
cameraEventStreamController.add(
CameraInitializedEvent(
cameraId,
cameraSize.width,
cameraSize.height,
// TODO(bselwe): Add support for exposure mode and point (https://github.com/flutter/flutter/issues/86857).
ExposureMode.auto,
false,
// TODO(bselwe): Add support for focus mode and point (https://github.com/flutter/flutter/issues/86858).
FocusMode.auto,
false,
),
);
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Stream<CameraInitializedEvent> onCameraInitialized(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraInitializedEvent>();
}
/// Emits an empty stream as there is no event corresponding to a change
/// in the camera resolution on the web.
///
/// In order to change the camera resolution a new camera with appropriate
/// [CameraOptions.video] constraints has to be created and initialized.
@override
Stream<CameraResolutionChangedEvent> onCameraResolutionChanged(int cameraId) {
return const Stream<CameraResolutionChangedEvent>.empty();
}
@override
Stream<CameraClosingEvent> onCameraClosing(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraClosingEvent>();
}
@override
Stream<CameraErrorEvent> onCameraError(int cameraId) {
return _cameraEvents(cameraId).whereType<CameraErrorEvent>();
}
@override
Stream<VideoRecordedEvent> onVideoRecordedEvent(int cameraId) {
return getCamera(cameraId).onVideoRecordedEvent;
}
@override
Stream<DeviceOrientationChangedEvent> onDeviceOrientationChanged() {
final html.ScreenOrientation? orientation = window?.screen?.orientation;
if (orientation != null) {
// Create an initial orientation event that emits the device orientation
// as soon as subscribed to this stream.
final html.Event initialOrientationEvent = html.Event('change');
return orientation.onChange.startWith(initialOrientationEvent).map(
(html.Event _) {
final DeviceOrientation deviceOrientation = _cameraService
.mapOrientationTypeToDeviceOrientation(orientation.type!);
return DeviceOrientationChangedEvent(deviceOrientation);
},
);
} else {
return const Stream<DeviceOrientationChangedEvent>.empty();
}
}
@override
Future<void> lockCaptureOrientation(
int cameraId,
DeviceOrientation orientation,
) async {
try {
final html.ScreenOrientation? screenOrientation =
window?.screen?.orientation;
final html.Element? documentElement = window?.document.documentElement;
if (screenOrientation != null && documentElement != null) {
final String orientationType =
_cameraService.mapDeviceOrientationToOrientationType(orientation);
// Full-screen mode may be required to modify the device orientation.
// See: https://w3c.github.io/screen-orientation/#interaction-with-fullscreen-api
// Recent versions of Dart changed requestFullscreen to return a Future instead of void.
// This wrapper allows use of both the old and new APIs.
dynamic fullScreen() => documentElement.requestFullscreen();
await fullScreen();
await screenOrientation.lock(orientationType);
} else {
throw PlatformException(
code: CameraErrorCode.orientationNotSupported.toString(),
message: 'Orientation is not supported in the current browser.',
);
}
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
}
}
@override
Future<void> unlockCaptureOrientation(int cameraId) async {
try {
final html.ScreenOrientation? orientation = window?.screen?.orientation;
final html.Element? documentElement = window?.document.documentElement;
if (orientation != null && documentElement != null) {
orientation.unlock();
} else {
throw PlatformException(
code: CameraErrorCode.orientationNotSupported.toString(),
message: 'Orientation is not supported in the current browser.',
);
}
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
}
}
@override
Future<XFile> takePicture(int cameraId) {
try {
return getCamera(cameraId).takePicture();
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Future<void> prepareForVideoRecording() async {
// This is a no-op as it is not required for the web.
}
@override
Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) {
return startVideoCapturing(
VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration));
}
@override
Future<void> startVideoCapturing(VideoCaptureOptions options) {
if (options.streamCallback != null || options.streamOptions != null) {
throw UnimplementedError('Streaming is not currently supported on web');
}
try {
final Camera camera = getCamera(options.cameraId);
// Add camera's video recording errors to the camera events stream.
// The error event fires when the video recording is not allowed or an unsupported
// codec is used.
_cameraVideoRecordingErrorSubscriptions[options.cameraId] =
camera.onVideoRecordingError.listen((html.ErrorEvent errorEvent) {
cameraEventStreamController.add(
CameraErrorEvent(
options.cameraId,
'Error code: ${errorEvent.type}, error message: ${errorEvent.message}.',
),
);
});
return camera.startVideoRecording(maxVideoDuration: options.maxDuration);
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Future<XFile> stopVideoRecording(int cameraId) async {
try {
final XFile videoRecording =
await getCamera(cameraId).stopVideoRecording();
await _cameraVideoRecordingErrorSubscriptions[cameraId]?.cancel();
return videoRecording;
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Future<void> pauseVideoRecording(int cameraId) {
try {
return getCamera(cameraId).pauseVideoRecording();
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Future<void> resumeVideoRecording(int cameraId) {
try {
return getCamera(cameraId).resumeVideoRecording();
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Future<void> setFlashMode(int cameraId, FlashMode mode) async {
try {
getCamera(cameraId).setFlashMode(mode);
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Future<void> setExposureMode(int cameraId, ExposureMode mode) {
throw UnimplementedError('setExposureMode() is not implemented.');
}
@override
Future<void> setExposurePoint(int cameraId, Point<double>? point) {
throw UnimplementedError('setExposurePoint() is not implemented.');
}
@override
Future<double> getMinExposureOffset(int cameraId) {
throw UnimplementedError('getMinExposureOffset() is not implemented.');
}
@override
Future<double> getMaxExposureOffset(int cameraId) {
throw UnimplementedError('getMaxExposureOffset() is not implemented.');
}
@override
Future<double> getExposureOffsetStepSize(int cameraId) {
throw UnimplementedError('getExposureOffsetStepSize() is not implemented.');
}
@override
Future<double> setExposureOffset(int cameraId, double offset) {
throw UnimplementedError('setExposureOffset() is not implemented.');
}
@override
Future<void> setFocusMode(int cameraId, FocusMode mode) {
throw UnimplementedError('setFocusMode() is not implemented.');
}
@override
Future<void> setFocusPoint(int cameraId, Point<double>? point) {
throw UnimplementedError('setFocusPoint() is not implemented.');
}
@override
Future<double> getMaxZoomLevel(int cameraId) async {
try {
return getCamera(cameraId).getMaxZoomLevel();
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Future<double> getMinZoomLevel(int cameraId) async {
try {
return getCamera(cameraId).getMinZoomLevel();
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Future<void> setZoomLevel(int cameraId, double zoom) async {
try {
getCamera(cameraId).setZoomLevel(zoom);
} on html.DomException catch (e) {
throw CameraException(e.name, e.message);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw CameraException(e.code.toString(), e.description);
}
}
@override
Future<void> pausePreview(int cameraId) async {
try {
getCamera(cameraId).pause();
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
}
}
@override
Future<void> resumePreview(int cameraId) async {
try {
await getCamera(cameraId).play();
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}
@override
Widget buildPreview(int cameraId) {
return HtmlElementView(
viewType: getCamera(cameraId).getViewType(),
);
}
@override
Future<void> dispose(int cameraId) async {
try {
await getCamera(cameraId).dispose();
await _cameraVideoErrorSubscriptions[cameraId]?.cancel();
await _cameraVideoAbortSubscriptions[cameraId]?.cancel();
await _cameraEndedSubscriptions[cameraId]?.cancel();
await _cameraVideoRecordingErrorSubscriptions[cameraId]?.cancel();
cameras.remove(cameraId);
_cameraVideoErrorSubscriptions.remove(cameraId);
_cameraVideoAbortSubscriptions.remove(cameraId);
_cameraEndedSubscriptions.remove(cameraId);
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
}
}
/// Returns a media video stream for the device with the given [deviceId].
Future<html.MediaStream> _getVideoStreamForDevice(
String deviceId,
) {
// Create camera options with the desired device id.
final CameraOptions cameraOptions = CameraOptions(
video: VideoConstraints(deviceId: deviceId),
);
return _cameraService.getMediaStreamForOptions(cameraOptions);
}
/// Returns a camera for the given [cameraId].
///
/// Throws a [CameraException] if the camera does not exist.
@visibleForTesting
Camera getCamera(int cameraId) {
final Camera? camera = cameras[cameraId];
if (camera == null) {
throw PlatformException(
code: CameraErrorCode.notFound.toString(),
message: 'No camera found for the given camera id $cameraId.',
);
}
return camera;
}
/// Adds a [CameraErrorEvent], associated with the [exception],
/// to the stream of camera events.
void _addCameraErrorEvent(CameraWebException exception) {
cameraEventStreamController.add(
CameraErrorEvent(
exception.cameraId,
'Error code: ${exception.code}, error message: ${exception.description}',
),
);
}
}
| plugins/packages/camera/camera_web/lib/src/camera_web.dart/0 | {
"file_path": "plugins/packages/camera/camera_web/lib/src/camera_web.dart",
"repo_id": "plugins",
"token_count": 8818
} | 1,151 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
/// A mock [MethodChannel] implementation for use in tests.
class MethodChannelMock {
/// Creates a new instance with the specified channel name.
///
/// This method channel will handle all method invocations specified by
/// returning the value mapped to the method name key. If a delay is
/// specified, results are returned after the delay has elapsed.
MethodChannelMock({
required String channelName,
this.delay,
required this.methods,
}) : methodChannel = MethodChannel(channelName) {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(methodChannel, _handler);
}
final Duration? delay;
final MethodChannel methodChannel;
final Map<String, dynamic> methods;
final List<MethodCall> log = <MethodCall>[];
Future<dynamic> _handler(MethodCall methodCall) async {
log.add(methodCall);
if (!methods.containsKey(methodCall.method)) {
throw MissingPluginException('No TEST implementation found for method '
'${methodCall.method} on channel ${methodChannel.name}');
}
return Future<dynamic>.delayed(delay ?? Duration.zero, () {
final dynamic result = methods[methodCall.method];
if (result is Exception) {
throw result;
}
return Future<dynamic>.value(result);
});
}
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/camera/camera_windows/test/utils/method_channel_mock.dart/0 | {
"file_path": "plugins/packages/camera/camera_windows/test/utils/method_channel_mock.dart",
"repo_id": "plugins",
"token_count": 573
} | 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.
// This file exists solely to host compiled excerpts for README.md, and is not
// intended for use as an actual example application.
// ignore_for_file: public_member_api_docs
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231)
// ignore: unnecessary_import
import 'dart:typed_data';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('README snippet app'),
),
body: const Text('See example in main.dart'),
),
);
}
Future<void> saveFile() async {
// #docregion Save
const String fileName = 'suggested_name.txt';
final String? path = await getSavePath(suggestedName: fileName);
if (path == null) {
// Operation was canceled by the user.
return;
}
final Uint8List fileData = Uint8List.fromList('Hello World!'.codeUnits);
const String mimeType = 'text/plain';
final XFile textFile =
XFile.fromData(fileData, mimeType: mimeType, name: fileName);
await textFile.saveTo(path);
// #enddocregion Save
}
Future<void> directoryPath() async {
// #docregion GetDirectory
final String? directoryPath = await getDirectoryPath();
if (directoryPath == null) {
// Operation was canceled by the user.
return;
}
// #enddocregion GetDirectory
}
}
| plugins/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart",
"repo_id": "plugins",
"token_count": 664
} | 1,153 |
## NEXT
* Updates example code for `use_build_context_synchronously` lint.
* Updates minimum Flutter version to 3.0.
## 0.5.0+2
* Changes XTypeGroup initialization from final to const.
* Updates minimum Flutter version to 2.10.
## 0.5.0+1
* Updates README for endorsement.
## 0.5.0
* Initial iOS implementation of `file_selector`.
| plugins/packages/file_selector/file_selector_ios/CHANGELOG.md/0 | {
"file_path": "plugins/packages/file_selector/file_selector_ios/CHANGELOG.md",
"repo_id": "plugins",
"token_count": 111
} | 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.
// Autogenerated from Pigeon (v3.2.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import
import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;
import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';
class FileSelectorConfig {
FileSelectorConfig({
required this.utis,
required this.allowMultiSelection,
});
List<String?> utis;
bool allowMultiSelection;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['utis'] = utis;
pigeonMap['allowMultiSelection'] = allowMultiSelection;
return pigeonMap;
}
static FileSelectorConfig decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return FileSelectorConfig(
utis: (pigeonMap['utis'] as List<Object?>?)!.cast<String?>(),
allowMultiSelection: pigeonMap['allowMultiSelection']! as bool,
);
}
}
class _FileSelectorApiCodec extends StandardMessageCodec {
const _FileSelectorApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is FileSelectorConfig) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return FileSelectorConfig.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class FileSelectorApi {
/// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
FileSelectorApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _FileSelectorApiCodec();
Future<List<String?>> openFile(FileSelectorConfig arg_config) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.FileSelectorApi.openFile', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_config]) as Map<Object?, Object?>?;
if (replyMap == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyMap['error'] != null) {
final Map<Object?, Object?> error =
(replyMap['error'] as Map<Object?, Object?>?)!;
throw PlatformException(
code: (error['code'] as String?)!,
message: error['message'] as String?,
details: error['details'],
);
} else if (replyMap['result'] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyMap['result'] as List<Object?>?)!.cast<String?>();
}
}
}
| plugins/packages/file_selector/file_selector_ios/lib/src/messages.g.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_ios/lib/src/messages.g.dart",
"repo_id": "plugins",
"token_count": 1262
} | 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:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/material.dart';
/// Screen that allows the user to select one or more directories using `getDirectoryPaths`,
/// then displays the selected directories in a dialog.
class GetMultipleDirectoriesPage extends StatelessWidget {
/// Default Constructor
const GetMultipleDirectoriesPage({Key? key}) : super(key: key);
Future<void> _getDirectoryPaths(BuildContext context) async {
const String confirmButtonText = 'Choose';
final List<String> directoryPaths =
await FileSelectorPlatform.instance.getDirectoryPaths(
confirmButtonText: confirmButtonText,
);
if (directoryPaths.isEmpty) {
// Operation was canceled by the user.
return;
}
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) =>
TextDisplay(directoryPaths.join('\n')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Select multiple directories'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: Colors.blue,
// ignore: deprecated_member_use
onPrimary: Colors.white,
),
child: const Text(
'Press to ask user to choose multiple directories'),
onPressed: () => _getDirectoryPaths(context),
),
],
),
),
);
}
}
/// Widget that displays a text file in a dialog.
class TextDisplay extends StatelessWidget {
/// Creates a `TextDisplay`.
const TextDisplay(this.directoriesPaths, {Key? key}) : super(key: key);
/// The path selected in the dialog.
final String directoriesPaths;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Selected Directories'),
content: Scrollbar(
child: SingleChildScrollView(
child: Text(directoriesPaths),
),
),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () => Navigator.pop(context),
),
],
);
}
}
| plugins/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart",
"repo_id": "plugins",
"token_count": 1080
} | 1,156 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'fake_maps_controllers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakePlatformViewsController fakePlatformViewsController =
FakePlatformViewsController();
setUpAll(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform_views,
fakePlatformViewsController.fakePlatformViewsMethodHandler,
);
});
setUp(() {
fakePlatformViewsController.reset();
});
testWidgets('Initial camera position', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.cameraPosition,
const CameraPosition(target: LatLng(10.0, 15.0)));
});
testWidgets('Initial camera position change is a no-op',
(WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 16.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.cameraPosition,
const CameraPosition(target: LatLng(10.0, 15.0)));
});
testWidgets('Can update compassEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
compassEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.compassEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(platformGoogleMap.compassEnabled, true);
});
testWidgets('Can update mapToolbarEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
mapToolbarEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.mapToolbarEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(platformGoogleMap.mapToolbarEnabled, true);
});
testWidgets('Can update cameraTargetBounds', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition:
const CameraPosition(target: LatLng(10.0, 15.0)),
cameraTargetBounds: CameraTargetBounds(
LatLngBounds(
southwest: const LatLng(10.0, 20.0),
northeast: const LatLng(30.0, 40.0),
),
),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(
platformGoogleMap.cameraTargetBounds,
CameraTargetBounds(
LatLngBounds(
southwest: const LatLng(10.0, 20.0),
northeast: const LatLng(30.0, 40.0),
),
));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition:
const CameraPosition(target: LatLng(10.0, 15.0)),
cameraTargetBounds: CameraTargetBounds(
LatLngBounds(
southwest: const LatLng(16.0, 20.0),
northeast: const LatLng(30.0, 40.0),
),
),
),
),
);
expect(
platformGoogleMap.cameraTargetBounds,
CameraTargetBounds(
LatLngBounds(
southwest: const LatLng(16.0, 20.0),
northeast: const LatLng(30.0, 40.0),
),
));
});
testWidgets('Can update mapType', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
mapType: MapType.hybrid,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.mapType, MapType.hybrid);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
mapType: MapType.satellite,
),
),
);
expect(platformGoogleMap.mapType, MapType.satellite);
});
testWidgets('Can update minMaxZoom', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
minMaxZoomPreference: MinMaxZoomPreference(1.0, 3.0),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.minMaxZoomPreference,
const MinMaxZoomPreference(1.0, 3.0));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(
platformGoogleMap.minMaxZoomPreference, MinMaxZoomPreference.unbounded);
});
testWidgets('Can update rotateGesturesEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
rotateGesturesEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.rotateGesturesEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(platformGoogleMap.rotateGesturesEnabled, true);
});
testWidgets('Can update scrollGesturesEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
scrollGesturesEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.scrollGesturesEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(platformGoogleMap.scrollGesturesEnabled, true);
});
testWidgets('Can update tiltGesturesEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
tiltGesturesEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.tiltGesturesEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(platformGoogleMap.tiltGesturesEnabled, true);
});
testWidgets('Can update trackCameraPosition', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.trackCameraPosition, false);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition:
const CameraPosition(target: LatLng(10.0, 15.0)),
onCameraMove: (CameraPosition position) {},
),
),
);
expect(platformGoogleMap.trackCameraPosition, true);
});
testWidgets('Can update zoomGesturesEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
zoomGesturesEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.zoomGesturesEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(platformGoogleMap.zoomGesturesEnabled, true);
});
testWidgets('Can update zoomControlsEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
zoomControlsEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.zoomControlsEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(platformGoogleMap.zoomControlsEnabled, true);
});
testWidgets('Can update myLocationEnabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.myLocationEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
myLocationEnabled: true,
),
),
);
expect(platformGoogleMap.myLocationEnabled, true);
});
testWidgets('Can update myLocationButtonEnabled',
(WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.myLocationButtonEnabled, true);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
myLocationButtonEnabled: false,
),
),
);
expect(platformGoogleMap.myLocationButtonEnabled, false);
});
testWidgets('Is default padding 0', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.padding, <double>[0, 0, 0, 0]);
});
testWidgets('Can update padding', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.padding, <double>[0, 0, 0, 0]);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
padding: EdgeInsets.fromLTRB(10, 20, 30, 40),
),
),
);
expect(platformGoogleMap.padding, <double>[20, 10, 40, 30]);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
padding: EdgeInsets.fromLTRB(50, 60, 70, 80),
),
),
);
expect(platformGoogleMap.padding, <double>[60, 50, 80, 70]);
});
testWidgets('Can update traffic', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.trafficEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
trafficEnabled: true,
),
),
);
expect(platformGoogleMap.trafficEnabled, true);
});
testWidgets('Can update buildings', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
buildingsEnabled: false,
),
),
);
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.buildingsEnabled, false);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)),
),
),
);
expect(platformGoogleMap.buildingsEnabled, true);
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart",
"repo_id": "plugins",
"token_count": 6973
} | 1,157 |
# google\_maps\_flutter\_ios
The iOS implementation of [`google_maps_flutter`][1].
## Usage
This package is [endorsed][2], which means you can simply use
`google_maps_flutter` normally. This package will be automatically included in
your app when you do.
[1]: https://pub.dev/packages/google_maps_flutter
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/README.md/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/README.md",
"repo_id": "plugins",
"token_count": 132
} | 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.
#import "PartiallyMockedMapView.h"
@interface PartiallyMockedMapView ()
@property(nonatomic, assign) NSInteger frameObserverCount;
@end
@implementation PartiallyMockedMapView
- (void)addObserver:(NSObject *)observer
forKeyPath:(NSString *)keyPath
options:(NSKeyValueObservingOptions)options
context:(void *)context {
[super addObserver:observer forKeyPath:keyPath options:options context:context];
if ([keyPath isEqualToString:@"frame"]) {
++self.frameObserverCount;
}
}
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath {
[super removeObserver:observer forKeyPath:keyPath];
if ([keyPath isEqualToString:@"frame"]) {
--self.frameObserverCount;
}
}
@end
| plugins/packages/google_maps_flutter/google_maps_flutter_ios/example/ios/RunnerTests/PartiallyMockedMapView.m/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_ios/example/ios/RunnerTests/PartiallyMockedMapView.m",
"repo_id": "plugins",
"token_count": 310
} | 1,159 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show immutable;
/// Joint types for [Polyline].
@immutable
class JointType {
const JointType._(this.value);
/// The value representing the [JointType] on the sdk.
final int value;
/// Mitered joint, with fixed pointed extrusion equal to half the stroke width on the outside of the joint.
///
/// Constant Value: 0
static const JointType mitered = JointType._(0);
/// Flat bevel on the outside of the joint.
///
/// Constant Value: 1
static const JointType bevel = JointType._(1);
/// Rounded on the outside of the joint by an arc of radius equal to half the stroke width, centered at the vertex.
///
/// Constant Value: 2
static const JointType round = JointType._(2);
}
| plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/joint_type.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/joint_type.dart",
"repo_id": "plugins",
"token_count": 255
} | 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_test/flutter_test.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Can initialize the plugin', (WidgetTester tester) async {
final GoogleSignIn signIn = GoogleSignIn();
expect(signIn, isNotNull);
});
}
| plugins/packages/google_sign_in/google_sign_in/example/integration_test/google_sign_in_test.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/example/integration_test/google_sign_in_test.dart",
"repo_id": "plugins",
"token_count": 174
} | 1,161 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_sign_in/google_sign_in.dart';
/// A instantiable class that extends [GoogleIdentity]
class _TestGoogleIdentity extends GoogleIdentity {
_TestGoogleIdentity({
required this.id,
required this.email,
this.photoUrl,
});
@override
final String id;
@override
final String email;
@override
final String? photoUrl;
@override
String? get displayName => null;
@override
String? get serverAuthCode => null;
}
/// A mocked [HttpClient] which always returns a [_MockHttpRequest].
class _MockHttpClient extends Fake implements HttpClient {
@override
bool autoUncompress = true;
@override
Future<HttpClientRequest> getUrl(Uri url) {
return Future<HttpClientRequest>.value(_MockHttpRequest());
}
}
/// A mocked [HttpClientRequest] which always returns a [_MockHttpClientResponse].
class _MockHttpRequest extends Fake implements HttpClientRequest {
@override
Future<HttpClientResponse> close() {
return Future<HttpClientResponse>.value(_MockHttpResponse());
}
}
/// Arbitrary valid image returned by the [_MockHttpResponse].
///
/// This is an transparent 1x1 gif image.
/// It doesn't have to match the placeholder used in [GoogleUserCircleAvatar].
///
/// Those bytes come from `resources/transparentImage.gif`.
final Uint8List _transparentImage = Uint8List.fromList(
<int>[
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, //
0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x21, 0xf9, 0x04, 0x01, 0x00, //
0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, //
0x00, 0x02, 0x01, 0x44, 0x00, 0x3B
],
);
/// A mocked [HttpClientResponse] which is empty and has a [statusCode] of 200
/// and returns valid image.
class _MockHttpResponse extends Fake implements HttpClientResponse {
final Stream<Uint8List> _delegate =
Stream<Uint8List>.value(_transparentImage);
@override
int get contentLength => -1;
@override
HttpClientResponseCompressionState get compressionState {
return HttpClientResponseCompressionState.decompressed;
}
@override
StreamSubscription<Uint8List> listen(void Function(Uint8List event)? onData,
{Function? onError, void Function()? onDone, bool? cancelOnError}) {
return _delegate.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
@override
int get statusCode => 200;
}
void main() {
testWidgets('It should build the GoogleUserCircleAvatar successfully',
(WidgetTester tester) async {
final GoogleIdentity identity = _TestGoogleIdentity(
email: '[email protected]',
id: 'userId',
photoUrl: 'photoUrl',
);
tester.binding.window.physicalSizeTestValue = const Size(100, 100);
await HttpOverrides.runZoned(
() async {
await tester.pumpWidget(MaterialApp(
home: SizedBox(
height: 100,
width: 100,
child: GoogleUserCircleAvatar(
identity: identity,
),
),
));
},
createHttpClient: (SecurityContext? c) => _MockHttpClient(),
);
});
}
| plugins/packages/google_sign_in/google_sign_in/test/widgets_test.dart/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in/test/widgets_test.dart",
"repo_id": "plugins",
"token_count": 1283
} | 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 Flutter;
@import XCTest;
@import google_sign_in_ios;
@import google_sign_in_ios.Test;
@import GoogleSignIn;
// OCMock library doesn't generate a valid modulemap.
#import <OCMock/OCMock.h>
@interface FLTGoogleSignInPluginTest : XCTestCase
@property(strong, nonatomic) NSObject<FlutterBinaryMessenger> *mockBinaryMessenger;
@property(strong, nonatomic) NSObject<FlutterPluginRegistrar> *mockPluginRegistrar;
@property(strong, nonatomic) FLTGoogleSignInPlugin *plugin;
@property(strong, nonatomic) id mockSignIn;
@end
@implementation FLTGoogleSignInPluginTest
- (void)setUp {
[super setUp];
self.mockBinaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
self.mockPluginRegistrar = OCMProtocolMock(@protocol(FlutterPluginRegistrar));
id mockSignIn = OCMClassMock([GIDSignIn class]);
self.mockSignIn = mockSignIn;
OCMStub(self.mockPluginRegistrar.messenger).andReturn(self.mockBinaryMessenger);
self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:mockSignIn];
[FLTGoogleSignInPlugin registerWithRegistrar:self.mockPluginRegistrar];
}
- (void)testUnimplementedMethod {
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"bogus"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(id result) {
XCTAssertEqualObjects(result, FlutterMethodNotImplemented);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testSignOut {
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"signOut"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(id result) {
XCTAssertNil(result);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
OCMVerify([self.mockSignIn signOut]);
}
- (void)testDisconnect {
[[self.mockSignIn stub] disconnectWithCallback:[OCMArg invokeBlockWithArgs:[NSNull null], nil]];
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"disconnect"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSDictionary *result) {
XCTAssertEqualObjects(result, @{});
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testDisconnectIgnoresError {
NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
code:kGIDSignInErrorCodeHasNoAuthInKeychain
userInfo:nil];
[[self.mockSignIn stub] disconnectWithCallback:[OCMArg invokeBlockWithArgs:error, nil]];
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"disconnect"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSDictionary *result) {
XCTAssertEqualObjects(result, @{});
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
#pragma mark - Init
- (void)testInitNoClientIdError {
// Init plugin without GoogleService-Info.plist.
self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:self.mockSignIn
withGoogleServiceProperties:nil];
// init call does not provide a clientId.
FlutterMethodCall *initMethodCall = [FlutterMethodCall methodCallWithMethodName:@"init"
arguments:@{}];
XCTestExpectation *initExpectation =
[self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:initMethodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"missing-config");
[initExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testInitGoogleServiceInfoPlist {
FlutterMethodCall *initMethodCall =
[FlutterMethodCall methodCallWithMethodName:@"init"
arguments:@{@"hostedDomain" : @"example.com"}];
XCTestExpectation *initExpectation =
[self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:initMethodCall
result:^(id result) {
XCTAssertNil(result);
[initExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
// Initialization values used in the next sign in request.
FlutterMethodCall *signInMethodCall = [FlutterMethodCall methodCallWithMethodName:@"signIn"
arguments:nil];
[self.plugin handleMethodCall:signInMethodCall
result:^(id r){
}];
OCMVerify([self.mockSignIn
signInWithConfiguration:[OCMArg checkWithBlock:^BOOL(GIDConfiguration *configuration) {
// Set in example app GoogleService-Info.plist.
return
[configuration.hostedDomain isEqualToString:@"example.com"] &&
[configuration.clientID
isEqualToString:
@"479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com"] &&
[configuration.serverClientID isEqualToString:@"YOUR_SERVER_CLIENT_ID"];
}]
presentingViewController:[OCMArg isKindOfClass:[FlutterViewController class]]
hint:nil
additionalScopes:OCMOCK_ANY
callback:OCMOCK_ANY]);
}
- (void)testInitDynamicClientIdNullDomain {
// Init plugin without GoogleService-Info.plist.
self.plugin = [[FLTGoogleSignInPlugin alloc] initWithSignIn:self.mockSignIn
withGoogleServiceProperties:nil];
FlutterMethodCall *initMethodCall = [FlutterMethodCall
methodCallWithMethodName:@"init"
arguments:@{@"hostedDomain" : [NSNull null], @"clientId" : @"mockClientId"}];
XCTestExpectation *initExpectation =
[self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:initMethodCall
result:^(id result) {
XCTAssertNil(result);
[initExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
// Initialization values used in the next sign in request.
FlutterMethodCall *signInMethodCall = [FlutterMethodCall methodCallWithMethodName:@"signIn"
arguments:nil];
[self.plugin handleMethodCall:signInMethodCall
result:^(id r){
}];
OCMVerify([self.mockSignIn
signInWithConfiguration:[OCMArg checkWithBlock:^BOOL(GIDConfiguration *configuration) {
return configuration.hostedDomain == nil &&
[configuration.clientID isEqualToString:@"mockClientId"];
}]
presentingViewController:[OCMArg isKindOfClass:[FlutterViewController class]]
hint:nil
additionalScopes:OCMOCK_ANY
callback:OCMOCK_ANY]);
}
- (void)testInitDynamicServerClientIdNullDomain {
FlutterMethodCall *initMethodCall =
[FlutterMethodCall methodCallWithMethodName:@"init"
arguments:@{
@"hostedDomain" : [NSNull null],
@"serverClientId" : @"mockServerClientId"
}];
XCTestExpectation *initExpectation =
[self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:initMethodCall
result:^(id result) {
XCTAssertNil(result);
[initExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
// Initialization values used in the next sign in request.
FlutterMethodCall *signInMethodCall = [FlutterMethodCall methodCallWithMethodName:@"signIn"
arguments:nil];
[self.plugin handleMethodCall:signInMethodCall
result:^(id r){
}];
OCMVerify([self.mockSignIn
signInWithConfiguration:[OCMArg checkWithBlock:^BOOL(GIDConfiguration *configuration) {
return configuration.hostedDomain == nil &&
[configuration.serverClientID isEqualToString:@"mockServerClientId"];
}]
presentingViewController:[OCMArg isKindOfClass:[FlutterViewController class]]
hint:nil
additionalScopes:OCMOCK_ANY
callback:OCMOCK_ANY]);
}
#pragma mark - Is signed in
- (void)testIsNotSignedIn {
OCMStub([self.mockSignIn hasPreviousSignIn]).andReturn(NO);
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"isSignedIn"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSNumber *result) {
XCTAssertFalse(result.boolValue);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testIsSignedIn {
OCMStub([self.mockSignIn hasPreviousSignIn]).andReturn(YES);
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"isSignedIn"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSNumber *result) {
XCTAssertTrue(result.boolValue);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
#pragma mark - Sign in silently
- (void)testSignInSilently {
id mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([mockUser userID]).andReturn(@"mockID");
[[self.mockSignIn stub]
restorePreviousSignInWithCallback:[OCMArg invokeBlockWithArgs:mockUser, [NSNull null], nil]];
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"signInSilently"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSDictionary<NSString *, NSString *> *result) {
XCTAssertEqualObjects(result[@"displayName"], [NSNull null]);
XCTAssertEqualObjects(result[@"email"], [NSNull null]);
XCTAssertEqualObjects(result[@"id"], @"mockID");
XCTAssertEqualObjects(result[@"photoUrl"], [NSNull null]);
XCTAssertEqualObjects(result[@"serverAuthCode"], [NSNull null]);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testSignInSilentlyWithError {
NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
code:kGIDSignInErrorCodeHasNoAuthInKeychain
userInfo:nil];
[[self.mockSignIn stub]
restorePreviousSignInWithCallback:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"signInSilently"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"sign_in_required");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
#pragma mark - Sign in
- (void)testSignIn {
id mockUser = OCMClassMock([GIDGoogleUser class]);
id mockUserProfile = OCMClassMock([GIDProfileData class]);
OCMStub([mockUserProfile name]).andReturn(@"mockDisplay");
OCMStub([mockUserProfile email]).andReturn(@"[email protected]");
OCMStub([mockUserProfile hasImage]).andReturn(YES);
OCMStub([mockUserProfile imageURLWithDimension:1337])
.andReturn([NSURL URLWithString:@"https://example.com/profile.png"]);
OCMStub([mockUser profile]).andReturn(mockUserProfile);
OCMStub([mockUser userID]).andReturn(@"mockID");
OCMStub([mockUser serverAuthCode]).andReturn(@"mockAuthCode");
[[self.mockSignIn expect]
signInWithConfiguration:[OCMArg checkWithBlock:^BOOL(GIDConfiguration *configuration) {
return [configuration.clientID
isEqualToString:
@"479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com"];
}]
presentingViewController:[OCMArg isKindOfClass:[FlutterViewController class]]
hint:nil
additionalScopes:@[]
callback:[OCMArg invokeBlockWithArgs:mockUser, [NSNull null], nil]];
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"signIn"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin
handleMethodCall:methodCall
result:^(NSDictionary<NSString *, NSString *> *result) {
XCTAssertEqualObjects(result[@"displayName"], @"mockDisplay");
XCTAssertEqualObjects(result[@"email"], @"[email protected]");
XCTAssertEqualObjects(result[@"id"], @"mockID");
XCTAssertEqualObjects(result[@"photoUrl"], @"https://example.com/profile.png");
XCTAssertEqualObjects(result[@"serverAuthCode"], @"mockAuthCode");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
OCMVerifyAll(self.mockSignIn);
}
- (void)testSignInWithInitializedScopes {
FlutterMethodCall *initMethodCall =
[FlutterMethodCall methodCallWithMethodName:@"init"
arguments:@{@"scopes" : @[ @"initial1", @"initial2" ]}];
XCTestExpectation *initExpectation =
[self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:initMethodCall
result:^(id result) {
XCTAssertNil(result);
[initExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
id mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([mockUser userID]).andReturn(@"mockID");
[[self.mockSignIn expect]
signInWithConfiguration:OCMOCK_ANY
presentingViewController:OCMOCK_ANY
hint:nil
additionalScopes:[OCMArg checkWithBlock:^BOOL(NSArray<NSString *> *scopes) {
return [[NSSet setWithArray:scopes]
isEqualToSet:[NSSet setWithObjects:@"initial1", @"initial2", nil]];
}]
callback:[OCMArg invokeBlockWithArgs:mockUser, [NSNull null], nil]];
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"signIn"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSDictionary<NSString *, NSString *> *result) {
XCTAssertEqualObjects(result[@"id"], @"mockID");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
OCMVerifyAll(self.mockSignIn);
}
- (void)testSignInAlreadyGranted {
id mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([mockUser userID]).andReturn(@"mockID");
[[self.mockSignIn stub]
signInWithConfiguration:OCMOCK_ANY
presentingViewController:OCMOCK_ANY
hint:nil
additionalScopes:OCMOCK_ANY
callback:[OCMArg invokeBlockWithArgs:mockUser, [NSNull null], nil]];
NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
code:kGIDSignInErrorCodeScopesAlreadyGranted
userInfo:nil];
[[self.mockSignIn stub] addScopes:OCMOCK_ANY
presentingViewController:OCMOCK_ANY
callback:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"signIn"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSDictionary<NSString *, NSString *> *result) {
XCTAssertEqualObjects(result[@"id"], @"mockID");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testSignInError {
NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
code:kGIDSignInErrorCodeCanceled
userInfo:nil];
[[self.mockSignIn stub]
signInWithConfiguration:OCMOCK_ANY
presentingViewController:OCMOCK_ANY
hint:nil
additionalScopes:OCMOCK_ANY
callback:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"signIn"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"sign_in_canceled");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testSignInException {
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"signIn"
arguments:nil];
OCMExpect([self.mockSignIn signInWithConfiguration:OCMOCK_ANY
presentingViewController:OCMOCK_ANY
hint:OCMOCK_ANY
additionalScopes:OCMOCK_ANY
callback:OCMOCK_ANY])
.andThrow([NSException exceptionWithName:@"MockName" reason:@"MockReason" userInfo:nil]);
__block FlutterError *error;
XCTAssertThrows([self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
error = result;
}]);
XCTAssertEqualObjects(error.code, @"google_sign_in");
XCTAssertEqualObjects(error.message, @"MockReason");
XCTAssertEqualObjects(error.details, @"MockName");
}
#pragma mark - Get tokens
- (void)testGetTokens {
id mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([self.mockSignIn currentUser]).andReturn(mockUser);
id mockAuthentication = OCMClassMock([GIDAuthentication class]);
OCMStub([mockAuthentication idToken]).andReturn(@"mockIdToken");
OCMStub([mockAuthentication accessToken]).andReturn(@"mockAccessToken");
[[mockAuthentication stub]
doWithFreshTokens:[OCMArg invokeBlockWithArgs:mockAuthentication, [NSNull null], nil]];
OCMStub([mockUser authentication]).andReturn(mockAuthentication);
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"getTokens"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSDictionary<NSString *, NSString *> *result) {
XCTAssertEqualObjects(result[@"idToken"], @"mockIdToken");
XCTAssertEqualObjects(result[@"accessToken"], @"mockAccessToken");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testGetTokensNoAuthKeychainError {
id mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([self.mockSignIn currentUser]).andReturn(mockUser);
id mockAuthentication = OCMClassMock([GIDAuthentication class]);
NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
code:kGIDSignInErrorCodeHasNoAuthInKeychain
userInfo:nil];
[[mockAuthentication stub]
doWithFreshTokens:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
OCMStub([mockUser authentication]).andReturn(mockAuthentication);
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"getTokens"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"sign_in_required");
XCTAssertEqualObjects(result.message, kGIDSignInErrorDomain);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testGetTokensCancelledError {
id mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([self.mockSignIn currentUser]).andReturn(mockUser);
id mockAuthentication = OCMClassMock([GIDAuthentication class]);
NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
code:kGIDSignInErrorCodeCanceled
userInfo:nil];
[[mockAuthentication stub]
doWithFreshTokens:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
OCMStub([mockUser authentication]).andReturn(mockAuthentication);
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"getTokens"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"sign_in_canceled");
XCTAssertEqualObjects(result.message, kGIDSignInErrorDomain);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testGetTokensURLError {
id mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([self.mockSignIn currentUser]).andReturn(mockUser);
id mockAuthentication = OCMClassMock([GIDAuthentication class]);
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:nil];
[[mockAuthentication stub]
doWithFreshTokens:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
OCMStub([mockUser authentication]).andReturn(mockAuthentication);
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"getTokens"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"network_error");
XCTAssertEqualObjects(result.message, NSURLErrorDomain);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testGetTokensUnknownError {
id mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([self.mockSignIn currentUser]).andReturn(mockUser);
id mockAuthentication = OCMClassMock([GIDAuthentication class]);
NSError *error = [NSError errorWithDomain:@"BogusDomain" code:42 userInfo:nil];
[[mockAuthentication stub]
doWithFreshTokens:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
OCMStub([mockUser authentication]).andReturn(mockAuthentication);
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"getTokens"
arguments:nil];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"sign_in_failed");
XCTAssertEqualObjects(result.message, @"BogusDomain");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
#pragma mark - Request scopes
- (void)testRequestScopesResultErrorIfNotSignedIn {
NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
code:kGIDSignInErrorCodeNoCurrentUser
userInfo:nil];
[[self.mockSignIn stub] addScopes:@[ @"mockScope1" ]
presentingViewController:OCMOCK_ANY
callback:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
FlutterMethodCall *methodCall =
[FlutterMethodCall methodCallWithMethodName:@"requestScopes"
arguments:@{@"scopes" : @[ @"mockScope1" ]}];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"sign_in_required");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testRequestScopesIfNoMissingScope {
NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
code:kGIDSignInErrorCodeScopesAlreadyGranted
userInfo:nil];
[[self.mockSignIn stub] addScopes:@[ @"mockScope1" ]
presentingViewController:OCMOCK_ANY
callback:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
FlutterMethodCall *methodCall =
[FlutterMethodCall methodCallWithMethodName:@"requestScopes"
arguments:@{@"scopes" : @[ @"mockScope1" ]}];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSNumber *result) {
XCTAssertTrue(result.boolValue);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testRequestScopesWithUnknownError {
NSError *error = [NSError errorWithDomain:@"BogusDomain" code:42 userInfo:nil];
[[self.mockSignIn stub] addScopes:@[ @"mockScope1" ]
presentingViewController:OCMOCK_ANY
callback:[OCMArg invokeBlockWithArgs:[NSNull null], error, nil]];
FlutterMethodCall *methodCall =
[FlutterMethodCall methodCallWithMethodName:@"requestScopes"
arguments:@{@"scopes" : @[ @"mockScope1" ]}];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSNumber *result) {
XCTAssertFalse(result.boolValue);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testRequestScopesException {
FlutterMethodCall *methodCall = [FlutterMethodCall methodCallWithMethodName:@"requestScopes"
arguments:nil];
OCMExpect([self.mockSignIn addScopes:@[] presentingViewController:OCMOCK_ANY callback:OCMOCK_ANY])
.andThrow([NSException exceptionWithName:@"MockName" reason:@"MockReason" userInfo:nil]);
[self.plugin handleMethodCall:methodCall
result:^(FlutterError *result) {
XCTAssertEqualObjects(result.code, @"request_scopes");
XCTAssertEqualObjects(result.message, @"MockReason");
XCTAssertEqualObjects(result.details, @"MockName");
}];
}
- (void)testRequestScopesReturnsFalseIfOnlySubsetGranted {
GIDGoogleUser *mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([self.mockSignIn currentUser]).andReturn(mockUser);
NSArray<NSString *> *requestedScopes = @[ @"mockScope1", @"mockScope2" ];
// Only grant one of the two requested scopes.
OCMStub(mockUser.grantedScopes).andReturn(@[ @"mockScope1" ]);
[[self.mockSignIn stub] addScopes:requestedScopes
presentingViewController:OCMOCK_ANY
callback:[OCMArg invokeBlockWithArgs:mockUser, [NSNull null], nil]];
FlutterMethodCall *methodCall =
[FlutterMethodCall methodCallWithMethodName:@"requestScopes"
arguments:@{@"scopes" : requestedScopes}];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns false"];
[self.plugin handleMethodCall:methodCall
result:^(NSNumber *result) {
XCTAssertFalse(result.boolValue);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
- (void)testRequestsInitializedScopes {
FlutterMethodCall *initMethodCall =
[FlutterMethodCall methodCallWithMethodName:@"init"
arguments:@{@"scopes" : @[ @"initial1", @"initial2" ]}];
XCTestExpectation *initExpectation =
[self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:initMethodCall
result:^(id result) {
XCTAssertNil(result);
[initExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
// Include one of the initially requested scopes.
NSArray<NSString *> *addedScopes = @[ @"initial1", @"addScope1", @"addScope2" ];
FlutterMethodCall *methodCall =
[FlutterMethodCall methodCallWithMethodName:@"requestScopes"
arguments:@{@"scopes" : addedScopes}];
[self.plugin handleMethodCall:methodCall
result:^(id result){
}];
// All four scopes are requested.
[[self.mockSignIn verify]
addScopes:[OCMArg checkWithBlock:^BOOL(NSArray<NSString *> *scopes) {
return [[NSSet setWithArray:scopes]
isEqualToSet:[NSSet setWithObjects:@"initial1", @"initial2",
@"addScope1", @"addScope2", nil]];
}]
presentingViewController:OCMOCK_ANY
callback:OCMOCK_ANY];
}
- (void)testRequestScopesReturnsTrueIfGranted {
GIDGoogleUser *mockUser = OCMClassMock([GIDGoogleUser class]);
OCMStub([self.mockSignIn currentUser]).andReturn(mockUser);
NSArray<NSString *> *requestedScopes = @[ @"mockScope1", @"mockScope2" ];
// Grant both of the requested scopes.
OCMStub(mockUser.grantedScopes).andReturn(requestedScopes);
[[self.mockSignIn stub] addScopes:requestedScopes
presentingViewController:OCMOCK_ANY
callback:[OCMArg invokeBlockWithArgs:mockUser, [NSNull null], nil]];
FlutterMethodCall *methodCall =
[FlutterMethodCall methodCallWithMethodName:@"requestScopes"
arguments:@{@"scopes" : requestedScopes}];
XCTestExpectation *expectation = [self expectationWithDescription:@"expect result returns true"];
[self.plugin handleMethodCall:methodCall
result:^(NSNumber *result) {
XCTAssertTrue(result.boolValue);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:5.0 handler:nil];
}
@end
| plugins/packages/google_sign_in/google_sign_in_ios/example/ios/RunnerTests/GoogleSignInTests.m/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_ios/example/ios/RunnerTests/GoogleSignInTests.m",
"repo_id": "plugins",
"token_count": 16782
} | 1,163 |
name: google_sign_in_ios
description: iOS implementation of the google_sign_in plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/google_sign_in/google_sign_in_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22
version: 5.5.1
environment:
sdk: ">=2.14.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
implements: google_sign_in
platforms:
ios:
dartPluginClass: GoogleSignInIOS
pluginClass: FLTGoogleSignInPlugin
dependencies:
flutter:
sdk: flutter
google_sign_in_platform_interface: ^2.2.0
dev_dependencies:
flutter_driver:
sdk: flutter
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
# The example deliberately includes limited-use secrets.
false_secrets:
- /example/ios/Runner/GoogleService-Info.plist
- /example/ios/RunnerTests/GoogleSignInTests.m
- /example/lib/main.dart
| plugins/packages/google_sign_in/google_sign_in_ios/pubspec.yaml/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_ios/pubspec.yaml",
"repo_id": "plugins",
"token_count": 383
} | 1,164 |
# google\_sign\_in\_web
The web implementation of [google_sign_in](https://pub.dev/packages/google_sign_in)
## Migrating to v0.11 (Google Identity Services)
The `google_sign_in_web` plugin is backed by the new Google Identity Services
(GIS) JS SDK since version 0.11.0.
The GIS SDK is used both for [Authentication](https://developers.google.com/identity/gsi/web/guides/overview)
and [Authorization](https://developers.google.com/identity/oauth2/web/guides/overview) flows.
The GIS SDK, however, doesn't behave exactly like the one being deprecated.
Some concepts have experienced pretty drastic changes, and that's why this
plugin required a major version update.
### Differences between Google Identity Services SDK and Google Sign-In for Web SDK.
The **Google Sign-In JavaScript for Web JS SDK** is set to be deprecated after
March 31, 2023. **Google Identity Services (GIS) SDK** is the new solution to
quickly and easily sign users into your app suing their Google accounts.
* In the GIS SDK, Authentication and Authorization are now two separate concerns.
* Authentication (information about the current user) flows will not
authorize `scopes` anymore.
* Authorization (permissions for the app to access certain user information)
flows will not return authentication information.
* The GIS SDK no longer has direct access to previously-seen users upon initialization.
* `signInSilently` now displays the One Tap UX for web.
* The GIS SDK only provides an `idToken` (JWT-encoded info) when the user
successfully completes an authentication flow. In the plugin: `signInSilently`.
* The plugin `signIn` method uses the Oauth "Implicit Flow" to Authorize the requested `scopes`.
* If the user hasn't `signInSilently`, they'll have to sign in as a first step
of the Authorization popup flow.
* If `signInSilently` was unsuccessful, the plugin will add extra `scopes` to
`signIn` and retrieve basic Profile information from the People API via a
REST call immediately after a successful authorization. In this case, the
`idToken` field of the `GoogleSignInUserData` will always be null.
* The GIS SDK no longer handles sign-in state and user sessions, it only provides
Authentication credentials for the moment the user did authenticate.
* The GIS SDK no longer is able to renew Authorization sessions on the web.
Once the token expires, API requests will begin to fail with unauthorized,
and user Authorization is required again.
See more differences in the following migration guides:
* Authentication > [Migrating from Google Sign-In](https://developers.google.com/identity/gsi/web/guides/migration)
* Authorization > [Migrate to Google Identity Services](https://developers.google.com/identity/oauth2/web/guides/migration-to-gis)
### New use cases to take into account in your app
#### Enable access to the People API for your GCP project
Since the GIS SDK is separating Authentication from Authorization, the
[Oauth Implicit pop-up flow](https://developers.google.com/identity/oauth2/web/guides/use-token-model)
used to Authorize scopes does **not** return any Authentication information
anymore (user credential / `idToken`).
If the plugin is not able to Authenticate an user from `signInSilently` (the
OneTap UX flow), it'll add extra `scopes` to those requested by the programmer
so it can perform a [People API request](https://developers.google.com/people/api/rest/v1/people/get)
to retrieve basic profile information about the user that is signed-in.
The information retrieved from the People API is used to complete data for the
[`GoogleSignInAccount`](https://pub.dev/documentation/google_sign_in/latest/google_sign_in/GoogleSignInAccount-class.html)
object that is returned after `signIn` completes successfully.
#### `signInSilently` always returns `null`
Previous versions of this plugin were able to return a `GoogleSignInAccount`
object that was fully populated (signed-in and authorized) from `signInSilently`
because the former SDK equated "is authenticated" and "is authorized".
With the GIS SDK, `signInSilently` only deals with user Authentication, so users
retrieved "silently" will only contain an `idToken`, but not an `accessToken`.
Only after `signIn` or `requestScopes`, a user will be fully formed.
The GIS-backed plugin always returns `null` from `signInSilently`, to force apps
that expect the former logic to perform a full `signIn`, which will result in a
fully Authenticated and Authorized user, and making this migration easier.
#### `idToken` is `null` in the `GoogleSignInAccount` object after `signIn`
Since the GIS SDK is separating Authentication and Authorization, when a user
fails to Authenticate through `signInSilently` and the plugin performs the
fallback request to the People API described above,
the returned `GoogleSignInUserData` object will contain basic profile information
(name, email, photo, ID), but its `idToken` will be `null`.
This is because JWT are cryptographically signed by Google Identity Services, and
this plugin won't spoof that signature when it retrieves the information from a
simple REST request.
#### User Sessions
Since the GIS SDK does _not_ manage user sessions anymore, apps that relied on
this feature might break.
If long-lived sessions are required, consider using some user authentication
system that supports Google Sign In as a federated Authentication provider,
like [Firebase Auth](https://firebase.google.com/docs/auth/flutter/federated-auth#google),
or similar.
#### Expired / Invalid Authorization Tokens
Since the GIS SDK does _not_ auto-renew authorization tokens anymore, it's now
the responsibility of your app to do so.
Apps now need to monitor the status code of their REST API requests for response
codes different to `200`. For example:
* `401`: Missing or invalid access token.
* `403`: Expired access token.
In either case, your app needs to prompt the end user to `signIn` or
`requestScopes`, to interactively renew the token.
The GIS SDK limits authorization token duration to one hour (3600 seconds).
## Usage
### Import the package
This package is [endorsed](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin),
which means you can simply use `google_sign_in`
normally. This package will be automatically included in your app when you do.
### Web integration
First, go through the instructions [here](https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid) to create your Google Sign-In OAuth client ID.
On your `web/index.html` file, add the following `meta` tag, somewhere in the
`head` of the document:
```html
<meta name="google-signin-client_id" content="YOUR_GOOGLE_SIGN_IN_OAUTH_CLIENT_ID.apps.googleusercontent.com">
```
For this client to work correctly, the last step is to configure the **Authorized JavaScript origins**, which _identify the domains from which your application can send API requests._ When in local development, this is normally `localhost` and some port.
You can do this by:
1. Going to the [Credentials page](https://console.developers.google.com/apis/credentials).
2. Clicking "Edit" in the OAuth 2.0 Web application client that you created above.
3. Adding the URIs you want to the **Authorized JavaScript origins**.
For local development, you must add two `localhost` entries:
* `http://localhost` and
* `http://localhost:7357` (or any port that is free in your machine)
#### Starting flutter in http://localhost:7357
Normally `flutter run` starts in a random port. In the case where you need to deal with authentication like the above, that's not the most appropriate behavior.
You can tell `flutter run` to listen for requests in a specific host and port with the following:
```sh
flutter run -d chrome --web-hostname localhost --web-port 7357
```
### Other APIs
Read the rest of the instructions if you need to add extra APIs (like Google People API).
### Using the plugin
See the [**Usage** instructions of `package:google_sign_in`](https://pub.dev/packages/google_sign_in#usage)
Note that the **`serverClientId` parameter of the `GoogleSignIn` constructor is not supported on Web.**
## Example
Find the example wiring in the [Google sign-in example application](https://github.com/flutter/plugins/blob/main/packages/google_sign_in/google_sign_in/example/lib/main.dart).
## API details
See [google_sign_in.dart](https://github.com/flutter/plugins/blob/main/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart) for more API details.
## Contributions and Testing
Tests are crucial for contributions to this package. All new contributions should be reasonably tested.
**Check the [`test/README.md` file](https://github.com/flutter/plugins/blob/main/packages/google_sign_in/google_sign_in_web/test/README.md)** for more information on how to run tests on this package.
Contributions to this package are welcome. Read the [Contributing to Flutter Plugins](https://github.com/flutter/plugins/blob/main/CONTRIBUTING.md) guide to get started.
## Issues and feedback
Please file [issues](https://github.com/flutter/flutter/issues/new)
to send feedback or report a bug.
**Thank you!**
| plugins/packages/google_sign_in/google_sign_in_web/README.md/0 | {
"file_path": "plugins/packages/google_sign_in/google_sign_in_web/README.md",
"repo_id": "plugins",
"token_count": 2482
} | 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'image_picker_test.mocks.dart' as base_mock;
// Add the mixin to make the platform interface accept the mock.
class MockImagePickerPlatform extends base_mock.MockImagePickerPlatform
with MockPlatformInterfaceMixin {}
@GenerateMocks(<Type>[ImagePickerPlatform])
void main() {
group('ImagePicker', () {
late MockImagePickerPlatform mockPlatform;
setUp(() {
mockPlatform = MockImagePickerPlatform();
ImagePickerPlatform.instance = mockPlatform;
});
group('#Single image/video', () {
group('#pickImage', () {
setUp(() {
when(mockPlatform.getImageFromSource(
source: anyNamed('source'), options: anyNamed('options')))
.thenAnswer((Invocation _) async => null);
});
test('passes the image source argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(source: ImageSource.camera);
await picker.pickImage(source: ImageSource.gallery);
verifyInOrder(<Object>[
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>(),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.gallery,
options: argThat(
isInstanceOf<ImagePickerOptions>(),
named: 'options',
),
),
]);
});
test('passes the width and height arguments correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(source: ImageSource.camera);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
);
await picker.pickImage(
source: ImageSource.camera,
maxHeight: 10.0,
);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.pickImage(
source: ImageSource.camera, maxWidth: 10.0, imageQuality: 70);
await picker.pickImage(
source: ImageSource.camera, maxHeight: 10.0, imageQuality: 70);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
maxHeight: 20.0,
imageQuality: 70);
verifyInOrder(<Object>[
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', isNull)
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', isNull)
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
isNull),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', equals(10.0))
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', isNull)
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
isNull),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', isNull)
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', equals(10.0))
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
isNull),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', equals(10.0))
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', equals(20.0))
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
isNull),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', equals(10.0))
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', isNull)
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', isNull)
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', equals(10.0))
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', equals(10.0))
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', equals(20.0))
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
]);
});
test('does not accept a negative width or height argument', () {
final ImagePicker picker = ImagePicker();
expect(
() => picker.pickImage(source: ImageSource.camera, maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickImage(source: ImageSource.camera, maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles a null image file response gracefully', () async {
final ImagePicker picker = ImagePicker();
expect(await picker.pickImage(source: ImageSource.gallery), isNull);
expect(await picker.pickImage(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(source: ImageSource.camera);
verify(mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>().having(
(ImagePickerOptions options) => options.preferredCameraDevice,
'preferredCameraDevice',
equals(CameraDevice.rear)),
named: 'options',
),
));
});
test('camera position can set to front', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
verify(mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>().having(
(ImagePickerOptions options) => options.preferredCameraDevice,
'preferredCameraDevice',
equals(CameraDevice.front)),
named: 'options',
),
));
});
test('full metadata argument defaults to true', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(source: ImageSource.gallery);
verify(mockPlatform.getImageFromSource(
source: ImageSource.gallery,
options: argThat(
isInstanceOf<ImagePickerOptions>().having(
(ImagePickerOptions options) => options.requestFullMetadata,
'requestFullMetadata',
isTrue),
named: 'options',
),
));
});
test('passes the full metadata argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(
source: ImageSource.gallery,
requestFullMetadata: false,
);
verify(mockPlatform.getImageFromSource(
source: ImageSource.gallery,
options: argThat(
isInstanceOf<ImagePickerOptions>().having(
(ImagePickerOptions options) => options.requestFullMetadata,
'requestFullMetadata',
isFalse),
named: 'options',
),
));
});
});
group('#pickVideo', () {
setUp(() {
when(mockPlatform.getVideo(
source: anyNamed('source'),
preferredCameraDevice: anyNamed('preferredCameraDevice'),
maxDuration: anyNamed('maxDuration')))
.thenAnswer((Invocation _) async => null);
});
test('passes the image source argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickVideo(source: ImageSource.camera);
await picker.pickVideo(source: ImageSource.gallery);
verifyInOrder(<Object>[
mockPlatform.getVideo(source: ImageSource.camera),
mockPlatform.getVideo(source: ImageSource.gallery),
]);
});
test('passes the duration argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickVideo(source: ImageSource.camera);
await picker.pickVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 10));
verifyInOrder(<Object>[
mockPlatform.getVideo(source: ImageSource.camera),
mockPlatform.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 10)),
]);
});
test('handles a null video file response gracefully', () async {
final ImagePicker picker = ImagePicker();
expect(await picker.pickVideo(source: ImageSource.gallery), isNull);
expect(await picker.pickVideo(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
final ImagePicker picker = ImagePicker();
await picker.pickVideo(source: ImageSource.camera);
verify(mockPlatform.getVideo(source: ImageSource.camera));
});
test('camera position can set to front', () async {
final ImagePicker picker = ImagePicker();
await picker.pickVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
verify(mockPlatform.getVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front));
});
});
group('#retrieveLostData', () {
test('retrieveLostData get success response', () async {
final ImagePicker picker = ImagePicker();
final XFile lostFile = XFile('/example/path');
when(mockPlatform.getLostData()).thenAnswer((Invocation _) async =>
LostDataResponse(
file: lostFile,
files: <XFile>[lostFile],
type: RetrieveType.image));
final LostDataResponse response = await picker.retrieveLostData();
expect(response.type, RetrieveType.image);
expect(response.file!.path, '/example/path');
});
test('retrieveLostData should successfully retrieve multiple files',
() async {
final ImagePicker picker = ImagePicker();
final List<XFile> lostFiles = <XFile>[
XFile('/example/path0'),
XFile('/example/path1'),
];
when(mockPlatform.getLostData()).thenAnswer((Invocation _) async =>
LostDataResponse(
file: lostFiles.last,
files: lostFiles,
type: RetrieveType.image));
final LostDataResponse response = await picker.retrieveLostData();
expect(response.type, RetrieveType.image);
expect(response.file, isNotNull);
expect(response.file!.path, '/example/path1');
expect(response.files!.first.path, '/example/path0');
expect(response.files!.length, 2);
});
test('retrieveLostData get error response', () async {
final ImagePicker picker = ImagePicker();
when(mockPlatform.getLostData()).thenAnswer((Invocation _) async =>
LostDataResponse(
exception: PlatformException(
code: 'test_error_code', message: 'test_error_message'),
type: RetrieveType.video));
final LostDataResponse response = await picker.retrieveLostData();
expect(response.type, RetrieveType.video);
expect(response.exception!.code, 'test_error_code');
expect(response.exception!.message, 'test_error_message');
});
});
});
group('#Multi images', () {
setUp(() {
when(
mockPlatform.getMultiImageWithOptions(
options: anyNamed('options'),
),
).thenAnswer((Invocation _) async => <XFile>[]);
});
group('#pickMultiImage', () {
test('passes the width and height arguments correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultiImage();
await picker.pickMultiImage(
maxWidth: 10.0,
);
await picker.pickMultiImage(
maxHeight: 10.0,
);
await picker.pickMultiImage(
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.pickMultiImage(
maxWidth: 10.0,
imageQuality: 70,
);
await picker.pickMultiImage(
maxHeight: 10.0,
imageQuality: 70,
);
await picker.pickMultiImage(
maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70);
verifyInOrder(<Object>[
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>(),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>().having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxWidth',
equals(10.0)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>().having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(10.0)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>()
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(20.0)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>()
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>()
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>()
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxHeight',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
]);
});
test('does not accept a negative width or height argument', () {
final ImagePicker picker = ImagePicker();
expect(
() => picker.pickMultiImage(maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickMultiImage(maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles an empty image file response gracefully', () async {
final ImagePicker picker = ImagePicker();
expect(await picker.pickMultiImage(), isEmpty);
expect(await picker.pickMultiImage(), isEmpty);
});
test('full metadata argument defaults to true', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultiImage();
verify(mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>().having(
(MultiImagePickerOptions options) =>
options.imageOptions.requestFullMetadata,
'requestFullMetadata',
isTrue),
named: 'options',
),
));
});
test('passes the full metadata argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultiImage(
requestFullMetadata: false,
);
verify(mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>().having(
(MultiImagePickerOptions options) =>
options.imageOptions.requestFullMetadata,
'requestFullMetadata',
isFalse),
named: 'options',
),
));
});
});
});
});
}
| plugins/packages/image_picker/image_picker/test/image_picker_test.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker/test/image_picker_test.dart",
"repo_id": "plugins",
"token_count": 11434
} | 1,166 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.imagepicker;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import androidx.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
class ImageResizer {
private final File externalFilesDirectory;
private final ExifDataCopier exifDataCopier;
ImageResizer(File externalFilesDirectory, ExifDataCopier exifDataCopier) {
this.externalFilesDirectory = externalFilesDirectory;
this.exifDataCopier = exifDataCopier;
}
/**
* If necessary, resizes the image located in imagePath and then returns the path for the scaled
* image.
*
* <p>If no resizing is needed, returns the path for the original image.
*/
String resizeImageIfNeeded(
String imagePath,
@Nullable Double maxWidth,
@Nullable Double maxHeight,
@Nullable Integer imageQuality) {
Bitmap bmp = decodeFile(imagePath);
if (bmp == null) {
return null;
}
boolean shouldScale =
maxWidth != null || maxHeight != null || isImageQualityValid(imageQuality);
if (!shouldScale) {
return imagePath;
}
try {
String[] pathParts = imagePath.split("/");
String imageName = pathParts[pathParts.length - 1];
File file = resizedImage(bmp, maxWidth, maxHeight, imageQuality, imageName);
copyExif(imagePath, file.getPath());
return file.getPath();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private File resizedImage(
Bitmap bmp, Double maxWidth, Double maxHeight, Integer imageQuality, String outputImageName)
throws IOException {
double originalWidth = bmp.getWidth() * 1.0;
double originalHeight = bmp.getHeight() * 1.0;
if (!isImageQualityValid(imageQuality)) {
imageQuality = 100;
}
boolean hasMaxWidth = maxWidth != null;
boolean hasMaxHeight = maxHeight != null;
Double width = hasMaxWidth ? Math.min(originalWidth, maxWidth) : originalWidth;
Double height = hasMaxHeight ? Math.min(originalHeight, maxHeight) : originalHeight;
boolean shouldDownscaleWidth = hasMaxWidth && maxWidth < originalWidth;
boolean shouldDownscaleHeight = hasMaxHeight && maxHeight < originalHeight;
boolean shouldDownscale = shouldDownscaleWidth || shouldDownscaleHeight;
if (shouldDownscale) {
double downscaledWidth = (height / originalHeight) * originalWidth;
double downscaledHeight = (width / originalWidth) * originalHeight;
if (width < height) {
if (!hasMaxWidth) {
width = downscaledWidth;
} else {
height = downscaledHeight;
}
} else if (height < width) {
if (!hasMaxHeight) {
height = downscaledHeight;
} else {
width = downscaledWidth;
}
} else {
if (originalWidth < originalHeight) {
width = downscaledWidth;
} else if (originalHeight < originalWidth) {
height = downscaledHeight;
}
}
}
Bitmap scaledBmp = createScaledBitmap(bmp, width.intValue(), height.intValue(), false);
File file =
createImageOnExternalDirectory("/scaled_" + outputImageName, scaledBmp, imageQuality);
return file;
}
private File createFile(File externalFilesDirectory, String child) {
File image = new File(externalFilesDirectory, child);
if (!image.getParentFile().exists()) {
image.getParentFile().mkdirs();
}
return image;
}
private FileOutputStream createOutputStream(File imageFile) throws IOException {
return new FileOutputStream(imageFile);
}
private void copyExif(String filePathOri, String filePathDest) {
exifDataCopier.copyExif(filePathOri, filePathDest);
}
private Bitmap decodeFile(String path) {
return BitmapFactory.decodeFile(path);
}
private Bitmap createScaledBitmap(Bitmap bmp, int width, int height, boolean filter) {
return Bitmap.createScaledBitmap(bmp, width, height, filter);
}
private boolean isImageQualityValid(Integer imageQuality) {
return imageQuality != null && imageQuality > 0 && imageQuality < 100;
}
private File createImageOnExternalDirectory(String name, Bitmap bitmap, int imageQuality)
throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
boolean saveAsPNG = bitmap.hasAlpha();
if (saveAsPNG) {
Log.d(
"ImageResizer",
"image_picker: compressing is not supported for type PNG. Returning the image with original quality");
}
bitmap.compress(
saveAsPNG ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG,
imageQuality,
outputStream);
File imageFile = createFile(externalFilesDirectory, name);
FileOutputStream fileOutput = createOutputStream(imageFile);
fileOutput.write(outputStream.toByteArray());
fileOutput.close();
return imageFile;
}
}
| plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImageResizer.java/0 | {
"file_path": "plugins/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImageResizer.java",
"repo_id": "plugins",
"token_count": 1785
} | 1,167 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartTestOut: 'test/test_api.g.dart',
objcHeaderOut: 'ios/Classes/messages.g.h',
objcSourceOut: 'ios/Classes/messages.g.m',
objcOptions: ObjcOptions(
prefix: 'FLT',
),
copyrightHeader: 'pigeons/copyright.txt',
))
class MaxSize {
MaxSize(this.width, this.height);
double? width;
double? height;
}
// Corresponds to `CameraDevice` from the platform interface package.
enum SourceCamera { rear, front }
// Corresponds to `ImageSource` from the platform interface package.
enum SourceType { camera, gallery }
class SourceSpecification {
SourceSpecification(this.type, this.camera);
SourceType type;
SourceCamera? camera;
}
@HostApi(dartHostTestHandler: 'TestHostImagePickerApi')
abstract class ImagePickerApi {
@async
@ObjCSelector('pickImageWithSource:maxSize:quality:fullMetadata:')
String? pickImage(SourceSpecification source, MaxSize maxSize,
int? imageQuality, bool requestFullMetadata);
@async
@ObjCSelector('pickMultiImageWithMaxSize:quality:fullMetadata:')
List<String>? pickMultiImage(
MaxSize maxSize, int? imageQuality, bool requestFullMetadata);
@async
@ObjCSelector('pickVideoWithSource:maxDuration:')
String? pickVideo(SourceSpecification source, int? maxDurationSeconds);
}
| plugins/packages/image_picker/image_picker_ios/pigeons/messages.dart/0 | {
"file_path": "plugins/packages/image_picker/image_picker_ios/pigeons/messages.dart",
"repo_id": "plugins",
"token_count": 503
} | 1,168 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.