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 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'src/messages.g.dart';
/// An implementation of [UrlLauncherPlatform] for Windows.
class UrlLauncherWindows extends UrlLauncherPlatform {
/// Creates a new plugin implementation instance.
UrlLauncherWindows({
@visibleForTesting UrlLauncherApi? api,
}) : _hostApi = api ?? UrlLauncherApi();
final UrlLauncherApi _hostApi;
/// Registers this class as the default instance of [UrlLauncherPlatform].
static void registerWith() {
UrlLauncherPlatform.instance = UrlLauncherWindows();
}
@override
final LinkDelegate? linkDelegate = null;
@override
Future<bool> canLaunch(String url) {
return _hostApi.canLaunchUrl(url);
}
@override
Future<bool> launch(
String url, {
required bool useSafariVC,
required bool useWebView,
required bool enableJavaScript,
required bool enableDomStorage,
required bool universalLinksOnly,
required Map<String, String> headers,
String? webOnlyWindowName,
}) async {
return _hostApi.launchUrl(url);
}
@override
Future<bool> supportsMode(PreferredLaunchMode mode) async {
return mode == PreferredLaunchMode.platformDefault ||
mode == PreferredLaunchMode.externalApplication;
}
@override
Future<bool> supportsCloseForMode(PreferredLaunchMode mode) async {
// No supported mode is closeable.
return false;
}
}
| packages/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart",
"repo_id": "packages",
"token_count": 537
} | 1,054 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:video_player/video_player.dart';
const Duration _playDuration = Duration(seconds: 1);
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets(
'can substitute one controller by another without crashing',
(WidgetTester tester) async {
// Use WebM for web to allow CI to use Chromium.
const String videoAssetKey =
kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4';
final VideoPlayerController controller = VideoPlayerController.asset(
videoAssetKey,
);
final VideoPlayerController another = VideoPlayerController.asset(
videoAssetKey,
);
await controller.initialize();
await another.initialize();
await controller.setVolume(0);
await another.setVolume(0);
final Completer<void> started = Completer<void>();
final Completer<void> ended = Completer<void>();
another.addListener(() {
if (another.value.isBuffering && !started.isCompleted) {
started.complete();
}
if (started.isCompleted &&
!another.value.isBuffering &&
!ended.isCompleted) {
ended.complete();
}
});
// Inject a widget with `controller`...
await tester.pumpWidget(renderVideoWidget(controller));
await controller.play();
await tester.pumpAndSettle(_playDuration);
await controller.pause();
// Disposing controller causes the Widget to crash in the next line
// (Issue https://github.com/flutter/flutter/issues/90046)
await controller.dispose();
// Now replace it with `another` controller...
await tester.pumpWidget(renderVideoWidget(another));
await another.play();
await another.seekTo(const Duration(seconds: 5));
await tester.pumpAndSettle(_playDuration);
await another.pause();
// Expect that `another` played.
expect(another.value.position,
(Duration position) => position > Duration.zero);
await expectLater(started.future, completes);
await expectLater(ended.future, completes);
},
skip: !(kIsWeb || defaultTargetPlatform == TargetPlatform.android),
);
}
Widget renderVideoWidget(VideoPlayerController controller) {
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: AspectRatio(
key: const Key('same'),
aspectRatio: controller.value.aspectRatio,
child: VideoPlayer(controller),
),
),
),
);
}
| packages/packages/video_player/video_player/example/integration_test/controller_swap_test.dart/0 | {
"file_path": "packages/packages/video_player/video_player/example/integration_test/controller_swap_test.dart",
"repo_id": "packages",
"token_count": 1084
} | 1,055 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 2.4.12
* Updates compileSdk version to 34.
* Adds error handling for `BehindLiveWindowException`, which may occur upon live-video playback failure.
## 2.4.11
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Fixes new lint warnings.
## 2.4.10
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.4.9
* Bumps ExoPlayer version to 2.18.7.
## 2.4.8
* Bumps ExoPlayer version to 2.18.6.
## 2.4.7
* Fixes Java warnings.
## 2.4.6
* Fixes compatibility with AGP versions older than 4.2.
## 2.4.5
* Adds a namespace for compatibility with AGP 8.0.
## 2.4.4
* Synchronizes `VideoPlayerValue.isPlaying` with `ExoPlayer`.
* Updates minimum Flutter version to 3.3.
## 2.4.3
* Bumps ExoPlayer version to 2.18.5.
## 2.4.2
* Bumps ExoPlayer version to 2.18.4.
## 2.4.1
* Changes the severity of `javac` warnings so that they are treated as errors and fixes the violations.
## 2.4.0
* Allows setting the ExoPlayer user agent by passing a User-Agent HTTP header.
## 2.3.12
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
* Updates compileSdkVersion to 33.
## 2.3.11
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 2.3.10
* Adds compatibilty with version 6.0 of the platform interface.
* Fixes file URI construction in example.
* Updates code for new analysis options.
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
* Updates minimum Flutter version to 2.10.
* Fixes violations of new analysis option use_named_constants.
* Removes an unnecessary override in example code.
## 2.3.9
* Updates ExoPlayer to 2.18.1.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
## 2.3.8
* Updates ExoPlayer to 2.18.0.
## 2.3.7
* Bumps gradle version to 7.2.1.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316).
## 2.3.6
* Updates references to the obsolete master branch.
## 2.3.5
* Sets rotationCorrection for videos recorded in landscapeRight (https://github.com/flutter/flutter/issues/60327).
## 2.3.4
* Updates ExoPlayer to 2.17.1.
## 2.3.3
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.3.2
* Updates ExoPlayer to 2.17.0.
## 2.3.1
* Renames internal method channels to avoid potential confusion with the
default implementation's method channel.
* Updates Pigeon to 2.0.1.
## 2.3.0
* Updates Pigeon to ^1.0.16.
## 2.2.17
* Splits from `video_player` as a federated implementation.
| packages/packages/video_player/video_player_android/CHANGELOG.md/0 | {
"file_path": "packages/packages/video_player/video_player_android/CHANGELOG.md",
"repo_id": "packages",
"token_count": 953
} | 1,056 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/video_player/video_player_android/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/video_player/video_player_android/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 1,057 |
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.4.2'
}
}
allprojects {
repositories {
// See https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure#gradle-structure for more info.
def artifactRepoKey = 'ARTIFACT_HUB_REPOSITORY'
if (System.getenv().containsKey(artifactRepoKey)) {
println "Using artifact hub"
maven { url System.getenv(artifactRepoKey) }
}
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
// Build the plugin project with warnings enabled. This is here rather than
// in the plugin itself to avoid breaking clients that have different
// warnings (e.g., deprecation warnings from a newer SDK than this project
// builds with).
gradle.projectsEvaluated {
project(":video_player_android") {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:all" << "-Werror"
// Workaround for several warnings when building
// that the above turns into errors, coming from
// org.checkerframework.checker.nullness.qual and
// com.google.errorprone.annotations:
//
// warning: Cannot find annotation method 'value()' in type
// 'EnsuresNonNull': class file for
// org.checkerframework.checker.nullness.qual.EnsuresNonNull not found
//
// warning: Cannot find annotation method 'replacement()' in type
// 'InlineMe': class file for
// com.google.errorprone.annotations.InlineMe not found
//
// The dependency version are taken from:
// https://github.com/google/ExoPlayer/blob/r2.18.1/constants.gradle
//
// For future reference the dependencies are excluded here:
// https://github.com/google/ExoPlayer/blob/r2.18.1/library/common/build.gradle#L33-L34
dependencies {
implementation "org.checkerframework:checker-qual:3.13.0"
implementation "com.google.errorprone:error_prone_annotations:2.10.0"
}
}
}
}
| packages/packages/video_player/video_player_android/example/android/build.gradle/0 | {
"file_path": "packages/packages/video_player/video_player_android/example/android/build.gradle",
"repo_id": "packages",
"token_count": 1044
} | 1,058 |
name: video_player_android
description: Android implementation of the video_player plugin.
repository: https://github.com/flutter/packages/tree/main/packages/video_player/video_player_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22
version: 2.4.12
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: video_player
platforms:
android:
dartPluginClass: AndroidVideoPlayer
package: io.flutter.plugins.videoplayer
pluginClass: VideoPlayerPlugin
dependencies:
flutter:
sdk: flutter
video_player_platform_interface: ">=6.1.0 <7.0.0"
dev_dependencies:
flutter_test:
sdk: flutter
pigeon: ^9.2.5
topics:
- video
- video-player
| packages/packages/video_player/video_player_android/pubspec.yaml/0 | {
"file_path": "packages/packages/video_player/video_player_android/pubspec.yaml",
"repo_id": "packages",
"token_count": 312
} | 1,059 |
// 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 "../FVPDisplayLink.h"
#import <CoreVideo/CoreVideo.h>
#import <Foundation/Foundation.h>
@interface FVPDisplayLink ()
// The underlying display link implementation.
@property(nonatomic, assign) CVDisplayLinkRef displayLink;
// A dispatch source to move display link callbacks to the main thread.
@property(nonatomic, strong) dispatch_source_t displayLinkSource;
// The plugin registrar, to get screen information.
@property(nonatomic, weak) NSObject<FlutterPluginRegistrar> *registrar;
@end
static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *now,
const CVTimeStamp *outputTime, CVOptionFlags flagsIn,
CVOptionFlags *flagsOut, void *displayLinkSource) {
// Trigger the main-thread dispatch queue, to drive the callback there.
__weak dispatch_source_t source = (__bridge dispatch_source_t)displayLinkSource;
dispatch_source_merge_data(source, 1);
return kCVReturnSuccess;
}
@implementation FVPDisplayLink
- (instancetype)initWithRegistrar:(id<FlutterPluginRegistrar>)registrar
callback:(void (^)(void))callback {
self = [super init];
if (self) {
_registrar = registrar;
// Create and start the main-thread dispatch queue to drive frameUpdater.
_displayLinkSource =
dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler(_displayLinkSource, ^() {
@autoreleasepool {
callback();
}
});
dispatch_resume(_displayLinkSource);
if (CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink) == kCVReturnSuccess) {
CVDisplayLinkSetOutputCallback(_displayLink, &DisplayLinkCallback,
(__bridge void *)(_displayLinkSource));
}
}
return self;
}
- (void)dealloc {
CVDisplayLinkStop(_displayLink);
CVDisplayLinkRelease(_displayLink);
_displayLink = NULL;
dispatch_source_cancel(_displayLinkSource);
}
- (BOOL)running {
return CVDisplayLinkIsRunning(self.displayLink);
}
- (void)setRunning:(BOOL)running {
if (self.running == running) {
return;
}
if (running) {
// TODO(stuartmorgan): Move this to init + a screen change listener; this won't correctly
// handle windows being dragged to another screen until the next pause/play cycle. That will
// likely require new plugin registrar APIs.
NSScreen *screen = self.registrar.view.window.screen;
if (screen) {
CGDirectDisplayID viewDisplayID =
(CGDirectDisplayID)[screen.deviceDescription[@"NSScreenNumber"] unsignedIntegerValue];
CVDisplayLinkSetCurrentCGDisplay(self.displayLink, viewDisplayID);
}
CVDisplayLinkStart(self.displayLink);
} else {
CVDisplayLinkStop(self.displayLink);
}
}
@end
| packages/packages/video_player/video_player_avfoundation/darwin/Classes/macos/FVPDisplayLink.m/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/macos/FVPDisplayLink.m",
"repo_id": "packages",
"token_count": 1054
} | 1,060 |
// 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:video_player_platform_interface/video_player_platform_interface.dart';
void main() {
group('VideoPlayerWebOptionsControls', () {
late VideoPlayerWebOptionsControls controls;
group('when disabled', () {
setUp(() {
controls = const VideoPlayerWebOptionsControls.disabled();
});
test(
'expect enabled isFalse',
() {
expect(controls.enabled, isFalse);
},
);
});
group('when enabled', () {
group('and all options are allowed', () {
setUp(() {
controls = const VideoPlayerWebOptionsControls.enabled();
});
test(
'expect enabled isTrue',
() {
expect(controls.enabled, isTrue);
expect(controls.allowDownload, isTrue);
expect(controls.allowFullscreen, isTrue);
expect(controls.allowPlaybackRate, isTrue);
expect(controls.allowPictureInPicture, isTrue);
},
);
test(
'expect controlsList isEmpty',
() {
expect(controls.controlsList, isEmpty);
},
);
});
group('and some options are disallowed', () {
setUp(() {
controls = const VideoPlayerWebOptionsControls.enabled(
allowDownload: false,
allowFullscreen: false,
allowPlaybackRate: false,
);
});
test(
'expect enabled isTrue',
() {
expect(controls.enabled, isTrue);
expect(controls.allowDownload, isFalse);
expect(controls.allowFullscreen, isFalse);
expect(controls.allowPlaybackRate, isFalse);
expect(controls.allowPictureInPicture, isTrue);
},
);
test(
'expect controlsList is correct',
() {
expect(
controls.controlsList,
'nodownload nofullscreen noplaybackrate',
);
},
);
});
});
});
}
| packages/packages/video_player/video_player_platform_interface/test/video_player_web_options_controls_test.dart/0 | {
"file_path": "packages/packages/video_player/video_player_platform_interface/test/video_player_web_options_controls_test.dart",
"repo_id": "packages",
"token_count": 1035
} | 1,061 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print, avoid_dynamic_calls
import 'dart:async';
import 'dart:convert' show JsonEncoder, LineSplitter, json, utf8;
import 'dart:io' as io;
import 'dart:math' as math;
import 'package:path/path.dart' as path;
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
import 'common.dart';
/// Options passed to Chrome when launching it.
class ChromeOptions {
/// Creates chrome options.
ChromeOptions({
this.userDataDirectory,
this.url,
this.windowWidth = 1024,
this.windowHeight = 1024,
required this.headless,
this.debugPort,
});
/// If not null passed as `--user-data-dir`.
final String? userDataDirectory;
/// If not null launches a Chrome tab at this URL.
final String? url;
/// The width of the Chrome window.
///
/// This is important for screenshots and benchmarks.
final int windowWidth;
/// The height of the Chrome window.
///
/// This is important for screenshots and benchmarks.
final int windowHeight;
/// Launches code in "headless" mode, which allows running Chrome in
/// environments without a display, such as LUCI and Cirrus.
final bool headless;
/// The port Chrome will use for its debugging protocol.
///
/// If null, Chrome is launched without debugging. When running in headless
/// mode without a debug port, Chrome quits immediately. For most tests it is
/// typical to set [headless] to true and set a non-null debug port.
final int? debugPort;
}
/// A function called when the Chrome process encounters an error.
typedef ChromeErrorCallback = void Function(String);
/// Manages a single Chrome process.
class Chrome {
Chrome._(this._chromeProcess, this._onError, this._debugConnection,
bool headless) {
if (headless) {
// In headless mode, if the Chrome process quits before it was asked to
// quit, notify the error listener. If it's not running headless, the
// developer may close the browser any time, so it's not considered to
// be an error.
_chromeProcess.exitCode.then((int exitCode) {
if (!_isStopped) {
_onError(
'Chrome process exited prematurely with exit code $exitCode');
}
});
}
}
/// Launches Chrome with the give [options].
///
/// The [onError] callback is called with an error message when the Chrome
/// process encounters an error. In particular, [onError] is called when the
/// Chrome process exits prematurely, i.e. before [stop] is called.
static Future<Chrome> launch(ChromeOptions options,
{String? workingDirectory, required ChromeErrorCallback onError}) async {
if (!io.Platform.isWindows) {
final io.ProcessResult versionResult = io.Process.runSync(
_findSystemChromeExecutable(), const <String>['--version']);
print('Launching ${versionResult.stdout}');
} else {
print('Launching Chrome...');
}
final String? url = options.url;
final bool withDebugging = options.debugPort != null;
final List<String> args = <String>[
if (options.userDataDirectory != null)
'--user-data-dir=${options.userDataDirectory}',
if (url != null) url,
if (io.Platform.environment['CHROME_NO_SANDBOX'] == 'true')
'--no-sandbox',
if (options.headless) '--headless',
if (withDebugging) '--remote-debugging-port=${options.debugPort}',
'--window-size=${options.windowWidth},${options.windowHeight}',
'--disable-extensions',
'--disable-popup-blocking',
// Indicates that the browser is in "browse without sign-in" (Guest session) mode.
'--bwsi',
'--no-first-run',
'--no-default-browser-check',
'--disable-default-apps',
'--disable-translate',
];
final io.Process chromeProcess = await io.Process.start(
_findSystemChromeExecutable(),
args,
workingDirectory: workingDirectory,
);
WipConnection? debugConnection;
final int? debugPort = options.debugPort;
if (debugPort != null) {
debugConnection =
await _connectToChromeDebugPort(chromeProcess, debugPort);
}
return Chrome._(chromeProcess, onError, debugConnection, options.headless);
}
final io.Process _chromeProcess;
final ChromeErrorCallback _onError;
final WipConnection? _debugConnection;
bool _isStopped = false;
Completer<void>? _tracingCompleter;
StreamSubscription<WipEvent>? _tracingSubscription;
List<Map<String, dynamic>>? _tracingData;
/// Starts recording a performance trace.
///
/// If there is already a tracing session in progress, throws an error. Call
/// [endRecordingPerformance] before starting a new tracing session.
///
/// The [label] is for debugging convenience.
Future<void> beginRecordingPerformance(String? label) async {
if (_tracingCompleter != null) {
throw StateError(
'Cannot start a new performance trace. A tracing session labeled '
'"$label" is already in progress.');
}
_tracingCompleter = Completer<void>();
_tracingData = <Map<String, dynamic>>[];
// Subscribe to tracing events prior to calling "Tracing.start". Otherwise,
// we'll miss tracing data.
_tracingSubscription =
_debugConnection?.onNotification.listen((WipEvent event) {
// We receive data as a sequence of "Tracing.dataCollected" followed by
// "Tracing.tracingComplete" at the end. Until "Tracing.tracingComplete"
// is received, the data may be incomplete.
if (event.method == 'Tracing.tracingComplete') {
_tracingCompleter!.complete();
_tracingSubscription?.cancel();
_tracingSubscription = null;
} else if (event.method == 'Tracing.dataCollected') {
final dynamic value = event.params!['value'];
if (value is! List) {
throw FormatException(
'"Tracing.dataCollected" returned malformed data. '
'Expected a List but got: ${value.runtimeType}');
}
_tracingData?.addAll((event.params!['value'] as List<dynamic>)
.cast<Map<String, dynamic>>());
}
});
await _debugConnection?.sendCommand('Tracing.start', <String, dynamic>{
// The choice of categories is as follows:
//
// blink:
// provides everything on the UI thread, including scripting,
// style recalculations, layout, painting, and some compositor
// work.
// blink.user_timing:
// provides marks recorded using window.performance. We use marks
// to find frames that the benchmark cares to measure.
// gpu:
// provides tracing data from the GPU data
// disabled due to https://bugs.chromium.org/p/chromium/issues/detail?id=1068259
// TODO(yjbanov): extract useful GPU data
'categories': 'blink,blink.user_timing',
'transferMode': 'SendAsStream',
});
}
/// Stops a performance tracing session started by [beginRecordingPerformance].
///
/// Returns all the collected tracing data unfiltered.
Future<List<Map<String, dynamic>>?> endRecordingPerformance() async {
await _debugConnection?.sendCommand('Tracing.end');
await _tracingCompleter?.future;
final List<Map<String, dynamic>>? data = _tracingData;
_tracingCompleter = null;
_tracingData = null;
return data;
}
/// Stops the Chrome process.
void stop() {
_isStopped = true;
_tracingSubscription?.cancel();
_chromeProcess.kill();
}
/// Resolves when the Chrome process exits.
Future<void> get whenExits async {
await _chromeProcess.exitCode;
}
}
String _findSystemChromeExecutable() {
// On some environments, such as the Dart HHH tester, Chrome resides in a
// non-standard location and is provided via the following environment
// variable.
final String? envExecutable = io.Platform.environment['CHROME_EXECUTABLE'];
if (envExecutable != null) {
return envExecutable;
}
if (io.Platform.isLinux) {
final io.ProcessResult which =
io.Process.runSync('which', <String>['google-chrome']);
if (which.exitCode != 0) {
throw Exception('Failed to locate system Chrome installation.');
}
final String output = which.stdout as String;
return output.trim();
} else if (io.Platform.isMacOS) {
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
} else if (io.Platform.isWindows) {
const String kWindowsExecutable = r'Google\Chrome\Application\chrome.exe';
final List<String> kWindowsPrefixes = <String>[
for (final String? item in <String?>[
io.Platform.environment['LOCALAPPDATA'],
io.Platform.environment['PROGRAMFILES'],
io.Platform.environment['PROGRAMFILES(X86)'],
])
if (item != null) item
];
final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) {
final String expectedPath = path.join(prefix, kWindowsExecutable);
return io.File(expectedPath).existsSync();
}, orElse: () => '.');
return path.join(windowsPrefix, kWindowsExecutable);
} else {
throw Exception(
'Web benchmarks cannot run on ${io.Platform.operatingSystem}.');
}
}
/// Waits for Chrome to print DevTools URI and connects to it.
Future<WipConnection> _connectToChromeDebugPort(
io.Process chromeProcess, int port) async {
chromeProcess.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((String line) {
print('[CHROME]: $line');
});
await chromeProcess.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.map((String line) {
print('[CHROME]: $line');
return line;
}).firstWhere((String line) => line.startsWith('DevTools listening'),
orElse: () {
throw Exception('Expected Chrome to print "DevTools listening" string '
'with DevTools URL, but the string was never printed.');
});
final Uri devtoolsUri =
await _getRemoteDebuggerUrl(Uri.parse('http://localhost:$port'));
print('Connecting to DevTools: $devtoolsUri');
final ChromeConnection chromeConnection = ChromeConnection('localhost', port);
final Iterable<ChromeTab> tabs =
(await chromeConnection.getTabs()).where((ChromeTab tab) {
return tab.url.startsWith('http://localhost');
});
final ChromeTab tab = tabs.single;
final WipConnection debugConnection = await tab.connect();
print('Connected to Chrome tab: ${tab.title} (${tab.url})');
return debugConnection;
}
/// Gets the Chrome debugger URL for the web page being benchmarked.
Future<Uri> _getRemoteDebuggerUrl(Uri base) async {
final io.HttpClient client = io.HttpClient();
final io.HttpClientRequest request =
await client.getUrl(base.resolve('/json/list'));
final io.HttpClientResponse response = await request.close();
final List<dynamic>? jsonObject =
await json.fuse(utf8).decoder.bind(response).single as List<dynamic>?;
if (jsonObject == null || jsonObject.isEmpty) {
return base;
}
return base.resolve(jsonObject.first['webSocketDebuggerUrl'] as String);
}
/// Summarizes a Blink trace down to a few interesting values.
class BlinkTraceSummary {
BlinkTraceSummary._({
required this.averageBeginFrameTime,
required this.averageUpdateLifecyclePhasesTime,
}) : averageTotalUIFrameTime =
averageBeginFrameTime + averageUpdateLifecyclePhasesTime;
/// Summarizes Blink trace from the raw JSON trace.
static BlinkTraceSummary? fromJson(List<Map<String, dynamic>> traceJson) {
try {
// Convert raw JSON data to BlinkTraceEvent objects sorted by timestamp.
List<BlinkTraceEvent> events = traceJson
.map<BlinkTraceEvent>(BlinkTraceEvent.fromJson)
.toList()
..sort((BlinkTraceEvent a, BlinkTraceEvent b) => a.ts - b.ts);
Exception noMeasuredFramesFound() => Exception(
'No measured frames found in benchmark tracing data. This likely '
'indicates a bug in the benchmark. For example, the benchmark failed '
"to pump enough frames. It may also indicate a change in Chrome's "
'tracing data format. Check if Chrome version changed recently and '
'adjust the parsing code accordingly.',
);
// Use the pid from the first "measured_frame" event since the event is
// emitted by the script running on the process we're interested in.
//
// We previously tried using the "CrRendererMain" event. However, for
// reasons unknown, Chrome in the devicelab refuses to emit this event
// sometimes, causing to flakes.
final BlinkTraceEvent firstMeasuredFrameEvent = events.firstWhere(
(BlinkTraceEvent event) => event.isBeginMeasuredFrame,
orElse: () => throw noMeasuredFramesFound(),
);
final int tabPid = firstMeasuredFrameEvent.pid;
// Filter out data from unrelated processes
events = events
.where((BlinkTraceEvent element) => element.pid == tabPid)
.toList();
// Extract frame data.
final List<BlinkFrame> frames = <BlinkFrame>[];
int skipCount = 0;
BlinkFrame frame = BlinkFrame();
for (final BlinkTraceEvent event in events) {
if (event.isBeginFrame) {
frame.beginFrame = event;
} else if (event.isUpdateAllLifecyclePhases) {
frame.updateAllLifecyclePhases = event;
if (frame.endMeasuredFrame != null) {
frames.add(frame);
} else {
skipCount += 1;
}
frame = BlinkFrame();
} else if (event.isBeginMeasuredFrame) {
frame.beginMeasuredFrame = event;
} else if (event.isEndMeasuredFrame) {
frame.endMeasuredFrame = event;
}
}
print('Extracted ${frames.length} measured frames.');
print('Skipped $skipCount non-measured frames.');
if (frames.isEmpty) {
throw noMeasuredFramesFound();
}
// Compute averages and summarize.
return BlinkTraceSummary._(
averageBeginFrameTime: _computeAverageDuration(frames
.map((BlinkFrame frame) => frame.beginFrame)
.whereType<BlinkTraceEvent>()
.toList()),
averageUpdateLifecyclePhasesTime: _computeAverageDuration(frames
.map((BlinkFrame frame) => frame.updateAllLifecyclePhases)
.whereType<BlinkTraceEvent>()
.toList()),
);
} catch (_) {
final io.File traceFile = io.File('./chrome-trace.json');
io.stderr.writeln(
'Failed to interpret the Chrome trace contents. The trace was saved in ${traceFile.path}');
traceFile.writeAsStringSync(
const JsonEncoder.withIndent(' ').convert(traceJson));
rethrow;
}
}
/// The average duration of "WebViewImpl::beginFrame" events.
///
/// This event contains all of scripting time of an animation frame, plus an
/// unknown small amount of work browser does before and after scripting.
final Duration averageBeginFrameTime;
/// The average duration of "WebViewImpl::updateAllLifecyclePhases" events.
///
/// This event contains style, layout, painting, and compositor computations,
/// which are not included in the scripting time. This event does not
/// include GPU time, which happens on a separate thread.
final Duration averageUpdateLifecyclePhasesTime;
/// The average sum of [averageBeginFrameTime] and
/// [averageUpdateLifecyclePhasesTime].
///
/// This value contains the vast majority of work the UI thread performs in
/// any given animation frame.
final Duration averageTotalUIFrameTime;
@override
String toString() => '$BlinkTraceSummary('
'averageBeginFrameTime: ${averageBeginFrameTime.inMicroseconds / 1000}ms, '
'averageUpdateLifecyclePhasesTime: ${averageUpdateLifecyclePhasesTime.inMicroseconds / 1000}ms)';
}
/// Contains events pertaining to a single frame in the Blink trace data.
class BlinkFrame {
/// Corresponds to 'WebViewImpl::beginFrame' event.
BlinkTraceEvent? beginFrame;
/// Corresponds to 'WebViewImpl::updateAllLifecyclePhases' event.
BlinkTraceEvent? updateAllLifecyclePhases;
/// Corresponds to 'measured_frame' begin event.
BlinkTraceEvent? beginMeasuredFrame;
/// Corresponds to 'measured_frame' end event.
BlinkTraceEvent? endMeasuredFrame;
}
/// Takes a list of events that have non-null [BlinkTraceEvent.tdur] computes
/// their average as a [Duration] value.
Duration _computeAverageDuration(List<BlinkTraceEvent> events) {
// Compute the sum of "tdur" fields of the last kMeasuredSampleCount events.
final double sum = events
.skip(math.max(events.length - kMeasuredSampleCount, 0))
.fold(0.0, (double previousValue, BlinkTraceEvent event) {
final int? threadClockDuration = event.tdur;
if (threadClockDuration == null) {
throw FormatException('Trace event lacks "tdur" field: $event');
}
return previousValue + threadClockDuration;
});
final int sampleCount = math.min(events.length, kMeasuredSampleCount);
return Duration(microseconds: sum ~/ sampleCount);
}
/// An event collected by the Blink tracer (in Chrome accessible using chrome://tracing).
///
/// See also:
/// * https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
class BlinkTraceEvent {
BlinkTraceEvent._({
required this.args,
required this.cat,
required this.name,
required this.ph,
required this.pid,
required this.tid,
required this.ts,
required this.tts,
required this.tdur,
});
/// Parses an event from its JSON representation.
///
/// Sample event encoded as JSON (the data is bogus, this just shows the format):
///
/// ```
/// {
/// "name": "myName",
/// "cat": "category,list",
/// "ph": "B",
/// "ts": 12345,
/// "pid": 123,
/// "tid": 456,
/// "args": {
/// "someArg": 1,
/// "anotherArg": {
/// "value": "my value"
/// }
/// }
/// }
/// ```
///
/// For detailed documentation of the format see:
///
/// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
static BlinkTraceEvent fromJson(Map<String, dynamic> json) {
return BlinkTraceEvent._(
args: json['args'] as Map<String, dynamic>,
cat: json['cat'] as String,
name: json['name'] as String,
ph: json['ph'] as String,
pid: _readInt(json, 'pid')!,
tid: _readInt(json, 'tid')!,
ts: _readInt(json, 'ts')!,
tts: _readInt(json, 'tts'),
tdur: _readInt(json, 'tdur'),
);
}
/// Event-specific data.
final Map<String, dynamic> args;
/// Event category.
final String cat;
/// Event name.
final String name;
/// Event "phase".
final String ph;
/// Process ID of the process that emitted the event.
final int pid;
/// Thread ID of the thread that emitted the event.
final int tid;
/// Timestamp in microseconds using tracer clock.
final int ts;
/// Timestamp in microseconds using thread clock.
final int? tts;
/// Event duration in microseconds.
final int? tdur;
/// A "begin frame" event contains all of the scripting time of an animation
/// frame (JavaScript, WebAssembly), plus a negligible amount of internal
/// browser overhead.
///
/// This event does not include non-UI thread scripting, such as web workers,
/// service workers, and CSS Paint paintlets.
///
/// WebViewImpl::beginFrame was used in earlier versions of Chrome, kept
/// for compatibility.
///
/// This event is a duration event that has its `tdur` populated.
bool get isBeginFrame =>
ph == 'X' &&
(name == 'WebViewImpl::beginFrame' ||
name == 'WebFrameWidgetBase::BeginMainFrame' ||
name == 'WebFrameWidgetImpl::BeginMainFrame');
/// An "update all lifecycle phases" event contains UI thread computations
/// related to an animation frame that's outside the scripting phase.
///
/// This event includes style recalculation, layer tree update, layout,
/// painting, and parts of compositing work.
///
/// This event is a duration event that has its `tdur` populated.
bool get isUpdateAllLifecyclePhases =>
ph == 'X' &&
(name == 'WebViewImpl::updateAllLifecyclePhases' ||
name == 'WebFrameWidgetImpl::UpdateLifecycle');
/// Whether this is the beginning of a "measured_frame" event.
///
/// This event is a custom event emitted by our benchmark test harness.
///
/// See also:
/// * `recorder.dart`, which emits this event.
bool get isBeginMeasuredFrame => ph == 'b' && name == 'measured_frame';
/// Whether this is the end of a "measured_frame" event.
///
/// This event is a custom event emitted by our benchmark test harness.
///
/// See also:
/// * `recorder.dart`, which emits this event.
bool get isEndMeasuredFrame => ph == 'e' && name == 'measured_frame';
@override
String toString() => '$BlinkTraceEvent('
'args: ${json.encode(args)}, '
'cat: $cat, '
'name: $name, '
'ph: $ph, '
'pid: $pid, '
'tid: $tid, '
'ts: $ts, '
'tts: $tts, '
'tdur: $tdur)';
}
/// Read an integer out of [json] stored under [key].
///
/// Since JSON does not distinguish between `int` and `double`, extra
/// validation and conversion is needed.
///
/// Returns null if the value is null.
int? _readInt(Map<String, dynamic> json, String key) {
final num? jsonValue = json[key] as num?;
if (jsonValue == null) {
return null; // ignore: avoid_returning_null
}
return jsonValue.toInt();
}
| packages/packages/web_benchmarks/lib/src/browser.dart/0 | {
"file_path": "packages/packages/web_benchmarks/lib/src/browser.dart",
"repo_id": "packages",
"token_count": 7592
} | 1,062 |
// 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';
const ValueKey<String> backKey = ValueKey<String>('backKey');
class AboutPage extends StatelessWidget {
const AboutPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: BackButton(
key: backKey,
onPressed: () => Navigator.of(context).pop(),
),
),
body: Center(
child: Text(
'This is a sample app.',
style: Theme.of(context).textTheme.displaySmall,
),
),
);
}
}
| packages/packages/web_benchmarks/testing/test_app/lib/about_page.dart/0 | {
"file_path": "packages/packages/web_benchmarks/testing/test_app/lib/about_page.dart",
"repo_id": "packages",
"token_count": 291
} | 1,063 |
<manifest package="io.flutter.plugins.webviewflutter">
</manifest>
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/AndroidManifest.xml/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 23
} | 1,064 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.platform.PlatformViewRegistry;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.CookieManagerHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.CustomViewCallbackHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.DownloadListenerHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.FlutterAssetManagerHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.GeolocationPermissionsCallbackHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.HttpAuthHandlerHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.InstanceManagerHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.JavaObjectHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.JavaScriptChannelHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.PermissionRequestHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebChromeClientHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebSettingsHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebStorageHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebViewClientHostApi;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebViewHostApi;
/**
* Java platform implementation of the webview_flutter plugin.
*
* <p>Register this in an add to app scenario to gracefully handle activity and context changes.
*
* <p>Call {@link #registerWith} to use the stable {@code io.flutter.plugin.common} package instead.
*/
public class WebViewFlutterPlugin implements FlutterPlugin, ActivityAware {
@Nullable private InstanceManager instanceManager;
private FlutterPluginBinding pluginBinding;
private WebViewHostApiImpl webViewHostApi;
private JavaScriptChannelHostApiImpl javaScriptChannelHostApi;
/**
* Add an instance of this to {@link io.flutter.embedding.engine.plugins.PluginRegistry} to
* register it.
*
* <p>THIS PLUGIN CODE PATH DEPENDS ON A NEWER VERSION OF FLUTTER THAN THE ONE DEFINED IN THE
* PUBSPEC.YAML. Text input will fail on some Android devices unless this is used with at least
* flutter/flutter@1d4d63ace1f801a022ea9ec737bf8c15395588b9. Use the V1 embedding with {@link
* #registerWith} to use this plugin with older Flutter versions.
*
* <p>Registration should eventually be handled automatically by v2 of the
* GeneratedPluginRegistrant. https://github.com/flutter/flutter/issues/42694
*/
public WebViewFlutterPlugin() {}
/**
* Registers a plugin implementation that uses the stable {@code io.flutter.plugin.common}
* package.
*
* <p>Calling this automatically initializes the plugin. However plugins initialized this way
* won't react to changes in activity or context, unlike {@link WebViewFlutterPlugin}.
*/
@SuppressWarnings({"unused", "deprecation"})
public static void registerWith(
@NonNull io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
new WebViewFlutterPlugin()
.setUp(
registrar.messenger(),
registrar.platformViewRegistry(),
registrar.activity(),
new FlutterAssetManager.RegistrarFlutterAssetManager(
registrar.context().getAssets(), registrar));
}
private void setUp(
BinaryMessenger binaryMessenger,
PlatformViewRegistry viewRegistry,
Context context,
FlutterAssetManager flutterAssetManager) {
instanceManager =
InstanceManager.create(
identifier ->
new GeneratedAndroidWebView.JavaObjectFlutterApi(binaryMessenger)
.dispose(identifier, reply -> {}));
InstanceManagerHostApi.setup(binaryMessenger, () -> instanceManager.clear());
viewRegistry.registerViewFactory(
"plugins.flutter.io/webview", new FlutterViewFactory(instanceManager));
webViewHostApi =
new WebViewHostApiImpl(
instanceManager, binaryMessenger, new WebViewHostApiImpl.WebViewProxy(), context);
javaScriptChannelHostApi =
new JavaScriptChannelHostApiImpl(
instanceManager,
new JavaScriptChannelHostApiImpl.JavaScriptChannelCreator(),
new JavaScriptChannelFlutterApiImpl(binaryMessenger, instanceManager),
new Handler(context.getMainLooper()));
JavaObjectHostApi.setup(binaryMessenger, new JavaObjectHostApiImpl(instanceManager));
WebViewHostApi.setup(binaryMessenger, webViewHostApi);
JavaScriptChannelHostApi.setup(binaryMessenger, javaScriptChannelHostApi);
WebViewClientHostApi.setup(
binaryMessenger,
new WebViewClientHostApiImpl(
instanceManager,
new WebViewClientHostApiImpl.WebViewClientCreator(),
new WebViewClientFlutterApiImpl(binaryMessenger, instanceManager)));
WebChromeClientHostApi.setup(
binaryMessenger,
new WebChromeClientHostApiImpl(
instanceManager,
new WebChromeClientHostApiImpl.WebChromeClientCreator(),
new WebChromeClientFlutterApiImpl(binaryMessenger, instanceManager)));
DownloadListenerHostApi.setup(
binaryMessenger,
new DownloadListenerHostApiImpl(
instanceManager,
new DownloadListenerHostApiImpl.DownloadListenerCreator(),
new DownloadListenerFlutterApiImpl(binaryMessenger, instanceManager)));
WebSettingsHostApi.setup(
binaryMessenger,
new WebSettingsHostApiImpl(
instanceManager, new WebSettingsHostApiImpl.WebSettingsCreator()));
FlutterAssetManagerHostApi.setup(
binaryMessenger, new FlutterAssetManagerHostApiImpl(flutterAssetManager));
CookieManagerHostApi.setup(
binaryMessenger, new CookieManagerHostApiImpl(binaryMessenger, instanceManager));
WebStorageHostApi.setup(
binaryMessenger,
new WebStorageHostApiImpl(instanceManager, new WebStorageHostApiImpl.WebStorageCreator()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
PermissionRequestHostApi.setup(
binaryMessenger, new PermissionRequestHostApiImpl(binaryMessenger, instanceManager));
}
GeolocationPermissionsCallbackHostApi.setup(
binaryMessenger,
new GeolocationPermissionsCallbackHostApiImpl(binaryMessenger, instanceManager));
CustomViewCallbackHostApi.setup(
binaryMessenger, new CustomViewCallbackHostApiImpl(binaryMessenger, instanceManager));
HttpAuthHandlerHostApi.setup(
binaryMessenger, new HttpAuthHandlerHostApiImpl(binaryMessenger, instanceManager));
}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
pluginBinding = binding;
setUp(
binding.getBinaryMessenger(),
binding.getPlatformViewRegistry(),
binding.getApplicationContext(),
new FlutterAssetManager.PluginBindingFlutterAssetManager(
binding.getApplicationContext().getAssets(), binding.getFlutterAssets()));
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
if (instanceManager != null) {
instanceManager.stopFinalizationListener();
instanceManager = null;
}
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) {
updateContext(activityPluginBinding.getActivity());
}
@Override
public void onDetachedFromActivityForConfigChanges() {
updateContext(pluginBinding.getApplicationContext());
}
@Override
public void onReattachedToActivityForConfigChanges(
@NonNull ActivityPluginBinding activityPluginBinding) {
updateContext(activityPluginBinding.getActivity());
}
@Override
public void onDetachedFromActivity() {
updateContext(pluginBinding.getApplicationContext());
}
private void updateContext(Context context) {
webViewHostApi.setContext(context);
javaScriptChannelHostApi.setPlatformThreadHandler(new Handler(context.getMainLooper()));
}
/** Maintains instances used to communicate with the corresponding objects in Dart. */
@Nullable
public InstanceManager getInstanceManager() {
return instanceManager;
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterPlugin.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterPlugin.java",
"repo_id": "packages",
"token_count": 2986
} | 1,065 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import android.view.View;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.ViewFlutterApi;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class ViewTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public View mockView;
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public ViewFlutterApi mockFlutterApi;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Test
public void flutterApiCreate() {
final ViewFlutterApiImpl flutterApi =
new ViewFlutterApiImpl(mockBinaryMessenger, instanceManager);
flutterApi.setApi(mockFlutterApi);
flutterApi.create(mockView, reply -> {});
final long instanceIdentifier =
Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockView));
verify(mockFlutterApi).create(eq(instanceIdentifier), any());
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/ViewTest.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/ViewTest.java",
"repo_id": "packages",
"token_count": 543
} | 1,066 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'android_proxy.dart';
import 'android_webview.dart' as android_webview;
import 'android_webview_api_impls.dart';
import 'instance_manager.dart';
import 'platform_views_service_proxy.dart';
import 'weak_reference_utils.dart';
/// Object specifying creation parameters for creating a [AndroidWebViewController].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebViewControllerCreationParams] for
/// more information.
@immutable
class AndroidWebViewControllerCreationParams
extends PlatformWebViewControllerCreationParams {
/// Creates a new [AndroidWebViewControllerCreationParams] instance.
AndroidWebViewControllerCreationParams({
@visibleForTesting this.androidWebViewProxy = const AndroidWebViewProxy(),
@visibleForTesting android_webview.WebStorage? androidWebStorage,
}) : androidWebStorage =
androidWebStorage ?? android_webview.WebStorage.instance,
super();
/// Creates a [AndroidWebViewControllerCreationParams] instance based on [PlatformWebViewControllerCreationParams].
factory AndroidWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebViewControllerCreationParams params, {
@visibleForTesting
AndroidWebViewProxy androidWebViewProxy = const AndroidWebViewProxy(),
@visibleForTesting android_webview.WebStorage? androidWebStorage,
}) {
return AndroidWebViewControllerCreationParams(
androidWebViewProxy: androidWebViewProxy,
androidWebStorage:
androidWebStorage ?? android_webview.WebStorage.instance,
);
}
/// Handles constructing objects and calling static methods for the Android WebView
/// native library.
@visibleForTesting
final AndroidWebViewProxy androidWebViewProxy;
/// Manages the JavaScript storage APIs provided by the [android_webview.WebView].
@visibleForTesting
final android_webview.WebStorage androidWebStorage;
}
/// Android-specific resources that can require permissions.
class AndroidWebViewPermissionResourceType
extends WebViewPermissionResourceType {
const AndroidWebViewPermissionResourceType._(super.name);
/// A resource that will allow sysex messages to be sent to or received from
/// MIDI devices.
static const AndroidWebViewPermissionResourceType midiSysex =
AndroidWebViewPermissionResourceType._('midiSysex');
/// A resource that belongs to a protected media identifier.
static const AndroidWebViewPermissionResourceType protectedMediaId =
AndroidWebViewPermissionResourceType._('protectedMediaId');
}
/// Implementation of the [PlatformWebViewController] with the Android WebView API.
class AndroidWebViewController extends PlatformWebViewController {
/// Creates a new [AndroidWebViewController].
AndroidWebViewController(PlatformWebViewControllerCreationParams params)
: super.implementation(params is AndroidWebViewControllerCreationParams
? params
: AndroidWebViewControllerCreationParams
.fromPlatformWebViewControllerCreationParams(params)) {
_webView.settings.setDomStorageEnabled(true);
_webView.settings.setJavaScriptCanOpenWindowsAutomatically(true);
_webView.settings.setSupportMultipleWindows(true);
_webView.settings.setLoadWithOverviewMode(true);
_webView.settings.setUseWideViewPort(true);
_webView.settings.setDisplayZoomControls(false);
_webView.settings.setBuiltInZoomControls(true);
_webView.setWebChromeClient(_webChromeClient);
}
AndroidWebViewControllerCreationParams get _androidWebViewParams =>
params as AndroidWebViewControllerCreationParams;
/// The native [android_webview.WebView] being controlled.
late final android_webview.WebView _webView =
_androidWebViewParams.androidWebViewProxy.createAndroidWebView(
onScrollChanged: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (int left, int top, int oldLeft, int oldTop) async {
final void Function(ScrollPositionChange)? callback =
weakReference.target?._onScrollPositionChangedCallback;
callback?.call(ScrollPositionChange(left.toDouble(), top.toDouble()));
};
}));
late final android_webview.WebChromeClient _webChromeClient =
_androidWebViewParams.androidWebViewProxy.createAndroidWebChromeClient(
onProgressChanged: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (android_webview.WebView webView, int progress) {
if (weakReference.target?._currentNavigationDelegate?._onProgress !=
null) {
weakReference
.target!._currentNavigationDelegate!._onProgress!(progress);
}
};
}),
onGeolocationPermissionsShowPrompt: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (String origin,
android_webview.GeolocationPermissionsCallback callback) async {
final OnGeolocationPermissionsShowPrompt? onShowPrompt =
weakReference.target?._onGeolocationPermissionsShowPrompt;
if (onShowPrompt != null) {
final GeolocationPermissionsResponse response = await onShowPrompt(
GeolocationPermissionsRequestParams(origin: origin),
);
return callback.invoke(origin, response.allow, response.retain);
} else {
// default don't allow
return callback.invoke(origin, false, false);
}
};
}),
onGeolocationPermissionsHidePrompt: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (android_webview.WebChromeClient instance) {
final OnGeolocationPermissionsHidePrompt? onHidePrompt =
weakReference.target?._onGeolocationPermissionsHidePrompt;
if (onHidePrompt != null) {
onHidePrompt();
}
};
}),
onShowCustomView: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (_, android_webview.View view,
android_webview.CustomViewCallback callback) {
final AndroidWebViewController? webViewController =
weakReference.target;
if (webViewController == null) {
callback.onCustomViewHidden();
return;
}
final OnShowCustomWidgetCallback? onShowCallback =
webViewController._onShowCustomWidgetCallback;
if (onShowCallback == null) {
callback.onCustomViewHidden();
return;
}
onShowCallback(
AndroidCustomViewWidget.private(
controller: webViewController,
customView: view,
),
() => callback.onCustomViewHidden(),
);
};
}),
onHideCustomView: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (android_webview.WebChromeClient instance) {
final OnHideCustomWidgetCallback? onHideCustomViewCallback =
weakReference.target?._onHideCustomWidgetCallback;
if (onHideCustomViewCallback != null) {
onHideCustomViewCallback();
}
};
}),
onShowFileChooser: withWeakReferenceTo(
this,
(WeakReference<AndroidWebViewController> weakReference) {
return (android_webview.WebView webView,
android_webview.FileChooserParams params) async {
if (weakReference.target?._onShowFileSelectorCallback != null) {
return weakReference.target!._onShowFileSelectorCallback!(
FileSelectorParams._fromFileChooserParams(params),
);
}
return <String>[];
};
},
),
onConsoleMessage: withWeakReferenceTo(
this,
(WeakReference<AndroidWebViewController> weakReference) {
return (android_webview.WebChromeClient webChromeClient,
android_webview.ConsoleMessage consoleMessage) async {
final void Function(JavaScriptConsoleMessage)? callback =
weakReference.target?._onConsoleLogCallback;
if (callback != null) {
JavaScriptLogLevel logLevel;
switch (consoleMessage.level) {
// Android maps `console.debug` to `MessageLevel.TIP`, it seems
// `MessageLevel.DEBUG` if not being used.
case ConsoleMessageLevel.debug:
case ConsoleMessageLevel.tip:
logLevel = JavaScriptLogLevel.debug;
case ConsoleMessageLevel.error:
logLevel = JavaScriptLogLevel.error;
case ConsoleMessageLevel.warning:
logLevel = JavaScriptLogLevel.warning;
case ConsoleMessageLevel.unknown:
case ConsoleMessageLevel.log:
logLevel = JavaScriptLogLevel.log;
}
callback(JavaScriptConsoleMessage(
level: logLevel,
message: consoleMessage.message,
));
}
};
},
),
onPermissionRequest: withWeakReferenceTo(
this,
(WeakReference<AndroidWebViewController> weakReference) {
return (_, android_webview.PermissionRequest request) async {
final void Function(PlatformWebViewPermissionRequest)? callback =
weakReference.target?._onPermissionRequestCallback;
if (callback == null) {
return request.deny();
} else {
final Set<WebViewPermissionResourceType> types = request.resources
.map<WebViewPermissionResourceType?>((String type) {
switch (type) {
case android_webview.PermissionRequest.videoCapture:
return WebViewPermissionResourceType.camera;
case android_webview.PermissionRequest.audioCapture:
return WebViewPermissionResourceType.microphone;
case android_webview.PermissionRequest.midiSysex:
return AndroidWebViewPermissionResourceType.midiSysex;
case android_webview.PermissionRequest.protectedMediaId:
return AndroidWebViewPermissionResourceType
.protectedMediaId;
}
// Type not supported.
return null;
})
.whereType<WebViewPermissionResourceType>()
.toSet();
// If the request didn't contain any permissions recognized by the
// implementation, deny by default.
if (types.isEmpty) {
return request.deny();
}
callback(AndroidWebViewPermissionRequest._(
types: types,
request: request,
));
}
};
},
),
onJsAlert: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (String url, String message) async {
final Future<void> Function(JavaScriptAlertDialogRequest)? callback =
weakReference.target?._onJavaScriptAlert;
if (callback != null) {
final JavaScriptAlertDialogRequest request =
JavaScriptAlertDialogRequest(message: message, url: url);
await callback.call(request);
}
return;
};
}),
onJsConfirm: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (String url, String message) async {
final Future<bool> Function(JavaScriptConfirmDialogRequest)? callback =
weakReference.target?._onJavaScriptConfirm;
if (callback != null) {
final JavaScriptConfirmDialogRequest request =
JavaScriptConfirmDialogRequest(message: message, url: url);
final bool result = await callback.call(request);
return result;
}
return false;
};
}),
onJsPrompt: withWeakReferenceTo(this,
(WeakReference<AndroidWebViewController> weakReference) {
return (String url, String message, String defaultValue) async {
final Future<String> Function(JavaScriptTextInputDialogRequest)?
callback = weakReference.target?._onJavaScriptPrompt;
if (callback != null) {
final JavaScriptTextInputDialogRequest request =
JavaScriptTextInputDialogRequest(
message: message, url: url, defaultText: defaultValue);
final String result = await callback.call(request);
return result;
}
return '';
};
}),
);
/// The native [android_webview.FlutterAssetManager] allows managing assets.
late final android_webview.FlutterAssetManager _flutterAssetManager =
_androidWebViewParams.androidWebViewProxy.createFlutterAssetManager();
final Map<String, AndroidJavaScriptChannelParams> _javaScriptChannelParams =
<String, AndroidJavaScriptChannelParams>{};
AndroidNavigationDelegate? _currentNavigationDelegate;
Future<List<String>> Function(FileSelectorParams)?
_onShowFileSelectorCallback;
OnGeolocationPermissionsShowPrompt? _onGeolocationPermissionsShowPrompt;
OnGeolocationPermissionsHidePrompt? _onGeolocationPermissionsHidePrompt;
OnShowCustomWidgetCallback? _onShowCustomWidgetCallback;
OnHideCustomWidgetCallback? _onHideCustomWidgetCallback;
void Function(PlatformWebViewPermissionRequest)? _onPermissionRequestCallback;
void Function(JavaScriptConsoleMessage consoleMessage)? _onConsoleLogCallback;
Future<void> Function(JavaScriptAlertDialogRequest request)?
_onJavaScriptAlert;
Future<bool> Function(JavaScriptConfirmDialogRequest request)?
_onJavaScriptConfirm;
Future<String> Function(JavaScriptTextInputDialogRequest request)?
_onJavaScriptPrompt;
void Function(ScrollPositionChange scrollPositionChange)?
_onScrollPositionChangedCallback;
/// Whether to enable the platform's webview content debugging tools.
///
/// Defaults to false.
static Future<void> enableDebugging(
bool enabled, {
@visibleForTesting
AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(),
}) {
return webViewProxy.setWebContentsDebuggingEnabled(enabled);
}
/// Identifier used to retrieve the underlying native `WKWebView`.
///
/// This is typically used by other plugins to retrieve the native `WebView`
/// from an `InstanceManager`.
///
/// See Java method `WebViewFlutterPlugin.getWebView`.
int get webViewIdentifier =>
// ignore: invalid_use_of_visible_for_testing_member
android_webview.WebView.api.instanceManager.getIdentifier(_webView)!;
@override
Future<void> loadFile(
String absoluteFilePath,
) {
final String url = absoluteFilePath.startsWith('file://')
? absoluteFilePath
: Uri.file(absoluteFilePath).toString();
_webView.settings.setAllowFileAccess(true);
return _webView.loadUrl(url, <String, String>{});
}
@override
Future<void> loadFlutterAsset(
String key,
) async {
final String assetFilePath =
await _flutterAssetManager.getAssetFilePathByName(key);
final List<String> pathElements = assetFilePath.split('/');
final String fileName = pathElements.removeLast();
final List<String?> paths =
await _flutterAssetManager.list(pathElements.join('/'));
if (!paths.contains(fileName)) {
throw ArgumentError(
'Asset for key "$key" not found.',
'key',
);
}
return _webView.loadUrl(
Uri.file('/android_asset/$assetFilePath').toString(),
<String, String>{},
);
}
@override
Future<void> loadHtmlString(
String html, {
String? baseUrl,
}) {
return _webView.loadDataWithBaseUrl(
baseUrl: baseUrl,
data: html,
mimeType: 'text/html',
);
}
@override
Future<void> loadRequest(
LoadRequestParams params,
) {
if (!params.uri.hasScheme) {
throw ArgumentError('WebViewRequest#uri is required to have a scheme.');
}
switch (params.method) {
case LoadRequestMethod.get:
return _webView.loadUrl(params.uri.toString(), params.headers);
case LoadRequestMethod.post:
return _webView.postUrl(
params.uri.toString(), params.body ?? Uint8List(0));
}
// The enum comes from a different package, which could get a new value at
// any time, so a fallback case is necessary. Since there is no reasonable
// default behavior, throw to alert the client that they need an updated
// version. This is deliberately outside the switch rather than a `default`
// so that the linter will flag the switch as needing an update.
// ignore: dead_code
throw UnimplementedError(
'This version of `AndroidWebViewController` currently has no '
'implementation for HTTP method ${params.method.serialize()} in '
'loadRequest.');
}
@override
Future<String?> currentUrl() => _webView.getUrl();
@override
Future<bool> canGoBack() => _webView.canGoBack();
@override
Future<bool> canGoForward() => _webView.canGoForward();
@override
Future<void> goBack() => _webView.goBack();
@override
Future<void> goForward() => _webView.goForward();
@override
Future<void> reload() => _webView.reload();
@override
Future<void> clearCache() => _webView.clearCache(true);
@override
Future<void> clearLocalStorage() =>
_androidWebViewParams.androidWebStorage.deleteAllData();
@override
Future<void> setPlatformNavigationDelegate(
covariant AndroidNavigationDelegate handler) async {
_currentNavigationDelegate = handler;
await Future.wait(<Future<void>>[
handler.setOnLoadRequest(loadRequest),
_webView.setWebViewClient(handler.androidWebViewClient),
_webView.setDownloadListener(handler.androidDownloadListener),
]);
}
@override
Future<void> runJavaScript(String javaScript) {
return _webView.evaluateJavascript(javaScript);
}
@override
Future<Object> runJavaScriptReturningResult(String javaScript) async {
final String? result = await _webView.evaluateJavascript(javaScript);
if (result == null) {
return '';
} else if (result == 'true') {
return true;
} else if (result == 'false') {
return false;
}
return num.tryParse(result) ?? result;
}
@override
Future<void> addJavaScriptChannel(
JavaScriptChannelParams javaScriptChannelParams,
) {
final AndroidJavaScriptChannelParams androidJavaScriptParams =
javaScriptChannelParams is AndroidJavaScriptChannelParams
? javaScriptChannelParams
: AndroidJavaScriptChannelParams.fromJavaScriptChannelParams(
javaScriptChannelParams);
// When JavaScript channel with the same name exists make sure to remove it
// before registering the new channel.
if (_javaScriptChannelParams.containsKey(androidJavaScriptParams.name)) {
_webView
.removeJavaScriptChannel(androidJavaScriptParams._javaScriptChannel);
}
_javaScriptChannelParams[androidJavaScriptParams.name] =
androidJavaScriptParams;
return _webView
.addJavaScriptChannel(androidJavaScriptParams._javaScriptChannel);
}
@override
Future<void> removeJavaScriptChannel(String javaScriptChannelName) async {
final AndroidJavaScriptChannelParams? javaScriptChannelParams =
_javaScriptChannelParams[javaScriptChannelName];
if (javaScriptChannelParams == null) {
return;
}
_javaScriptChannelParams.remove(javaScriptChannelName);
return _webView
.removeJavaScriptChannel(javaScriptChannelParams._javaScriptChannel);
}
@override
Future<String?> getTitle() => _webView.getTitle();
@override
Future<void> scrollTo(int x, int y) => _webView.scrollTo(x, y);
@override
Future<void> scrollBy(int x, int y) => _webView.scrollBy(x, y);
@override
Future<Offset> getScrollPosition() {
return _webView.getScrollPosition();
}
@override
Future<void> enableZoom(bool enabled) =>
_webView.settings.setSupportZoom(enabled);
@override
Future<void> setBackgroundColor(Color color) =>
_webView.setBackgroundColor(color);
@override
Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) =>
_webView.settings
.setJavaScriptEnabled(javaScriptMode == JavaScriptMode.unrestricted);
@override
Future<void> setUserAgent(String? userAgent) =>
_webView.settings.setUserAgentString(userAgent);
@override
Future<void> setOnScrollPositionChange(
void Function(ScrollPositionChange scrollPositionChange)?
onScrollPositionChange) async {
_onScrollPositionChangedCallback = onScrollPositionChange;
}
/// Sets the restrictions that apply on automatic media playback.
Future<void> setMediaPlaybackRequiresUserGesture(bool require) {
return _webView.settings.setMediaPlaybackRequiresUserGesture(require);
}
/// Sets the text zoom of the page in percent.
///
/// The default is 100.
Future<void> setTextZoom(int textZoom) =>
_webView.settings.setTextZoom(textZoom);
/// Sets the callback that is invoked when the client should show a file
/// selector.
Future<void> setOnShowFileSelector(
Future<List<String>> Function(FileSelectorParams params)?
onShowFileSelector,
) {
_onShowFileSelectorCallback = onShowFileSelector;
return _webChromeClient.setSynchronousReturnValueForOnShowFileChooser(
onShowFileSelector != null,
);
}
/// Sets a callback that notifies the host application that web content is
/// requesting permission to access the specified resources.
///
/// Only invoked on Android versions 21+.
@override
Future<void> setOnPlatformPermissionRequest(
void Function(
PlatformWebViewPermissionRequest request,
) onPermissionRequest,
) async {
_onPermissionRequestCallback = onPermissionRequest;
}
/// Sets the callback that is invoked when the client request handle geolocation permissions.
///
/// Param [onShowPrompt] notifies the host application that web content from the specified origin is attempting to use the Geolocation API,
/// but no permission state is currently set for that origin.
///
/// The host application should invoke the specified callback with the desired permission state.
/// See GeolocationPermissions for details.
///
/// Note that for applications targeting Android N and later SDKs (API level > Build.VERSION_CODES.M)
/// this method is only called for requests originating from secure origins such as https.
/// On non-secure origins geolocation requests are automatically denied.
///
/// Param [onHidePrompt] notifies the host application that a request for Geolocation permissions,
/// made with a previous call to onGeolocationPermissionsShowPrompt() has been canceled.
/// Any related UI should therefore be hidden.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String,%20android.webkit.GeolocationPermissions.Callback)
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsHidePrompt()
Future<void> setGeolocationPermissionsPromptCallbacks({
OnGeolocationPermissionsShowPrompt? onShowPrompt,
OnGeolocationPermissionsHidePrompt? onHidePrompt,
}) async {
_onGeolocationPermissionsShowPrompt = onShowPrompt;
_onGeolocationPermissionsHidePrompt = onHidePrompt;
}
/// Sets the callbacks that are invoked when the host application wants to
/// show or hide a custom widget.
///
/// The most common use case these methods are invoked a video element wants
/// to be displayed in fullscreen.
///
/// The [onShowCustomWidget] notifies the host application that web content
/// from the specified origin wants to be displayed in a custom widget. After
/// this call, web content will no longer be rendered in the `WebViewWidget`,
/// but will instead be rendered in the custom widget. The application may
/// explicitly exit fullscreen mode by invoking `onCustomWidgetHidden` in the
/// [onShowCustomWidget] callback (ex. when the user presses the back
/// button). However, this is generally not necessary as the web page will
/// often show its own UI to close out of fullscreen. Regardless of how the
/// WebView exits fullscreen mode, WebView will invoke [onHideCustomWidget],
/// signaling for the application to remove the custom widget. If this value
/// is `null` when passed to an `AndroidWebViewWidget`, a default handler
/// will be set.
///
/// The [onHideCustomWidget] notifies the host application that the custom
/// widget must be hidden. After this call, web content will render in the
/// original `WebViewWidget` again.
Future<void> setCustomWidgetCallbacks({
required OnShowCustomWidgetCallback? onShowCustomWidget,
required OnHideCustomWidgetCallback? onHideCustomWidget,
}) async {
_onShowCustomWidgetCallback = onShowCustomWidget;
_onHideCustomWidgetCallback = onHideCustomWidget;
}
/// Sets a callback that notifies the host application of any log messages
/// written to the JavaScript console.
@override
Future<void> setOnConsoleMessage(
void Function(JavaScriptConsoleMessage consoleMessage)
onConsoleMessage) async {
_onConsoleLogCallback = onConsoleMessage;
return _webChromeClient.setSynchronousReturnValueForOnConsoleMessage(
_onConsoleLogCallback != null);
}
@override
Future<String?> getUserAgent() => _webView.settings.getUserAgentString();
@override
Future<void> setOnJavaScriptAlertDialog(
Future<void> Function(JavaScriptAlertDialogRequest request)
onJavaScriptAlertDialog) async {
_onJavaScriptAlert = onJavaScriptAlertDialog;
return _webChromeClient.setSynchronousReturnValueForOnJsAlert(true);
}
@override
Future<void> setOnJavaScriptConfirmDialog(
Future<bool> Function(JavaScriptConfirmDialogRequest request)
onJavaScriptConfirmDialog) async {
_onJavaScriptConfirm = onJavaScriptConfirmDialog;
return _webChromeClient.setSynchronousReturnValueForOnJsConfirm(true);
}
@override
Future<void> setOnJavaScriptTextInputDialog(
Future<String> Function(JavaScriptTextInputDialogRequest request)
onJavaScriptTextInputDialog) async {
_onJavaScriptPrompt = onJavaScriptTextInputDialog;
return _webChromeClient.setSynchronousReturnValueForOnJsPrompt(true);
}
}
/// Android implementation of [PlatformWebViewPermissionRequest].
class AndroidWebViewPermissionRequest extends PlatformWebViewPermissionRequest {
const AndroidWebViewPermissionRequest._({
required super.types,
required android_webview.PermissionRequest request,
}) : _request = request;
final android_webview.PermissionRequest _request;
@override
Future<void> grant() {
return _request
.grant(types.map<String>((WebViewPermissionResourceType type) {
switch (type) {
case WebViewPermissionResourceType.camera:
return android_webview.PermissionRequest.videoCapture;
case WebViewPermissionResourceType.microphone:
return android_webview.PermissionRequest.audioCapture;
case AndroidWebViewPermissionResourceType.midiSysex:
return android_webview.PermissionRequest.midiSysex;
case AndroidWebViewPermissionResourceType.protectedMediaId:
return android_webview.PermissionRequest.protectedMediaId;
}
throw UnsupportedError(
'Resource of type `${type.name}` is not supported.',
);
}).toList());
}
@override
Future<void> deny() {
return _request.deny();
}
}
/// Signature for the `setGeolocationPermissionsPromptCallbacks` callback responsible for request the Geolocation API.
typedef OnGeolocationPermissionsShowPrompt
= Future<GeolocationPermissionsResponse> Function(
GeolocationPermissionsRequestParams request);
/// Signature for the `setGeolocationPermissionsPromptCallbacks` callback responsible for request the Geolocation API is cancel.
typedef OnGeolocationPermissionsHidePrompt = void Function();
/// Signature for the `setCustomWidgetCallbacks` callback responsible for showing the custom view.
typedef OnShowCustomWidgetCallback = void Function(
Widget widget, void Function() onCustomWidgetHidden);
/// Signature for the `setCustomWidgetCallbacks` callback responsible for hiding the custom view.
typedef OnHideCustomWidgetCallback = void Function();
/// A request params used by the host application to set the Geolocation permission state for an origin.
@immutable
class GeolocationPermissionsRequestParams {
/// [origin]: The origin for which permissions are set.
const GeolocationPermissionsRequestParams({
required this.origin,
});
/// [origin]: The origin for which permissions are set.
final String origin;
}
/// A response used by the host application to set the Geolocation permission state for an origin.
@immutable
class GeolocationPermissionsResponse {
/// [allow]: Whether or not the origin should be allowed to use the Geolocation API.
///
/// [retain]: Whether the permission should be retained beyond the lifetime of
/// a page currently being displayed by a WebView.
const GeolocationPermissionsResponse({
required this.allow,
required this.retain,
});
/// Whether or not the origin should be allowed to use the Geolocation API.
final bool allow;
/// Whether the permission should be retained beyond the lifetime of
/// a page currently being displayed by a WebView.
final bool retain;
}
/// Mode of how to select files for a file chooser.
enum FileSelectorMode {
/// Open single file and requires that the file exists before allowing the
/// user to pick it.
open,
/// Similar to [open] but allows multiple files to be selected.
openMultiple,
/// Allows picking a nonexistent file and saving it.
save,
}
/// Parameters received when the `WebView` should show a file selector.
@immutable
class FileSelectorParams {
/// Constructs a [FileSelectorParams].
const FileSelectorParams({
required this.isCaptureEnabled,
required this.acceptTypes,
this.filenameHint,
required this.mode,
});
factory FileSelectorParams._fromFileChooserParams(
android_webview.FileChooserParams params,
) {
final FileSelectorMode mode;
switch (params.mode) {
case android_webview.FileChooserMode.open:
mode = FileSelectorMode.open;
case android_webview.FileChooserMode.openMultiple:
mode = FileSelectorMode.openMultiple;
case android_webview.FileChooserMode.save:
mode = FileSelectorMode.save;
}
return FileSelectorParams(
isCaptureEnabled: params.isCaptureEnabled,
acceptTypes: params.acceptTypes,
mode: mode,
filenameHint: params.filenameHint,
);
}
/// Preference for a live media captured value (e.g. Camera, Microphone).
final bool isCaptureEnabled;
/// A list of acceptable MIME types.
final List<String> acceptTypes;
/// The file name of a default selection if specified, or null.
final String? filenameHint;
/// Mode of how to select files for a file selector.
final FileSelectorMode mode;
}
/// An implementation of [JavaScriptChannelParams] with the Android WebView API.
///
/// See [AndroidWebViewController.addJavaScriptChannel].
@immutable
class AndroidJavaScriptChannelParams extends JavaScriptChannelParams {
/// Constructs a [AndroidJavaScriptChannelParams].
AndroidJavaScriptChannelParams({
required super.name,
required super.onMessageReceived,
@visibleForTesting
AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(),
}) : assert(name.isNotEmpty),
_javaScriptChannel = webViewProxy.createJavaScriptChannel(
name,
postMessage: withWeakReferenceTo(
onMessageReceived,
(WeakReference<void Function(JavaScriptMessage)> weakReference) {
return (
String message,
) {
if (weakReference.target != null) {
weakReference.target!(
JavaScriptMessage(message: message),
);
}
};
},
),
);
/// Constructs a [AndroidJavaScriptChannelParams] using a
/// [JavaScriptChannelParams].
AndroidJavaScriptChannelParams.fromJavaScriptChannelParams(
JavaScriptChannelParams params, {
@visibleForTesting
AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(),
}) : this(
name: params.name,
onMessageReceived: params.onMessageReceived,
webViewProxy: webViewProxy,
);
final android_webview.JavaScriptChannel _javaScriptChannel;
}
/// Object specifying creation parameters for creating a [AndroidWebViewWidget].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebViewWidgetCreationParams] for
/// more information.
@immutable
class AndroidWebViewWidgetCreationParams
extends PlatformWebViewWidgetCreationParams {
/// Creates [AndroidWebWidgetCreationParams].
AndroidWebViewWidgetCreationParams({
super.key,
required super.controller,
super.layoutDirection,
super.gestureRecognizers,
this.displayWithHybridComposition = false,
@visibleForTesting InstanceManager? instanceManager,
@visibleForTesting
this.platformViewsServiceProxy = const PlatformViewsServiceProxy(),
}) : instanceManager =
instanceManager ?? android_webview.JavaObject.globalInstanceManager;
/// Constructs a [WebKitWebViewWidgetCreationParams] using a
/// [PlatformWebViewWidgetCreationParams].
AndroidWebViewWidgetCreationParams.fromPlatformWebViewWidgetCreationParams(
PlatformWebViewWidgetCreationParams params, {
bool displayWithHybridComposition = false,
@visibleForTesting InstanceManager? instanceManager,
@visibleForTesting PlatformViewsServiceProxy platformViewsServiceProxy =
const PlatformViewsServiceProxy(),
}) : this(
key: params.key,
controller: params.controller,
layoutDirection: params.layoutDirection,
gestureRecognizers: params.gestureRecognizers,
displayWithHybridComposition: displayWithHybridComposition,
instanceManager: instanceManager,
platformViewsServiceProxy: platformViewsServiceProxy,
);
/// Maintains instances used to communicate with the native objects they
/// represent.
///
/// This field is exposed for testing purposes only and should not be used
/// outside of tests.
@visibleForTesting
final InstanceManager instanceManager;
/// Proxy that provides access to the platform views service.
///
/// This service allows creating and controlling platform-specific views.
@visibleForTesting
final PlatformViewsServiceProxy platformViewsServiceProxy;
/// Whether the [WebView] will be displayed using the Hybrid Composition
/// PlatformView implementation.
///
/// For most use cases, this flag should be set to false. Hybrid Composition
/// can have performance costs but doesn't have the limitation of rendering to
/// an Android SurfaceTexture. See
/// * https://flutter.dev/docs/development/platform-integration/platform-views#performance
/// * https://github.com/flutter/flutter/issues/104889
/// * https://github.com/flutter/flutter/issues/116954
///
/// Defaults to false.
final bool displayWithHybridComposition;
@override
int get hashCode => Object.hash(
controller,
layoutDirection,
displayWithHybridComposition,
platformViewsServiceProxy,
instanceManager,
);
@override
bool operator ==(Object other) {
return other is AndroidWebViewWidgetCreationParams &&
controller == other.controller &&
layoutDirection == other.layoutDirection &&
displayWithHybridComposition == other.displayWithHybridComposition &&
platformViewsServiceProxy == other.platformViewsServiceProxy &&
instanceManager == other.instanceManager;
}
}
/// An implementation of [PlatformWebViewWidget] with the Android WebView API.
class AndroidWebViewWidget extends PlatformWebViewWidget {
/// Constructs a [WebKitWebViewWidget].
AndroidWebViewWidget(PlatformWebViewWidgetCreationParams params)
: super.implementation(
params is AndroidWebViewWidgetCreationParams
? params
: AndroidWebViewWidgetCreationParams
.fromPlatformWebViewWidgetCreationParams(params),
);
AndroidWebViewWidgetCreationParams get _androidParams =>
params as AndroidWebViewWidgetCreationParams;
@override
Widget build(BuildContext context) {
_trySetDefaultOnShowCustomWidgetCallbacks(context);
return PlatformViewLink(
// Setting a default key using `params` ensures the `PlatformViewLink`
// recreates the PlatformView when changes are made.
key: _androidParams.key ??
ValueKey<AndroidWebViewWidgetCreationParams>(
params as AndroidWebViewWidgetCreationParams),
viewType: 'plugins.flutter.io/webview',
surfaceFactory: (
BuildContext context,
PlatformViewController controller,
) {
return AndroidViewSurface(
controller: controller as AndroidViewController,
gestureRecognizers: _androidParams.gestureRecognizers,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
);
},
onCreatePlatformView: (PlatformViewCreationParams params) {
return _initAndroidView(
params,
displayWithHybridComposition:
_androidParams.displayWithHybridComposition,
platformViewsServiceProxy: _androidParams.platformViewsServiceProxy,
view:
(_androidParams.controller as AndroidWebViewController)._webView,
instanceManager: _androidParams.instanceManager,
layoutDirection: _androidParams.layoutDirection,
)
..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
..create();
},
);
}
// Attempt to handle custom views with a default implementation if it has not
// been set.
void _trySetDefaultOnShowCustomWidgetCallbacks(BuildContext context) {
final AndroidWebViewController controller =
_androidParams.controller as AndroidWebViewController;
if (controller._onShowCustomWidgetCallback == null) {
controller.setCustomWidgetCallbacks(
onShowCustomWidget:
(Widget widget, OnHideCustomWidgetCallback callback) {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) => widget,
fullscreenDialog: true,
));
},
onHideCustomWidget: () {
Navigator.of(context).pop();
},
);
}
}
}
/// Represents a Flutter implementation of the Android [View](https://developer.android.com/reference/android/view/View)
/// that is created by the host platform when web content needs to be displayed
/// in fullscreen mode.
///
/// The [AndroidCustomViewWidget] cannot be manually instantiated and is
/// provided to the host application through the callbacks specified using the
/// [AndroidWebViewController.setCustomWidgetCallbacks] method.
///
/// The [AndroidCustomViewWidget] is initialized internally and should only be
/// exposed as a [Widget] externally. The type [AndroidCustomViewWidget] is
/// visible for testing purposes only and should never be called externally.
@visibleForTesting
class AndroidCustomViewWidget extends StatelessWidget {
/// Creates a [AndroidCustomViewWidget].
///
/// The [AndroidCustomViewWidget] should only be instantiated internally.
/// This constructor is visible for testing purposes only and should
/// never be called externally.
@visibleForTesting
AndroidCustomViewWidget.private({
super.key,
required this.controller,
required this.customView,
@visibleForTesting InstanceManager? instanceManager,
@visibleForTesting
this.platformViewsServiceProxy = const PlatformViewsServiceProxy(),
}) : instanceManager =
instanceManager ?? android_webview.JavaObject.globalInstanceManager;
/// The reference to the Android native view that should be shown.
final android_webview.View customView;
/// The [PlatformWebViewController] that allows controlling the native web
/// view.
final PlatformWebViewController controller;
/// Maintains instances used to communicate with the native objects they
/// represent.
///
/// This field is exposed for testing purposes only and should not be used
/// outside of tests.
@visibleForTesting
final InstanceManager instanceManager;
/// Proxy that provides access to the platform views service.
///
/// This service allows creating and controlling platform-specific views.
@visibleForTesting
final PlatformViewsServiceProxy platformViewsServiceProxy;
@override
Widget build(BuildContext context) {
return PlatformViewLink(
key: key,
viewType: 'plugins.flutter.io/webview',
surfaceFactory: (
BuildContext context,
PlatformViewController controller,
) {
return AndroidViewSurface(
controller: controller as AndroidViewController,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
);
},
onCreatePlatformView: (PlatformViewCreationParams params) {
return _initAndroidView(
params,
displayWithHybridComposition: false,
platformViewsServiceProxy: platformViewsServiceProxy,
view: customView,
instanceManager: instanceManager,
)
..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
..create();
},
);
}
}
AndroidViewController _initAndroidView(
PlatformViewCreationParams params, {
required bool displayWithHybridComposition,
required PlatformViewsServiceProxy platformViewsServiceProxy,
required android_webview.View view,
required InstanceManager instanceManager,
TextDirection layoutDirection = TextDirection.ltr,
}) {
final int? instanceId = instanceManager.getIdentifier(view);
if (displayWithHybridComposition) {
return platformViewsServiceProxy.initExpensiveAndroidView(
id: params.id,
viewType: 'plugins.flutter.io/webview',
layoutDirection: layoutDirection,
creationParams: instanceId,
creationParamsCodec: const StandardMessageCodec(),
);
} else {
return platformViewsServiceProxy.initSurfaceAndroidView(
id: params.id,
viewType: 'plugins.flutter.io/webview',
layoutDirection: layoutDirection,
creationParams: instanceId,
creationParamsCodec: const StandardMessageCodec(),
);
}
}
/// Signature for the `loadRequest` callback responsible for loading the [url]
/// after a navigation request has been approved.
typedef LoadRequestCallback = Future<void> Function(LoadRequestParams params);
/// Error returned in `WebView.onWebResourceError` when a web resource loading error has occurred.
@immutable
class AndroidWebResourceError extends WebResourceError {
/// Creates a new [AndroidWebResourceError].
AndroidWebResourceError._({
required super.errorCode,
required super.description,
super.isForMainFrame,
super.url,
}) : failingUrl = url,
super(
errorType: _errorCodeToErrorType(errorCode),
);
/// Gets the URL for which the failing resource request was made.
@Deprecated('Please use `url`.')
final String? failingUrl;
static WebResourceErrorType? _errorCodeToErrorType(int errorCode) {
switch (errorCode) {
case android_webview.WebViewClient.errorAuthentication:
return WebResourceErrorType.authentication;
case android_webview.WebViewClient.errorBadUrl:
return WebResourceErrorType.badUrl;
case android_webview.WebViewClient.errorConnect:
return WebResourceErrorType.connect;
case android_webview.WebViewClient.errorFailedSslHandshake:
return WebResourceErrorType.failedSslHandshake;
case android_webview.WebViewClient.errorFile:
return WebResourceErrorType.file;
case android_webview.WebViewClient.errorFileNotFound:
return WebResourceErrorType.fileNotFound;
case android_webview.WebViewClient.errorHostLookup:
return WebResourceErrorType.hostLookup;
case android_webview.WebViewClient.errorIO:
return WebResourceErrorType.io;
case android_webview.WebViewClient.errorProxyAuthentication:
return WebResourceErrorType.proxyAuthentication;
case android_webview.WebViewClient.errorRedirectLoop:
return WebResourceErrorType.redirectLoop;
case android_webview.WebViewClient.errorTimeout:
return WebResourceErrorType.timeout;
case android_webview.WebViewClient.errorTooManyRequests:
return WebResourceErrorType.tooManyRequests;
case android_webview.WebViewClient.errorUnknown:
return WebResourceErrorType.unknown;
case android_webview.WebViewClient.errorUnsafeResource:
return WebResourceErrorType.unsafeResource;
case android_webview.WebViewClient.errorUnsupportedAuthScheme:
return WebResourceErrorType.unsupportedAuthScheme;
case android_webview.WebViewClient.errorUnsupportedScheme:
return WebResourceErrorType.unsupportedScheme;
}
throw ArgumentError(
'Could not find a WebResourceErrorType for errorCode: $errorCode',
);
}
}
/// Object specifying creation parameters for creating a [AndroidNavigationDelegate].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformNavigationDelegateCreationParams] for
/// more information.
@immutable
class AndroidNavigationDelegateCreationParams
extends PlatformNavigationDelegateCreationParams {
/// Creates a new [AndroidNavigationDelegateCreationParams] instance.
const AndroidNavigationDelegateCreationParams._({
@visibleForTesting this.androidWebViewProxy = const AndroidWebViewProxy(),
}) : super();
/// Creates a [AndroidNavigationDelegateCreationParams] instance based on [PlatformNavigationDelegateCreationParams].
factory AndroidNavigationDelegateCreationParams.fromPlatformNavigationDelegateCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformNavigationDelegateCreationParams params, {
@visibleForTesting
AndroidWebViewProxy androidWebViewProxy = const AndroidWebViewProxy(),
}) {
return AndroidNavigationDelegateCreationParams._(
androidWebViewProxy: androidWebViewProxy,
);
}
/// Handles constructing objects and calling static methods for the Android WebView
/// native library.
@visibleForTesting
final AndroidWebViewProxy androidWebViewProxy;
}
/// Android details of the change to a web view's url.
class AndroidUrlChange extends UrlChange {
/// Constructs an [AndroidUrlChange].
const AndroidUrlChange({required super.url, required this.isReload});
/// Whether the url is being reloaded.
final bool isReload;
}
/// A place to register callback methods responsible to handle navigation events
/// triggered by the [android_webview.WebView].
class AndroidNavigationDelegate extends PlatformNavigationDelegate {
/// Creates a new [AndroidNavigationDelegate].
AndroidNavigationDelegate(PlatformNavigationDelegateCreationParams params)
: super.implementation(params is AndroidNavigationDelegateCreationParams
? params
: AndroidNavigationDelegateCreationParams
.fromPlatformNavigationDelegateCreationParams(params)) {
final WeakReference<AndroidNavigationDelegate> weakThis =
WeakReference<AndroidNavigationDelegate>(this);
_webViewClient = (this.params as AndroidNavigationDelegateCreationParams)
.androidWebViewProxy
.createAndroidWebViewClient(
onPageFinished: (android_webview.WebView webView, String url) {
final PageEventCallback? callback = weakThis.target?._onPageFinished;
if (callback != null) {
callback(url);
}
},
onPageStarted: (android_webview.WebView webView, String url) {
final PageEventCallback? callback = weakThis.target?._onPageStarted;
if (callback != null) {
callback(url);
}
},
onReceivedHttpError: (
android_webview.WebView webView,
android_webview.WebResourceRequest request,
android_webview.WebResourceResponse response,
) {
if (weakThis.target?._onHttpError != null) {
weakThis.target!._onHttpError!(
HttpResponseError(
request: WebResourceRequest(
uri: Uri.parse(request.url),
),
response: WebResourceResponse(
uri: null,
statusCode: response.statusCode,
),
),
);
}
},
onReceivedRequestError: (
android_webview.WebView webView,
android_webview.WebResourceRequest request,
android_webview.WebResourceError error,
) {
final WebResourceErrorCallback? callback =
weakThis.target?._onWebResourceError;
if (callback != null) {
callback(AndroidWebResourceError._(
errorCode: error.errorCode,
description: error.description,
url: request.url,
isForMainFrame: request.isForMainFrame,
));
}
},
onReceivedError: (
android_webview.WebView webView,
int errorCode,
String description,
String failingUrl,
) {
final WebResourceErrorCallback? callback =
weakThis.target?._onWebResourceError;
if (callback != null) {
callback(AndroidWebResourceError._(
errorCode: errorCode,
description: description,
url: failingUrl,
isForMainFrame: true,
));
}
},
requestLoading: (
android_webview.WebView webView,
android_webview.WebResourceRequest request,
) {
weakThis.target?._handleNavigation(
request.url,
headers: request.requestHeaders,
isForMainFrame: request.isForMainFrame,
);
},
urlLoading: (android_webview.WebView webView, String url) {
weakThis.target?._handleNavigation(url, isForMainFrame: true);
},
doUpdateVisitedHistory: (
android_webview.WebView webView,
String url,
bool isReload,
) {
final UrlChangeCallback? callback = weakThis.target?._onUrlChange;
if (callback != null) {
callback(AndroidUrlChange(url: url, isReload: isReload));
}
},
onReceivedHttpAuthRequest: (
android_webview.WebView webView,
android_webview.HttpAuthHandler httpAuthHandler,
String host,
String realm,
) {
final void Function(HttpAuthRequest)? callback =
weakThis.target?._onHttpAuthRequest;
if (callback != null) {
callback(
HttpAuthRequest(
onProceed: (WebViewCredential credential) {
httpAuthHandler.proceed(credential.user, credential.password);
},
onCancel: () {
httpAuthHandler.cancel();
},
host: host,
realm: realm,
),
);
} else {
httpAuthHandler.cancel();
}
},
);
_downloadListener = (this.params as AndroidNavigationDelegateCreationParams)
.androidWebViewProxy
.createDownloadListener(
onDownloadStart: (
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
) {
if (weakThis.target != null) {
weakThis.target?._handleNavigation(url, isForMainFrame: true);
}
},
);
}
AndroidNavigationDelegateCreationParams get _androidParams =>
params as AndroidNavigationDelegateCreationParams;
late final android_webview.WebChromeClient _webChromeClient =
_androidParams.androidWebViewProxy.createAndroidWebChromeClient();
/// Gets the native [android_webview.WebChromeClient] that is bridged by this [AndroidNavigationDelegate].
///
/// Used by the [AndroidWebViewController] to set the `android_webview.WebView.setWebChromeClient`.
@Deprecated(
'This value is not used by `AndroidWebViewController` and has no effect on the `WebView`.',
)
android_webview.WebChromeClient get androidWebChromeClient =>
_webChromeClient;
late final android_webview.WebViewClient _webViewClient;
/// Gets the native [android_webview.WebViewClient] that is bridged by this [AndroidNavigationDelegate].
///
/// Used by the [AndroidWebViewController] to set the `android_webview.WebView.setWebViewClient`.
android_webview.WebViewClient get androidWebViewClient => _webViewClient;
late final android_webview.DownloadListener _downloadListener;
/// Gets the native [android_webview.DownloadListener] that is bridged by this [AndroidNavigationDelegate].
///
/// Used by the [AndroidWebViewController] to set the `android_webview.WebView.setDownloadListener`.
android_webview.DownloadListener get androidDownloadListener =>
_downloadListener;
PageEventCallback? _onPageFinished;
PageEventCallback? _onPageStarted;
HttpResponseErrorCallback? _onHttpError;
ProgressCallback? _onProgress;
WebResourceErrorCallback? _onWebResourceError;
NavigationRequestCallback? _onNavigationRequest;
LoadRequestCallback? _onLoadRequest;
UrlChangeCallback? _onUrlChange;
HttpAuthRequestCallback? _onHttpAuthRequest;
void _handleNavigation(
String url, {
required bool isForMainFrame,
Map<String, String> headers = const <String, String>{},
}) {
final LoadRequestCallback? onLoadRequest = _onLoadRequest;
final NavigationRequestCallback? onNavigationRequest = _onNavigationRequest;
if (onNavigationRequest == null || onLoadRequest == null) {
return;
}
final FutureOr<NavigationDecision> returnValue = onNavigationRequest(
NavigationRequest(
url: url,
isMainFrame: isForMainFrame,
),
);
if (returnValue is NavigationDecision &&
returnValue == NavigationDecision.navigate) {
onLoadRequest(LoadRequestParams(
uri: Uri.parse(url),
headers: headers,
));
} else if (returnValue is Future<NavigationDecision>) {
returnValue.then((NavigationDecision shouldLoadUrl) {
if (shouldLoadUrl == NavigationDecision.navigate) {
onLoadRequest(LoadRequestParams(
uri: Uri.parse(url),
headers: headers,
));
}
});
}
}
/// Invoked when loading the url after a navigation request is approved.
Future<void> setOnLoadRequest(
LoadRequestCallback onLoadRequest,
) async {
_onLoadRequest = onLoadRequest;
}
@override
Future<void> setOnNavigationRequest(
NavigationRequestCallback onNavigationRequest,
) async {
_onNavigationRequest = onNavigationRequest;
return _webViewClient
.setSynchronousReturnValueForShouldOverrideUrlLoading(true);
}
@override
Future<void> setOnPageStarted(
PageEventCallback onPageStarted,
) async {
_onPageStarted = onPageStarted;
}
@override
Future<void> setOnPageFinished(
PageEventCallback onPageFinished,
) async {
_onPageFinished = onPageFinished;
}
@override
Future<void> setOnHttpError(
HttpResponseErrorCallback onHttpError,
) async {
_onHttpError = onHttpError;
}
@override
Future<void> setOnProgress(
ProgressCallback onProgress,
) async {
_onProgress = onProgress;
}
@override
Future<void> setOnWebResourceError(
WebResourceErrorCallback onWebResourceError,
) async {
_onWebResourceError = onWebResourceError;
}
@override
Future<void> setOnUrlChange(UrlChangeCallback onUrlChange) async {
_onUrlChange = onUrlChange;
}
@override
Future<void> setOnHttpAuthRequest(
HttpAuthRequestCallback onHttpAuthRequest,
) async {
_onHttpAuthRequest = onHttpAuthRequest;
}
}
| packages/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart",
"repo_id": "packages",
"token_count": 19766
} | 1,067 |
// 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_android/src/android_proxy.dart';
import 'package:webview_flutter_android/src/android_webview.dart'
as android_webview;
import 'package:webview_flutter_android/src/android_webview_api_impls.dart';
import 'package:webview_flutter_android/src/instance_manager.dart';
import 'package:webview_flutter_android/src/platform_views_service_proxy.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'android_navigation_delegate_test.dart';
import 'android_webview_controller_test.mocks.dart';
import 'android_webview_test.mocks.dart'
show
MockTestCustomViewCallbackHostApi,
MockTestGeolocationPermissionsCallbackHostApi;
import 'test_android_webview.g.dart';
@GenerateNiceMocks(<MockSpec<Object>>[
MockSpec<AndroidNavigationDelegate>(),
MockSpec<AndroidWebViewController>(),
MockSpec<AndroidWebViewProxy>(),
MockSpec<AndroidWebViewWidgetCreationParams>(),
MockSpec<ExpensiveAndroidViewController>(),
MockSpec<android_webview.FlutterAssetManager>(),
MockSpec<android_webview.JavaScriptChannel>(),
MockSpec<android_webview.PermissionRequest>(),
MockSpec<PlatformViewsServiceProxy>(),
MockSpec<SurfaceAndroidViewController>(),
MockSpec<android_webview.WebChromeClient>(),
MockSpec<android_webview.WebSettings>(),
MockSpec<android_webview.WebView>(),
MockSpec<android_webview.WebViewClient>(),
MockSpec<android_webview.WebStorage>(),
MockSpec<InstanceManager>(),
MockSpec<TestInstanceManagerHostApi>(),
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
AndroidWebViewController createControllerWithMocks({
android_webview.FlutterAssetManager? mockFlutterAssetManager,
android_webview.JavaScriptChannel? mockJavaScriptChannel,
android_webview.WebChromeClient Function({
void Function(android_webview.WebView webView, int progress)?
onProgressChanged,
Future<List<String>> Function(
android_webview.WebView webView,
android_webview.FileChooserParams params,
)? onShowFileChooser,
android_webview.GeolocationPermissionsShowPrompt?
onGeolocationPermissionsShowPrompt,
android_webview.GeolocationPermissionsHidePrompt?
onGeolocationPermissionsHidePrompt,
void Function(
android_webview.WebChromeClient instance,
android_webview.PermissionRequest request,
)? onPermissionRequest,
void Function(
android_webview.WebChromeClient instance,
android_webview.View view,
android_webview.CustomViewCallback callback)?
onShowCustomView,
void Function(android_webview.WebChromeClient instance)? onHideCustomView,
void Function(android_webview.WebChromeClient instance,
android_webview.ConsoleMessage message)?
onConsoleMessage,
Future<void> Function(String url, String message)? onJsAlert,
Future<bool> Function(String url, String message)? onJsConfirm,
Future<String> Function(String url, String message, String defaultValue)?
onJsPrompt,
})? createWebChromeClient,
android_webview.WebView? mockWebView,
android_webview.WebViewClient? mockWebViewClient,
android_webview.WebStorage? mockWebStorage,
android_webview.WebSettings? mockSettings,
}) {
final android_webview.WebView nonNullMockWebView =
mockWebView ?? MockWebView();
final AndroidWebViewControllerCreationParams creationParams =
AndroidWebViewControllerCreationParams(
androidWebStorage: mockWebStorage ?? MockWebStorage(),
androidWebViewProxy: AndroidWebViewProxy(
createAndroidWebChromeClient: createWebChromeClient ??
({
void Function(android_webview.WebView, int)?
onProgressChanged,
Future<List<String>> Function(
android_webview.WebView webView,
android_webview.FileChooserParams params,
)? onShowFileChooser,
void Function(
android_webview.WebChromeClient instance,
android_webview.PermissionRequest request,
)? onPermissionRequest,
Future<void> Function(
String origin,
android_webview.GeolocationPermissionsCallback callback,
)? onGeolocationPermissionsShowPrompt,
void Function(android_webview.WebChromeClient instance)?
onGeolocationPermissionsHidePrompt,
void Function(
android_webview.WebChromeClient instance,
android_webview.View view,
android_webview.CustomViewCallback callback)?
onShowCustomView,
void Function(android_webview.WebChromeClient instance)?
onHideCustomView,
void Function(android_webview.WebChromeClient instance,
android_webview.ConsoleMessage message)?
onConsoleMessage,
Future<void> Function(String url, String message)?
onJsAlert,
Future<bool> Function(String url, String message)?
onJsConfirm,
Future<String> Function(
String url, String message, String defaultValue)?
onJsPrompt,
}) =>
MockWebChromeClient(),
createAndroidWebView: (
{dynamic Function(
int left, int top, int oldLeft, int oldTop)?
onScrollChanged}) =>
nonNullMockWebView,
createAndroidWebViewClient: ({
void Function(android_webview.WebView webView, String url)?
onPageFinished,
void Function(android_webview.WebView webView, String url)?
onPageStarted,
void Function(
android_webview.WebView webView,
android_webview.WebResourceRequest request,
android_webview.WebResourceResponse response)?
onReceivedHttpError,
@Deprecated('Only called on Android version < 23.')
void Function(
android_webview.WebView webView,
int errorCode,
String description,
String failingUrl,
)? onReceivedError,
void Function(
android_webview.WebView webView,
android_webview.HttpAuthHandler hander,
String host,
String realm,
)? onReceivedHttpAuthRequest,
void Function(
android_webview.WebView webView,
android_webview.WebResourceRequest request,
android_webview.WebResourceError error,
)? onReceivedRequestError,
void Function(
android_webview.WebView webView,
android_webview.WebResourceRequest request,
)? requestLoading,
void Function(android_webview.WebView webView, String url)?
urlLoading,
void Function(
android_webview.WebView webView,
String url,
bool isReload,
)? doUpdateVisitedHistory,
}) =>
mockWebViewClient ?? MockWebViewClient(),
createFlutterAssetManager: () =>
mockFlutterAssetManager ?? MockFlutterAssetManager(),
createJavaScriptChannel: (
String channelName, {
required void Function(String) postMessage,
}) =>
mockJavaScriptChannel ?? MockJavaScriptChannel(),
));
when(nonNullMockWebView.settings)
.thenReturn(mockSettings ?? MockWebSettings());
return AndroidWebViewController(creationParams);
}
group('AndroidWebViewController', () {
AndroidJavaScriptChannelParams
createAndroidJavaScriptChannelParamsWithMocks({
String? name,
MockJavaScriptChannel? mockJavaScriptChannel,
}) {
return AndroidJavaScriptChannelParams(
name: name ?? 'test',
onMessageReceived: (JavaScriptMessage message) {},
webViewProxy: AndroidWebViewProxy(
createJavaScriptChannel: (
String channelName, {
required void Function(String) postMessage,
}) =>
mockJavaScriptChannel ?? MockJavaScriptChannel(),
));
}
test('loadFile without file prefix', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockWebSettings = MockWebSettings();
createControllerWithMocks(
mockWebView: mockWebView,
mockSettings: mockWebSettings,
);
verify(mockWebSettings.setBuiltInZoomControls(true)).called(1);
verify(mockWebSettings.setDisplayZoomControls(false)).called(1);
verify(mockWebSettings.setDomStorageEnabled(true)).called(1);
verify(mockWebSettings.setJavaScriptCanOpenWindowsAutomatically(true))
.called(1);
verify(mockWebSettings.setLoadWithOverviewMode(true)).called(1);
verify(mockWebSettings.setSupportMultipleWindows(true)).called(1);
verify(mockWebSettings.setUseWideViewPort(true)).called(1);
});
test('loadFile without file prefix', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockWebSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
mockSettings: mockWebSettings,
);
await controller.loadFile('/path/to/file.html');
verify(mockWebSettings.setAllowFileAccess(true)).called(1);
verify(mockWebView.loadUrl(
'file:///path/to/file.html',
<String, String>{},
)).called(1);
});
test('loadFile without file prefix and characters to be escaped', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockWebSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
mockSettings: mockWebSettings,
);
await controller.loadFile('/path/to/?_<_>_.html');
verify(mockWebSettings.setAllowFileAccess(true)).called(1);
verify(mockWebView.loadUrl(
'file:///path/to/%3F_%3C_%3E_.html',
<String, String>{},
)).called(1);
});
test('loadFile with file prefix', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockWebSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
when(mockWebView.settings).thenReturn(mockWebSettings);
await controller.loadFile('file:///path/to/file.html');
verify(mockWebSettings.setAllowFileAccess(true)).called(1);
verify(mockWebView.loadUrl(
'file:///path/to/file.html',
<String, String>{},
)).called(1);
});
test('loadFlutterAsset when asset does not exist', () async {
final MockWebView mockWebView = MockWebView();
final MockFlutterAssetManager mockAssetManager =
MockFlutterAssetManager();
final AndroidWebViewController controller = createControllerWithMocks(
mockFlutterAssetManager: mockAssetManager,
mockWebView: mockWebView,
);
when(mockAssetManager.getAssetFilePathByName('mock_key'))
.thenAnswer((_) => Future<String>.value(''));
when(mockAssetManager.list(''))
.thenAnswer((_) => Future<List<String>>.value(<String>[]));
try {
await controller.loadFlutterAsset('mock_key');
fail('Expected an `ArgumentError`.');
} on ArgumentError catch (e) {
expect(e.message, 'Asset for key "mock_key" not found.');
expect(e.name, 'key');
} on Error {
fail('Expect an `ArgumentError`.');
}
verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1);
verify(mockAssetManager.list('')).called(1);
verifyNever(mockWebView.loadUrl(any, any));
});
test('loadFlutterAsset when asset does exists', () async {
final MockWebView mockWebView = MockWebView();
final MockFlutterAssetManager mockAssetManager =
MockFlutterAssetManager();
final AndroidWebViewController controller = createControllerWithMocks(
mockFlutterAssetManager: mockAssetManager,
mockWebView: mockWebView,
);
when(mockAssetManager.getAssetFilePathByName('mock_key'))
.thenAnswer((_) => Future<String>.value('www/mock_file.html'));
when(mockAssetManager.list('www')).thenAnswer(
(_) => Future<List<String>>.value(<String>['mock_file.html']));
await controller.loadFlutterAsset('mock_key');
verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1);
verify(mockAssetManager.list('www')).called(1);
verify(mockWebView.loadUrl(
'file:///android_asset/www/mock_file.html', <String, String>{}));
});
test(
'loadFlutterAsset when asset name contains characters that should be escaped',
() async {
final MockWebView mockWebView = MockWebView();
final MockFlutterAssetManager mockAssetManager =
MockFlutterAssetManager();
final AndroidWebViewController controller = createControllerWithMocks(
mockFlutterAssetManager: mockAssetManager,
mockWebView: mockWebView,
);
when(mockAssetManager.getAssetFilePathByName('mock_key'))
.thenAnswer((_) => Future<String>.value('www/?_<_>_.html'));
when(mockAssetManager.list('www')).thenAnswer(
(_) => Future<List<String>>.value(<String>['?_<_>_.html']));
await controller.loadFlutterAsset('mock_key');
verify(mockAssetManager.getAssetFilePathByName('mock_key')).called(1);
verify(mockAssetManager.list('www')).called(1);
verify(mockWebView.loadUrl(
'file:///android_asset/www/%3F_%3C_%3E_.html', <String, String>{}));
});
test('loadHtmlString without baseUrl', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.loadHtmlString('<p>Hello Test!</p>');
verify(mockWebView.loadDataWithBaseUrl(
data: '<p>Hello Test!</p>',
mimeType: 'text/html',
)).called(1);
});
test('loadHtmlString with baseUrl', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.loadHtmlString('<p>Hello Test!</p>',
baseUrl: 'https://flutter.dev');
verify(mockWebView.loadDataWithBaseUrl(
data: '<p>Hello Test!</p>',
baseUrl: 'https://flutter.dev',
mimeType: 'text/html',
)).called(1);
});
test('loadRequest without URI scheme', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
final LoadRequestParams requestParams = LoadRequestParams(
uri: Uri.parse('flutter.dev'),
);
try {
await controller.loadRequest(requestParams);
fail('Expect an `ArgumentError`.');
} on ArgumentError catch (e) {
expect(e.message, 'WebViewRequest#uri is required to have a scheme.');
} on Error {
fail('Expect a `ArgumentError`.');
}
verifyNever(mockWebView.loadUrl(any, any));
verifyNever(mockWebView.postUrl(any, any));
});
test('loadRequest using the GET method', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
final LoadRequestParams requestParams = LoadRequestParams(
uri: Uri.parse('https://flutter.dev'),
headers: const <String, String>{'X-Test': 'Testing'},
);
await controller.loadRequest(requestParams);
verify(mockWebView.loadUrl(
'https://flutter.dev',
<String, String>{'X-Test': 'Testing'},
));
verifyNever(mockWebView.postUrl(any, any));
});
test('loadRequest using the POST method without body', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
final LoadRequestParams requestParams = LoadRequestParams(
uri: Uri.parse('https://flutter.dev'),
method: LoadRequestMethod.post,
headers: const <String, String>{'X-Test': 'Testing'},
);
await controller.loadRequest(requestParams);
verify(mockWebView.postUrl(
'https://flutter.dev',
Uint8List(0),
));
verifyNever(mockWebView.loadUrl(any, any));
});
test('loadRequest using the POST method with body', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
final LoadRequestParams requestParams = LoadRequestParams(
uri: Uri.parse('https://flutter.dev'),
method: LoadRequestMethod.post,
headers: const <String, String>{'X-Test': 'Testing'},
body: Uint8List.fromList('{"message": "Hello World!"}'.codeUnits),
);
await controller.loadRequest(requestParams);
verify(mockWebView.postUrl(
'https://flutter.dev',
Uint8List.fromList('{"message": "Hello World!"}'.codeUnits),
));
verifyNever(mockWebView.loadUrl(any, any));
});
test('currentUrl', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.currentUrl();
verify(mockWebView.getUrl()).called(1);
});
test('canGoBack', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.canGoBack();
verify(mockWebView.canGoBack()).called(1);
});
test('canGoForward', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.canGoForward();
verify(mockWebView.canGoForward()).called(1);
});
test('goBack', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.goBack();
verify(mockWebView.goBack()).called(1);
});
test('goForward', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.goForward();
verify(mockWebView.goForward()).called(1);
});
test('reload', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.reload();
verify(mockWebView.reload()).called(1);
});
test('clearCache', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.clearCache();
verify(mockWebView.clearCache(true)).called(1);
});
test('clearLocalStorage', () async {
final MockWebStorage mockWebStorage = MockWebStorage();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebStorage: mockWebStorage,
);
await controller.clearLocalStorage();
verify(mockWebStorage.deleteAllData()).called(1);
});
test('setPlatformNavigationDelegate', () async {
final MockAndroidNavigationDelegate mockNavigationDelegate =
MockAndroidNavigationDelegate();
final MockWebView mockWebView = MockWebView();
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final MockWebViewClient mockWebViewClient = MockWebViewClient();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
when(mockNavigationDelegate.androidWebChromeClient)
.thenReturn(mockWebChromeClient);
when(mockNavigationDelegate.androidWebViewClient)
.thenReturn(mockWebViewClient);
await controller.setPlatformNavigationDelegate(mockNavigationDelegate);
verify(mockWebView.setWebViewClient(mockWebViewClient));
verifyNever(mockWebView.setWebChromeClient(mockWebChromeClient));
});
test('onProgress', () {
final AndroidNavigationDelegate androidNavigationDelegate =
AndroidNavigationDelegate(
AndroidNavigationDelegateCreationParams
.fromPlatformNavigationDelegateCreationParams(
const PlatformNavigationDelegateCreationParams(),
androidWebViewProxy: const AndroidWebViewProxy(
createAndroidWebViewClient: android_webview.WebViewClient.detached,
createAndroidWebChromeClient:
android_webview.WebChromeClient.detached,
createDownloadListener: android_webview.DownloadListener.detached,
),
),
);
late final int callbackProgress;
androidNavigationDelegate
.setOnProgress((int progress) => callbackProgress = progress);
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: CapturingWebChromeClient.new,
);
controller.setPlatformNavigationDelegate(androidNavigationDelegate);
CapturingWebChromeClient.lastCreatedDelegate.onProgressChanged!(
android_webview.WebView.detached(),
42,
);
expect(callbackProgress, 42);
});
test('onProgress does not cause LateInitializationError', () {
// ignore: unused_local_variable
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: CapturingWebChromeClient.new,
);
// Should not cause LateInitializationError
CapturingWebChromeClient.lastCreatedDelegate.onProgressChanged!(
android_webview.WebView.detached(),
42,
);
});
test('setOnShowFileSelector', () async {
late final Future<List<String>> Function(
android_webview.WebView webView,
android_webview.FileChooserParams params,
) onShowFileChooserCallback;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
Future<List<String>> Function(
android_webview.WebView webView,
android_webview.FileChooserParams params,
)? onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
dynamic onPermissionRequest,
dynamic onShowCustomView,
dynamic onHideCustomView,
dynamic onConsoleMessage,
dynamic onJsAlert,
dynamic onJsConfirm,
dynamic onJsPrompt,
}) {
onShowFileChooserCallback = onShowFileChooser!;
return mockWebChromeClient;
},
);
late final FileSelectorParams fileSelectorParams;
await controller.setOnShowFileSelector(
(FileSelectorParams params) async {
fileSelectorParams = params;
return <String>[];
},
);
verify(
mockWebChromeClient.setSynchronousReturnValueForOnShowFileChooser(true),
);
await onShowFileChooserCallback(
android_webview.WebView.detached(),
android_webview.FileChooserParams.detached(
isCaptureEnabled: false,
acceptTypes: const <String>['png'],
filenameHint: 'filenameHint',
mode: android_webview.FileChooserMode.open,
),
);
expect(fileSelectorParams.isCaptureEnabled, isFalse);
expect(fileSelectorParams.acceptTypes, <String>['png']);
expect(fileSelectorParams.filenameHint, 'filenameHint');
expect(fileSelectorParams.mode, FileSelectorMode.open);
});
test('setGeolocationPermissionsPromptCallbacks', () async {
final MockTestGeolocationPermissionsCallbackHostApi mockApi =
MockTestGeolocationPermissionsCallbackHostApi();
TestGeolocationPermissionsCallbackHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final android_webview.GeolocationPermissionsCallback testCallback =
android_webview.GeolocationPermissionsCallback.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(testCallback, instanceIdentifier);
late final Future<void> Function(String origin,
android_webview.GeolocationPermissionsCallback callback)
onGeoPermissionHandle;
late final void Function(android_webview.WebChromeClient instance)
onGeoPermissionHidePromptHandle;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
Future<void> Function(String origin,
android_webview.GeolocationPermissionsCallback callback)?
onGeolocationPermissionsShowPrompt,
void Function(android_webview.WebChromeClient instance)?
onGeolocationPermissionsHidePrompt,
dynamic onPermissionRequest,
dynamic onShowCustomView,
dynamic onHideCustomView,
dynamic onConsoleMessage,
dynamic onJsAlert,
dynamic onJsConfirm,
dynamic onJsPrompt,
}) {
onGeoPermissionHandle = onGeolocationPermissionsShowPrompt!;
onGeoPermissionHidePromptHandle = onGeolocationPermissionsHidePrompt!;
return mockWebChromeClient;
},
);
String testValue = 'origin';
const String allowOrigin = 'https://www.allow.com';
bool isAllow = false;
late final GeolocationPermissionsResponse response;
await controller.setGeolocationPermissionsPromptCallbacks(
onShowPrompt: (GeolocationPermissionsRequestParams request) async {
isAllow = request.origin == allowOrigin;
response =
GeolocationPermissionsResponse(allow: isAllow, retain: isAllow);
return response;
},
onHidePrompt: () {
testValue = 'changed';
},
);
await onGeoPermissionHandle(
allowOrigin,
testCallback,
);
expect(isAllow, true);
onGeoPermissionHidePromptHandle(mockWebChromeClient);
expect(testValue, 'changed');
});
test('setCustomViewCallbacks', () async {
final MockTestCustomViewCallbackHostApi mockApi =
MockTestCustomViewCallbackHostApi();
TestCustomViewCallbackHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final android_webview.CustomViewCallback testCallback =
android_webview.CustomViewCallback.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(testCallback, instanceIdentifier);
late final void Function(
android_webview.WebChromeClient instance,
android_webview.View view,
android_webview.CustomViewCallback callback) onShowCustomViewHandle;
late final void Function(android_webview.WebChromeClient instance)
onHideCustomViewHandle;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
dynamic onPermissionRequest,
dynamic onJsAlert,
dynamic onJsConfirm,
dynamic onJsPrompt,
void Function(
android_webview.WebChromeClient instance,
android_webview.View view,
android_webview.CustomViewCallback callback)?
onShowCustomView,
void Function(android_webview.WebChromeClient instance)?
onHideCustomView,
dynamic onConsoleMessage,
}) {
onShowCustomViewHandle = onShowCustomView!;
onHideCustomViewHandle = onHideCustomView!;
return mockWebChromeClient;
},
);
final android_webview.View testView = android_webview.View.detached();
bool showCustomViewCalled = false;
bool hideCustomViewCalled = false;
await controller.setCustomWidgetCallbacks(
onShowCustomWidget:
(Widget widget, OnHideCustomWidgetCallback callback) async {
showCustomViewCalled = true;
},
onHideCustomWidget: () {
hideCustomViewCalled = true;
},
);
onShowCustomViewHandle(
mockWebChromeClient,
testView,
android_webview.CustomViewCallback.detached(),
);
expect(showCustomViewCalled, true);
onHideCustomViewHandle(mockWebChromeClient);
expect(hideCustomViewCalled, true);
});
test('setOnPlatformPermissionRequest', () async {
late final void Function(
android_webview.WebChromeClient instance,
android_webview.PermissionRequest request,
) onPermissionRequestCallback;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
void Function(
android_webview.WebChromeClient instance,
android_webview.PermissionRequest request,
)? onPermissionRequest,
dynamic onShowCustomView,
dynamic onHideCustomView,
dynamic onConsoleMessage,
dynamic onJsAlert,
dynamic onJsConfirm,
dynamic onJsPrompt,
}) {
onPermissionRequestCallback = onPermissionRequest!;
return mockWebChromeClient;
},
);
late final PlatformWebViewPermissionRequest permissionRequest;
await controller.setOnPlatformPermissionRequest(
(PlatformWebViewPermissionRequest request) async {
permissionRequest = request;
await request.grant();
},
);
final List<String> permissionTypes = <String>[
android_webview.PermissionRequest.audioCapture,
];
final MockPermissionRequest mockPermissionRequest =
MockPermissionRequest();
when(mockPermissionRequest.resources).thenReturn(permissionTypes);
onPermissionRequestCallback(
android_webview.WebChromeClient.detached(),
mockPermissionRequest,
);
expect(permissionRequest.types, <WebViewPermissionResourceType>[
WebViewPermissionResourceType.microphone,
]);
verify(mockPermissionRequest.grant(permissionTypes));
});
test(
'setOnPlatformPermissionRequest callback not invoked when type is not recognized',
() async {
late final void Function(
android_webview.WebChromeClient instance,
android_webview.PermissionRequest request,
) onPermissionRequestCallback;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
void Function(
android_webview.WebChromeClient instance,
android_webview.PermissionRequest request,
)? onPermissionRequest,
dynamic onShowCustomView,
dynamic onHideCustomView,
dynamic onConsoleMessage,
dynamic onJsAlert,
dynamic onJsConfirm,
dynamic onJsPrompt,
}) {
onPermissionRequestCallback = onPermissionRequest!;
return mockWebChromeClient;
},
);
bool callbackCalled = false;
await controller.setOnPlatformPermissionRequest(
(PlatformWebViewPermissionRequest request) async {
callbackCalled = true;
},
);
final MockPermissionRequest mockPermissionRequest =
MockPermissionRequest();
when(mockPermissionRequest.resources).thenReturn(<String>['unknownType']);
onPermissionRequestCallback(
android_webview.WebChromeClient.detached(),
mockPermissionRequest,
);
expect(callbackCalled, isFalse);
});
group('JavaScript Dialog', () {
test('setOnJavaScriptAlertDialog', () async {
late final Future<void> Function(String url, String message)
onJsAlertCallback;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
dynamic onPermissionRequest,
dynamic onShowCustomView,
dynamic onHideCustomView,
Future<void> Function(String url, String message)? onJsAlert,
dynamic onJsConfirm,
dynamic onJsPrompt,
dynamic onConsoleMessage,
}) {
onJsAlertCallback = onJsAlert!;
return mockWebChromeClient;
},
);
late final String message;
await controller.setOnJavaScriptAlertDialog(
(JavaScriptAlertDialogRequest request) async {
message = request.message;
return;
});
const String callbackMessage = 'Message';
await onJsAlertCallback('', callbackMessage);
expect(message, callbackMessage);
});
test('setOnJavaScriptConfirmDialog', () async {
late final Future<bool> Function(String url, String message)
onJsConfirmCallback;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
dynamic onPermissionRequest,
dynamic onShowCustomView,
dynamic onHideCustomView,
dynamic onJsAlert,
Future<bool> Function(String url, String message)? onJsConfirm,
dynamic onJsPrompt,
dynamic onConsoleMessage,
}) {
onJsConfirmCallback = onJsConfirm!;
return mockWebChromeClient;
},
);
late final String message;
const bool callbackReturnValue = true;
await controller.setOnJavaScriptConfirmDialog(
(JavaScriptConfirmDialogRequest request) async {
message = request.message;
return callbackReturnValue;
});
const String callbackMessage = 'Message';
final bool returnValue = await onJsConfirmCallback('', callbackMessage);
expect(message, callbackMessage);
expect(returnValue, callbackReturnValue);
});
test('setOnJavaScriptTextInputDialog', () async {
late final Future<String> Function(
String url, String message, String defaultValue) onJsPromptCallback;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
dynamic onPermissionRequest,
dynamic onShowCustomView,
dynamic onHideCustomView,
dynamic onJsAlert,
dynamic onJsConfirm,
Future<String> Function(
String url, String message, String defaultText)?
onJsPrompt,
dynamic onConsoleMessage,
}) {
onJsPromptCallback = onJsPrompt!;
return mockWebChromeClient;
},
);
late final String message;
late final String? defaultText;
const String callbackReturnValue = 'Return Value';
await controller.setOnJavaScriptTextInputDialog(
(JavaScriptTextInputDialogRequest request) async {
message = request.message;
defaultText = request.defaultText;
return callbackReturnValue;
});
const String callbackMessage = 'Message';
const String callbackDefaultText = 'Default Text';
final String returnValue =
await onJsPromptCallback('', callbackMessage, callbackDefaultText);
expect(message, callbackMessage);
expect(defaultText, callbackDefaultText);
expect(returnValue, callbackReturnValue);
});
});
test('setOnConsoleLogCallback', () async {
late final void Function(
android_webview.WebChromeClient instance,
android_webview.ConsoleMessage message,
) onConsoleMessageCallback;
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
dynamic onPermissionRequest,
dynamic onShowCustomView,
dynamic onHideCustomView,
dynamic onJsAlert,
dynamic onJsConfirm,
dynamic onJsPrompt,
void Function(
android_webview.WebChromeClient,
android_webview.ConsoleMessage,
)? onConsoleMessage,
}) {
onConsoleMessageCallback = onConsoleMessage!;
return mockWebChromeClient;
},
);
final Map<String, JavaScriptLogLevel> logs =
<String, JavaScriptLogLevel>{};
await controller.setOnConsoleMessage(
(JavaScriptConsoleMessage message) async {
logs[message.message] = message.level;
},
);
onConsoleMessageCallback(
mockWebChromeClient,
ConsoleMessage(
lineNumber: 42,
message: 'Debug message',
level: ConsoleMessageLevel.debug,
sourceId: 'source',
),
);
onConsoleMessageCallback(
mockWebChromeClient,
ConsoleMessage(
lineNumber: 42,
message: 'Error message',
level: ConsoleMessageLevel.error,
sourceId: 'source',
),
);
onConsoleMessageCallback(
mockWebChromeClient,
ConsoleMessage(
lineNumber: 42,
message: 'Log message',
level: ConsoleMessageLevel.log,
sourceId: 'source',
),
);
onConsoleMessageCallback(
mockWebChromeClient,
ConsoleMessage(
lineNumber: 42,
message: 'Tip message',
level: ConsoleMessageLevel.tip,
sourceId: 'source',
),
);
onConsoleMessageCallback(
mockWebChromeClient,
ConsoleMessage(
lineNumber: 42,
message: 'Warning message',
level: ConsoleMessageLevel.warning,
sourceId: 'source',
),
);
onConsoleMessageCallback(
mockWebChromeClient,
ConsoleMessage(
lineNumber: 42,
message: 'Unknown message',
level: ConsoleMessageLevel.unknown,
sourceId: 'source',
),
);
expect(logs.length, 6);
expect(logs['Debug message'], JavaScriptLogLevel.debug);
expect(logs['Error message'], JavaScriptLogLevel.error);
expect(logs['Log message'], JavaScriptLogLevel.log);
expect(logs['Tip message'], JavaScriptLogLevel.debug);
expect(logs['Warning message'], JavaScriptLogLevel.warning);
expect(logs['Unknown message'], JavaScriptLogLevel.log);
});
test('runJavaScript', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.runJavaScript('alert("This is a test.");');
verify(mockWebView.evaluateJavascript('alert("This is a test.");'))
.called(1);
});
test('runJavaScriptReturningResult with return value', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
when(mockWebView.evaluateJavascript('return "Hello" + " World!";'))
.thenAnswer((_) => Future<String>.value('Hello World!'));
final String message = await controller.runJavaScriptReturningResult(
'return "Hello" + " World!";') as String;
expect(message, 'Hello World!');
});
test('runJavaScriptReturningResult returning null', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
when(mockWebView.evaluateJavascript('alert("This is a test.");'))
.thenAnswer((_) => Future<String?>.value());
final String message = await controller
.runJavaScriptReturningResult('alert("This is a test.");') as String;
expect(message, '');
});
test('runJavaScriptReturningResult parses num', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
when(mockWebView.evaluateJavascript('alert("This is a test.");'))
.thenAnswer((_) => Future<String?>.value('3.14'));
final num message = await controller
.runJavaScriptReturningResult('alert("This is a test.");') as num;
expect(message, 3.14);
});
test('runJavaScriptReturningResult parses true', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
when(mockWebView.evaluateJavascript('alert("This is a test.");'))
.thenAnswer((_) => Future<String?>.value('true'));
final bool message = await controller
.runJavaScriptReturningResult('alert("This is a test.");') as bool;
expect(message, true);
});
test('runJavaScriptReturningResult parses false', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
when(mockWebView.evaluateJavascript('alert("This is a test.");'))
.thenAnswer((_) => Future<String?>.value('false'));
final bool message = await controller
.runJavaScriptReturningResult('alert("This is a test.");') as bool;
expect(message, false);
});
test('addJavaScriptChannel', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
final AndroidJavaScriptChannelParams paramsWithMock =
createAndroidJavaScriptChannelParamsWithMocks(name: 'test');
await controller.addJavaScriptChannel(paramsWithMock);
verify(mockWebView.addJavaScriptChannel(
argThat(isA<android_webview.JavaScriptChannel>())))
.called(1);
});
test(
'addJavaScriptChannel add channel with same name should remove existing channel',
() async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
final AndroidJavaScriptChannelParams paramsWithMock =
createAndroidJavaScriptChannelParamsWithMocks(name: 'test');
await controller.addJavaScriptChannel(paramsWithMock);
verify(mockWebView.addJavaScriptChannel(
argThat(isA<android_webview.JavaScriptChannel>())))
.called(1);
await controller.addJavaScriptChannel(paramsWithMock);
verifyInOrder(<Object>[
mockWebView.removeJavaScriptChannel(
argThat(isA<android_webview.JavaScriptChannel>())),
mockWebView.addJavaScriptChannel(
argThat(isA<android_webview.JavaScriptChannel>())),
]);
});
test('removeJavaScriptChannel when channel is not registered', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.removeJavaScriptChannel('test');
verifyNever(mockWebView.removeJavaScriptChannel(any));
});
test('removeJavaScriptChannel when channel exists', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
final AndroidJavaScriptChannelParams paramsWithMock =
createAndroidJavaScriptChannelParamsWithMocks(name: 'test');
// Make sure channel exists before removing it.
await controller.addJavaScriptChannel(paramsWithMock);
verify(mockWebView.addJavaScriptChannel(
argThat(isA<android_webview.JavaScriptChannel>())))
.called(1);
await controller.removeJavaScriptChannel('test');
verify(mockWebView.removeJavaScriptChannel(
argThat(isA<android_webview.JavaScriptChannel>())))
.called(1);
});
test('getTitle', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.getTitle();
verify(mockWebView.getTitle()).called(1);
});
test('scrollTo', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.scrollTo(4, 2);
verify(mockWebView.scrollTo(4, 2)).called(1);
});
test('scrollBy', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.scrollBy(4, 2);
verify(mockWebView.scrollBy(4, 2)).called(1);
});
test('getScrollPosition', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
when(mockWebView.getScrollPosition())
.thenAnswer((_) => Future<Offset>.value(const Offset(4, 2)));
final Offset position = await controller.getScrollPosition();
verify(mockWebView.getScrollPosition()).called(1);
expect(position.dx, 4);
expect(position.dy, 2);
});
test('enableDebugging', () async {
final MockAndroidWebViewProxy mockProxy = MockAndroidWebViewProxy();
await AndroidWebViewController.enableDebugging(
true,
webViewProxy: mockProxy,
);
verify(mockProxy.setWebContentsDebuggingEnabled(true)).called(1);
});
test('enableZoom', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
mockSettings: mockSettings,
);
clearInteractions(mockWebView);
await controller.enableZoom(true);
verify(mockWebView.settings).called(1);
verify(mockSettings.setSupportZoom(true)).called(1);
});
test('setBackgroundColor', () async {
final MockWebView mockWebView = MockWebView();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
await controller.setBackgroundColor(Colors.blue);
verify(mockWebView.setBackgroundColor(Colors.blue)).called(1);
});
test('setJavaScriptMode', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
mockSettings: mockSettings,
);
clearInteractions(mockWebView);
await controller.setJavaScriptMode(JavaScriptMode.disabled);
verify(mockWebView.settings).called(1);
verify(mockSettings.setJavaScriptEnabled(false)).called(1);
});
test('setUserAgent', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
mockSettings: mockSettings,
);
clearInteractions(mockWebView);
await controller.setUserAgent('Test Framework');
verify(mockWebView.settings).called(1);
verify(mockSettings.setUserAgentString('Test Framework')).called(1);
});
test('getUserAgent', () async {
final MockWebSettings mockSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockSettings: mockSettings,
);
const String userAgent = 'str';
when(mockSettings.getUserAgentString())
.thenAnswer((_) => Future<String>.value(userAgent));
expect(await controller.getUserAgent(), userAgent);
});
});
test('setMediaPlaybackRequiresUserGesture', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
mockSettings: mockSettings,
);
await controller.setMediaPlaybackRequiresUserGesture(true);
verify(mockSettings.setMediaPlaybackRequiresUserGesture(true)).called(1);
});
test('setTextZoom', () async {
final MockWebView mockWebView = MockWebView();
final MockWebSettings mockSettings = MockWebSettings();
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
mockSettings: mockSettings,
);
clearInteractions(mockWebView);
await controller.setTextZoom(100);
verify(mockWebView.settings).called(1);
verify(mockSettings.setTextZoom(100)).called(1);
});
test('webViewIdentifier', () {
final MockWebView mockWebView = MockWebView();
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
instanceManager.addHostCreatedInstance(mockWebView, 0);
android_webview.WebView.api = WebViewHostApiImpl(
instanceManager: instanceManager,
);
final AndroidWebViewController controller = createControllerWithMocks(
mockWebView: mockWebView,
);
expect(
controller.webViewIdentifier,
0,
);
android_webview.WebView.api = WebViewHostApiImpl();
});
group('AndroidWebViewWidget', () {
testWidgets('Builds Android view using supplied parameters',
(WidgetTester tester) async {
final AndroidWebViewController controller = createControllerWithMocks();
final AndroidWebViewWidget webViewWidget = AndroidWebViewWidget(
AndroidWebViewWidgetCreationParams(
key: const Key('test_web_view'),
controller: controller,
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) => webViewWidget.build(context),
));
expect(find.byType(PlatformViewLink), findsOneWidget);
expect(find.byKey(const Key('test_web_view')), findsOneWidget);
});
testWidgets('displayWithHybridComposition is false',
(WidgetTester tester) async {
final AndroidWebViewController controller = createControllerWithMocks();
final MockPlatformViewsServiceProxy mockPlatformViewsService =
MockPlatformViewsServiceProxy();
when(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
).thenReturn(MockSurfaceAndroidViewController());
final AndroidWebViewWidget webViewWidget = AndroidWebViewWidget(
AndroidWebViewWidgetCreationParams(
key: const Key('test_web_view'),
controller: controller,
platformViewsServiceProxy: mockPlatformViewsService,
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) => webViewWidget.build(context),
));
await tester.pumpAndSettle();
verify(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
);
});
testWidgets('displayWithHybridComposition is true',
(WidgetTester tester) async {
final AndroidWebViewController controller = createControllerWithMocks();
final MockPlatformViewsServiceProxy mockPlatformViewsService =
MockPlatformViewsServiceProxy();
when(
mockPlatformViewsService.initExpensiveAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
).thenReturn(MockExpensiveAndroidViewController());
final AndroidWebViewWidget webViewWidget = AndroidWebViewWidget(
AndroidWebViewWidgetCreationParams(
key: const Key('test_web_view'),
controller: controller,
platformViewsServiceProxy: mockPlatformViewsService,
displayWithHybridComposition: true,
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) => webViewWidget.build(context),
));
await tester.pumpAndSettle();
verify(
mockPlatformViewsService.initExpensiveAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
);
});
testWidgets('default handling of custom views',
(WidgetTester tester) async {
final MockWebChromeClient mockWebChromeClient = MockWebChromeClient();
void Function(
android_webview.WebChromeClient instance,
android_webview.View view,
android_webview.CustomViewCallback callback)?
onShowCustomViewCallback;
final AndroidWebViewController controller = createControllerWithMocks(
createWebChromeClient: ({
dynamic onProgressChanged,
dynamic onShowFileChooser,
dynamic onGeolocationPermissionsShowPrompt,
dynamic onGeolocationPermissionsHidePrompt,
dynamic onPermissionRequest,
void Function(
android_webview.WebChromeClient instance,
android_webview.View view,
android_webview.CustomViewCallback callback)?
onShowCustomView,
dynamic onHideCustomView,
dynamic onConsoleMessage,
dynamic onJsAlert,
dynamic onJsConfirm,
dynamic onJsPrompt,
}) {
onShowCustomViewCallback = onShowCustomView;
return mockWebChromeClient;
},
);
final MockPlatformViewsServiceProxy mockPlatformViewsService =
MockPlatformViewsServiceProxy();
when(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
).thenReturn(MockSurfaceAndroidViewController());
final AndroidWebViewWidget webViewWidget = AndroidWebViewWidget(
AndroidWebViewWidgetCreationParams(
key: const Key('test_web_view'),
controller: controller,
platformViewsServiceProxy: mockPlatformViewsService,
),
);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (BuildContext context) => webViewWidget.build(context),
),
),
);
await tester.pumpAndSettle();
onShowCustomViewCallback!(
MockWebChromeClient(),
android_webview.WebView.detached(),
android_webview.CustomViewCallback.detached(),
);
await tester.pumpAndSettle();
expect(find.byType(AndroidCustomViewWidget), findsOneWidget);
});
testWidgets('PlatformView is recreated when the controller changes',
(WidgetTester tester) async {
final MockPlatformViewsServiceProxy mockPlatformViewsService =
MockPlatformViewsServiceProxy();
when(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
).thenReturn(MockSurfaceAndroidViewController());
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return AndroidWebViewWidget(
AndroidWebViewWidgetCreationParams(
controller: createControllerWithMocks(),
platformViewsServiceProxy: mockPlatformViewsService,
),
).build(context);
},
));
await tester.pumpAndSettle();
verify(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return AndroidWebViewWidget(
AndroidWebViewWidgetCreationParams(
controller: createControllerWithMocks(),
platformViewsServiceProxy: mockPlatformViewsService,
),
).build(context);
},
));
await tester.pumpAndSettle();
verify(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
);
});
testWidgets(
'PlatformView does not rebuild when creation params stay the same',
(WidgetTester tester) async {
final MockPlatformViewsServiceProxy mockPlatformViewsService =
MockPlatformViewsServiceProxy();
final AndroidWebViewController controller = createControllerWithMocks();
when(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
).thenReturn(MockSurfaceAndroidViewController());
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return AndroidWebViewWidget(
AndroidWebViewWidgetCreationParams(
controller: controller,
platformViewsServiceProxy: mockPlatformViewsService,
),
).build(context);
},
));
await tester.pumpAndSettle();
verify(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
return AndroidWebViewWidget(
AndroidWebViewWidgetCreationParams(
controller: controller,
platformViewsServiceProxy: mockPlatformViewsService,
),
).build(context);
},
));
await tester.pumpAndSettle();
verifyNever(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
);
});
});
group('AndroidCustomViewWidget', () {
testWidgets('Builds Android custom view using supplied parameters',
(WidgetTester tester) async {
final AndroidWebViewController controller = createControllerWithMocks();
final AndroidCustomViewWidget customViewWidget =
AndroidCustomViewWidget.private(
key: const Key('test_custom_view'),
customView: android_webview.View.detached(),
controller: controller,
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) => customViewWidget.build(context),
));
expect(find.byType(PlatformViewLink), findsOneWidget);
expect(find.byKey(const Key('test_custom_view')), findsOneWidget);
});
testWidgets('displayWithHybridComposition should be false',
(WidgetTester tester) async {
final AndroidWebViewController controller = createControllerWithMocks();
final MockPlatformViewsServiceProxy mockPlatformViewsService =
MockPlatformViewsServiceProxy();
when(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
).thenReturn(MockSurfaceAndroidViewController());
final AndroidCustomViewWidget customViewWidget =
AndroidCustomViewWidget.private(
controller: controller,
customView: android_webview.View.detached(),
platformViewsServiceProxy: mockPlatformViewsService,
);
await tester.pumpWidget(Builder(
builder: (BuildContext context) => customViewWidget.build(context),
));
await tester.pumpAndSettle();
verify(
mockPlatformViewsService.initSurfaceAndroidView(
id: anyNamed('id'),
viewType: anyNamed('viewType'),
layoutDirection: anyNamed('layoutDirection'),
creationParams: anyNamed('creationParams'),
creationParamsCodec: anyNamed('creationParamsCodec'),
onFocus: anyNamed('onFocus'),
),
);
});
});
}
| packages/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart",
"repo_id": "packages",
"token_count": 27081
} | 1,068 |
// 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.
/// Defines the parameters of the pending navigation callback.
class NavigationRequest {
/// Creates a [NavigationRequest].
const NavigationRequest({
required this.url,
required this.isMainFrame,
});
/// The URL of the pending navigation request.
final String url;
/// Indicates whether the request was made in the web site's main frame or a subframe.
final bool isMainFrame;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/navigation_request.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/navigation_request.dart",
"repo_id": "packages",
"token_count": 148
} | 1,069 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 0.2.2+4
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Fixes new lint warnings.
## 0.2.2+3
* Migrates to `dart:ui_web` APIs.
* Updates minimum supported SDK version to Flutter 3.13.0/Dart 3.1.0.
## 0.2.2+2
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
* Removes obsolete null checks on non-nullable values.
* Updates minimum Flutter version to 3.3.
* Aligns Dart and Flutter SDK constraints.
## 0.2.2+1
* Updates links for the merge of flutter/plugins into flutter/packages.
## 0.2.2
* Updates `WebWebViewController.loadRequest` to only set the src of the iFrame
when `LoadRequestParams.headers` and `LoadRequestParams.body` are empty and is
using the HTTP GET request method. [#118573](https://github.com/flutter/flutter/issues/118573).
* Parses the `content-type` header of XHR responses to extract the correct
MIME-type and charset. [#118090](https://github.com/flutter/flutter/issues/118090).
* Sets `width` and `height` of widget the way the Engine wants, to remove distracting
warnings from the development console.
* Updates minimum Flutter version to 3.0.
## 0.2.1
* Adds auto registration of the `WebViewPlatform` implementation.
## 0.2.0
* **BREAKING CHANGE** Updates platform implementation to `2.0.0` release of
`webview_flutter_platform_interface`. See README for updated usage.
* Updates minimum Flutter version to 2.10.
## 0.1.0+4
* Fixes incorrect escaping of some characters when setting the HTML to the iframe element.
## 0.1.0+3
* Minor fixes for new analysis options.
## 0.1.0+2
* Removes unnecessary imports.
* Fixes unit tests to run on latest `master` version of Flutter.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.1.0+1
* Adds an explanation of registering the implementation in the README.
## 0.1.0
* First web implementation for webview_flutter
| packages/packages/webview_flutter/webview_flutter_web/CHANGELOG.md/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_web/CHANGELOG.md",
"repo_id": "packages",
"token_count": 653
} | 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 FWFDataConvertersTests : XCTestCase
@end
@implementation FWFDataConvertersTests
- (void)testFWFNSURLRequestFromRequestData {
NSURLRequest *request = FWFNativeNSURLRequestFromRequestData([FWFNSUrlRequestData
makeWithUrl:@"https://flutter.dev"
httpMethod:@"post"
httpBody:[FlutterStandardTypedData typedDataWithBytes:[NSData data]]
allHttpHeaderFields:@{@"a" : @"header"}]);
XCTAssertEqualObjects(request.URL, [NSURL URLWithString:@"https://flutter.dev"]);
XCTAssertEqualObjects(request.HTTPMethod, @"POST");
XCTAssertEqualObjects(request.HTTPBody, [NSData data]);
XCTAssertEqualObjects(request.allHTTPHeaderFields, @{@"a" : @"header"});
}
- (void)testFWFNSURLRequestFromRequestDataDoesNotOverrideDefaultValuesWithNull {
NSURLRequest *request =
FWFNativeNSURLRequestFromRequestData([FWFNSUrlRequestData makeWithUrl:@"https://flutter.dev"
httpMethod:nil
httpBody:nil
allHttpHeaderFields:@{}]);
XCTAssertEqualObjects(request.HTTPMethod, @"GET");
}
- (void)testFWFNSHTTPCookieFromCookieData {
NSHTTPCookie *cookie = FWFNativeNSHTTPCookieFromCookieData([FWFNSHttpCookieData
makeWithPropertyKeys:@[ [FWFNSHttpCookiePropertyKeyEnumData
makeWithValue:FWFNSHttpCookiePropertyKeyEnumName] ]
propertyValues:@[ @"cookieName" ]]);
XCTAssertEqualObjects(cookie,
[NSHTTPCookie cookieWithProperties:@{NSHTTPCookieName : @"cookieName"}]);
}
- (void)testFWFWKUserScriptFromScriptData {
WKUserScript *userScript = FWFNativeWKUserScriptFromScriptData([FWFWKUserScriptData
makeWithSource:@"mySource"
injectionTime:[FWFWKUserScriptInjectionTimeEnumData
makeWithValue:FWFWKUserScriptInjectionTimeEnumAtDocumentStart]
isMainFrameOnly:NO]);
XCTAssertEqualObjects(userScript.source, @"mySource");
XCTAssertEqual(userScript.injectionTime, WKUserScriptInjectionTimeAtDocumentStart);
XCTAssertEqual(userScript.isForMainFrameOnly, NO);
}
- (void)testFWFWKNavigationActionDataFromNavigationAction {
WKNavigationAction *mockNavigationAction = OCMClassMock([WKNavigationAction class]);
OCMStub([mockNavigationAction navigationType]).andReturn(WKNavigationTypeReload);
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.flutter.dev/"]];
OCMStub([mockNavigationAction request]).andReturn(request);
WKFrameInfo *mockFrameInfo = OCMClassMock([WKFrameInfo class]);
OCMStub([mockFrameInfo isMainFrame]).andReturn(YES);
OCMStub([mockNavigationAction targetFrame]).andReturn(mockFrameInfo);
FWFWKNavigationActionData *data =
FWFWKNavigationActionDataFromNativeWKNavigationAction(mockNavigationAction);
XCTAssertNotNil(data);
XCTAssertEqual(data.navigationType, FWFWKNavigationTypeReload);
}
- (void)testFWFNSUrlRequestDataFromNSURLRequest {
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.flutter.dev/"]];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"aString" dataUsingEncoding:NSUTF8StringEncoding];
request.allHTTPHeaderFields = @{@"a" : @"field"};
FWFNSUrlRequestData *data = FWFNSUrlRequestDataFromNativeNSURLRequest(request);
XCTAssertEqualObjects(data.url, @"https://www.flutter.dev/");
XCTAssertEqualObjects(data.httpMethod, @"POST");
XCTAssertEqualObjects(data.httpBody.data, [@"aString" dataUsingEncoding:NSUTF8StringEncoding]);
XCTAssertEqualObjects(data.allHttpHeaderFields, @{@"a" : @"field"});
}
- (void)testFWFWKFrameInfoDataFromWKFrameInfo {
WKFrameInfo *mockFrameInfo = OCMClassMock([WKFrameInfo class]);
OCMStub([mockFrameInfo isMainFrame]).andReturn(YES);
FWFWKFrameInfoData *targetFrameData = FWFWKFrameInfoDataFromNativeWKFrameInfo(mockFrameInfo);
XCTAssertEqual(targetFrameData.isMainFrame, YES);
}
- (void)testFWFNSErrorDataFromNSError {
NSObject *unsupportedType = [[NSObject alloc] init];
NSError *error = [NSError errorWithDomain:@"domain"
code:23
userInfo:@{@"a" : @"b", @"c" : unsupportedType}];
FWFNSErrorData *data = FWFNSErrorDataFromNativeNSError(error);
XCTAssertEqual(data.code, 23);
XCTAssertEqualObjects(data.domain, @"domain");
NSDictionary *userInfo = @{
@"a" : @"b",
@"c" : [NSString stringWithFormat:@"Unsupported Type: %@", unsupportedType.description]
};
XCTAssertEqualObjects(data.userInfo, userInfo);
}
- (void)testFWFWKScriptMessageDataFromWKScriptMessage {
WKScriptMessage *mockScriptMessage = OCMClassMock([WKScriptMessage class]);
OCMStub([mockScriptMessage name]).andReturn(@"name");
OCMStub([mockScriptMessage body]).andReturn(@"message");
FWFWKScriptMessageData *data = FWFWKScriptMessageDataFromNativeWKScriptMessage(mockScriptMessage);
XCTAssertEqualObjects(data.name, @"name");
XCTAssertEqualObjects(data.body, @"message");
}
- (void)testFWFWKSecurityOriginDataFromWKSecurityOrigin {
WKSecurityOrigin *mockSecurityOrigin = OCMClassMock([WKSecurityOrigin class]);
OCMStub([mockSecurityOrigin host]).andReturn(@"host");
OCMStub([mockSecurityOrigin port]).andReturn(2);
OCMStub([mockSecurityOrigin protocol]).andReturn(@"protocol");
FWFWKSecurityOriginData *data =
FWFWKSecurityOriginDataFromNativeWKSecurityOrigin(mockSecurityOrigin);
XCTAssertEqualObjects(data.host, @"host");
XCTAssertEqual(data.port, 2);
XCTAssertEqualObjects(data.protocol, @"protocol");
}
- (void)testFWFWKPermissionDecisionFromData API_AVAILABLE(ios(15.0)) {
XCTAssertEqual(FWFNativeWKPermissionDecisionFromData(
[FWFWKPermissionDecisionData makeWithValue:FWFWKPermissionDecisionDeny]),
WKPermissionDecisionDeny);
XCTAssertEqual(FWFNativeWKPermissionDecisionFromData(
[FWFWKPermissionDecisionData makeWithValue:FWFWKPermissionDecisionGrant]),
WKPermissionDecisionGrant);
XCTAssertEqual(FWFNativeWKPermissionDecisionFromData(
[FWFWKPermissionDecisionData makeWithValue:FWFWKPermissionDecisionPrompt]),
WKPermissionDecisionPrompt);
}
- (void)testFWFWKMediaCaptureTypeDataFromWKMediaCaptureType API_AVAILABLE(ios(15.0)) {
XCTAssertEqual(
FWFWKMediaCaptureTypeDataFromNativeWKMediaCaptureType(WKMediaCaptureTypeCamera).value,
FWFWKMediaCaptureTypeCamera);
XCTAssertEqual(
FWFWKMediaCaptureTypeDataFromNativeWKMediaCaptureType(WKMediaCaptureTypeMicrophone).value,
FWFWKMediaCaptureTypeMicrophone);
XCTAssertEqual(
FWFWKMediaCaptureTypeDataFromNativeWKMediaCaptureType(WKMediaCaptureTypeCameraAndMicrophone)
.value,
FWFWKMediaCaptureTypeCameraAndMicrophone);
}
- (void)testNSKeyValueChangeKeyConversionReturnsUnknownIfUnrecognized {
XCTAssertEqual(
FWFNSKeyValueChangeKeyEnumDataFromNativeNSKeyValueChangeKey(@"SomeUnknownValue").value,
FWFNSKeyValueChangeKeyEnumUnknown);
}
- (void)testWKNavigationTypeConversionReturnsUnknownIfUnrecognized {
XCTAssertEqual(FWFWKNavigationTypeFromNativeWKNavigationType(-15), FWFWKNavigationTypeUnknown);
}
- (void)testFWFWKNavigationResponseDataFromNativeNavigationResponse {
WKNavigationResponse *mockResponse = OCMClassMock([WKNavigationResponse class]);
OCMStub([mockResponse isForMainFrame]).andReturn(YES);
NSHTTPURLResponse *mockURLResponse = OCMClassMock([NSHTTPURLResponse class]);
OCMStub([mockURLResponse statusCode]).andReturn(1);
OCMStub([mockResponse response]).andReturn(mockURLResponse);
FWFWKNavigationResponseData *data =
FWFWKNavigationResponseDataFromNativeNavigationResponse(mockResponse);
XCTAssertEqual(data.forMainFrame, YES);
}
- (void)testFWFNSHttpUrlResponseDataFromNativeNSURLResponse {
NSHTTPURLResponse *mockResponse = OCMClassMock([NSHTTPURLResponse class]);
OCMStub([mockResponse statusCode]).andReturn(1);
FWFNSHttpUrlResponseData *data = FWFNSHttpUrlResponseDataFromNativeNSURLResponse(mockResponse);
XCTAssertEqual(data.statusCode, 1);
}
- (void)testFWFNativeWKNavigationResponsePolicyFromEnum {
XCTAssertEqual(
FWFNativeWKNavigationResponsePolicyFromEnum(FWFWKNavigationResponsePolicyEnumAllow),
WKNavigationResponsePolicyAllow);
XCTAssertEqual(
FWFNativeWKNavigationResponsePolicyFromEnum(FWFWKNavigationResponsePolicyEnumCancel),
WKNavigationResponsePolicyCancel);
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFDataConvertersTests.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFDataConvertersTests.m",
"repo_id": "packages",
"token_count": 3462
} | 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 "FLTWebViewFlutterPlugin.h"
#import "FWFGeneratedWebKitApis.h"
#import "FWFHTTPCookieStoreHostApi.h"
#import "FWFInstanceManager.h"
#import "FWFNavigationDelegateHostApi.h"
#import "FWFObjectHostApi.h"
#import "FWFPreferencesHostApi.h"
#import "FWFScriptMessageHandlerHostApi.h"
#import "FWFScrollViewDelegateHostApi.h"
#import "FWFScrollViewHostApi.h"
#import "FWFUIDelegateHostApi.h"
#import "FWFUIViewHostApi.h"
#import "FWFURLCredentialHostApi.h"
#import "FWFURLHostApi.h"
#import "FWFUserContentControllerHostApi.h"
#import "FWFWebViewConfigurationHostApi.h"
#import "FWFWebViewHostApi.h"
#import "FWFWebsiteDataStoreHostApi.h"
@interface FWFWebViewFactory : NSObject <FlutterPlatformViewFactory>
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
- (instancetype)initWithManager:(FWFInstanceManager *)manager;
@end
@implementation FWFWebViewFactory
- (instancetype)initWithManager:(FWFInstanceManager *)manager {
self = [self init];
if (self) {
_instanceManager = manager;
}
return self;
}
- (NSObject<FlutterMessageCodec> *)createArgsCodec {
return [FlutterStandardMessageCodec sharedInstance];
}
- (NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args {
NSNumber *identifier = (NSNumber *)args;
FWFWebView *webView =
(FWFWebView *)[self.instanceManager instanceForIdentifier:identifier.longValue];
webView.frame = frame;
return webView;
}
@end
@implementation FLTWebViewFlutterPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FWFInstanceManager *instanceManager =
[[FWFInstanceManager alloc] initWithDeallocCallback:^(long identifier) {
FWFObjectFlutterApiImpl *objectApi = [[FWFObjectFlutterApiImpl alloc]
initWithBinaryMessenger:registrar.messenger
instanceManager:[[FWFInstanceManager alloc] init]];
dispatch_async(dispatch_get_main_queue(), ^{
[objectApi disposeObjectWithIdentifier:identifier
completion:^(FlutterError *error) {
NSAssert(!error, @"%@", error);
}];
});
}];
SetUpFWFWKHttpCookieStoreHostApi(
registrar.messenger,
[[FWFHTTPCookieStoreHostApiImpl alloc] initWithInstanceManager:instanceManager]);
SetUpFWFWKNavigationDelegateHostApi(
registrar.messenger,
[[FWFNavigationDelegateHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
instanceManager:instanceManager]);
SetUpFWFNSObjectHostApi(registrar.messenger,
[[FWFObjectHostApiImpl alloc] initWithInstanceManager:instanceManager]);
SetUpFWFWKPreferencesHostApi(registrar.messenger, [[FWFPreferencesHostApiImpl alloc]
initWithInstanceManager:instanceManager]);
SetUpFWFWKScriptMessageHandlerHostApi(
registrar.messenger,
[[FWFScriptMessageHandlerHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
instanceManager:instanceManager]);
SetUpFWFUIScrollViewHostApi(registrar.messenger, [[FWFScrollViewHostApiImpl alloc]
initWithInstanceManager:instanceManager]);
SetUpFWFWKUIDelegateHostApi(registrar.messenger, [[FWFUIDelegateHostApiImpl alloc]
initWithBinaryMessenger:registrar.messenger
instanceManager:instanceManager]);
SetUpFWFUIViewHostApi(registrar.messenger,
[[FWFUIViewHostApiImpl alloc] initWithInstanceManager:instanceManager]);
SetUpFWFWKUserContentControllerHostApi(
registrar.messenger,
[[FWFUserContentControllerHostApiImpl alloc] initWithInstanceManager:instanceManager]);
SetUpFWFWKWebsiteDataStoreHostApi(
registrar.messenger,
[[FWFWebsiteDataStoreHostApiImpl alloc] initWithInstanceManager:instanceManager]);
SetUpFWFWKWebViewConfigurationHostApi(
registrar.messenger,
[[FWFWebViewConfigurationHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
instanceManager:instanceManager]);
SetUpFWFWKWebViewHostApi(registrar.messenger, [[FWFWebViewHostApiImpl alloc]
initWithBinaryMessenger:registrar.messenger
instanceManager:instanceManager]);
SetUpFWFNSUrlHostApi(registrar.messenger,
[[FWFURLHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
instanceManager:instanceManager]);
SetUpFWFUIScrollViewDelegateHostApi(
registrar.messenger,
[[FWFScrollViewDelegateHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
instanceManager:instanceManager]);
SetUpFWFNSUrlCredentialHostApi(
registrar.messenger,
[[FWFURLCredentialHostApiImpl alloc] initWithBinaryMessenger:registrar.messenger
instanceManager:instanceManager]);
FWFWebViewFactory *webviewFactory = [[FWFWebViewFactory alloc] initWithManager:instanceManager];
[registrar registerViewFactory:webviewFactory withId:@"plugins.flutter.io/webview"];
// InstanceManager is published so that a strong reference is maintained.
[registrar publish:instanceManager];
}
- (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
[registrar publish:[NSNull null]];
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FLTWebViewFlutterPlugin.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FLTWebViewFlutterPlugin.m",
"repo_id": "packages",
"token_count": 2692
} | 1,072 |
// 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
/// Flutter API implementation for `NSURLProtectionSpace`.
///
/// 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 FWFURLProtectionSpaceFlutterApiImpl : NSObject
/// The Flutter API used to send messages back to Dart.
@property FWFNSUrlProtectionSpaceFlutterApi *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)createWithInstance:(NSURLProtectionSpace *)instance
host:(nullable NSString *)host
realm:(nullable NSString *)realm
authenticationMethod:(nullable NSString *)authenticationMethod
completion:(void (^)(FlutterError *_Nullable))completion;
@end
NS_ASSUME_NONNULL_END
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLProtectionSpaceHostApi.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLProtectionSpaceHostApi.h",
"repo_id": "packages",
"token_count": 428
} | 1,073 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/xdg_directories/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/xdg_directories/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 1,074 |
This folder contains configuration files that are passed to commands in place
of package lists. They are primarily used by CI to opt specific packages out of
tests, but can also useful when running multi-package tests locally.
**Any entry added to a file in this directory should include a comment**.
Skipping tests or checks for packages is usually not something we want to do,
so the comment should either include an issue link to the issue tracking
removing it or (much more rarely) explaining why it is a permanent exclusion.
Expected format:
```
# Reason for exclusion
- name_of_package
```
If there are no exclusions there should be an file with []. | packages/script/configs/README.md/0 | {
"file_path": "packages/script/configs/README.md",
"repo_id": "packages",
"token_count": 152
} | 1,075 |
# Packages that have not yet adopted code-excerpt.
#
# This only exists to allow incrementally adopting the new requirement.
# Packages shoud never be added to this list.
# TODO(stuartmorgan): Remove everything from this list. See
# https://github.com/flutter/flutter/issues/102679
- espresso
- go_router_builder
- image_picker_for_web
- in_app_purchase/in_app_purchase
- palette_generator
- pointer_interceptor
- quick_actions/quick_actions
| packages/script/configs/temp_exclude_excerpt.yaml/0 | {
"file_path": "packages/script/configs/temp_exclude_excerpt.yaml",
"repo_id": "packages",
"token_count": 137
} | 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 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import 'git_version_finder.dart';
import 'repository_package.dart';
/// The state of a package on disk relative to git state.
@immutable
class PackageChangeState {
/// Creates a new immutable state instance.
const PackageChangeState({
required this.hasChanges,
required this.hasChangelogChange,
required this.needsChangelogChange,
required this.needsVersionChange,
});
/// True if there are any changes to files in the package.
final bool hasChanges;
/// True if the package's CHANGELOG.md has been changed.
final bool hasChangelogChange;
/// True if any changes in the package require a version change according
/// to repository policy.
final bool needsVersionChange;
/// True if any changes in the package require a CHANGELOG change according
/// to repository policy.
final bool needsChangelogChange;
}
/// Checks [package] against [changedPaths] to determine what changes it has
/// and how those changes relate to repository policy about CHANGELOG and
/// version updates.
///
/// [changedPaths] should be a list of POSIX-style paths from a common root,
/// and [relativePackagePath] should be the path to [package] from that same
/// root. Commonly these will come from `gitVersionFinder.getChangedFiles()`
/// and `getRelativePosixPath(package.directory, gitDir.path)` respectively;
/// they are arguments mainly to allow for caching the changed paths for an
/// entire command run.
///
/// If [git] is provided, [changedPaths] must be repository-relative
/// paths, and change type detection can use file diffs in addition to paths.
Future<PackageChangeState> checkPackageChangeState(
RepositoryPackage package, {
required List<String> changedPaths,
required String relativePackagePath,
GitVersionFinder? git,
}) async {
final String packagePrefix = relativePackagePath.endsWith('/')
? relativePackagePath
: '$relativePackagePath/';
bool hasChanges = false;
bool hasChangelogChange = false;
bool needsVersionChange = false;
bool needsChangelogChange = false;
for (final String path in changedPaths) {
// Only consider files within the package.
if (!path.startsWith(packagePrefix)) {
continue;
}
final String packageRelativePath = path.substring(packagePrefix.length);
hasChanges = true;
final List<String> components = p.posix.split(packageRelativePath);
if (components.isEmpty) {
continue;
}
if (components.first == 'CHANGELOG.md') {
hasChangelogChange = true;
continue;
}
if (!needsVersionChange) {
// Developer-only changes don't need version changes or changelog changes.
if (await _isDevChange(components, git: git, repoPath: path)) {
continue;
}
final bool isUnpublishedExampleChange =
_isUnpublishedExampleChange(components, package);
// Since examples of federated plugin implementations are only intended
// for testing purposes, any unpublished example change in one of them is
// effectively a developer-only change.
if (package.isFederated &&
package.isPlatformImplementation &&
isUnpublishedExampleChange) {
continue;
}
// Anything that is not developer-only might benefit from changelog
// changes. This errs on the side of flagging, so that someone checks to
// see if it should be mentioned there or not.
needsChangelogChange = true;
// Most changes that aren't developer-only need version changes.
if (
// One of a few special files example will be shown on pub.dev, but
// for anything else in the example, publishing isn't necessary (even
// if it is relevant to mention in the CHANGELOG for the future).
!isUnpublishedExampleChange) {
needsVersionChange = true;
}
}
}
return PackageChangeState(
hasChanges: hasChanges,
hasChangelogChange: hasChangelogChange,
needsChangelogChange: needsChangelogChange,
needsVersionChange: needsVersionChange);
}
bool _isTestChange(List<String> pathComponents) {
return pathComponents.contains('test') ||
pathComponents.contains('integration_test') ||
pathComponents.contains('androidTest') ||
pathComponents.contains('RunnerTests') ||
pathComponents.contains('RunnerUITests') ||
pathComponents.last == 'dart_test.yaml' ||
// Pigeon's custom platform tests.
pathComponents.first == 'platform_tests';
}
// True if the given file is an example file other than the one that will be
// published according to https://dart.dev/tools/pub/package-layout#examples.
//
// This is not exhastive; it currently only handles variations we actually have
// in our repositories.
bool _isUnpublishedExampleChange(
List<String> pathComponents, RepositoryPackage package) {
if (pathComponents.first != 'example') {
return false;
}
final List<String> exampleComponents = pathComponents.sublist(1);
if (exampleComponents.isEmpty) {
return false;
}
final Directory exampleDirectory =
package.directory.childDirectory('example');
// Check for example.md/EXAMPLE.md first, as that has priority. If it's
// present, any other example file is unpublished.
final bool hasExampleMd =
exampleDirectory.childFile('example.md').existsSync() ||
exampleDirectory.childFile('EXAMPLE.md').existsSync();
if (hasExampleMd) {
return !(exampleComponents.length == 1 &&
exampleComponents.first.toLowerCase() == 'example.md');
}
// Most packages have an example/lib/main.dart (or occasionally
// example/main.dart), so check for that. The other naming variations aren't
// currently used.
const String mainName = 'main.dart';
final bool hasExampleCode =
exampleDirectory.childDirectory('lib').childFile(mainName).existsSync() ||
exampleDirectory.childFile(mainName).existsSync();
if (hasExampleCode) {
// If there is an example main, only that example file is published.
return !((exampleComponents.length == 1 &&
exampleComponents.first == mainName) ||
(exampleComponents.length == 2 &&
exampleComponents.first == 'lib' &&
exampleComponents[1] == mainName));
}
// If there's no example code either, the example README.md, if any, is the
// file that will be published.
return exampleComponents.first.toLowerCase() != 'readme.md';
}
// True if the change is only relevant to people working on the package.
Future<bool> _isDevChange(List<String> pathComponents,
{GitVersionFinder? git, String? repoPath}) async {
return _isTestChange(pathComponents) ||
// The top-level "tool" directory is for non-client-facing utility
// code, such as test scripts.
pathComponents.first == 'tool' ||
// The top-level "pigeons" directory is the repo convention for storing
// pigeon input files.
pathComponents.first == 'pigeons' ||
// Entry point for the 'custom-test' command, which is only for CI and
// local testing.
pathComponents.first == 'run_tests.sh' ||
// CONTRIBUTING.md is dev-facing.
pathComponents.last == 'CONTRIBUTING.md' ||
// Lints don't affect clients.
pathComponents.contains('analysis_options.yaml') ||
pathComponents.contains('lint-baseline.xml') ||
// Example build files are very unlikely to be interesting to clients.
_isExampleBuildFile(pathComponents) ||
// Test-only gradle depenedencies don't affect clients.
await _isGradleTestDependencyChange(pathComponents,
git: git, repoPath: repoPath) ||
// Implementation comments don't affect clients.
// This check is currently Dart-only since that's the only place
// this has come up in practice; it could be generalized to other
// languages if needed.
await _isDartImplementationCommentChange(pathComponents,
git: git, repoPath: repoPath);
}
bool _isExampleBuildFile(List<String> pathComponents) {
if (!pathComponents.contains('example')) {
return false;
}
return pathComponents.contains('gradle-wrapper.properties') ||
pathComponents.contains('gradle.properties') ||
pathComponents.contains('build.gradle') ||
pathComponents.contains('Runner.xcodeproj') ||
pathComponents.contains('Runner.xcscheme') ||
pathComponents.contains('Runner.xcworkspace') ||
pathComponents.contains('Podfile') ||
pathComponents.contains('CMakeLists.txt') ||
pathComponents.contains('.pluginToolsConfig.yaml') ||
pathComponents.contains('pubspec.yaml');
}
Future<bool> _isGradleTestDependencyChange(List<String> pathComponents,
{GitVersionFinder? git, String? repoPath}) async {
if (git == null) {
return false;
}
if (pathComponents.last != 'build.gradle') {
return false;
}
final List<String> diff = await git.getDiffContents(targetPath: repoPath);
final RegExp changeLine = RegExp(r'^[+-] ');
final RegExp testDependencyLine =
RegExp(r'^[+-]\s*(?:androidT|t)estImplementation\s');
bool foundTestDependencyChange = false;
for (final String line in diff) {
if (!changeLine.hasMatch(line) ||
line.startsWith('--- ') ||
line.startsWith('+++ ')) {
continue;
}
if (!testDependencyLine.hasMatch(line)) {
return false;
}
foundTestDependencyChange = true;
}
// Only return true if a test dependency change was found, as a failsafe
// against having the wrong (e.g., incorrectly empty) diff output.
return foundTestDependencyChange;
}
// Returns true if the given file is a Dart file whose only changes are
// implementation comments (i.e., not doc comments).
Future<bool> _isDartImplementationCommentChange(List<String> pathComponents,
{GitVersionFinder? git, String? repoPath}) async {
if (git == null) {
return false;
}
if (!pathComponents.last.endsWith('.dart')) {
return false;
}
final List<String> diff = await git.getDiffContents(targetPath: repoPath);
final RegExp changeLine = RegExp(r'^[+-] ');
final RegExp whitespaceLine = RegExp(r'^[+-]\s*$');
final RegExp nonDocCommentLine = RegExp(r'^[+-]\s*//\s');
bool foundIgnoredChange = false;
for (final String line in diff) {
if (!changeLine.hasMatch(line) ||
line.startsWith('--- ') ||
line.startsWith('+++ ')) {
continue;
}
if (!nonDocCommentLine.hasMatch(line) && !whitespaceLine.hasMatch(line)) {
return false;
}
foundIgnoredChange = true;
}
// Only return true if an ignored change was found, as a failsafe against
// having the wrong (e.g., incorrectly empty) diff output.
return foundIgnoredChange;
}
| packages/script/tool/lib/src/common/package_state_utils.dart/0 | {
"file_path": "packages/script/tool/lib/src/common/package_state_utils.dart",
"repo_id": "packages",
"token_count": 3657
} | 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:convert';
import 'dart:io' as io;
import 'package:file/file.dart';
import 'package:http/http.dart' as http;
import 'package:meta/meta.dart';
import 'common/core.dart';
import 'common/output_utils.dart';
import 'common/package_command.dart';
/// In theory this should be 8191, but in practice that was still resulting in
/// "The input line is too long" errors. This was chosen as a value that worked
/// in practice via trial and error, but may need to be adjusted based on
/// further experience.
@visibleForTesting
const int windowsCommandLineMax = 8000;
/// This value is picked somewhat arbitrarily based on checking `ARG_MAX` on a
/// macOS and Linux machine. If anyone encounters a lower limit in pratice, it
/// can be lowered accordingly.
@visibleForTesting
const int nonWindowsCommandLineMax = 1000000;
const int _exitClangFormatFailed = 3;
const int _exitFlutterFormatFailed = 4;
const int _exitJavaFormatFailed = 5;
const int _exitGitFailed = 6;
const int _exitDependencyMissing = 7;
const int _exitSwiftFormatFailed = 8;
const int _exitKotlinFormatFailed = 9;
final Uri _javaFormatterUrl = Uri.https('github.com',
'/google/google-java-format/releases/download/google-java-format-1.3/google-java-format-1.3-all-deps.jar');
final Uri _kotlinFormatterUrl = Uri.https('maven.org',
'/maven2/com/facebook/ktfmt/0.46/ktfmt-0.46-jar-with-dependencies.jar');
/// A command to format all package code.
class FormatCommand extends PackageCommand {
/// Creates an instance of the format command.
FormatCommand(
super.packagesDir, {
super.processRunner,
super.platform,
}) {
argParser.addFlag('fail-on-change', hide: true);
argParser.addFlag(_dartArg, help: 'Format Dart files', defaultsTo: true);
argParser.addFlag(_clangFormatArg,
help: 'Format with "clang-format"', defaultsTo: true);
argParser.addFlag(_kotlinArg,
help: 'Format Kotlin files', defaultsTo: true);
argParser.addFlag(_javaArg, help: 'Format Java files', defaultsTo: true);
argParser.addFlag(_swiftArg,
help: 'Format and lint Swift files', defaultsTo: true);
argParser.addOption(_clangFormatPathArg,
defaultsTo: 'clang-format', help: 'Path to "clang-format" executable.');
argParser.addOption(_javaPathArg,
defaultsTo: 'java', help: 'Path to "java" executable.');
argParser.addOption(_swiftFormatPathArg,
defaultsTo: 'swift-format', help: 'Path to "swift-format" executable.');
}
static const String _dartArg = 'dart';
static const String _clangFormatArg = 'clang-format';
static const String _kotlinArg = 'kotlin';
static const String _javaArg = 'java';
static const String _swiftArg = 'swift';
static const String _clangFormatPathArg = 'clang-format-path';
static const String _javaPathArg = 'java-path';
static const String _swiftFormatPathArg = 'swift-format-path';
@override
final String name = 'format';
@override
final String description =
'Formats the code of all packages (C++, Dart, Java, Kotlin, Objective-C, '
'and optionally Swift).\n\n'
'This command requires "git", "flutter", "java", and "clang-format" v5 '
'to be in your path.';
@override
Future<void> run() async {
final String javaFormatterPath = await _getJavaFormatterPath();
final String kotlinFormatterPath = await _getKotlinFormatterPath();
// This class is not based on PackageLoopingCommand because running the
// formatters separately for each package is an order of magnitude slower,
// due to the startup overhead of the formatters.
final Iterable<String> files =
await _getFilteredFilePaths(getFiles(), relativeTo: packagesDir);
if (getBoolArg(_dartArg)) {
await _formatDart(files);
}
if (getBoolArg(_javaArg)) {
await _formatJava(files, javaFormatterPath);
}
if (getBoolArg(_kotlinArg)) {
await _formatKotlin(files, kotlinFormatterPath);
}
if (getBoolArg(_clangFormatArg)) {
await _formatCppAndObjectiveC(files);
}
if (getBoolArg(_swiftArg)) {
await _formatAndLintSwift(files);
}
if (getBoolArg('fail-on-change')) {
final bool modified = await _didModifyAnything();
if (modified) {
throw ToolExit(exitCommandFoundErrors);
}
}
}
Future<bool> _didModifyAnything() async {
final io.ProcessResult modifiedFiles = await processRunner.run(
'git',
<String>['ls-files', '--modified'],
workingDir: packagesDir,
logOnError: true,
);
if (modifiedFiles.exitCode != 0) {
printError('Unable to determine changed files.');
throw ToolExit(_exitGitFailed);
}
print('\n\n');
final String stdout = modifiedFiles.stdout as String;
if (stdout.isEmpty) {
print('All files formatted correctly.');
return false;
}
print('These files are not formatted correctly (see diff below):');
LineSplitter.split(stdout).map((String line) => ' $line').forEach(print);
print('\nTo fix run the repository tooling `format` command: '
'https://github.com/flutter/packages/blob/main/script/tool/README.md#format-code\n'
'or copy-paste this command into your terminal:');
final io.ProcessResult diff = await processRunner.run(
'git',
<String>['diff'],
workingDir: packagesDir,
logOnError: true,
);
if (diff.exitCode != 0) {
printError('Unable to determine diff.');
throw ToolExit(_exitGitFailed);
}
print('patch -p1 <<DONE');
print(diff.stdout);
print('DONE');
return true;
}
Future<void> _formatCppAndObjectiveC(Iterable<String> files) async {
final Iterable<String> clangFiles = _getPathsWithExtensions(
files, <String>{'.h', '.m', '.mm', '.cc', '.cpp'});
if (clangFiles.isNotEmpty) {
final String clangFormat = await _findValidClangFormat();
print('Formatting .cc, .cpp, .h, .m, and .mm files...');
final int exitCode = await _runBatched(
clangFormat, <String>['-i', '--style=file'],
files: clangFiles);
if (exitCode != 0) {
printError(
'Failed to format C, C++, and Objective-C files: exit code $exitCode.');
throw ToolExit(_exitClangFormatFailed);
}
}
}
Future<void> _formatAndLintSwift(Iterable<String> files) async {
final Iterable<String> swiftFiles =
_getPathsWithExtensions(files, <String>{'.swift'});
if (swiftFiles.isNotEmpty) {
final String swiftFormat = await _findValidSwiftFormat();
print('Formatting .swift files...');
final int formatExitCode =
await _runBatched(swiftFormat, <String>['-i'], files: swiftFiles);
if (formatExitCode != 0) {
printError('Failed to format Swift files: exit code $formatExitCode.');
throw ToolExit(_exitSwiftFormatFailed);
}
print('Linting .swift files...');
final int lintExitCode = await _runBatched(
swiftFormat,
<String>[
'lint',
'--parallel',
'--strict',
],
files: swiftFiles);
if (lintExitCode != 0) {
printError('Failed to lint Swift files: exit code $lintExitCode.');
throw ToolExit(_exitSwiftFormatFailed);
}
}
}
Future<String> _findValidClangFormat() async {
final String clangFormat = getStringArg(_clangFormatPathArg);
if (await _hasDependency(clangFormat)) {
return clangFormat;
}
// There is a known issue where "chromium/depot_tools/clang-format"
// fails with "Problem while looking for clang-format in Chromium source tree".
// Loop through all "clang-format"s in PATH until a working one is found,
// for example "/usr/local/bin/clang-format" or a "brew" installed version.
for (final String clangFormatPath in await _whichAll('clang-format')) {
if (await _hasDependency(clangFormatPath)) {
return clangFormatPath;
}
}
printError('Unable to run "clang-format". Make sure that it is in your '
'path, or provide a full path with --$_clangFormatPathArg.');
throw ToolExit(_exitDependencyMissing);
}
Future<String> _findValidSwiftFormat() async {
final String swiftFormat = getStringArg(_swiftFormatPathArg);
if (await _hasDependency(swiftFormat)) {
return swiftFormat;
}
printError('Unable to run "swift-format". Make sure that it is in your '
'path, or provide a full path with --$_swiftFormatPathArg.');
throw ToolExit(_exitDependencyMissing);
}
Future<void> _formatJava(Iterable<String> files, String formatterPath) async {
final Iterable<String> javaFiles =
_getPathsWithExtensions(files, <String>{'.java'});
if (javaFiles.isNotEmpty) {
final String java = getStringArg(_javaPathArg);
if (!await _hasDependency(java)) {
printError(
'Unable to run "java". Make sure that it is in your path, or '
'provide a full path with --$_javaPathArg.');
throw ToolExit(_exitDependencyMissing);
}
print('Formatting .java files...');
final int exitCode = await _runBatched(
java, <String>['-jar', formatterPath, '--replace'],
files: javaFiles);
if (exitCode != 0) {
printError('Failed to format Java files: exit code $exitCode.');
throw ToolExit(_exitJavaFormatFailed);
}
}
}
Future<void> _formatKotlin(
Iterable<String> files, String formatterPath) async {
final Iterable<String> kotlinFiles =
_getPathsWithExtensions(files, <String>{'.kt'});
if (kotlinFiles.isNotEmpty) {
final String java = getStringArg(_javaPathArg);
if (!await _hasDependency(java)) {
printError(
'Unable to run "java". Make sure that it is in your path, or '
'provide a full path with --$_javaPathArg.');
throw ToolExit(_exitDependencyMissing);
}
print('Formatting .kt files...');
final int exitCode = await _runBatched(
java, <String>['-jar', formatterPath],
files: kotlinFiles);
if (exitCode != 0) {
printError('Failed to format Kotlin files: exit code $exitCode.');
throw ToolExit(_exitKotlinFormatFailed);
}
}
}
Future<void> _formatDart(Iterable<String> files) async {
final Iterable<String> dartFiles =
_getPathsWithExtensions(files, <String>{'.dart'});
if (dartFiles.isNotEmpty) {
print('Formatting .dart files...');
final int exitCode =
await _runBatched('dart', <String>['format'], files: dartFiles);
if (exitCode != 0) {
printError('Failed to format Dart files: exit code $exitCode.');
throw ToolExit(_exitFlutterFormatFailed);
}
}
}
/// Given a stream of [files], returns the paths of any that are not in known
/// locations to ignore, relative to [relativeTo].
Future<Iterable<String>> _getFilteredFilePaths(
Stream<File> files, {
required Directory relativeTo,
}) async {
// Returns a pattern to check for [directories] as a subset of a file path.
RegExp pathFragmentForDirectories(List<String> directories) {
String s = path.separator;
// Escape the separator for use in the regex.
if (s == r'\') {
s = r'\\';
}
return RegExp('(?:^|$s)${path.joinAll(directories)}$s');
}
final String fromPath = relativeTo.path;
// Dart files are allowed to have a pragma to disable auto-formatting. This
// was added because Hixie hurts when dealing with what dartfmt does to
// artisanally-formatted Dart, while Stuart gets really frustrated when
// dealing with PRs from newer contributors who don't know how to make Dart
// readable. After much discussion, it was decided that files in the plugins
// and packages repos that really benefit from hand-formatting (e.g. files
// with large blobs of hex literals) could be opted-out of the requirement
// that they be autoformatted, so long as the code's owner was willing to
// bear the cost of this during code reviews.
// In the event that code ownership moves to someone who does not hold the
// same views as the original owner, the pragma can be removed and the file
// auto-formatted.
const String handFormattedExtension = '.dart';
const String handFormattedPragma = '// This file is hand-formatted.';
return files
.where((File file) {
// See comment above near [handFormattedPragma].
return path.extension(file.path) != handFormattedExtension ||
!file.readAsLinesSync().contains(handFormattedPragma);
})
.map((File file) => path.relative(file.path, from: fromPath))
.where((String path) =>
// Ignore files in build/ directories (e.g., headers of frameworks)
// to avoid useless extra work in local repositories.
!path.contains(
pathFragmentForDirectories(<String>['example', 'build'])) &&
// Ignore files in Pods, which are not part of the repository.
!path.contains(pathFragmentForDirectories(<String>['Pods'])) &&
// See https://github.com/flutter/flutter/issues/144039
!path.endsWith('GeneratedPluginRegistrant.swift') &&
// Ignore .dart_tool/, which can have various intermediate files.
!path.contains(pathFragmentForDirectories(<String>['.dart_tool'])))
.toList();
}
Iterable<String> _getPathsWithExtensions(
Iterable<String> files, Set<String> extensions) {
return files.where(
(String filePath) => extensions.contains(path.extension(filePath)));
}
Future<String> _getJavaFormatterPath() async {
final String javaFormatterPath = path.join(
path.dirname(path.fromUri(platform.script)),
'google-java-format-1.3-all-deps.jar');
final File javaFormatterFile =
packagesDir.fileSystem.file(javaFormatterPath);
if (!javaFormatterFile.existsSync()) {
print('Downloading Google Java Format...');
final http.Response response = await http.get(_javaFormatterUrl);
javaFormatterFile.writeAsBytesSync(response.bodyBytes);
}
return javaFormatterPath;
}
Future<String> _getKotlinFormatterPath() async {
final String kotlinFormatterPath = path.join(
path.dirname(path.fromUri(platform.script)),
'ktfmt-0.46-jar-with-dependencies.jar');
final File kotlinFormatterFile =
packagesDir.fileSystem.file(kotlinFormatterPath);
if (!kotlinFormatterFile.existsSync()) {
print('Downloading ktfmt...');
final http.Response response = await http.get(_kotlinFormatterUrl);
kotlinFormatterFile.writeAsBytesSync(response.bodyBytes);
}
return kotlinFormatterPath;
}
/// Returns true if [command] can be run successfully.
Future<bool> _hasDependency(String command) async {
// Some versions of Java accept both -version and --version, but some only
// accept -version.
final String versionFlag = command == 'java' ? '-version' : '--version';
try {
final io.ProcessResult result =
await processRunner.run(command, <String>[versionFlag]);
if (result.exitCode != 0) {
return false;
}
} on io.ProcessException {
// Thrown when the binary is missing entirely.
return false;
}
return true;
}
/// Returns all instances of [command] executable found on user path.
Future<List<String>> _whichAll(String command) async {
try {
final io.ProcessResult result =
await processRunner.run('which', <String>['-a', command]);
if (result.exitCode != 0) {
return <String>[];
}
final String stdout = (result.stdout as String).trim();
if (stdout.isEmpty) {
return <String>[];
}
return LineSplitter.split(stdout).toList();
} on io.ProcessException {
return <String>[];
}
}
/// Runs [command] on [arguments] on all of the files in [files], batched as
/// necessary to avoid OS command-line length limits.
///
/// Returns the exit code of the first failure, which stops the run, or 0
/// on success.
Future<int> _runBatched(
String command,
List<String> arguments, {
required Iterable<String> files,
}) async {
final int commandLineMax =
platform.isWindows ? windowsCommandLineMax : nonWindowsCommandLineMax;
// Compute the max length of the file argument portion of a batch.
// Add one to each argument's length for the space before it.
final int argumentTotalLength =
arguments.fold(0, (int sum, String arg) => sum + arg.length + 1);
final int batchMaxTotalLength =
commandLineMax - command.length - argumentTotalLength;
// Run the command in batches.
final List<List<String>> batches =
_partitionFileList(files, maxStringLength: batchMaxTotalLength);
for (final List<String> batch in batches) {
batch.sort(); // For ease of testing.
final int exitCode = await processRunner.runAndStream(
command, <String>[...arguments, ...batch],
workingDir: packagesDir);
if (exitCode != 0) {
return exitCode;
}
}
return 0;
}
/// Partitions [files] into batches whose max string length as parameters to
/// a command (including the spaces between them, and between the list and
/// the command itself) is no longer than [maxStringLength].
List<List<String>> _partitionFileList(Iterable<String> files,
{required int maxStringLength}) {
final List<List<String>> batches = <List<String>>[<String>[]];
int currentBatchTotalLength = 0;
for (final String file in files) {
final int length = file.length + 1 /* for the space */;
if (currentBatchTotalLength + length > maxStringLength) {
// Start a new batch.
batches.add(<String>[]);
currentBatchTotalLength = 0;
}
batches.last.add(file);
currentBatchTotalLength += length;
}
return batches;
}
}
| packages/script/tool/lib/src/format_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/format_command.dart",
"repo_id": "packages",
"token_count": 6754
} | 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:file/file.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/repository_package.dart';
class _UpdateResult {
const _UpdateResult(this.changed, this.snippetCount, this.errors);
final bool changed;
final int snippetCount;
final List<String> errors;
}
enum _ExcerptParseMode { normal, pragma, injecting }
/// A command to update .md code excerpts from code files.
class UpdateExcerptsCommand extends PackageLoopingCommand {
/// Creates a excerpt updater command instance.
UpdateExcerptsCommand(
super.packagesDir, {
super.processRunner,
super.platform,
super.gitDir,
}) {
argParser.addFlag(
_failOnChangeFlag,
help: 'Fail if the command does anything. '
'(Used in CI to ensure excerpts are up to date.)',
);
}
static const String _failOnChangeFlag = 'fail-on-change';
@override
final String name = 'update-excerpts';
@override
final String description = 'Updates code excerpts in .md files, based '
'on code from code files, via <?code-excerpt?> pragmas.';
@override
bool get hasLongOutput => false;
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
final List<File> changedFiles = <File>[];
final List<String> errors = <String>[];
final List<File> markdownFiles = package.directory
.listSync(recursive: true)
.where((FileSystemEntity entity) {
return entity is File &&
entity.basename != 'CHANGELOG.md' &&
entity.basename.toLowerCase().endsWith('.md');
})
.cast<File>()
.toList();
for (final File file in markdownFiles) {
final _UpdateResult result = _updateExcerptsIn(file);
if (result.snippetCount > 0) {
final String displayPath =
getRelativePosixPath(file, from: package.directory);
print('${indentation}Checked ${result.snippetCount} snippet(s) in '
'$displayPath.');
}
if (result.changed) {
changedFiles.add(file);
}
if (result.errors.isNotEmpty) {
errors.addAll(result.errors);
}
}
if (errors.isNotEmpty) {
printError('${indentation}Injecting excerpts failed:');
printError(errors.join('\n$indentation'));
return PackageResult.fail();
}
if (getBoolArg(_failOnChangeFlag) && changedFiles.isNotEmpty) {
printError(
'${indentation}The following files have out of date excerpts:\n'
'$indentation ${changedFiles.map((File file) => file.path).join("\n$indentation ")}\n'
'\n'
'${indentation}If you edited code in a .md file directly, you should '
'instead edit the files that contain the sources of the excerpts.\n'
'${indentation}If you did edit those source files, run the repository '
'tooling\'s "$name" command on this package, and update your PR with '
'the resulting changes.\n'
'\n'
'${indentation}For more information, see '
'https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#readme-code',
);
return PackageResult.fail();
}
return PackageResult.success();
}
static const String _pragma = '<?code-excerpt';
static final RegExp _basePattern =
RegExp(r'^ *<\?code-excerpt path-base="([^"]+)"\?>$');
static final RegExp _injectPattern = RegExp(
r'^ *<\?code-excerpt "(?<path>[^ ]+) \((?<section>[^)]+)\)"(?: plaster="(?<plaster>[^"]*)")?\?>$',
);
_UpdateResult _updateExcerptsIn(File file) {
bool detectedChange = false;
int snippetCount = 0;
final List<String> errors = <String>[];
Directory pathBase = file.parent;
final StringBuffer output = StringBuffer();
final StringBuffer existingBlock = StringBuffer();
String? language;
String? excerpt;
_ExcerptParseMode mode = _ExcerptParseMode.normal;
int lineNumber = 0;
for (final String line in file.readAsLinesSync()) {
lineNumber += 1;
switch (mode) {
case _ExcerptParseMode.normal:
if (line.contains(_pragma)) {
RegExpMatch? match = _basePattern.firstMatch(line);
if (match != null) {
pathBase =
file.parent.childDirectory(path.normalize(match.group(1)!));
} else {
match = _injectPattern.firstMatch(line);
if (match != null) {
snippetCount++;
final String excerptPath =
path.normalize(match.namedGroup('path')!);
final File excerptSourceFile = pathBase.childFile(excerptPath);
final String extension = path.extension(excerptSourceFile.path);
switch (extension) {
case '':
language = 'txt';
case '.kt':
language = 'kotlin';
case '.cc':
case '.cpp':
language = 'c++';
case '.m':
language = 'objectivec';
case '.gradle':
language = 'groovy';
default:
language = extension.substring(1);
break;
}
final String section = match.namedGroup('section')!;
final String plaster = match.namedGroup('plaster') ?? '···';
if (!excerptSourceFile.existsSync()) {
errors.add(
'${file.path}:$lineNumber: specified file "$excerptPath" (resolved to "${excerptSourceFile.path}") does not exist');
} else {
excerpt = _extractExcerpt(
excerptSourceFile, section, plaster, language, errors);
}
mode = _ExcerptParseMode.pragma;
} else {
errors.add(
'${file.path}:$lineNumber: $_pragma?> pragma does not match expected syntax or is not alone on the line');
}
}
}
output.writeln(line);
case _ExcerptParseMode.pragma:
if (!line.startsWith('```')) {
errors.add(
'${file.path}:$lineNumber: expected code block but did not find one');
mode = _ExcerptParseMode.normal;
} else {
if (line.startsWith('``` ')) {
errors.add(
'${file.path}:$lineNumber: code block was followed by a space character instead of the language (expected "$language")');
mode = _ExcerptParseMode.injecting;
} else if (line != '```$language' &&
line != '```rfwtxt' &&
line != '```json') {
// We special-case rfwtxt and json because the rfw package extracts such sections from Dart files.
// If we get more special cases we should think about a more general solution.
errors.add(
'${file.path}:$lineNumber: code block has wrong language');
}
mode = _ExcerptParseMode.injecting;
}
output.writeln(line);
case _ExcerptParseMode.injecting:
if (line == '```') {
if (existingBlock.toString() != excerpt) {
detectedChange = true;
}
output.write(excerpt);
output.writeln(line);
mode = _ExcerptParseMode.normal;
language = null;
excerpt = null;
existingBlock.clear();
} else {
existingBlock.writeln(line);
}
}
}
if (detectedChange) {
if (errors.isNotEmpty) {
errors.add('${file.path}: skipped updating file due to errors');
} else {
try {
file.writeAsStringSync(output.toString());
} catch (e) {
errors.add(
'${file.path}: failed to update file (${e.runtimeType}: $e)');
}
}
}
return _UpdateResult(detectedChange, snippetCount, errors);
}
String _extractExcerpt(File excerptSourceFile, String section,
String plasterInside, String language, List<String> errors) {
final List<String> buffer = <String>[];
bool extracting = false;
int lineNumber = 0;
int maxLength = 0;
bool found = false;
String prefix = '';
String suffix = '';
String padding = '';
switch (language) {
case 'cc':
case 'c++':
case 'dart':
case 'js':
case 'kotlin':
case 'rfwtxt':
case 'java':
case 'groovy':
case 'objectivec':
case 'swift':
prefix = '// ';
case 'css':
prefix = '/* ';
suffix = ' */';
case 'html':
case 'xml':
prefix = '<!--';
suffix = '-->';
padding = ' ';
case 'yaml':
prefix = '# ';
case 'sh':
prefix = '# ';
}
final String startRegionMarker = '$prefix#docregion $section$suffix';
final String endRegionMarker = '$prefix#enddocregion $section$suffix';
final String plaster = '$prefix$padding$plasterInside$padding$suffix';
int? indentation;
for (final String excerptLine in excerptSourceFile.readAsLinesSync()) {
final String trimmedLine = excerptLine.trimLeft();
lineNumber += 1;
if (extracting) {
if (trimmedLine == endRegionMarker) {
extracting = false;
indentation = excerptLine.length - trimmedLine.length;
} else {
if (trimmedLine == startRegionMarker) {
errors.add(
'${excerptSourceFile.path}:$lineNumber: saw "$startRegionMarker" pragma while already in a "$section" doc region');
}
if (excerptLine.length > maxLength) {
maxLength = excerptLine.length;
}
if (!excerptLine.contains('$prefix#docregion ') &&
!excerptLine.contains('$prefix#enddocregion ')) {
buffer.add(excerptLine);
}
}
} else {
if (trimmedLine == startRegionMarker) {
found = true;
extracting = true;
if (buffer.isNotEmpty && plasterInside != 'none') {
assert(indentation != null);
buffer.add('${" " * indentation!}$plaster');
indentation = null;
}
}
}
}
if (extracting) {
errors
.add('${excerptSourceFile.path}: missing "$endRegionMarker" pragma');
}
if (!found) {
errors.add(
'${excerptSourceFile.path}: did not find a "$startRegionMarker" pragma');
return '';
}
if (buffer.isEmpty) {
errors.add('${excerptSourceFile.path}: region "$section" is empty');
return '';
}
int indent = maxLength;
for (final String line in buffer) {
if (indent == 0) {
break;
}
if (line.isEmpty) {
continue;
}
for (int index = 0; index < line.length; index += 1) {
if (line[index] != ' ') {
if (index < indent) {
indent = index;
}
}
}
}
final StringBuffer excerpt = StringBuffer();
for (final String line in buffer) {
if (line.isEmpty) {
excerpt.writeln();
} else {
excerpt.writeln(line.substring(indent));
}
}
return excerpt.toString();
}
}
| packages/script/tool/lib/src/update_excerpts_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/update_excerpts_command.dart",
"repo_id": "packages",
"token_count": 5207
} | 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:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/common/plugin_utils.dart';
import 'package:test/test.dart';
import '../util.dart';
void main() {
late FileSystem fileSystem;
late Directory packagesDir;
setUp(() {
fileSystem = MemoryFileSystem();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
});
group('pluginSupportsPlatform', () {
test('no platforms', () async {
final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir);
expect(pluginSupportsPlatform(platformAndroid, plugin), isFalse);
expect(pluginSupportsPlatform(platformIOS, plugin), isFalse);
expect(pluginSupportsPlatform(platformLinux, plugin), isFalse);
expect(pluginSupportsPlatform(platformMacOS, plugin), isFalse);
expect(pluginSupportsPlatform(platformWeb, plugin), isFalse);
expect(pluginSupportsPlatform(platformWindows, plugin), isFalse);
});
test('all platforms', () async {
final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
platformLinux: const PlatformDetails(PlatformSupport.inline),
platformMacOS: const PlatformDetails(PlatformSupport.inline),
platformWeb: const PlatformDetails(PlatformSupport.inline),
platformWindows: const PlatformDetails(PlatformSupport.inline),
});
expect(pluginSupportsPlatform(platformAndroid, plugin), isTrue);
expect(pluginSupportsPlatform(platformIOS, plugin), isTrue);
expect(pluginSupportsPlatform(platformLinux, plugin), isTrue);
expect(pluginSupportsPlatform(platformMacOS, plugin), isTrue);
expect(pluginSupportsPlatform(platformWeb, plugin), isTrue);
expect(pluginSupportsPlatform(platformWindows, plugin), isTrue);
});
test('some platforms', () async {
final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformLinux: const PlatformDetails(PlatformSupport.inline),
platformWeb: const PlatformDetails(PlatformSupport.inline),
});
expect(pluginSupportsPlatform(platformAndroid, plugin), isTrue);
expect(pluginSupportsPlatform(platformIOS, plugin), isFalse);
expect(pluginSupportsPlatform(platformLinux, plugin), isTrue);
expect(pluginSupportsPlatform(platformMacOS, plugin), isFalse);
expect(pluginSupportsPlatform(platformWeb, plugin), isTrue);
expect(pluginSupportsPlatform(platformWindows, plugin), isFalse);
});
test('inline plugins are only detected as inline', () async {
final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
platformLinux: const PlatformDetails(PlatformSupport.inline),
platformMacOS: const PlatformDetails(PlatformSupport.inline),
platformWeb: const PlatformDetails(PlatformSupport.inline),
platformWindows: const PlatformDetails(PlatformSupport.inline),
});
expect(
pluginSupportsPlatform(platformAndroid, plugin,
requiredMode: PlatformSupport.inline),
isTrue);
expect(
pluginSupportsPlatform(platformAndroid, plugin,
requiredMode: PlatformSupport.federated),
isFalse);
expect(
pluginSupportsPlatform(platformIOS, plugin,
requiredMode: PlatformSupport.inline),
isTrue);
expect(
pluginSupportsPlatform(platformIOS, plugin,
requiredMode: PlatformSupport.federated),
isFalse);
expect(
pluginSupportsPlatform(platformLinux, plugin,
requiredMode: PlatformSupport.inline),
isTrue);
expect(
pluginSupportsPlatform(platformLinux, plugin,
requiredMode: PlatformSupport.federated),
isFalse);
expect(
pluginSupportsPlatform(platformMacOS, plugin,
requiredMode: PlatformSupport.inline),
isTrue);
expect(
pluginSupportsPlatform(platformMacOS, plugin,
requiredMode: PlatformSupport.federated),
isFalse);
expect(
pluginSupportsPlatform(platformWeb, plugin,
requiredMode: PlatformSupport.inline),
isTrue);
expect(
pluginSupportsPlatform(platformWeb, plugin,
requiredMode: PlatformSupport.federated),
isFalse);
expect(
pluginSupportsPlatform(platformWindows, plugin,
requiredMode: PlatformSupport.inline),
isTrue);
expect(
pluginSupportsPlatform(platformWindows, plugin,
requiredMode: PlatformSupport.federated),
isFalse);
});
test('federated plugins are only detected as federated', () async {
final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir,
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.federated),
platformIOS: const PlatformDetails(PlatformSupport.federated),
platformLinux: const PlatformDetails(PlatformSupport.federated),
platformMacOS: const PlatformDetails(PlatformSupport.federated),
platformWeb: const PlatformDetails(PlatformSupport.federated),
platformWindows: const PlatformDetails(PlatformSupport.federated),
});
expect(
pluginSupportsPlatform(platformAndroid, plugin,
requiredMode: PlatformSupport.federated),
isTrue);
expect(
pluginSupportsPlatform(platformAndroid, plugin,
requiredMode: PlatformSupport.inline),
isFalse);
expect(
pluginSupportsPlatform(platformIOS, plugin,
requiredMode: PlatformSupport.federated),
isTrue);
expect(
pluginSupportsPlatform(platformIOS, plugin,
requiredMode: PlatformSupport.inline),
isFalse);
expect(
pluginSupportsPlatform(platformLinux, plugin,
requiredMode: PlatformSupport.federated),
isTrue);
expect(
pluginSupportsPlatform(platformLinux, plugin,
requiredMode: PlatformSupport.inline),
isFalse);
expect(
pluginSupportsPlatform(platformMacOS, plugin,
requiredMode: PlatformSupport.federated),
isTrue);
expect(
pluginSupportsPlatform(platformMacOS, plugin,
requiredMode: PlatformSupport.inline),
isFalse);
expect(
pluginSupportsPlatform(platformWeb, plugin,
requiredMode: PlatformSupport.federated),
isTrue);
expect(
pluginSupportsPlatform(platformWeb, plugin,
requiredMode: PlatformSupport.inline),
isFalse);
expect(
pluginSupportsPlatform(platformWindows, plugin,
requiredMode: PlatformSupport.federated),
isTrue);
expect(
pluginSupportsPlatform(platformWindows, plugin,
requiredMode: PlatformSupport.inline),
isFalse);
});
});
group('pluginHasNativeCodeForPlatform', () {
test('returns false for web', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
platformSupport: <String, PlatformDetails>{
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
expect(pluginHasNativeCodeForPlatform(platformWeb, plugin), isFalse);
});
test('returns false for a native-only plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
platformSupport: <String, PlatformDetails>{
platformLinux: const PlatformDetails(PlatformSupport.inline),
platformMacOS: const PlatformDetails(PlatformSupport.inline),
platformWindows: const PlatformDetails(PlatformSupport.inline),
},
);
expect(pluginHasNativeCodeForPlatform(platformLinux, plugin), isTrue);
expect(pluginHasNativeCodeForPlatform(platformMacOS, plugin), isTrue);
expect(pluginHasNativeCodeForPlatform(platformWindows, plugin), isTrue);
});
test('returns true for a native+Dart plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
platformSupport: <String, PlatformDetails>{
platformLinux:
const PlatformDetails(PlatformSupport.inline, hasDartCode: true),
platformMacOS:
const PlatformDetails(PlatformSupport.inline, hasDartCode: true),
platformWindows:
const PlatformDetails(PlatformSupport.inline, hasDartCode: true),
},
);
expect(pluginHasNativeCodeForPlatform(platformLinux, plugin), isTrue);
expect(pluginHasNativeCodeForPlatform(platformMacOS, plugin), isTrue);
expect(pluginHasNativeCodeForPlatform(platformWindows, plugin), isTrue);
});
test('returns false for a Dart-only plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
platformSupport: <String, PlatformDetails>{
platformLinux: const PlatformDetails(PlatformSupport.inline,
hasNativeCode: false, hasDartCode: true),
platformMacOS: const PlatformDetails(PlatformSupport.inline,
hasNativeCode: false, hasDartCode: true),
platformWindows: const PlatformDetails(PlatformSupport.inline,
hasNativeCode: false, hasDartCode: true),
},
);
expect(pluginHasNativeCodeForPlatform(platformLinux, plugin), isFalse);
expect(pluginHasNativeCodeForPlatform(platformMacOS, plugin), isFalse);
expect(pluginHasNativeCodeForPlatform(platformWindows, plugin), isFalse);
});
});
}
| packages/script/tool/test/common/plugin_utils_test.dart/0 | {
"file_path": "packages/script/tool/test/common/plugin_utils_test.dart",
"repo_id": "packages",
"token_count": 3982
} | 1,080 |
// 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/license_check_command.dart';
import 'package:mockito/mockito.dart';
import 'package:platform/platform.dart';
import 'package:test/test.dart';
import 'common/package_command_test.mocks.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
group('LicenseCheckCommand', () {
late CommandRunner<void> runner;
late FileSystem fileSystem;
late Platform platform;
late Directory root;
setUp(() {
fileSystem = MemoryFileSystem();
platform = MockPlatformWithSeparator();
final Directory packagesDir =
fileSystem.currentDirectory.childDirectory('packages');
root = packagesDir.parent;
final MockGitDir gitDir = MockGitDir();
when(gitDir.path).thenReturn(packagesDir.parent.path);
final LicenseCheckCommand command = LicenseCheckCommand(
packagesDir,
platform: platform,
gitDir: gitDir,
);
runner =
CommandRunner<void>('license_test', 'Test for $LicenseCheckCommand');
runner.addCommand(command);
});
/// Writes a copyright+license block to [file], defaulting to a standard
/// block for this repository.
///
/// [commentString] is added to the start of each line.
/// [prefix] is added to the start of the entire block.
/// [suffix] is added to the end of the entire block.
void writeLicense(
File file, {
String comment = '// ',
String prefix = '',
String suffix = '',
String copyright =
'Copyright 2013 The Flutter Authors. All rights reserved.',
List<String> license = const <String>[
'Use of this source code is governed by a BSD-style license that can be',
'found in the LICENSE file.',
],
bool useCrlf = false,
}) {
final List<String> lines = <String>['$prefix$comment$copyright'];
for (final String line in license) {
lines.add('$comment$line');
}
final String newline = useCrlf ? '\r\n' : '\n';
file.writeAsStringSync(lines.join(newline) + suffix + newline);
}
test('looks at only expected extensions', () async {
final Map<String, bool> extensions = <String, bool>{
'c': true,
'cc': true,
'cpp': true,
'dart': true,
'h': true,
'html': true,
'java': true,
'json': false,
'kt': true,
'm': true,
'md': false,
'mm': true,
'png': false,
'swift': true,
'sh': true,
'yaml': false,
};
const String filenameBase = 'a_file';
for (final String fileExtension in extensions.keys) {
root.childFile('$filenameBase.$fileExtension').createSync();
}
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
// Ignore failure; the files are empty so the check is expected to fail,
// but this test isn't for that behavior.
});
extensions.forEach((String fileExtension, bool shouldCheck) {
final Matcher logLineMatcher =
contains('Checking $filenameBase.$fileExtension');
expect(output, shouldCheck ? logLineMatcher : isNot(logLineMatcher));
});
});
test('ignore list overrides extension matches', () async {
final List<String> ignoredFiles = <String>[
// Ignored base names.
'flutter_export_environment.sh',
'GeneratedPluginRegistrant.java',
'GeneratedPluginRegistrant.m',
'generated_plugin_registrant.cc',
'generated_plugin_registrant.cpp',
// Ignored path suffixes.
'foo.g.dart',
'foo.mocks.dart',
// Ignored files.
'resource.h',
];
for (final String name in ignoredFiles) {
root.childFile(name).createSync();
}
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
for (final String name in ignoredFiles) {
expect(output, isNot(contains('Checking $name')));
}
});
test('ignores submodules', () async {
const String submoduleName = 'a_submodule';
final File submoduleSpec = root.childFile('.gitmodules');
submoduleSpec.writeAsStringSync('''
[submodule "$submoduleName"]
path = $submoduleName
url = https://github.com/foo/$submoduleName
''');
const List<String> submoduleFiles = <String>[
'$submoduleName/foo.dart',
'$submoduleName/a/b/bar.dart',
'$submoduleName/LICENSE',
];
for (final String filePath in submoduleFiles) {
root.childFile(filePath).createSync(recursive: true);
}
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
for (final String filePath in submoduleFiles) {
expect(output, isNot(contains('Checking $filePath')));
}
});
test('passes if all checked files have license blocks', () async {
final File checked = root.childFile('checked.cc');
checked.createSync();
writeLicense(checked);
final File notChecked = root.childFile('not_checked.md');
notChecked.createSync();
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
// Sanity check that the test did actually check a file.
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checking checked.cc'),
contains('All files passed validation!'),
]));
});
test('passes correct license blocks on Windows', () async {
final File checked = root.childFile('checked.cc');
checked.createSync();
writeLicense(checked, useCrlf: true);
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
// Sanity check that the test did actually check a file.
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checking checked.cc'),
contains('All files passed validation!'),
]));
});
test('handles the comment styles for all supported languages', () async {
final File fileA = root.childFile('file_a.cc');
fileA.createSync();
writeLicense(fileA);
final File fileB = root.childFile('file_b.sh');
fileB.createSync();
writeLicense(fileB, comment: '# ');
final File fileC = root.childFile('file_c.html');
fileC.createSync();
writeLicense(fileC, comment: '', prefix: '<!-- ', suffix: ' -->');
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
// Sanity check that the test did actually check the files.
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checking file_a.cc'),
contains('Checking file_b.sh'),
contains('Checking file_c.html'),
contains('All files passed validation!'),
]));
});
test('fails if any checked files are missing license blocks', () async {
final File goodA = root.childFile('good.cc');
goodA.createSync();
writeLicense(goodA);
final File goodB = root.childFile('good.h');
goodB.createSync();
writeLicense(goodB);
root.childFile('bad.cc').createSync();
root.childFile('bad.h').createSync();
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
// Failure should give information about the problematic files.
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'The license block for these files is missing or incorrect:'),
contains(' bad.cc'),
contains(' bad.h'),
]));
// Failure shouldn't print the success message.
expect(output, isNot(contains(contains('All files passed validation!'))));
});
test('fails if any checked files are missing just the copyright', () async {
final File good = root.childFile('good.cc');
good.createSync();
writeLicense(good);
final File bad = root.childFile('bad.cc');
bad.createSync();
writeLicense(bad, copyright: '');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
// Failure should give information about the problematic files.
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'The license block for these files is missing or incorrect:'),
contains(' bad.cc'),
]));
// Failure shouldn't print the success message.
expect(output, isNot(contains(contains('All files passed validation!'))));
});
test('fails if any checked files are missing just the license', () async {
final File good = root.childFile('good.cc');
good.createSync();
writeLicense(good);
final File bad = root.childFile('bad.cc');
bad.createSync();
writeLicense(bad, license: <String>[]);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
// Failure should give information about the problematic files.
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'The license block for these files is missing or incorrect:'),
contains(' bad.cc'),
]));
// Failure shouldn't print the success message.
expect(output, isNot(contains(contains('All files passed validation!'))));
});
test('fails if any third-party code is not in a third_party directory',
() async {
final File thirdPartyFile = root.childFile('third_party.cc');
thirdPartyFile.createSync();
writeLicense(thirdPartyFile, copyright: 'Copyright 2017 Someone Else');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
// Failure should give information about the problematic files.
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'The license block for these files is missing or incorrect:'),
contains(' third_party.cc'),
]));
// Failure shouldn't print the success message.
expect(output, isNot(contains(contains('All files passed validation!'))));
});
test('succeeds for third-party code in a third_party directory', () async {
final File thirdPartyFile = root
.childDirectory('a_plugin')
.childDirectory('lib')
.childDirectory('src')
.childDirectory('third_party')
.childFile('file.cc');
thirdPartyFile.createSync(recursive: true);
writeLicense(thirdPartyFile,
copyright: 'Copyright 2017 Workiva Inc.',
license: <String>[
'Licensed under the Apache License, Version 2.0 (the "License");',
'you may not use this file except in compliance with the License.'
]);
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
// Sanity check that the test did actually check the file.
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checking a_plugin/lib/src/third_party/file.cc'),
contains('All files passed validation!'),
]));
});
test('allows first-party code in a third_party directory', () async {
final File firstPartyFileInThirdParty = root
.childDirectory('a_plugin')
.childDirectory('lib')
.childDirectory('src')
.childDirectory('third_party')
.childFile('first_party.cc');
firstPartyFileInThirdParty.createSync(recursive: true);
writeLicense(firstPartyFileInThirdParty);
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
// Sanity check that the test did actually check the file.
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checking a_plugin/lib/src/third_party/first_party.cc'),
contains('All files passed validation!'),
]));
});
test('fails for licenses that the tool does not expect', () async {
final File good = root.childFile('good.cc');
good.createSync();
writeLicense(good);
final File bad = root.childDirectory('third_party').childFile('bad.cc');
bad.createSync(recursive: true);
writeLicense(bad, license: <String>[
'This program is free software: you can redistribute it and/or modify',
'it under the terms of the GNU General Public License',
]);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
// Failure should give information about the problematic files.
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'No recognized license was found for the following third-party files:'),
contains(' third_party/bad.cc'),
]));
// Failure shouldn't print the success message.
expect(output, isNot(contains(contains('All files passed validation!'))));
});
test('Apache is not recognized for new authors without validation changes',
() async {
final File good = root.childFile('good.cc');
good.createSync();
writeLicense(good);
final File bad = root.childDirectory('third_party').childFile('bad.cc');
bad.createSync(recursive: true);
writeLicense(
bad,
copyright: 'Copyright 2017 Some New Authors.',
license: <String>[
'Licensed under the Apache License, Version 2.0 (the "License");',
'you may not use this file except in compliance with the License.'
],
);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
// Failure should give information about the problematic files.
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'No recognized license was found for the following third-party files:'),
contains(' third_party/bad.cc'),
]));
// Failure shouldn't print the success message.
expect(output, isNot(contains(contains('All files passed validation!'))));
});
test('passes if all first-party LICENSE files are correctly formatted',
() async {
final File license = root.childFile('LICENSE');
license.createSync();
license.writeAsStringSync(_correctLicenseFileText);
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
// Sanity check that the test did actually check the file.
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checking LICENSE'),
contains('All files passed validation!'),
]));
});
test('passes correct LICENSE files on Windows', () async {
final File license = root.childFile('LICENSE');
license.createSync();
license
.writeAsStringSync(_correctLicenseFileText.replaceAll('\n', '\r\n'));
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
// Sanity check that the test did actually check the file.
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checking LICENSE'),
contains('All files passed validation!'),
]));
});
test('fails if any first-party LICENSE files are incorrectly formatted',
() async {
final File license = root.childFile('LICENSE');
license.createSync();
license.writeAsStringSync(_incorrectLicenseFileText);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(output, isNot(contains(contains('All files passed validation!'))));
});
test('ignores third-party LICENSE format', () async {
final File license =
root.childDirectory('third_party').childFile('LICENSE');
license.createSync(recursive: true);
license.writeAsStringSync(_incorrectLicenseFileText);
final List<String> output =
await runCapturingPrint(runner, <String>['license-check']);
// The file shouldn't be checked.
expect(output, isNot(contains(contains('Checking third_party/LICENSE'))));
});
test('outputs all errors at the end', () async {
root.childFile('bad.cc').createSync();
root
.childDirectory('third_party')
.childFile('bad.cc')
.createSync(recursive: true);
final File license = root.childFile('LICENSE');
license.createSync();
license.writeAsStringSync(_incorrectLicenseFileText);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['license-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Checking LICENSE'),
contains('Checking bad.cc'),
contains('Checking third_party/bad.cc'),
contains(
'The following LICENSE files do not follow the expected format:'),
contains(' LICENSE'),
contains(
'The license block for these files is missing or incorrect:'),
contains(' bad.cc'),
contains(
'No recognized license was found for the following third-party files:'),
contains(' third_party/bad.cc'),
]));
});
});
}
class MockPlatformWithSeparator extends MockPlatform {
@override
String get pathSeparator => isWindows ? r'\' : '/';
}
const String _correctLicenseFileText = '''
Copyright 2013 The Flutter Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
''';
// A common incorrect version created by copying text intended for a code file,
// with comment markers.
const String _incorrectLicenseFileText = '''
// Copyright 2013 The Flutter Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
''';
| packages/script/tool/test/license_check_command_test.dart/0 | {
"file_path": "packages/script/tool/test/license_check_command_test.dart",
"repo_id": "packages",
"token_count": 8563
} | 1,081 |
// 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_release_info_command.dart';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import 'common/package_command_test.mocks.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
late FileSystem fileSystem;
late Directory packagesDir;
late MockGitDir gitDir;
late RecordingProcessRunner processRunner;
late CommandRunner<void> runner;
setUp(() {
fileSystem = MemoryFileSystem();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
processRunner = RecordingProcessRunner();
gitDir = MockGitDir();
when(gitDir.path).thenReturn(packagesDir.parent.path);
when(gitDir.runCommand(any, throwOnError: anyNamed('throwOnError')))
.thenAnswer((Invocation invocation) {
final List<String> arguments =
invocation.positionalArguments[0]! as List<String>;
// Route git calls through a process runner, to make mock output
// consistent with other processes. Attach the first argument to the
// command to make targeting the mock results easier.
final String gitCommand = arguments.removeAt(0);
return processRunner.run('git-$gitCommand', arguments);
});
final UpdateReleaseInfoCommand command = UpdateReleaseInfoCommand(
packagesDir,
gitDir: gitDir,
);
runner = CommandRunner<void>(
'update_release_info_command', 'Test for update_release_info_command');
runner.addCommand(command);
});
group('flags', () {
test('fails if --changelog is missing', () async {
Error? commandError;
await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=next',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ArgumentError>());
});
test('fails if --changelog is blank', () async {
Exception? commandError;
await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=next',
'--changelog',
'',
], exceptionHandler: (Exception e) {
commandError = e;
});
expect(commandError, isA<UsageException>());
});
test('fails if --version is missing', () async {
Error? commandError;
await runCapturingPrint(
runner, <String>['update-release-info', '--changelog', 'A change.'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ArgumentError>());
});
test('fails if --version is an unknown value', () async {
Exception? commandError;
await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=foo',
'--changelog',
'A change.',
], exceptionHandler: (Exception e) {
commandError = e;
});
expect(commandError, isA<UsageException>());
});
});
group('changelog', () {
test('adds new NEXT section', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
## 1.0.0
* Previous changes.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=next',
'--changelog',
'A change.'
]);
final String newChangelog = package.changelogFile.readAsStringSync();
const String expectedChangeLog = '''
## NEXT
* A change.
$originalChangelog''';
expect(
output,
containsAllInOrder(<Matcher>[
contains(' Added a NEXT section.'),
]),
);
expect(newChangelog, expectedChangeLog);
});
test('adds to existing NEXT section', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
## NEXT
* Already-pending changes.
## 1.0.0
* Old changes.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=next',
'--changelog',
'A change.'
]);
final String newChangelog = package.changelogFile.readAsStringSync();
const String expectedChangeLog = '''
## NEXT
* A change.
* Already-pending changes.
## 1.0.0
* Old changes.
''';
expect(output,
containsAllInOrder(<Matcher>[contains(' Updated NEXT section.')]));
expect(newChangelog, expectedChangeLog);
});
test('adds new version section', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
## 1.0.0
* Previous changes.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=bugfix',
'--changelog',
'A change.'
]);
final String newChangelog = package.changelogFile.readAsStringSync();
const String expectedChangeLog = '''
## 1.0.1
* A change.
$originalChangelog''';
expect(
output,
containsAllInOrder(<Matcher>[
contains(' Added a 1.0.1 section.'),
]),
);
expect(newChangelog, expectedChangeLog);
});
test('converts existing NEXT section to version section', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
## NEXT
* Already-pending changes.
## 1.0.0
* Old changes.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=bugfix',
'--changelog',
'A change.'
]);
final String newChangelog = package.changelogFile.readAsStringSync();
const String expectedChangeLog = '''
## 1.0.1
* A change.
* Already-pending changes.
## 1.0.0
* Old changes.
''';
expect(output,
containsAllInOrder(<Matcher>[contains(' Updated NEXT section.')]));
expect(newChangelog, expectedChangeLog);
});
test('treats multiple lines as multiple list items', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
## 1.0.0
* Previous changes.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=bugfix',
'--changelog',
'First change.\nSecond change.'
]);
final String newChangelog = package.changelogFile.readAsStringSync();
const String expectedChangeLog = '''
## 1.0.1
* First change.
* Second change.
$originalChangelog''';
expect(newChangelog, expectedChangeLog);
});
test('adds a period to any lines missing it, and removes whitespace',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
## 1.0.0
* Previous changes.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=bugfix',
'--changelog',
'First change \nSecond change'
]);
final String newChangelog = package.changelogFile.readAsStringSync();
const String expectedChangeLog = '''
## 1.0.1
* First change.
* Second change.
$originalChangelog''';
expect(newChangelog, expectedChangeLog);
});
test('handles non-standard changelog format', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
# 1.0.0
* A version with the wrong heading format.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=next',
'--changelog',
'A change.'
]);
final String newChangelog = package.changelogFile.readAsStringSync();
const String expectedChangeLog = '''
## NEXT
* A change.
$originalChangelog''';
expect(output,
containsAllInOrder(<Matcher>[contains(' Added a NEXT section.')]));
expect(newChangelog, expectedChangeLog);
});
test('adds to existing NEXT section using - list style', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
## NEXT
- Already-pending changes.
## 1.0.0
- Previous changes.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=next',
'--changelog',
'A change.'
]);
final String newChangelog = package.changelogFile.readAsStringSync();
const String expectedChangeLog = '''
## NEXT
- A change.
- Already-pending changes.
## 1.0.0
- Previous changes.
''';
expect(output,
containsAllInOrder(<Matcher>[contains(' Updated NEXT section.')]));
expect(newChangelog, expectedChangeLog);
});
test('skips for "minimal" when there are no changes at all', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.1');
processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/different_package/lib/foo.dart
''')),
];
final String originalChangelog = package.changelogFile.readAsStringSync();
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minimal',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '1.0.1');
expect(package.changelogFile.readAsStringSync(), originalChangelog);
expect(
output,
containsAllInOrder(<Matcher>[
contains('No changes to package'),
contains('Skipped 1 package')
]));
});
test('skips for "minimal" when there are only test changes', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.1');
processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/a_package/test/a_test.dart
packages/a_package/example/integration_test/another_test.dart
''')),
];
final String originalChangelog = package.changelogFile.readAsStringSync();
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minimal',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '1.0.1');
expect(package.changelogFile.readAsStringSync(), originalChangelog);
expect(
output,
containsAllInOrder(<Matcher>[
contains('No non-exempt changes to package'),
contains('Skipped 1 package')
]));
});
test('fails if CHANGELOG.md is missing', () async {
createFakePackage('a_package', packagesDir, includeCommonFiles: false);
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minor',
'--changelog',
'A change.',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(output,
containsAllInOrder(<Matcher>[contains(' Missing CHANGELOG.md.')]));
});
test('fails if CHANGELOG.md has unexpected NEXT block format', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String originalChangelog = '''
## NEXT
Some free-form text that isn't a list.
## 1.0.0
- Previous changes.
''';
package.changelogFile.writeAsStringSync(originalChangelog);
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minor',
'--changelog',
'A change.',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(' Existing NEXT section has unrecognized format.')
]));
});
});
group('pubspec', () {
test('does not change for --next', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.0');
await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=next',
'--changelog',
'A change.'
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '1.0.0');
});
test('updates bugfix version for pre-1.0 without existing build number',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '0.1.0');
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=bugfix',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '0.1.0+1');
expect(
output,
containsAllInOrder(
<Matcher>[contains(' Incremented version to 0.1.0+1')]));
});
test('updates bugfix version for pre-1.0 with existing build number',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '0.1.0+2');
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=bugfix',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '0.1.0+3');
expect(
output,
containsAllInOrder(
<Matcher>[contains(' Incremented version to 0.1.0+3')]));
});
test('updates bugfix version for post-1.0', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.1');
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=bugfix',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '1.0.2');
expect(
output,
containsAllInOrder(
<Matcher>[contains(' Incremented version to 1.0.2')]));
});
test('updates minor version for pre-1.0', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '0.1.0+2');
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minor',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '0.1.1');
expect(
output,
containsAllInOrder(
<Matcher>[contains(' Incremented version to 0.1.1')]));
});
test('updates minor version for post-1.0', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.1');
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minor',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '1.1.0');
expect(
output,
containsAllInOrder(
<Matcher>[contains(' Incremented version to 1.1.0')]));
});
test('updates bugfix version for "minimal" with publish-worthy changes',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.1');
processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/a_package/lib/plugin.dart
''')),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minimal',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '1.0.2');
expect(
output,
containsAllInOrder(
<Matcher>[contains(' Incremented version to 1.0.2')]));
});
test('no version change for "minimal" with non-publish-worthy changes',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, version: '1.0.1');
processRunner.mockProcessesForExecutable['git-diff'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/a_package/test/plugin_test.dart
''')),
];
await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minimal',
'--changelog',
'A change.',
]);
final String version = package.parsePubspec().version?.toString() ?? '';
expect(version, '1.0.1');
});
test('fails if there is no version in pubspec', () async {
createFakePackage('a_package', packagesDir, version: null);
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-release-info',
'--version=minor',
'--changelog',
'A change.',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(
<Matcher>[contains('Could not determine current version.')]));
});
});
}
| packages/script/tool/test/update_release_info_command_test.dart/0 | {
"file_path": "packages/script/tool/test/update_release_info_command_test.dart",
"repo_id": "packages",
"token_count": 7788
} | 1,082 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// This test file is primarily here to serve as a source for code excerpts.
library;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets(
'Cupertino Icon Test',
(WidgetTester tester) async {
// #docregion CupertinoIcon
const Icon icon = Icon(
CupertinoIcons.heart_fill,
color: Colors.pink,
size: 24.0,
);
// #enddocregion CupertinoIcon
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: icon,
),
),
);
expect(find.byType(Icon), findsOne);
},
);
}
| packages/third_party/packages/cupertino_icons/test/cupertino_icons_test.dart/0 | {
"file_path": "packages/third_party/packages/cupertino_icons/test/cupertino_icons_test.dart",
"repo_id": "packages",
"token_count": 354
} | 1,083 |
// GENERATED CODE - DO NOT MODIFY BY HAND
import 'package:flutter/widgets.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class Assets {
static const android = Asset(
name: 'android',
path: 'assets/images/android.png',
size: Size(450, 658),
);
static const dash = Asset(
name: 'dash',
path: 'assets/images/dash.png',
size: Size(650, 587),
);
static const dino = Asset(
name: 'dino',
path: 'assets/images/dino.png',
size: Size(648, 757),
);
static const sparky = Asset(
name: 'sparky',
path: 'assets/images/sparky.png',
size: Size(730, 588),
);
static const googleProps = {
Asset(
name: '01_google_v1',
path: 'assets/props/google/01_google_v1.png',
size: Size(847, 697),
),
Asset(
name: '02_google_v1',
path: 'assets/props/google/02_google_v1.png',
size: Size(349, 682),
),
Asset(
name: '03_google_V1',
path: 'assets/props/google/03_google_V1.png',
size: Size(640, 595),
),
Asset(
name: '04_google_v1',
path: 'assets/props/google/04_google_v1.png',
size: Size(631, 365),
),
Asset(
name: '05_google_v1',
path: 'assets/props/google/05_google_v1.png',
size: Size(968, 187),
),
Asset(
name: '06_google_v1',
path: 'assets/props/google/06_google_v1.png',
size: Size(1008, 465),
),
Asset(
name: '07_google_v1',
path: 'assets/props/google/07_google_v1.png',
size: Size(1009, 469),
),
Asset(
name: '08_google_v1',
path: 'assets/props/google/08_google_v1.png',
size: Size(793, 616),
),
Asset(
name: '09_google_v1',
path: 'assets/props/google/09_google_v1.png',
size: Size(603, 810),
),
Asset(
name: '10_google_v1',
path: 'assets/props/google/10_google_v1.png',
size: Size(971, 764),
),
Asset(
name: '11_google_v1',
path: 'assets/props/google/11_google_v1.png',
size: Size(839, 840),
),
Asset(
name: '12_google_v1',
path: 'assets/props/google/12_google_v1.png',
size: Size(995, 181),
),
Asset(
name: '13_google_v1',
path: 'assets/props/google/13_google_v1.png',
size: Size(884, 589),
),
Asset(
name: '14_google_v1',
path: 'assets/props/google/14_google_v1.png',
size: Size(726, 591),
),
Asset(
name: '15_google_v1',
path: 'assets/props/google/15_google_v1.png',
size: Size(450, 722),
),
Asset(
name: '16_google_v1',
path: 'assets/props/google/16_google_v1.png',
size: Size(690, 772),
),
Asset(
name: '17_google_v1',
path: 'assets/props/google/17_google_v1.png',
size: Size(671, 641),
),
Asset(
name: '18_google_v1',
path: 'assets/props/google/18_google_v1.png',
size: Size(437, 452),
),
Asset(
name: '19_google_v1',
path: 'assets/props/google/19_google_v1.png',
size: Size(620, 619),
),
Asset(
name: '20_google_v1',
path: 'assets/props/google/20_google_v1.png',
size: Size(320, 903),
),
Asset(
name: '21_google_v1',
path: 'assets/props/google/21_google_v1.png',
size: Size(301, 795),
),
Asset(
name: '22_google_v1',
path: 'assets/props/google/22_google_v1.png',
size: Size(901, 870),
),
Asset(
name: '23_google_v1',
path: 'assets/props/google/23_google_v1.png',
size: Size(541, 715),
),
Asset(
name: '24_google_v1',
path: 'assets/props/google/24_google_v1.png',
size: Size(784, 807),
),
Asset(
name: '25_google_v1',
path: 'assets/props/google/25_google_v1.png',
size: Size(1086, 898),
),
Asset(
name: '26_google_v1',
path: 'assets/props/google/26_google_v1.png',
size: Size(419, 820),
),
Asset(
name: '27_google_v1',
path: 'assets/props/google/27_google_v1.png',
size: Size(921, 613),
),
Asset(
name: '28_google_v1',
path: 'assets/props/google/28_google_v1.png',
size: Size(403, 741),
),
Asset(
name: '29_google_v1',
path: 'assets/props/google/29_google_v1.png',
size: Size(570, 556),
),
Asset(
name: '30_google_v1',
path: 'assets/props/google/30_google_v1.png',
size: Size(890, 747),
),
Asset(
name: '31_google_v1',
path: 'assets/props/google/31_google_v1.png',
size: Size(891, 639),
),
Asset(
name: '32_google_v1',
path: 'assets/props/google/32_google_v1.png',
size: Size(599, 468),
),
Asset(
name: '33_google_v1',
path: 'assets/props/google/33_google_v1.png',
size: Size(639, 657),
),
Asset(
name: '34_google_v1',
path: 'assets/props/google/34_google_v1.png',
size: Size(570, 556),
),
Asset(
name: '35_google_v1',
path: 'assets/props/google/35_google_v1.png',
size: Size(662, 591),
),
};
static const hatProps = {
Asset(
name: '01_hats_v1',
path: 'assets/props/hats/01_hats_v1.png',
size: Size(571, 296),
),
Asset(
name: '02_hats_v1',
path: 'assets/props/hats/02_hats_v1.png',
size: Size(348, 594),
),
Asset(
name: '03_hats_v1',
path: 'assets/props/hats/03_hats_v1.png',
size: Size(833, 490),
),
Asset(
name: '04_hats_v1',
path: 'assets/props/hats/04_hats_v1.png',
size: Size(1051, 616),
),
Asset(
name: '05_hats_v1',
path: 'assets/props/hats/05_hats_v1.png',
size: Size(555, 298),
),
Asset(
name: '06_hats_v1',
path: 'assets/props/hats/06_hats_v1.png',
size: Size(1048, 656),
),
Asset(
name: '07_hats_v1',
path: 'assets/props/hats/07_hats_v1.png',
size: Size(925, 673),
),
Asset(
name: '08_hats_v1',
path: 'assets/props/hats/08_hats_v1.png',
size: Size(693, 361),
),
Asset(
name: '09_hats_v1',
path: 'assets/props/hats/09_hats_v1.png',
size: Size(558, 296),
),
Asset(
name: '10_hats_v1',
path: 'assets/props/hats/10_hats_v1.png',
size: Size(185, 676),
),
Asset(
name: '11_hats_v1',
path: 'assets/props/hats/11_hats_v1.png',
size: Size(677, 464),
),
Asset(
name: '12_hats_v1',
path: 'assets/props/hats/12_hats_v1.png',
size: Size(578, 762),
),
Asset(
name: '13_hats_v1',
path: 'assets/props/hats/13_hats_v1.png',
size: Size(590, 255),
),
Asset(
name: '14_hats_v1',
path: 'assets/props/hats/14_hats_v1.png',
size: Size(673, 555),
),
Asset(
name: '15_hats_v1',
path: 'assets/props/hats/15_hats_v1.png',
size: Size(860, 535),
),
Asset(
name: '16_hats_v1',
path: 'assets/props/hats/16_hats_v1.png',
size: Size(560, 611),
),
Asset(
name: '17_hats_v1',
path: 'assets/props/hats/17_hats_v1.png',
size: Size(1044, 618),
),
Asset(
name: '18_hats_v1',
path: 'assets/props/hats/18_hats_v1.png',
size: Size(849, 299),
),
Asset(
name: '19_hats_v1',
path: 'assets/props/hats/19_hats_v1.png',
size: Size(701, 483),
),
Asset(
name: '20_hats_v1',
path: 'assets/props/hats/20_hats_v1.png',
size: Size(644, 433),
),
Asset(
name: '21_hats_v1',
path: 'assets/props/hats/21_hats_v1.png',
size: Size(530, 612),
),
Asset(
name: '22_hats_v1',
path: 'assets/props/hats/22_hats_v1.png',
size: Size(664, 146),
),
Asset(
name: '23_hats_v1',
path: 'assets/props/hats/23_hats_v1.png',
size: Size(969, 336),
),
Asset(
name: '24_hats_v1',
path: 'assets/props/hats/24_hats_v1.png',
size: Size(812, 622),
),
Asset(
name: '25_hats_v1',
path: 'assets/props/hats/25_hats_v1.png',
size: Size(608, 316),
),
Asset(
name: '26_hats_v1',
path: 'assets/props/hats/26_hats_v1.png',
size: Size(693, 360),
),
Asset(
name: '27_hats_v1',
path: 'assets/props/hats/27_hats_v1.png',
size: Size(469, 608),
),
};
static const eyewearProps = {
Asset(
name: '01_eyewear_v1',
path: 'assets/props/eyewear/01_eyewear_v1.png',
size: Size(479, 330),
),
Asset(
name: '02_eyewear_v1',
path: 'assets/props/eyewear/02_eyewear_v1.png',
size: Size(512, 133),
),
Asset(
name: '03_eyewear_v1',
path: 'assets/props/eyewear/03_eyewear_v1.png',
size: Size(1212, 522),
),
Asset(
name: '04_eyewear_v1',
path: 'assets/props/eyewear/04_eyewear_v1.png',
size: Size(723, 343),
),
Asset(
name: '05_eyewear_v1',
path: 'assets/props/eyewear/05_eyewear_v1.png',
size: Size(1173, 436),
),
Asset(
name: '06_eyewear_v1',
path: 'assets/props/eyewear/06_eyewear_v1.png',
size: Size(973, 411),
),
Asset(
name: '07_eyewear_v1',
path: 'assets/props/eyewear/07_eyewear_v1.png',
size: Size(1195, 451),
),
Asset(
name: '08_eyewear_v1',
path: 'assets/props/eyewear/08_eyewear_v1.png',
size: Size(985, 250),
),
Asset(
name: '09_eyewear_v1',
path: 'assets/props/eyewear/09_eyewear_v1.png',
size: Size(479, 330),
),
Asset(
name: '10_eyewear_v1',
path: 'assets/props/eyewear/10_eyewear_v1.png',
size: Size(1405, 589),
),
Asset(
name: '11_eyewear_v1',
path: 'assets/props/eyewear/11_eyewear_v1.png',
size: Size(1151, 495),
),
Asset(
name: '12_eyewear_v1',
path: 'assets/props/eyewear/12_eyewear_v1.png',
size: Size(1267, 388),
),
Asset(
name: '13_eyewear_v1',
path: 'assets/props/eyewear/13_eyewear_v1.png',
size: Size(957, 334),
),
Asset(
name: '14_eyewear_v1',
path: 'assets/props/eyewear/14_eyewear_v1.png',
size: Size(989, 601),
),
Asset(
name: '15_eyewear_v1',
path: 'assets/props/eyewear/15_eyewear_v1.png',
size: Size(1200, 482),
),
Asset(
name: '16_eyewear_v1',
path: 'assets/props/eyewear/16_eyewear_v1.png',
size: Size(1028, 360),
),
};
static const foodProps = {
Asset(
name: '01_food_v1',
path: 'assets/props/food/01_food_v1.png',
size: Size(587, 678),
),
Asset(
name: '02_food_v1',
path: 'assets/props/food/02_food_v1.png',
size: Size(325, 591),
),
Asset(
name: '03_food_v1',
path: 'assets/props/food/03_food_v1.png',
size: Size(685, 686),
),
Asset(
name: '04_food_v1',
path: 'assets/props/food/04_food_v1.png',
size: Size(496, 422),
),
Asset(
name: '05_food_v1',
path: 'assets/props/food/05_food_v1.png',
size: Size(373, 431),
),
Asset(
name: '06_food_v1',
path: 'assets/props/food/06_food_v1.png',
size: Size(635, 587),
),
Asset(
name: '07_food_v1',
path: 'assets/props/food/07_food_v1.png',
size: Size(847, 720),
),
Asset(
name: '08_food_v1',
path: 'assets/props/food/08_food_v1.png',
size: Size(799, 610),
),
Asset(
name: '09_food_v1',
path: 'assets/props/food/09_food_v1.png',
size: Size(771, 489),
),
Asset(
name: '10_food_v1',
path: 'assets/props/food/10_food_v1.png',
size: Size(651, 634),
),
Asset(
name: '11_food_v1',
path: 'assets/props/food/11_food_v1.png',
size: Size(391, 710),
),
Asset(
name: '12_food_v1',
path: 'assets/props/food/12_food_v1.png',
size: Size(530, 856),
),
Asset(
name: '13_food_v1',
path: 'assets/props/food/13_food_v1.png',
size: Size(451, 638),
),
Asset(
name: '14_food_v1',
path: 'assets/props/food/14_food_v1.png',
size: Size(721, 507),
),
Asset(
name: '15_food_v1',
path: 'assets/props/food/15_food_v1.png',
size: Size(353, 640),
),
Asset(
name: '16_food_v1',
path: 'assets/props/food/16_food_v1.png',
size: Size(353, 640),
),
Asset(
name: '17_food_v1',
path: 'assets/props/food/17_food_v1.png',
size: Size(524, 649),
),
Asset(
name: '18_food_v1',
path: 'assets/props/food/18_food_v1.png',
size: Size(437, 503),
),
Asset(
name: '19_food_v1',
path: 'assets/props/food/19_food_v1.png',
size: Size(327, 770),
),
Asset(
name: '20_food_v1',
path: 'assets/props/food/20_food_v1.png',
size: Size(391, 786),
),
Asset(
name: '21_food_v1',
path: 'assets/props/food/21_food_v1.png',
size: Size(315, 754),
),
Asset(
name: '22_food_v1',
path: 'assets/props/food/22_food_v1.png',
size: Size(532, 610),
),
Asset(
name: '23_food_v1',
path: 'assets/props/food/23_food_v1.png',
size: Size(761, 664),
),
Asset(
name: '24_food_v1',
path: 'assets/props/food/24_food_v1.png',
size: Size(829, 630),
),
Asset(
name: '25_food_v1',
path: 'assets/props/food/25_food_v1.png',
size: Size(668, 819),
),
};
static const shapeProps = {
Asset(
name: '01_shapes_v1',
path: 'assets/props/shapes/01_shapes_v1.png',
size: Size(519, 391),
),
Asset(
name: '02_shapes_v1',
path: 'assets/props/shapes/02_shapes_v1.png',
size: Size(486, 522),
),
Asset(
name: '03_shapes_v1',
path: 'assets/props/shapes/03_shapes_v1.png',
size: Size(404, 522),
),
Asset(
name: '04_shapes_v1',
path: 'assets/props/shapes/04_shapes_v1.png',
size: Size(636, 697),
),
Asset(
name: '05_shapes_v1',
path: 'assets/props/shapes/05_shapes_v1.png',
size: Size(463, 458),
),
Asset(
name: '06_shapes_v1',
path: 'assets/props/shapes/06_shapes_v1.png',
size: Size(447, 442),
),
Asset(
name: '07_shapes_v1',
path: 'assets/props/shapes/07_shapes_v1.png',
size: Size(793, 402),
),
Asset(
name: '08_shapes_v1',
path: 'assets/props/shapes/08_shapes_v1.png',
size: Size(442, 405),
),
Asset(
name: '09_shapes_v1',
path: 'assets/props/shapes/09_shapes_v1.png',
size: Size(973, 684),
),
Asset(
name: '10_shapes_v1',
path: 'assets/props/shapes/10_shapes_v1.png',
size: Size(586, 560),
),
Asset(
name: '11_shapes_v1',
path: 'assets/props/shapes/11_shapes_v1.png',
size: Size(760, 650),
),
Asset(
name: '12_shapes_v1',
path: 'assets/props/shapes/12_shapes_v1.png',
size: Size(696, 408),
),
Asset(
name: '13_shapes_v1',
path: 'assets/props/shapes/13_shapes_v1.png',
size: Size(423, 410),
),
Asset(
name: '14_shapes_v1',
path: 'assets/props/shapes/14_shapes_v1.png',
size: Size(319, 552),
),
Asset(
name: '15_shapes_v1',
path: 'assets/props/shapes/15_shapes_v1.png',
size: Size(779, 687),
),
Asset(
name: '16_shapes_v1',
path: 'assets/props/shapes/16_shapes_v1.png',
size: Size(651, 616),
),
Asset(
name: '17_shapes_v1',
path: 'assets/props/shapes/17_shapes_v1.png',
size: Size(704, 761),
),
Asset(
name: '18_shapes_v1',
path: 'assets/props/shapes/18_shapes_v1.png',
size: Size(936, 809),
),
Asset(
name: '19_shapes_v1',
path: 'assets/props/shapes/19_shapes_v1.png',
size: Size(848, 850),
),
Asset(
name: '20_shapes_v1',
path: 'assets/props/shapes/20_shapes_v1.png',
size: Size(377, 825),
),
Asset(
name: '21_shapes_v1',
path: 'assets/props/shapes/21_shapes_v1.png',
size: Size(365, 814),
),
Asset(
name: '22_shapes_v1',
path: 'assets/props/shapes/22_shapes_v1.png',
size: Size(297, 799),
),
Asset(
name: '23_shapes_v1',
path: 'assets/props/shapes/23_shapes_v1.png',
size: Size(363, 822),
),
Asset(
name: '24_shapes_v1',
path: 'assets/props/shapes/24_shapes_v1.png',
size: Size(363, 821),
),
Asset(
name: '25_shapes_v1',
path: 'assets/props/shapes/25_shapes_v1.png',
size: Size(363, 821),
),
};
static const props = {
...googleProps,
...eyewearProps,
...hatProps,
...foodProps,
...shapeProps
};
}
| photobooth/lib/assets.g.dart/0 | {
"file_path": "photobooth/lib/assets.g.dart",
"repo_id": "photobooth",
"token_count": 9191
} | 1,084 |
{
"@@locale": "zh",
"landingPageHeading": "欢迎来到 I\u2215O 照相馆",
"landingPageSubheading": "向社区分享您拍的照片!",
"landingPageTakePhotoButtonText": "开拍",
"footerMadeWithText": "产品构建基于 ",
"footerMadeWithFlutterLinkText": "Flutter",
"footerMadeWithFirebaseLinkText": "Firebase",
"footerGoogleIOLinkText": "Google I\u2215O",
"footerCodelabLinkText": "Codelab",
"footerHowItsMadeLinkText": "本应用如何构建",
"footerTermsOfServiceLinkText": "服务条款",
"footerPrivacyPolicyLinkText": "隐私权政策",
"sharePageHeading": "向社区分享您拍的照片!",
"sharePageSubheading": "向社区分享您拍的照片!",
"sharePageSuccessHeading": "拍照已分享!",
"sharePageSuccessSubheading": "感谢使用由 Flutter 构建的 Web 应用,您拍的照片已经发布在这个唯一的网址上了",
"sharePageSuccessCaption1": "您拍的照片将在这个网址上保留 30 天然后被自动删除。若要请求提前删除,请联系 ",
"sharePageSuccessCaption2": "[email protected]",
"sharePageSuccessCaption3": " 并确保带上照片的唯一网址。",
"sharePageRetakeButtonText": "重新拍一张",
"sharePageShareButtonText": "分享",
"sharePageDownloadButtonText": "下载",
"socialMediaShareLinkText": "刚通过 #IO照相馆 拍了一张自拍,大家 #GoogleIO 大会见!#IOPhotoBooth ",
"previewPageCameraNotAllowedText": "您拒绝授予使用设备相机的权限,为了使用这个应用,请予以授权。",
"sharePageSocialMediaShareClarification1": "如果您选择在社交平台上分享您拍的照片,应用将会生成一个唯一的、30 天有效期网址的网址(过期自动删除),照片亦不会被分享或者存储。如果您希望提早删除这些照片,请联系 ",
"sharePageSocialMediaShareClarification2": "[email protected]",
"sharePageSocialMediaShareClarification3": " 并且带上照片的唯一网址。",
"sharePageCopyLinkButton": "复制",
"sharePageLinkedCopiedButton": "已复制",
"sharePageErrorHeading": "处理照片时遇到了一些问题",
"sharePageErrorSubheading": "请确保您的设备和浏览器都更新到了最新版本,如果问题依旧存在,请通过这个邮件与我们联系 [email protected] 。",
"shareDialogHeading": "分享您拍的照片!",
"shareDialogSubheading": "与其他人分享您拍的照片,也可以替换为头像,让大家知道您在参加 Google I/O 大会!",
"shareErrorDialogHeading": "喔唷!",
"shareErrorDialogTryAgainButton": "退回",
"shareErrorDialogSubheading": "出了点问题,我们没法加载您拍的照片了。",
"sharePageProgressOverlayHeading": "正在通过 Flutter “精修” 您拍的照片!",
"sharePageProgressOverlaySubheading": "请不要关闭本页面。",
"shareDialogTwitterButtonText": "Twitter",
"shareDialogFacebookButtonText": "Facebook",
"photoBoothCameraAccessDeniedHeadline": "相机权限获取失败",
"photoBoothCameraAccessDeniedSubheadline": "为了拍照成功,您需要允许浏览器获取您的相机权限",
"photoBoothCameraNotFoundHeadline": "无法找到相机",
"photoBoothCameraNotFoundSubheadline1": "您的设备似乎并没有相机或者相机工作不正常",
"photoBoothCameraNotFoundSubheadline2": "如果您希望使用这个应用进行拍照,请通过相机功能正常的设备访问 I\u2215O 照相馆页面。",
"photoBoothCameraErrorHeadline": "糟糕,出错儿了",
"photoBoothCameraErrorSubheadline1": "请刷新您的浏览器然后重试。",
"photoBoothCameraErrorSubheadline2": "如果问题仍一直出现,请通过邮件联系我们 [email protected]",
"photoBoothCameraNotSupportedHeadline": "糟糕,出错儿了",
"photoBoothCameraNotSupportedSubheadline": "请确保您的设备和浏览器都已更新至最新版本。",
"stickersDrawerTitle": "添加贴纸",
"openStickersTooltip": "添加贴纸",
"retakeButtonTooltip": "重拍",
"clearStickersButtonTooltip": "清除贴纸",
"charactersCaptionText": "来几个好朋友",
"sharePageLearnMoreAboutTextPart1": "您可以了解更多关于 ",
"sharePageLearnMoreAboutTextPart2": " 和 ",
"sharePageLearnMoreAboutTextPart3": ",或者更深入的了解和查看 ",
"sharePageLearnMoreAboutTextPart4": "开源代码。",
"goToGoogleIOButtonText": "查看 Google I\u2215O 内容",
"clearStickersDialogHeading": "要清除所有贴纸吗?",
"clearStickersDialogSubheading": "您是要清空屏幕上所有添加的贴纸吗?",
"clearStickersDialogCancelButtonText": "不是,请返回上一页",
"clearStickersDialogConfirmButtonText": "是的,清除所有贴纸",
"propsReminderText": "添加一些贴纸",
"stickersNextConfirmationHeading": "准备好查看您拍的照片了嘛?",
"stickersNextConfirmationSubheading": "一旦您离开这个页面,照片就不能再进行任何修改了喔。",
"stickersNextConfirmationCancelButtonText": "不要,我还需要再改改",
"stickersNextConfirmationConfirmButtonText": "可以,展示我拍的照片",
"stickersRetakeConfirmationHeading": "您确定吗?",
"stickersRetakeConfirmationSubheading": "选择重拍会让您添加的所有贴纸和朋友都被移除",
"stickersRetakeConfirmationCancelButtonText": "不要,请留在当前页面",
"stickersRetakeConfirmationConfirmButtonText": "是的,重新拍照",
"shareRetakeConfirmationHeading": "准备好拍一张新照片了吗?",
"shareRetakeConfirmationSubheading": "记得把刚拍的那张下载保存或者分享出去",
"shareRetakeConfirmationCancelButtonText": "没有,请留在当前页面",
"shareRetakeConfirmationConfirmButtonText": "是的,重新拍照",
"shutterButtonLabelText": "拍照",
"stickersNextButtonLabelText": "创建最终版的照片",
"dashButtonLabelText": "添加朋友 dash",
"sparkyButtonLabelText": "添加朋友 sparky",
"dinoButtonLabelText": "添加朋友 dino",
"androidButtonLabelText": "添加朋友 android jetpack",
"addStickersButtonLabelText": "添加贴纸",
"retakePhotoButtonLabelText": "重拍",
"clearAllStickersButtonLabelText": "清除所有贴纸"
} | photobooth/lib/l10n/arb/app_zh.arb/0 | {
"file_path": "photobooth/lib/l10n/arb/app_zh.arb",
"repo_id": "photobooth",
"token_count": 3402
} | 1,085 |
export 'bloc/photobooth_bloc.dart';
export 'view/photobooth_page.dart';
export 'widgets/widgets.dart';
| photobooth/lib/photobooth/photobooth.dart/0 | {
"file_path": "photobooth/lib/photobooth/photobooth.dart",
"repo_id": "photobooth",
"token_count": 42
} | 1,086 |
export 'animated_characters/animated_characters.dart';
export 'character_icon_button.dart';
export 'characters_caption.dart';
export 'characters_layer.dart';
export 'photobooth_background.dart';
export 'photobooth_error.dart';
export 'photobooth_photo.dart';
export 'photobooth_preview.dart';
export 'shutter_button.dart';
export 'stickers_layer.dart';
| photobooth/lib/photobooth/widgets/widgets.dart/0 | {
"file_path": "photobooth/lib/photobooth/widgets/widgets.dart",
"repo_id": "photobooth",
"token_count": 124
} | 1,087 |
import 'dart:typed_data';
import 'package:analytics/analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:platform_helper/platform_helper.dart';
class ShareButton extends StatelessWidget {
ShareButton({
required this.image,
PlatformHelper? platformHelper,
super.key,
}) : platformHelper = platformHelper ?? PlatformHelper();
/// Composited image
final Uint8List image;
/// Optional [PlatformHelper] instance.
final PlatformHelper platformHelper;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return ElevatedButton(
key: const Key('sharePage_share_elevatedButton'),
onPressed: () {
trackEvent(
category: 'button',
action: 'click-share-photo',
label: 'share-photo',
);
showAppModal<void>(
context: context,
platformHelper: platformHelper,
landscapeChild: MultiBlocProvider(
providers: [
BlocProvider.value(value: context.read<PhotoboothBloc>()),
BlocProvider.value(value: context.read<ShareBloc>()),
],
child: ShareDialog(image: image),
),
portraitChild: MultiBlocProvider(
providers: [
BlocProvider.value(value: context.read<PhotoboothBloc>()),
BlocProvider.value(value: context.read<ShareBloc>()),
],
child: ShareBottomSheet(image: image),
),
);
},
child: Text(l10n.sharePageShareButtonText),
);
}
}
| photobooth/lib/share/widgets/share_button.dart/0 | {
"file_path": "photobooth/lib/share/widgets/share_button.dart",
"repo_id": "photobooth",
"token_count": 772
} | 1,088 |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/footer/footer.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
const _initialStickerScale = 0.25;
const _minStickerScale = 0.05;
class StickersPage extends StatelessWidget {
const StickersPage({
super.key,
});
static Route<void> route() {
return AppPageRoute(builder: (_) => const StickersPage());
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => StickersBloc(),
child: const StickersView(),
);
}
}
class StickersView extends StatelessWidget {
const StickersView({super.key});
@override
Widget build(BuildContext context) {
final state = context.watch<PhotoboothBloc>().state;
final image = state.image;
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
const PhotoboothBackground(),
Center(
child: AspectRatio(
aspectRatio: state.aspectRatio,
child: Stack(
fit: StackFit.expand,
children: [
const Positioned.fill(
child: ColoredBox(color: PhotoboothColors.black),
),
if (image != null) PreviewImage(data: image.data),
const Align(
alignment: Alignment.bottomLeft,
child: Padding(
padding: EdgeInsets.only(left: 16, bottom: 24),
child: MadeWithIconLinks(),
),
),
const CharactersLayer(),
const _DraggableStickers(),
const Positioned(
left: 15,
top: 15,
child: Row(
children: [
_RetakeButton(),
ClearStickersButtonLayer(),
],
),
),
Positioned(
right: 15,
top: 15,
child: OpenStickersButton(
onPressed: () {
context
.read<StickersBloc>()
.add(const StickersDrawerToggled());
},
),
),
const Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: EdgeInsets.only(bottom: 30),
child: _NextButton(),
),
),
const Align(
alignment: Alignment.bottomCenter,
child: _StickerReminderText(),
)
],
),
),
),
const StickersDrawerLayer(),
],
),
);
}
}
class _StickerReminderText extends StatelessWidget {
const _StickerReminderText();
@override
Widget build(BuildContext context) {
final shouldDisplayPropsReminder = context.select(
(StickersBloc bloc) => bloc.state.shouldDisplayPropsReminder,
);
if (!shouldDisplayPropsReminder) return const SizedBox();
return Container(
margin: const EdgeInsets.only(bottom: 125),
child: AppTooltip.custom(
key: const Key('stickersPage_propsReminder_appTooltip'),
visible: true,
message: context.l10n.propsReminderText,
),
);
}
}
class _DraggableStickers extends StatelessWidget {
const _DraggableStickers();
@override
Widget build(BuildContext context) {
final state = context.watch<PhotoboothBloc>().state;
if (state.stickers.isEmpty) return const SizedBox();
return Stack(
fit: StackFit.expand,
children: [
Positioned.fill(
child: GestureDetector(
key: const Key('stickersView_background_gestureDetector'),
onTap: () {
context.read<PhotoboothBloc>().add(const PhotoTapped());
},
),
),
for (final sticker in state.stickers)
DraggableResizable(
key: Key('stickerPage_${sticker.id}_draggableResizable_asset'),
canTransform: sticker.id == state.selectedAssetId,
onUpdate: (update) => context
.read<PhotoboothBloc>()
.add(PhotoStickerDragged(sticker: sticker, update: update)),
onDelete: () => context
.read<PhotoboothBloc>()
.add(const PhotoDeleteSelectedStickerTapped()),
size: sticker.asset.size * _initialStickerScale,
constraints: sticker.getImageConstraints(),
child: SizedBox.expand(
child: Image.asset(
sticker.asset.path,
fit: BoxFit.fill,
gaplessPlayback: true,
),
),
),
],
);
}
}
class _RetakeButton extends StatelessWidget {
const _RetakeButton();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Semantics(
focusable: true,
button: true,
label: l10n.retakePhotoButtonLabelText,
child: AppTooltipButton(
key: const Key('stickersPage_retake_appTooltipButton'),
onPressed: () async {
final photoboothBloc = context.read<PhotoboothBloc>();
final navigator = Navigator.of(context);
final confirmed = await showAppModal<bool>(
context: context,
landscapeChild: const _RetakeConfirmationDialogContent(),
portraitChild: const _RetakeConfirmationBottomSheet(),
);
if (confirmed ?? false) {
photoboothBloc.add(const PhotoClearAllTapped());
unawaited(
navigator.pushReplacement(PhotoboothPage.route()),
);
}
},
verticalOffset: 50,
message: l10n.retakeButtonTooltip,
child: Image.asset('assets/icons/retake_button_icon.png', height: 100),
),
);
}
}
class _NextButton extends StatelessWidget {
const _NextButton();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Semantics(
focusable: true,
button: true,
label: l10n.stickersNextButtonLabelText,
child: Material(
clipBehavior: Clip.hardEdge,
shape: const CircleBorder(),
color: PhotoboothColors.transparent,
child: InkWell(
key: const Key('stickersPage_next_inkWell'),
onTap: () async {
final navigator = Navigator.of(context);
final confirmed = await showAppModal<bool>(
context: context,
landscapeChild: const _NextConfirmationDialogContent(),
portraitChild: const _NextConfirmationBottomSheet(),
);
if (confirmed ?? false) {
unawaited(navigator.pushReplacement(SharePage.route()));
}
},
child: Image.asset(
'assets/icons/go_next_button_icon.png',
height: 100,
),
),
),
);
}
}
class _RetakeConfirmationDialogContent extends StatelessWidget {
const _RetakeConfirmationDialogContent();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(60),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.stickersRetakeConfirmationHeading,
textAlign: TextAlign.center,
style: theme.textTheme.displayLarge,
),
const SizedBox(height: 24),
Text(
l10n.stickersRetakeConfirmationSubheading,
textAlign: TextAlign.center,
style: theme.textTheme.displaySmall,
),
const SizedBox(height: 24),
Wrap(
alignment: WrapAlignment.center,
spacing: 24,
runSpacing: 24,
children: [
OutlinedButton(
style: OutlinedButton.styleFrom(
side: const BorderSide(color: PhotoboothColors.black),
),
onPressed: () => Navigator.of(context).pop(false),
child: Text(
l10n.stickersRetakeConfirmationCancelButtonText,
style: theme.textTheme.labelLarge?.copyWith(
color: PhotoboothColors.black,
),
),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text(
l10n.stickersRetakeConfirmationConfirmButtonText,
),
)
],
),
],
),
),
),
);
}
}
class _RetakeConfirmationBottomSheet extends StatelessWidget {
const _RetakeConfirmationBottomSheet();
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 30),
decoration: const BoxDecoration(
color: PhotoboothColors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
),
child: Stack(
children: [
const _RetakeConfirmationDialogContent(),
Positioned(
right: 24,
top: 24,
child: IconButton(
icon: const Icon(Icons.clear, color: PhotoboothColors.black54),
onPressed: () => Navigator.of(context).pop(false),
),
),
],
),
);
}
}
class _NextConfirmationDialogContent extends StatelessWidget {
const _NextConfirmationDialogContent();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(60),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
l10n.stickersNextConfirmationHeading,
textAlign: TextAlign.center,
style: theme.textTheme.displayLarge,
),
const SizedBox(height: 24),
Text(
l10n.stickersNextConfirmationSubheading,
textAlign: TextAlign.center,
style: theme.textTheme.displaySmall,
),
const SizedBox(height: 24),
Wrap(
alignment: WrapAlignment.center,
spacing: 24,
runSpacing: 24,
children: [
OutlinedButton(
style: OutlinedButton.styleFrom(
side: const BorderSide(color: PhotoboothColors.black),
),
onPressed: () => Navigator.of(context).pop(false),
child: Text(
l10n.stickersNextConfirmationCancelButtonText,
style: theme.textTheme.labelLarge?.copyWith(
color: PhotoboothColors.black,
),
),
),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text(
l10n.stickersNextConfirmationConfirmButtonText,
),
)
],
),
],
),
),
),
);
}
}
class _NextConfirmationBottomSheet extends StatelessWidget {
const _NextConfirmationBottomSheet();
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(top: 30),
decoration: const BoxDecoration(
color: PhotoboothColors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
),
child: Stack(
children: [
const _NextConfirmationDialogContent(),
Positioned(
right: 24,
top: 24,
child: IconButton(
icon: const Icon(Icons.clear, color: PhotoboothColors.black54),
onPressed: () => Navigator.of(context).pop(false),
),
),
],
),
);
}
}
extension on PhotoAsset {
BoxConstraints getImageConstraints() {
return BoxConstraints(
minWidth: asset.size.width * _minStickerScale,
minHeight: asset.size.height * _minStickerScale,
);
}
}
class OpenStickersButton extends StatefulWidget {
const OpenStickersButton({
required this.onPressed,
super.key,
});
final VoidCallback onPressed;
@override
State<OpenStickersButton> createState() => _OpenStickersButtonState();
}
class _OpenStickersButtonState extends State<OpenStickersButton> {
bool _isAnimating = true;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final child = Semantics(
focusable: true,
button: true,
label: l10n.addStickersButtonLabelText,
child: AppTooltipButton(
key: const Key('stickersView_openStickersButton_appTooltipButton'),
onPressed: () {
widget.onPressed();
if (_isAnimating) setState(() => _isAnimating = false);
},
message: l10n.openStickersTooltip,
verticalOffset: 50,
child: Image.asset(
'assets/icons/stickers_button_icon.png',
height: 100,
),
),
);
return _isAnimating ? AnimatedPulse(child: child) : child;
}
}
| photobooth/lib/stickers/view/stickers_page.dart/0 | {
"file_path": "photobooth/lib/stickers/view/stickers_page.dart",
"repo_id": "photobooth",
"token_count": 7274
} | 1,089 |
import 'dart:js';
import 'package:flutter/foundation.dart';
/// Exposed [JsObject] for testing purposes.
@visibleForTesting
JsObject? testContext;
/// Method which tracks an event for the provided
/// [category], [action], and [label].
void trackEvent({
required String category,
required String action,
required String label,
}) {
try {
(testContext ?? context).callMethod(
'ga',
<dynamic>['send', 'event', category, action, label],
);
} catch (_) {}
}
| photobooth/packages/analytics/lib/src/analytics_web.dart/0 | {
"file_path": "photobooth/packages/analytics/lib/src/analytics_web.dart",
"repo_id": "photobooth",
"token_count": 158
} | 1,090 |
name: example
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
flutter: ">=2.0.0"
dependencies:
camera:
path: ../
flutter:
sdk: flutter
dev_dependencies:
very_good_analysis: ^4.0.0+1
flutter:
uses-material-design: true
| photobooth/packages/camera/camera/example/pubspec.yaml/0 | {
"file_path": "photobooth/packages/camera/camera/example/pubspec.yaml",
"repo_id": "photobooth",
"token_count": 117
} | 1,091 |
class CameraImage {
const CameraImage({
required this.data,
required this.width,
required this.height,
});
/// A data URI containing a representation of the image ('image/png').
final String data;
/// Is an unsigned long representing the actual height,
/// in pixels, of the image data.
final int width;
/// Is an unsigned long representing the actual width,
/// in pixels, of the image data.
final int height;
}
| photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_image.dart/0 | {
"file_path": "photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_image.dart",
"repo_id": "photobooth",
"token_count": 124
} | 1,092 |
/// Unsupported Implementation of [ImageCompositor]
class ImageCompositor {
/// Throws [UnsupportedError].
Future<List<int>> composite({
required String data,
required int width,
required int height,
required List<dynamic> layers,
required double aspectRatio,
}) {
throw UnsupportedError(
'composite is not supported for the current host platform',
);
}
}
| photobooth/packages/image_compositor/lib/src/unsupported.dart/0 | {
"file_path": "photobooth/packages/image_compositor/lib/src/unsupported.dart",
"repo_id": "photobooth",
"token_count": 127
} | 1,093 |
import 'package:flutter/widgets.dart';
/// Defines the color palette for the Photobooth UI.
abstract class PhotoboothColors {
/// Black
static const Color black = Color(0xFF202124);
/// Black 54% opacity
static const Color black54 = Color(0x8A000000);
/// Black 25% opacity
static const Color black25 = Color(0x40202124);
/// Gray
static const Color gray = Color(0xFFCFCFCF);
/// White
static const Color white = Color(0xFFFFFFFF);
/// WhiteBackground
static const Color whiteBackground = Color(0xFFE8EAED);
/// Transparent
static const Color transparent = Color(0x00000000);
/// Blue
static const Color blue = Color(0xFF428EFF);
/// Red
static const Color red = Color(0xFFFB5246);
/// Green
static const Color green = Color(0xFF3fBC5C);
/// Orange
static const Color orange = Color(0xFFFFBB00);
/// Charcoal
static const Color charcoal = Color(0xBF202124);
}
| photobooth/packages/photobooth_ui/lib/src/colors.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/colors.dart",
"repo_id": "photobooth",
"token_count": 286
} | 1,094 |
export 'font_weights.dart';
export 'text_styles.dart';
| photobooth/packages/photobooth_ui/lib/src/typography/typography.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/typography/typography.dart",
"repo_id": "photobooth",
"token_count": 20
} | 1,095 |
name: photobooth_ui
description: UI Toolkit for the Photobooth Flutter Application
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
equatable: ^2.0.5
flame: ^1.6.0
flutter:
sdk: flutter
platform_helper:
path: ../platform_helper
url_launcher: ^6.1.8
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
plugin_platform_interface: ^2.1.3
url_launcher_platform_interface: ^2.1.1
very_good_analysis: ^4.0.0+1
flutter:
fonts:
- family: GoogleSans
fonts:
- asset: assets/fonts/GoogleSans-Bold.ttf
weight: 700
- asset: assets/fonts/GoogleSans-BoldItalic.ttf
weight: 700
style: italic
- asset: assets/fonts/GoogleSans-Medium.ttf
weight: 500
- asset: assets/fonts/GoogleSans-MediumItalic.ttf
weight: 500
style: italic
- asset: assets/fonts/GoogleSans-Regular.ttf
weight: 400
- asset: assets/fonts/GoogleSans-Italic.ttf
weight: 400
style: italic
| photobooth/packages/photobooth_ui/pubspec.yaml/0 | {
"file_path": "photobooth/packages/photobooth_ui/pubspec.yaml",
"repo_id": "photobooth",
"token_count": 517
} | 1,096 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
void main() {
group('showAppDialog', () {
testWidgets('should show dialog', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => TextButton(
onPressed: () => showAppDialog<void>(
context: context,
child: const Text('dialog'),
),
child: const Text('open dialog'),
),
),
),
);
await tester.tap(find.text('open dialog'));
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsOneWidget);
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/app_dialog_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/widgets/app_dialog_test.dart",
"repo_id": "photobooth",
"token_count": 358
} | 1,097 |
// ignore_for_file: prefer_const_constructors
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 {}
void main() {
setUpAll(() {
registerFallbackValue(LaunchOptions());
});
group('IconLink', () {
testWidgets('opens link when tapped', (tester) async {
final originalUrlLauncher = UrlLauncherPlatform.instance;
final mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await tester.pumpApp(
IconLink(
link: 'https://example.com',
icon: Icon(Icons.image),
),
);
await tester.tap(find.byType(IconLink));
await tester.pumpAndSettle();
verify(() => mock.launchUrl('https://example.com', any())).called(1);
UrlLauncherPlatform.instance = originalUrlLauncher;
});
});
group('FlutterIconLink', () {
testWidgets('renders IconLink widget with a proper link', (tester) async {
await tester.pumpApp(FlutterIconLink());
final widget = tester.widget<IconLink>(find.byType(IconLink));
expect(widget.link, equals(flutterDevExternalLink));
});
});
group('FirebaseIconLink', () {
testWidgets('renders IconLink widget with a proper link', (tester) async {
await tester.pumpApp(FirebaseIconLink());
final widget = tester.widget<IconLink>(find.byType(IconLink));
expect(widget.link, equals(firebaseExternalLink));
});
});
}
| photobooth/test/app/widgets/icon_link_test.dart/0 | {
"file_path": "photobooth/test/app/widgets/icon_link_test.dart",
"repo_id": "photobooth",
"token_count": 746
} | 1,098 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:just_audio/just_audio.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import '../../helpers/helpers.dart';
class MockAnimationController extends Mock implements AnimationController {}
class MockCanvas extends Mock implements Canvas {}
class MockPaint extends Mock implements Paint {}
class RectFake extends Fake implements Rect {}
class MockAudioPlayer extends Mock implements AudioPlayer {}
void main() {
late AudioPlayer audioPlayer;
setUp(() {
audioPlayer = MockAudioPlayer();
when(() => audioPlayer.setAsset(any())).thenAnswer((_) async => null);
when(() => audioPlayer.load()).thenAnswer((_) async => null);
when(() => audioPlayer.play()).thenAnswer((_) async {});
when(() => audioPlayer.pause()).thenAnswer((_) async {});
when(() => audioPlayer.stop()).thenAnswer((_) async {});
when(() => audioPlayer.seek(any())).thenAnswer((_) async {});
when(() => audioPlayer.dispose()).thenAnswer((_) async {});
when(() => audioPlayer.playerStateStream).thenAnswer(
(_) => Stream.fromIterable(
[
PlayerState(true, ProcessingState.ready),
],
),
);
});
group('ShutterButton', () {
testWidgets('renders', (tester) async {
await tester.pumpApp(ShutterButton(onCountdownComplete: () {}));
expect(find.byType(ShutterButton), findsOneWidget);
});
testWidgets('renders CameraButton when animation has not started',
(tester) async {
await tester.pumpApp(ShutterButton(onCountdownComplete: () {}));
expect(find.byType(CameraButton), findsOneWidget);
expect(find.byType(CountdownTimer), findsNothing);
});
testWidgets('renders CountdownTimer when clicks on CameraButton with audio',
(tester) async {
await tester.runAsync(() async {
await tester.pumpApp(
ShutterButton(
onCountdownComplete: () {},
audioPlayer: () => audioPlayer,
),
);
await tester.tap(find.byType(CameraButton));
await tester.pump();
expect(find.byType(CountdownTimer), findsOneWidget);
await tester.pumpAndSettle();
verify(() => audioPlayer.setAsset(any())).called(1);
verify(() => audioPlayer.play()).called(2);
verify(() => audioPlayer.pause()).called(1);
});
});
});
group('TimerPainter', () {
late AnimationController animation;
setUp(() {
animation = MockAnimationController();
registerFallbackValue(Paint());
registerFallbackValue(const Offset(200, 200));
registerFallbackValue(RectFake());
});
test('verifies should not repaint', () async {
final timePainter = TimerPainter(animation: animation, countdown: 3);
expect(timePainter.shouldRepaint(timePainter), false);
});
test('counter is blue with value 3', () async {
final timePainter = TimerPainter(animation: animation, countdown: 3);
final blue = timePainter.calculateColor();
expect(blue, PhotoboothColors.blue);
});
test('counter is orange with value 2', () async {
final timePainter = TimerPainter(animation: animation, countdown: 2);
final blue = timePainter.calculateColor();
expect(blue, PhotoboothColors.orange);
});
test('counter is green with value 1', () async {
final timePainter = TimerPainter(animation: animation, countdown: 1);
final blue = timePainter.calculateColor();
expect(blue, PhotoboothColors.green);
});
test('verify paints correctly', () {
when(() => animation.value).thenReturn(2);
final canvas = MockCanvas();
TimerPainter(animation: animation, countdown: 3)
.paint(canvas, const Size(200, 200));
verify(() => canvas.drawCircle(any(), any(), any())).called(1);
verify(() => canvas.drawArc(any(), any(), any(), any(), any())).called(1);
});
});
}
| photobooth/test/photobooth/widgets/shutter_button_test.dart/0 | {
"file_path": "photobooth/test/photobooth/widgets/shutter_button_test.dart",
"repo_id": "photobooth",
"token_count": 1506
} | 1,099 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/share/share.dart';
import '../../helpers/helpers.dart';
void main() {
group('ShareTryAgainButton', () {
testWidgets('renders', (tester) async {
await tester.pumpApp(ShareTryAgainButton());
expect(find.byType(ShareTryAgainButton), findsOneWidget);
});
testWidgets('pops when tapped', (tester) async {
await tester.pumpApp(ShareTryAgainButton());
await tester.tap(find.byType(ShareTryAgainButton));
await tester.pumpAndSettle();
expect(find.byType(ShareTryAgainButton), findsNothing);
});
});
}
| photobooth/test/share/widgets/share_try_again_button_test.dart/0 | {
"file_path": "photobooth/test/share/widgets/share_try_again_button_test.dart",
"repo_id": "photobooth",
"token_count": 255
} | 1,100 |
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch pinball",
"request": "launch",
"type": "dart",
"program": "lib/main.dart"
},
{
"name": "Launch component sandbox",
"request": "launch",
"type": "dart",
"program": "packages/pinball_components/sandbox/lib/main.dart"
}
]
}
| pinball/.vscode/launch.json/0 | {
"file_path": "pinball/.vscode/launch.json",
"repo_id": "pinball",
"token_count": 218
} | 1,101 |
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /leaderboard/{userId} {
function prohibited(initials) {
let prohibitedInitials = get(/databases/$(database)/documents/prohibitedInitials/list).data.prohibitedInitials;
return initials in prohibitedInitials;
}
function inCharLimit(initials) {
return initials.matches('[A-Z]{3}');
}
function isValidScore(score) {
return score > 0 && score < 9999999999;
}
function isAuthedUser(auth) {
return request.auth.uid != null && auth.token.firebase.sign_in_provider == 'anonymous'
}
function isValidCharacter(character) {
return character == 'android' || character == 'dash' || character == 'dino' || character == 'sparky';
}
// Leaderboard can be read if it doesn't contain any prohibited initials
allow read: if isAuthedUser(request.auth);
// A leaderboard entry can be created if the user is authenticated,
// it's 3 characters long and capital letters only, not a
// prohibited combination, the score is within the accepted score window
// and the character is in the valid list
allow create: if isAuthedUser(request.auth) &&
inCharLimit(request.resource.data.playerInitials) &&
!prohibited(request.resource.data.playerInitials) &&
isValidScore(request.resource.data.score) &&
isValidCharacter(request.resource.data.character);
}
}
} | pinball/firestore.rules/0 | {
"file_path": "pinball/firestore.rules",
"repo_id": "pinball",
"token_count": 637
} | 1,102 |
export 'animatronic_looping_behavior.dart';
export 'ball_spawning_behavior.dart';
export 'bonus_ball_spawning_behavior.dart';
export 'bonus_noise_behavior.dart';
export 'bumper_noise_behavior.dart';
export 'camera_focusing_behavior.dart';
export 'character_selection_behavior.dart';
export 'cow_bumper_noise_behavior.dart';
export 'kicker_noise_behavior.dart';
export 'rollover_noise_behavior.dart';
export 'scoring_behavior.dart';
| pinball/lib/game/behaviors/behaviors.dart/0 | {
"file_path": "pinball/lib/game/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 151
} | 1,103 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball_components/pinball_components.dart';
/// {@template ramp_bonus_behavior}
/// Increases the score when a [Ball] is shot 10 times into the [SpaceshipRamp].
/// {@endtemplate}
class RampBonusBehavior extends Component
with FlameBlocListenable<SpaceshipRampCubit, SpaceshipRampState> {
/// {@macro ramp_bonus_behavior}
RampBonusBehavior({
required Points points,
}) : _points = points,
super();
final Points _points;
@override
bool listenWhen(
SpaceshipRampState previousState,
SpaceshipRampState newState,
) {
final hitsIncreased = previousState.hits < newState.hits;
final achievedOneMillionPoints = newState.hits % 10 == 0;
return hitsIncreased && achievedOneMillionPoints;
}
@override
void onNewState(SpaceshipRampState state) {
parent!.add(
ScoringBehavior(
points: _points,
position: Vector2(0, -60),
duration: 2,
),
);
}
}
| pinball/lib/game/components/android_acres/behaviors/ramp_bonus_behavior.dart/0 | {
"file_path": "pinball/lib/game/components/android_acres/behaviors/ramp_bonus_behavior.dart",
"repo_id": "pinball",
"token_count": 402
} | 1,104 |
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_ui/pinball_ui.dart';
final _bodyTextPaint = TextPaint(
style: const TextStyle(
fontSize: 3,
color: PinballColors.white,
fontFamily: PinballFonts.pixeloidSans,
),
);
/// {@template loading_display}
/// Display used to show the loading animation.
/// {@endtemplate}
class LoadingDisplay extends TextComponent {
/// {@template loading_display}
LoadingDisplay();
late final String _label;
@override
Future<void> onLoad() async {
await super.onLoad();
position = Vector2(0, -10);
anchor = Anchor.center;
text = _label = readProvider<AppLocalizations>().loading;
textRenderer = _bodyTextPaint;
await add(
TimerComponent(
period: 1,
repeat: true,
onTick: () {
final index = text.indexOf('.');
if (index != -1 && text.substring(index).length == 3) {
text = _label;
} else {
text = '$text.';
}
},
),
);
}
}
| pinball/lib/game/components/backbox/displays/loading_display.dart/0 | {
"file_path": "pinball/lib/game/components/backbox/displays/loading_display.dart",
"repo_id": "pinball",
"token_count": 497
} | 1,105 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flutter/material.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/google_gallery/behaviors/behaviors.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template google_gallery}
/// Middle section of the board containing the [GoogleWord] and the
/// [GoogleRollover]s.
/// {@endtemplate}
class GoogleGallery extends Component with ZIndex {
/// {@macro google_gallery}
GoogleGallery()
: super(
children: [
FlameBlocProvider<GoogleWordCubit, GoogleWordState>(
create: GoogleWordCubit.new,
children: [
GoogleRollover(
side: BoardSide.right,
children: [
ScoringContactBehavior(points: Points.fiveThousand),
RolloverNoiseBehavior(),
],
),
GoogleRollover(
side: BoardSide.left,
children: [
ScoringContactBehavior(points: Points.fiveThousand),
RolloverNoiseBehavior(),
],
),
GoogleWord(position: Vector2(-4.45, 1.8)),
GoogleWordBonusBehavior(),
],
),
],
) {
zIndex = ZIndexes.decal;
}
/// Creates a [GoogleGallery] without any children.
///
/// This can be used for testing [GoogleGallery]'s behaviors in isolation.
@visibleForTesting
GoogleGallery.test();
}
| pinball/lib/game/components/google_gallery/google_gallery.dart/0 | {
"file_path": "pinball/lib/game/components/google_gallery/google_gallery.dart",
"repo_id": "pinball",
"token_count": 782
} | 1,106 |
import 'package:flame/flame.dart';
import 'package:flame/sprite.dart';
import 'package:flutter/material.dart' hide Image;
import 'package:pinball/gen/assets.gen.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template bonus_animation}
/// [Widget] that displays bonus animations.
/// {@endtemplate}
class BonusAnimation extends StatefulWidget {
/// {@macro bonus_animation}
const BonusAnimation._(
String imagePath, {
VoidCallback? onCompleted,
Key? key,
}) : _imagePath = imagePath,
_onCompleted = onCompleted,
super(key: key);
/// [Widget] that displays the dash nest animation.
BonusAnimation.dashNest({
Key? key,
VoidCallback? onCompleted,
}) : this._(
Assets.images.bonusAnimation.dashNest.keyName,
onCompleted: onCompleted,
key: key,
);
/// [Widget] that displays the sparky turbo charge animation.
BonusAnimation.sparkyTurboCharge({
Key? key,
VoidCallback? onCompleted,
}) : this._(
Assets.images.bonusAnimation.sparkyTurboCharge.keyName,
onCompleted: onCompleted,
key: key,
);
/// [Widget] that displays the dino chomp animation.
BonusAnimation.dinoChomp({
Key? key,
VoidCallback? onCompleted,
}) : this._(
Assets.images.bonusAnimation.dinoChomp.keyName,
onCompleted: onCompleted,
key: key,
);
/// [Widget] that displays the android spaceship animation.
BonusAnimation.androidSpaceship({
Key? key,
VoidCallback? onCompleted,
}) : this._(
Assets.images.bonusAnimation.androidSpaceship.keyName,
onCompleted: onCompleted,
key: key,
);
/// [Widget] that displays the google word animation.
BonusAnimation.googleWord({
Key? key,
VoidCallback? onCompleted,
}) : this._(
Assets.images.bonusAnimation.googleWord.keyName,
onCompleted: onCompleted,
key: key,
);
final String _imagePath;
final VoidCallback? _onCompleted;
/// Returns a list of assets to be loaded for animations.
static List<Future Function()> loadAssets() {
Flame.images.prefix = '';
return [
() => Flame.images.load(Assets.images.bonusAnimation.dashNest.keyName),
() => Flame.images
.load(Assets.images.bonusAnimation.sparkyTurboCharge.keyName),
() => Flame.images.load(Assets.images.bonusAnimation.dinoChomp.keyName),
() => Flame.images
.load(Assets.images.bonusAnimation.androidSpaceship.keyName),
() => Flame.images.load(Assets.images.bonusAnimation.googleWord.keyName),
];
}
@override
State<BonusAnimation> createState() => _BonusAnimationState();
}
class _BonusAnimationState extends State<BonusAnimation>
with TickerProviderStateMixin {
late SpriteAnimationController controller;
late SpriteAnimation animation;
bool shouldRunBuildCallback = true;
@override
void dispose() {
controller.dispose();
super.dispose();
}
// When the animation is overwritten by another animation, we need to stop
// the callback in the build method as it will break the new animation.
// Otherwise we need to set up a new callback when a new animation starts to
// show the score view at the end of the animation.
@override
void didUpdateWidget(BonusAnimation oldWidget) {
shouldRunBuildCallback = oldWidget._imagePath == widget._imagePath;
Future<void>.delayed(
Duration(seconds: animation.totalDuration().ceil()),
() {
widget._onCompleted?.call();
},
);
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
final spriteSheet = SpriteSheet.fromColumnsAndRows(
image: Flame.images.fromCache(widget._imagePath),
columns: 8,
rows: 9,
);
animation = spriteSheet.createAnimation(
row: 0,
stepTime: 1 / 12,
to: spriteSheet.rows * spriteSheet.columns,
loop: false,
);
Future<void>.delayed(
Duration(seconds: animation.totalDuration().ceil()),
() {
if (shouldRunBuildCallback) {
widget._onCompleted?.call();
}
},
);
controller = SpriteAnimationController(
animation: animation,
vsync: this,
)..forward();
return SizedBox(
width: double.infinity,
height: double.infinity,
child: SpriteAnimationWidget(
controller: controller,
),
);
}
}
| pinball/lib/game/view/widgets/bonus_animation.dart/0 | {
"file_path": "pinball/lib/game/view/widgets/bonus_animation.dart",
"repo_id": "pinball",
"token_count": 1665
} | 1,107 |
import 'package:equatable/equatable.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball_theme/pinball_theme.dart';
/// {@template leaderboard_entry}
/// A model representing a leaderboard entry containing the ranking position,
/// player's initials, score, and chosen character.
///
/// {@endtemplate}
class LeaderboardEntry extends Equatable {
/// {@macro leaderboard_entry}
const LeaderboardEntry({
required this.rank,
required this.playerInitials,
required this.score,
required this.character,
});
/// Ranking position for [LeaderboardEntry].
final String rank;
/// Player's chosen initials for [LeaderboardEntry].
final String playerInitials;
/// Score for [LeaderboardEntry].
final int score;
/// [CharacterTheme] for [LeaderboardEntry].
final AssetGenImage character;
@override
List<Object?> get props => [rank, playerInitials, score, character];
}
/// Converts [LeaderboardEntryData] from repository to [LeaderboardEntry].
extension LeaderboardEntryDataX on LeaderboardEntryData {
/// Conversion method to [LeaderboardEntry]
LeaderboardEntry toEntry(int position) {
return LeaderboardEntry(
rank: position.toString(),
playerInitials: playerInitials,
score: score,
character: character.toTheme.leaderboardIcon,
);
}
}
/// Converts [CharacterType] to [CharacterTheme] to show on UI character theme
/// from repository.
extension CharacterTypeX on CharacterType {
/// Conversion method to [CharacterTheme]
CharacterTheme get toTheme {
switch (this) {
case CharacterType.dash:
return const DashTheme();
case CharacterType.sparky:
return const SparkyTheme();
case CharacterType.android:
return const AndroidTheme();
case CharacterType.dino:
return const DinoTheme();
}
}
}
/// Converts [CharacterTheme] to [CharacterType] to persist at repository the
/// character theme from UI.
extension CharacterThemeX on CharacterTheme {
/// Conversion method to [CharacterType]
CharacterType get toType {
switch (runtimeType) {
case DashTheme:
return CharacterType.dash;
case SparkyTheme:
return CharacterType.sparky;
case AndroidTheme:
return CharacterType.android;
case DinoTheme:
return CharacterType.dino;
default:
return CharacterType.dash;
}
}
}
| pinball/lib/leaderboard/models/leader_board_entry.dart/0 | {
"file_path": "pinball/lib/leaderboard/models/leader_board_entry.dart",
"repo_id": "pinball",
"token_count": 773
} | 1,108 |
# authentication_repository
[![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link]
[![License: MIT][license_badge]][license_link]
Repository to manage user authentication.
[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/authentication_repository/README.md/0 | {
"file_path": "pinball/packages/authentication_repository/README.md",
"repo_id": "pinball",
"token_count": 168
} | 1,109 |
library leaderboard_repository;
export 'src/leaderboard_repository.dart';
export 'src/models/models.dart';
| pinball/packages/leaderboard_repository/lib/leaderboard_repository.dart/0 | {
"file_path": "pinball/packages/leaderboard_repository/lib/leaderboard_repository.dart",
"repo_id": "pinball",
"token_count": 37
} | 1,110 |
// ignore_for_file: prefer_const_constructors, one_member_abstracts
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_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_audio/gen/assets.gen.dart';
import 'package:pinball_audio/pinball_audio.dart';
class _MockAudioPool extends Mock implements AudioPool {}
class _MockAudioCache extends Mock implements AudioCache {}
class _MockCreateAudioPool extends Mock {
Future<AudioPool> onCall(
String sound, {
bool? repeating,
int? maxPlayers,
int? minPlayers,
String? prefix,
});
}
class _MockConfigureAudioCache extends Mock {
void onCall(AudioCache cache);
}
class _MockPlaySingleAudio extends Mock {
Future<void> onCall(String path, {double volume});
}
class _MockLoopSingleAudio extends Mock {
Future<void> onCall(String path, {double volume});
}
abstract class _PreCacheSingleAudio {
Future<void> onCall(String path);
}
class _MockPreCacheSingleAudio extends Mock implements _PreCacheSingleAudio {}
class _MockRandom extends Mock implements Random {}
class _MockClock extends Mock implements Clock {}
void main() {
group('PinballAudio', () {
late _MockCreateAudioPool createAudioPool;
late _MockConfigureAudioCache configureAudioCache;
late _MockPlaySingleAudio playSingleAudio;
late _MockLoopSingleAudio loopSingleAudio;
late _PreCacheSingleAudio preCacheSingleAudio;
late Random seed;
late PinballAudioPlayer audioPlayer;
setUpAll(() {
registerFallbackValue(_MockAudioCache());
});
setUp(() {
createAudioPool = _MockCreateAudioPool();
when(
() => createAudioPool.onCall(
any(),
maxPlayers: any(named: 'maxPlayers'),
prefix: any(named: 'prefix'),
),
).thenAnswer((_) async => _MockAudioPool());
configureAudioCache = _MockConfigureAudioCache();
when(() => configureAudioCache.onCall(any())).thenAnswer((_) {});
playSingleAudio = _MockPlaySingleAudio();
when(() => playSingleAudio.onCall(any(), volume: any(named: 'volume')))
.thenAnswer((_) async {});
loopSingleAudio = _MockLoopSingleAudio();
when(() => loopSingleAudio.onCall(any(), volume: any(named: 'volume')))
.thenAnswer((_) async {});
preCacheSingleAudio = _MockPreCacheSingleAudio();
when(() => preCacheSingleAudio.onCall(any())).thenAnswer((_) async {});
seed = _MockRandom();
audioPlayer = PinballAudioPlayer(
configureAudioCache: configureAudioCache.onCall,
createAudioPool: createAudioPool.onCall,
playSingleAudio: playSingleAudio.onCall,
loopSingleAudio: loopSingleAudio.onCall,
preCacheSingleAudio: preCacheSingleAudio.onCall,
seed: seed,
);
});
test('can be instantiated', () {
expect(PinballAudioPlayer(), isNotNull);
});
group('load', () {
test('creates the bumpers pools', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
verify(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.bumperA}',
maxPlayers: 4,
prefix: '',
),
).called(1);
verify(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.bumperB}',
maxPlayers: 4,
prefix: '',
),
).called(1);
});
test('creates the kicker pools', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
verify(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.kickerA}',
maxPlayers: 4,
prefix: '',
),
).called(1);
verify(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.kickerB}',
maxPlayers: 4,
prefix: '',
),
).called(1);
});
test('creates the flipper pool', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
verify(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.flipper}',
maxPlayers: 2,
prefix: '',
),
).called(1);
});
test('configures the audio cache instance', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
verify(() => configureAudioCache.onCall(FlameAudio.audioCache))
.called(1);
});
test('sets the correct prefix', () async {
audioPlayer = PinballAudioPlayer(
createAudioPool: createAudioPool.onCall,
playSingleAudio: playSingleAudio.onCall,
preCacheSingleAudio: preCacheSingleAudio.onCall,
);
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
expect(FlameAudio.audioCache.prefix, equals(''));
});
test('pre cache the assets', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/google.mp3'),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/sparky.mp3'),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/dino.mp3'),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/android.mp3'),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/dash.mp3'),
).called(1);
verify(
() => preCacheSingleAudio.onCall(
'packages/pinball_audio/assets/sfx/io_pinball_voice_over.mp3',
),
).called(1);
verify(
() => preCacheSingleAudio.onCall(
'packages/pinball_audio/assets/sfx/game_over_voice_over.mp3',
),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/launcher.mp3'),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/rollover.mp3'),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/cow_moo.mp3'),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/music/background.mp3'),
).called(1);
});
});
group('bumper', () {
late AudioPool bumperAPool;
late AudioPool bumperBPool;
setUp(() {
bumperAPool = _MockAudioPool();
when(() => bumperAPool.start(volume: any(named: 'volume')))
.thenAnswer((_) async => () {});
when(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.bumperA}',
maxPlayers: any(named: 'maxPlayers'),
prefix: any(named: 'prefix'),
),
).thenAnswer((_) async => bumperAPool);
bumperBPool = _MockAudioPool();
when(() => bumperBPool.start(volume: any(named: 'volume')))
.thenAnswer((_) async => () {});
when(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.bumperB}',
maxPlayers: any(named: 'maxPlayers'),
prefix: any(named: 'prefix'),
),
).thenAnswer((_) async => bumperBPool);
});
group('when seed is true', () {
test('plays the bumper A sound pool', () async {
when(seed.nextBool).thenReturn(true);
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.bumper);
verify(() => bumperAPool.start(volume: 0.6)).called(1);
});
});
group('when seed is false', () {
test('plays the bumper B sound pool', () async {
when(seed.nextBool).thenReturn(false);
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.bumper);
verify(() => bumperBPool.start(volume: 0.6)).called(1);
});
});
});
group('kicker', () {
late AudioPool kickerAPool;
late AudioPool kickerBPool;
setUp(() {
kickerAPool = _MockAudioPool();
when(() => kickerAPool.start(volume: any(named: 'volume')))
.thenAnswer((_) async => () {});
when(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.kickerA}',
maxPlayers: any(named: 'maxPlayers'),
prefix: any(named: 'prefix'),
),
).thenAnswer((_) async => kickerAPool);
kickerBPool = _MockAudioPool();
when(() => kickerBPool.start(volume: any(named: 'volume')))
.thenAnswer((_) async => () {});
when(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.kickerB}',
maxPlayers: any(named: 'maxPlayers'),
prefix: any(named: 'prefix'),
),
).thenAnswer((_) async => kickerBPool);
});
group('when seed is true', () {
test('plays the kicker A sound pool', () async {
when(seed.nextBool).thenReturn(true);
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.kicker);
verify(() => kickerAPool.start(volume: 0.6)).called(1);
});
});
group('when seed is false', () {
test('plays the kicker B sound pool', () async {
when(seed.nextBool).thenReturn(false);
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.kicker);
verify(() => kickerBPool.start(volume: 0.6)).called(1);
});
});
});
group('flipper', () {
late AudioPool pool;
setUp(() {
pool = _MockAudioPool();
when(() => pool.start(volume: any(named: 'volume')))
.thenAnswer((_) async => () {});
when(
() => createAudioPool.onCall(
'packages/pinball_audio/${Assets.sfx.flipper}',
maxPlayers: any(named: 'maxPlayers'),
prefix: any(named: 'prefix'),
),
).thenAnswer((_) async => pool);
});
test('plays the flipper sound pool', () async {
when(seed.nextBool).thenReturn(true);
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.flipper);
verify(() => pool.start()).called(1);
});
});
group('cow moo', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.cowMoo);
verify(
() => playSingleAudio
.onCall('packages/pinball_audio/${Assets.sfx.cowMoo}'),
).called(1);
});
test('only plays the sound again after 2 seconds', () async {
final clock = _MockClock();
await withClock(clock, () async {
when(clock.now).thenReturn(DateTime(2022));
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer
..play(PinballAudio.cowMoo)
..play(PinballAudio.cowMoo);
verify(
() => playSingleAudio
.onCall('packages/pinball_audio/${Assets.sfx.cowMoo}'),
).called(1);
when(clock.now).thenReturn(DateTime(2022, 1, 1, 1, 2));
audioPlayer.play(PinballAudio.cowMoo);
verify(
() => playSingleAudio
.onCall('packages/pinball_audio/${Assets.sfx.cowMoo}'),
).called(1);
});
});
});
group('google', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.google);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.google}',
volume: any(named: 'volume'),
),
).called(1);
});
});
group('sparky', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.sparky);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.sparky}',
volume: any(named: 'volume'),
),
).called(1);
});
});
group('dino', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.dino);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.dino}',
volume: any(named: 'volume'),
),
).called(1);
});
test('only plays the sound again after 6 seconds', () async {
final clock = _MockClock();
await withClock(clock, () async {
when(clock.now).thenReturn(DateTime(2022));
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer
..play(PinballAudio.dino)
..play(PinballAudio.dino);
verify(
() => playSingleAudio
.onCall('packages/pinball_audio/${Assets.sfx.dino}'),
).called(1);
when(clock.now).thenReturn(DateTime(2022, 1, 1, 1, 6));
audioPlayer.play(PinballAudio.dino);
verify(
() => playSingleAudio
.onCall('packages/pinball_audio/${Assets.sfx.dino}'),
).called(1);
});
});
});
group('android', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.android);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.android}',
volume: any(named: 'volume'),
),
).called(1);
});
});
group('dash', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.dash);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.dash}',
volume: any(named: 'volume'),
),
).called(1);
});
});
group('launcher', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.launcher);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.launcher}',
volume: any(named: 'volume'),
),
).called(1);
});
});
group('rollover', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.rollover);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.rollover}',
volume: .3,
),
).called(1);
});
});
group('ioPinballVoiceOver', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.ioPinballVoiceOver);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.ioPinballVoiceOver}',
volume: any(named: 'volume'),
),
).called(1);
});
});
group('gameOverVoiceOver', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.gameOverVoiceOver);
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.gameOverVoiceOver}',
volume: any(named: 'volume'),
),
).called(1);
});
});
group('backgroundMusic', () {
test('plays the correct file', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer.play(PinballAudio.backgroundMusic);
verify(
() => loopSingleAudio.onCall(
'packages/pinball_audio/${Assets.music.background}',
volume: .6,
),
).called(1);
});
test('plays only once', () async {
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
audioPlayer
..play(PinballAudio.backgroundMusic)
..play(PinballAudio.backgroundMusic);
verify(
() => loopSingleAudio.onCall(
'packages/pinball_audio/${Assets.music.background}',
volume: .6,
),
).called(1);
});
});
test(
'throws assertions error when playing an unregistered audio',
() async {
audioPlayer.audios.remove(PinballAudio.google);
await Future.wait(
audioPlayer.load().map((loadableBuilder) => loadableBuilder()),
);
expect(
() => audioPlayer.play(PinballAudio.google),
throwsAssertionError,
);
},
);
});
}
| pinball/packages/pinball_audio/test/src/pinball_audio_test.dart/0 | {
"file_path": "pinball/packages/pinball_audio/test/src/pinball_audio_test.dart",
"repo_id": "pinball",
"token_count": 8754
} | 1,111 |
export 'android_animatronic_ball_contact_behavior.dart.dart';
| pinball/packages/pinball_components/lib/src/components/android_animatronic/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/android_animatronic/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 21
} | 1,112 |
import 'package:flame/components.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template ball_impulsing_behavior}
/// Impulses the [Ball] in a given direction.
/// {@endtemplate}
class BallImpulsingBehavior extends Component with ParentIsA<Ball> {
/// {@macro ball_impulsing_behavior}
BallImpulsingBehavior({
required Vector2 impulse,
}) : _impulse = impulse;
final Vector2 _impulse;
@override
Future<void> onLoad() async {
await super.onLoad();
parent.body.linearVelocity = _impulse;
shouldRemove = true;
}
}
| pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_impulsing_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_impulsing_behavior.dart",
"repo_id": "pinball",
"token_count": 212
} | 1,113 |
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_spitting_behavior}
/// Spits the [Ball] from the [ChromeDino] the next time the mouth opens.
/// {@endtemplate}
class ChromeDinoSpittingBehavior extends Component
with ContactCallbacks, ParentIsA<ChromeDino> {
bool _waitingForSwivel = true;
void _onNewState(ChromeDinoState state) {
if (state.status == ChromeDinoStatus.chomping) {
if (state.isMouthOpen && !_waitingForSwivel) {
add(
TimerComponent(
period: 0.4,
onTick: _spit,
removeOnFinish: true,
),
);
_waitingForSwivel = true;
}
if (_waitingForSwivel && !state.isMouthOpen) {
_waitingForSwivel = false;
}
}
}
void _spit() {
parent.bloc.state.ball!
..descendants().whereType<SpriteComponent>().single.setOpacity(1)
..body.linearVelocity = Vector2(-50, 0);
parent.bloc.onSpit();
}
@override
Future<void> onLoad() async {
await super.onLoad();
parent.bloc.stream.listen(_onNewState);
}
}
| pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_spitting_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_spitting_behavior.dart",
"repo_id": "pinball",
"token_count": 535
} | 1,114 |
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/flapper/behaviors/behaviors.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template flapper}
/// Flap to let a [Ball] out of the [LaunchRamp] and to prevent [Ball]s from
/// going back in.
/// {@endtemplate}
class Flapper extends Component {
/// {@macro flapper}
Flapper()
: super(
children: [
FlapperEntrance(
children: [
FlapperSpinningBehavior(),
],
)..initialPosition = Vector2(3.8, -69.3),
_FlapperStructure(),
_FlapperExit()..initialPosition = Vector2(-0.8, -33.8),
_BackSupportSpriteComponent(),
_FrontSupportSpriteComponent(),
FlapSpriteAnimationComponent(),
],
);
/// Creates a [Flapper] without any children.
///
/// This can be used for testing [Flapper]'s behaviors in isolation.
@visibleForTesting
Flapper.test();
}
/// {@template flapper_entrance}
/// Sensor used in [FlapperSpinningBehavior] to animate
/// [FlapSpriteAnimationComponent].
/// {@endtemplate}
class FlapperEntrance extends BodyComponent with InitialPosition, Layered {
/// {@macro flapper_entrance}
FlapperEntrance({
Iterable<Component>? children,
}) : super(
children: children,
renderBody: false,
) {
layer = Layer.launcher;
}
@override
Body createBody() {
final shape = EdgeShape()
..set(
Vector2.zero(),
Vector2(0, 3.2),
);
final fixtureDef = FixtureDef(
shape,
isSensor: true,
);
final bodyDef = BodyDef(position: initialPosition);
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
}
class _FlapperStructure extends BodyComponent with Layered {
_FlapperStructure() : super(renderBody: false) {
layer = Layer.board;
}
List<FixtureDef> _createFixtureDefs() {
final leftEdgeShape = EdgeShape()
..set(
Vector2(1.7, -69.3),
Vector2(1.7, -66),
);
final bottomEdgeShape = EdgeShape()
..set(
leftEdgeShape.vertex2,
Vector2(3.7, -66),
);
return [
FixtureDef(leftEdgeShape),
FixtureDef(bottomEdgeShape),
];
}
@override
Body createBody() {
final body = world.createBody(BodyDef());
_createFixtureDefs().forEach(body.createFixture);
return body;
}
}
class _FlapperExit extends LayerSensor {
_FlapperExit()
: super(
insideLayer: Layer.launcher,
outsideLayer: Layer.board,
orientation: LayerEntranceOrientation.down,
insideZIndex: ZIndexes.ballOnLaunchRamp,
outsideZIndex: ZIndexes.ballOnBoard,
) {
layer = Layer.launcher;
}
@override
Shape get shape => PolygonShape()
..setAsBox(
1.7,
0.1,
initialPosition,
1.5708,
);
}
/// {@template flap_sprite_animation_component}
/// Flap suspended between supports that animates to let the [Ball] exit the
/// [LaunchRamp].
/// {@endtemplate}
@visibleForTesting
class FlapSpriteAnimationComponent extends SpriteAnimationComponent
with HasGameRef, ZIndex {
/// {@macro flap_sprite_animation_component}
FlapSpriteAnimationComponent()
: super(
anchor: Anchor.center,
position: Vector2(2.6, -70.7),
playing: false,
) {
zIndex = ZIndexes.flapper;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final spriteSheet = gameRef.images.fromCache(
Assets.images.flapper.flap.keyName,
);
const amountPerRow = 14;
const amountPerColumn = 1;
final textureSize = Vector2(
spriteSheet.width / amountPerRow,
spriteSheet.height / amountPerColumn,
);
size = textureSize / 10;
animation = SpriteAnimation.fromFrameData(
spriteSheet,
SpriteAnimationData.sequenced(
amount: amountPerRow * amountPerColumn,
amountPerRow: amountPerRow,
stepTime: 1 / 24,
textureSize: textureSize,
loop: false,
),
)..onComplete = () {
animation?.reset();
playing = false;
};
}
}
class _BackSupportSpriteComponent extends SpriteComponent
with HasGameRef, ZIndex {
_BackSupportSpriteComponent()
: super(
anchor: Anchor.center,
position: Vector2(2.75, -70.6),
) {
zIndex = ZIndexes.flapperBack;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(
Assets.images.flapper.backSupport.keyName,
),
);
this.sprite = sprite;
size = sprite.originalSize / 10;
}
}
class _FrontSupportSpriteComponent extends SpriteComponent
with HasGameRef, ZIndex {
_FrontSupportSpriteComponent()
: super(
anchor: Anchor.center,
position: Vector2(2.7, -67.7),
) {
zIndex = ZIndexes.flapperFront;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(
Assets.images.flapper.frontSupport.keyName,
),
);
this.sprite = sprite;
size = sprite.originalSize / 10;
}
}
| pinball/packages/pinball_components/lib/src/components/flapper/flapper.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/flapper/flapper.dart",
"repo_id": "pinball",
"token_count": 2249
} | 1,115 |
part of 'google_word_cubit.dart';
class GoogleWordState extends Equatable {
const GoogleWordState({required this.letterSpriteStates});
GoogleWordState.initial()
: this(
letterSpriteStates: {
for (var i = 0; i <= 5; i++) i: GoogleLetterSpriteState.dimmed
},
);
final Map<int, GoogleLetterSpriteState> letterSpriteStates;
@override
List<Object> get props => [...letterSpriteStates.values];
}
| pinball/packages/pinball_components/lib/src/components/google_word/cubit/google_word_state.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/google_word/cubit/google_word_state.dart",
"repo_id": "pinball",
"token_count": 171
} | 1,116 |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
part 'multiball_state.dart';
class MultiballCubit extends Cubit<MultiballState> {
MultiballCubit() : super(const MultiballState.initial());
void onAnimate() {
emit(
state.copyWith(animationState: MultiballAnimationState.blinking),
);
}
void onStop() {
emit(
state.copyWith(animationState: MultiballAnimationState.idle),
);
}
void onBlink() {
switch (state.lightState) {
case MultiballLightState.lit:
emit(
state.copyWith(lightState: MultiballLightState.dimmed),
);
break;
case MultiballLightState.dimmed:
emit(
state.copyWith(lightState: MultiballLightState.lit),
);
break;
}
}
}
| pinball/packages/pinball_components/lib/src/components/multiball/cubit/multiball_cubit.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/multiball/cubit/multiball_cubit.dart",
"repo_id": "pinball",
"token_count": 341
} | 1,117 |
export 'score_component_scaling_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/score_component/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/score_component/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 15
} | 1,118 |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
part 'spaceship_ramp_state.dart';
class SpaceshipRampCubit extends Cubit<SpaceshipRampState> {
SpaceshipRampCubit() : super(const SpaceshipRampState.initial());
void onAscendingBallEntered() => emit(state.copyWith(hits: state.hits + 1));
void onProgressed() {
final index = ArrowLightState.values.indexOf(state.lightState);
emit(
state.copyWith(
lightState:
ArrowLightState.values[(index + 1) % ArrowLightState.values.length],
),
);
}
void onReset() => emit(const SpaceshipRampState.initial());
}
| pinball/packages/pinball_components/lib/src/components/spaceship_ramp/cubit/spaceship_ramp_cubit.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/spaceship_ramp/cubit/spaceship_ramp_cubit.dart",
"repo_id": "pinball",
"token_count": 241
} | 1,119 |
export 'score.dart';
| pinball/packages/pinball_components/lib/src/extensions/extensions.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/extensions/extensions.dart",
"repo_id": "pinball",
"token_count": 8
} | 1,120 |
import 'dart:async';
import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class AndroidBumperBGame extends BallGame {
AndroidBumperBGame()
: super(
imagesFileNames: [
Assets.images.android.bumper.b.lit.keyName,
Assets.images.android.bumper.b.dimmed.keyName,
],
);
static const description = '''
Shows how a AndroidBumperB is rendered.
- Activate the "trace" parameter to overlay the body.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
camera.followVector2(Vector2.zero());
await add(
AndroidBumper.b()..priority = 1,
);
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_bumper_b_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_bumper_b_game.dart",
"repo_id": "pinball",
"token_count": 311
} | 1,121 |
import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class BoundariesGame extends BallGame {
BoundariesGame()
: super(
imagesFileNames: [
Assets.images.boundary.outer.keyName,
Assets.images.boundary.outerBottom.keyName,
Assets.images.boundary.bottom.keyName,
],
);
static const description = '''
Shows how Boundaries are rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a ball into the game.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
camera
..followVector2(Vector2.zero())
..zoom = 6;
await add(Boundaries());
await ready();
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/boundaries/boundaries_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/boundaries/boundaries_game.dart",
"repo_id": "pinball",
"token_count": 334
} | 1,122 |
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/google_word/google_letter_game.dart';
void addGoogleWordStories(Dashbook dashbook) {
dashbook.storiesOf('Google Word').addGame(
title: 'Letter 0',
description: GoogleLetterGame.description,
gameBuilder: (_) => GoogleLetterGame(),
);
}
| pinball/packages/pinball_components/sandbox/lib/stories/google_word/stories.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/google_word/stories.dart",
"repo_id": "pinball",
"token_count": 138
} | 1,123 |
export 'android_acres/stories.dart';
export 'arrow_icon/stories.dart';
export 'ball/stories.dart';
export 'bottom_group/stories.dart';
export 'boundaries/stories.dart';
export 'dino_desert/stories.dart';
export 'effects/stories.dart';
export 'error_component/stories.dart';
export 'flutter_forest/stories.dart';
export 'google_word/stories.dart';
export 'launch_ramp/stories.dart';
export 'layer/stories.dart';
export 'multiball/stories.dart';
export 'multipliers/stories.dart';
export 'plunger/stories.dart';
export 'score/stories.dart';
export 'sparky_scorch/stories.dart';
| pinball/packages/pinball_components/sandbox/lib/stories/stories.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/stories.dart",
"repo_id": "pinball",
"token_count": 203
} | 1,124 |
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/android_bumper/behaviors/behaviors.dart';
import '../../../../helpers/helpers.dart';
class _MockAndroidBumperCubit extends Mock implements AndroidBumperCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
group(
'AndroidBumperBlinkingBehavior',
() {
flameTester.testGameWidget(
'calls onBlinked after 0.05 seconds when dimmed',
setUp: (game, tester) async {
final behavior = AndroidBumperBlinkingBehavior();
final bloc = _MockAndroidBumperCubit();
final streamController = StreamController<AndroidBumperState>();
whenListen(
bloc,
streamController.stream,
initialState: AndroidBumperState.lit,
);
final androidBumper = AndroidBumper.test(bloc: bloc);
await androidBumper.add(behavior);
await game.ensureAdd(androidBumper);
streamController.add(AndroidBumperState.dimmed);
await tester.pump();
game.update(0.05);
await streamController.close();
verify(bloc.onBlinked).called(1);
},
);
},
);
}
| pinball/packages/pinball_components/test/src/components/android_bumper/behaviors/android_bumper_blinking_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/android_bumper/behaviors/android_bumper_blinking_behavior_test.dart",
"repo_id": "pinball",
"token_count": 617
} | 1,125 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import '../../helpers/helpers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.boardBackground.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('BoardBackgroundSpriteComponent', () {
flameTester.test(
'loads correctly',
(game) async {
final boardBackground = BoardBackgroundSpriteComponent();
await game.ensureAdd(boardBackground);
expect(game.contains(boardBackground), isTrue);
},
);
flameTester.testGameWidget(
'renders correctly',
setUp: (game, tester) async {
await game.images.loadAll(assets);
final boardBackground = BoardBackgroundSpriteComponent();
await game.ensureAdd(boardBackground);
await tester.pump();
game.camera
..followVector2(Vector2.zero())
..zoom = 3.7;
},
verify: (game, tester) async {
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/board_background.png'),
);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/board_background_sprite_component_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/board_background_sprite_component_test.dart",
"repo_id": "pinball",
"token_count": 530
} | 1,126 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import '../../helpers/helpers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final asset = Assets.images.dash.animatronic.keyName;
final flameTester = FlameTester(() => TestGame([asset]));
group('DashAnimatronic', () {
flameTester.testGameWidget(
'renders correctly',
setUp: (game, tester) async {
await game.images.load(asset);
await game.ensureAdd(DashAnimatronic()..playing = true);
game.camera.followVector2(Vector2.zero());
await tester.pump();
},
verify: (game, tester) async {
final animationDuration =
game.firstChild<DashAnimatronic>()!.animation!.totalDuration();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/dash_animatronic/start.png'),
);
game.update(animationDuration * 0.25);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/dash_animatronic/middle.png'),
);
game.update(animationDuration * 0.75);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/dash_animatronic/end.png'),
);
},
);
flameTester.test(
'loads correctly',
(game) async {
final dashAnimatronic = DashAnimatronic();
await game.ensureAdd(dashAnimatronic);
expect(game.contains(dashAnimatronic), isTrue);
},
);
flameTester.test('adds new children', (game) async {
final component = Component();
final dashAnimatronic = DashAnimatronic(
children: [component],
);
await game.ensureAdd(dashAnimatronic);
expect(dashAnimatronic.children, contains(component));
});
});
}
| pinball/packages/pinball_components/test/src/components/dash_animatronic_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/dash_animatronic_test.dart",
"repo_id": "pinball",
"token_count": 852
} | 1,127 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/google_rollover/behaviors/behaviors.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.googleRollover.left.decal.keyName,
Assets.images.googleRollover.left.pin.keyName,
]);
}
Future<void> pump(
GoogleRollover child, {
GoogleWordCubit? bloc,
}) async {
// Not needed once https://github.com/flame-engine/flame/issues/1607
// is fixed
await onLoad();
await ensureAdd(
FlameBlocProvider<GoogleWordCubit, GoogleWordState>.value(
value: bloc ?? GoogleWordCubit(),
children: [child],
),
);
}
}
class _MockBall extends Mock implements Ball {}
class _MockContact extends Mock implements Contact {}
class _MockGoogleWordCubit extends Mock implements GoogleWordCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group(
'GoogleRolloverBallContactBehavior',
() {
test('can be instantiated', () {
expect(
GoogleRolloverBallContactBehavior(),
isA<GoogleRolloverBallContactBehavior>(),
);
});
flameTester.testGameWidget(
'beginContact animates pin and calls onRolloverContacted '
'when contacts with a ball',
setUp: (game, tester) async {
final behavior = GoogleRolloverBallContactBehavior();
final bloc = _MockGoogleWordCubit();
final googleRollover = GoogleRollover(side: BoardSide.left);
await googleRollover.add(behavior);
await game.pump(googleRollover, bloc: bloc);
behavior.beginContact(_MockBall(), _MockContact());
await tester.pump();
expect(
googleRollover.firstChild<SpriteAnimationComponent>()!.playing,
isTrue,
);
verify(bloc.onRolloverContacted).called(1);
},
);
},
);
}
| pinball/packages/pinball_components/test/src/components/google_rollover/behaviors/google_rollover_ball_contact_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/google_rollover/behaviors/google_rollover_ball_contact_behavior_test.dart",
"repo_id": "pinball",
"token_count": 938
} | 1,128 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group(
'MultiballCubit',
() {
blocTest<MultiballCubit, MultiballState>(
'onAnimate emits animationState [animate]',
build: MultiballCubit.new,
act: (bloc) => bloc.onAnimate(),
expect: () => [
isA<MultiballState>()
..having(
(state) => state.animationState,
'animationState',
MultiballAnimationState.blinking,
)
],
);
blocTest<MultiballCubit, MultiballState>(
'onStop emits animationState [stopped]',
build: MultiballCubit.new,
act: (bloc) => bloc.onStop(),
expect: () => [
isA<MultiballState>()
..having(
(state) => state.animationState,
'animationState',
MultiballAnimationState.idle,
)
],
);
blocTest<MultiballCubit, MultiballState>(
'onBlink emits lightState [lit, dimmed, lit]',
build: MultiballCubit.new,
act: (bloc) => bloc
..onBlink()
..onBlink()
..onBlink(),
expect: () => [
isA<MultiballState>()
..having(
(state) => state.lightState,
'lightState',
MultiballLightState.lit,
),
isA<MultiballState>()
..having(
(state) => state.lightState,
'lightState',
MultiballLightState.dimmed,
),
isA<MultiballState>()
..having(
(state) => state.lightState,
'lightState',
MultiballLightState.lit,
)
],
);
},
);
}
| pinball/packages/pinball_components/test/src/components/multiball/cubit/multiball_cubit_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/multiball/cubit/multiball_cubit_test.dart",
"repo_id": "pinball",
"token_count": 1015
} | 1,129 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group('SignpostCubit', () {
blocTest<SignpostCubit, SignpostState>(
'onProgressed progresses',
build: SignpostCubit.new,
act: (bloc) {
bloc
..onProgressed()
..onProgressed()
..onProgressed()
..onProgressed();
},
expect: () => [
SignpostState.active1,
SignpostState.active2,
SignpostState.active3,
SignpostState.inactive,
],
);
blocTest<SignpostCubit, SignpostState>(
'onReset emits inactive',
build: SignpostCubit.new,
act: (bloc) => bloc.onReset(),
expect: () => [SignpostState.inactive],
);
test('isFullyProgressed when on active3', () {
final bloc = SignpostCubit();
expect(bloc.isFullyProgressed(), isFalse);
bloc.onProgressed();
expect(bloc.isFullyProgressed(), isFalse);
bloc.onProgressed();
expect(bloc.isFullyProgressed(), isFalse);
bloc.onProgressed();
expect(bloc.isFullyProgressed(), isTrue);
});
});
}
| pinball/packages/pinball_components/test/src/components/signpost/cubit/signpost_cubit_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/signpost/cubit/signpost_cubit_test.dart",
"repo_id": "pinball",
"token_count": 545
} | 1,130 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group(
'SparkyBumperCubit',
() {
blocTest<SparkyBumperCubit, SparkyBumperState>(
'onBallContacted emits dimmed',
build: SparkyBumperCubit.new,
act: (bloc) => bloc.onBallContacted(),
expect: () => [SparkyBumperState.dimmed],
);
blocTest<SparkyBumperCubit, SparkyBumperState>(
'onBlinked emits lit',
build: SparkyBumperCubit.new,
act: (bloc) => bloc.onBlinked(),
expect: () => [SparkyBumperState.lit],
);
},
);
}
| pinball/packages/pinball_components/test/src/components/sparky_bumper/cubit/sparky_bumper_cubit_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/sparky_bumper/cubit/sparky_bumper_cubit_test.dart",
"repo_id": "pinball",
"token_count": 315
} | 1,131 |
import 'dart:typed_data';
import 'dart:ui';
/// {@template canvas_wrapper}
/// Custom [Canvas] implementation for Pinball
/// {@endtemplate}
class CanvasWrapper implements Canvas {
/// [Canvas] used for painting operations
late Canvas canvas;
@override
void clipPath(Path path, {bool doAntiAlias = true}) =>
canvas.clipPath(path, doAntiAlias: doAntiAlias);
@override
void clipRRect(RRect rrect, {bool doAntiAlias = true}) =>
canvas.clipRRect(rrect, doAntiAlias: doAntiAlias);
@override
void clipRect(
Rect rect, {
ClipOp clipOp = ClipOp.intersect,
bool doAntiAlias = true,
}) =>
canvas.clipRect(rect, clipOp: clipOp, doAntiAlias: doAntiAlias);
@override
void drawArc(
Rect rect,
double startAngle,
double sweepAngle,
bool useCenter,
Paint paint,
) =>
canvas.drawArc(rect, startAngle, sweepAngle, useCenter, paint);
@override
void drawAtlas(
Image atlas,
List<RSTransform> transforms,
List<Rect> rects,
List<Color>? colors,
BlendMode? blendMode,
Rect? cullRect,
Paint paint,
) =>
canvas.drawAtlas(
atlas,
transforms,
rects,
colors,
blendMode,
cullRect,
paint,
);
@override
void drawCircle(Offset c, double radius, Paint paint) => canvas.drawCircle(
c,
radius,
paint,
);
@override
void drawColor(Color color, BlendMode blendMode) =>
canvas.drawColor(color, blendMode);
@override
void drawDRRect(RRect outer, RRect inner, Paint paint) =>
canvas.drawDRRect(outer, inner, paint);
@override
void drawImage(Image image, Offset offset, Paint paint) =>
canvas.drawImage(image, offset, paint);
@override
void drawImageNine(Image image, Rect center, Rect dst, Paint paint) =>
canvas.drawImageNine(image, center, dst, paint);
@override
void drawImageRect(Image image, Rect src, Rect dst, Paint paint) =>
canvas.drawImageRect(image, src, dst, paint);
@override
void drawLine(Offset p1, Offset p2, Paint paint) =>
canvas.drawLine(p1, p2, paint);
@override
void drawOval(Rect rect, Paint paint) => canvas.drawOval(rect, paint);
@override
void drawPaint(Paint paint) => canvas.drawPaint(paint);
@override
void drawParagraph(Paragraph paragraph, Offset offset) =>
canvas.drawParagraph(paragraph, offset);
@override
void drawPath(Path path, Paint paint) => canvas.drawPath(path, paint);
@override
void drawPicture(Picture picture) => canvas.drawPicture(picture);
@override
void drawPoints(PointMode pointMode, List<Offset> points, Paint paint) =>
canvas.drawPoints(pointMode, points, paint);
@override
void drawRRect(RRect rrect, Paint paint) => canvas.drawRRect(rrect, paint);
@override
void drawRawAtlas(
Image atlas,
Float32List rstTransforms,
Float32List rects,
Int32List? colors,
BlendMode? blendMode,
Rect? cullRect,
Paint paint,
) =>
canvas.drawRawAtlas(
atlas,
rstTransforms,
rects,
colors,
blendMode,
cullRect,
paint,
);
@override
void drawRawPoints(PointMode pointMode, Float32List points, Paint paint) =>
canvas.drawRawPoints(pointMode, points, paint);
@override
void drawRect(Rect rect, Paint paint) => canvas.drawRect(rect, paint);
@override
void drawShadow(
Path path,
Color color,
double elevation,
bool transparentOccluder,
) =>
canvas.drawShadow(path, color, elevation, transparentOccluder);
@override
void drawVertices(Vertices vertices, BlendMode blendMode, Paint paint) =>
canvas.drawVertices(vertices, blendMode, paint);
@override
int getSaveCount() => canvas.getSaveCount();
@override
void restore() => canvas.restore();
@override
void rotate(double radians) => canvas.rotate(radians);
@override
void save() => canvas.save();
@override
void saveLayer(Rect? bounds, Paint paint) => canvas.saveLayer(bounds, paint);
@override
void scale(double sx, [double? sy]) => canvas.scale(sx, sy);
@override
void skew(double sx, double sy) => canvas.skew(sx, sy);
@override
void transform(Float64List matrix4) => canvas.transform(matrix4);
@override
void translate(double dx, double dy) => canvas.translate(dx, dy);
}
| pinball/packages/pinball_flame/lib/src/canvas/canvas_wrapper.dart/0 | {
"file_path": "pinball/packages/pinball_flame/lib/src/canvas/canvas_wrapper.dart",
"repo_id": "pinball",
"token_count": 1613
} | 1,132 |
// 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() {
final shape = CircleShape()..radius = 1;
return world.createBody(BodyDef())..createFixtureFromShape(shape);
}
}
class _TestZIndexBodyComponent extends _TestBodyComponent with ZIndex {
_TestZIndexBodyComponent({required int zIndex}) {
zIndex = zIndex;
}
}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(Forge2DGame.new);
group('ZIndexContactBehavior', () {
test('can be instantiated', () {
expect(
ZIndexContactBehavior(zIndex: 0),
isA<ZIndexContactBehavior>(),
);
});
flameTester.test('can be loaded', (game) async {
final behavior = ZIndexContactBehavior(zIndex: 0);
final parent = _TestBodyComponent();
await game.ensureAdd(parent);
await parent.ensureAdd(behavior);
expect(parent.children, contains(behavior));
});
flameTester.test('beginContact changes zIndex', (game) async {
const oldIndex = 0;
const newIndex = 1;
final behavior = ZIndexContactBehavior(zIndex: newIndex);
final parent = _TestBodyComponent();
await game.ensureAdd(parent);
await parent.ensureAdd(behavior);
final component = _TestZIndexBodyComponent(zIndex: oldIndex);
behavior.beginContact(component, _MockContact());
expect(component.zIndex, newIndex);
});
flameTester.test('endContact changes zIndex', (game) async {
const oldIndex = 0;
const newIndex = 1;
final behavior = ZIndexContactBehavior(zIndex: newIndex, onBegin: false);
final parent = _TestBodyComponent();
await game.ensureAdd(parent);
await parent.ensureAdd(behavior);
final component = _TestZIndexBodyComponent(zIndex: oldIndex);
behavior.endContact(component, _MockContact());
expect(component.zIndex, newIndex);
});
});
}
| pinball/packages/pinball_flame/test/src/behaviors/z_index_contact_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_flame/test/src/behaviors/z_index_contact_behavior_test.dart",
"repo_id": "pinball",
"token_count": 803
} | 1,133 |
# pinball_theme
[![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link]
[![License: MIT][license_badge]][license_link]
Package containing themes for pinball game.
[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/pinball_theme/README.md/0 | {
"file_path": "pinball/packages/pinball_theme/README.md",
"repo_id": "pinball",
"token_count": 168
} | 1,134 |
export 'android_theme.dart';
export 'character_theme.dart';
export 'dash_theme.dart';
export 'dino_theme.dart';
export 'sparky_theme.dart';
| pinball/packages/pinball_theme/lib/src/themes/themes.dart/0 | {
"file_path": "pinball/packages/pinball_theme/lib/src/themes/themes.dart",
"repo_id": "pinball",
"token_count": 53
} | 1,135 |
import 'package:flutter/material.dart';
import 'package:pinball_ui/gen/gen.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// {@template pinball_button}
/// Pinball-themed button with pixel art.
/// {@endtemplate}
class PinballButton extends StatelessWidget {
/// {@macro pinball_button}
const PinballButton({
Key? key,
required this.text,
required this.onTap,
}) : super(key: key);
/// Text of the button.
final String text;
/// Tap callback.
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: PinballColors.transparent,
child: DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(Assets.images.button.pinballButton.keyName),
),
),
child: Center(
child: InkWell(
onTap: onTap,
highlightColor: PinballColors.transparent,
splashColor: PinballColors.transparent,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 32,
vertical: 16,
),
child: Text(
text,
style: Theme.of(context)
.textTheme
.headline3!
.copyWith(color: PinballColors.white),
),
),
),
),
),
);
}
}
| pinball/packages/pinball_ui/lib/src/widgets/pinball_button.dart/0 | {
"file_path": "pinball/packages/pinball_ui/lib/src/widgets/pinball_button.dart",
"repo_id": "pinball",
"token_count": 691
} | 1,136 |
// ignore_for_file: cascade_invocations
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.score.fiveThousand.keyName,
Assets.images.score.twentyThousand.keyName,
Assets.images.score.twoHundredThousand.keyName,
Assets.images.score.oneMillion.keyName,
]);
}
Future<void> pump(BodyComponent child, {GameBloc? gameBloc}) {
return ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: gameBloc ?? GameBloc(),
children: [
ZCanvasComponent(children: [child])
],
),
);
}
}
class _TestBodyComponent extends BodyComponent {
@override
Body createBody() => world.createBody(BodyDef());
}
class _MockBall extends Mock implements Ball {}
class _MockBody extends Mock implements Body {}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late GameBloc bloc;
late Ball ball;
late BodyComponent parent;
setUp(() {
bloc = _MockGameBloc();
ball = _MockBall();
final ballBody = _MockBody();
when(() => ball.body).thenReturn(ballBody);
when(() => ballBody.position).thenReturn(Vector2.all(4));
parent = _TestBodyComponent();
});
final flameBlocTester = FlameTester(_TestGame.new);
group('ScoringBehavior', () {
test('can be instantiated', () {
expect(
ScoringBehavior(
points: Points.fiveThousand,
position: Vector2.zero(),
),
isA<ScoringBehavior>(),
);
});
flameBlocTester.test(
'can be loaded',
(game) async {
await game.pump(parent);
final behavior = ScoringBehavior(
points: Points.fiveThousand,
position: Vector2.zero(),
);
await parent.ensureAdd(behavior);
expect(
parent.firstChild<ScoringBehavior>(),
equals(behavior),
);
},
);
flameBlocTester.test(
'emits Scored event with points when added',
(game) async {
await game.pump(parent, gameBloc: bloc);
const points = Points.oneMillion;
final behavior = ScoringBehavior(
points: points,
position: Vector2(0, 0),
);
await parent.ensureAdd(behavior);
verify(
() => bloc.add(
Scored(points: points.value),
),
).called(1);
},
);
flameBlocTester.test(
'correctly renders text',
(game) async {
await game.pump(parent);
const points = Points.oneMillion;
final position = Vector2.all(1);
final behavior = ScoringBehavior(
points: points,
position: position,
);
await parent.ensureAdd(behavior);
final scoreText = game.descendants().whereType<ScoreComponent>();
expect(scoreText.length, equals(1));
expect(
scoreText.first.points,
equals(points),
);
expect(
scoreText.first.position,
equals(position),
);
},
);
flameBlocTester.testGameWidget(
'is removed after duration',
setUp: (game, tester) async {
await game.onLoad();
await game.pump(parent);
const duration = 2.0;
final behavior = ScoringBehavior(
points: Points.oneMillion,
position: Vector2(0, 0),
duration: duration,
);
await parent.ensureAdd(behavior);
game.update(duration);
game.update(0);
await tester.pump();
},
verify: (game, _) async {
expect(
game.descendants().whereType<ScoringBehavior>(),
isEmpty,
);
},
);
});
group('ScoringContactBehavior', () {
flameBlocTester.testGameWidget(
'beginContact adds a ScoringBehavior',
setUp: (game, tester) async {
await game.onLoad();
await game.pump(parent);
final behavior = ScoringContactBehavior(points: Points.oneMillion);
await parent.ensureAdd(behavior);
behavior.beginContact(ball, _MockContact());
await game.ready();
expect(
parent.firstChild<ScoringBehavior>(),
isNotNull,
);
},
);
flameBlocTester.testGameWidget(
"beginContact positions text at contact's position",
setUp: (game, tester) async {
await game.onLoad();
await game.pump(parent);
final behavior = ScoringContactBehavior(points: Points.oneMillion);
await parent.ensureAdd(behavior);
behavior.beginContact(ball, _MockContact());
await game.ready();
final scoreText = game.descendants().whereType<ScoreComponent>();
expect(
scoreText.first.position,
equals(ball.body.position),
);
},
);
});
}
| pinball/test/game/behaviors/scoring_behavior_test.dart/0 | {
"file_path": "pinball/test/game/behaviors/scoring_behavior_test.dart",
"repo_id": "pinball",
"token_count": 2333
} | 1,137 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/bloc/game_bloc.dart';
import 'package:pinball/game/components/backbox/displays/initials_input_display.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_theme/pinball_theme.dart' as theme;
class _TestGame extends Forge2DGame with HasKeyboardHandlerComponents {
final characterIconPath = theme.Assets.images.dash.leaderboardIcon.keyName;
@override
Future<void> onLoad() async {
await super.onLoad();
images.prefix = '';
await images.loadAll(
[
characterIconPath,
Assets.images.backbox.displayDivider.keyName,
],
);
}
Future<void> pump(InitialsInputDisplay component) {
return ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: GameBloc(),
children: [
FlameProvider.value(
_MockAppLocalizations(),
children: [component],
),
],
),
);
}
}
class _MockAppLocalizations extends Mock implements AppLocalizations {
@override
String get score => '';
@override
String get name => '';
@override
String get enterInitials => '';
@override
String get arrows => '';
@override
String get andPress => '';
@override
String get enterReturn => '';
@override
String get toSubmit => '';
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('InitialsInputDisplay', () {
flameTester.test(
'loads correctly',
(game) async {
final component = InitialsInputDisplay(
score: 0,
characterIconPath: game.characterIconPath,
onSubmit: (_) {},
);
await game.pump(component);
expect(game.descendants(), contains(component));
},
);
flameTester.testGameWidget(
'can change the initials',
setUp: (game, tester) async {
await game.onLoad();
final component = InitialsInputDisplay(
score: 1000,
characterIconPath: game.characterIconPath,
onSubmit: (_) {},
);
await game.pump(component);
// Focus is on the first letter
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
// Move to the next an press down again
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
// One more time
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
// Back to the previous and press down again
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
},
verify: (game, tester) async {
final component =
game.descendants().whereType<InitialsInputDisplay>().single;
expect(component.initials, equals('BCB'));
},
);
String? submittedInitials;
flameTester.testGameWidget(
'submits the initials',
setUp: (game, tester) async {
await game.onLoad();
final component = InitialsInputDisplay(
score: 1000,
characterIconPath: game.characterIconPath,
onSubmit: (value) {
submittedInitials = value;
},
);
await game.pump(component);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
},
verify: (game, tester) async {
expect(submittedInitials, equals('AAA'));
},
);
group('BackboardLetterPrompt', () {
flameTester.testGameWidget(
'cycles the char up and down when it has focus',
setUp: (game, tester) async {
await game.onLoad();
await game.ensureAdd(
InitialsLetterPrompt(hasFocus: true, position: Vector2.zero()),
);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
},
verify: (game, tester) async {
final prompt = game.firstChild<InitialsLetterPrompt>();
expect(prompt?.char, equals('C'));
},
);
flameTester.testGameWidget(
"does nothing when it doesn't have focus",
setUp: (game, tester) async {
await game.onLoad();
await game.ensureAdd(
InitialsLetterPrompt(position: Vector2.zero()),
);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
},
verify: (game, tester) async {
final prompt = game.firstChild<InitialsLetterPrompt>();
expect(prompt?.char, equals('A'));
},
);
flameTester.testGameWidget(
'blinks the prompt when it has the focus',
setUp: (game, tester) async {
await game.onLoad();
await game.ensureAdd(
InitialsLetterPrompt(position: Vector2.zero(), hasFocus: true),
);
},
verify: (game, tester) async {
final underscore =
game.descendants().whereType<ShapeComponent>().first;
expect(underscore.paint.color, Colors.white);
game.update(2);
expect(underscore.paint.color, Colors.transparent);
},
);
});
});
}
| pinball/test/game/components/backbox/displays/initials_input_display_test.dart/0 | {
"file_path": "pinball/test/game/components/backbox/displays/initials_input_display_test.dart",
"repo_id": "pinball",
"token_count": 2709
} | 1,138 |
// ignore_for_file: cascade_invocations
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/google_gallery/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.googleWord.letter1.lit.keyName,
Assets.images.googleWord.letter1.dimmed.keyName,
Assets.images.googleWord.letter2.lit.keyName,
Assets.images.googleWord.letter2.dimmed.keyName,
Assets.images.googleWord.letter3.lit.keyName,
Assets.images.googleWord.letter3.dimmed.keyName,
Assets.images.googleWord.letter4.lit.keyName,
Assets.images.googleWord.letter4.dimmed.keyName,
Assets.images.googleWord.letter5.lit.keyName,
Assets.images.googleWord.letter5.dimmed.keyName,
Assets.images.googleWord.letter6.lit.keyName,
Assets.images.googleWord.letter6.dimmed.keyName,
]);
}
Future<void> pump(
GoogleGallery child, {
required GameBloc gameBloc,
required GoogleWordCubit googleWordBloc,
}) async {
// Not needed once https://github.com/flame-engine/flame/issues/1607
// is fixed
await onLoad();
await ensureAdd(
FlameMultiBlocProvider(
providers: [
FlameBlocProvider<GameBloc, GameState>.value(
value: gameBloc,
),
FlameBlocProvider<GoogleWordCubit, GoogleWordState>.value(
value: googleWordBloc,
),
],
children: [child],
),
);
}
}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockGoogleWordCubit extends Mock implements GoogleWordCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('GoogleWordBonusBehavior', () {
late GameBloc gameBloc;
setUp(() {
gameBloc = _MockGameBloc();
});
final flameTester = FlameTester(_TestGame.new);
test('can be instantiated', () {
expect(GoogleWordBonusBehavior(), isA<GoogleWordBonusBehavior>());
});
flameTester.testGameWidget(
'adds GameBonus.googleWord to the game when all letters '
'in google word are activated and calls onReset',
setUp: (game, tester) async {
final behavior = GoogleWordBonusBehavior();
final parent = GoogleGallery.test();
final googleWord = GoogleWord(position: Vector2.zero());
final googleWordBloc = _MockGoogleWordCubit();
final streamController = StreamController<GoogleWordState>();
whenListen(
googleWordBloc,
streamController.stream,
initialState: GoogleWordState.initial(),
);
await parent.add(googleWord);
await game.pump(
parent,
gameBloc: gameBloc,
googleWordBloc: googleWordBloc,
);
await parent.ensureAdd(behavior);
streamController.add(
const GoogleWordState(
letterSpriteStates: {
0: GoogleLetterSpriteState.lit,
1: GoogleLetterSpriteState.lit,
2: GoogleLetterSpriteState.lit,
3: GoogleLetterSpriteState.lit,
4: GoogleLetterSpriteState.lit,
5: GoogleLetterSpriteState.lit,
},
),
);
await tester.pump();
verify(
() => gameBloc.add(const BonusActivated(GameBonus.googleWord)),
).called(1);
verify(googleWordBloc.onReset).called(1);
},
);
flameTester.testGameWidget(
'adds BonusBallSpawningBehavior and GoogleWordAnimatingBehavior '
'to the game when all letters in google word are activated',
setUp: (game, tester) async {
final behavior = GoogleWordBonusBehavior();
final parent = GoogleGallery.test();
final googleWord = GoogleWord(position: Vector2.zero());
final googleWordBloc = _MockGoogleWordCubit();
final streamController = StreamController<GoogleWordState>();
whenListen(
googleWordBloc,
streamController.stream,
initialState: GoogleWordState.initial(),
);
await parent.add(googleWord);
await game.pump(
parent,
gameBloc: gameBloc,
googleWordBloc: googleWordBloc,
);
await parent.ensureAdd(behavior);
streamController.add(
const GoogleWordState(
letterSpriteStates: {
0: GoogleLetterSpriteState.lit,
1: GoogleLetterSpriteState.lit,
2: GoogleLetterSpriteState.lit,
3: GoogleLetterSpriteState.lit,
4: GoogleLetterSpriteState.lit,
5: GoogleLetterSpriteState.lit,
},
),
);
await tester.pump();
await game.ready();
expect(
game.descendants().whereType<BonusBallSpawningBehavior>().length,
equals(1),
);
expect(
game.descendants().whereType<GoogleWordAnimatingBehavior>().length,
equals(1),
);
},
);
});
}
| pinball/test/game/components/google_gallery/behaviors/google_word_bonus_behavior_test.dart/0 | {
"file_path": "pinball/test/game/components/google_gallery/behaviors/google_word_bonus_behavior_test.dart",
"repo_id": "pinball",
"token_count": 2362
} | 1,139 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/start_game/bloc/start_game_bloc.dart';
import '../../../helpers/helpers.dart';
class _MockStartGameBloc extends Mock implements StartGameBloc {}
class _MockGameBloc extends Mock implements GameBloc {}
void main() {
group('ReplayButtonOverlay', () {
late StartGameBloc startGameBloc;
late _MockGameBloc gameBloc;
setUp(() async {
await mockFlameImages();
startGameBloc = _MockStartGameBloc();
gameBloc = _MockGameBloc();
whenListen(
startGameBloc,
Stream.value(const StartGameState.initial()),
initialState: const StartGameState.initial(),
);
whenListen(
gameBloc,
Stream.value(const GameState.initial()),
initialState: const GameState.initial(),
);
});
testWidgets('renders correctly', (tester) async {
await tester.pumpApp(const ReplayButtonOverlay());
expect(find.text('Replay'), findsOneWidget);
});
testWidgets('adds ReplayTapped event to StartGameBloc when tapped',
(tester) async {
await tester.pumpApp(
const ReplayButtonOverlay(),
gameBloc: gameBloc,
startGameBloc: startGameBloc,
);
await tester.tap(find.text('Replay'));
await tester.pump();
verify(() => startGameBloc.add(const ReplayTapped())).called(1);
});
testWidgets('adds GameStarted event to GameBloc when tapped',
(tester) async {
await tester.pumpApp(
const ReplayButtonOverlay(),
gameBloc: gameBloc,
startGameBloc: startGameBloc,
);
await tester.tap(find.text('Replay'));
await tester.pump();
verify(() => gameBloc.add(const GameStarted())).called(1);
});
});
}
| pinball/test/game/view/widgets/replay_button_overlay_test.dart/0 | {
"file_path": "pinball/test/game/view/widgets/replay_button_overlay_test.dart",
"repo_id": "pinball",
"token_count": 791
} | 1,140 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.zoomlevel;
import android.graphics.Rect;
import androidx.annotation.NonNull;
import androidx.core.math.MathUtils;
/**
* Utility class containing methods that assist with zoom features in the {@link
* android.hardware.camera2} API.
*/
final class ZoomUtils {
/**
* Computes an image sensor area based on the supplied zoom settings.
*
* <p>The returned image sensor area can be applied to the {@link android.hardware.camera2} API in
* order to control zoom levels. This method of zoom should only be used for Android versions <=
* 11 as past that, the newer {@link #computeZoomRatio()} functional can be used.
*
* @param zoom The desired zoom level.
* @param sensorArraySize The current area of the image sensor.
* @param minimumZoomLevel The minimum supported zoom level.
* @param maximumZoomLevel The maximim supported zoom level.
* @return An image sensor area based on the supplied zoom settings
*/
static Rect computeZoomRect(
float zoom, @NonNull Rect sensorArraySize, float minimumZoomLevel, float maximumZoomLevel) {
final float newZoom = computeZoomRatio(zoom, minimumZoomLevel, maximumZoomLevel);
final int centerX = sensorArraySize.width() / 2;
final int centerY = sensorArraySize.height() / 2;
final int deltaX = (int) ((0.5f * sensorArraySize.width()) / newZoom);
final int deltaY = (int) ((0.5f * sensorArraySize.height()) / newZoom);
return new Rect(centerX - deltaX, centerY - deltaY, centerX + deltaX, centerY + deltaY);
}
static Float computeZoomRatio(float zoom, float minimumZoomLevel, float maximumZoomLevel) {
return MathUtils.clamp(zoom, minimumZoomLevel, maximumZoomLevel);
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/zoomlevel/ZoomUtils.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/zoomlevel/ZoomUtils.java",
"repo_id": "plugins",
"token_count": 576
} | 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.camera;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CaptureRequest;
import android.media.CamcorderProfile;
import android.media.EncoderProfiles;
import android.os.Handler;
import android.os.HandlerThread;
import androidx.annotation.NonNull;
import io.flutter.plugins.camera.features.CameraFeatureFactory;
import io.flutter.plugins.camera.features.autofocus.AutoFocusFeature;
import io.flutter.plugins.camera.features.exposurelock.ExposureLockFeature;
import io.flutter.plugins.camera.features.exposureoffset.ExposureOffsetFeature;
import io.flutter.plugins.camera.features.exposurepoint.ExposurePointFeature;
import io.flutter.plugins.camera.features.flash.FlashFeature;
import io.flutter.plugins.camera.features.focuspoint.FocusPointFeature;
import io.flutter.plugins.camera.features.fpsrange.FpsRangeFeature;
import io.flutter.plugins.camera.features.noisereduction.NoiseReductionFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionFeature;
import io.flutter.plugins.camera.features.resolution.ResolutionPreset;
import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature;
import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature;
import io.flutter.view.TextureRegistry;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
public class CameraTest_getRecordingProfileTest {
private CameraProperties mockCameraProperties;
private CameraFeatureFactory mockCameraFeatureFactory;
private DartMessenger mockDartMessenger;
private Camera camera;
private CameraCaptureSession mockCaptureSession;
private CaptureRequest.Builder mockPreviewRequestBuilder;
private MockedStatic<Camera.HandlerThreadFactory> mockHandlerThreadFactory;
private HandlerThread mockHandlerThread;
private MockedStatic<Camera.HandlerFactory> mockHandlerFactory;
private Handler mockHandler;
@Before
public void before() {
mockCameraProperties = mock(CameraProperties.class);
mockCameraFeatureFactory = new TestCameraFeatureFactory();
mockDartMessenger = mock(DartMessenger.class);
final Activity mockActivity = mock(Activity.class);
final TextureRegistry.SurfaceTextureEntry mockFlutterTexture =
mock(TextureRegistry.SurfaceTextureEntry.class);
final ResolutionPreset resolutionPreset = ResolutionPreset.high;
final boolean enableAudio = false;
camera =
new Camera(
mockActivity,
mockFlutterTexture,
mockCameraFeatureFactory,
mockDartMessenger,
mockCameraProperties,
resolutionPreset,
enableAudio);
}
@Config(maxSdk = 30)
@Test
public void getRecordingProfileLegacy() {
ResolutionFeature mockResolutionFeature =
mockCameraFeatureFactory.createResolutionFeature(mockCameraProperties, null, null);
CamcorderProfile mockCamcorderProfile = mock(CamcorderProfile.class);
when(mockResolutionFeature.getRecordingProfileLegacy()).thenReturn(mockCamcorderProfile);
CamcorderProfile actualRecordingProfile = camera.getRecordingProfileLegacy();
verify(mockResolutionFeature, times(1)).getRecordingProfileLegacy();
assertEquals(mockCamcorderProfile, actualRecordingProfile);
}
@Config(minSdk = 31)
@Test
public void getRecordingProfile() {
ResolutionFeature mockResolutionFeature =
mockCameraFeatureFactory.createResolutionFeature(mockCameraProperties, null, null);
EncoderProfiles mockRecordingProfile = mock(EncoderProfiles.class);
when(mockResolutionFeature.getRecordingProfile()).thenReturn(mockRecordingProfile);
EncoderProfiles actualRecordingProfile = camera.getRecordingProfile();
verify(mockResolutionFeature, times(1)).getRecordingProfile();
assertEquals(mockRecordingProfile, actualRecordingProfile);
}
private static class TestCameraFeatureFactory implements CameraFeatureFactory {
private final AutoFocusFeature mockAutoFocusFeature;
private final ExposureLockFeature mockExposureLockFeature;
private final ExposureOffsetFeature mockExposureOffsetFeature;
private final ExposurePointFeature mockExposurePointFeature;
private final FlashFeature mockFlashFeature;
private final FocusPointFeature mockFocusPointFeature;
private final FpsRangeFeature mockFpsRangeFeature;
private final NoiseReductionFeature mockNoiseReductionFeature;
private final ResolutionFeature mockResolutionFeature;
private final SensorOrientationFeature mockSensorOrientationFeature;
private final ZoomLevelFeature mockZoomLevelFeature;
public TestCameraFeatureFactory() {
this.mockAutoFocusFeature = mock(AutoFocusFeature.class);
this.mockExposureLockFeature = mock(ExposureLockFeature.class);
this.mockExposureOffsetFeature = mock(ExposureOffsetFeature.class);
this.mockExposurePointFeature = mock(ExposurePointFeature.class);
this.mockFlashFeature = mock(FlashFeature.class);
this.mockFocusPointFeature = mock(FocusPointFeature.class);
this.mockFpsRangeFeature = mock(FpsRangeFeature.class);
this.mockNoiseReductionFeature = mock(NoiseReductionFeature.class);
this.mockResolutionFeature = mock(ResolutionFeature.class);
this.mockSensorOrientationFeature = mock(SensorOrientationFeature.class);
this.mockZoomLevelFeature = mock(ZoomLevelFeature.class);
}
@Override
public AutoFocusFeature createAutoFocusFeature(
@NonNull CameraProperties cameraProperties, boolean recordingVideo) {
return mockAutoFocusFeature;
}
@Override
public ExposureLockFeature createExposureLockFeature(
@NonNull CameraProperties cameraProperties) {
return mockExposureLockFeature;
}
@Override
public ExposureOffsetFeature createExposureOffsetFeature(
@NonNull CameraProperties cameraProperties) {
return mockExposureOffsetFeature;
}
@Override
public FlashFeature createFlashFeature(@NonNull CameraProperties cameraProperties) {
return mockFlashFeature;
}
@Override
public ResolutionFeature createResolutionFeature(
@NonNull CameraProperties cameraProperties,
ResolutionPreset initialSetting,
String cameraName) {
return mockResolutionFeature;
}
@Override
public FocusPointFeature createFocusPointFeature(
@NonNull CameraProperties cameraProperties,
@NonNull SensorOrientationFeature sensorOrienttionFeature) {
return mockFocusPointFeature;
}
@Override
public FpsRangeFeature createFpsRangeFeature(@NonNull CameraProperties cameraProperties) {
return mockFpsRangeFeature;
}
@Override
public SensorOrientationFeature createSensorOrientationFeature(
@NonNull CameraProperties cameraProperties,
@NonNull Activity activity,
@NonNull DartMessenger dartMessenger) {
return mockSensorOrientationFeature;
}
@Override
public ZoomLevelFeature createZoomLevelFeature(@NonNull CameraProperties cameraProperties) {
return mockZoomLevelFeature;
}
@Override
public ExposurePointFeature createExposurePointFeature(
@NonNull CameraProperties cameraProperties,
@NonNull SensorOrientationFeature sensorOrientationFeature) {
return mockExposurePointFeature;
}
@Override
public NoiseReductionFeature createNoiseReductionFeature(
@NonNull CameraProperties cameraProperties) {
return mockNoiseReductionFeature;
}
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraTest_getRecordingProfileTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraTest_getRecordingProfileTest.java",
"repo_id": "plugins",
"token_count": 2518
} | 1,142 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.resolution;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
import android.media.CamcorderProfile;
import android.media.EncoderProfiles;
import android.util.Size;
import io.flutter.plugins.camera.CameraProperties;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
public class ResolutionFeatureTest {
private static final String cameraName = "1";
private CamcorderProfile mockProfileLowLegacy;
private EncoderProfiles mockProfileLow;
private MockedStatic<CamcorderProfile> mockedStaticProfile;
@Before
@SuppressWarnings("deprecation")
public void beforeLegacy() {
mockedStaticProfile = mockStatic(CamcorderProfile.class);
mockProfileLowLegacy = mock(CamcorderProfile.class);
CamcorderProfile mockProfileLegacy = mock(CamcorderProfile.class);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_HIGH))
.thenReturn(true);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_2160P))
.thenReturn(true);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_1080P))
.thenReturn(true);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_720P))
.thenReturn(true);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_480P))
.thenReturn(true);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_QVGA))
.thenReturn(true);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_LOW))
.thenReturn(true);
mockedStaticProfile
.when(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_HIGH))
.thenReturn(mockProfileLegacy);
mockedStaticProfile
.when(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_2160P))
.thenReturn(mockProfileLegacy);
mockedStaticProfile
.when(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_1080P))
.thenReturn(mockProfileLegacy);
mockedStaticProfile
.when(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_720P))
.thenReturn(mockProfileLegacy);
mockedStaticProfile
.when(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_480P))
.thenReturn(mockProfileLegacy);
mockedStaticProfile
.when(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_QVGA))
.thenReturn(mockProfileLegacy);
mockedStaticProfile
.when(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_LOW))
.thenReturn(mockProfileLowLegacy);
}
public void before() {
mockProfileLow = mock(EncoderProfiles.class);
EncoderProfiles mockProfile = mock(EncoderProfiles.class);
EncoderProfiles.VideoProfile mockVideoProfile = mock(EncoderProfiles.VideoProfile.class);
List<EncoderProfiles.VideoProfile> mockVideoProfilesList = List.of(mockVideoProfile);
mockedStaticProfile
.when(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_HIGH))
.thenReturn(mockProfile);
mockedStaticProfile
.when(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_2160P))
.thenReturn(mockProfile);
mockedStaticProfile
.when(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_1080P))
.thenReturn(mockProfile);
mockedStaticProfile
.when(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_720P))
.thenReturn(mockProfile);
mockedStaticProfile
.when(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_480P))
.thenReturn(mockProfile);
mockedStaticProfile
.when(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_QVGA))
.thenReturn(mockProfile);
mockedStaticProfile
.when(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_LOW))
.thenReturn(mockProfileLow);
when(mockProfile.getVideoProfiles()).thenReturn(mockVideoProfilesList);
when(mockVideoProfile.getHeight()).thenReturn(100);
when(mockVideoProfile.getWidth()).thenReturn(100);
}
@After
public void after() {
mockedStaticProfile.reset();
mockedStaticProfile.close();
}
@Test
public void getDebugName_shouldReturnTheNameOfTheFeature() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ResolutionFeature resolutionFeature =
new ResolutionFeature(mockCameraProperties, ResolutionPreset.max, cameraName);
assertEquals("ResolutionFeature", resolutionFeature.getDebugName());
}
@Test
public void getValue_shouldReturnInitialValueWhenNotSet() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ResolutionFeature resolutionFeature =
new ResolutionFeature(mockCameraProperties, ResolutionPreset.max, cameraName);
assertEquals(ResolutionPreset.max, resolutionFeature.getValue());
}
@Test
public void getValue_shouldEchoSetValue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ResolutionFeature resolutionFeature =
new ResolutionFeature(mockCameraProperties, ResolutionPreset.max, cameraName);
resolutionFeature.setValue(ResolutionPreset.high);
assertEquals(ResolutionPreset.high, resolutionFeature.getValue());
}
@Test
public void checkIsSupport_returnsTrue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ResolutionFeature resolutionFeature =
new ResolutionFeature(mockCameraProperties, ResolutionPreset.max, cameraName);
assertTrue(resolutionFeature.checkIsSupported());
}
@Config(maxSdk = 30)
@SuppressWarnings("deprecation")
@Test
public void getBestAvailableCamcorderProfileForResolutionPreset_shouldFallThroughLegacy() {
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_HIGH))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_2160P))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_1080P))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_720P))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_480P))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_QVGA))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_LOW))
.thenReturn(true);
assertEquals(
mockProfileLowLegacy,
ResolutionFeature.getBestAvailableCamcorderProfileForResolutionPresetLegacy(
1, ResolutionPreset.max));
}
@Config(minSdk = 31)
@Test
public void getBestAvailableCamcorderProfileForResolutionPreset_shouldFallThrough() {
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_HIGH))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_2160P))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_1080P))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_720P))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_480P))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_QVGA))
.thenReturn(false);
mockedStaticProfile
.when(() -> CamcorderProfile.hasProfile(1, CamcorderProfile.QUALITY_LOW))
.thenReturn(true);
assertEquals(
mockProfileLow,
ResolutionFeature.getBestAvailableCamcorderProfileForResolutionPreset(
1, ResolutionPreset.max));
}
@Config(maxSdk = 30)
@SuppressWarnings("deprecation")
@Test
public void computeBestPreviewSize_shouldUse720PWhenResolutionPresetMaxLegacy() {
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.max);
mockedStaticProfile.verify(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_720P));
}
@Config(minSdk = 31)
@Test
public void computeBestPreviewSize_shouldUse720PWhenResolutionPresetMax() {
before();
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.max);
mockedStaticProfile.verify(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_720P));
}
@Config(maxSdk = 30)
@SuppressWarnings("deprecation")
@Test
public void computeBestPreviewSize_shouldUse720PWhenResolutionPresetUltraHighLegacy() {
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.ultraHigh);
mockedStaticProfile.verify(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_720P));
}
@Config(minSdk = 31)
@Test
public void computeBestPreviewSize_shouldUse720PWhenResolutionPresetUltraHigh() {
before();
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.ultraHigh);
mockedStaticProfile.verify(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_720P));
}
@Config(maxSdk = 30)
@SuppressWarnings("deprecation")
@Test
public void computeBestPreviewSize_shouldUse720PWhenResolutionPresetVeryHighLegacy() {
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.veryHigh);
mockedStaticProfile.verify(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_720P));
}
@Config(minSdk = 31)
@SuppressWarnings("deprecation")
@Test
public void computeBestPreviewSize_shouldUse720PWhenResolutionPresetVeryHigh() {
before();
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.veryHigh);
mockedStaticProfile.verify(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_720P));
}
@Config(maxSdk = 30)
@SuppressWarnings("deprecation")
@Test
public void computeBestPreviewSize_shouldUse720PWhenResolutionPresetHighLegacy() {
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.high);
mockedStaticProfile.verify(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_720P));
}
@Config(minSdk = 31)
@Test
public void computeBestPreviewSize_shouldUse720PWhenResolutionPresetHigh() {
before();
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.high);
mockedStaticProfile.verify(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_720P));
}
@Config(maxSdk = 30)
@SuppressWarnings("deprecation")
@Test
public void computeBestPreviewSize_shouldUse480PWhenResolutionPresetMediumLegacy() {
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.medium);
mockedStaticProfile.verify(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_480P));
}
@Config(minSdk = 31)
@Test
public void computeBestPreviewSize_shouldUse480PWhenResolutionPresetMedium() {
before();
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.medium);
mockedStaticProfile.verify(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_480P));
}
@Config(maxSdk = 30)
@SuppressWarnings("deprecation")
@Test
public void computeBestPreviewSize_shouldUseQVGAWhenResolutionPresetLowLegacy() {
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.low);
mockedStaticProfile.verify(() -> CamcorderProfile.get(1, CamcorderProfile.QUALITY_QVGA));
}
@Config(minSdk = 31)
@Test
public void computeBestPreviewSize_shouldUseQVGAWhenResolutionPresetLow() {
before();
ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.low);
mockedStaticProfile.verify(() -> CamcorderProfile.getAll("1", CamcorderProfile.QUALITY_QVGA));
}
@Config(minSdk = 31)
@Test
public void computeBestPreviewSize_shouldUseLegacyBehaviorWhenEncoderProfilesNull() {
try (MockedStatic<ResolutionFeature> mockedResolutionFeature =
mockStatic(ResolutionFeature.class)) {
mockedResolutionFeature
.when(
() ->
ResolutionFeature.getBestAvailableCamcorderProfileForResolutionPreset(
anyInt(), any(ResolutionPreset.class)))
.thenAnswer(
(Answer<EncoderProfiles>)
invocation -> {
EncoderProfiles mockEncoderProfiles = mock(EncoderProfiles.class);
List<EncoderProfiles.VideoProfile> videoProfiles =
new ArrayList<EncoderProfiles.VideoProfile>() {
{
add(null);
}
};
when(mockEncoderProfiles.getVideoProfiles()).thenReturn(videoProfiles);
return mockEncoderProfiles;
});
mockedResolutionFeature
.when(
() ->
ResolutionFeature.getBestAvailableCamcorderProfileForResolutionPresetLegacy(
anyInt(), any(ResolutionPreset.class)))
.thenAnswer(
(Answer<CamcorderProfile>)
invocation -> {
CamcorderProfile mockCamcorderProfile = mock(CamcorderProfile.class);
mockCamcorderProfile.videoFrameWidth = 10;
mockCamcorderProfile.videoFrameHeight = 50;
return mockCamcorderProfile;
});
mockedResolutionFeature
.when(() -> ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.max))
.thenCallRealMethod();
Size testPreviewSize = ResolutionFeature.computeBestPreviewSize(1, ResolutionPreset.max);
assertEquals(testPreviewSize.getWidth(), 10);
assertEquals(testPreviewSize.getHeight(), 50);
}
}
@Config(minSdk = 31)
@Test
public void resolutionFeatureShouldUseLegacyBehaviorWhenEncoderProfilesNull() {
beforeLegacy();
try (MockedStatic<ResolutionFeature> mockedResolutionFeature =
mockStatic(ResolutionFeature.class)) {
mockedResolutionFeature
.when(
() ->
ResolutionFeature.getBestAvailableCamcorderProfileForResolutionPreset(
anyInt(), any(ResolutionPreset.class)))
.thenAnswer(
(Answer<EncoderProfiles>)
invocation -> {
EncoderProfiles mockEncoderProfiles = mock(EncoderProfiles.class);
List<EncoderProfiles.VideoProfile> videoProfiles =
new ArrayList<EncoderProfiles.VideoProfile>() {
{
add(null);
}
};
when(mockEncoderProfiles.getVideoProfiles()).thenReturn(videoProfiles);
return mockEncoderProfiles;
});
mockedResolutionFeature
.when(
() ->
ResolutionFeature.getBestAvailableCamcorderProfileForResolutionPresetLegacy(
anyInt(), any(ResolutionPreset.class)))
.thenAnswer(
(Answer<CamcorderProfile>)
invocation -> {
CamcorderProfile mockCamcorderProfile = mock(CamcorderProfile.class);
return mockCamcorderProfile;
});
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ResolutionFeature resolutionFeature =
new ResolutionFeature(mockCameraProperties, ResolutionPreset.max, cameraName);
assertNotNull(resolutionFeature.getRecordingProfileLegacy());
assertNull(resolutionFeature.getRecordingProfile());
}
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/resolution/ResolutionFeatureTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/resolution/ResolutionFeatureTest.java",
"repo_id": "plugins",
"token_count": 6553
} | 1,143 |
rootProject.name = 'camera_android_camerax'
| plugins/packages/camera/camera_android_camerax/android/settings.gradle/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/settings.gradle",
"repo_id": "plugins",
"token_count": 15
} | 1,144 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camerax;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraInfo;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.UseCase;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import com.google.common.util.concurrent.ListenableFuture;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ProcessCameraProviderHostApi;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class ProcessCameraProviderHostApiImpl implements ProcessCameraProviderHostApi {
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
private Context context;
private LifecycleOwner lifecycleOwner;
public ProcessCameraProviderHostApiImpl(
BinaryMessenger binaryMessenger, InstanceManager instanceManager, Context context) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
this.context = context;
}
public void setLifecycleOwner(LifecycleOwner lifecycleOwner) {
this.lifecycleOwner = lifecycleOwner;
}
/**
* Sets the context that the {@code ProcessCameraProvider} will use to attach the lifecycle of the
* camera to.
*
* <p>If using the camera plugin in an add-to-app context, ensure that a new instance of the
* {@code ProcessCameraProvider} is fetched via {@code #getInstance} anytime the context changes.
*/
public void setContext(Context context) {
this.context = context;
}
/**
* Returns the instance of the {@code ProcessCameraProvider} to manage the lifecycle of the camera
* for the current {@code Context}.
*/
@Override
public void getInstance(GeneratedCameraXLibrary.Result<Long> result) {
ListenableFuture<ProcessCameraProvider> processCameraProviderFuture =
ProcessCameraProvider.getInstance(context);
processCameraProviderFuture.addListener(
() -> {
try {
// Camera provider is now guaranteed to be available.
ProcessCameraProvider processCameraProvider = processCameraProviderFuture.get();
final ProcessCameraProviderFlutterApiImpl flutterApi =
new ProcessCameraProviderFlutterApiImpl(binaryMessenger, instanceManager);
if (!instanceManager.containsInstance(processCameraProvider)) {
flutterApi.create(processCameraProvider, reply -> {});
}
result.success(instanceManager.getIdentifierForStrongReference(processCameraProvider));
} catch (Exception e) {
result.error(e);
}
},
ContextCompat.getMainExecutor(context));
}
/** Returns cameras available to the {@code ProcessCameraProvider}. */
@Override
public List<Long> getAvailableCameraInfos(@NonNull Long identifier) {
ProcessCameraProvider processCameraProvider =
(ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier));
List<CameraInfo> availableCameras = processCameraProvider.getAvailableCameraInfos();
List<Long> availableCamerasIds = new ArrayList<Long>();
final CameraInfoFlutterApiImpl cameraInfoFlutterApi =
new CameraInfoFlutterApiImpl(binaryMessenger, instanceManager);
for (CameraInfo cameraInfo : availableCameras) {
if (!instanceManager.containsInstance(cameraInfo)) {
cameraInfoFlutterApi.create(cameraInfo, result -> {});
}
availableCamerasIds.add(instanceManager.getIdentifierForStrongReference(cameraInfo));
}
return availableCamerasIds;
}
/**
* Binds specified {@code UseCase}s to the lifecycle of the {@code LifecycleOwner} that
* corresponds to this instance and returns the instance of the {@code Camera} whose lifecycle
* that {@code LifecycleOwner} reflects.
*/
@Override
public Long bindToLifecycle(
@NonNull Long identifier,
@NonNull Long cameraSelectorIdentifier,
@NonNull List<Long> useCaseIds) {
ProcessCameraProvider processCameraProvider =
(ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier));
CameraSelector cameraSelector =
(CameraSelector)
Objects.requireNonNull(instanceManager.getInstance(cameraSelectorIdentifier));
UseCase[] useCases = new UseCase[useCaseIds.size()];
for (int i = 0; i < useCaseIds.size(); i++) {
useCases[i] =
(UseCase)
Objects.requireNonNull(
instanceManager.getInstance(((Number) useCaseIds.get(i)).longValue()));
}
Camera camera =
processCameraProvider.bindToLifecycle(
(LifecycleOwner) lifecycleOwner, cameraSelector, useCases);
final CameraFlutterApiImpl cameraFlutterApi =
new CameraFlutterApiImpl(binaryMessenger, instanceManager);
if (!instanceManager.containsInstance(camera)) {
cameraFlutterApi.create(camera, result -> {});
}
return instanceManager.getIdentifierForStrongReference(camera);
}
@Override
public void unbind(@NonNull Long identifier, @NonNull List<Long> useCaseIds) {
ProcessCameraProvider processCameraProvider =
(ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier));
UseCase[] useCases = new UseCase[useCaseIds.size()];
for (int i = 0; i < useCaseIds.size(); i++) {
useCases[i] =
(UseCase)
Objects.requireNonNull(
instanceManager.getInstance(((Number) useCaseIds.get(i)).longValue()));
}
processCameraProvider.unbind(useCases);
}
@Override
public void unbindAll(@NonNull Long identifier) {
ProcessCameraProvider processCameraProvider =
(ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier));
processCameraProvider.unbindAll();
}
}
| plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderHostApiImpl.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderHostApiImpl.java",
"repo_id": "plugins",
"token_count": 2053
} | 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.
// Autogenerated from Pigeon (v3.2.9), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, 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 ResolutionInfo {
ResolutionInfo({
required this.width,
required this.height,
});
int width;
int height;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['width'] = width;
pigeonMap['height'] = height;
return pigeonMap;
}
static ResolutionInfo decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return ResolutionInfo(
width: pigeonMap['width']! as int,
height: pigeonMap['height']! as int,
);
}
}
class CameraPermissionsErrorData {
CameraPermissionsErrorData({
required this.errorCode,
required this.description,
});
String errorCode;
String description;
Object encode() {
final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
pigeonMap['errorCode'] = errorCode;
pigeonMap['description'] = description;
return pigeonMap;
}
static CameraPermissionsErrorData decode(Object message) {
final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
return CameraPermissionsErrorData(
errorCode: pigeonMap['errorCode']! as String,
description: pigeonMap['description']! as String,
);
}
}
class _JavaObjectHostApiCodec extends StandardMessageCodec {
const _JavaObjectHostApiCodec();
}
class JavaObjectHostApi {
/// Constructor for [JavaObjectHostApi]. 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.
JavaObjectHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _JavaObjectHostApiCodec();
Future<void> dispose(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.JavaObjectHostApi.dispose', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier]) 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 {
return;
}
}
}
class _JavaObjectFlutterApiCodec extends StandardMessageCodec {
const _JavaObjectFlutterApiCodec();
}
abstract class JavaObjectFlutterApi {
static const MessageCodec<Object?> codec = _JavaObjectFlutterApiCodec();
void dispose(int identifier);
static void setup(JavaObjectFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.JavaObjectFlutterApi.dispose', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.JavaObjectFlutterApi.dispose was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.JavaObjectFlutterApi.dispose was null, expected non-null int.');
api.dispose(arg_identifier!);
return;
});
}
}
}
}
class _CameraInfoHostApiCodec extends StandardMessageCodec {
const _CameraInfoHostApiCodec();
}
class CameraInfoHostApi {
/// Constructor for [CameraInfoHostApi]. 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.
CameraInfoHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _CameraInfoHostApiCodec();
Future<int> getSensorRotationDegrees(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier]) 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 int?)!;
}
}
}
class _CameraInfoFlutterApiCodec extends StandardMessageCodec {
const _CameraInfoFlutterApiCodec();
}
abstract class CameraInfoFlutterApi {
static const MessageCodec<Object?> codec = _CameraInfoFlutterApiCodec();
void create(int identifier);
static void setup(CameraInfoFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraInfoFlutterApi.create', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.CameraInfoFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.CameraInfoFlutterApi.create was null, expected non-null int.');
api.create(arg_identifier!);
return;
});
}
}
}
}
class _CameraSelectorHostApiCodec extends StandardMessageCodec {
const _CameraSelectorHostApiCodec();
}
class CameraSelectorHostApi {
/// Constructor for [CameraSelectorHostApi]. 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.
CameraSelectorHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _CameraSelectorHostApiCodec();
Future<void> create(int arg_identifier, int? arg_lensFacing) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraSelectorHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier, arg_lensFacing])
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 {
return;
}
}
Future<List<int?>> filter(
int arg_identifier, List<int?> arg_cameraInfoIds) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraSelectorHostApi.filter', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier, arg_cameraInfoIds])
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<int?>();
}
}
}
class _CameraSelectorFlutterApiCodec extends StandardMessageCodec {
const _CameraSelectorFlutterApiCodec();
}
abstract class CameraSelectorFlutterApi {
static const MessageCodec<Object?> codec = _CameraSelectorFlutterApiCodec();
void create(int identifier, int? lensFacing);
static void setup(CameraSelectorFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraSelectorFlutterApi.create', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.CameraSelectorFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.CameraSelectorFlutterApi.create was null, expected non-null int.');
final int? arg_lensFacing = (args[1] as int?);
api.create(arg_identifier!, arg_lensFacing);
return;
});
}
}
}
}
class _ProcessCameraProviderHostApiCodec extends StandardMessageCodec {
const _ProcessCameraProviderHostApiCodec();
}
class ProcessCameraProviderHostApi {
/// Constructor for [ProcessCameraProviderHostApi]. 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.
ProcessCameraProviderHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec =
_ProcessCameraProviderHostApiCodec();
Future<int> getInstance() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.getInstance', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) 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 int?)!;
}
}
Future<List<int?>> getAvailableCameraInfos(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos',
codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier]) 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<int?>();
}
}
Future<int> bindToLifecycle(int arg_identifier,
int arg_cameraSelectorIdentifier, List<int?> arg_useCaseIds) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle',
codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = await channel.send(<Object?>[
arg_identifier,
arg_cameraSelectorIdentifier,
arg_useCaseIds
]) 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 int?)!;
}
}
Future<void> unbind(int arg_identifier, List<int?> arg_useCaseIds) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier, arg_useCaseIds])
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 {
return;
}
}
Future<void> unbindAll(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier]) 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 {
return;
}
}
}
class _ProcessCameraProviderFlutterApiCodec extends StandardMessageCodec {
const _ProcessCameraProviderFlutterApiCodec();
}
abstract class ProcessCameraProviderFlutterApi {
static const MessageCodec<Object?> codec =
_ProcessCameraProviderFlutterApiCodec();
void create(int identifier);
static void setup(ProcessCameraProviderFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.ProcessCameraProviderFlutterApi.create', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.ProcessCameraProviderFlutterApi.create was null, expected non-null int.');
api.create(arg_identifier!);
return;
});
}
}
}
}
class _CameraFlutterApiCodec extends StandardMessageCodec {
const _CameraFlutterApiCodec();
}
abstract class CameraFlutterApi {
static const MessageCodec<Object?> codec = _CameraFlutterApiCodec();
void create(int identifier);
static void setup(CameraFlutterApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.CameraFlutterApi.create', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.CameraFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.CameraFlutterApi.create was null, expected non-null int.');
api.create(arg_identifier!);
return;
});
}
}
}
}
class _SystemServicesHostApiCodec extends StandardMessageCodec {
const _SystemServicesHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is CameraPermissionsErrorData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return CameraPermissionsErrorData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class SystemServicesHostApi {
/// Constructor for [SystemServicesHostApi]. 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.
SystemServicesHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _SystemServicesHostApiCodec();
Future<CameraPermissionsErrorData?> requestCameraPermissions(
bool arg_enableAudio) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions',
codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = await channel
.send(<Object?>[arg_enableAudio]) 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 {
return (replyMap['result'] as CameraPermissionsErrorData?);
}
}
Future<void> startListeningForDeviceOrientationChange(
bool arg_isFrontFacing, int arg_sensorOrientation) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.SystemServicesHostApi.startListeningForDeviceOrientationChange',
codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_isFrontFacing, arg_sensorOrientation])
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 {
return;
}
}
Future<void> stopListeningForDeviceOrientationChange() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.SystemServicesHostApi.stopListeningForDeviceOrientationChange',
codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) 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 {
return;
}
}
}
class _SystemServicesFlutterApiCodec extends StandardMessageCodec {
const _SystemServicesFlutterApiCodec();
}
abstract class SystemServicesFlutterApi {
static const MessageCodec<Object?> codec = _SystemServicesFlutterApiCodec();
void onDeviceOrientationChanged(String orientation);
void onCameraError(String errorDescription);
static void setup(SystemServicesFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.SystemServicesFlutterApi.onDeviceOrientationChanged',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.SystemServicesFlutterApi.onDeviceOrientationChanged was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_orientation = (args[0] as String?);
assert(arg_orientation != null,
'Argument for dev.flutter.pigeon.SystemServicesFlutterApi.onDeviceOrientationChanged was null, expected non-null String.');
api.onDeviceOrientationChanged(arg_orientation!);
return;
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.SystemServicesFlutterApi.onCameraError', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.SystemServicesFlutterApi.onCameraError was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_errorDescription = (args[0] as String?);
assert(arg_errorDescription != null,
'Argument for dev.flutter.pigeon.SystemServicesFlutterApi.onCameraError was null, expected non-null String.');
api.onCameraError(arg_errorDescription!);
return;
});
}
}
}
}
class _PreviewHostApiCodec extends StandardMessageCodec {
const _PreviewHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is ResolutionInfo) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is ResolutionInfo) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return ResolutionInfo.decode(readValue(buffer)!);
case 129:
return ResolutionInfo.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class PreviewHostApi {
/// Constructor for [PreviewHostApi]. 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.
PreviewHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _PreviewHostApiCodec();
Future<void> create(int arg_identifier, int? arg_rotation,
ResolutionInfo? arg_targetResolution) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PreviewHostApi.create', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap = await channel
.send(<Object?>[arg_identifier, arg_rotation, arg_targetResolution])
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 {
return;
}
}
Future<int> setSurfaceProvider(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier]) 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 int?)!;
}
}
Future<void> releaseFlutterSurfaceTexture() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PreviewHostApi.releaseFlutterSurfaceTexture', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(null) 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 {
return;
}
}
Future<ResolutionInfo> getResolutionInfo(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PreviewHostApi.getResolutionInfo', codec,
binaryMessenger: _binaryMessenger);
final Map<Object?, Object?>? replyMap =
await channel.send(<Object?>[arg_identifier]) 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 ResolutionInfo?)!;
}
}
}
| plugins/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart",
"repo_id": "plugins",
"token_count": 11901
} | 1,146 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_android_camerax/src/camera.dart';
import 'package:camera_android_camerax/src/instance_manager.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Camera', () {
test('flutterApiCreateTest', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CameraFlutterApiImpl flutterApi = CameraFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(0);
expect(instanceManager.getInstanceWithWeakReference(0), isA<Camera>());
});
});
}
| plugins/packages/camera/camera_android_camerax/test/camera_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/test/camera_test.dart",
"repo_id": "plugins",
"token_count": 283
} | 1,147 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import AVFoundation;
#import "CameraPermissionUtils.h"
void FLTRequestPermission(BOOL forAudio, FLTCameraPermissionRequestCompletionHandler handler) {
AVMediaType mediaType;
if (forAudio) {
mediaType = AVMediaTypeAudio;
} else {
mediaType = AVMediaTypeVideo;
}
switch ([AVCaptureDevice authorizationStatusForMediaType:mediaType]) {
case AVAuthorizationStatusAuthorized:
handler(nil);
break;
case AVAuthorizationStatusDenied: {
FlutterError *flutterError;
if (forAudio) {
flutterError =
[FlutterError errorWithCode:@"AudioAccessDeniedWithoutPrompt"
message:@"User has previously denied the audio access request. "
@"Go to Settings to enable audio access."
details:nil];
} else {
flutterError =
[FlutterError errorWithCode:@"CameraAccessDeniedWithoutPrompt"
message:@"User has previously denied the camera access request. "
@"Go to Settings to enable camera access."
details:nil];
}
handler(flutterError);
break;
}
case AVAuthorizationStatusRestricted: {
FlutterError *flutterError;
if (forAudio) {
flutterError = [FlutterError errorWithCode:@"AudioAccessRestricted"
message:@"Audio access is restricted. "
details:nil];
} else {
flutterError = [FlutterError errorWithCode:@"CameraAccessRestricted"
message:@"Camera access is restricted. "
details:nil];
}
handler(flutterError);
break;
}
case AVAuthorizationStatusNotDetermined: {
[AVCaptureDevice requestAccessForMediaType:mediaType
completionHandler:^(BOOL granted) {
// handler can be invoked on an arbitrary dispatch queue.
if (granted) {
handler(nil);
} else {
FlutterError *flutterError;
if (forAudio) {
flutterError = [FlutterError
errorWithCode:@"AudioAccessDenied"
message:@"User denied the audio access request."
details:nil];
} else {
flutterError = [FlutterError
errorWithCode:@"CameraAccessDenied"
message:@"User denied the camera access request."
details:nil];
}
handler(flutterError);
}
}];
break;
}
}
}
void FLTRequestCameraPermissionWithCompletionHandler(
FLTCameraPermissionRequestCompletionHandler handler) {
FLTRequestPermission(/*forAudio*/ NO, handler);
}
void FLTRequestAudioPermissionWithCompletionHandler(
FLTCameraPermissionRequestCompletionHandler handler) {
FLTRequestPermission(/*forAudio*/ YES, handler);
}
| plugins/packages/camera/camera_avfoundation/ios/Classes/CameraPermissionUtils.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/CameraPermissionUtils.m",
"repo_id": "plugins",
"token_count": 1971
} | 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 "FLTThreadSafeFlutterResult.h"
#import <Foundation/Foundation.h>
#import "QueueUtils.h"
@implementation FLTThreadSafeFlutterResult {
}
- (id)initWithResult:(FlutterResult)result {
self = [super init];
if (!self) {
return nil;
}
_flutterResult = result;
return self;
}
- (void)sendSuccess {
[self send:nil];
}
- (void)sendSuccessWithData:(id)data {
[self send:data];
}
- (void)sendError:(NSError *)error {
[self sendErrorWithCode:[NSString stringWithFormat:@"Error %d", (int)error.code]
message:error.localizedDescription
details:error.domain];
}
- (void)sendErrorWithCode:(NSString *)code
message:(NSString *_Nullable)message
details:(id _Nullable)details {
FlutterError *flutterError = [FlutterError errorWithCode:code message:message details:details];
[self send:flutterError];
}
- (void)sendFlutterError:(FlutterError *)flutterError {
[self send:flutterError];
}
- (void)sendNotImplemented {
[self send:FlutterMethodNotImplemented];
}
/**
* Sends result to flutterResult on the main thread.
*/
- (void)send:(id _Nullable)result {
FLTEnsureToRunOnMainQueue(^{
// WARNING: Should not use weak self, because `FlutterResult`s are passed as arguments
// (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.
self.flutterResult(result);
});
}
@end
| plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeFlutterResult.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTThreadSafeFlutterResult.m",
"repo_id": "plugins",
"token_count": 636
} | 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.
/// The possible flash modes that can be set for a camera
enum FlashMode {
/// Do not use the flash when taking a picture.
off,
/// Let the device decide whether to flash the camera when taking a picture.
auto,
/// Always use the flash when taking a picture.
always,
/// Turns on the flash light and keeps it on until switched off.
torch,
}
| plugins/packages/camera/camera_platform_interface/lib/src/types/flash_mode.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/lib/src/types/flash_mode.dart",
"repo_id": "plugins",
"token_count": 136
} | 1,150 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_platform_interface/src/types/exposure_mode.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('ExposureMode should contain 2 options', () {
const List<ExposureMode> values = ExposureMode.values;
expect(values.length, 2);
});
test('ExposureMode enum should have items in correct index', () {
const List<ExposureMode> values = ExposureMode.values;
expect(values[0], ExposureMode.auto);
expect(values[1], ExposureMode.locked);
});
test('serializeExposureMode() should serialize correctly', () {
expect(serializeExposureMode(ExposureMode.auto), 'auto');
expect(serializeExposureMode(ExposureMode.locked), 'locked');
});
test('deserializeExposureMode() should deserialize correctly', () {
expect(deserializeExposureMode('auto'), ExposureMode.auto);
expect(deserializeExposureMode('locked'), ExposureMode.locked);
});
}
| plugins/packages/camera/camera_platform_interface/test/types/exposure_mode_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/test/types/exposure_mode_test.dart",
"repo_id": "plugins",
"token_count": 350
} | 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.
#ifndef PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PHOTO_HANDLER_H_
#define PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PHOTO_HANDLER_H_
#include <mfapi.h>
#include <mfcaptureengine.h>
#include <wrl/client.h>
#include <memory>
#include <string>
#include "capture_engine_listener.h"
namespace camera_windows {
using Microsoft::WRL::ComPtr;
// Various states that the photo handler can be in.
//
// When created, the handler is in |kNotStarted| state and transtions in
// sequential order through the states.
enum class PhotoState {
kNotStarted,
kIdle,
kTakingPhoto,
};
// Handles photo sink initialization and tracks photo capture states.
class PhotoHandler {
public:
PhotoHandler() {}
virtual ~PhotoHandler() = default;
// Prevent copying.
PhotoHandler(PhotoHandler const&) = delete;
PhotoHandler& operator=(PhotoHandler const&) = delete;
// Initializes photo sink if not initialized and requests the capture engine
// to take photo.
//
// Sets photo state to: kTakingPhoto.
//
// capture_engine: A pointer to capture engine instance.
// Called to take the photo.
// base_media_type: A pointer to base media type used as a base
// for the actual photo capture media type.
// file_path: A string that hold file path for photo capture.
HRESULT TakePhoto(const std::string& file_path,
IMFCaptureEngine* capture_engine,
IMFMediaType* base_media_type);
// Set the photo handler recording state to: kIdle.
void OnPhotoTaken();
// Returns true if photo state is kIdle.
bool IsInitialized() const { return photo_state_ == PhotoState::kIdle; }
// Returns true if photo state is kTakingPhoto.
bool IsTakingPhoto() const {
return photo_state_ == PhotoState::kTakingPhoto;
}
// Returns the filesystem path of the captured photo.
std::string GetPhotoPath() const { return file_path_; }
private:
// Initializes record sink for video file capture.
HRESULT InitPhotoSink(IMFCaptureEngine* capture_engine,
IMFMediaType* base_media_type);
std::string file_path_;
PhotoState photo_state_ = PhotoState::kNotStarted;
ComPtr<IMFCapturePhotoSink> photo_sink_;
};
} // namespace camera_windows
#endif // PACKAGES_CAMERA_CAMERA_WINDOWS_WINDOWS_PHOTO_HANDLER_H_
| plugins/packages/camera/camera_windows/windows/photo_handler.h/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/photo_handler.h",
"repo_id": "plugins",
"token_count": 836
} | 1,152 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'fake_maps_controllers.dart';
Widget _mapWithMarkers(Set<Marker> markers) {
return Directionality(
textDirection: TextDirection.ltr,
child: GoogleMap(
initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)),
markers: markers,
),
);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final FakePlatformViewsController fakePlatformViewsController =
FakePlatformViewsController();
setUpAll(() {
_ambiguate(TestDefaultBinaryMessengerBinding.instance)!
.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.platform_views,
fakePlatformViewsController.fakePlatformViewsMethodHandler,
);
});
setUp(() {
fakePlatformViewsController.reset();
});
testWidgets('Initializing a marker', (WidgetTester tester) async {
const Marker m1 = Marker(markerId: MarkerId('marker_1'));
await tester.pumpWidget(_mapWithMarkers(<Marker>{m1}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markersToAdd.length, 1);
final Marker initializedMarker = platformGoogleMap.markersToAdd.first;
expect(initializedMarker, equals(m1));
expect(platformGoogleMap.markerIdsToRemove.isEmpty, true);
expect(platformGoogleMap.markersToChange.isEmpty, true);
});
testWidgets('Adding a marker', (WidgetTester tester) async {
const Marker m1 = Marker(markerId: MarkerId('marker_1'));
const Marker m2 = Marker(markerId: MarkerId('marker_2'));
await tester.pumpWidget(_mapWithMarkers(<Marker>{m1}));
await tester.pumpWidget(_mapWithMarkers(<Marker>{m1, m2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markersToAdd.length, 1);
final Marker addedMarker = platformGoogleMap.markersToAdd.first;
expect(addedMarker, equals(m2));
expect(platformGoogleMap.markerIdsToRemove.isEmpty, true);
expect(platformGoogleMap.markersToChange.isEmpty, true);
});
testWidgets('Removing a marker', (WidgetTester tester) async {
const Marker m1 = Marker(markerId: MarkerId('marker_1'));
await tester.pumpWidget(_mapWithMarkers(<Marker>{m1}));
await tester.pumpWidget(_mapWithMarkers(<Marker>{}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markerIdsToRemove.length, 1);
expect(platformGoogleMap.markerIdsToRemove.first, equals(m1.markerId));
expect(platformGoogleMap.markersToChange.isEmpty, true);
expect(platformGoogleMap.markersToAdd.isEmpty, true);
});
testWidgets('Updating a marker', (WidgetTester tester) async {
const Marker m1 = Marker(markerId: MarkerId('marker_1'));
const Marker m2 = Marker(markerId: MarkerId('marker_1'), alpha: 0.5);
await tester.pumpWidget(_mapWithMarkers(<Marker>{m1}));
await tester.pumpWidget(_mapWithMarkers(<Marker>{m2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markersToChange.length, 1);
expect(platformGoogleMap.markersToChange.first, equals(m2));
expect(platformGoogleMap.markerIdsToRemove.isEmpty, true);
expect(platformGoogleMap.markersToAdd.isEmpty, true);
});
testWidgets('Updating a marker', (WidgetTester tester) async {
const Marker m1 = Marker(markerId: MarkerId('marker_1'));
const Marker m2 = Marker(
markerId: MarkerId('marker_1'),
infoWindow: InfoWindow(snippet: 'changed'),
);
await tester.pumpWidget(_mapWithMarkers(<Marker>{m1}));
await tester.pumpWidget(_mapWithMarkers(<Marker>{m2}));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markersToChange.length, 1);
final Marker update = platformGoogleMap.markersToChange.first;
expect(update, equals(m2));
expect(update.infoWindow.snippet, 'changed');
});
testWidgets('Multi Update', (WidgetTester tester) async {
Marker m1 = const Marker(markerId: MarkerId('marker_1'));
Marker m2 = const Marker(markerId: MarkerId('marker_2'));
final Set<Marker> prev = <Marker>{m1, m2};
m1 = const Marker(markerId: MarkerId('marker_1'), visible: false);
m2 = const Marker(markerId: MarkerId('marker_2'), draggable: true);
final Set<Marker> cur = <Marker>{m1, m2};
await tester.pumpWidget(_mapWithMarkers(prev));
await tester.pumpWidget(_mapWithMarkers(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markersToChange, cur);
expect(platformGoogleMap.markerIdsToRemove.isEmpty, true);
expect(platformGoogleMap.markersToAdd.isEmpty, true);
});
testWidgets('Multi Update', (WidgetTester tester) async {
Marker m2 = const Marker(markerId: MarkerId('marker_2'));
const Marker m3 = Marker(markerId: MarkerId('marker_3'));
final Set<Marker> prev = <Marker>{m2, m3};
// m1 is added, m2 is updated, m3 is removed.
const Marker m1 = Marker(markerId: MarkerId('marker_1'));
m2 = const Marker(markerId: MarkerId('marker_2'), draggable: true);
final Set<Marker> cur = <Marker>{m1, m2};
await tester.pumpWidget(_mapWithMarkers(prev));
await tester.pumpWidget(_mapWithMarkers(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markersToChange.length, 1);
expect(platformGoogleMap.markersToAdd.length, 1);
expect(platformGoogleMap.markerIdsToRemove.length, 1);
expect(platformGoogleMap.markersToChange.first, equals(m2));
expect(platformGoogleMap.markersToAdd.first, equals(m1));
expect(platformGoogleMap.markerIdsToRemove.first, equals(m3.markerId));
});
testWidgets('Partial Update', (WidgetTester tester) async {
const Marker m1 = Marker(markerId: MarkerId('marker_1'));
const Marker m2 = Marker(markerId: MarkerId('marker_2'));
Marker m3 = const Marker(markerId: MarkerId('marker_3'));
final Set<Marker> prev = <Marker>{m1, m2, m3};
m3 = const Marker(markerId: MarkerId('marker_3'), draggable: true);
final Set<Marker> cur = <Marker>{m1, m2, m3};
await tester.pumpWidget(_mapWithMarkers(prev));
await tester.pumpWidget(_mapWithMarkers(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markersToChange, <Marker>{m3});
expect(platformGoogleMap.markerIdsToRemove.isEmpty, true);
expect(platformGoogleMap.markersToAdd.isEmpty, true);
});
testWidgets('Update non platform related attr', (WidgetTester tester) async {
Marker m1 = const Marker(markerId: MarkerId('marker_1'));
final Set<Marker> prev = <Marker>{m1};
m1 = Marker(
markerId: const MarkerId('marker_1'),
onTap: () {},
onDragEnd: (LatLng latLng) {});
final Set<Marker> cur = <Marker>{m1};
await tester.pumpWidget(_mapWithMarkers(prev));
await tester.pumpWidget(_mapWithMarkers(cur));
final FakePlatformGoogleMap platformGoogleMap =
fakePlatformViewsController.lastCreatedView!;
expect(platformGoogleMap.markersToChange.isEmpty, true);
expect(platformGoogleMap.markerIdsToRemove.isEmpty, true);
expect(platformGoogleMap.markersToAdd.isEmpty, true);
});
}
/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
T? _ambiguate<T>(T? value) => value;
| plugins/packages/google_maps_flutter/google_maps_flutter/test/marker_updates_test.dart/0 | {
"file_path": "plugins/packages/google_maps_flutter/google_maps_flutter/test/marker_updates_test.dart",
"repo_id": "plugins",
"token_count": 3000
} | 1,153 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.