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.
package io.flutter.plugins.webviewflutter;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.FlutterAssetManagerHostApi;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Host api implementation for {@link WebView}.
*
* <p>Handles creating {@link WebView}s that intercommunicate with a paired Dart object.
*/
public class FlutterAssetManagerHostApiImpl implements FlutterAssetManagerHostApi {
final FlutterAssetManager flutterAssetManager;
/** Constructs a new instance of {@link FlutterAssetManagerHostApiImpl}. */
public FlutterAssetManagerHostApiImpl(@NonNull FlutterAssetManager flutterAssetManager) {
this.flutterAssetManager = flutterAssetManager;
}
@NonNull
@Override
public List<String> list(@NonNull String path) {
try {
String[] paths = flutterAssetManager.list(path);
if (paths == null) {
return new ArrayList<>();
}
return Arrays.asList(paths);
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage());
}
}
@NonNull
@Override
public String getAssetFilePathByName(@NonNull String name) {
return flutterAssetManager.getAssetFilePathByName(name);
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterAssetManagerHostApiImpl.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/FlutterAssetManagerHostApiImpl.java",
"repo_id": "packages",
"token_count": 471
} | 1,120 |
// 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.net.Uri;
import android.os.Build;
import android.os.Message;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebChromeClientHostApi;
import java.util.Objects;
/**
* Host api implementation for {@link WebChromeClient}.
*
* <p>Handles creating {@link WebChromeClient}s that intercommunicate with a paired Dart object.
*/
public class WebChromeClientHostApiImpl implements WebChromeClientHostApi {
private final InstanceManager instanceManager;
private final WebChromeClientCreator webChromeClientCreator;
private final WebChromeClientFlutterApiImpl flutterApi;
private Context context;
/**
* Implementation of {@link WebChromeClient} that passes arguments of callback methods to Dart.
*/
public static class WebChromeClientImpl extends SecureWebChromeClient {
private final WebChromeClientFlutterApiImpl flutterApi;
private boolean returnValueForOnShowFileChooser = false;
private boolean returnValueForOnConsoleMessage = false;
private boolean returnValueForOnJsAlert = false;
private boolean returnValueForOnJsConfirm = false;
private boolean returnValueForOnJsPrompt = false;
/**
* Creates a {@link WebChromeClient} that passes arguments of callbacks methods to Dart.
*
* @param flutterApi handles sending messages to Dart
*/
public WebChromeClientImpl(@NonNull WebChromeClientFlutterApiImpl flutterApi) {
this.flutterApi = flutterApi;
}
@Override
public void onProgressChanged(@NonNull WebView view, int progress) {
flutterApi.onProgressChanged(this, view, (long) progress, reply -> {});
}
@Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
flutterApi.onShowCustomView(this, view, callback, reply -> {});
}
@Override
public void onHideCustomView() {
flutterApi.onHideCustomView(this, reply -> {});
}
public void onGeolocationPermissionsShowPrompt(
@NonNull String origin, @NonNull GeolocationPermissions.Callback callback) {
flutterApi.onGeolocationPermissionsShowPrompt(this, origin, callback, reply -> {});
}
@Override
public void onGeolocationPermissionsHidePrompt() {
flutterApi.onGeolocationPermissionsHidePrompt(this, reply -> {});
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@SuppressWarnings("LambdaLast")
@Override
public boolean onShowFileChooser(
@NonNull WebView webView,
@NonNull ValueCallback<Uri[]> filePathCallback,
@NonNull FileChooserParams fileChooserParams) {
final boolean currentReturnValueForOnShowFileChooser = returnValueForOnShowFileChooser;
flutterApi.onShowFileChooser(
this,
webView,
fileChooserParams,
reply -> {
// The returned list of file paths can only be passed to `filePathCallback` if the
// `onShowFileChooser` method returned true.
if (currentReturnValueForOnShowFileChooser) {
final Uri[] filePaths = new Uri[reply.size()];
for (int i = 0; i < reply.size(); i++) {
filePaths[i] = Uri.parse(reply.get(i));
}
filePathCallback.onReceiveValue(filePaths);
}
});
return currentReturnValueForOnShowFileChooser;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onPermissionRequest(@NonNull PermissionRequest request) {
flutterApi.onPermissionRequest(this, request, reply -> {});
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
flutterApi.onConsoleMessage(this, consoleMessage, reply -> {});
return returnValueForOnConsoleMessage;
}
/** Sets return value for {@link #onShowFileChooser}. */
public void setReturnValueForOnShowFileChooser(boolean value) {
returnValueForOnShowFileChooser = value;
}
/** Sets return value for {@link #onConsoleMessage}. */
public void setReturnValueForOnConsoleMessage(boolean value) {
returnValueForOnConsoleMessage = value;
}
public void setReturnValueForOnJsAlert(boolean value) {
returnValueForOnJsAlert = value;
}
public void setReturnValueForOnJsConfirm(boolean value) {
returnValueForOnJsConfirm = value;
}
public void setReturnValueForOnJsPrompt(boolean value) {
returnValueForOnJsPrompt = value;
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
if (returnValueForOnJsAlert) {
flutterApi.onJsAlert(
this,
url,
message,
reply -> {
result.confirm();
});
return true;
} else {
return false;
}
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
if (returnValueForOnJsConfirm) {
flutterApi.onJsConfirm(
this,
url,
message,
reply -> {
if (reply) {
result.confirm();
} else {
result.cancel();
}
});
return true;
} else {
return false;
}
}
@Override
public boolean onJsPrompt(
WebView view, String url, String message, String defaultValue, JsPromptResult result) {
if (returnValueForOnJsPrompt) {
flutterApi.onJsPrompt(
this,
url,
message,
defaultValue,
reply -> {
@Nullable String inputMessage = reply;
if (inputMessage != null) {
result.confirm(inputMessage);
} else {
result.cancel();
}
});
return true;
} else {
return false;
}
}
}
/**
* Implementation of {@link WebChromeClient} that only allows secure urls when opening a new
* window.
*/
public static class SecureWebChromeClient extends WebChromeClient {
@Nullable WebViewClient webViewClient;
@Override
public boolean onCreateWindow(
@NonNull final WebView view,
boolean isDialog,
boolean isUserGesture,
@NonNull Message resultMsg) {
return onCreateWindow(view, resultMsg, new WebView(view.getContext()));
}
/**
* Verifies that a url opened by `Window.open` has a secure url.
*
* @param view the WebView from which the request for a new window originated.
* @param resultMsg the message to send when once a new WebView has been created. resultMsg.obj
* is a {@link WebView.WebViewTransport} object. This should be used to transport the new
* WebView, by calling WebView.WebViewTransport.setWebView(WebView)
* @param onCreateWindowWebView the temporary WebView used to verify the url is secure
* @return this method should return true if the host application will create a new window, in
* which case resultMsg should be sent to its target. Otherwise, this method should return
* false. Returning false from this method but also sending resultMsg will result in
* undefined behavior
*/
@VisibleForTesting
boolean onCreateWindow(
@NonNull final WebView view,
@NonNull Message resultMsg,
@Nullable WebView onCreateWindowWebView) {
// WebChromeClient requires a WebViewClient because of a bug fix that makes
// calls to WebViewClient.requestLoading/WebViewClient.urlLoading when a new
// window is opened. This is to make sure a url opened by `Window.open` has
// a secure url.
if (webViewClient == null) {
return false;
}
final WebViewClient windowWebViewClient =
new WebViewClient() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(
@NonNull WebView windowWebView, @NonNull WebResourceRequest request) {
if (!webViewClient.shouldOverrideUrlLoading(view, request)) {
view.loadUrl(request.getUrl().toString());
}
return true;
}
// Legacy codepath for < N.
@Override
@SuppressWarnings({"deprecation", "RedundantSuppression"})
public boolean shouldOverrideUrlLoading(WebView windowWebView, String url) {
if (!webViewClient.shouldOverrideUrlLoading(view, url)) {
view.loadUrl(url);
}
return true;
}
};
if (onCreateWindowWebView == null) {
onCreateWindowWebView = new WebView(view.getContext());
}
onCreateWindowWebView.setWebViewClient(windowWebViewClient);
final WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(onCreateWindowWebView);
resultMsg.sendToTarget();
return true;
}
/**
* Set the {@link WebViewClient} that calls to {@link WebChromeClient#onCreateWindow} are passed
* to.
*
* @param webViewClient the forwarding {@link WebViewClient}
*/
public void setWebViewClient(@NonNull WebViewClient webViewClient) {
this.webViewClient = webViewClient;
}
}
/** Handles creating {@link WebChromeClient}s for a {@link WebChromeClientHostApiImpl}. */
public static class WebChromeClientCreator {
/**
* Creates a {@link WebChromeClientHostApiImpl.WebChromeClientImpl}.
*
* @param flutterApi handles sending messages to Dart
* @return the created {@link WebChromeClientHostApiImpl.WebChromeClientImpl}
*/
@NonNull
public WebChromeClientImpl createWebChromeClient(
@NonNull WebChromeClientFlutterApiImpl flutterApi) {
return new WebChromeClientImpl(flutterApi);
}
}
/**
* Creates a host API that handles creating {@link WebChromeClient}s.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param webChromeClientCreator handles creating {@link WebChromeClient}s
* @param flutterApi handles sending messages to Dart
*/
public WebChromeClientHostApiImpl(
@NonNull InstanceManager instanceManager,
@NonNull WebChromeClientCreator webChromeClientCreator,
@NonNull WebChromeClientFlutterApiImpl flutterApi) {
this.instanceManager = instanceManager;
this.webChromeClientCreator = webChromeClientCreator;
this.flutterApi = flutterApi;
}
@Override
public void create(@NonNull Long instanceId) {
final WebChromeClient webChromeClient =
webChromeClientCreator.createWebChromeClient(flutterApi);
instanceManager.addDartCreatedInstance(webChromeClient, instanceId);
}
@Override
public void setSynchronousReturnValueForOnShowFileChooser(
@NonNull Long instanceId, @NonNull Boolean value) {
final WebChromeClientImpl webChromeClient =
Objects.requireNonNull(instanceManager.getInstance(instanceId));
webChromeClient.setReturnValueForOnShowFileChooser(value);
}
@Override
public void setSynchronousReturnValueForOnConsoleMessage(
@NonNull Long instanceId, @NonNull Boolean value) {
final WebChromeClientImpl webChromeClient =
Objects.requireNonNull(instanceManager.getInstance(instanceId));
webChromeClient.setReturnValueForOnConsoleMessage(value);
}
@Override
public void setSynchronousReturnValueForOnJsAlert(
@NonNull Long instanceId, @NonNull Boolean value) {
final WebChromeClientImpl webChromeClient =
Objects.requireNonNull(instanceManager.getInstance(instanceId));
webChromeClient.setReturnValueForOnJsAlert(value);
}
@Override
public void setSynchronousReturnValueForOnJsConfirm(
@NonNull Long instanceId, @NonNull Boolean value) {
final WebChromeClientImpl webChromeClient =
Objects.requireNonNull(instanceManager.getInstance(instanceId));
webChromeClient.setReturnValueForOnJsConfirm(value);
}
@Override
public void setSynchronousReturnValueForOnJsPrompt(
@NonNull Long instanceId, @NonNull Boolean value) {
final WebChromeClientImpl webChromeClient =
Objects.requireNonNull(instanceManager.getInstance(instanceId));
webChromeClient.setReturnValueForOnJsPrompt(value);
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebChromeClientHostApiImpl.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebChromeClientHostApiImpl.java",
"repo_id": "packages",
"token_count": 4957
} | 1,121 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import android.webkit.HttpAuthHandler;
import io.flutter.plugin.common.BinaryMessenger;
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 HttpAuthHandlerTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock HttpAuthHandler mockAuthHandler;
@Mock BinaryMessenger mockBinaryMessenger;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Test
public void proceed() {
final HttpAuthHandlerHostApiImpl hostApi =
new HttpAuthHandlerHostApiImpl(mockBinaryMessenger, instanceManager);
final long instanceIdentifier = 65L;
final String username = "username";
final String password = "password";
instanceManager.addDartCreatedInstance(mockAuthHandler, instanceIdentifier);
hostApi.proceed(instanceIdentifier, username, password);
verify(mockAuthHandler).proceed(eq(username), eq(password));
}
@Test
public void cancel() {
final HttpAuthHandlerHostApiImpl hostApi =
new HttpAuthHandlerHostApiImpl(mockBinaryMessenger, instanceManager);
final long instanceIdentifier = 65L;
instanceManager.addDartCreatedInstance(mockAuthHandler, instanceIdentifier);
hostApi.cancel(instanceIdentifier);
verify(mockAuthHandler).cancel();
}
@Test
public void useHttpAuthUsernamePassword() {
final HttpAuthHandlerHostApiImpl hostApi =
new HttpAuthHandlerHostApiImpl(mockBinaryMessenger, instanceManager);
final long instanceIdentifier = 65L;
instanceManager.addDartCreatedInstance(mockAuthHandler, instanceIdentifier);
hostApi.useHttpAuthUsernamePassword(instanceIdentifier);
verify(mockAuthHandler).useHttpAuthUsernamePassword();
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/HttpAuthHandlerTest.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/HttpAuthHandlerTest.java",
"repo_id": "packages",
"token_count": 738
} | 1,122 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
void main() {
runApp(const MaterialApp(home: WebViewExample()));
}
const String kNavigationExamplePage = '''
<!DOCTYPE html><html>
<head><title>Navigation Delegate Example</title></head>
<body>
<p>
The navigation delegate is set to block navigation to the youtube website.
</p>
<ul>
<ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
<ul><a href="https://www.google.com/">https://www.google.com/</a></ul>
</ul>
</body>
</html>
''';
const String kLocalExamplePage = '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Load file or HTML string example</title>
</head>
<body>
<h1>Local demo page</h1>
<p>
This is an example page used to demonstrate how to load a local file or HTML
string using the <a href="https://pub.dev/packages/webview_flutter">Flutter
webview</a> plugin.
</p>
</body>
</html>
''';
const String kTransparentBackgroundPage = '''
<!DOCTYPE html>
<html>
<head>
<title>Transparent background test</title>
</head>
<style type="text/css">
body { background: transparent; margin: 0; padding: 0; }
#container { position: relative; margin: 0; padding: 0; width: 100vw; height: 100vh; }
#shape { background: #FF0000; width: 200px; height: 100%; margin: 0; padding: 0; position: absolute; top: 0; bottom: 0; left: calc(50% - 100px); }
p { text-align: center; }
</style>
<body>
<div id="container">
<p>Transparent background test</p>
<div id="shape"></div>
</div>
</body>
</html>
''';
const String kLogExamplePage = '''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Load file or HTML string example</title>
</head>
<body onload="console.log('Logging that the page is loading.')">
<h1>Local demo page</h1>
<p>
This page is used to test the forwarding of console logs to Dart.
</p>
<style>
.btn-group button {
padding: 24px; 24px;
display: block;
width: 25%;
margin: 5px 0px 0px 0px;
}
</style>
<div class="btn-group">
<button onclick="console.error('This is an error message.')">Error</button>
<button onclick="console.warn('This is a warning message.')">Warning</button>
<button onclick="console.info('This is a info message.')">Info</button>
<button onclick="console.debug('This is a debug message.')">Debug</button>
<button onclick="console.log('This is a log message.')">Log</button>
</div>
</body>
</html>
''';
const String kAlertTestPage = '''
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function showAlert(text) {
alert(text);
}
function showConfirm(text) {
var result = confirm(text);
alert(result);
}
function showPrompt(text, defaultText) {
var inputString = prompt('Enter input', 'Default text');
alert(inputString);
}
</script>
</head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type = "button" value = "Alert" onclick = "showAlert('Test Alert');" />
<input type = "button" value = "Confirm" onclick = "showConfirm('Test Confirm');" />
<input type = "button" value = "Prompt" onclick = "showPrompt('Test Prompt', 'Default Value');" />
</form>
</body>
</html>
''';
class WebViewExample extends StatefulWidget {
const WebViewExample({super.key, this.cookieManager});
final PlatformWebViewCookieManager? cookieManager;
@override
State<WebViewExample> createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
late final PlatformWebViewController _controller;
@override
void initState() {
super.initState();
_controller = PlatformWebViewController(
AndroidWebViewControllerCreationParams(),
)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x80000000))
..setPlatformNavigationDelegate(
PlatformNavigationDelegate(
const PlatformNavigationDelegateCreationParams(),
)
..setOnProgress((int progress) {
debugPrint('WebView is loading (progress : $progress%)');
})
..setOnPageStarted((String url) {
debugPrint('Page started loading: $url');
})
..setOnPageFinished((String url) {
debugPrint('Page finished loading: $url');
})
..setOnHttpError((HttpResponseError error) {
debugPrint(
'HTTP error occured on page: ${error.response?.statusCode}',
);
})
..setOnWebResourceError((WebResourceError error) {
debugPrint('''
Page resource error:
code: ${error.errorCode}
description: ${error.description}
errorType: ${error.errorType}
isForMainFrame: ${error.isForMainFrame}
url: ${error.url}
''');
})
..setOnNavigationRequest((NavigationRequest request) {
if (request.url.contains('pub.dev')) {
debugPrint('blocking navigation to ${request.url}');
return NavigationDecision.prevent;
}
debugPrint('allowing navigation to ${request.url}');
return NavigationDecision.navigate;
})
..setOnUrlChange((UrlChange change) {
debugPrint('url change to ${change.url}');
})
..setOnHttpAuthRequest((HttpAuthRequest request) {
openDialog(request);
}),
)
..addJavaScriptChannel(JavaScriptChannelParams(
name: 'Toaster',
onMessageReceived: (JavaScriptMessage message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message.message)),
);
},
))
..setOnPlatformPermissionRequest(
(PlatformWebViewPermissionRequest request) {
debugPrint(
'requesting permissions for ${request.types.map((WebViewPermissionResourceType type) => type.name)}',
);
request.grant();
},
)
..loadRequest(
LoadRequestParams(
uri: Uri.parse('https://flutter.dev'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF4CAF50),
appBar: AppBar(
title: const Text('Flutter WebView example'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[
NavigationControls(webViewController: _controller),
SampleMenu(
webViewController: _controller,
cookieManager: widget.cookieManager,
),
],
),
body: PlatformWebViewWidget(
PlatformWebViewWidgetCreationParams(controller: _controller),
).build(context),
floatingActionButton: favoriteButton(),
);
}
Widget favoriteButton() {
return FloatingActionButton(
onPressed: () async {
final String? url = await _controller.currentUrl();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Favorited $url')),
);
}
},
child: const Icon(Icons.favorite),
);
}
Future<void> openDialog(HttpAuthRequest httpRequest) async {
final TextEditingController usernameTextController =
TextEditingController();
final TextEditingController passwordTextController =
TextEditingController();
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('${httpRequest.host}: ${httpRequest.realm ?? '-'}'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
decoration: const InputDecoration(labelText: 'Username'),
autofocus: true,
controller: usernameTextController,
),
TextField(
decoration: const InputDecoration(labelText: 'Password'),
controller: passwordTextController,
),
],
),
actions: <Widget>[
TextButton(
onPressed: () {
httpRequest.onProceed(
WebViewCredential(
user: usernameTextController.text,
password: passwordTextController.text,
),
);
Navigator.of(context).pop();
},
child: const Text('Authenticate'),
),
],
);
},
);
}
}
enum MenuOptions {
showUserAgent,
listCookies,
clearCookies,
addToCache,
listCache,
clearCache,
navigationDelegate,
doPostRequest,
loadLocalFile,
loadFlutterAsset,
loadHtmlString,
transparentBackground,
setCookie,
videoExample,
logExample,
basicAuthentication,
javaScriptAlert,
}
class SampleMenu extends StatelessWidget {
SampleMenu({
super.key,
required this.webViewController,
PlatformWebViewCookieManager? cookieManager,
}) : cookieManager = cookieManager ??
PlatformWebViewCookieManager(
const PlatformWebViewCookieManagerCreationParams(),
);
final PlatformWebViewController webViewController;
late final PlatformWebViewCookieManager cookieManager;
@override
Widget build(BuildContext context) {
return PopupMenuButton<MenuOptions>(
key: const ValueKey<String>('ShowPopupMenu'),
onSelected: (MenuOptions value) {
switch (value) {
case MenuOptions.showUserAgent:
_onShowUserAgent();
case MenuOptions.listCookies:
_onListCookies(context);
case MenuOptions.clearCookies:
_onClearCookies(context);
case MenuOptions.addToCache:
_onAddToCache(context);
case MenuOptions.listCache:
_onListCache();
case MenuOptions.clearCache:
_onClearCache(context);
case MenuOptions.navigationDelegate:
_onNavigationDelegateExample();
case MenuOptions.doPostRequest:
_onDoPostRequest();
case MenuOptions.loadLocalFile:
_onLoadLocalFileExample();
case MenuOptions.loadFlutterAsset:
_onLoadFlutterAssetExample();
case MenuOptions.loadHtmlString:
_onLoadHtmlStringExample();
case MenuOptions.transparentBackground:
_onTransparentBackground();
case MenuOptions.setCookie:
_onSetCookie();
case MenuOptions.videoExample:
_onVideoExample(context);
case MenuOptions.logExample:
_onLogExample();
case MenuOptions.basicAuthentication:
_promptForUrl(context);
case MenuOptions.javaScriptAlert:
_onJavaScriptAlertExample(context);
}
},
itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[
const PopupMenuItem<MenuOptions>(
value: MenuOptions.showUserAgent,
child: Text('Show user agent'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.listCookies,
child: Text('List cookies'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.clearCookies,
child: Text('Clear cookies'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.addToCache,
child: Text('Add to cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.listCache,
child: Text('List cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.clearCache,
child: Text('Clear cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.navigationDelegate,
child: Text('Navigation Delegate example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.doPostRequest,
child: Text('Post Request'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadHtmlString,
child: Text('Load HTML string'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadLocalFile,
child: Text('Load local file'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.loadFlutterAsset,
child: Text('Load Flutter Asset'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.setCookie,
child: Text('Set cookie'),
),
const PopupMenuItem<MenuOptions>(
key: ValueKey<String>('ShowTransparentBackgroundExample'),
value: MenuOptions.transparentBackground,
child: Text('Transparent background example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.logExample,
child: Text('Log example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.videoExample,
child: Text('Video example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.basicAuthentication,
child: Text('Basic Authentication Example'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.javaScriptAlert,
child: Text('JavaScript Alert Example'),
),
],
);
}
Future<void> _onShowUserAgent() {
// Send a message with the user agent string to the Toaster JavaScript channel we registered
// with the WebView.
return webViewController.runJavaScript(
'Toaster.postMessage("User Agent: " + navigator.userAgent);',
);
}
Future<void> _onListCookies(BuildContext context) async {
final String cookies = await webViewController
.runJavaScriptReturningResult('document.cookie') as String;
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Cookies:'),
_getCookieList(cookies),
],
),
));
}
}
Future<void> _onAddToCache(BuildContext context) async {
await webViewController.runJavaScript(
'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";',
);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Added a test entry to cache.'),
));
}
}
Future<void> _onListCache() {
return webViewController.runJavaScript('caches.keys()'
// ignore: missing_whitespace_between_adjacent_strings
'.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))'
'.then((caches) => Toaster.postMessage(caches))');
}
Future<void> _onClearCache(BuildContext context) async {
await webViewController.clearCache();
await webViewController.clearLocalStorage();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Cache cleared.'),
));
}
}
Future<void> _onClearCookies(BuildContext context) async {
final bool hadCookies = await cookieManager.clearCookies();
String message = 'There were cookies. Now, they are gone!';
if (!hadCookies) {
message = 'There are no cookies.';
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
));
}
}
Future<void> _onNavigationDelegateExample() {
final String contentBase64 = base64Encode(
const Utf8Encoder().convert(kNavigationExamplePage),
);
return webViewController.loadRequest(
LoadRequestParams(
uri: Uri.parse('data:text/html;base64,$contentBase64'),
),
);
}
Future<void> _onSetCookie() async {
await cookieManager.setCookie(
const WebViewCookie(
name: 'foo',
value: 'bar',
domain: 'httpbin.org',
path: '/anything',
),
);
await webViewController.loadRequest(LoadRequestParams(
uri: Uri.parse('https://httpbin.org/anything'),
));
}
Future<void> _onVideoExample(BuildContext context) {
final AndroidWebViewController androidController =
webViewController as AndroidWebViewController;
// #docregion fullscreen_example
androidController.setCustomWidgetCallbacks(
onShowCustomWidget: (Widget widget, OnHideCustomWidgetCallback callback) {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) => widget,
fullscreenDialog: true,
));
},
onHideCustomWidget: () {
Navigator.of(context).pop();
},
);
// #enddocregion fullscreen_example
return androidController.loadRequest(
LoadRequestParams(
uri: Uri.parse('https://www.youtube.com/watch?v=4AoFA19gbLo'),
),
);
}
Future<void> _onDoPostRequest() {
return webViewController.loadRequest(LoadRequestParams(
uri: Uri.parse('https://httpbin.org/post'),
method: LoadRequestMethod.post,
headers: const <String, String>{
'foo': 'bar',
'Content-Type': 'text/plain',
},
body: Uint8List.fromList('Test Body'.codeUnits),
));
}
Future<void> _onLoadLocalFileExample() async {
final String pathToIndex = await _prepareLocalFile();
await webViewController.loadFile(pathToIndex);
}
Future<void> _onLoadFlutterAssetExample() {
return webViewController.loadFlutterAsset('assets/www/index.html');
}
Future<void> _onLoadHtmlStringExample() {
return webViewController.loadHtmlString(kLocalExamplePage);
}
Future<void> _onTransparentBackground() {
return webViewController.loadHtmlString(kTransparentBackgroundPage);
}
Future<void> _onJavaScriptAlertExample(BuildContext context) {
webViewController.setOnJavaScriptAlertDialog(
(JavaScriptAlertDialogRequest request) async {
await _showAlert(context, request.message);
});
webViewController.setOnJavaScriptConfirmDialog(
(JavaScriptConfirmDialogRequest request) async {
final bool result = await _showConfirm(context, request.message);
return result;
});
webViewController.setOnJavaScriptTextInputDialog(
(JavaScriptTextInputDialogRequest request) async {
final String result =
await _showTextInput(context, request.message, request.defaultText);
return result;
});
return webViewController.loadHtmlString(kAlertTestPage);
}
Widget _getCookieList(String cookies) {
if (cookies == '""') {
return Container();
}
final List<String> cookieList = cookies.split(';');
final Iterable<Text> cookieWidgets =
cookieList.map((String cookie) => Text(cookie));
return Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: cookieWidgets.toList(),
);
}
static Future<String> _prepareLocalFile() async {
final String tmpDir = (await getTemporaryDirectory()).path;
final File indexFile = File(
<String>{tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator));
await indexFile.create(recursive: true);
await indexFile.writeAsString(kLocalExamplePage);
return indexFile.path;
}
Future<void> _onLogExample() {
webViewController
.setOnConsoleMessage((JavaScriptConsoleMessage consoleMessage) {
debugPrint(
'== JS == ${consoleMessage.level.name}: ${consoleMessage.message}');
});
return webViewController.loadHtmlString(kLogExamplePage);
}
Future<void> _promptForUrl(BuildContext context) {
final TextEditingController urlTextController = TextEditingController();
return showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Input URL to visit'),
content: TextField(
decoration: const InputDecoration(labelText: 'URL'),
autofocus: true,
controller: urlTextController,
),
actions: <Widget>[
TextButton(
onPressed: () {
if (urlTextController.text.isNotEmpty) {
final Uri? uri = Uri.tryParse(urlTextController.text);
if (uri != null && uri.scheme.isNotEmpty) {
webViewController.loadRequest(
LoadRequestParams(uri: uri),
);
Navigator.pop(context);
}
}
},
child: const Text('Visit'),
),
],
);
},
);
}
Future<void> _showAlert(BuildContext context, String message) async {
return showDialog<void>(
context: context,
builder: (BuildContext ctx) {
return AlertDialog(
content: Text(message),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: const Text('OK'))
],
);
});
}
Future<bool> _showConfirm(BuildContext context, String message) async {
return await showDialog<bool>(
context: context,
builder: (BuildContext ctx) {
return AlertDialog(
content: Text(message),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop(false);
},
child: const Text('Cancel')),
TextButton(
onPressed: () {
Navigator.of(ctx).pop(true);
},
child: const Text('OK')),
],
);
}) ??
false;
}
Future<String> _showTextInput(
BuildContext context, String message, String? defaultText) async {
return await showDialog<String>(
context: context,
builder: (BuildContext ctx) {
return AlertDialog(
content: Text(message),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop('Text test');
},
child: const Text('Enter')),
],
);
}) ??
'';
}
}
class NavigationControls extends StatelessWidget {
const NavigationControls({super.key, required this.webViewController});
final PlatformWebViewController webViewController;
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () async {
if (await webViewController.canGoBack()) {
await webViewController.goBack();
} else {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No back history item')),
);
}
}
},
),
IconButton(
icon: const Icon(Icons.arrow_forward_ios),
onPressed: () async {
if (await webViewController.canGoForward()) {
await webViewController.goForward();
} else {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No forward history item')),
);
}
}
},
),
IconButton(
icon: const Icon(Icons.replay),
onPressed: () => webViewController.reload(),
),
],
);
}
}
| packages/packages/webview_flutter/webview_flutter_android/example/lib/main.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/example/lib/main.dart",
"repo_id": "packages",
"token_count": 10755
} | 1,123 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Helper method for creating callbacks methods with a weak reference.
///
/// Example:
/// ```
/// final JavascriptChannelRegistry javascriptChannelRegistry = ...
///
/// final WKScriptMessageHandler handler = WKScriptMessageHandler(
/// didReceiveScriptMessage: withWeakReferenceTo(
/// javascriptChannelRegistry,
/// (WeakReference<JavascriptChannelRegistry> weakReference) {
/// return (
/// WKUserContentController userContentController,
/// WKScriptMessage message,
/// ) {
/// weakReference.target?.onJavascriptChannelMessage(
/// message.name,
/// message.body!.toString(),
/// );
/// };
/// },
/// ),
/// );
/// ```
S withWeakReferenceTo<T extends Object, S extends Object>(
T reference,
S Function(WeakReference<T> weakReference) onCreate,
) {
final WeakReference<T> weakReference = WeakReference<T>(reference);
return onCreate(weakReference);
}
| packages/packages/webview_flutter/webview_flutter_android/lib/src/weak_reference_utils.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/lib/src/weak_reference_utils.dart",
"repo_id": "packages",
"token_count": 363
} | 1,124 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_android/src/android_webview.dart'
as android_webview;
import 'package:webview_flutter_android/src/legacy/webview_android_cookie_manager.dart';
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
import 'webview_android_cookie_manager_test.mocks.dart';
@GenerateMocks(<Type>[android_webview.CookieManager])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('clearCookies should call android_webview.clearCookies', () {
final MockCookieManager mockCookieManager = MockCookieManager();
when(mockCookieManager.removeAllCookies())
.thenAnswer((_) => Future<bool>.value(true));
WebViewAndroidCookieManager(
cookieManager: mockCookieManager,
).clearCookies();
verify(mockCookieManager.removeAllCookies());
});
test('setCookie should throw ArgumentError for cookie with invalid path', () {
expect(
() => WebViewAndroidCookieManager(cookieManager: MockCookieManager())
.setCookie(const WebViewCookie(
name: 'foo',
value: 'bar',
domain: 'flutter.dev',
path: 'invalid;path',
)),
throwsA(const TypeMatcher<ArgumentError>()),
);
});
test(
'setCookie should call android_webview.csetCookie with properly formatted cookie value',
() {
final MockCookieManager mockCookieManager = MockCookieManager();
WebViewAndroidCookieManager(cookieManager: mockCookieManager)
.setCookie(const WebViewCookie(
name: 'foo&',
value: 'bar@',
domain: 'flutter.dev',
));
verify(mockCookieManager.setCookie('flutter.dev', 'foo%26=bar%40; path=/'));
});
}
| packages/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart",
"repo_id": "packages",
"token_count": 722
} | 1,125 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'types.dart';
/// Configuration to use when creating a new [WebViewPlatformController].
///
/// The `autoMediaPlaybackPolicy` parameter must not be null.
class CreationParams {
/// Constructs an instance to use when creating a new
/// [WebViewPlatformController].
///
/// The `autoMediaPlaybackPolicy` parameter must not be null.
CreationParams({
this.initialUrl,
this.webSettings,
this.javascriptChannelNames = const <String>{},
this.userAgent,
this.autoMediaPlaybackPolicy =
AutoMediaPlaybackPolicy.require_user_action_for_all_media_types,
this.backgroundColor,
this.cookies = const <WebViewCookie>[],
});
/// The initialUrl to load in the webview.
///
/// When null the webview will be created without loading any page.
final String? initialUrl;
/// The initial [WebSettings] for the new webview.
///
/// This can later be updated with [WebViewPlatformController.updateSettings].
final WebSettings? webSettings;
/// The initial set of JavaScript channels that are configured for this webview.
///
/// For each value in this set the platform's webview should make sure that a corresponding
/// property with a postMessage method is set on `window`. For example for a JavaScript channel
/// named `Foo` it should be possible for JavaScript code executing in the webview to do
///
/// ```javascript
/// Foo.postMessage('hello');
/// ```
// TODO(amirh): describe what should happen when postMessage is called once that code is migrated
// to PlatformWebView.
final Set<String> javascriptChannelNames;
/// The value used for the HTTP User-Agent: request header.
///
/// When null the platform's webview default is used for the User-Agent header.
final String? userAgent;
/// Which restrictions apply on automatic media playback.
final AutoMediaPlaybackPolicy autoMediaPlaybackPolicy;
/// The background color of the webview.
///
/// When null the platform's webview default background color is used.
final Color? backgroundColor;
/// The initial set of cookies to set before the webview does its first load.
final List<WebViewCookie> cookies;
@override
String toString() {
return 'CreationParams(initialUrl: $initialUrl, settings: $webSettings, javascriptChannelNames: $javascriptChannelNames, UserAgent: $userAgent, backgroundColor: $backgroundColor, cookies: $cookies)';
}
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/creation_params.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/creation_params.dart",
"repo_id": "packages",
"token_count": 712
} | 1,126 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:meta/meta.dart';
import 'javascript_log_level.dart';
/// Represents a console message written to the JavaScript console.
@immutable
class JavaScriptConsoleMessage {
/// Creates a [JavaScriptConsoleMessage].
const JavaScriptConsoleMessage({
required this.level,
required this.message,
});
/// The severity of a JavaScript log message.
final JavaScriptLogLevel level;
/// The message written to the console.
final String message;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_console_message.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_console_message.dart",
"repo_id": "packages",
"token_count": 168
} | 1,127 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
/// Possible error type categorizations used by [WebResourceError].
enum WebResourceErrorType {
/// User authentication failed on server.
authentication,
/// Malformed URL.
badUrl,
/// Failed to connect to the server.
connect,
/// Failed to perform SSL handshake.
failedSslHandshake,
/// Generic file error.
file,
/// File not found.
fileNotFound,
/// Server or proxy hostname lookup failed.
hostLookup,
/// Failed to read or write to the server.
io,
/// User authentication failed on proxy.
proxyAuthentication,
/// Too many redirects.
redirectLoop,
/// Connection timed out.
timeout,
/// Too many requests during this load.
tooManyRequests,
/// Generic error.
unknown,
/// Resource load was canceled by Safe Browsing.
unsafeResource,
/// Unsupported authentication scheme (not basic or digest).
unsupportedAuthScheme,
/// Unsupported URI scheme.
unsupportedScheme,
/// The web content process was terminated.
webContentProcessTerminated,
/// The web view was invalidated.
webViewInvalidated,
/// A JavaScript exception occurred.
javaScriptExceptionOccurred,
/// The result of JavaScript execution could not be returned.
javaScriptResultTypeIsUnsupported,
}
/// Error returned in `WebView.onWebResourceError` when a web resource loading error has occurred.
///
/// Platform specific implementations can add additional fields by extending
/// this class.
///
/// {@tool sample}
/// This example demonstrates how to extend the [WebResourceError] to
/// provide additional platform specific parameters.
///
/// When extending [WebResourceError] additional parameters should always
/// accept `null` or have a default value to prevent breaking changes.
///
/// ```dart
/// class IOSWebResourceError extends WebResourceError {
/// IOSWebResourceError._(WebResourceError error, {required this.domain})
/// : super(
/// errorCode: error.errorCode,
/// description: error.description,
/// errorType: error.errorType,
/// );
///
/// factory IOSWebResourceError.fromWebResourceError(
/// WebResourceError error, {
/// required String? domain,
/// }) {
/// return IOSWebResourceError._(error, domain: domain);
/// }
///
/// final String? domain;
/// }
/// ```
/// {@end-tool}
@immutable
class WebResourceError {
/// Used by the platform implementation to create a new [WebResourceError].
const WebResourceError({
required this.errorCode,
required this.description,
this.errorType,
this.isForMainFrame,
this.url,
});
/// Raw code of the error from the respective platform.
final int errorCode;
/// Description of the error that can be used to communicate the problem to the user.
final String description;
/// The type this error can be categorized as.
final WebResourceErrorType? errorType;
/// Whether the error originated from the main frame.
final bool? isForMainFrame;
/// The URL for which the failing resource request was made.
final String? url;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/web_resource_error.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/web_resource_error.dart",
"repo_id": "packages",
"token_count": 907
} | 1,128 |
name: webview_flutter_web_example
description: Demonstrates how to use the webview_flutter_web plugin.
publish_to: none
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
webview_flutter_platform_interface: ^2.0.0
webview_flutter_web:
# When depending on this package from a real application you should use:
# webview_flutter_web: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/webview_flutter/webview_flutter_web/example/pubspec.yaml/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_web/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 292
} | 1,129 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:webview_flutter_web/src/content_type.dart';
void main() {
group('ContentType.parse', () {
test('basic content-type (lowers case)', () {
final ContentType contentType = ContentType.parse('text/pLaIn');
expect(contentType.mimeType, 'text/plain');
expect(contentType.boundary, isNull);
expect(contentType.charset, isNull);
});
test('with charset', () {
final ContentType contentType =
ContentType.parse('text/pLaIn; charset=utf-8');
expect(contentType.mimeType, 'text/plain');
expect(contentType.boundary, isNull);
expect(contentType.charset, 'utf-8');
});
test('with boundary', () {
final ContentType contentType =
ContentType.parse('text/pLaIn; boundary=---xyz');
expect(contentType.mimeType, 'text/plain');
expect(contentType.boundary, '---xyz');
expect(contentType.charset, isNull);
});
test('with charset and boundary', () {
final ContentType contentType =
ContentType.parse('text/pLaIn; charset=utf-8; boundary=---xyz');
expect(contentType.mimeType, 'text/plain');
expect(contentType.boundary, '---xyz');
expect(contentType.charset, 'utf-8');
});
test('with boundary and charset', () {
final ContentType contentType =
ContentType.parse('text/pLaIn; boundary=---xyz; charset=utf-8');
expect(contentType.mimeType, 'text/plain');
expect(contentType.boundary, '---xyz');
expect(contentType.charset, 'utf-8');
});
test('with a bunch of whitespace, boundary and charset', () {
final ContentType contentType = ContentType.parse(
' text/pLaIn ; boundary=---xyz; charset=utf-8 ');
expect(contentType.mimeType, 'text/plain');
expect(contentType.boundary, '---xyz');
expect(contentType.charset, 'utf-8');
});
test('empty string', () {
final ContentType contentType = ContentType.parse('');
expect(contentType.mimeType, '');
expect(contentType.boundary, isNull);
expect(contentType.charset, isNull);
});
test('unknown parameter (throws)', () {
expect(() {
ContentType.parse('text/pLaIn; wrong=utf-8');
}, throwsStateError);
});
});
}
| packages/packages/webview_flutter/webview_flutter_web/test/content_type_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_web/test/content_type_test.dart",
"repo_id": "packages",
"token_count": 976
} | 1,130 |
h1 {
color: blue;
} | packages/packages/webview_flutter/webview_flutter_wkwebview/example/assets/www/styles/style.css/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/assets/www/styles/style.css",
"repo_id": "packages",
"token_count": 13
} | 1,131 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFInstanceManager.h"
NS_ASSUME_NONNULL_BEGIN
@interface FWFInstanceManager ()
/// The next identifier that will be used for a host-created instance.
@property long nextIdentifier;
/// The number of instances stored as a strong reference.
///
/// Added for debugging purposes.
- (NSUInteger)strongInstanceCount;
/// The number of instances stored as a weak reference.
///
/// Added for debugging purposes. NSMapTables that store keys or objects as weak reference will be
/// reclaimed nondeterministically.
- (NSUInteger)weakInstanceCount;
@end
NS_ASSUME_NONNULL_END
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFInstanceManager_Test.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFInstanceManager_Test.h",
"repo_id": "packages",
"token_count": 202
} | 1,132 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFUIViewHostApi.h"
@interface FWFUIViewHostApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFUIViewHostApiImpl
- (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (UIView *)viewForIdentifier:(NSInteger)identifier {
return (UIView *)[self.instanceManager instanceForIdentifier:identifier];
}
- (void)setBackgroundColorForViewWithIdentifier:(NSInteger)identifier
toValue:(nullable NSNumber *)color
error:(FlutterError *_Nullable *_Nonnull)error {
if (color == nil) {
[[self viewForIdentifier:identifier] setBackgroundColor:nil];
}
int colorInt = color.intValue;
UIColor *colorObject = [UIColor colorWithRed:(colorInt >> 16 & 0xff) / 255.0
green:(colorInt >> 8 & 0xff) / 255.0
blue:(colorInt & 0xff) / 255.0
alpha:(colorInt >> 24 & 0xff) / 255.0];
[[self viewForIdentifier:identifier] setBackgroundColor:colorObject];
}
- (void)setOpaqueForViewWithIdentifier:(NSInteger)identifier
isOpaque:(BOOL)opaque
error:(FlutterError *_Nullable *_Nonnull)error {
[[self viewForIdentifier:identifier] setOpaque:opaque];
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIViewHostApi.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUIViewHostApi.m",
"repo_id": "packages",
"token_count": 740
} | 1,133 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFWebViewHostApi.h"
#import "FWFDataConverters.h"
@implementation FWFAssetManager
- (NSString *)lookupKeyForAsset:(NSString *)asset {
return [FlutterDartProject lookupKeyForAsset:asset];
}
@end
@implementation FWFWebView
- (instancetype)initWithFrame:(CGRect)frame
configuration:(nonnull WKWebViewConfiguration *)configuration
binaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self initWithFrame:frame configuration:configuration];
if (self) {
_objectApi = [[FWFObjectFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager];
self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
if (@available(iOS 13.0, *)) {
self.scrollView.automaticallyAdjustsScrollIndicatorInsets = NO;
}
}
return self;
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
// Prevents the contentInsets from being adjusted by iOS and gives control to Flutter.
self.scrollView.contentInset = UIEdgeInsetsZero;
// Adjust contentInset to compensate the adjustedContentInset so the sum will
// always be 0.
if (UIEdgeInsetsEqualToEdgeInsets(self.scrollView.adjustedContentInset, UIEdgeInsetsZero)) {
return;
}
UIEdgeInsets insetToAdjust = self.scrollView.adjustedContentInset;
self.scrollView.contentInset = UIEdgeInsetsMake(-insetToAdjust.top, -insetToAdjust.left,
-insetToAdjust.bottom, -insetToAdjust.right);
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey, id> *)change
context:(void *)context {
[self.objectApi observeValueForObject:self
keyPath:keyPath
object:object
change:change
completion:^(FlutterError *error) {
NSAssert(!error, @"%@", error);
}];
}
- (nonnull UIView *)view {
return self;
}
@end
@interface FWFWebViewHostApiImpl ()
// BinaryMessenger must be weak to prevent a circular reference with the host API it
// references.
@property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger;
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@property NSBundle *bundle;
@property FWFAssetManager *assetManager;
@end
@implementation FWFWebViewHostApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
return [self initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager
bundle:[NSBundle mainBundle]
assetManager:[[FWFAssetManager alloc] init]];
}
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager
bundle:(NSBundle *)bundle
assetManager:(FWFAssetManager *)assetManager {
self = [self init];
if (self) {
_binaryMessenger = binaryMessenger;
_instanceManager = instanceManager;
_bundle = bundle;
_assetManager = assetManager;
}
return self;
}
- (FWFWebView *)webViewForIdentifier:(NSInteger)identifier {
return (FWFWebView *)[self.instanceManager instanceForIdentifier:identifier];
}
+ (nonnull FlutterError *)errorForURLString:(nonnull NSString *)string {
NSString *errorDetails = [NSString stringWithFormat:@"Initializing NSURL with the supplied "
@"'%@' path resulted in a nil value.",
string];
return [FlutterError errorWithCode:@"FWFURLParsingError"
message:@"Failed parsing file path."
details:errorDetails];
}
- (void)createWithIdentifier:(NSInteger)identifier
configurationIdentifier:(NSInteger)configurationIdentifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager
instanceForIdentifier:configurationIdentifier];
FWFWebView *webView = [[FWFWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)
configuration:configuration
binaryMessenger:self.binaryMessenger
instanceManager:self.instanceManager];
[self.instanceManager addDartCreatedInstance:webView withIdentifier:identifier];
}
- (void)loadRequestForWebViewWithIdentifier:(NSInteger)identifier
request:(nonnull FWFNSUrlRequestData *)request
error:
(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
NSURLRequest *urlRequest = FWFNativeNSURLRequestFromRequestData(request);
if (!urlRequest) {
*error = [FlutterError errorWithCode:@"FWFURLRequestParsingError"
message:@"Failed instantiating an NSURLRequest."
details:[NSString stringWithFormat:@"URL was: '%@'", request.url]];
return;
}
[[self webViewForIdentifier:identifier] loadRequest:urlRequest];
}
- (void)setCustomUserAgentForWebViewWithIdentifier:(NSInteger)identifier
userAgent:(nullable NSString *)userAgent
error:
(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
[[self webViewForIdentifier:identifier] setCustomUserAgent:userAgent];
}
- (nullable NSNumber *)
canGoBackForWebViewWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return @([self webViewForIdentifier:identifier].canGoBack);
}
- (nullable NSString *)
URLForWebViewWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return [self webViewForIdentifier:identifier].URL.absoluteString;
}
- (nullable NSNumber *)
canGoForwardForWebViewWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return @([[self webViewForIdentifier:identifier] canGoForward]);
}
- (nullable NSNumber *)
estimatedProgressForWebViewWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
return @([[self webViewForIdentifier:identifier] estimatedProgress]);
}
- (void)evaluateJavaScriptForWebViewWithIdentifier:(NSInteger)identifier
javaScriptString:(nonnull NSString *)javaScriptString
completion:
(nonnull void (^)(id _Nullable,
FlutterError *_Nullable))completion {
[[self webViewForIdentifier:identifier]
evaluateJavaScript:javaScriptString
completionHandler:^(id _Nullable result, NSError *_Nullable error) {
id returnValue = nil;
FlutterError *flutterError = nil;
if (!error) {
if (!result || [result isKindOfClass:[NSString class]] ||
[result isKindOfClass:[NSNumber class]]) {
returnValue = result;
} else if (![result isKindOfClass:[NSNull class]]) {
NSString *className = NSStringFromClass([result class]);
NSLog(@"Return type of evaluateJavaScript is not directly supported: %@. Returned "
@"description of value.",
className);
returnValue = [result description];
}
} else {
flutterError = [FlutterError errorWithCode:@"FWFEvaluateJavaScriptError"
message:@"Failed evaluating JavaScript."
details:FWFNSErrorDataFromNativeNSError(error)];
}
completion(returnValue, flutterError);
}];
}
- (void)setInspectableForWebViewWithIdentifier:(NSInteger)identifier
inspectable:(BOOL)inspectable
error:(FlutterError *_Nullable *_Nonnull)error {
if (@available(macOS 13.3, iOS 16.4, tvOS 16.4, *)) {
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130300 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 160400
[[self webViewForIdentifier:identifier] setInspectable:inspectable];
#endif
} else {
*error = [FlutterError errorWithCode:@"FWFUnsupportedVersionError"
message:@"setInspectable is only supported on versions 16.4+."
details:nil];
}
}
- (void)goBackForWebViewWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[[self webViewForIdentifier:identifier] goBack];
}
- (void)goForwardForWebViewWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[[self webViewForIdentifier:identifier] goForward];
}
- (void)loadAssetForWebViewWithIdentifier:(NSInteger)identifier
assetKey:(nonnull NSString *)key
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
NSString *assetFilePath = [self.assetManager lookupKeyForAsset:key];
NSURL *url = [self.bundle URLForResource:[assetFilePath stringByDeletingPathExtension]
withExtension:assetFilePath.pathExtension];
if (!url) {
*error = [FWFWebViewHostApiImpl errorForURLString:assetFilePath];
} else {
[[self webViewForIdentifier:identifier] loadFileURL:url
allowingReadAccessToURL:[url URLByDeletingLastPathComponent]];
}
}
- (void)loadFileForWebViewWithIdentifier:(NSInteger)identifier
fileURL:(nonnull NSString *)url
readAccessURL:(nonnull NSString *)readAccessUrl
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
NSURL *fileURL = [NSURL fileURLWithPath:url isDirectory:NO];
NSURL *readAccessNSURL = [NSURL fileURLWithPath:readAccessUrl isDirectory:YES];
if (!fileURL) {
*error = [FWFWebViewHostApiImpl errorForURLString:url];
} else if (!readAccessNSURL) {
*error = [FWFWebViewHostApiImpl errorForURLString:readAccessUrl];
} else {
[[self webViewForIdentifier:identifier] loadFileURL:fileURL
allowingReadAccessToURL:readAccessNSURL];
}
}
- (void)loadHTMLForWebViewWithIdentifier:(NSInteger)identifier
HTMLString:(nonnull NSString *)string
baseURL:(nullable NSString *)baseUrl
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[[self webViewForIdentifier:identifier] loadHTMLString:string
baseURL:[NSURL URLWithString:baseUrl]];
}
- (void)reloadWebViewWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[[self webViewForIdentifier:identifier] reload];
}
- (void)
setAllowsBackForwardForWebViewWithIdentifier:(NSInteger)identifier
isAllowed:(BOOL)allow
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
[[self webViewForIdentifier:identifier] setAllowsBackForwardNavigationGestures:allow];
}
- (void)
setNavigationDelegateForWebViewWithIdentifier:(NSInteger)identifier
delegateIdentifier:(nullable NSNumber *)navigationDelegateIdentifier
error:
(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
id<WKNavigationDelegate> navigationDelegate = (id<WKNavigationDelegate>)[self.instanceManager
instanceForIdentifier:navigationDelegateIdentifier.longValue];
[[self webViewForIdentifier:identifier] setNavigationDelegate:navigationDelegate];
}
- (void)setUIDelegateForWebViewWithIdentifier:(NSInteger)identifier
delegateIdentifier:(nullable NSNumber *)uiDelegateIdentifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)
error {
id<WKUIDelegate> navigationDelegate =
(id<WKUIDelegate>)[self.instanceManager instanceForIdentifier:uiDelegateIdentifier.longValue];
[[self webViewForIdentifier:identifier] setUIDelegate:navigationDelegate];
}
- (nullable NSString *)
titleForWebViewWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return [[self webViewForIdentifier:identifier] title];
}
- (nullable NSString *)
customUserAgentForWebViewWithIdentifier:(NSInteger)identifier
error:
(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
return [[self webViewForIdentifier:identifier] customUserAgent];
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewHostApi.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewHostApi.m",
"repo_id": "packages",
"token_count": 6624
} | 1,134 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:flutter/services.dart';
import '../common/instance_manager.dart';
import '../common/web_kit.g.dart';
import '../foundation/foundation.dart';
import '../web_kit/web_kit.dart';
import 'ui_kit.dart';
/// Host api implementation for [UIScrollView].
class UIScrollViewHostApiImpl extends UIScrollViewHostApi {
/// Constructs a [UIScrollViewHostApiImpl].
UIScrollViewHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Sends binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with Objective-C objects.
final InstanceManager instanceManager;
/// Calls [createFromWebView] with the ids of the provided object instances.
Future<void> createFromWebViewForInstances(
UIScrollView instance,
WKWebView webView,
) {
return createFromWebView(
instanceManager.addDartCreatedInstance(instance),
instanceManager.getIdentifier(webView)!,
);
}
/// Calls [getContentOffset] with the ids of the provided object instances.
Future<Point<double>> getContentOffsetForInstances(
UIScrollView instance,
) async {
final List<double?> point = await getContentOffset(
instanceManager.getIdentifier(instance)!,
);
return Point<double>(point[0]!, point[1]!);
}
/// Calls [scrollBy] with the ids of the provided object instances.
Future<void> scrollByForInstances(
UIScrollView instance,
Point<double> offset,
) {
return scrollBy(
instanceManager.getIdentifier(instance)!,
offset.x,
offset.y,
);
}
/// Calls [setContentOffset] with the ids of the provided object instances.
Future<void> setContentOffsetForInstances(
UIScrollView instance,
Point<double> offset,
) async {
return setContentOffset(
instanceManager.getIdentifier(instance)!,
offset.x,
offset.y,
);
}
/// Calls [setDelegate] with the ids of the provided object instances.
Future<void> setDelegateForInstances(
UIScrollView instance,
UIScrollViewDelegate? delegate,
) async {
return setDelegate(
instanceManager.getIdentifier(instance)!,
delegate != null ? instanceManager.getIdentifier(delegate) : null,
);
}
}
/// Host api implementation for [UIView].
class UIViewHostApiImpl extends UIViewHostApi {
/// Constructs a [UIViewHostApiImpl].
UIViewHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Sends binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with Objective-C objects.
final InstanceManager instanceManager;
/// Calls [setBackgroundColor] with the ids of the provided object instances.
Future<void> setBackgroundColorForInstances(
UIView instance,
Color? color,
) async {
return setBackgroundColor(
instanceManager.getIdentifier(instance)!,
color?.value,
);
}
/// Calls [setOpaque] with the ids of the provided object instances.
Future<void> setOpaqueForInstances(
UIView instance,
bool opaque,
) async {
return setOpaque(instanceManager.getIdentifier(instance)!, opaque);
}
}
/// Flutter api implementation for [UIScrollViewDelegate].
class UIScrollViewDelegateFlutterApiImpl
extends UIScrollViewDelegateFlutterApi {
/// Constructs a [UIScrollViewDelegateFlutterApiImpl].
UIScrollViewDelegateFlutterApiImpl({InstanceManager? instanceManager})
: instanceManager = instanceManager ?? NSObject.globalInstanceManager;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
UIScrollViewDelegate _getDelegate(int identifier) {
return instanceManager.getInstanceWithWeakReference(identifier)!;
}
@override
void scrollViewDidScroll(
int identifier,
int uiScrollViewIdentifier,
double x,
double y,
) {
final void Function(UIScrollView, double, double)? callback =
_getDelegate(identifier).scrollViewDidScroll;
final UIScrollView? uiScrollView = instanceManager
.getInstanceWithWeakReference(uiScrollViewIdentifier) as UIScrollView?;
assert(uiScrollView != null);
callback?.call(uiScrollView!, x, y);
}
}
/// Host api implementation for [UIScrollViewDelegate].
class UIScrollViewDelegateHostApiImpl extends UIScrollViewDelegateHostApi {
/// Constructs a [UIScrollViewDelegateHostApiImpl].
UIScrollViewDelegateHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Sends binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with Objective-C objects.
final InstanceManager instanceManager;
/// Calls [create] with the ids of the provided object instances.
Future<void> createForInstance(UIScrollViewDelegate instance) async {
return create(instanceManager.addDartCreatedInstance(instance));
}
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/ui_kit/ui_kit_api_impls.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/ui_kit/ui_kit_api_impls.dart",
"repo_id": "packages",
"token_count": 1884
} | 1,135 |
# Can't use Flutter integration tests due to native modal UI.
- file_selector_ios
- file_selector
| packages/script/configs/exclude_integration_ios.yaml/0 | {
"file_path": "packages/script/configs/exclude_integration_ios.yaml",
"repo_id": "packages",
"token_count": 30
} | 1,136 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:pub_semver/pub_semver.dart';
/// The signature for a print handler for commands that allow overriding the
/// print destination.
typedef Print = void Function(Object? object);
/// Key for APK (Android) platform.
const String platformAndroid = 'android';
/// Alias for APK (Android) platform.
const String platformAndroidAlias = 'apk';
/// Key for IPA (iOS) platform.
const String platformIOS = 'ios';
/// Key for linux platform.
const String platformLinux = 'linux';
/// Key for macos platform.
const String platformMacOS = 'macos';
/// Key for Web platform.
const String platformWeb = 'web';
/// Key for windows platform.
const String platformWindows = 'windows';
/// Key for enable experiment.
const String kEnableExperiment = 'enable-experiment';
/// Target platforms supported by Flutter.
// ignore: public_member_api_docs
enum FlutterPlatform { android, ios, linux, macos, web, windows }
const Map<String, FlutterPlatform> _platformByName = <String, FlutterPlatform>{
platformAndroid: FlutterPlatform.android,
platformIOS: FlutterPlatform.ios,
platformLinux: FlutterPlatform.linux,
platformMacOS: FlutterPlatform.macos,
platformWeb: FlutterPlatform.web,
platformWindows: FlutterPlatform.windows,
};
/// Maps from a platform name (e.g., flag or platform directory) to the
/// corresponding platform enum.
FlutterPlatform getPlatformByName(String name) {
final FlutterPlatform? platform = _platformByName[name];
if (platform == null) {
throw ArgumentError('Invalid platform: $name');
}
return platform;
}
// Flutter->Dart SDK version mapping. Any time a command fails to look up a
// corresponding version, this map should be updated.
final Map<Version, Version> _dartSdkForFlutterSdk = <Version, Version>{
Version(3, 0, 0): Version(2, 17, 0),
Version(3, 0, 5): Version(2, 17, 6),
Version(3, 3, 0): Version(2, 18, 0),
Version(3, 3, 10): Version(2, 18, 6),
Version(3, 7, 0): Version(2, 19, 0),
Version(3, 7, 12): Version(2, 19, 6),
Version(3, 10, 0): Version(3, 0, 0),
Version(3, 10, 6): Version(3, 0, 6),
Version(3, 13, 0): Version(3, 1, 0),
Version(3, 13, 9): Version(3, 1, 5),
Version(3, 16, 0): Version(3, 2, 0),
Version(3, 16, 6): Version(3, 2, 3),
Version(3, 16, 9): Version(3, 2, 6),
Version(3, 19, 0): Version(3, 3, 0),
};
/// Returns the version of the Dart SDK that shipped with the given Flutter
/// SDK.
Version? getDartSdkForFlutterSdk(Version flutterVersion) =>
_dartSdkForFlutterSdk[flutterVersion];
/// Returns whether the given directory is a Dart package.
bool isPackage(FileSystemEntity entity) {
if (entity is! Directory) {
return false;
}
// According to
// https://dart.dev/guides/libraries/create-library-packages#what-makes-a-library-package
// a package must also have a `lib/` directory, but in practice that's not
// always true. Some special cases (espresso, flutter_template_images, etc.)
// don't have any source, so this deliberately doesn't check that there's a
// lib directory.
return entity.childFile('pubspec.yaml').existsSync();
}
/// Error thrown when a command needs to exit with a non-zero exit code.
///
/// While there is no specific definition of the meaning of different non-zero
/// exit codes for this tool, commands should follow the general convention:
/// 1: The command ran correctly, but found errors.
/// 2: The command failed to run because the arguments were invalid.
/// >2: The command failed to run correctly for some other reason. Ideally,
/// each such failure should have a unique exit code within the context of
/// that command.
class ToolExit extends Error {
/// Creates a tool exit with the given [exitCode].
ToolExit(this.exitCode);
/// The code that the process should exit with.
final int exitCode;
}
/// A exit code for [ToolExit] for a successful run that found errors.
const int exitCommandFoundErrors = 1;
/// A exit code for [ToolExit] for a failure to run due to invalid arguments.
const int exitInvalidArguments = 2;
| packages/script/tool/lib/src/common/core.dart/0 | {
"file_path": "packages/script/tool/lib/src/common/core.dart",
"repo_id": "packages",
"token_count": 1274
} | 1,137 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'common/core.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/plugin_utils.dart';
import 'common/pub_utils.dart';
import 'common/repository_package.dart';
/// A command to run Dart unit tests for packages.
class DartTestCommand extends PackageLoopingCommand {
/// Creates an instance of the test command.
DartTestCommand(
super.packagesDir, {
super.processRunner,
super.platform,
}) {
argParser.addOption(
kEnableExperiment,
defaultsTo: '',
help:
'Runs Dart unit tests in Dart VM with the given experiments enabled. '
'See https://github.com/dart-lang/sdk/blob/main/docs/process/experimental-flags.md '
'for details.',
);
argParser.addOption(
_platformFlag,
help: 'Runs tests on the given platform instead of the default platform '
'("vm" in most cases, "chrome" for web plugin implementations).',
);
}
static const String _platformFlag = 'platform';
@override
final String name = 'dart-test';
// TODO(stuartmorgan): Eventually remove 'test', which is a legacy name from
// before there were other test commands that made it ambiguous. For now it's
// an alias to avoid breaking people's workflows.
@override
List<String> get aliases => <String>['test', 'test-dart'];
@override
final String description = 'Runs the Dart tests for all packages.\n\n'
'This command requires "flutter" to be in your path.';
@override
PackageLoopingType get packageLoopingType =>
PackageLoopingType.includeAllSubpackages;
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
if (!package.testDirectory.existsSync()) {
return PackageResult.skip('No test/ directory.');
}
String? platform = getNullableStringArg(_platformFlag);
// Skip running plugin tests for non-web-supporting plugins (or non-web
// federated plugin implementations) on web, since there's no reason to
// expect them to work.
final bool webPlatform = platform != null && platform != 'vm';
final bool explicitVMPlatform = platform == 'vm';
final bool isWebOnlyPluginImplementation = pluginSupportsPlatform(
platformWeb, package,
requiredMode: PlatformSupport.inline) &&
package.directory.basename.endsWith('_web');
if (webPlatform) {
if (isFlutterPlugin(package) &&
!pluginSupportsPlatform(platformWeb, package)) {
return PackageResult.skip(
"Non-web plugin tests don't need web testing.");
}
if (_requiresVM(package)) {
// This explict skip is necessary because trying to run tests in a mode
// that the package has opted out of returns a non-zero exit code.
return PackageResult.skip('Package has opted out of non-vm testing.');
}
} else if (explicitVMPlatform) {
if (isWebOnlyPluginImplementation) {
return PackageResult.skip("Web plugin tests don't need vm testing.");
}
if (_requiresNonVM(package)) {
// This explict skip is necessary because trying to run tests in a mode
// that the package has opted out of returns a non-zero exit code.
return PackageResult.skip('Package has opted out of vm testing.');
}
} else if (platform == null && isWebOnlyPluginImplementation) {
// If no explicit mode is requested, run web plugin implementations in
// Chrome since their tests are not expected to work in vm mode. This
// allows easily running all unit tests locally, without having to run
// both modes.
platform = 'chrome';
}
// All the web tests assume the html renderer currently.
final String? webRenderer = (platform == 'chrome') ? 'html' : null;
bool passed;
if (package.requiresFlutter()) {
passed = await _runFlutterTests(package, platform: platform, webRenderer: webRenderer);
} else {
passed = await _runDartTests(package, platform: platform);
}
return passed ? PackageResult.success() : PackageResult.fail();
}
/// Runs the Dart tests for a Flutter package, returning true on success.
Future<bool> _runFlutterTests(RepositoryPackage package,
{String? platform, String? webRenderer}) async {
final String experiment = getStringArg(kEnableExperiment);
final int exitCode = await processRunner.runAndStream(
flutterCommand,
<String>[
'test',
'--color',
if (experiment.isNotEmpty) '--enable-experiment=$experiment',
// Flutter defaults to VM mode (under a different name) and explicitly
// setting it is deprecated, so pass nothing in that case.
if (platform != null && platform != 'vm') '--platform=$platform',
if (webRenderer != null) '--web-renderer=$webRenderer',
],
workingDir: package.directory,
);
return exitCode == 0;
}
/// Runs the Dart tests for a non-Flutter package, returning true on success.
Future<bool> _runDartTests(RepositoryPackage package,
{String? platform}) async {
// Unlike `flutter test`, `dart run test` does not automatically get
// packages
if (!await runPubGet(package, processRunner, super.platform)) {
printError('Unable to fetch dependencies.');
return false;
}
final String experiment = getStringArg(kEnableExperiment);
final int exitCode = await processRunner.runAndStream(
'dart',
<String>[
'run',
if (experiment.isNotEmpty) '--enable-experiment=$experiment',
'test',
if (platform != null) '--platform=$platform',
],
workingDir: package.directory,
);
return exitCode == 0;
}
bool _requiresVM(RepositoryPackage package) {
final File testConfig = package.directory.childFile('dart_test.yaml');
if (!testConfig.existsSync()) {
return false;
}
// test_on lines can be very complex, but in pratice the packages in this
// repo currently only need the ability to require vm or not, so that
// simple directive is all that is currently supported.
final RegExp vmRequrimentRegex = RegExp(r'^test_on:\s*vm$');
return testConfig
.readAsLinesSync()
.any((String line) => vmRequrimentRegex.hasMatch(line));
}
bool _requiresNonVM(RepositoryPackage package) {
final File testConfig = package.directory.childFile('dart_test.yaml');
if (!testConfig.existsSync()) {
return false;
}
// test_on lines can be very complex, but in pratice the packages in this
// repo currently only need the ability to require vm or not, so a simple
// one-target directive is all that's supported currently. Making it
// deliberately strict avoids the possibility of accidentally skipping vm
// coverage due to a complex expression that's not handled correctly.
final RegExp testOnRegex = RegExp(r'^test_on:\s*([a-z])*\s*$');
return testConfig.readAsLinesSync().any((String line) {
final RegExpMatch? match = testOnRegex.firstMatch(line);
return match != null && match.group(1) != 'vm';
});
}
}
| packages/script/tool/lib/src/dart_test_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/dart_test_command.dart",
"repo_id": "packages",
"token_count": 2486
} | 1,138 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io' as io;
import 'package:http/http.dart' as http;
import 'package:pub_semver/pub_semver.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/pub_utils.dart';
import 'common/pub_version_finder.dart';
import 'common/repository_package.dart';
/// A command to check that packages are publishable via 'dart publish'.
class PublishCheckCommand extends PackageLoopingCommand {
/// Creates an instance of the publish command.
PublishCheckCommand(
super.packagesDir, {
super.processRunner,
super.platform,
http.Client? httpClient,
}) : _pubVersionFinder =
PubVersionFinder(httpClient: httpClient ?? http.Client()) {
argParser.addFlag(
_allowPrereleaseFlag,
help: 'Allows the pre-release SDK warning to pass.\n'
'When enabled, a pub warning, which asks to publish the package as a pre-release version when '
'the SDK constraint is a pre-release version, is ignored.',
);
argParser.addFlag(_machineFlag,
help: 'Switch outputs to a machine readable JSON. \n'
'The JSON contains a "status" field indicating the final status of the command, the possible values are:\n'
' $_statusNeedsPublish: There is at least one package need to be published. They also passed all publish checks.\n'
' $_statusMessageNoPublish: There are no packages needs to be published. Either no pubspec change detected or all versions have already been published.\n'
' $_statusMessageError: Some error has occurred.');
}
static const String _allowPrereleaseFlag = 'allow-pre-release';
static const String _machineFlag = 'machine';
static const String _statusNeedsPublish = 'needs-publish';
static const String _statusMessageNoPublish = 'no-publish';
static const String _statusMessageError = 'error';
static const String _statusKey = 'status';
static const String _humanMessageKey = 'humanMessage';
@override
final String name = 'publish-check';
@override
List<String> get aliases => <String>['check-publish'];
@override
final String description =
'Checks to make sure that a package *could* be published.';
final PubVersionFinder _pubVersionFinder;
/// The overall result of the run for machine-readable output. This is the
/// highest value that occurs during the run.
_PublishCheckResult _overallResult = _PublishCheckResult.nothingToPublish;
@override
bool get captureOutput => getBoolArg(_machineFlag);
@override
Future<void> initializeRun() async {
_overallResult = _PublishCheckResult.nothingToPublish;
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
_PublishCheckResult? result = await _passesPublishCheck(package);
if (result == null) {
return PackageResult.skip('Package is marked as unpublishable.');
}
if (!_passesAuthorsCheck(package)) {
_printImportantStatusMessage(
'No AUTHORS file found. Packages must include an AUTHORS file.',
isError: true);
result = _PublishCheckResult.error;
}
if (result.index > _overallResult.index) {
_overallResult = result;
}
return result == _PublishCheckResult.error
? PackageResult.fail()
: PackageResult.success();
}
@override
Future<void> completeRun() async {
_pubVersionFinder.httpClient.close();
}
@override
Future<void> handleCapturedOutput(List<String> output) async {
final Map<String, dynamic> machineOutput = <String, dynamic>{
_statusKey: _statusStringForResult(_overallResult),
_humanMessageKey: output,
};
print(const JsonEncoder.withIndent(' ').convert(machineOutput));
}
String _statusStringForResult(_PublishCheckResult result) {
switch (result) {
case _PublishCheckResult.nothingToPublish:
return _statusMessageNoPublish;
case _PublishCheckResult.needsPublishing:
return _statusNeedsPublish;
case _PublishCheckResult.error:
return _statusMessageError;
}
}
Pubspec? _tryParsePubspec(RepositoryPackage package) {
try {
return package.parsePubspec();
} on Exception catch (exception) {
print(
'Failed to parse `pubspec.yaml` at ${package.pubspecFile.path}: '
'$exception',
);
return null;
}
}
// Run `dart pub get` on the examples of [package].
Future<void> _fetchExampleDeps(RepositoryPackage package) async {
for (final RepositoryPackage example in package.getExamples()) {
await runPubGet(example, processRunner, platform);
}
}
Future<bool> _hasValidPublishCheckRun(RepositoryPackage package) async {
// `pub publish` does not do `dart pub get` inside `example` directories
// of a package (but they're part of the analysis output!).
// Issue: https://github.com/flutter/flutter/issues/113788
await _fetchExampleDeps(package);
print('Running pub publish --dry-run:');
final io.Process process = await processRunner.start(
flutterCommand,
<String>['pub', 'publish', '--', '--dry-run'],
workingDirectory: package.directory,
);
final StringBuffer outputBuffer = StringBuffer();
final Completer<void> stdOutCompleter = Completer<void>();
process.stdout.listen(
(List<int> event) {
final String output = String.fromCharCodes(event);
if (output.isNotEmpty) {
print(output);
outputBuffer.write(output);
}
},
onDone: () => stdOutCompleter.complete(),
);
final Completer<void> stdInCompleter = Completer<void>();
process.stderr.listen(
(List<int> event) {
final String output = String.fromCharCodes(event);
if (output.isNotEmpty) {
// The final result is always printed on stderr, whether success or
// failure.
final bool isError = !output.contains('has 0 warnings');
_printImportantStatusMessage(output, isError: isError);
outputBuffer.write(output);
}
},
onDone: () => stdInCompleter.complete(),
);
if (await process.exitCode == 0) {
return true;
}
if (!getBoolArg(_allowPrereleaseFlag)) {
return false;
}
await stdOutCompleter.future;
await stdInCompleter.future;
final String output = outputBuffer.toString();
return output.contains('Package has 1 warning') &&
output.contains(
'Packages with an SDK constraint on a pre-release of the Dart SDK should themselves be published as a pre-release version.');
}
/// Returns the result of the publish check, or null if the package is marked
/// as unpublishable.
Future<_PublishCheckResult?> _passesPublishCheck(
RepositoryPackage package) async {
final String packageName = package.directory.basename;
final Pubspec? pubspec = _tryParsePubspec(package);
if (pubspec == null) {
print('No valid pubspec found.');
return _PublishCheckResult.error;
} else if (pubspec.publishTo == 'none') {
return null;
}
final Version? version = pubspec.version;
final _PublishCheckResult alreadyPublishedResult =
await _checkPublishingStatus(
packageName: packageName, version: version);
if (alreadyPublishedResult == _PublishCheckResult.error) {
print('Check pub version failed $packageName');
return _PublishCheckResult.error;
}
// Run the dry run even if no publishing is needed, so that changes in pub
// behavior (e.g., new checks that some existing packages may fail) are
// caught by CI in the Flutter roller, rather than the next time the package
// package is actually published.
if (await _hasValidPublishCheckRun(package)) {
if (alreadyPublishedResult == _PublishCheckResult.nothingToPublish) {
print(
'Package $packageName version: $version has already been published on pub.');
} else {
print('Package $packageName is able to be published.');
}
return alreadyPublishedResult;
} else {
print('Unable to publish $packageName');
return _PublishCheckResult.error;
}
}
// Check if `packageName` already has `version` published on pub.
Future<_PublishCheckResult> _checkPublishingStatus(
{required String packageName, required Version? version}) async {
final PubVersionFinderResponse pubVersionFinderResponse =
await _pubVersionFinder.getPackageVersion(packageName: packageName);
switch (pubVersionFinderResponse.result) {
case PubVersionFinderResult.success:
return pubVersionFinderResponse.versions.contains(version)
? _PublishCheckResult.nothingToPublish
: _PublishCheckResult.needsPublishing;
case PubVersionFinderResult.fail:
print('''
Error fetching version on pub for $packageName.
HTTP Status ${pubVersionFinderResponse.httpResponse.statusCode}
HTTP response: ${pubVersionFinderResponse.httpResponse.body}
''');
return _PublishCheckResult.error;
case PubVersionFinderResult.noPackageFound:
return _PublishCheckResult.needsPublishing;
}
}
bool _passesAuthorsCheck(RepositoryPackage package) {
final List<String> pathComponents =
package.directory.fileSystem.path.split(package.path);
if (pathComponents.contains('third_party')) {
// Third-party packages aren't required to have an AUTHORS file.
return true;
}
return package.authorsFile.existsSync();
}
void _printImportantStatusMessage(String message, {required bool isError}) {
final String statusMessage = '${isError ? 'ERROR' : 'SUCCESS'}: $message';
if (getBoolArg(_machineFlag)) {
print(statusMessage);
} else {
if (isError) {
printError(statusMessage);
} else {
printSuccess(statusMessage);
}
}
}
}
/// Possible outcomes of of a publishing check.
enum _PublishCheckResult {
nothingToPublish,
needsPublishing,
error,
}
| packages/script/tool/lib/src/publish_check_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/publish_check_command.dart",
"repo_id": "packages",
"token_count": 3572
} | 1,139 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:flutter_plugin_tools/src/common/git_version_finder.dart';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import 'package_command_test.mocks.dart';
void main() {
late List<List<String>?> gitDirCommands;
late String gitDiffResponse;
late MockGitDir gitDir;
String mergeBaseResponse = '';
setUp(() {
gitDirCommands = <List<String>?>[];
gitDiffResponse = '';
gitDir = MockGitDir();
when(gitDir.runCommand(any, throwOnError: anyNamed('throwOnError')))
.thenAnswer((Invocation invocation) {
final List<String> arguments =
invocation.positionalArguments[0]! as List<String>;
gitDirCommands.add(arguments);
String? gitStdOut;
if (arguments[0] == 'diff') {
gitStdOut = gitDiffResponse;
} else if (arguments[0] == 'merge-base') {
gitStdOut = mergeBaseResponse;
}
return Future<ProcessResult>.value(
ProcessResult(0, 0, gitStdOut ?? '', ''));
});
});
test('No git diff should result no files changed', () async {
final GitVersionFinder finder =
GitVersionFinder(gitDir, baseSha: 'some base sha');
final List<String> changedFiles = await finder.getChangedFiles();
expect(changedFiles, isEmpty);
});
test('get correct files changed based on git diff', () async {
gitDiffResponse = '''
file1/file1.cc
file2/file2.cc
''';
final GitVersionFinder finder =
GitVersionFinder(gitDir, baseSha: 'some base sha');
final List<String> changedFiles = await finder.getChangedFiles();
expect(changedFiles, equals(<String>['file1/file1.cc', 'file2/file2.cc']));
});
test('get correct pubspec change based on git diff', () async {
gitDiffResponse = '''
file1/pubspec.yaml
file2/file2.cc
''';
final GitVersionFinder finder =
GitVersionFinder(gitDir, baseSha: 'some base sha');
final List<String> changedFiles = await finder.getChangedPubSpecs();
expect(changedFiles, equals(<String>['file1/pubspec.yaml']));
});
test('use correct base sha if not specified', () async {
mergeBaseResponse = 'shaqwiueroaaidf12312jnadf123nd';
gitDiffResponse = '''
file1/pubspec.yaml
file2/file2.cc
''';
final GitVersionFinder finder = GitVersionFinder(gitDir);
await finder.getChangedFiles();
verify(gitDir.runCommand(
<String>['merge-base', '--fork-point', 'FETCH_HEAD', 'HEAD'],
throwOnError: false));
verify(gitDir.runCommand(
<String>['diff', '--name-only', mergeBaseResponse, 'HEAD']));
});
test('uses correct base branch to find base sha if specified', () async {
mergeBaseResponse = 'shaqwiueroaaidf12312jnadf123nd';
gitDiffResponse = '''
file1/pubspec.yaml
file2/file2.cc
''';
final GitVersionFinder finder =
GitVersionFinder(gitDir, baseBranch: 'upstream/main');
await finder.getChangedFiles();
verify(gitDir.runCommand(
<String>['merge-base', '--fork-point', 'upstream/main', 'HEAD'],
throwOnError: false));
verify(gitDir.runCommand(
<String>['diff', '--name-only', mergeBaseResponse, 'HEAD']));
});
test('use correct base sha if specified', () async {
const String customBaseSha = 'aklsjdcaskf12312';
gitDiffResponse = '''
file1/pubspec.yaml
file2/file2.cc
''';
final GitVersionFinder finder =
GitVersionFinder(gitDir, baseSha: customBaseSha);
await finder.getChangedFiles();
verify(gitDir
.runCommand(<String>['diff', '--name-only', customBaseSha, 'HEAD']));
});
test('include uncommitted files if requested', () async {
const String customBaseSha = 'aklsjdcaskf12312';
gitDiffResponse = '''
file1/pubspec.yaml
file2/file2.cc
''';
final GitVersionFinder finder =
GitVersionFinder(gitDir, baseSha: customBaseSha);
await finder.getChangedFiles(includeUncommitted: true);
// The call should not have HEAD as a final argument like the default diff.
verify(gitDir.runCommand(<String>['diff', '--name-only', customBaseSha]));
});
}
| packages/script/tool/test/common/git_version_finder_test.dart/0 | {
"file_path": "packages/script/tool/test/common/git_version_finder_test.dart",
"repo_id": "packages",
"token_count": 1594
} | 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.
import 'dart:convert';
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/common/core.dart';
import 'package:flutter_plugin_tools/src/common/plugin_utils.dart';
import 'package:flutter_plugin_tools/src/drive_examples_command.dart';
import 'package:platform/platform.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
const String _fakeIOSDevice = '67d5c3d1-8bdf-46ad-8f6b-b00e2a972dda';
const String _fakeAndroidDevice = 'emulator-1234';
void main() {
group('test drive_example_command', () {
late FileSystem fileSystem;
late Platform mockPlatform;
late Directory packagesDir;
late CommandRunner<void> runner;
late RecordingProcessRunner processRunner;
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
processRunner = RecordingProcessRunner();
final DriveExamplesCommand command = DriveExamplesCommand(packagesDir,
processRunner: processRunner, platform: mockPlatform);
runner = CommandRunner<void>(
'drive_examples_command', 'Test for drive_example_command');
runner.addCommand(command);
});
void setMockFlutterDevicesOutput({
bool hasIOSDevice = true,
bool hasAndroidDevice = true,
bool includeBanner = false,
}) {
const String updateBanner = '''
╔════════════════════════════════════════════════════════════════════════════╗
║ A new version of Flutter is available! ║
║ ║
║ To update to the latest version, run "flutter upgrade". ║
╚════════════════════════════════════════════════════════════════════════════╝
''';
final List<String> devices = <String>[
if (hasIOSDevice) '{"id": "$_fakeIOSDevice", "targetPlatform": "ios"}',
if (hasAndroidDevice)
'{"id": "$_fakeAndroidDevice", "targetPlatform": "android-x86"}',
];
final String output =
'''${includeBanner ? updateBanner : ''}[${devices.join(',')}]''';
final MockProcess mockDevicesProcess =
MockProcess(stdout: output, stdoutEncoding: utf8);
processRunner
.mockProcessesForExecutable[getFlutterCommand(mockPlatform)] =
<FakeProcessInfo>[
FakeProcessInfo(mockDevicesProcess, <String>['devices'])
];
}
test('fails if no platforms are provided', () async {
setMockFlutterDevicesOutput();
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Exactly one of'),
]),
);
});
test('fails if multiple platforms are provided', () async {
setMockFlutterDevicesOutput();
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--ios', '--macos'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Exactly one of'),
]),
);
});
test('fails for iOS if no iOS devices are present', () async {
setMockFlutterDevicesOutput(hasIOSDevice: false);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--ios'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('No iOS devices'),
]),
);
});
test('handles flutter tool banners when checking devices', () async {
createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/test_driver/integration_test.dart',
'example/integration_test/foo_test.dart',
'example/ios/ios.m',
],
platformSupport: <String, PlatformDetails>{
platformIOS: const PlatformDetails(PlatformSupport.inline),
},
);
setMockFlutterDevicesOutput(includeBanner: true);
final List<String> output =
await runCapturingPrint(runner, <String>['drive-examples', '--ios']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
});
test('fails for iOS if getting devices fails', () async {
// Simulate failure from `flutter devices`.
processRunner
.mockProcessesForExecutable[getFlutterCommand(mockPlatform)] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['devices'])
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--ios'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('No iOS devices'),
]),
);
});
test('fails for Android if no Android devices are present', () async {
setMockFlutterDevicesOutput(hasAndroidDevice: false);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--android'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('No Android devices'),
]),
);
});
test('a plugin without any integration test files is reported as an error',
() async {
setMockFlutterDevicesOutput();
createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/lib/main.dart',
'example/android/android.java',
'example/ios/ios.m',
],
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
},
);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--android'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No driver tests were run (1 example(s) found).'),
contains('No tests ran'),
]),
);
});
test('integration tests using test(...) fail validation', () async {
setMockFlutterDevicesOutput();
final RepositoryPackage package = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/test_driver/integration_test.dart',
'example/integration_test/foo_test.dart',
'example/android/android.java',
],
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
},
);
package.directory
.childDirectory('example')
.childDirectory('integration_test')
.childFile('foo_test.dart')
.writeAsStringSync('''
test('this is the wrong kind of test!'), () {
...
}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--android'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('foo_test.dart failed validation'),
]),
);
});
test('tests an iOS plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/bar_test.dart',
'example/integration_test/foo_test.dart',
'example/integration_test/ignore_me.dart',
'example/android/android.java',
'example/ios/ios.m',
],
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
setMockFlutterDevicesOutput();
final List<String> output =
await runCapturingPrint(runner, <String>['drive-examples', '--ios']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(getFlutterCommand(mockPlatform),
const <String>['devices', '--machine'], null),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
_fakeIOSDevice,
'integration_test',
],
pluginExampleDirectory.path),
]));
});
test('driving when plugin does not support Linux is a no-op', () async {
createFakePlugin('plugin', packagesDir, extraFiles: <String>[
'example/integration_test/plugin_test.dart',
]);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--linux',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('Skipping unsupported platform linux...'),
contains('No issues found!'),
]),
);
// Output should be empty since running drive-examples --linux on a non-Linux
// plugin is a no-op.
expect(processRunner.recordedCalls, <ProcessCall>[]);
});
test('tests a Linux plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/linux/linux.cc',
],
platformSupport: <String, PlatformDetails>{
platformLinux: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--linux',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'linux',
'integration_test',
],
pluginExampleDirectory.path),
]));
});
test('driving when plugin does not suppport macOS is a no-op', () async {
createFakePlugin('plugin', packagesDir, extraFiles: <String>[
'example/integration_test/plugin_test.dart',
]);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--macos',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('Skipping unsupported platform macos...'),
contains('No issues found!'),
]),
);
// Output should be empty since running drive-examples --macos with no macos
// implementation is a no-op.
expect(processRunner.recordedCalls, <ProcessCall>[]);
});
test('tests a macOS plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/macos/macos.swift',
],
platformSupport: <String, PlatformDetails>{
platformMacOS: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--macos',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'macos',
'integration_test',
],
pluginExampleDirectory.path),
]));
});
// This tests the workaround for https://github.com/flutter/flutter/issues/135673
// and the behavior it tests should be removed once that is fixed.
group('runs tests separately on desktop', () {
test('macOS', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/first_test.dart',
'example/integration_test/second_test.dart',
'example/macos/macos.swift',
],
platformSupport: <String, PlatformDetails>{
platformMacOS: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--macos',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'macos',
'integration_test/first_test.dart',
],
pluginExampleDirectory.path),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'macos',
'integration_test/second_test.dart',
],
pluginExampleDirectory.path),
]));
});
// This tests the workaround for https://github.com/flutter/flutter/issues/135673
// and the behavior it tests should be removed once that is fixed.
test('Linux', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/first_test.dart',
'example/integration_test/second_test.dart',
'example/linux/foo.cc',
],
platformSupport: <String, PlatformDetails>{
platformLinux: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--linux',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'linux',
'integration_test/first_test.dart',
],
pluginExampleDirectory.path),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'linux',
'integration_test/second_test.dart',
],
pluginExampleDirectory.path),
]));
});
// This tests the workaround for https://github.com/flutter/flutter/issues/135673
// and the behavior it tests should be removed once that is fixed.
test('Windows', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/first_test.dart',
'example/integration_test/second_test.dart',
'example/windows/foo.cpp',
],
platformSupport: <String, PlatformDetails>{
platformWindows: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--windows',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'windows',
'integration_test/first_test.dart',
],
pluginExampleDirectory.path),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'windows',
'integration_test/second_test.dart',
],
pluginExampleDirectory.path),
]));
});
});
test('driving when plugin does not suppport web is a no-op', () async {
createFakePlugin('plugin', packagesDir, extraFiles: <String>[
'example/integration_test/plugin_test.dart',
]);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--web',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
// Output should be empty since running drive-examples --web on a non-web
// plugin is a no-op.
expect(processRunner.recordedCalls, <ProcessCall>[]);
});
test('drives a web plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/test_driver/integration_test.dart',
'example/web/index.html',
],
platformSupport: <String, PlatformDetails>{
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--web',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'drive',
'-d',
'web-server',
'--web-port=7357',
'--browser-name=chrome',
'--web-renderer=html',
'--driver',
'test_driver/integration_test.dart',
'--target',
'integration_test/plugin_test.dart',
],
pluginExampleDirectory.path),
]));
});
test('runs chromedriver when requested', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/test_driver/integration_test.dart',
'example/web/index.html',
],
platformSupport: <String, PlatformDetails>{
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--web', '--run-chromedriver']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall('chromedriver', <String>['--port=4444'], null),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'drive',
'-d',
'web-server',
'--web-port=7357',
'--browser-name=chrome',
'--web-renderer=html',
'--driver',
'test_driver/integration_test.dart',
'--target',
'integration_test/plugin_test.dart',
],
pluginExampleDirectory.path),
]));
});
test('drives a web plugin with CHROME_EXECUTABLE', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/test_driver/integration_test.dart',
'example/web/index.html',
],
platformSupport: <String, PlatformDetails>{
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
mockPlatform.environment['CHROME_EXECUTABLE'] = '/path/to/chrome';
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--web',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'drive',
'-d',
'web-server',
'--web-port=7357',
'--browser-name=chrome',
'--web-renderer=html',
'--chrome-binary=/path/to/chrome',
'--driver',
'test_driver/integration_test.dart',
'--target',
'integration_test/plugin_test.dart',
],
pluginExampleDirectory.path),
]));
});
test('driving when plugin does not suppport Windows is a no-op', () async {
createFakePlugin('plugin', packagesDir, extraFiles: <String>[
'example/integration_test/plugin_test.dart',
]);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--windows',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('Skipping unsupported platform windows...'),
contains('No issues found!'),
]),
);
// Output should be empty since running drive-examples --windows on a
// non-Windows plugin is a no-op.
expect(processRunner.recordedCalls, <ProcessCall>[]);
});
test('tests a Windows plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/windows/windows.cpp',
],
platformSupport: <String, PlatformDetails>{
platformWindows: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--windows',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
'windows',
'integration_test',
],
pluginExampleDirectory.path),
]));
});
test('tests an Android plugin', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/android/android.java',
],
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
setMockFlutterDevicesOutput();
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--android',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(getFlutterCommand(mockPlatform),
const <String>['devices', '--machine'], null),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
_fakeAndroidDevice,
'integration_test',
],
pluginExampleDirectory.path),
]));
});
test('tests an Android plugin with "apk" alias', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/android/android.java',
],
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
setMockFlutterDevicesOutput();
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--apk',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(getFlutterCommand(mockPlatform),
const <String>['devices', '--machine'], null),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
_fakeAndroidDevice,
'integration_test',
],
pluginExampleDirectory.path),
]));
});
test('driving when plugin does not support Android is no-op', () async {
createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
],
platformSupport: <String, PlatformDetails>{
platformMacOS: const PlatformDetails(PlatformSupport.inline),
},
);
setMockFlutterDevicesOutput();
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--android']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('Skipping unsupported platform android...'),
contains('No issues found!'),
]),
);
// Output should be empty other than the device query.
expect(processRunner.recordedCalls, <ProcessCall>[
ProcessCall(getFlutterCommand(mockPlatform),
const <String>['devices', '--machine'], null),
]);
});
test('driving when plugin does not support iOS is no-op', () async {
createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
],
platformSupport: <String, PlatformDetails>{
platformMacOS: const PlatformDetails(PlatformSupport.inline),
},
);
setMockFlutterDevicesOutput();
final List<String> output =
await runCapturingPrint(runner, <String>['drive-examples', '--ios']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('Skipping unsupported platform ios...'),
contains('No issues found!'),
]),
);
// Output should be empty other than the device query.
expect(processRunner.recordedCalls, <ProcessCall>[
ProcessCall(getFlutterCommand(mockPlatform),
const <String>['devices', '--machine'], null),
]);
});
test('platform interface plugins are silently skipped', () async {
createFakePlugin('aplugin_platform_interface', packagesDir,
examples: <String>[]);
setMockFlutterDevicesOutput();
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--macos']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for aplugin_platform_interface'),
contains(
'SKIPPING: Platform interfaces are not expected to have integration tests.'),
contains('No issues found!'),
]),
);
// Output should be empty since it's skipped.
expect(processRunner.recordedCalls, <ProcessCall>[]);
});
test('enable-experiment flag', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/plugin_test.dart',
'example/android/android.java',
'example/ios/ios.m',
],
platformSupport: <String, PlatformDetails>{
platformAndroid: const PlatformDetails(PlatformSupport.inline),
platformIOS: const PlatformDetails(PlatformSupport.inline),
},
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
setMockFlutterDevicesOutput();
await runCapturingPrint(runner, <String>[
'drive-examples',
'--ios',
'--enable-experiment=exp1',
]);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(getFlutterCommand(mockPlatform),
const <String>['devices', '--machine'], null),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
_fakeIOSDevice,
'--enable-experiment=exp1',
'integration_test',
],
pluginExampleDirectory.path),
]));
});
test('fails when no example is present', () async {
createFakePlugin(
'plugin',
packagesDir,
examples: <String>[],
platformSupport: <String, PlatformDetails>{
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--web'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No driver tests were run (0 example(s) found).'),
contains('The following packages had errors:'),
contains(' plugin:\n'
' No tests ran (use --exclude if this is intentional)'),
]),
);
});
test('web fails when no driver is present', () async {
createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/bar_test.dart',
'example/integration_test/foo_test.dart',
'example/web/index.html',
],
platformSupport: <String, PlatformDetails>{
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--web'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No driver found for plugin/example'),
contains('No driver tests were run (1 example(s) found).'),
contains('The following packages had errors:'),
contains(' plugin:\n'
' No tests ran (use --exclude if this is intentional)'),
]),
);
});
test('web fails when no integration tests are present', () async {
createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/test_driver/integration_test.dart',
'example/web/index.html',
],
platformSupport: <String, PlatformDetails>{
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--web'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('No driver tests were run (1 example(s) found).'),
contains('The following packages had errors:'),
contains(' plugin:\n'
' No tests ran (use --exclude if this is intentional)'),
]),
);
});
test('"flutter drive" reports test failures', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/test_driver/integration_test.dart',
'example/integration_test/bar_test.dart',
'example/integration_test/foo_test.dart',
'example/web/index.html',
],
platformSupport: <String, PlatformDetails>{
platformWeb: const PlatformDetails(PlatformSupport.inline),
},
);
// Simulate failure from `flutter drive`.
processRunner
.mockProcessesForExecutable[getFlutterCommand(mockPlatform)] =
<FakeProcessInfo>[
// Fail both bar_test.dart and foo_test.dart.
FakeProcessInfo(MockProcess(exitCode: 1), <String>['drive']),
FakeProcessInfo(MockProcess(exitCode: 1), <String>['drive']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--web'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('The following packages had errors:'),
contains(' plugin:\n'
' example/integration_test/bar_test.dart\n'
' example/integration_test/foo_test.dart'),
]),
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'drive',
'-d',
'web-server',
'--web-port=7357',
'--browser-name=chrome',
'--web-renderer=html',
'--driver',
'test_driver/integration_test.dart',
'--target',
'integration_test/bar_test.dart',
],
pluginExampleDirectory.path),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'drive',
'-d',
'web-server',
'--web-port=7357',
'--browser-name=chrome',
'--web-renderer=html',
'--driver',
'test_driver/integration_test.dart',
'--target',
'integration_test/foo_test.dart',
],
pluginExampleDirectory.path),
]));
});
test('"flutter test" reports test failures', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin',
packagesDir,
extraFiles: <String>[
'example/integration_test/bar_test.dart',
'example/integration_test/foo_test.dart',
'example/ios/ios.swift',
],
platformSupport: <String, PlatformDetails>{
platformIOS: const PlatformDetails(PlatformSupport.inline),
},
);
setMockFlutterDevicesOutput();
// Simulate failure from `flutter test`.
processRunner.mockProcessesForExecutable[getFlutterCommand(mockPlatform)]!
.add(FakeProcessInfo(MockProcess(exitCode: 1), <String>['test']));
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['drive-examples', '--ios'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('The following packages had errors:'),
contains(' plugin:\n'
' Integration tests failed.'),
]),
);
final Directory pluginExampleDirectory = getExampleDir(plugin);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(getFlutterCommand(mockPlatform),
const <String>['devices', '--machine'], null),
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'test',
'-d',
_fakeIOSDevice,
'integration_test',
],
pluginExampleDirectory.path),
]));
});
group('packages', () {
test('can be driven', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, extraFiles: <String>[
'example/integration_test/foo_test.dart',
'example/test_driver/integration_test.dart',
'example/web/index.html',
]);
final Directory exampleDirectory = getExampleDir(package);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--web',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'drive',
'-d',
'web-server',
'--web-port=7357',
'--browser-name=chrome',
'--web-renderer=html',
'--driver',
'test_driver/integration_test.dart',
'--target',
'integration_test/foo_test.dart'
],
exampleDirectory.path),
]));
});
test('are skipped when example does not support platform', () async {
createFakePackage('a_package', packagesDir,
isFlutter: true,
extraFiles: <String>[
'example/integration_test/foo_test.dart',
'example/test_driver/integration_test.dart',
]);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--web',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package'),
contains('Skipping a_package/example; does not support any '
'requested platforms'),
contains('SKIPPING: No example supports requested platform(s).'),
]),
);
expect(processRunner.recordedCalls.isEmpty, true);
});
test('drive only supported examples if there is more than one', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
isFlutter: true,
examples: <String>[
'with_web',
'without_web'
],
extraFiles: <String>[
'example/with_web/integration_test/foo_test.dart',
'example/with_web/test_driver/integration_test.dart',
'example/with_web/web/index.html',
'example/without_web/integration_test/foo_test.dart',
'example/without_web/test_driver/integration_test.dart',
]);
final Directory supportedExampleDirectory =
getExampleDir(package).childDirectory('with_web');
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--web',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package'),
contains(
'Skipping a_package/example/without_web; does not support any requested platforms.'),
contains('No issues found!'),
]),
);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
getFlutterCommand(mockPlatform),
const <String>[
'drive',
'-d',
'web-server',
'--web-port=7357',
'--browser-name=chrome',
'--web-renderer=html',
'--driver',
'test_driver/integration_test.dart',
'--target',
'integration_test/foo_test.dart'
],
supportedExampleDirectory.path),
]));
});
test('are skipped when there is no integration testing', () async {
createFakePackage('a_package', packagesDir,
isFlutter: true, extraFiles: <String>['example/web/index.html']);
final List<String> output = await runCapturingPrint(runner, <String>[
'drive-examples',
'--web',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package'),
contains(
'SKIPPING: No example is configured for integration tests.'),
]),
);
expect(processRunner.recordedCalls.isEmpty, true);
});
});
});
}
| packages/script/tool/test/drive_examples_command_test.dart/0 | {
"file_path": "packages/script/tool/test/drive_examples_command_test.dart",
"repo_id": "packages",
"token_count": 21833
} | 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.
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/pubspec_check_command.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
/// Returns the top section of a pubspec.yaml for a package named [name].
///
/// By default it will create a header that includes all of the expected
/// values, elements can be changed via arguments to create incorrect
/// entries.
///
/// If [includeRepository] is true, by default the path in the link will
/// be "packages/[name]"; a different "packages"-relative path can be
/// provided with [repositoryPackagesDirRelativePath].
String _headerSection(
String name, {
String repository = 'flutter/packages',
bool includeRepository = true,
String repositoryBranch = 'main',
String? repositoryPackagesDirRelativePath,
bool includeHomepage = false,
bool includeIssueTracker = true,
bool publishable = true,
String? description,
}) {
final String repositoryPath = repositoryPackagesDirRelativePath ?? name;
final List<String> repoLinkPathComponents = <String>[
repository,
'tree',
repositoryBranch,
'packages',
repositoryPath,
];
final String repoLink =
'https://github.com/${repoLinkPathComponents.join('/')}';
final String issueTrackerLink = 'https://github.com/flutter/flutter/issues?'
'q=is%3Aissue+is%3Aopen+label%3A%22p%3A+$name%22';
description ??= 'A test package for validating that the pubspec.yaml '
'follows repo best practices.';
return '''
name: $name
description: $description
${includeRepository ? 'repository: $repoLink' : ''}
${includeHomepage ? 'homepage: $repoLink' : ''}
${includeIssueTracker ? 'issue_tracker: $issueTrackerLink' : ''}
version: 1.0.0
${publishable ? '' : "publish_to: 'none'"}
''';
}
String _environmentSection({
String dartConstraint = '>=2.17.0 <4.0.0',
String? flutterConstraint = '>=3.0.0',
}) {
return <String>[
'environment:',
' sdk: "$dartConstraint"',
if (flutterConstraint != null) ' flutter: "$flutterConstraint"',
'',
].join('\n');
}
String _flutterSection({
bool isPlugin = false,
String? implementedPackage,
Map<String, Map<String, String>> pluginPlatformDetails =
const <String, Map<String, String>>{},
}) {
String pluginEntry = '''
plugin:
${implementedPackage == null ? '' : ' implements: $implementedPackage'}
platforms:
''';
for (final MapEntry<String, Map<String, String>> platform
in pluginPlatformDetails.entries) {
pluginEntry += '''
${platform.key}:
''';
for (final MapEntry<String, String> detail in platform.value.entries) {
pluginEntry += '''
${detail.key}: ${detail.value}
''';
}
}
return '''
flutter:
${isPlugin ? pluginEntry : ''}
''';
}
String _dependenciesSection(
[List<String> extraDependencies = const <String>[]]) {
return '''
dependencies:
flutter:
sdk: flutter
${extraDependencies.map((String dep) => ' $dep').join('\n')}
''';
}
String _devDependenciesSection(
[List<String> extraDependencies = const <String>[]]) {
return '''
dev_dependencies:
flutter_test:
sdk: flutter
${extraDependencies.map((String dep) => ' $dep').join('\n')}
''';
}
String _topicsSection([List<String> topics = const <String>['a-topic']]) {
return '''
topics:
${topics.map((String topic) => ' - $topic').join('\n')}
''';
}
String _falseSecretsSection() {
return '''
false_secrets:
- /lib/main.dart
''';
}
void main() {
group('test pubspec_check_command', () {
late CommandRunner<void> runner;
late RecordingProcessRunner processRunner;
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = fileSystem.currentDirectory.childDirectory('packages');
createPackagesDirectory(parentDir: packagesDir.parent);
processRunner = RecordingProcessRunner();
final PubspecCheckCommand command = PubspecCheckCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner = CommandRunner<void>(
'pubspec_check_command', 'Test for pubspec_check_command');
runner.addCommand(command);
});
test('passes for a plugin following conventions', () async {
final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection()}
${_falseSecretsSection()}
''');
plugin.getExamples().first.pubspecFile.writeAsStringSync('''
${_headerSection(
'plugin_example',
publishable: false,
includeRepository: false,
includeIssueTracker: false,
)}
${_environmentSection()}
${_dependenciesSection()}
${_flutterSection()}
''');
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin...'),
contains('Running for plugin/example...'),
contains('No issues found!'),
]),
);
});
test('passes for a Flutter package following conventions', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection()}
${_dependenciesSection()}
${_devDependenciesSection()}
${_flutterSection()}
${_topicsSection()}
${_falseSecretsSection()}
''');
package.getExamples().first.pubspecFile.writeAsStringSync('''
${_headerSection(
'a_package',
publishable: false,
includeRepository: false,
includeIssueTracker: false,
)}
${_environmentSection()}
${_dependenciesSection()}
${_flutterSection()}
''');
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package...'),
contains('Running for a_package/example...'),
contains('No issues found!'),
]),
);
});
test('passes for a minimal package following conventions', () async {
final RepositoryPackage package =
createFakePackage('package', packagesDir, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('package')}
${_environmentSection()}
${_dependenciesSection()}
${_topicsSection()}
''');
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for package...'),
contains('No issues found!'),
]),
);
});
test('fails when homepage is included', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', includeHomepage: true)}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Found a "homepage" entry; only "repository" should be used.'),
]),
);
});
test('fails when repository is missing', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', includeRepository: false)}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Missing "repository"'),
]),
);
});
test('fails when homepage is given instead of repository', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', includeHomepage: true, includeRepository: false)}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Found a "homepage" entry; only "repository" should be used.'),
]),
);
});
test('fails when repository package name is incorrect', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', repositoryPackagesDirRelativePath: 'different_plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The "repository" link should end with the package path.'),
]),
);
});
test('fails when repository uses master instead of main', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', repositoryBranch: 'master')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The "repository" link should start with the repository\'s '
'main tree: "https://github.com/flutter/packages/tree/main"'),
]),
);
});
test('fails when repository is not flutter/packages', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', repository: 'flutter/plugins')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The "repository" link should start with the repository\'s '
'main tree: "https://github.com/flutter/packages/tree/main"'),
]),
);
});
test('fails when issue tracker is missing', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', includeIssueTracker: false)}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('A package should have an "issue_tracker" link'),
]),
);
});
test('fails when description is too short', () async {
final RepositoryPackage plugin = createFakePlugin(
'a_plugin', packagesDir.childDirectory('a_plugin'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', description: 'Too short')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('"description" is too short. pub.dev recommends package '
'descriptions of 60-180 characters.'),
]),
);
});
test(
'allows short descriptions for non-app-facing parts of federated plugins',
() async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', description: 'Too short')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('"description" is too short. pub.dev recommends package '
'descriptions of 60-180 characters.'),
]),
);
});
test('fails when description is too long', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
const String description = 'This description is too long. It just goes '
'on and on and on and on and on. pub.dev will down-score it because '
'there is just too much here. Someone shoul really cut this down to just '
'the core description so that search results are more useful and the '
'package does not lose pub points.';
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin', description: description)}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('"description" is too long. pub.dev recommends package '
'descriptions of 60-180 characters.'),
]),
);
});
test('fails when topics section is missing', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('A published package should include "topics".'),
]),
);
});
test('fails when topics section is empty', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>[])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('A published package should include "topics".'),
]),
);
});
test('fails when federated plugin topics do not include plugin name',
() async {
final RepositoryPackage plugin = createFakePlugin(
'some_plugin_ios', packagesDir.childDirectory('some_plugin'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'A federated plugin package should include its plugin name as a topic. '
'Add "some-plugin" to the "topics" section.'),
]),
);
});
test('fails when topic name contains a space', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['plugin a'])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Invalid topic(s): plugin a in "topics" section. '),
]),
);
});
test('fails when topic a topic name contains double dash', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['plugin--a'])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Invalid topic(s): plugin--a in "topics" section. '),
]),
);
});
test('fails when topic a topic name starts with a number', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['1plugin-a'])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Invalid topic(s): 1plugin-a in "topics" section. '),
]),
);
});
test('fails when topic a topic name contains uppercase', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['plugin-A'])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Invalid topic(s): plugin-A in "topics" section. '),
]),
);
});
test('fails when there are more than 5 topics', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>[
'plugin-a',
'plugin-a',
'plugin-a',
'plugin-a',
'plugin-a',
'plugin-a'
])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
' A published package should have maximum 5 topics. See https://dart.dev/tools/pub/pubspec#topics.'),
]),
);
});
test('fails if a topic name is longer than 32 characters', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['foobarfoobarfoobarfoobarfoobarfoobarfoo'])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Invalid topic(s): foobarfoobarfoobarfoobarfoobarfoobarfoo in "topics" section. '),
]),
);
});
test('fails if a topic name is longer than 2 characters', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['a'])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Invalid topic(s): a in "topics" section. '),
]),
);
});
test('fails if a topic name ends in a dash', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['plugin-'])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Invalid topic(s): plugin- in "topics" section. '),
]),
);
});
test('Invalid topics section has expected error message', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['plugin-A', 'Plugin-b'])}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Invalid topic(s): plugin-A, Plugin-b in "topics" section. '
'Topics must consist of lowercase alphanumerical characters or dash (but no double dash), '
'start with a-z and ending with a-z or 0-9, have a minimum of 2 characters '
'and have a maximum of 32 characters.'),
]),
);
});
test('fails when environment section is out of order', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_environmentSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Major sections should follow standard repository ordering:'),
]),
);
});
test('fails when flutter section is out of order', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_flutterSection(isPlugin: true)}
${_environmentSection()}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Major sections should follow standard repository ordering:'),
]),
);
});
test('fails when dependencies section is out of order', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_devDependenciesSection()}
${_dependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Major sections should follow standard repository ordering:'),
]),
);
});
test('fails when dev_dependencies section is out of order', () async {
final RepositoryPackage plugin = createFakePlugin('plugin', packagesDir);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_devDependenciesSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Major sections should follow standard repository ordering:'),
]),
);
});
test('fails when false_secrets section is out of order', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_falseSecretsSection()}
${_devDependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Major sections should follow standard repository ordering:'),
]),
);
});
test('fails when an implemenation package is missing "implements"',
() async {
final RepositoryPackage plugin = createFakePlugin(
'plugin_a_foo', packagesDir.childDirectory('plugin_a'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin_a_foo')}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Missing "implements: plugin_a" in "plugin" section.'),
]),
);
});
test('fails when an implemenation package has the wrong "implements"',
() async {
final RepositoryPackage plugin = createFakePlugin(
'plugin_a_foo', packagesDir.childDirectory('plugin_a'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin_a_foo')}
${_environmentSection()}
${_flutterSection(isPlugin: true, implementedPackage: 'plugin_a_foo')}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Expecetd "implements: plugin_a"; '
'found "implements: plugin_a_foo".'),
]),
);
});
test('passes for a correct implemenation package', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin_a_foo', packagesDir.childDirectory('plugin_a'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection(
'plugin_a_foo',
repositoryPackagesDirRelativePath: 'plugin_a/plugin_a_foo',
)}
${_environmentSection()}
${_flutterSection(isPlugin: true, implementedPackage: 'plugin_a')}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['plugin-a'])}
''');
final List<String> output =
await runCapturingPrint(runner, <String>['pubspec-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin_a_foo...'),
contains('No issues found!'),
]),
);
});
test('fails when a "default_package" looks incorrect', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin_a', packagesDir.childDirectory('plugin_a'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection(
'plugin_a',
repositoryPackagesDirRelativePath: 'plugin_a/plugin_a',
)}
${_environmentSection()}
${_flutterSection(
isPlugin: true,
pluginPlatformDetails: <String, Map<String, String>>{
'android': <String, String>{'default_package': 'plugin_b_android'}
},
)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'"plugin_b_android" is not an expected implementation name for "plugin_a"'),
]),
);
});
test(
'fails when a "default_package" does not have a corresponding dependency',
() async {
final RepositoryPackage plugin = createFakePlugin(
'plugin_a', packagesDir.childDirectory('plugin_a'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection(
'plugin_a',
repositoryPackagesDirRelativePath: 'plugin_a/plugin_a',
)}
${_environmentSection()}
${_flutterSection(
isPlugin: true,
pluginPlatformDetails: <String, Map<String, String>>{
'android': <String, String>{'default_package': 'plugin_a_android'}
},
)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The following default_packages are missing corresponding '
'dependencies:\n plugin_a_android'),
]),
);
});
test('passes for an app-facing package without "implements"', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin_a', packagesDir.childDirectory('plugin_a'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection(
'plugin_a',
repositoryPackagesDirRelativePath: 'plugin_a/plugin_a',
)}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['plugin-a'])}
''');
final List<String> output =
await runCapturingPrint(runner, <String>['pubspec-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin_a/plugin_a...'),
contains('No issues found!'),
]),
);
});
test('passes for a platform interface package without "implements"',
() async {
final RepositoryPackage plugin = createFakePlugin(
'plugin_a_platform_interface', packagesDir.childDirectory('plugin_a'),
examples: <String>[]);
plugin.pubspecFile.writeAsStringSync('''
${_headerSection(
'plugin_a_platform_interface',
repositoryPackagesDirRelativePath:
'plugin_a/plugin_a_platform_interface',
)}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_topicsSection(<String>['plugin-a'])}
''');
final List<String> output =
await runCapturingPrint(runner, <String>['pubspec-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin_a_platform_interface...'),
contains('No issues found!'),
]),
);
});
test('validates some properties even for unpublished packages', () async {
final RepositoryPackage plugin = createFakePlugin(
'plugin_a_foo', packagesDir.childDirectory('plugin_a'),
examples: <String>[]);
// Environment section is in the wrong location.
// Missing 'implements'.
plugin.pubspecFile.writeAsStringSync('''
${_headerSection('plugin_a_foo', publishable: false)}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
${_environmentSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['pubspec-check'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Major sections should follow standard repository ordering:'),
contains('Missing "implements: plugin_a" in "plugin" section.'),
]),
);
});
test('ignores some checks for unpublished packages', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, examples: <String>[]);
// Missing metadata that is only useful for published packages, such as
// repository and issue tracker.
plugin.pubspecFile.writeAsStringSync('''
${_headerSection(
'plugin',
publishable: false,
includeRepository: false,
includeIssueTracker: false,
)}
${_environmentSection()}
${_flutterSection(isPlugin: true)}
${_dependenciesSection()}
${_devDependenciesSection()}
''');
final List<String> output =
await runCapturingPrint(runner, <String>['pubspec-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin...'),
contains('No issues found!'),
]),
);
});
test('fails when a Flutter package has a too-low minimum Flutter version',
() async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
isFlutter: true, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection(flutterConstraint: '>=2.10.0')}
${_dependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
'--min-min-flutter-version',
'3.0.0'
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Minimum allowed Flutter version 2.10.0 is less than 3.0.0'),
]),
);
});
test(
'passes when a Flutter package requires exactly the minimum Flutter version',
() async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
isFlutter: true, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection(flutterConstraint: '>=3.3.0', dartConstraint: '>=2.18.0 <4.0.0')}
${_dependenciesSection()}
${_topicsSection()}
''');
final List<String> output = await runCapturingPrint(runner,
<String>['pubspec-check', '--min-min-flutter-version', '3.3.0']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test(
'passes when a Flutter package requires a higher minimum Flutter version',
() async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
isFlutter: true, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection(flutterConstraint: '>=3.7.0', dartConstraint: '>=2.19.0 <4.0.0')}
${_dependenciesSection()}
${_topicsSection()}
''');
final List<String> output = await runCapturingPrint(runner,
<String>['pubspec-check', '--min-min-flutter-version', '3.3.0']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test('fails when a non-Flutter package has a too-low minimum Dart version',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection(dartConstraint: '>=2.14.0 <4.0.0', flutterConstraint: null)}
${_dependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
'--min-min-flutter-version',
'3.0.0'
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Minimum allowed Dart version 2.14.0 is less than 2.17.0'),
]),
);
});
test(
'passes when a non-Flutter package requires exactly the minimum Dart version',
() async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
isFlutter: true, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection(dartConstraint: '>=2.18.0 <4.0.0', flutterConstraint: null)}
${_dependenciesSection()}
${_topicsSection()}
''');
final List<String> output = await runCapturingPrint(runner,
<String>['pubspec-check', '--min-min-flutter-version', '3.3.0']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test(
'passes when a non-Flutter package requires a higher minimum Dart version',
() async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
isFlutter: true, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection(dartConstraint: '>=2.18.0 <4.0.0', flutterConstraint: null)}
${_dependenciesSection()}
${_topicsSection()}
''');
final List<String> output = await runCapturingPrint(runner,
<String>['pubspec-check', '--min-min-flutter-version', '3.0.0']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test('fails when a Flutter->Dart SDK version mapping is missing', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection()}
${_dependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
'--min-min-flutter-version',
'2.0.0'
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Dart SDK version for Fluter SDK version 2.0.0 is unknown'),
]),
);
});
test(
'fails when a Flutter package has a too-low minimum Dart version for '
'the corresponding minimum Flutter version', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
isFlutter: true, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection(flutterConstraint: '>=3.3.0', dartConstraint: '>=2.16.0 <4.0.0')}
${_dependenciesSection()}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('The minimum Dart version is 2.16.0, but the '
'minimum Flutter version of 3.3.0 shipped with '
'Dart 2.18.0. Please use consistent lower SDK '
'bounds'),
]),
);
});
group('dependency check', () {
test('passes for local dependencies', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
final RepositoryPackage dependencyPackage =
createFakePackage('local_dependency', packagesDir);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection()}
${_dependenciesSection(<String>['local_dependency: ^1.0.0'])}
${_topicsSection()}
''');
dependencyPackage.pubspecFile.writeAsStringSync('''
${_headerSection('local_dependency')}
${_environmentSection()}
${_dependenciesSection()}
${_topicsSection()}
''');
final List<String> output =
await runCapturingPrint(runner, <String>['pubspec-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test('fails when an unexpected dependency is found', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection()}
${_dependenciesSection(<String>['bad_dependency: ^1.0.0'])}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'The following unexpected non-local dependencies were found:\n'
' bad_dependency\n'
'Please see https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#Dependencies '
'for more information and next steps.'),
]),
);
});
test('fails when an unexpected dev dependency is found', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection()}
${_dependenciesSection()}
${_devDependenciesSection(<String>['bad_dependency: ^1.0.0'])}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'The following unexpected non-local dependencies were found:\n'
' bad_dependency\n'
'Please see https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#Dependencies '
'for more information and next steps.'),
]),
);
});
test('passes when a dependency is on the allow list', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection()}
${_dependenciesSection(<String>['allowed: ^1.0.0'])}
${_topicsSection()}
''');
final List<String> output = await runCapturingPrint(runner,
<String>['pubspec-check', '--allow-dependencies', 'allowed']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test('passes when a pinned dependency is on the pinned allow list',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection()}
${_dependenciesSection(<String>['allow_pinned: 1.0.0'])}
${_topicsSection()}
''');
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
'--allow-pinned-dependencies',
'allow_pinned'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for a_package...'),
contains('No issues found!'),
]),
);
});
test('fails when an allowed-when-pinned dependency is unpinned',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
package.pubspecFile.writeAsStringSync('''
${_headerSection('a_package')}
${_environmentSection()}
${_dependenciesSection(<String>['allow_pinned: ^1.0.0'])}
${_topicsSection()}
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'pubspec-check',
'--allow-pinned-dependencies',
'allow_pinned'
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'The following unexpected non-local dependencies were found:\n'
' allow_pinned\n'
'Please see https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#Dependencies '
'for more information and next steps.'),
]),
);
});
});
});
group('test pubspec_check_command on Windows', () {
late CommandRunner<void> runner;
late RecordingProcessRunner processRunner;
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
setUp(() {
fileSystem = MemoryFileSystem(style: FileSystemStyle.windows);
mockPlatform = MockPlatform(isWindows: true);
packagesDir = fileSystem.currentDirectory.childDirectory('packages');
createPackagesDirectory(parentDir: packagesDir.parent);
processRunner = RecordingProcessRunner();
final PubspecCheckCommand command = PubspecCheckCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner = CommandRunner<void>(
'pubspec_check_command', 'Test for pubspec_check_command');
runner.addCommand(command);
});
test('repository check works', () async {
final RepositoryPackage package =
createFakePackage('package', packagesDir, examples: <String>[]);
package.pubspecFile.writeAsStringSync('''
${_headerSection('package')}
${_environmentSection()}
${_dependenciesSection()}
${_topicsSection()}
''');
final List<String> output =
await runCapturingPrint(runner, <String>['pubspec-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for package...'),
contains('No issues found!'),
]),
);
});
});
}
| packages/script/tool/test/pubspec_check_command_test.dart/0 | {
"file_path": "packages/script/tool/test/pubspec_check_command_test.dart",
"repo_id": "packages",
"token_count": 21405
} | 1,142 |
@font-face {
font-family: 'Cupertino Icons';
font-style: normal;
font-weight: 400;
src: url("../assets/CupertinoIcons.ttf") format("truetype");
}
.cupertino-icons, .cupertino-icons {
font-family: 'Cupertino Icons';
font-weight: normal;
font-style: normal;
font-size: 28px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
-moz-osx-font-smoothing: grayscale;
-webkit-font-feature-settings: "liga";
-moz-font-feature-settings: "liga=1";
-moz-font-feature-settings: "liga";
font-feature-settings: "liga";
text-align: center;
} | packages/third_party/packages/cupertino_icons/css/icons.css/0 | {
"file_path": "packages/third_party/packages/cupertino_icons/css/icons.css",
"repo_id": "packages",
"token_count": 285
} | 1,143 |
export default `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/png" href="{{{assetUrls.favicon}}}">
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>{{meta.title}}</title>
<meta name="descripton" content="{{meta.desc}}">
{{{ga}}}
<meta property="og:title" content="{{meta.title}}">
<meta property="og:description" content="{{meta.desc}}">
<meta property="og:url" content="{{{shareUrl}}}">
<meta property="og:image" content="{{{shareImageUrl}}}">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="{{meta.title}}">
<meta name="twitter:text:title" content="{{meta.title}}">
<meta name="twitter:description" content="{{meta.desc}}">
<meta name="twitter:image" content="{{{shareImageUrl}}}">
<meta name="twitter:site" content="@flutterdev">
<link href="https://fonts.googleapis.com/css?family=Google+Sans:400,500" rel="stylesheet">
<style>{{{styles}}}</style>
</head>
<body>
<div class="backdrop"></div>
<img src="{{{assetUrls.fixedPhotosLeft}}}" class="fixed-photos left">
<img src="{{{assetUrls.fixedPhotosRight}}}" class="fixed-photos right">
<main>
<div class="share-image">
<img src="{{{shareImageUrl}}}">
</div>
<div class="text">
<h1>Taken with I/O Photo Booth</h1>
<h2>Join the fun! Grab a photo with your favorite Google mascot
at the I/O Photo Booth.</h2>
<a class="share-btn" href="/">Get started</a>
</div>
</main>
{{{footer}}}
</body>
</html>
`;
| photobooth/functions/src/share/templates/share.ts/0 | {
"file_path": "photobooth/functions/src/share/templates/share.ts",
"repo_id": "photobooth",
"token_count": 666
} | 1,144 |
{
"@@locale": "es",
"landingPageHeading": "Bienvenido a I\u2215O Photo Booth",
"landingPageSubheading": "¡Haz una foto y compártela con la comunidad!",
"landingPageTakePhotoButtonText": "Empezar",
"footerMadeWithText": "Hecho con ",
"footerMadeWithFlutterLinkText": "Flutter",
"footerMadeWithFirebaseLinkText": "Firebase",
"footerGoogleIOLinkText": "Google I\u2215O",
"footerCodelabLinkText": "Codelab",
"footerHowItsMadeLinkText": "Cómo se ha hecho",
"footerTermsOfServiceLinkText": "Términos de Servicio",
"footerPrivacyPolicyLinkText": "Política de Privacidad",
"sharePageHeading": "¡Comparte tu foto con la comunidad!",
"sharePageSubheading": "¡Comparte tu foto con la comunidad!",
"sharePageSuccessHeading": "¡Foto compartida!",
"sharePageSuccessSubheading": "¡Gracias por utilizar nuestra aplicación web con Flutter! Tu foto ha sido publicada en esta url única",
"sharePageSuccessCaption1": "Tu foto estará disponible en esta URL durante 30 días y después se eliminará automáticamente. Para solicitar que se elimine antes, por favor contacta con ",
"sharePageSuccessCaption2": "[email protected]",
"sharePageSuccessCaption3": " y asegúrate de incluir la URL única en tu solicitud.",
"sharePageRetakeButtonText": "Hacer una foto nueva",
"sharePageShareButtonText": "Compartir",
"sharePageDownloadButtonText": "Descargar",
"socialMediaShareLinkText": "Me hice un selfie en #IOPhotoBooth. Nos vemos en #GoogleIO!",
"previewPageCameraNotAllowedText": "Has denegado los permisos de la cámara. Por favor activa los permisos para poder utilizar la aplicación.",
"sharePageSocialMediaShareClarification1": "Si eliges compartir tu foto en redes sociales, estará disponible en una URL única durante 30 días y después se eliminará automáticamente. Fotos que no se compartan no se guardarán. Para solicitar que se elimine antes, por favor contacta con ",
"sharePageSocialMediaShareClarification2": "[email protected]",
"sharePageSocialMediaShareClarification3": " y asegúrate de incluir la URL única en tu solicitud.",
"sharePageCopyLinkButton": "Copiar",
"sharePageLinkedCopiedButton": "Copiado",
"sharePageErrorHeading": "Tenemos problemas procesando tu imagen",
"sharePageErrorSubheading": "Por favor asegúrate de que tu dispositivo y navegador están actualizados. Si el problema continúa, por favor contacta [email protected].",
"shareDialogHeading": "¡Comparte tu foto!",
"shareDialogSubheading": "¡Deja que todo el mundo sepa que estás en Google I\u2215O compartiendo tu foto y actualizando tu foto de perfil durante el evento!",
"shareErrorDialogHeading": "Oops!",
"shareErrorDialogTryAgainButton": "Volver",
"shareErrorDialogSubheading": "Algo ha ido mal y no pudimos cargar tu foto.",
"sharePageProgressOverlayHeading": "¡Estamos haciendo tu foto pixel perfect con Flutter! ",
"sharePageProgressOverlaySubheading": "Por favor no cierres esta pestaña.",
"shareDialogTwitterButtonText": "Twitter",
"shareDialogFacebookButtonText": "Facebook",
"photoBoothCameraAccessDeniedHeadline": "Acceso a la cámara denegado",
"photoBoothCameraAccessDeniedSubheadline": "Para hacerte una foto necesitas dar acceso a tu cámara al navegador.",
"photoBoothCameraNotFoundHeadline": "No podemos encontrar tu cámara",
"photoBoothCameraNotFoundSubheadline1": "Parece que tu dispositivo no tiene cámara o no está funcionando.",
"photoBoothCameraNotFoundSubheadline2": "Para hacerte una foto, por favor vuelve a visitar I\u2215O Photo Booth desde un dispositivo con cámara.",
"photoBoothCameraErrorHeadline": "¡Oops! Algo fue mal",
"photoBoothCameraErrorSubheadline1": "Por favor refresca tu navegador e inténtalo de nuevo.",
"photoBoothCameraErrorSubheadline2": "Si este problema persiste, por favor contacta con [email protected]",
"photoBoothCameraNotSupportedHeadline": "Oops! Algo ha ido mal",
"photoBoothCameraNotSupportedSubheadline": "Por favor asegúrate de que tu dispositivo y navegador están actualizados.",
"stickersDrawerTitle": "Añade Accesorios",
"openStickersTooltip": "Añadir Accesorios",
"retakeButtonTooltip": "Volver a hacer una foto",
"clearStickersButtonTooltip": "Eliminar Accesorios",
"charactersCaptionText": "Añadir amigos",
"sharePageLearnMoreAboutTextPart1": "Aprende más sobre ",
"sharePageLearnMoreAboutTextPart2": " y ",
"sharePageLearnMoreAboutTextPart3": " o sumérgete ",
"sharePageLearnMoreAboutTextPart4": "en el código open source",
"goToGoogleIOButtonText": "Ir a Google I\u2215O",
"clearStickersDialogHeading": "¿Borrar todos los accesorios?",
"clearStickersDialogSubheading": "¿Quieres borrar todos los accesorios de la pantalla?",
"clearStickersDialogCancelButtonText": "No, llévame de vuelta",
"clearStickersDialogConfirmButtonText": "Sí, borra todos los accesorios",
"propsReminderText": "Añade algún accesorio",
"stickersNextConfirmationHeading": "¿Preparado para ver la foto final?",
"stickersNextConfirmationSubheading": "Al salir de esta pantalla no podrás hacer más cambios",
"stickersNextConfirmationCancelButtonText": "No, todavía estoy creando",
"stickersNextConfirmationConfirmButtonText": "Sí, múestramela",
"stickersRetakeConfirmationHeading": "¿Estás seguro?",
"stickersRetakeConfirmationSubheading": "Repetir la foto borrará cualquier accesorio añadido",
"stickersRetakeConfirmationCancelButtonText": "No, me quedo aquí",
"stickersRetakeConfirmationConfirmButtonText": "Sí, volver a hacer la foto",
"shareRetakeConfirmationHeading": "¿Listo para hacer una nueva foto?",
"shareRetakeConfirmationSubheading": "Recuerda descargar o compartir esta primero",
"shareRetakeConfirmationCancelButtonText": "No, me quedo aquí",
"shareRetakeConfirmationConfirmButtonText": "Sí, volver a hacer la foto",
"shutterButtonLabelText": "Hacer foto",
"stickersNextButtonLabelText": "Crear foto final",
"dashButtonLabelText": "Añadir al amigo dash",
"sparkyButtonLabelText": "Añadir al amigo sparky",
"dinoButtonLabelText": "Añadir al amigo dino",
"androidButtonLabelText": "Añadir al amigo android jetpack",
"addStickersButtonLabelText": "Añadir accesorios",
"retakePhotoButtonLabelText": "Volver a hacer la foto",
"clearAllStickersButtonLabelText": "Eliminar todos los accesorios"
} | photobooth/lib/l10n/arb/app_es.arb/0 | {
"file_path": "photobooth/lib/l10n/arb/app_es.arb",
"repo_id": "photobooth",
"token_count": 2370
} | 1,145 |
import 'package:flutter/material.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/landing/landing.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class LandingBody extends StatelessWidget {
const LandingBody({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = context.l10n;
final size = MediaQuery.of(context).size;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
children: [
const SizedBox(height: 48),
SelectableText(
l10n.landingPageHeading,
key: const Key('landingPage_heading_text'),
style: theme.textTheme.displayLarge,
textAlign: TextAlign.center,
),
const SizedBox(height: 40),
SelectableText(
l10n.landingPageSubheading,
key: const Key('landingPage_subheading_text'),
style: theme.textTheme.displaySmall,
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
const LandingTakePhotoButton(),
const SizedBox(height: 48),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 48),
child: Image.asset(
'assets/backgrounds/landing_background.png',
height: size.width <= PhotoboothBreakpoints.small
? size.height * 0.4
: size.height * 0.5,
),
),
],
),
);
}
}
| photobooth/lib/landing/widgets/landing_body.dart/0 | {
"file_path": "photobooth/lib/landing/widgets/landing_body.dart",
"repo_id": "photobooth",
"token_count": 748
} | 1,146 |
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
class CharactersLayer extends StatelessWidget {
const CharactersLayer({super.key});
@override
Widget build(BuildContext context) {
final state = context.watch<PhotoboothBloc>().state;
return LayoutBuilder(
builder: (context, constraints) {
return Stack(
children: [
for (final character in state.characters)
Builder(
builder: (context) {
final widthFactor =
constraints.maxWidth / character.constraint.width;
final heightFactor =
constraints.maxHeight / character.constraint.height;
return Positioned(
key: Key(
'charactersLayer_${character.asset.name}_positioned',
),
top: character.position.dy * heightFactor,
left: character.position.dx * widthFactor,
child: Transform.rotate(
angle: character.angle,
child: Image.asset(
character.asset.path,
fit: BoxFit.fill,
height: character.size.height * heightFactor,
width: character.size.width * widthFactor,
),
),
);
},
),
],
);
},
);
}
}
| photobooth/lib/photobooth/widgets/characters_layer.dart/0 | {
"file_path": "photobooth/lib/photobooth/widgets/characters_layer.dart",
"repo_id": "photobooth",
"token_count": 848
} | 1,147 |
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:photobooth_ui/photobooth_ui.dart';
import 'package:photos_repository/photos_repository.dart';
class SharePage extends StatelessWidget {
const SharePage({super.key});
static Route<void> route() {
return AppPageRoute(builder: (_) => const SharePage());
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return BlocProvider(
create: (context) {
final state = context.read<PhotoboothBloc>().state;
return ShareBloc(
photosRepository: context.read<PhotosRepository>(),
imageId: state.imageId,
image: state.image!,
assets: state.assets,
aspectRatio: state.aspectRatio,
shareText: l10n.socialMediaShareLinkText,
)..add(const ShareViewLoaded());
},
child: const ShareView(),
);
}
}
class ShareView extends StatelessWidget {
const ShareView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ShareStateListener(
child: const AppPageView(
background: ShareBackground(),
body: ShareBody(),
footer: WhiteFooter(),
overlays: [
_ShareRetakeButton(),
ShareProgressOverlay(),
],
),
),
);
}
}
class _ShareRetakeButton extends StatelessWidget {
const _ShareRetakeButton();
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final isLoading = context.select(
(ShareBloc bloc) => bloc.state.compositeStatus.isLoading,
);
if (isLoading) return const SizedBox();
return Positioned(
left: 15,
top: 15,
child: Semantics(
focusable: true,
button: true,
label: l10n.retakePhotoButtonLabelText,
child: AppTooltipButton(
key: const Key('sharePage_retake_appTooltipButton'),
onPressed: () async {
final photoboothBloc = context.read<PhotoboothBloc>();
final navigator = Navigator.of(context);
final confirmed = await showAppModal<bool>(
context: context,
landscapeChild: const _ConfirmationDialogContent(),
portraitChild: const _ConfirmationBottomSheet(),
);
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 _ConfirmationDialogContent extends StatelessWidget {
const _ConfirmationDialogContent();
@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.shareRetakeConfirmationHeading,
textAlign: TextAlign.center,
style: theme.textTheme.displayLarge,
),
const SizedBox(height: 24),
Text(
l10n.shareRetakeConfirmationSubheading,
textAlign: TextAlign.center,
style: theme.textTheme.displaySmall,
),
const SizedBox(height: 24),
Wrap(
alignment: WrapAlignment.center,
spacing: 24,
runSpacing: 24,
children: [
OutlinedButton(
key: const Key('sharePage_retakeCancel_elevatedButton'),
style: OutlinedButton.styleFrom(
side: const BorderSide(color: PhotoboothColors.black),
),
onPressed: () => Navigator.of(context).pop(false),
child: Text(
l10n.shareRetakeConfirmationCancelButtonText,
style: theme.textTheme.labelLarge?.copyWith(
color: PhotoboothColors.black,
),
),
),
ElevatedButton(
key: const Key('sharePage_retakeConfirm_elevatedButton'),
onPressed: () => Navigator.of(context).pop(true),
child: Text(l10n.shareRetakeConfirmationConfirmButtonText),
)
],
),
],
),
),
),
);
}
}
class _ConfirmationBottomSheet extends StatelessWidget {
const _ConfirmationBottomSheet();
@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 _ConfirmationDialogContent(),
Positioned(
right: 24,
top: 24,
child: IconButton(
icon: const Icon(Icons.clear, color: PhotoboothColors.black54),
onPressed: () => Navigator.of(context).pop(false),
),
),
],
),
);
}
}
| photobooth/lib/share/view/share_page.dart/0 | {
"file_path": "photobooth/lib/share/view/share_page.dart",
"repo_id": "photobooth",
"token_count": 2848
} | 1,148 |
import 'package:flutter/material.dart';
import 'package:io_photobooth/l10n/l10n.dart';
class ShareTryAgainButton extends StatelessWidget {
const ShareTryAgainButton({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.shareErrorDialogTryAgainButton),
);
}
}
| photobooth/lib/share/widgets/share_try_again_button.dart/0 | {
"file_path": "photobooth/lib/share/widgets/share_try_again_button.dart",
"repo_id": "photobooth",
"token_count": 151
} | 1,149 |
import 'package:flutter/material.dart';
import 'package:io_photobooth/assets.g.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class StickersTabs extends StatefulWidget {
const StickersTabs({
required this.onStickerSelected,
required this.onTabChanged,
this.initialIndex = 0,
super.key,
});
final ValueSetter<Asset> onStickerSelected;
final ValueSetter<int> onTabChanged;
final int initialIndex;
@override
State<StickersTabs> createState() => _StickersTabsState();
}
class _StickersTabsState extends State<StickersTabs>
with TickerProviderStateMixin {
late final TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(
length: 5,
vsync: this,
initialIndex: widget.initialIndex,
);
_tabController.addListener(() {
// False when swipe
if (!_tabController.indexIsChanging) {
widget.onTabChanged(_tabController.index);
}
});
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TabBar(
onTap: widget.onTabChanged,
controller: _tabController,
tabs: const [
StickersTab(
key: Key('stickersTabs_googleTab'),
assetPath: 'assets/icons/google_icon.png',
),
StickersTab(
key: Key('stickersTabs_hatsTab'),
assetPath: 'assets/icons/hats_icon.png',
),
StickersTab(
key: Key('stickersTabs_eyewearTab'),
assetPath: 'assets/icons/eyewear_icon.png',
),
StickersTab(
key: Key('stickersTabs_foodTab'),
assetPath: 'assets/icons/food_icon.png',
),
StickersTab(
key: Key('stickersTabs_shapesTab'),
assetPath: 'assets/icons/shapes_icon.png',
),
],
),
const Divider(),
Expanded(
child: TabBarView(
controller: _tabController,
children: [
StickersTabBarView(
key: const Key('stickersTabs_googleTabBarView'),
stickers: Assets.googleProps,
onStickerSelected: widget.onStickerSelected,
),
StickersTabBarView(
key: const Key('stickersTabs_hatsTabBarView'),
stickers: Assets.hatProps,
onStickerSelected: widget.onStickerSelected,
),
StickersTabBarView(
key: const Key('stickersTabs_eyewearTabBarView'),
stickers: Assets.eyewearProps,
onStickerSelected: widget.onStickerSelected,
),
StickersTabBarView(
key: const Key('stickersTabs_foodTabBarView'),
stickers: Assets.foodProps,
onStickerSelected: widget.onStickerSelected,
),
StickersTabBarView(
key: const Key('stickersTabs_shapesTabBarView'),
stickers: Assets.shapeProps,
onStickerSelected: widget.onStickerSelected,
),
],
),
),
],
);
}
}
@visibleForTesting
class StickersTab extends StatefulWidget {
const StickersTab({
required this.assetPath,
super.key,
});
final String assetPath;
@override
State<StickersTab> createState() => _StickersTabState();
}
class _StickersTabState extends State<StickersTab>
with AutomaticKeepAliveClientMixin<StickersTab> {
@override
Widget build(BuildContext context) {
super.build(context);
return Tab(
iconMargin: const EdgeInsets.only(bottom: 24),
icon: Image.asset(
widget.assetPath,
width: 30,
height: 30,
color: IconTheme.of(context).color,
),
);
}
@override
bool get wantKeepAlive => true;
}
@visibleForTesting
class StickersTabBarView extends StatelessWidget {
const StickersTabBarView({
required this.stickers,
required this.onStickerSelected,
super.key,
});
final Set<Asset> stickers;
final ValueSetter<Asset> onStickerSelected;
static const _smallGridDelegate = SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 100,
mainAxisSpacing: 48,
crossAxisSpacing: 24,
);
static const _defaultGridDelegate = SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 150,
mainAxisSpacing: 64,
crossAxisSpacing: 42,
);
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final gridDelegate = size.width < PhotoboothBreakpoints.small
? _smallGridDelegate
: _defaultGridDelegate;
return GridView.builder(
key: PageStorageKey<String>('$key'),
gridDelegate: gridDelegate,
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 64),
itemCount: stickers.length,
itemBuilder: (context, index) {
final sticker = stickers.elementAt(index);
return StickerChoice(
asset: sticker,
onPressed: () => onStickerSelected(sticker),
);
},
);
}
}
@visibleForTesting
class StickerChoice extends StatelessWidget {
const StickerChoice({
required this.asset,
required this.onPressed,
super.key,
});
final Asset asset;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Image.asset(
asset.path,
frameBuilder: (
BuildContext context,
Widget child,
int? frame,
bool wasSynchronouslyLoaded,
) {
return AppAnimatedCrossFade(
firstChild: SizedBox.fromSize(
size: const Size(20, 20),
child: const AppCircularProgressIndicator(strokeWidth: 2),
),
secondChild: InkWell(
onTap: onPressed,
child: child,
),
crossFadeState: frame == null
? CrossFadeState.showFirst
: CrossFadeState.showSecond,
);
},
);
}
}
| photobooth/lib/stickers/widgets/stickers_tabs.dart/0 | {
"file_path": "photobooth/lib/stickers/widgets/stickers_tabs.dart",
"repo_id": "photobooth",
"token_count": 2834
} | 1,150 |
// ignore_for_file: must_be_immutable
import 'package:authentication_repository/authentication_repository.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class MockFirebaseAuth extends Mock implements firebase_auth.FirebaseAuth {}
class MockUserCredential extends Mock implements firebase_auth.UserCredential {}
class FakeAuthCredential extends Fake implements firebase_auth.AuthCredential {}
void main() {
group('AuthenticationRepository', () {
late firebase_auth.FirebaseAuth firebaseAuth;
late AuthenticationRepository authenticationRepository;
setUpAll(() {
registerFallbackValue(FakeAuthCredential());
});
setUp(() {
firebaseAuth = MockFirebaseAuth();
authenticationRepository = AuthenticationRepository(
firebaseAuth: firebaseAuth,
);
});
group('signInAnonymously', () {
setUp(() {
when(
() => firebaseAuth.signInAnonymously(),
).thenAnswer((_) => Future.value(MockUserCredential()));
});
test('calls signInAnonymously', () async {
await authenticationRepository.signInAnonymously();
verify(
() => firebaseAuth.signInAnonymously(),
).called(1);
});
test('succeeds when signInAnonymously succeeds', () async {
expect(
authenticationRepository.signInAnonymously(),
completes,
);
});
test(
'throws SignInAnonymouslyException '
'when signInAnonymously throws', () async {
when(
() => firebaseAuth.signInAnonymously(),
).thenThrow(Exception());
expect(
authenticationRepository.signInAnonymously(),
throwsA(isA<SignInAnonymouslyException>()),
);
});
});
});
}
| photobooth/packages/authentication_repository/test/authentication_repository_test.dart/0 | {
"file_path": "photobooth/packages/authentication_repository/test/authentication_repository_test.dart",
"repo_id": "photobooth",
"token_count": 738
} | 1,151 |
name: camera
description: A Flutter plugin for integrating Camera Access.
version: 0.1.0
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
flutter: ">=2.0.0"
flutter:
plugin:
platforms:
web:
default_package: camera_web
dependencies:
camera_platform_interface:
path: ../camera_platform_interface
camera_web:
path: ../camera_web
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
meta: ^1.8.0
mocktail: ^0.3.0
plugin_platform_interface: ^2.1.3
very_good_analysis: ^4.0.0+1
| photobooth/packages/camera/camera/pubspec.yaml/0 | {
"file_path": "photobooth/packages/camera/camera/pubspec.yaml",
"repo_id": "photobooth",
"token_count": 238
} | 1,152 |
name: camera_web
description: Web platform implementation of camera
version: 0.1.0
publish_to: none
environment:
sdk: ">=2.19.0 <3.0.0"
flutter: ">=2.0.0"
flutter:
plugin:
platforms:
web:
pluginClass: CameraPlugin
fileName: camera_web.dart
dependencies:
camera_platform_interface:
path: ../camera_platform_interface
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
meta: ^1.8.0
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
test: ^1.21.7
very_good_analysis: ^4.0.0+1
| photobooth/packages/camera/camera_web/pubspec.yaml/0 | {
"file_path": "photobooth/packages/camera/camera_web/pubspec.yaml",
"repo_id": "photobooth",
"token_count": 248
} | 1,153 |
import 'package:flutter/material.dart';
/// {@template app_page_route}
/// Default [MaterialPageRoute] for the `photobooth_ui` toolkit.
/// This page route disables all transition animations.
/// {@endtemplate}
class AppPageRoute<T> extends MaterialPageRoute<T> {
/// {@macro app_page_route}
AppPageRoute({
required super.builder,
super.settings,
super.maintainState,
super.fullscreenDialog,
});
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return child;
}
}
| photobooth/packages/photobooth_ui/lib/src/navigation/app_page_route.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/navigation/app_page_route.dart",
"repo_id": "photobooth",
"token_count": 204
} | 1,154 |
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
/// {@template tooltip_mode}
/// The tooltip mode which determines when the tooltip is visible
/// {@endtemplate}
enum TooltipMode {
/// Default tooltip behavior
normal,
/// Tooltip is always visible until the user interacts with the button.
visibleUntilInteraction
}
/// {@template app_tooltip_button}
/// An [AppTooltip] button which handles showing a tooltip based on the
/// [TooltipMode].
/// {@endtemplate}
class AppTooltipButton extends StatefulWidget {
/// {@macro app_tooltip_button}
const AppTooltipButton({
required this.onPressed,
required this.message,
required this.child,
this.mode = TooltipMode.normal,
this.verticalOffset,
super.key,
});
/// [VoidCallback] which is invoked when the user taps the [child].
final VoidCallback onPressed;
/// Message to be shown in the tooltip.
final String message;
/// {@macro tooltip_mode}
final TooltipMode mode;
/// The tooltip's vertical offset.
final double? verticalOffset;
/// The widget which will be rendered.
final Widget child;
@override
State<AppTooltipButton> createState() => _AppTooltipButtonState();
}
class _AppTooltipButtonState extends State<AppTooltipButton> {
var _hasBeenTapped = false;
bool get _isTooltipVisible =>
widget.mode == TooltipMode.visibleUntilInteraction && !_hasBeenTapped;
@override
Widget build(BuildContext context) {
final child = InkWell(
onTap: () {
setState(() => _hasBeenTapped = true);
widget.onPressed();
},
child: widget.child,
);
return Material(
color: PhotoboothColors.transparent,
shape: const CircleBorder(),
clipBehavior: Clip.hardEdge,
child: AppTooltip.custom(
visible: _isTooltipVisible,
message: widget.message,
verticalOffset: widget.verticalOffset,
child: child,
),
);
}
}
| photobooth/packages/photobooth_ui/lib/src/widgets/app_tooltip_button.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/app_tooltip_button.dart",
"repo_id": "photobooth",
"token_count": 675
} | 1,155 |
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
void main() {
group('isMobile', () {
test('returns true', () {
expect(isMobile, equals(true));
});
});
}
| photobooth/packages/photobooth_ui/test/src/platform/is_mobile_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/platform/is_mobile_test.dart",
"repo_id": "photobooth",
"token_count": 90
} | 1,156 |
@TestOn('!chrome')
library;
import 'package:flutter_test/flutter_test.dart';
import 'package:platform_helper/platform_helper.dart';
void main() {
group('MobilePlatformHelper', () {
test('returns true', () {
final helper = PlatformHelper();
expect(helper.isMobile, true);
});
});
}
| photobooth/packages/platform_helper/test/src/mobile_platform_helper_test.dart/0 | {
"file_path": "photobooth/packages/platform_helper/test/src/mobile_platform_helper_test.dart",
"repo_id": "photobooth",
"token_count": 114
} | 1,157 |
import 'package:camera/camera.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:test/test.dart';
class MockCameraImage extends Mock implements CameraImage {}
class MockAsset extends Mock implements Asset {}
class MockPhotoAsset extends Mock implements PhotoAsset {}
class MockDragUpdate extends Mock implements DragUpdate {}
void main() {
group('PhotoboothEvent', () {
group('PhotoCaptured', () {
test('support value equality', () {
const aspectRatio = PhotoboothAspectRatio.portrait;
final image = MockCameraImage();
final instanceA = PhotoCaptured(aspectRatio: aspectRatio, image: image);
final instanceB = PhotoCaptured(aspectRatio: aspectRatio, image: image);
expect(instanceA, equals(instanceB));
});
});
group('PhotoCharacterToggled', () {
test('support value equality', () {
final character = MockAsset();
final instanceA = PhotoCharacterToggled(character: character);
final instanceB = PhotoCharacterToggled(character: character);
expect(instanceA, equals(instanceB));
});
});
group('PhotoCharacterDragged', () {
test('support value equality', () {
final character = MockPhotoAsset();
final update = MockDragUpdate();
final instanceA = PhotoCharacterDragged(
character: character,
update: update,
);
final instanceB = PhotoCharacterDragged(
character: character,
update: update,
);
expect(instanceA, equals(instanceB));
});
});
group('PhotoStickerTapped', () {
test('support value equality', () {
final sticker = MockAsset();
final instanceA = PhotoStickerTapped(sticker: sticker);
final instanceB = PhotoStickerTapped(sticker: sticker);
expect(instanceA, equals(instanceB));
});
});
group('PhotoStickerDragged', () {
test('support value equality', () {
final sticker = MockPhotoAsset();
final update = MockDragUpdate();
final instanceA = PhotoStickerDragged(
sticker: sticker,
update: update,
);
final instanceB = PhotoStickerDragged(
sticker: sticker,
update: update,
);
expect(instanceA, equals(instanceB));
});
});
});
}
| photobooth/test/photobooth/bloc/photobooth_event_test.dart/0 | {
"file_path": "photobooth/test/photobooth/bloc/photobooth_event_test.dart",
"repo_id": "photobooth",
"token_count": 930
} | 1,158 |
// ignore_for_file: prefer_const_constructors
import 'dart:ui';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import '../../helpers/helpers.dart';
class FakePhotoboothEvent extends Fake implements PhotoboothEvent {}
class FakePhotoboothState extends Fake implements PhotoboothState {}
void main() {
const width = 1;
const height = 1;
const data = '';
const image = CameraImage(width: width, height: height, data: data);
late PhotoboothBloc photoboothBloc;
setUpAll(() {
registerFallbackValue(FakePhotoboothEvent());
registerFallbackValue(FakePhotoboothState());
});
setUp(() {
photoboothBloc = MockPhotoboothBloc();
when(() => photoboothBloc.state).thenReturn(PhotoboothState(image: image));
});
group('AnimatedPhotoboothPhoto', () {
group('portrait', () {
testWidgets(
'displays AnimatedPhotoboothPhotoPortrait '
'when aspect ratio is portrait '
'and screen size is small', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
aspectRatio: PhotoboothAspectRatio.portrait,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
expect(
find.byType(AnimatedPhotoboothPhotoPortrait),
findsOneWidget,
);
});
testWidgets(
'displays AnimatedPhotoboothPhotoPortrait '
'when aspect ratio is portrait '
'and screen size is large', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
aspectRatio: PhotoboothAspectRatio.portrait,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
expect(
find.byType(AnimatedPhotoboothPhotoPortrait),
findsOneWidget,
);
});
testWidgets(
'displays AnimatedPhotoboothPhotoPortrait '
'when aspect ratio is portrait '
'and screen size is xLarge', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
aspectRatio: PhotoboothAspectRatio.portrait,
),
);
tester.setDisplaySize(
const Size(
PhotoboothBreakpoints.large + 100,
800,
),
);
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
expect(
find.byType(AnimatedPhotoboothPhotoPortrait),
findsOneWidget,
);
});
testWidgets(
'displays AnimatedPhotoboothPhotoPortrait '
'when aspect ratio is portrait '
'with isPhotoVisible false', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
aspectRatio: PhotoboothAspectRatio.portrait,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
final widget = tester.widget<AnimatedPhotoboothPhotoPortrait>(
find.byType(AnimatedPhotoboothPhotoPortrait),
);
expect(widget.isPhotoVisible, false);
});
testWidgets(
'displays AnimatedPhotoboothPhotoPortrait '
'when aspect ratio is portrait '
'with isPhotoVisible true '
'after 2 seconds', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
aspectRatio: PhotoboothAspectRatio.portrait,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
await tester.pump(Duration(seconds: 2));
final widget = tester.widget<AnimatedPhotoboothPhotoPortrait>(
find.byType(AnimatedPhotoboothPhotoPortrait),
);
expect(widget.isPhotoVisible, true);
});
});
group('landscape', () {
testWidgets(
'displays AnimatedPhotoboothPhotoLandscape '
'when aspect ratio is landscape '
'and screen size is small', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
expect(
find.byType(AnimatedPhotoboothPhotoLandscape),
findsOneWidget,
);
});
testWidgets(
'displays AnimatedPhotoboothPhotoLandscape '
'when aspect ratio is landscape '
'and screen size is medium', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.medium, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
expect(
find.byType(AnimatedPhotoboothPhotoLandscape),
findsOneWidget,
);
});
testWidgets(
'displays AnimatedPhotoboothPhotoLandscape '
'when aspect ratio is landscape '
'and screen size is large', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
expect(
find.byType(AnimatedPhotoboothPhotoLandscape),
findsOneWidget,
);
});
testWidgets(
'displays AnimatedPhotoboothPhotoLandscape '
'when aspect ratio is landscape '
'and screen size is xLarge', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
),
);
tester.setDisplaySize(
const Size(
PhotoboothBreakpoints.large + 100,
800,
),
);
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
expect(
find.byType(AnimatedPhotoboothPhotoLandscape),
findsOneWidget,
);
});
testWidgets(
'displays AnimatedPhotoboothPhotoLandscape '
'when aspect ratio is landscape '
'with isPhotoVisible false', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
final widget = tester.widget<AnimatedPhotoboothPhotoLandscape>(
find.byType(AnimatedPhotoboothPhotoLandscape),
);
expect(widget.isPhotoVisible, false);
});
testWidgets(
'displays AnimatedPhotoboothPhotoLandscape '
'when aspect ratio is landscape '
'with isPhotoVisible true '
'after 2 seconds', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
image: image,
),
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 800));
await tester.pumpApp(
AnimatedPhotoboothPhoto(image: image),
photoboothBloc: photoboothBloc,
);
await tester.pump(Duration(seconds: 2));
final widget = tester.widget<AnimatedPhotoboothPhotoLandscape>(
find.byType(AnimatedPhotoboothPhotoLandscape),
);
expect(widget.isPhotoVisible, true);
});
});
});
}
| photobooth/test/share/widgets/animated_share_photo_test.dart/0 | {
"file_path": "photobooth/test/share/widgets/animated_share_photo_test.dart",
"repo_id": "photobooth",
"token_count": 4156
} | 1,159 |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball_audio/pinball_audio.dart';
part 'assets_manager_state.dart';
class AssetsManagerCubit extends Cubit<AssetsManagerState> {
AssetsManagerCubit(this._game, this._audioPlayer)
: super(const AssetsManagerState.initial());
final PinballGame _game;
final PinballAudioPlayer _audioPlayer;
Future<void> load() async {
/// Assigning loadables is a very expensive operation. With this purposeful
/// delay here, which is a bit random in duration but enough to let the UI
/// do its job without adding too much delay for the user, we are letting
/// the UI paint first, and then we start loading the assets.
await Future<void>.delayed(const Duration(seconds: 1));
final loadables = <Future<void> Function()>[
_game.preFetchLeaderboard,
..._game.preLoadAssets(),
..._audioPlayer.load(),
...BonusAnimation.loadAssets(),
...SelectedCharacter.loadAssets(),
];
emit(
state.copyWith(
assetsCount: loadables.length,
),
);
late void Function() _triggerLoad;
_triggerLoad = () async {
if (loadables.isEmpty) return;
final loadable = loadables.removeAt(0);
await loadable();
_triggerLoad();
emit(state.copyWith(loaded: state.loaded + 1));
};
const _throttleSize = 3;
for (var i = 0; i < _throttleSize; i++) {
_triggerLoad();
}
}
}
| pinball/lib/assets_manager/cubit/assets_manager_cubit.dart/0 | {
"file_path": "pinball/lib/assets_manager/cubit/assets_manager_cubit.dart",
"repo_id": "pinball",
"token_count": 561
} | 1,160 |
// ignore_for_file: avoid_renaming_method_parameters
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template scoring_behavior}
/// Adds [_points] to the score and shows a text effect.
///
/// The behavior removes itself after the duration.
/// {@endtemplate}
class ScoringBehavior extends Component
with HasGameRef, FlameBlocReader<GameBloc, GameState> {
/// {@macro scoring_behavior}
ScoringBehavior({
required Points points,
required Vector2 position,
double duration = 1,
}) : _points = points,
_position = position,
_effectController = EffectController(
duration: duration,
);
final Points _points;
final Vector2 _position;
final EffectController _effectController;
@override
void update(double dt) {
super.update(dt);
if (_effectController.completed) {
removeFromParent();
}
}
@override
Future<void> onLoad() async {
await super.onLoad();
bloc.add(Scored(points: _points.value));
final canvas = gameRef.descendants().whereType<ZCanvasComponent>().single;
await canvas.add(
ScoreComponent(
points: _points,
position: _position,
effectController: _effectController,
),
);
}
}
/// {@template scoring_contact_behavior}
/// Adds points to the score when the [Ball] contacts the [parent].
/// {@endtemplate}
class ScoringContactBehavior extends ContactBehavior {
/// {@macro scoring_contact_behavior}
ScoringContactBehavior({
required Points points,
}) : _points = points;
final Points _points;
@override
void beginContact(Object other, Contact contact) {
super.beginContact(other, contact);
if (other is! Ball) return;
parent.add(
ScoringBehavior(
points: _points,
position: other.body.position,
),
);
}
}
| pinball/lib/game/behaviors/scoring_behavior.dart/0 | {
"file_path": "pinball/lib/game/behaviors/scoring_behavior.dart",
"repo_id": "pinball",
"token_count": 740
} | 1,161 |
export 'game_over_info_display.dart';
export 'initials_input_display.dart';
export 'initials_submission_failure_display.dart';
export 'initials_submission_success_display.dart';
export 'leaderboard_display.dart';
export 'leaderboard_failure_display.dart';
export 'loading_display.dart';
export 'share_display.dart';
| pinball/lib/game/components/backbox/displays/displays.dart/0 | {
"file_path": "pinball/lib/game/components/backbox/displays/displays.dart",
"repo_id": "pinball",
"token_count": 105
} | 1,162 |
import 'package:flame/extensions.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/foundation.dart';
import 'package:pinball/game/components/drain/behaviors/behaviors.dart';
import 'package:pinball_components/pinball_components.dart';
/// {@template drain}
/// Area located at the bottom of the board.
///
/// Its [DrainingBehavior] handles removing a [Ball] from the game.
/// {@endtemplate}
class Drain extends BodyComponent with ContactCallbacks {
/// {@macro drain}
Drain()
: super(
renderBody: false,
children: [DrainingBehavior()],
);
/// Creates a [Drain] without any children.
///
/// This can be used for testing a [Drain]'s behaviors in isolation.
@visibleForTesting
Drain.test();
@override
Body createBody() {
final shape = EdgeShape()
..set(
BoardDimensions.bounds.bottomLeft.toVector2(),
BoardDimensions.bounds.bottomRight.toVector2(),
);
final fixtureDef = FixtureDef(shape, isSensor: true);
return world.createBody(BodyDef())..createFixture(fixtureDef);
}
}
| pinball/lib/game/components/drain/drain.dart/0 | {
"file_path": "pinball/lib/game/components/drain/drain.dart",
"repo_id": "pinball",
"token_count": 392
} | 1,163 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Adds a [GameBonus.sparkyTurboCharge] when a [Ball] enters the
/// [SparkyComputer].
class SparkyComputerBonusBehavior extends Component
with ParentIsA<SparkyScorch>, FlameBlocReader<GameBloc, GameState> {
@override
void onMount() {
super.onMount();
final sparkyComputer = parent.firstChild<SparkyComputer>()!;
sparkyComputer.bloc.stream.listen((state) async {
final listenWhen = state == SparkyComputerState.withBall;
if (!listenWhen) return;
bloc.add(const BonusActivated(GameBonus.sparkyTurboCharge));
});
}
}
| pinball/lib/game/components/sparky_scorch/behaviors/sparky_computer_bonus_behavior.dart/0 | {
"file_path": "pinball/lib/game/components/sparky_scorch/behaviors/sparky_computer_bonus_behavior.dart",
"repo_id": "pinball",
"token_count": 286
} | 1,164 |
/// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
/// FlutterGen
/// *****************************************************
// ignore_for_file: directives_ordering,unnecessary_import
import 'package:flutter/widgets.dart';
class $AssetsImagesGen {
const $AssetsImagesGen();
$AssetsImagesBonusAnimationGen get bonusAnimation =>
const $AssetsImagesBonusAnimationGen();
$AssetsImagesComponentsGen get components =>
const $AssetsImagesComponentsGen();
$AssetsImagesLoadingGameGen get loadingGame =>
const $AssetsImagesLoadingGameGen();
$AssetsImagesScoreGen get score => const $AssetsImagesScoreGen();
}
class $AssetsImagesBonusAnimationGen {
const $AssetsImagesBonusAnimationGen();
/// File path: assets/images/bonus_animation/android_spaceship.png
AssetGenImage get androidSpaceship => const AssetGenImage(
'assets/images/bonus_animation/android_spaceship.png');
/// File path: assets/images/bonus_animation/dash_nest.png
AssetGenImage get dashNest =>
const AssetGenImage('assets/images/bonus_animation/dash_nest.png');
/// File path: assets/images/bonus_animation/dino_chomp.png
AssetGenImage get dinoChomp =>
const AssetGenImage('assets/images/bonus_animation/dino_chomp.png');
/// File path: assets/images/bonus_animation/google_word.png
AssetGenImage get googleWord =>
const AssetGenImage('assets/images/bonus_animation/google_word.png');
/// File path: assets/images/bonus_animation/sparky_turbo_charge.png
AssetGenImage get sparkyTurboCharge => const AssetGenImage(
'assets/images/bonus_animation/sparky_turbo_charge.png');
}
class $AssetsImagesComponentsGen {
const $AssetsImagesComponentsGen();
/// File path: assets/images/components/key.png
AssetGenImage get key =>
const AssetGenImage('assets/images/components/key.png');
/// File path: assets/images/components/space.png
AssetGenImage get space =>
const AssetGenImage('assets/images/components/space.png');
}
class $AssetsImagesLoadingGameGen {
const $AssetsImagesLoadingGameGen();
/// File path: assets/images/loading_game/io_pinball.png
AssetGenImage get ioPinball =>
const AssetGenImage('assets/images/loading_game/io_pinball.png');
}
class $AssetsImagesScoreGen {
const $AssetsImagesScoreGen();
/// File path: assets/images/score/mini_score_background.png
AssetGenImage get miniScoreBackground =>
const AssetGenImage('assets/images/score/mini_score_background.png');
}
class Assets {
Assets._();
static const $AssetsImagesGen images = $AssetsImagesGen();
}
class AssetGenImage extends AssetImage {
const AssetGenImage(String assetName) : super(assetName);
Image image({
Key? key,
ImageFrameBuilder? frameBuilder,
ImageLoadingBuilder? loadingBuilder,
ImageErrorWidgetBuilder? errorBuilder,
String? semanticLabel,
bool excludeFromSemantics = false,
double? width,
double? height,
Color? color,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
bool gaplessPlayback = false,
bool isAntiAlias = false,
FilterQuality filterQuality = FilterQuality.low,
}) {
return Image(
key: key,
image: this,
frameBuilder: frameBuilder,
loadingBuilder: loadingBuilder,
errorBuilder: errorBuilder,
semanticLabel: semanticLabel,
excludeFromSemantics: excludeFromSemantics,
width: width,
height: height,
color: color,
colorBlendMode: colorBlendMode,
fit: fit,
alignment: alignment,
repeat: repeat,
centerSlice: centerSlice,
matchTextDirection: matchTextDirection,
gaplessPlayback: gaplessPlayback,
isAntiAlias: isAntiAlias,
filterQuality: filterQuality,
);
}
String get path => assetName;
}
| pinball/lib/gen/assets.gen.dart/0 | {
"file_path": "pinball/lib/gen/assets.gen.dart",
"repo_id": "pinball",
"token_count": 1316
} | 1,165 |
export 'character_selection_page.dart';
export 'selected_character.dart';
| pinball/lib/select_character/view/view.dart/0 | {
"file_path": "pinball/lib/select_character/view/view.dart",
"repo_id": "pinball",
"token_count": 22
} | 1,166 |
library geometry;
export 'src/geometry.dart';
| pinball/packages/geometry/lib/geometry.dart/0 | {
"file_path": "pinball/packages/geometry/lib/geometry.dart",
"repo_id": "pinball",
"token_count": 16
} | 1,167 |
/// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
/// FlutterGen
/// *****************************************************
// ignore_for_file: directives_ordering,unnecessary_import
import 'package:flutter/widgets.dart';
class $AssetsImagesGen {
const $AssetsImagesGen();
$AssetsImagesAndroidGen get android => const $AssetsImagesAndroidGen();
$AssetsImagesBackboxGen get backbox => const $AssetsImagesBackboxGen();
$AssetsImagesBallGen get ball => const $AssetsImagesBallGen();
$AssetsImagesBaseboardGen get baseboard => const $AssetsImagesBaseboardGen();
/// File path: assets/images/board_background.png
AssetGenImage get boardBackground =>
const AssetGenImage('assets/images/board_background.png');
$AssetsImagesBoundaryGen get boundary => const $AssetsImagesBoundaryGen();
$AssetsImagesDashGen get dash => const $AssetsImagesDashGen();
$AssetsImagesDinoGen get dino => const $AssetsImagesDinoGen();
$AssetsImagesDisplayArrowsGen get displayArrows =>
const $AssetsImagesDisplayArrowsGen();
/// File path: assets/images/error_background.png
AssetGenImage get errorBackground =>
const AssetGenImage('assets/images/error_background.png');
$AssetsImagesFlapperGen get flapper => const $AssetsImagesFlapperGen();
$AssetsImagesFlipperGen get flipper => const $AssetsImagesFlipperGen();
$AssetsImagesGoogleRolloverGen get googleRollover =>
const $AssetsImagesGoogleRolloverGen();
$AssetsImagesGoogleWordGen get googleWord =>
const $AssetsImagesGoogleWordGen();
$AssetsImagesKickerGen get kicker => const $AssetsImagesKickerGen();
$AssetsImagesLaunchRampGen get launchRamp =>
const $AssetsImagesLaunchRampGen();
$AssetsImagesMultiballGen get multiball => const $AssetsImagesMultiballGen();
$AssetsImagesMultiplierGen get multiplier =>
const $AssetsImagesMultiplierGen();
$AssetsImagesPlungerGen get plunger => const $AssetsImagesPlungerGen();
$AssetsImagesScoreGen get score => const $AssetsImagesScoreGen();
$AssetsImagesSignpostGen get signpost => const $AssetsImagesSignpostGen();
$AssetsImagesSkillShotGen get skillShot => const $AssetsImagesSkillShotGen();
$AssetsImagesSlingshotGen get slingshot => const $AssetsImagesSlingshotGen();
$AssetsImagesSparkyGen get sparky => const $AssetsImagesSparkyGen();
}
class $AssetsImagesAndroidGen {
const $AssetsImagesAndroidGen();
$AssetsImagesAndroidBumperGen get bumper =>
const $AssetsImagesAndroidBumperGen();
$AssetsImagesAndroidRailGen get rail => const $AssetsImagesAndroidRailGen();
$AssetsImagesAndroidRampGen get ramp => const $AssetsImagesAndroidRampGen();
$AssetsImagesAndroidSpaceshipGen get spaceship =>
const $AssetsImagesAndroidSpaceshipGen();
}
class $AssetsImagesBackboxGen {
const $AssetsImagesBackboxGen();
$AssetsImagesBackboxButtonGen get button =>
const $AssetsImagesBackboxButtonGen();
/// File path: assets/images/backbox/display_divider.png
AssetGenImage get displayDivider =>
const AssetGenImage('assets/images/backbox/display_divider.png');
/// File path: assets/images/backbox/display_title_decoration.png
AssetGenImage get displayTitleDecoration =>
const AssetGenImage('assets/images/backbox/display_title_decoration.png');
/// File path: assets/images/backbox/marquee.png
AssetGenImage get marquee =>
const AssetGenImage('assets/images/backbox/marquee.png');
}
class $AssetsImagesBallGen {
const $AssetsImagesBallGen();
/// File path: assets/images/ball/flame_effect.png
AssetGenImage get flameEffect =>
const AssetGenImage('assets/images/ball/flame_effect.png');
}
class $AssetsImagesBaseboardGen {
const $AssetsImagesBaseboardGen();
/// File path: assets/images/baseboard/left.png
AssetGenImage get left =>
const AssetGenImage('assets/images/baseboard/left.png');
/// File path: assets/images/baseboard/right.png
AssetGenImage get right =>
const AssetGenImage('assets/images/baseboard/right.png');
}
class $AssetsImagesBoundaryGen {
const $AssetsImagesBoundaryGen();
/// File path: assets/images/boundary/bottom.png
AssetGenImage get bottom =>
const AssetGenImage('assets/images/boundary/bottom.png');
/// File path: assets/images/boundary/outer.png
AssetGenImage get outer =>
const AssetGenImage('assets/images/boundary/outer.png');
/// File path: assets/images/boundary/outer_bottom.png
AssetGenImage get outerBottom =>
const AssetGenImage('assets/images/boundary/outer_bottom.png');
}
class $AssetsImagesDashGen {
const $AssetsImagesDashGen();
/// File path: assets/images/dash/animatronic.png
AssetGenImage get animatronic =>
const AssetGenImage('assets/images/dash/animatronic.png');
$AssetsImagesDashBumperGen get bumper => const $AssetsImagesDashBumperGen();
}
class $AssetsImagesDinoGen {
const $AssetsImagesDinoGen();
$AssetsImagesDinoAnimatronicGen get animatronic =>
const $AssetsImagesDinoAnimatronicGen();
/// File path: assets/images/dino/bottom_wall.png
AssetGenImage get bottomWall =>
const AssetGenImage('assets/images/dino/bottom_wall.png');
/// File path: assets/images/dino/top_wall.png
AssetGenImage get topWall =>
const AssetGenImage('assets/images/dino/top_wall.png');
/// File path: assets/images/dino/top_wall_tunnel.png
AssetGenImage get topWallTunnel =>
const AssetGenImage('assets/images/dino/top_wall_tunnel.png');
}
class $AssetsImagesDisplayArrowsGen {
const $AssetsImagesDisplayArrowsGen();
AssetGenImage get arrowLeft =>
const AssetGenImage('assets/images/display_arrows/arrow_left.png');
AssetGenImage get arrowRight =>
const AssetGenImage('assets/images/display_arrows/arrow_right.png');
}
class $AssetsImagesFlapperGen {
const $AssetsImagesFlapperGen();
/// File path: assets/images/flapper/back_support.png
AssetGenImage get backSupport =>
const AssetGenImage('assets/images/flapper/back_support.png');
/// File path: assets/images/flapper/flap.png
AssetGenImage get flap =>
const AssetGenImage('assets/images/flapper/flap.png');
/// File path: assets/images/flapper/front_support.png
AssetGenImage get frontSupport =>
const AssetGenImage('assets/images/flapper/front_support.png');
}
class $AssetsImagesFlipperGen {
const $AssetsImagesFlipperGen();
/// File path: assets/images/flipper/left.png
AssetGenImage get left =>
const AssetGenImage('assets/images/flipper/left.png');
/// File path: assets/images/flipper/right.png
AssetGenImage get right =>
const AssetGenImage('assets/images/flipper/right.png');
}
class $AssetsImagesGoogleRolloverGen {
const $AssetsImagesGoogleRolloverGen();
$AssetsImagesGoogleRolloverLeftGen get left =>
const $AssetsImagesGoogleRolloverLeftGen();
$AssetsImagesGoogleRolloverRightGen get right =>
const $AssetsImagesGoogleRolloverRightGen();
}
class $AssetsImagesGoogleWordGen {
const $AssetsImagesGoogleWordGen();
$AssetsImagesGoogleWordLetter1Gen get letter1 =>
const $AssetsImagesGoogleWordLetter1Gen();
$AssetsImagesGoogleWordLetter2Gen get letter2 =>
const $AssetsImagesGoogleWordLetter2Gen();
$AssetsImagesGoogleWordLetter3Gen get letter3 =>
const $AssetsImagesGoogleWordLetter3Gen();
$AssetsImagesGoogleWordLetter4Gen get letter4 =>
const $AssetsImagesGoogleWordLetter4Gen();
$AssetsImagesGoogleWordLetter5Gen get letter5 =>
const $AssetsImagesGoogleWordLetter5Gen();
$AssetsImagesGoogleWordLetter6Gen get letter6 =>
const $AssetsImagesGoogleWordLetter6Gen();
}
class $AssetsImagesKickerGen {
const $AssetsImagesKickerGen();
$AssetsImagesKickerLeftGen get left => const $AssetsImagesKickerLeftGen();
$AssetsImagesKickerRightGen get right => const $AssetsImagesKickerRightGen();
}
class $AssetsImagesLaunchRampGen {
const $AssetsImagesLaunchRampGen();
/// File path: assets/images/launch_ramp/background_railing.png
AssetGenImage get backgroundRailing =>
const AssetGenImage('assets/images/launch_ramp/background_railing.png');
/// File path: assets/images/launch_ramp/foreground_railing.png
AssetGenImage get foregroundRailing =>
const AssetGenImage('assets/images/launch_ramp/foreground_railing.png');
/// File path: assets/images/launch_ramp/ramp.png
AssetGenImage get ramp =>
const AssetGenImage('assets/images/launch_ramp/ramp.png');
}
class $AssetsImagesMultiballGen {
const $AssetsImagesMultiballGen();
/// File path: assets/images/multiball/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/multiball/dimmed.png');
/// File path: assets/images/multiball/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/multiball/lit.png');
}
class $AssetsImagesMultiplierGen {
const $AssetsImagesMultiplierGen();
$AssetsImagesMultiplierX2Gen get x2 => const $AssetsImagesMultiplierX2Gen();
$AssetsImagesMultiplierX3Gen get x3 => const $AssetsImagesMultiplierX3Gen();
$AssetsImagesMultiplierX4Gen get x4 => const $AssetsImagesMultiplierX4Gen();
$AssetsImagesMultiplierX5Gen get x5 => const $AssetsImagesMultiplierX5Gen();
$AssetsImagesMultiplierX6Gen get x6 => const $AssetsImagesMultiplierX6Gen();
}
class $AssetsImagesPlungerGen {
const $AssetsImagesPlungerGen();
/// File path: assets/images/plunger/plunger.png
AssetGenImage get plunger =>
const AssetGenImage('assets/images/plunger/plunger.png');
/// File path: assets/images/plunger/rocket.png
AssetGenImage get rocket =>
const AssetGenImage('assets/images/plunger/rocket.png');
}
class $AssetsImagesScoreGen {
const $AssetsImagesScoreGen();
/// File path: assets/images/score/five_thousand.png
AssetGenImage get fiveThousand =>
const AssetGenImage('assets/images/score/five_thousand.png');
/// File path: assets/images/score/one_million.png
AssetGenImage get oneMillion =>
const AssetGenImage('assets/images/score/one_million.png');
/// File path: assets/images/score/twenty_thousand.png
AssetGenImage get twentyThousand =>
const AssetGenImage('assets/images/score/twenty_thousand.png');
/// File path: assets/images/score/two_hundred_thousand.png
AssetGenImage get twoHundredThousand =>
const AssetGenImage('assets/images/score/two_hundred_thousand.png');
}
class $AssetsImagesSignpostGen {
const $AssetsImagesSignpostGen();
/// File path: assets/images/signpost/active1.png
AssetGenImage get active1 =>
const AssetGenImage('assets/images/signpost/active1.png');
/// File path: assets/images/signpost/active2.png
AssetGenImage get active2 =>
const AssetGenImage('assets/images/signpost/active2.png');
/// File path: assets/images/signpost/active3.png
AssetGenImage get active3 =>
const AssetGenImage('assets/images/signpost/active3.png');
/// File path: assets/images/signpost/inactive.png
AssetGenImage get inactive =>
const AssetGenImage('assets/images/signpost/inactive.png');
}
class $AssetsImagesSkillShotGen {
const $AssetsImagesSkillShotGen();
/// File path: assets/images/skill_shot/decal.png
AssetGenImage get decal =>
const AssetGenImage('assets/images/skill_shot/decal.png');
/// File path: assets/images/skill_shot/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/skill_shot/dimmed.png');
/// File path: assets/images/skill_shot/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/skill_shot/lit.png');
/// File path: assets/images/skill_shot/pin.png
AssetGenImage get pin =>
const AssetGenImage('assets/images/skill_shot/pin.png');
}
class $AssetsImagesSlingshotGen {
const $AssetsImagesSlingshotGen();
/// File path: assets/images/slingshot/lower.png
AssetGenImage get lower =>
const AssetGenImage('assets/images/slingshot/lower.png');
/// File path: assets/images/slingshot/upper.png
AssetGenImage get upper =>
const AssetGenImage('assets/images/slingshot/upper.png');
}
class $AssetsImagesSparkyGen {
const $AssetsImagesSparkyGen();
/// File path: assets/images/sparky/animatronic.png
AssetGenImage get animatronic =>
const AssetGenImage('assets/images/sparky/animatronic.png');
$AssetsImagesSparkyBumperGen get bumper =>
const $AssetsImagesSparkyBumperGen();
$AssetsImagesSparkyComputerGen get computer =>
const $AssetsImagesSparkyComputerGen();
}
class $AssetsImagesAndroidBumperGen {
const $AssetsImagesAndroidBumperGen();
$AssetsImagesAndroidBumperAGen get a =>
const $AssetsImagesAndroidBumperAGen();
$AssetsImagesAndroidBumperBGen get b =>
const $AssetsImagesAndroidBumperBGen();
$AssetsImagesAndroidBumperCowGen get cow =>
const $AssetsImagesAndroidBumperCowGen();
}
class $AssetsImagesAndroidRailGen {
const $AssetsImagesAndroidRailGen();
/// File path: assets/images/android/rail/exit.png
AssetGenImage get exit =>
const AssetGenImage('assets/images/android/rail/exit.png');
/// File path: assets/images/android/rail/main.png
AssetGenImage get main =>
const AssetGenImage('assets/images/android/rail/main.png');
}
class $AssetsImagesAndroidRampGen {
const $AssetsImagesAndroidRampGen();
$AssetsImagesAndroidRampArrowGen get arrow =>
const $AssetsImagesAndroidRampArrowGen();
/// File path: assets/images/android/ramp/board_opening.png
AssetGenImage get boardOpening =>
const AssetGenImage('assets/images/android/ramp/board_opening.png');
/// File path: assets/images/android/ramp/main.png
AssetGenImage get main =>
const AssetGenImage('assets/images/android/ramp/main.png');
/// File path: assets/images/android/ramp/railing_background.png
AssetGenImage get railingBackground =>
const AssetGenImage('assets/images/android/ramp/railing_background.png');
/// File path: assets/images/android/ramp/railing_foreground.png
AssetGenImage get railingForeground =>
const AssetGenImage('assets/images/android/ramp/railing_foreground.png');
}
class $AssetsImagesAndroidSpaceshipGen {
const $AssetsImagesAndroidSpaceshipGen();
/// File path: assets/images/android/spaceship/animatronic.png
AssetGenImage get animatronic =>
const AssetGenImage('assets/images/android/spaceship/animatronic.png');
/// File path: assets/images/android/spaceship/light_beam.png
AssetGenImage get lightBeam =>
const AssetGenImage('assets/images/android/spaceship/light_beam.png');
/// File path: assets/images/android/spaceship/saucer.png
AssetGenImage get saucer =>
const AssetGenImage('assets/images/android/spaceship/saucer.png');
}
class $AssetsImagesBackboxButtonGen {
const $AssetsImagesBackboxButtonGen();
/// File path: assets/images/backbox/button/facebook.png
AssetGenImage get facebook =>
const AssetGenImage('assets/images/backbox/button/facebook.png');
/// File path: assets/images/backbox/button/twitter.png
AssetGenImage get twitter =>
const AssetGenImage('assets/images/backbox/button/twitter.png');
}
class $AssetsImagesDashBumperGen {
const $AssetsImagesDashBumperGen();
$AssetsImagesDashBumperAGen get a => const $AssetsImagesDashBumperAGen();
$AssetsImagesDashBumperBGen get b => const $AssetsImagesDashBumperBGen();
$AssetsImagesDashBumperMainGen get main =>
const $AssetsImagesDashBumperMainGen();
}
class $AssetsImagesDinoAnimatronicGen {
const $AssetsImagesDinoAnimatronicGen();
/// File path: assets/images/dino/animatronic/head.png
AssetGenImage get head =>
const AssetGenImage('assets/images/dino/animatronic/head.png');
/// File path: assets/images/dino/animatronic/mouth.png
AssetGenImage get mouth =>
const AssetGenImage('assets/images/dino/animatronic/mouth.png');
}
class $AssetsImagesGoogleRolloverLeftGen {
const $AssetsImagesGoogleRolloverLeftGen();
AssetGenImage get decal =>
const AssetGenImage('assets/images/google_rollover/left/decal.png');
AssetGenImage get pin =>
const AssetGenImage('assets/images/google_rollover/left/pin.png');
}
class $AssetsImagesGoogleRolloverRightGen {
const $AssetsImagesGoogleRolloverRightGen();
AssetGenImage get decal =>
const AssetGenImage('assets/images/google_rollover/right/decal.png');
AssetGenImage get pin =>
const AssetGenImage('assets/images/google_rollover/right/pin.png');
}
class $AssetsImagesGoogleWordLetter1Gen {
const $AssetsImagesGoogleWordLetter1Gen();
/// File path: assets/images/google_word/letter1/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/google_word/letter1/dimmed.png');
/// File path: assets/images/google_word/letter1/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/google_word/letter1/lit.png');
}
class $AssetsImagesGoogleWordLetter2Gen {
const $AssetsImagesGoogleWordLetter2Gen();
/// File path: assets/images/google_word/letter2/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/google_word/letter2/dimmed.png');
/// File path: assets/images/google_word/letter2/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/google_word/letter2/lit.png');
}
class $AssetsImagesGoogleWordLetter3Gen {
const $AssetsImagesGoogleWordLetter3Gen();
/// File path: assets/images/google_word/letter3/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/google_word/letter3/dimmed.png');
/// File path: assets/images/google_word/letter3/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/google_word/letter3/lit.png');
}
class $AssetsImagesGoogleWordLetter4Gen {
const $AssetsImagesGoogleWordLetter4Gen();
/// File path: assets/images/google_word/letter4/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/google_word/letter4/dimmed.png');
/// File path: assets/images/google_word/letter4/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/google_word/letter4/lit.png');
}
class $AssetsImagesGoogleWordLetter5Gen {
const $AssetsImagesGoogleWordLetter5Gen();
/// File path: assets/images/google_word/letter5/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/google_word/letter5/dimmed.png');
/// File path: assets/images/google_word/letter5/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/google_word/letter5/lit.png');
}
class $AssetsImagesGoogleWordLetter6Gen {
const $AssetsImagesGoogleWordLetter6Gen();
/// File path: assets/images/google_word/letter6/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/google_word/letter6/dimmed.png');
/// File path: assets/images/google_word/letter6/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/google_word/letter6/lit.png');
}
class $AssetsImagesKickerLeftGen {
const $AssetsImagesKickerLeftGen();
/// File path: assets/images/kicker/left/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/kicker/left/dimmed.png');
/// File path: assets/images/kicker/left/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/kicker/left/lit.png');
}
class $AssetsImagesKickerRightGen {
const $AssetsImagesKickerRightGen();
/// File path: assets/images/kicker/right/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/kicker/right/dimmed.png');
/// File path: assets/images/kicker/right/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/kicker/right/lit.png');
}
class $AssetsImagesMultiplierX2Gen {
const $AssetsImagesMultiplierX2Gen();
/// File path: assets/images/multiplier/x2/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/multiplier/x2/dimmed.png');
/// File path: assets/images/multiplier/x2/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/multiplier/x2/lit.png');
}
class $AssetsImagesMultiplierX3Gen {
const $AssetsImagesMultiplierX3Gen();
/// File path: assets/images/multiplier/x3/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/multiplier/x3/dimmed.png');
/// File path: assets/images/multiplier/x3/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/multiplier/x3/lit.png');
}
class $AssetsImagesMultiplierX4Gen {
const $AssetsImagesMultiplierX4Gen();
/// File path: assets/images/multiplier/x4/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/multiplier/x4/dimmed.png');
/// File path: assets/images/multiplier/x4/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/multiplier/x4/lit.png');
}
class $AssetsImagesMultiplierX5Gen {
const $AssetsImagesMultiplierX5Gen();
/// File path: assets/images/multiplier/x5/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/multiplier/x5/dimmed.png');
/// File path: assets/images/multiplier/x5/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/multiplier/x5/lit.png');
}
class $AssetsImagesMultiplierX6Gen {
const $AssetsImagesMultiplierX6Gen();
/// File path: assets/images/multiplier/x6/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/multiplier/x6/dimmed.png');
/// File path: assets/images/multiplier/x6/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/multiplier/x6/lit.png');
}
class $AssetsImagesSparkyBumperGen {
const $AssetsImagesSparkyBumperGen();
$AssetsImagesSparkyBumperAGen get a => const $AssetsImagesSparkyBumperAGen();
$AssetsImagesSparkyBumperBGen get b => const $AssetsImagesSparkyBumperBGen();
$AssetsImagesSparkyBumperCGen get c => const $AssetsImagesSparkyBumperCGen();
}
class $AssetsImagesSparkyComputerGen {
const $AssetsImagesSparkyComputerGen();
/// File path: assets/images/sparky/computer/base.png
AssetGenImage get base =>
const AssetGenImage('assets/images/sparky/computer/base.png');
/// File path: assets/images/sparky/computer/glow.png
AssetGenImage get glow =>
const AssetGenImage('assets/images/sparky/computer/glow.png');
/// File path: assets/images/sparky/computer/top.png
AssetGenImage get top =>
const AssetGenImage('assets/images/sparky/computer/top.png');
}
class $AssetsImagesAndroidBumperAGen {
const $AssetsImagesAndroidBumperAGen();
/// File path: assets/images/android/bumper/a/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/android/bumper/a/dimmed.png');
/// File path: assets/images/android/bumper/a/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/android/bumper/a/lit.png');
}
class $AssetsImagesAndroidBumperBGen {
const $AssetsImagesAndroidBumperBGen();
/// File path: assets/images/android/bumper/b/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/android/bumper/b/dimmed.png');
/// File path: assets/images/android/bumper/b/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/android/bumper/b/lit.png');
}
class $AssetsImagesAndroidBumperCowGen {
const $AssetsImagesAndroidBumperCowGen();
/// File path: assets/images/android/bumper/cow/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/android/bumper/cow/dimmed.png');
/// File path: assets/images/android/bumper/cow/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/android/bumper/cow/lit.png');
}
class $AssetsImagesAndroidRampArrowGen {
const $AssetsImagesAndroidRampArrowGen();
/// File path: assets/images/android/ramp/arrow/active1.png
AssetGenImage get active1 =>
const AssetGenImage('assets/images/android/ramp/arrow/active1.png');
/// File path: assets/images/android/ramp/arrow/active2.png
AssetGenImage get active2 =>
const AssetGenImage('assets/images/android/ramp/arrow/active2.png');
/// File path: assets/images/android/ramp/arrow/active3.png
AssetGenImage get active3 =>
const AssetGenImage('assets/images/android/ramp/arrow/active3.png');
/// File path: assets/images/android/ramp/arrow/active4.png
AssetGenImage get active4 =>
const AssetGenImage('assets/images/android/ramp/arrow/active4.png');
/// File path: assets/images/android/ramp/arrow/active5.png
AssetGenImage get active5 =>
const AssetGenImage('assets/images/android/ramp/arrow/active5.png');
/// File path: assets/images/android/ramp/arrow/inactive.png
AssetGenImage get inactive =>
const AssetGenImage('assets/images/android/ramp/arrow/inactive.png');
}
class $AssetsImagesDashBumperAGen {
const $AssetsImagesDashBumperAGen();
/// File path: assets/images/dash/bumper/a/active.png
AssetGenImage get active =>
const AssetGenImage('assets/images/dash/bumper/a/active.png');
/// File path: assets/images/dash/bumper/a/inactive.png
AssetGenImage get inactive =>
const AssetGenImage('assets/images/dash/bumper/a/inactive.png');
}
class $AssetsImagesDashBumperBGen {
const $AssetsImagesDashBumperBGen();
/// File path: assets/images/dash/bumper/b/active.png
AssetGenImage get active =>
const AssetGenImage('assets/images/dash/bumper/b/active.png');
/// File path: assets/images/dash/bumper/b/inactive.png
AssetGenImage get inactive =>
const AssetGenImage('assets/images/dash/bumper/b/inactive.png');
}
class $AssetsImagesDashBumperMainGen {
const $AssetsImagesDashBumperMainGen();
/// File path: assets/images/dash/bumper/main/active.png
AssetGenImage get active =>
const AssetGenImage('assets/images/dash/bumper/main/active.png');
/// File path: assets/images/dash/bumper/main/inactive.png
AssetGenImage get inactive =>
const AssetGenImage('assets/images/dash/bumper/main/inactive.png');
}
class $AssetsImagesSparkyBumperAGen {
const $AssetsImagesSparkyBumperAGen();
/// File path: assets/images/sparky/bumper/a/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/sparky/bumper/a/dimmed.png');
/// File path: assets/images/sparky/bumper/a/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/sparky/bumper/a/lit.png');
}
class $AssetsImagesSparkyBumperBGen {
const $AssetsImagesSparkyBumperBGen();
/// File path: assets/images/sparky/bumper/b/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/sparky/bumper/b/dimmed.png');
/// File path: assets/images/sparky/bumper/b/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/sparky/bumper/b/lit.png');
}
class $AssetsImagesSparkyBumperCGen {
const $AssetsImagesSparkyBumperCGen();
/// File path: assets/images/sparky/bumper/c/dimmed.png
AssetGenImage get dimmed =>
const AssetGenImage('assets/images/sparky/bumper/c/dimmed.png');
/// File path: assets/images/sparky/bumper/c/lit.png
AssetGenImage get lit =>
const AssetGenImage('assets/images/sparky/bumper/c/lit.png');
}
class Assets {
Assets._();
static const $AssetsImagesGen images = $AssetsImagesGen();
}
class AssetGenImage extends AssetImage {
const AssetGenImage(String assetName)
: super(assetName, package: 'pinball_components');
Image image({
Key? key,
ImageFrameBuilder? frameBuilder,
ImageLoadingBuilder? loadingBuilder,
ImageErrorWidgetBuilder? errorBuilder,
String? semanticLabel,
bool excludeFromSemantics = false,
double? width,
double? height,
Color? color,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
bool gaplessPlayback = false,
bool isAntiAlias = false,
FilterQuality filterQuality = FilterQuality.low,
}) {
return Image(
key: key,
image: this,
frameBuilder: frameBuilder,
loadingBuilder: loadingBuilder,
errorBuilder: errorBuilder,
semanticLabel: semanticLabel,
excludeFromSemantics: excludeFromSemantics,
width: width,
height: height,
color: color,
colorBlendMode: colorBlendMode,
fit: fit,
alignment: alignment,
repeat: repeat,
centerSlice: centerSlice,
matchTextDirection: matchTextDirection,
gaplessPlayback: gaplessPlayback,
isAntiAlias: isAntiAlias,
filterQuality: filterQuality,
);
}
String get path => assetName;
}
| pinball/packages/pinball_components/lib/gen/assets.gen.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/gen/assets.gen.dart",
"repo_id": "pinball",
"token_count": 9586
} | 1,168 |
part of 'android_spaceship_cubit.dart';
enum AndroidSpaceshipState {
withoutBonus,
withBonus,
}
| pinball/packages/pinball_components/lib/src/components/android_spaceship/cubit/android_spaceship_state.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/android_spaceship/cubit/android_spaceship_state.dart",
"repo_id": "pinball",
"token_count": 38
} | 1,169 |
import 'package:pinball_components/pinball_components.dart';
/// Indicates a side of the board.
///
/// Usually used to position or mirror elements of a pinball game; such as a
/// [Flipper] or [Kicker].
enum BoardSide {
/// The left side of the board.
left,
/// The right side of the board.
right,
}
/// Utility methods for [BoardSide].
extension BoardSideX on BoardSide {
/// Whether this side is [BoardSide.left].
bool get isLeft => this == BoardSide.left;
/// Whether this side is [BoardSide.right].
bool get isRight => this == BoardSide.right;
/// Direction of the [BoardSide].
///
/// Represents the path which the [BoardSide] moves along.
int get direction => isLeft ? -1 : 1;
}
| pinball/packages/pinball_components/lib/src/components/board_side.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/board_side.dart",
"repo_id": "pinball",
"token_count": 217
} | 1,170 |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:pinball_components/pinball_components.dart';
part 'dash_bumpers_state.dart';
class DashBumpersCubit extends Cubit<DashBumpersState> {
DashBumpersCubit() : super(DashBumpersState.initial());
/// Event added when a ball contacts with a bumper.
void onBallContacted(DashBumperId id) {
final spriteStatesMap = {...state.bumperSpriteStates};
emit(
DashBumpersState(
bumperSpriteStates: spriteStatesMap
..update(id, (_) => DashBumperSpriteState.active),
),
);
}
/// Event added when the bumpers should return to their initial
/// configurations.
void onReset() {
emit(DashBumpersState.initial());
}
}
| pinball/packages/pinball_components/lib/src/components/dash_bumper/cubit/dash_bumpers_cubit.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/dash_bumper/cubit/dash_bumpers_cubit.dart",
"repo_id": "pinball",
"token_count": 272
} | 1,171 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
enum GoogleLetterSpriteState {
lit,
dimmed,
}
/// {@template google_letter}
/// Circular decal that represents a letter in "GOOGLE" for a given index.
/// {@endtemplate}
class GoogleLetter extends SpriteGroupComponent<GoogleLetterSpriteState>
with HasGameRef, FlameBlocListenable<GoogleWordCubit, GoogleWordState> {
/// {@macro google_letter}
GoogleLetter(int index)
: _litAssetPath = _spritePaths[index][GoogleLetterSpriteState.lit]!,
_dimmedAssetPath = _spritePaths[index][GoogleLetterSpriteState.dimmed]!,
_index = index,
super(anchor: Anchor.center);
final String _litAssetPath;
final String _dimmedAssetPath;
final int _index;
@override
bool listenWhen(GoogleWordState previousState, GoogleWordState newState) {
return previousState.letterSpriteStates[_index] !=
newState.letterSpriteStates[_index];
}
@override
void onNewState(GoogleWordState state) =>
current = state.letterSpriteStates[_index];
@override
Future<void> onLoad() async {
await super.onLoad();
final sprites = {
GoogleLetterSpriteState.lit: Sprite(
gameRef.images.fromCache(_litAssetPath),
),
GoogleLetterSpriteState.dimmed: Sprite(
gameRef.images.fromCache(_dimmedAssetPath),
),
};
this.sprites = sprites;
current = readBloc<GoogleWordCubit, GoogleWordState>()
.state
.letterSpriteStates[_index];
size = sprites[current]!.originalSize / 10;
}
}
final _spritePaths = <Map<GoogleLetterSpriteState, String>>[
{
GoogleLetterSpriteState.lit: Assets.images.googleWord.letter1.lit.keyName,
GoogleLetterSpriteState.dimmed:
Assets.images.googleWord.letter1.dimmed.keyName,
},
{
GoogleLetterSpriteState.lit: Assets.images.googleWord.letter2.lit.keyName,
GoogleLetterSpriteState.dimmed:
Assets.images.googleWord.letter2.dimmed.keyName,
},
{
GoogleLetterSpriteState.lit: Assets.images.googleWord.letter3.lit.keyName,
GoogleLetterSpriteState.dimmed:
Assets.images.googleWord.letter3.dimmed.keyName,
},
{
GoogleLetterSpriteState.lit: Assets.images.googleWord.letter4.lit.keyName,
GoogleLetterSpriteState.dimmed:
Assets.images.googleWord.letter4.dimmed.keyName,
},
{
GoogleLetterSpriteState.lit: Assets.images.googleWord.letter5.lit.keyName,
GoogleLetterSpriteState.dimmed:
Assets.images.googleWord.letter5.dimmed.keyName,
},
{
GoogleLetterSpriteState.lit: Assets.images.googleWord.letter6.lit.keyName,
GoogleLetterSpriteState.dimmed:
Assets.images.googleWord.letter6.dimmed.keyName,
},
];
| pinball/packages/pinball_components/lib/src/components/google_letter.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/google_letter.dart",
"repo_id": "pinball",
"token_count": 1049
} | 1,172 |
import 'dart:math' as math;
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:geometry/geometry.dart' as geometry show centroid;
import 'package:pinball_components/gen/assets.gen.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets;
import 'package:pinball_components/src/components/bumping_behavior.dart';
import 'package:pinball_components/src/components/kicker/behaviors/behaviors.dart';
import 'package:pinball_flame/pinball_flame.dart';
export 'cubit/kicker_cubit.dart';
/// {@template kicker}
/// Triangular [BodyType.static] body that propels the [Ball] towards the
/// opposite side.
///
/// [Kicker]s are usually positioned above each [Flipper].
/// {@endtemplate kicker}
class Kicker extends BodyComponent with InitialPosition {
/// {@macro kicker}
Kicker({
required BoardSide side,
Iterable<Component>? children,
}) : this._(
side: side,
bloc: KickerCubit(),
children: children,
);
Kicker._({
required BoardSide side,
required this.bloc,
Iterable<Component>? children,
}) : _side = side,
super(
children: [
BumpingBehavior(strength: 25)..applyTo(['bouncy_edge']),
KickerBallContactBehavior()..applyTo(['bouncy_edge']),
KickerBlinkingBehavior(),
_KickerSpriteGroupComponent(
side: side,
state: bloc.state,
),
...?children,
],
renderBody: false,
);
/// Creates a [Kicker] without any children.
///
/// This can be used for testing [Kicker]'s behaviors in isolation.
@visibleForTesting
Kicker.test({
required this.bloc,
required BoardSide side,
}) : _side = side;
final KickerCubit bloc;
@override
void onRemove() {
bloc.close();
super.onRemove();
}
/// Whether the [Kicker] is on the left or right side of the board.
final BoardSide _side;
List<FixtureDef> _createFixtureDefs() {
final direction = _side.direction;
const quarterPi = math.pi / 4;
final size = Vector2(4.4, 15);
final upperCircle = CircleShape()..radius = 1.6;
upperCircle.position.setValues(0, upperCircle.radius / 2);
final lowerCircle = CircleShape()..radius = 1.6;
lowerCircle.position.setValues(
size.x * -direction,
size.y + 0.8,
);
final wallFacingEdge = EdgeShape()
..set(
upperCircle.position +
Vector2(
upperCircle.radius * direction,
0,
),
Vector2(2.5 * direction, size.y - 2),
);
final bottomEdge = EdgeShape()
..set(
wallFacingEdge.vertex2,
lowerCircle.position +
Vector2(
lowerCircle.radius * math.cos(quarterPi) * direction,
lowerCircle.radius * math.sin(quarterPi),
),
);
final bouncyEdge = EdgeShape()
..set(
upperCircle.position +
Vector2(
upperCircle.radius * math.cos(quarterPi) * -direction,
-upperCircle.radius * math.sin(quarterPi),
),
lowerCircle.position +
Vector2(
lowerCircle.radius * math.cos(quarterPi) * -direction,
-lowerCircle.radius * math.sin(quarterPi),
),
);
final fixturesDefs = [
FixtureDef(upperCircle),
FixtureDef(lowerCircle),
FixtureDef(wallFacingEdge),
FixtureDef(bottomEdge),
FixtureDef(bouncyEdge, userData: 'bouncy_edge'),
];
final centroid = geometry.centroid(
[
upperCircle.position + Vector2(0, -upperCircle.radius),
lowerCircle.position +
Vector2(
lowerCircle.radius * math.cos(quarterPi) * -direction,
lowerCircle.radius * math.sin(quarterPi),
),
wallFacingEdge.vertex2,
],
);
for (final fixtureDef in fixturesDefs) {
fixtureDef.shape.moveBy(-centroid);
}
return fixturesDefs;
}
@override
Body createBody() {
final bodyDef = BodyDef(
position: initialPosition,
);
final body = world.createBody(bodyDef);
_createFixtureDefs().forEach(body.createFixture);
return body;
}
}
class _KickerSpriteGroupComponent extends SpriteGroupComponent<KickerState>
with HasGameRef, ParentIsA<Kicker> {
_KickerSpriteGroupComponent({
required BoardSide side,
required KickerState state,
}) : _side = side,
super(
anchor: Anchor.center,
position: Vector2(0.7 * -side.direction, -2.2),
current: state,
);
final BoardSide _side;
@override
Future<void> onLoad() async {
await super.onLoad();
parent.bloc.stream.listen((state) => current = state);
final sprites = {
KickerState.lit: Sprite(
gameRef.images.fromCache(
(_side.isLeft)
? Assets.images.kicker.left.lit.keyName
: Assets.images.kicker.right.lit.keyName,
),
),
KickerState.dimmed: Sprite(
gameRef.images.fromCache(
(_side.isLeft)
? Assets.images.kicker.left.dimmed.keyName
: Assets.images.kicker.right.dimmed.keyName,
),
),
};
this.sprites = sprites;
size = sprites[current]!.originalSize / 10;
}
}
extension on Shape {
void moveBy(Vector2 offset) {
if (this is CircleShape) {
final circle = this as CircleShape;
circle.position.setFrom(circle.position + offset);
} else if (this is EdgeShape) {
final edge = this as EdgeShape;
edge.set(edge.vertex1 + offset, edge.vertex2 + offset);
}
}
}
| pinball/packages/pinball_components/lib/src/components/kicker/kicker.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/kicker/kicker.dart",
"repo_id": "pinball",
"token_count": 2495
} | 1,173 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Plays the [PinballAudio.launcher] sound.
///
/// It is attached when the plunger is released.
class PlungerNoiseBehavior extends Component
with FlameBlocListenable<PlungerCubit, PlungerState> {
@override
void onNewState(PlungerState state) {
super.onNewState(state);
if (state.isReleasing) {
readProvider<PinballAudioPlayer>().play(PinballAudio.launcher);
}
}
}
| pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_noise_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/plunger/behaviors/plunger_noise_behavior.dart",
"repo_id": "pinball",
"token_count": 228
} | 1,174 |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
part 'skill_shot_state.dart';
class SkillShotCubit extends Cubit<SkillShotState> {
SkillShotCubit() : super(const SkillShotState.initial());
void onBallContacted() {
emit(
const SkillShotState(
spriteState: SkillShotSpriteState.lit,
isBlinking: true,
),
);
}
void switched() {
switch (state.spriteState) {
case SkillShotSpriteState.lit:
emit(state.copyWith(spriteState: SkillShotSpriteState.dimmed));
break;
case SkillShotSpriteState.dimmed:
emit(state.copyWith(spriteState: SkillShotSpriteState.lit));
break;
}
}
void onBlinkingFinished() {
emit(
const SkillShotState(
spriteState: SkillShotSpriteState.dimmed,
isBlinking: false,
),
);
}
}
| pinball/packages/pinball_components/lib/src/components/skill_shot/cubit/skill_shot_cubit.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/skill_shot/cubit/skill_shot_cubit.dart",
"repo_id": "pinball",
"token_count": 359
} | 1,175 |
import 'dart:math' as math;
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/bumping_behavior.dart';
import 'package:pinball_components/src/components/sparky_bumper/behaviors/behaviors.dart';
import 'package:pinball_flame/pinball_flame.dart';
export 'cubit/sparky_bumper_cubit.dart';
/// {@template sparky_bumper}
/// Bumper for the Sparky Scorch.
/// {@endtemplate}
class SparkyBumper extends BodyComponent with InitialPosition, ZIndex {
/// {@macro sparky_bumper}
SparkyBumper._({
required double majorRadius,
required double minorRadius,
required String litAssetPath,
required String dimmedAssetPath,
required Vector2 spritePosition,
required this.bloc,
Iterable<Component>? children,
}) : _majorRadius = majorRadius,
_minorRadius = minorRadius,
super(
renderBody: false,
children: [
SparkyBumperBallContactBehavior(),
SparkyBumperBlinkingBehavior(),
_SparkyBumperSpriteGroupComponent(
litAssetPath: litAssetPath,
dimmedAssetPath: dimmedAssetPath,
position: spritePosition,
state: bloc.state,
),
...?children,
],
) {
zIndex = ZIndexes.sparkyBumper;
}
/// {@macro sparky_bumper}
SparkyBumper.a({
Iterable<Component>? children,
}) : this._(
majorRadius: 2.9,
minorRadius: 2.1,
litAssetPath: Assets.images.sparky.bumper.a.lit.keyName,
dimmedAssetPath: Assets.images.sparky.bumper.a.dimmed.keyName,
spritePosition: Vector2(0, -0.25),
bloc: SparkyBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// {@macro sparky_bumper}
SparkyBumper.b({
Iterable<Component>? children,
}) : this._(
majorRadius: 2.85,
minorRadius: 2,
litAssetPath: Assets.images.sparky.bumper.b.lit.keyName,
dimmedAssetPath: Assets.images.sparky.bumper.b.dimmed.keyName,
spritePosition: Vector2(0, -0.35),
bloc: SparkyBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// {@macro sparky_bumper}
SparkyBumper.c({
Iterable<Component>? children,
}) : this._(
majorRadius: 3,
minorRadius: 2.2,
litAssetPath: Assets.images.sparky.bumper.c.lit.keyName,
dimmedAssetPath: Assets.images.sparky.bumper.c.dimmed.keyName,
spritePosition: Vector2(0, -0.4),
bloc: SparkyBumperCubit(),
children: [
...?children,
BumpingBehavior(strength: 20),
],
);
/// Creates an [SparkyBumper] without any children.
///
/// This can be used for testing [SparkyBumper]'s behaviors in isolation.
@visibleForTesting
SparkyBumper.test({
required this.bloc,
}) : _majorRadius = 3,
_minorRadius = 2.2;
final double _majorRadius;
final double _minorRadius;
final SparkyBumperCubit bloc;
@override
void onRemove() {
bloc.close();
super.onRemove();
}
@override
Body createBody() {
final shape = EllipseShape(
center: Vector2.zero(),
majorRadius: _majorRadius,
minorRadius: _minorRadius,
)..rotate(math.pi / 2.1);
final bodyDef = BodyDef(
position: initialPosition,
);
return world.createBody(bodyDef)..createFixtureFromShape(shape);
}
}
class _SparkyBumperSpriteGroupComponent
extends SpriteGroupComponent<SparkyBumperState>
with HasGameRef, ParentIsA<SparkyBumper> {
_SparkyBumperSpriteGroupComponent({
required String litAssetPath,
required String dimmedAssetPath,
required Vector2 position,
required SparkyBumperState state,
}) : _litAssetPath = litAssetPath,
_dimmedAssetPath = dimmedAssetPath,
super(
anchor: Anchor.center,
position: position,
current: state,
);
final String _litAssetPath;
final String _dimmedAssetPath;
@override
Future<void> onLoad() async {
await super.onLoad();
parent.bloc.stream.listen((state) => current = state);
final sprites = {
SparkyBumperState.lit: Sprite(
gameRef.images.fromCache(_litAssetPath),
),
SparkyBumperState.dimmed: Sprite(
gameRef.images.fromCache(_dimmedAssetPath),
),
};
this.sprites = sprites;
size = sprites[current]!.originalSize / 10;
}
}
| pinball/packages/pinball_components/lib/src/components/sparky_bumper/sparky_bumper.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/sparky_bumper/sparky_bumper.dart",
"repo_id": "pinball",
"token_count": 2064
} | 1,176 |
import 'package:flame/input.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_theme/pinball_theme.dart' as theme;
import 'package:sandbox/common/common.dart';
class BallGame extends AssetsGame with TapDetector, Traceable {
BallGame({
this.ballPriority = 0,
this.ballLayer = Layer.all,
this.character,
List<String>? imagesFileNames,
}) : super(
imagesFileNames: [
theme.Assets.images.android.ball.keyName,
theme.Assets.images.dash.ball.keyName,
theme.Assets.images.dino.ball.keyName,
theme.Assets.images.sparky.ball.keyName,
if (imagesFileNames != null) ...imagesFileNames,
],
);
static const description = '''
Shows how a Ball works.
- Tap anywhere on the screen to spawn a ball into the game.
''';
static final characterBallPaths = <String, String>{
'Dash': theme.Assets.images.dash.ball.keyName,
'Sparky': theme.Assets.images.sparky.ball.keyName,
'Android': theme.Assets.images.android.ball.keyName,
'Dino': theme.Assets.images.dino.ball.keyName,
};
final int ballPriority;
final Layer ballLayer;
final String? character;
@override
void onTapUp(TapUpInfo info) {
add(
Ball(
assetPath: characterBallPaths[character],
)
..initialPosition = info.eventPosition.game
..layer = ballLayer
..priority = ballPriority,
);
traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/ball/basic_ball_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/ball/basic_ball_game.dart",
"repo_id": "pinball",
"token_count": 624
} | 1,177 |
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/error_component/error_component_game.dart';
void addErrorComponentStories(Dashbook dashbook) {
dashbook.storiesOf('ErrorComponent').addGame(
title: 'Basic',
description: ErrorComponentGame.description,
gameBuilder: (context) => ErrorComponentGame(
text: context.textProperty(
'label',
'Oh no, something went wrong!',
),
),
);
}
| pinball/packages/pinball_components/sandbox/lib/stories/error_component/stories.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/error_component/stories.dart",
"repo_id": "pinball",
"token_count": 211
} | 1,178 |
import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class PlungerGame extends BallGame
with HasKeyboardHandlerComponents, Traceable {
PlungerGame()
: super(
imagesFileNames: [
Assets.images.plunger.plunger.keyName,
],
);
static const description = '''
Shows how Plunger is rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a ball into the game.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
final center = screenToWorld(camera.viewport.canvasSize! / 2);
final plunger = Plunger()
..initialPosition = Vector2(center.x - 8.8, center.y);
await add(
FlameBlocProvider<PlungerCubit, PlungerState>(
create: PlungerCubit.new,
children: [plunger],
),
);
await plunger.add(PlungerKeyControllingBehavior());
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/plunger/plunger_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/plunger/plunger_game.dart",
"repo_id": "pinball",
"token_count": 440
} | 1,179 |
// 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 'package:pinball_theme/pinball_theme.dart' as theme;
import '../../../../helpers/helpers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final asset = theme.Assets.images.dash.ball.keyName;
final flameTester = FlameTester(() => TestGame([asset]));
group('BallGravitatingBehavior', () {
test('can be instantiated', () {
expect(
BallGravitatingBehavior(),
isA<BallGravitatingBehavior>(),
);
});
flameTester.test('can be loaded', (game) async {
final ball = Ball.test();
final behavior = BallGravitatingBehavior();
await ball.add(behavior);
await game.ensureAdd(ball);
expect(
ball.firstChild<BallGravitatingBehavior>(),
equals(behavior),
);
});
flameTester.test(
"overrides the body's horizontal gravity symmetrically",
(game) async {
final ball1 = Ball.test()..initialPosition = Vector2(10, 0);
await ball1.add(BallGravitatingBehavior());
final ball2 = Ball.test()..initialPosition = Vector2(-10, 0);
await ball2.add(BallGravitatingBehavior());
await game.ensureAddAll([ball1, ball2]);
game.update(1);
expect(
ball1.body.gravityOverride!.x,
equals(-ball2.body.gravityOverride!.x),
);
expect(
ball1.body.gravityOverride!.y,
equals(ball2.body.gravityOverride!.y),
);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/ball/behaviors/ball_gravitating_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/ball/behaviors/ball_gravitating_behavior_test.dart",
"repo_id": "pinball",
"token_count": 698
} | 1,180 |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/chrome_dino/behaviors/behaviors.dart';
import '../../../../helpers/helpers.dart';
class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
group(
'ChromeDinoSwivelingBehavior',
() {
const swivelPeriod = 98 / 48;
test('can be instantiated', () {
expect(
ChromeDinoSwivelingBehavior(),
isA<ChromeDinoSwivelingBehavior>(),
);
});
flameTester.test(
'creates a RevoluteJoint',
(game) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
initialState: const ChromeDinoState.initial(),
);
final chromeDino = ChromeDino.test(bloc: bloc);
await chromeDino.add(behavior);
await game.ensureAdd(chromeDino);
expect(
game.world.joints.whereType<RevoluteJoint>().single,
isNotNull,
);
},
);
flameTester.test(
'reverses swivel direction on each timer tick',
(game) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
initialState: const ChromeDinoState.initial(),
);
final chromeDino = ChromeDino.test(bloc: bloc);
await chromeDino.add(behavior);
await game.ensureAdd(chromeDino);
final timer = behavior.timer;
final joint = game.world.joints.whereType<RevoluteJoint>().single;
expect(joint.motorSpeed, isPositive);
timer.onTick!();
game.update(0);
expect(joint.motorSpeed, isNegative);
timer.onTick!();
game.update(0);
expect(joint.motorSpeed, isPositive);
},
);
group('calls', () {
flameTester.testGameWidget(
'onCloseMouth when joint angle is between limits '
'and mouth is open',
setUp: (game, tester) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
initialState:
const ChromeDinoState.initial().copyWith(isMouthOpen: true),
);
final chromeDino = ChromeDino.test(bloc: bloc);
await chromeDino.add(behavior);
await game.ensureAdd(chromeDino);
final joint = game.world.joints.whereType<RevoluteJoint>().single;
final angle = joint.jointAngle();
expect(
angle < joint.upperLimit && angle > joint.lowerLimit,
isTrue,
);
game.update(0);
verify(bloc.onCloseMouth).called(1);
},
);
flameTester.testGameWidget(
'onOpenMouth when joint angle is greater than the upperLimit '
'and mouth is closed',
setUp: (game, tester) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
initialState:
const ChromeDinoState.initial().copyWith(isMouthOpen: false),
);
final chromeDino = ChromeDino.test(bloc: bloc);
await chromeDino.add(behavior);
await game.ensureAdd(chromeDino);
final joint = game.world.joints.whereType<RevoluteJoint>().single;
game.update(swivelPeriod / 2);
await tester.pump();
final angle = joint.jointAngle();
expect(angle >= joint.upperLimit, isTrue);
verify(bloc.onOpenMouth).called(1);
},
);
flameTester.testGameWidget(
'onOpenMouth when joint angle is less than the lowerLimit '
'and mouth is closed',
setUp: (game, tester) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
initialState:
const ChromeDinoState.initial().copyWith(isMouthOpen: false),
);
final chromeDino = ChromeDino.test(bloc: bloc);
await chromeDino.add(behavior);
await game.ensureAdd(chromeDino);
final joint = game.world.joints.whereType<RevoluteJoint>().single;
game.update(swivelPeriod * 1.5);
await tester.pump();
final angle = joint.jointAngle();
expect(angle <= joint.lowerLimit, isTrue);
verify(bloc.onOpenMouth).called(1);
},
);
});
},
);
}
| pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_swiveling_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/chrome_dino/behaviors/chrome_dino_swiveling_behavior_test.dart",
"repo_id": "pinball",
"token_count": 2640
} | 1,181 |
// ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/src/components/components.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('FlipperJointingBehavior', () {
final flameTester = FlameTester(Forge2DGame.new);
test('can be instantiated', () {
expect(
FlipperJointingBehavior(),
isA<FlipperJointingBehavior>(),
);
});
flameTester.test('can be loaded', (game) async {
final parent = Flipper.test(side: BoardSide.left);
final behavior = FlipperJointingBehavior();
await game.ensureAdd(parent);
await parent.ensureAdd(behavior);
expect(parent.contains(behavior), isTrue);
});
flameTester.test('creates a joint', (game) async {
final parent = Flipper.test(side: BoardSide.left);
final behavior = FlipperJointingBehavior();
await game.ensureAdd(parent);
await parent.ensureAdd(behavior);
expect(parent.body.joints, isNotEmpty);
});
});
}
| pinball/packages/pinball_components/test/src/components/flipper/behaviors/flipper_jointing_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/flipper/behaviors/flipper_jointing_behavior_test.dart",
"repo_id": "pinball",
"token_count": 443
} | 1,182 |
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/kicker/behaviors/behaviors.dart';
import '../../../../helpers/helpers.dart';
class _MockKickerCubit extends Mock implements KickerCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
group(
'KickerBlinkingBehavior',
() {
flameTester.testGameWidget(
'calls onBlinked after 0.05 seconds when dimmed',
setUp: (game, tester) async {
final behavior = KickerBlinkingBehavior();
final bloc = _MockKickerCubit();
final streamController = StreamController<KickerState>();
whenListen(
bloc,
streamController.stream,
initialState: KickerState.lit,
);
final kicker = Kicker.test(
side: BoardSide.left,
bloc: bloc,
);
await kicker.add(behavior);
await game.ensureAdd(kicker);
streamController.add(KickerState.dimmed);
await tester.pump();
game.update(0.05);
await streamController.close();
verify(bloc.onBlinked).called(1);
},
);
},
);
}
| pinball/packages/pinball_components/test/src/components/kicker/behaviors/kicker_blinking_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/kicker/behaviors/kicker_blinking_behavior_test.dart",
"repo_id": "pinball",
"token_count": 642
} | 1,183 |
// ignore_for_file: cascade_invocations
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
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';
class _TestGame extends Forge2DGame {
Future<void> pump(
Component behavior, {
PlungerCubit? plungerBloc,
}) async {
final plunger = Plunger.test();
await ensureAdd(plunger);
return plunger.ensureAdd(
FlameBlocProvider<PlungerCubit, PlungerState>.value(
value: plungerBloc ?? _MockPlungerCubit(),
children: [behavior],
),
);
}
}
class _MockPlungerCubit extends Mock implements PlungerCubit {}
class _MockPrismaticJoint extends Mock implements PrismaticJoint {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('PlungerPullingBehavior', () {
test('can be instantiated', () {
expect(
PlungerPullingBehavior(strength: 0),
isA<PlungerPullingBehavior>(),
);
});
test('throws assertion error when strength is negative ', () {
expect(
() => PlungerPullingBehavior(strength: -1),
throwsAssertionError,
);
});
flameTester.test('can be loaded', (game) async {
final behavior = PlungerPullingBehavior(strength: 0);
await game.pump(behavior);
expect(game.descendants(), contains(behavior));
});
flameTester.test(
'applies vertical linear velocity when pulled',
(game) async {
final plungerBloc = _MockPlungerCubit();
whenListen<PlungerState>(
plungerBloc,
Stream.value(PlungerState.pulling),
initialState: PlungerState.pulling,
);
const strength = 2.0;
final behavior = PlungerPullingBehavior(
strength: strength,
);
await game.pump(
behavior,
plungerBloc: plungerBloc,
);
game.update(0);
final plunger = behavior.ancestors().whereType<Plunger>().single;
expect(plunger.body.linearVelocity.x, equals(0));
expect(plunger.body.linearVelocity.y, equals(strength));
},
);
});
group('PlungerAutoPullingBehavior', () {
test('can be instantiated', () {
expect(
PlungerAutoPullingBehavior(),
isA<PlungerAutoPullingBehavior>(),
);
});
flameTester.test('can be loaded', (game) async {
final behavior = PlungerAutoPullingBehavior();
await game.pump(behavior);
expect(game.descendants(), contains(behavior));
});
flameTester.test(
'releases when joint reaches limit',
(game) async {
final plungerBloc = _MockPlungerCubit();
whenListen<PlungerState>(
plungerBloc,
Stream.value(PlungerState.autoPulling),
initialState: PlungerState.autoPulling,
);
final behavior = PlungerAutoPullingBehavior();
await game.pump(
behavior,
plungerBloc: plungerBloc,
);
final plunger = behavior.ancestors().whereType<Plunger>().single;
final joint = _MockPrismaticJoint();
when(joint.getJointTranslation).thenReturn(0);
when(joint.getLowerLimit).thenReturn(0);
plunger.body.joints.add(joint);
game.update(0);
verify(plungerBloc.released).called(1);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_pulling_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/plunger/behaviors/plunger_pulling_behavior_test.dart",
"repo_id": "pinball",
"token_count": 1547
} | 1,184 |
// ignore_for_file: cascade_invocations
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_components/pinball_components.dart';
import 'package:pinball_components/src/components/spaceship_ramp/behavior/behavior.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.android.ramp.boardOpening.keyName,
Assets.images.android.ramp.railingForeground.keyName,
Assets.images.android.ramp.railingBackground.keyName,
Assets.images.android.ramp.main.keyName,
Assets.images.android.ramp.arrow.inactive.keyName,
Assets.images.android.ramp.arrow.active1.keyName,
Assets.images.android.ramp.arrow.active2.keyName,
Assets.images.android.ramp.arrow.active3.keyName,
Assets.images.android.ramp.arrow.active4.keyName,
Assets.images.android.ramp.arrow.active5.keyName,
]);
}
Future<void> pump(
SpaceshipRamp children, {
required SpaceshipRampCubit bloc,
}) async {
await ensureAdd(
FlameBlocProvider<SpaceshipRampCubit, SpaceshipRampState>.value(
value: bloc,
children: [
ZCanvasComponent(children: [children]),
],
),
);
}
}
class _MockSpaceshipRampCubit extends Mock implements SpaceshipRampCubit {}
class _MockBall extends Mock implements Ball {}
class _MockBody extends Mock implements Body {}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group(
'RampBallAscendingContactBehavior',
() {
test('can be instantiated', () {
expect(
RampBallAscendingContactBehavior(),
isA<RampBallAscendingContactBehavior>(),
);
});
group('beginContact', () {
late Ball ball;
late Body body;
setUp(() {
ball = _MockBall();
body = _MockBody();
when(() => ball.body).thenReturn(body);
});
flameTester.test(
"calls 'onAscendingBallEntered' when a ball enters into the ramp",
(game) async {
final behavior = RampBallAscendingContactBehavior();
final bloc = _MockSpaceshipRampCubit();
whenListen(
bloc,
const Stream<SpaceshipRampState>.empty(),
initialState: const SpaceshipRampState.initial(),
);
final opening = SpaceshipRampBoardOpening.test();
final spaceshipRamp = SpaceshipRamp.test(
children: [opening],
);
when(() => body.linearVelocity).thenReturn(Vector2(0, -1));
await game.pump(
spaceshipRamp,
bloc: bloc,
);
await opening.ensureAdd(behavior);
behavior.beginContact(ball, _MockContact());
verify(bloc.onAscendingBallEntered).called(1);
},
);
flameTester.test(
"doesn't call 'onAscendingBallEntered' when a ball goes out the ramp",
(game) async {
final behavior = RampBallAscendingContactBehavior();
final bloc = _MockSpaceshipRampCubit();
whenListen(
bloc,
const Stream<SpaceshipRampState>.empty(),
initialState: const SpaceshipRampState.initial(),
);
final opening = SpaceshipRampBoardOpening.test();
final spaceshipRamp = SpaceshipRamp.test(
children: [opening],
);
when(() => body.linearVelocity).thenReturn(Vector2(0, 1));
await game.pump(
spaceshipRamp,
bloc: bloc,
);
await opening.ensureAdd(behavior);
behavior.beginContact(ball, _MockContact());
verifyNever(bloc.onAscendingBallEntered);
},
);
});
},
);
}
| pinball/packages/pinball_components/test/src/components/spaceship_ramp/behavior/ramp_ball_ascending_contact_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/spaceship_ramp/behavior/ramp_ball_ascending_contact_behavior_test.dart",
"repo_id": "pinball",
"token_count": 1902
} | 1,185 |
library pinball_flame;
export 'src/behaviors/behaviors.dart';
export 'src/canvas/canvas.dart';
export 'src/flame_provider.dart';
export 'src/keyboard_input_controller.dart';
export 'src/layer.dart';
export 'src/parent_is_a.dart';
export 'src/pinball_forge2d_game.dart';
export 'src/shapes/shapes.dart';
export 'src/sprite_animation.dart';
| pinball/packages/pinball_flame/lib/pinball_flame.dart/0 | {
"file_path": "pinball/packages/pinball_flame/lib/pinball_flame.dart",
"repo_id": "pinball",
"token_count": 135
} | 1,186 |
import 'package:flame/extensions.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:geometry/geometry.dart';
/// {@template ellipse_shape}
/// Creates an ellipse.
/// {@endtemplate}
class EllipseShape extends ChainShape {
/// {@macro ellipse_shape}
EllipseShape({
required this.center,
required this.majorRadius,
required this.minorRadius,
}) {
createChain(
calculateEllipse(
center: center,
majorRadius: majorRadius,
minorRadius: minorRadius,
),
);
}
/// The top left corner of the ellipse.
///
/// Where the initial painting begins.
final Vector2 center;
/// Major radius is specified by [majorRadius].
final double majorRadius;
/// Minor radius is specified by [minorRadius].
final double minorRadius;
/// Rotates the ellipse by a given [angle] in radians.
void rotate(double angle) {
for (final vector in vertices) {
vector.rotate(angle);
}
}
}
| pinball/packages/pinball_flame/lib/src/shapes/ellipse_shape.dart/0 | {
"file_path": "pinball/packages/pinball_flame/lib/src/shapes/ellipse_shape.dart",
"repo_id": "pinball",
"token_count": 357
} | 1,187 |
/// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
/// FlutterGen
/// *****************************************************
// ignore_for_file: directives_ordering,unnecessary_import
import 'package:flutter/widgets.dart';
class $AssetsImagesGen {
const $AssetsImagesGen();
$AssetsImagesAndroidGen get android => const $AssetsImagesAndroidGen();
$AssetsImagesDashGen get dash => const $AssetsImagesDashGen();
$AssetsImagesDinoGen get dino => const $AssetsImagesDinoGen();
/// File path: assets/images/pinball_button.png
AssetGenImage get pinballButton =>
const AssetGenImage('assets/images/pinball_button.png');
/// File path: assets/images/select_character_background.png
AssetGenImage get selectCharacterBackground =>
const AssetGenImage('assets/images/select_character_background.png');
$AssetsImagesSparkyGen get sparky => const $AssetsImagesSparkyGen();
}
class $AssetsImagesAndroidGen {
const $AssetsImagesAndroidGen();
/// File path: assets/images/android/animation.png
AssetGenImage get animation =>
const AssetGenImage('assets/images/android/animation.png');
/// File path: assets/images/android/background.jpg
AssetGenImage get background =>
const AssetGenImage('assets/images/android/background.jpg');
/// File path: assets/images/android/ball.png
AssetGenImage get ball =>
const AssetGenImage('assets/images/android/ball.png');
/// File path: assets/images/android/icon.png
AssetGenImage get icon =>
const AssetGenImage('assets/images/android/icon.png');
/// File path: assets/images/android/leaderboard_icon.png
AssetGenImage get leaderboardIcon =>
const AssetGenImage('assets/images/android/leaderboard_icon.png');
}
class $AssetsImagesDashGen {
const $AssetsImagesDashGen();
/// File path: assets/images/dash/animation.png
AssetGenImage get animation =>
const AssetGenImage('assets/images/dash/animation.png');
/// File path: assets/images/dash/background.jpg
AssetGenImage get background =>
const AssetGenImage('assets/images/dash/background.jpg');
/// File path: assets/images/dash/ball.png
AssetGenImage get ball => const AssetGenImage('assets/images/dash/ball.png');
/// File path: assets/images/dash/icon.png
AssetGenImage get icon => const AssetGenImage('assets/images/dash/icon.png');
/// File path: assets/images/dash/leaderboard_icon.png
AssetGenImage get leaderboardIcon =>
const AssetGenImage('assets/images/dash/leaderboard_icon.png');
}
class $AssetsImagesDinoGen {
const $AssetsImagesDinoGen();
/// File path: assets/images/dino/animation.png
AssetGenImage get animation =>
const AssetGenImage('assets/images/dino/animation.png');
/// File path: assets/images/dino/background.jpg
AssetGenImage get background =>
const AssetGenImage('assets/images/dino/background.jpg');
/// File path: assets/images/dino/ball.png
AssetGenImage get ball => const AssetGenImage('assets/images/dino/ball.png');
/// File path: assets/images/dino/icon.png
AssetGenImage get icon => const AssetGenImage('assets/images/dino/icon.png');
/// File path: assets/images/dino/leaderboard_icon.png
AssetGenImage get leaderboardIcon =>
const AssetGenImage('assets/images/dino/leaderboard_icon.png');
}
class $AssetsImagesSparkyGen {
const $AssetsImagesSparkyGen();
/// File path: assets/images/sparky/animation.png
AssetGenImage get animation =>
const AssetGenImage('assets/images/sparky/animation.png');
/// File path: assets/images/sparky/background.jpg
AssetGenImage get background =>
const AssetGenImage('assets/images/sparky/background.jpg');
/// File path: assets/images/sparky/ball.png
AssetGenImage get ball =>
const AssetGenImage('assets/images/sparky/ball.png');
/// File path: assets/images/sparky/icon.png
AssetGenImage get icon =>
const AssetGenImage('assets/images/sparky/icon.png');
/// File path: assets/images/sparky/leaderboard_icon.png
AssetGenImage get leaderboardIcon =>
const AssetGenImage('assets/images/sparky/leaderboard_icon.png');
}
class Assets {
Assets._();
static const $AssetsImagesGen images = $AssetsImagesGen();
}
class AssetGenImage extends AssetImage {
const AssetGenImage(String assetName)
: super(assetName, package: 'pinball_theme');
Image image({
Key? key,
ImageFrameBuilder? frameBuilder,
ImageLoadingBuilder? loadingBuilder,
ImageErrorWidgetBuilder? errorBuilder,
String? semanticLabel,
bool excludeFromSemantics = false,
double? width,
double? height,
Color? color,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
bool gaplessPlayback = false,
bool isAntiAlias = false,
FilterQuality filterQuality = FilterQuality.low,
}) {
return Image(
key: key,
image: this,
frameBuilder: frameBuilder,
loadingBuilder: loadingBuilder,
errorBuilder: errorBuilder,
semanticLabel: semanticLabel,
excludeFromSemantics: excludeFromSemantics,
width: width,
height: height,
color: color,
colorBlendMode: colorBlendMode,
fit: fit,
alignment: alignment,
repeat: repeat,
centerSlice: centerSlice,
matchTextDirection: matchTextDirection,
gaplessPlayback: gaplessPlayback,
isAntiAlias: isAntiAlias,
filterQuality: filterQuality,
);
}
String get path => assetName;
}
| pinball/packages/pinball_theme/lib/src/generated/assets.gen.dart/0 | {
"file_path": "pinball/packages/pinball_theme/lib/src/generated/assets.gen.dart",
"repo_id": "pinball",
"token_count": 1819
} | 1,188 |
import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';
/// Opens the given [url] in a new tab of the host browser
Future<void> openLink(String url, {VoidCallback? onError}) async {
final uri = Uri.parse(url);
if (await canLaunchUrl(uri)) {
await launchUrl(uri);
} else if (onError != null) {
onError();
}
}
| pinball/packages/pinball_ui/lib/src/external_links/external_links.dart/0 | {
"file_path": "pinball/packages/pinball_ui/lib/src/external_links/external_links.dart",
"repo_id": "pinball",
"token_count": 129
} | 1,189 |
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_ui/pinball_ui.dart';
void main() {
group('PinballTextStyle', () {
test('headline1 has fontSize 28 and white color', () {
const style = PinballTextStyle.headline1;
expect(style.fontSize, 28);
expect(style.color, PinballColors.white);
});
test('headline2 has fontSize 24', () {
const style = PinballTextStyle.headline2;
expect(style.fontSize, 24);
});
test('headline3 has fontSize 20 and dark blue color', () {
const style = PinballTextStyle.headline3;
expect(style.fontSize, 20);
expect(style.color, PinballColors.darkBlue);
});
test('headline4 has fontSize 16 and white color', () {
const style = PinballTextStyle.headline4;
expect(style.fontSize, 16);
expect(style.color, PinballColors.white);
});
test('subtitle1 has fontSize 12 and yellow color', () {
const style = PinballTextStyle.subtitle1;
expect(style.fontSize, 12);
expect(style.color, PinballColors.yellow);
});
});
}
| pinball/packages/pinball_ui/test/src/theme/pinball_text_style_test.dart/0 | {
"file_path": "pinball/packages/pinball_ui/test/src/theme/pinball_text_style_test.dart",
"repo_id": "pinball",
"token_count": 409
} | 1,190 |
include: package:very_good_analysis/analysis_options.2.4.0.yaml | pinball/packages/share_repository/analysis_options.yaml/0 | {
"file_path": "pinball/packages/share_repository/analysis_options.yaml",
"repo_id": "pinball",
"token_count": 22
} | 1,191 |
// ignore_for_file: cascade_invocations
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/game.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
Future<void> pump(
BonusNoiseBehavior child, {
required PinballAudioPlayer audioPlayer,
required GameBloc bloc,
}) {
return ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: bloc,
children: [
FlameProvider<PinballAudioPlayer>.value(
audioPlayer,
children: [
child,
],
),
],
),
);
}
}
class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {}
class _MockGameBloc extends Mock implements GameBloc {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('BonusNoiseBehavior', () {
late PinballAudioPlayer audioPlayer;
late GameBloc bloc;
final flameTester = FlameTester(_TestGame.new);
setUpAll(() {
registerFallbackValue(PinballAudio.google);
});
setUp(() {
audioPlayer = _MockPinballAudioPlayer();
when(() => audioPlayer.play(any())).thenAnswer((_) {});
bloc = _MockGameBloc();
});
flameTester.testGameWidget(
'plays google sound',
setUp: (game, _) async {
const state = GameState(
totalScore: 0,
roundScore: 0,
multiplier: 1,
rounds: 0,
bonusHistory: [GameBonus.googleWord],
status: GameStatus.playing,
);
const initialState = GameState.initial();
whenListen(
bloc,
Stream.fromIterable([initialState, state]),
initialState: initialState,
);
final behavior = BonusNoiseBehavior();
await game.pump(behavior, audioPlayer: audioPlayer, bloc: bloc);
},
verify: (_, __) async {
verify(() => audioPlayer.play(PinballAudio.google)).called(1);
},
);
flameTester.testGameWidget(
'plays sparky sound',
setUp: (game, _) async {
const state = GameState(
totalScore: 0,
roundScore: 0,
multiplier: 1,
rounds: 0,
bonusHistory: [GameBonus.sparkyTurboCharge],
status: GameStatus.playing,
);
const initialState = GameState.initial();
whenListen(
bloc,
Stream.fromIterable([initialState, state]),
initialState: initialState,
);
final behavior = BonusNoiseBehavior();
await game.pump(behavior, audioPlayer: audioPlayer, bloc: bloc);
},
verify: (_, __) async {
verify(() => audioPlayer.play(PinballAudio.sparky)).called(1);
},
);
flameTester.testGameWidget(
'plays dino chomp sound',
setUp: (game, _) async {
const state = GameState(
totalScore: 0,
roundScore: 0,
multiplier: 1,
rounds: 0,
bonusHistory: [GameBonus.dinoChomp],
status: GameStatus.playing,
);
const initialState = GameState.initial();
whenListen(
bloc,
Stream.fromIterable([initialState, state]),
initialState: initialState,
);
final behavior = BonusNoiseBehavior();
await game.pump(behavior, audioPlayer: audioPlayer, bloc: bloc);
},
verify: (_, __) async {
verify(() => audioPlayer.play(PinballAudio.dino)).called(1);
},
);
flameTester.testGameWidget(
'plays android spaceship sound',
setUp: (game, _) async {
const state = GameState(
totalScore: 0,
roundScore: 0,
multiplier: 1,
rounds: 0,
bonusHistory: [GameBonus.androidSpaceship],
status: GameStatus.playing,
);
const initialState = GameState.initial();
whenListen(
bloc,
Stream.fromIterable([initialState, state]),
initialState: initialState,
);
final behavior = BonusNoiseBehavior();
await game.pump(behavior, audioPlayer: audioPlayer, bloc: bloc);
},
verify: (_, __) async {
verify(() => audioPlayer.play(PinballAudio.android)).called(1);
},
);
flameTester.testGameWidget(
'plays dash nest sound',
setUp: (game, _) async {
const state = GameState(
totalScore: 0,
roundScore: 0,
multiplier: 1,
rounds: 0,
bonusHistory: [GameBonus.dashNest],
status: GameStatus.playing,
);
const initialState = GameState.initial();
whenListen(
bloc,
Stream.fromIterable([initialState, state]),
initialState: initialState,
);
final behavior = BonusNoiseBehavior();
await game.pump(behavior, audioPlayer: audioPlayer, bloc: bloc);
},
verify: (_, __) async {
verify(() => audioPlayer.play(PinballAudio.dash)).called(1);
},
);
});
}
| pinball/test/game/behaviors/bonus_noise_behavior_test.dart/0 | {
"file_path": "pinball/test/game/behaviors/bonus_noise_behavior_test.dart",
"repo_id": "pinball",
"token_count": 2376
} | 1,192 |
// ignore_for_file: cascade_invocations, prefer_const_constructors
import 'dart:async';
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.android.ramp.boardOpening.keyName,
Assets.images.android.ramp.railingForeground.keyName,
Assets.images.android.ramp.railingBackground.keyName,
Assets.images.android.ramp.main.keyName,
Assets.images.android.ramp.arrow.inactive.keyName,
Assets.images.android.ramp.arrow.active1.keyName,
Assets.images.android.ramp.arrow.active2.keyName,
Assets.images.android.ramp.arrow.active3.keyName,
Assets.images.android.ramp.arrow.active4.keyName,
Assets.images.android.ramp.arrow.active5.keyName,
Assets.images.android.rail.main.keyName,
Assets.images.android.rail.exit.keyName,
Assets.images.score.fiveThousand.keyName,
]);
}
Future<void> pump(
SpaceshipRamp child, {
required GameBloc gameBloc,
required SpaceshipRampCubit bloc,
}) async {
await ensureAdd(
FlameMultiBlocProvider(
providers: [
FlameBlocProvider<GameBloc, GameState>.value(
value: gameBloc,
),
FlameBlocProvider<SpaceshipRampCubit, SpaceshipRampState>.value(
value: bloc,
),
],
children: [
ZCanvasComponent(children: [child]),
],
),
);
}
}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockSpaceshipRampCubit extends Mock implements SpaceshipRampCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('RampResetBehavior', () {
late GameBloc gameBloc;
setUp(() {
gameBloc = _MockGameBloc();
});
final flameTester = FlameTester(_TestGame.new);
flameTester.test(
'calls onReset when round lost',
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = GameState.initial();
final streamController = StreamController<GameState>();
whenListen(
gameBloc,
streamController.stream,
initialState: state,
);
final behavior = RampResetBehavior();
final parent = SpaceshipRamp.test(
children: [behavior],
);
await game.pump(
parent,
gameBloc: gameBloc,
bloc: bloc,
);
streamController.add(state.copyWith(rounds: state.rounds - 1));
await Future<void>.delayed(Duration.zero);
verify(bloc.onReset).called(1);
},
);
flameTester.test(
"doesn't call onReset when round stays the same",
(game) async {
final bloc = _MockSpaceshipRampCubit();
final state = GameState.initial();
final streamController = StreamController<GameState>();
whenListen(
gameBloc,
streamController.stream,
initialState: state,
);
final behavior = RampResetBehavior();
final parent = SpaceshipRamp.test(
children: [behavior],
);
await game.pump(
parent,
gameBloc: gameBloc,
bloc: bloc,
);
streamController
.add(state.copyWith(roundScore: state.roundScore + 100));
await Future<void>.delayed(Duration.zero);
verifyNever(bloc.onReset);
},
);
});
}
| pinball/test/game/components/android_acres/behaviors/ramp_reset_behavior_test.dart/0 | {
"file_path": "pinball/test/game/components/android_acres/behaviors/ramp_reset_behavior_test.dart",
"repo_id": "pinball",
"token_count": 1694
} | 1,193 |
// 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/components/dino_desert/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.dino.animatronic.head.keyName,
Assets.images.dino.animatronic.mouth.keyName,
Assets.images.dino.topWall.keyName,
Assets.images.dino.topWallTunnel.keyName,
Assets.images.dino.bottomWall.keyName,
Assets.images.slingshot.upper.keyName,
Assets.images.slingshot.lower.keyName,
]);
}
Future<void> pump(DinoDesert child) async {
await ensureAdd(
FlameBlocProvider<GameBloc, GameState>.value(
value: _MockGameBloc(),
children: [child],
),
);
}
}
class _MockGameBloc extends Mock implements GameBloc {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('DinoDesert', () {
flameTester.test('loads correctly', (game) async {
final component = DinoDesert();
await game.pump(component);
expect(game.descendants(), contains(component));
});
group('loads', () {
flameTester.test(
'a ChromeDino',
(game) async {
await game.pump(DinoDesert());
expect(
game.descendants().whereType<ChromeDino>().length,
equals(1),
);
},
);
flameTester.test(
'DinoWalls',
(game) async {
await game.pump(DinoDesert());
expect(
game.descendants().whereType<DinoWalls>().length,
equals(1),
);
},
);
flameTester.test(
'Slingshots',
(game) async {
await game.pump(DinoDesert());
expect(
game.descendants().whereType<Slingshots>().length,
equals(1),
);
},
);
});
group('adds', () {
flameTester.test(
'ScoringContactBehavior to ChromeDino',
(game) async {
await game.pump(DinoDesert());
final chromeDino = game.descendants().whereType<ChromeDino>().single;
expect(
chromeDino.firstChild<ScoringContactBehavior>(),
isNotNull,
);
},
);
flameTester.test('a ChromeDinoBonusBehavior', (game) async {
final component = DinoDesert();
await game.pump(component);
expect(
component.children.whereType<ChromeDinoBonusBehavior>().single,
isNotNull,
);
});
});
});
}
| pinball/test/game/components/dino_desert/dino_desert_test.dart/0 | {
"file_path": "pinball/test/game/components/dino_desert/dino_desert_test.dart",
"repo_id": "pinball",
"token_count": 1372
} | 1,194 |
// ignore_for_file: cascade_invocations
import 'dart:ui';
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leaderboard_repository/src/leaderboard_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball_audio/src/pinball_audio.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:platform_helper/platform_helper.dart';
import 'package:share_repository/share_repository.dart';
class _TestPinballGame extends PinballGame {
_TestPinballGame()
: super(
characterThemeBloc: CharacterThemeCubit(),
leaderboardRepository: _MockLeaderboardRepository(),
shareRepository: _MockShareRepository(),
gameBloc: GameBloc(),
l10n: _MockAppLocalizations(),
audioPlayer: _MockPinballAudioPlayer(),
platformHelper: _MockPlatformHelper(),
);
@override
Future<void> onLoad() async {
images.prefix = '';
final futures = preLoadAssets().map((loadableBuilder) => loadableBuilder());
await Future.wait<void>(futures);
await super.onLoad();
}
}
class _TestDebugPinballGame extends DebugPinballGame {
_TestDebugPinballGame()
: super(
characterThemeBloc: CharacterThemeCubit(),
leaderboardRepository: _MockLeaderboardRepository(),
shareRepository: _MockShareRepository(),
gameBloc: GameBloc(),
l10n: _MockAppLocalizations(),
audioPlayer: _MockPinballAudioPlayer(),
platformHelper: _MockPlatformHelper(),
);
@override
Future<void> onLoad() async {
images.prefix = '';
final futures = preLoadAssets().map((loadableBuilder) => loadableBuilder());
await Future.wait<void>(futures);
await super.onLoad();
}
}
class _MockGameBloc extends Mock implements GameBloc {}
class _MockAppLocalizations extends Mock implements AppLocalizations {
@override
String get leaderboardErrorMessage => '';
}
class _MockEventPosition extends Mock implements EventPosition {}
class _MockTapDownDetails extends Mock implements TapDownDetails {}
class _MockTapDownInfo extends Mock implements TapDownInfo {}
class _MockTapUpDetails extends Mock implements TapUpDetails {}
class _MockTapUpInfo extends Mock implements TapUpInfo {}
class _MockDragStartInfo extends Mock implements DragStartInfo {}
class _MockDragUpdateInfo extends Mock implements DragUpdateInfo {}
class _MockDragEndInfo extends Mock implements DragEndInfo {}
class _MockLeaderboardRepository extends Mock implements LeaderboardRepository {
}
class _MockShareRepository extends Mock implements ShareRepository {}
class _MockPinballAudioPlayer extends Mock implements PinballAudioPlayer {}
class _MockPlatformHelper extends Mock implements PlatformHelper {
@override
bool get isMobile => false;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late GameBloc gameBloc;
setUp(() {
gameBloc = _MockGameBloc();
whenListen(
gameBloc,
const Stream<GameState>.empty(),
initialState: const GameState.initial(),
);
});
group('PinballGame', () {
final flameTester = FlameTester(_TestPinballGame.new);
group('components', () {
flameTester.test(
'has only one BallSpawningBehavior',
(game) async {
await game.ready();
expect(
game.descendants().whereType<BallSpawningBehavior>().length,
equals(1),
);
},
);
flameTester.test(
'has only one CharacterSelectionBehavior',
(game) async {
await game.ready();
expect(
game.descendants().whereType<CharacterSelectionBehavior>().length,
equals(1),
);
},
);
flameTester.test(
'has only one Drain',
(game) async {
await game.ready();
expect(
game.descendants().whereType<Drain>().length,
equals(1),
);
},
);
flameTester.test(
'has only one BottomGroup',
(game) async {
await game.ready();
expect(
game.descendants().whereType<BottomGroup>().length,
equals(1),
);
},
);
flameTester.test(
'has only one Launcher',
(game) async {
await game.ready();
expect(
game.descendants().whereType<Launcher>().length,
equals(1),
);
},
);
flameTester.test(
'has one FlutterForest',
(game) async {
await game.ready();
expect(
game.descendants().whereType<FlutterForest>().length,
equals(1),
);
},
);
flameTester.test(
'has only one Multiballs',
(game) async {
await game.ready();
expect(
game.descendants().whereType<Multiballs>().length,
equals(1),
);
},
);
flameTester.test(
'one GoogleGallery',
(game) async {
await game.ready();
expect(
game.descendants().whereType<GoogleGallery>().length,
equals(1),
);
},
);
flameTester.test('one SkillShot', (game) async {
await game.ready();
expect(
game.descendants().whereType<SkillShot>().length,
equals(1),
);
});
flameTester.testGameWidget(
'paints sprites with FilterQuality.medium',
setUp: (game, tester) async {
game.images.prefix = '';
final futures =
game.preLoadAssets().map((loadableBuilder) => loadableBuilder());
await Future.wait<void>(futures);
await game.ready();
final descendants = game.descendants();
final components = [
...descendants.whereType<SpriteComponent>(),
...descendants.whereType<SpriteGroupComponent>(),
];
expect(components, isNotEmpty);
expect(
components.whereType<HasPaint>().length,
equals(components.length),
);
await tester.pump();
for (final component in components) {
if (component is! HasPaint) return;
expect(
component.paint.filterQuality,
equals(FilterQuality.medium),
);
}
},
);
});
group('flipper control', () {
flameTester.test('tap control only works if game is playing',
(game) async {
await game.ready();
final gameBloc = game
.descendants()
.whereType<FlameBlocProvider<GameBloc, GameState>>()
.first
.bloc;
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(Vector2.zero());
when(() => eventPosition.widget).thenReturn(Vector2.zero());
final raw = _MockTapDownDetails();
when(() => raw.kind).thenReturn(PointerDeviceKind.touch);
final tapDownEvent = _MockTapDownInfo();
when(() => tapDownEvent.eventPosition).thenReturn(eventPosition);
when(() => tapDownEvent.raw).thenReturn(raw);
final flipperBloc = game
.descendants()
.whereType<Flipper>()
.where((flipper) => flipper.side == BoardSide.left)
.single
.descendants()
.whereType<FlameBlocProvider<FlipperCubit, FlipperState>>()
.first
.bloc;
gameBloc.emit(gameBloc.state.copyWith(status: GameStatus.gameOver));
game.onTapDown(0, tapDownEvent);
await Future<void>.delayed(Duration.zero);
expect(flipperBloc.state, FlipperState.movingDown);
gameBloc.emit(gameBloc.state.copyWith(status: GameStatus.playing));
game.onTapDown(0, tapDownEvent);
await Future<void>.delayed(Duration.zero);
expect(flipperBloc.state, FlipperState.movingUp);
});
flameTester.test('tap down moves left flipper up', (game) async {
await game.ready();
final gameBloc = game
.descendants()
.whereType<FlameBlocProvider<GameBloc, GameState>>()
.first
.bloc;
gameBloc.emit(gameBloc.state.copyWith(status: GameStatus.playing));
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(Vector2.zero());
when(() => eventPosition.widget).thenReturn(Vector2.zero());
final raw = _MockTapDownDetails();
when(() => raw.kind).thenReturn(PointerDeviceKind.touch);
final tapDownEvent = _MockTapDownInfo();
when(() => tapDownEvent.eventPosition).thenReturn(eventPosition);
when(() => tapDownEvent.raw).thenReturn(raw);
game.onTapDown(0, tapDownEvent);
await Future<void>.delayed(Duration.zero);
final flipperBloc = game
.descendants()
.whereType<Flipper>()
.where((flipper) => flipper.side == BoardSide.left)
.single
.descendants()
.whereType<FlameBlocProvider<FlipperCubit, FlipperState>>()
.first
.bloc;
expect(flipperBloc.state, FlipperState.movingUp);
});
flameTester.test('tap down moves right flipper up', (game) async {
await game.ready();
final gameBloc = game
.descendants()
.whereType<FlameBlocProvider<GameBloc, GameState>>()
.first
.bloc;
gameBloc.emit(gameBloc.state.copyWith(status: GameStatus.playing));
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(Vector2.zero());
when(() => eventPosition.widget).thenReturn(game.canvasSize);
final raw = _MockTapDownDetails();
when(() => raw.kind).thenReturn(PointerDeviceKind.touch);
final tapDownEvent = _MockTapDownInfo();
when(() => tapDownEvent.eventPosition).thenReturn(eventPosition);
when(() => tapDownEvent.raw).thenReturn(raw);
game.onTapDown(0, tapDownEvent);
final flipperBloc = game
.descendants()
.whereType<Flipper>()
.where((flipper) => flipper.side == BoardSide.right)
.single
.descendants()
.whereType<FlameBlocProvider<FlipperCubit, FlipperState>>()
.first
.bloc;
await Future<void>.delayed(Duration.zero);
expect(flipperBloc.state, FlipperState.movingUp);
});
flameTester.test('tap up moves flipper down', (game) async {
await game.ready();
final gameBloc = game
.descendants()
.whereType<FlameBlocProvider<GameBloc, GameState>>()
.first
.bloc;
gameBloc.emit(gameBloc.state.copyWith(status: GameStatus.playing));
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(Vector2.zero());
when(() => eventPosition.widget).thenReturn(Vector2.zero());
final tapUpEvent = _MockTapUpInfo();
when(() => tapUpEvent.eventPosition).thenReturn(eventPosition);
game.onTapUp(0, tapUpEvent);
await game.ready();
final flipperBloc = game
.descendants()
.whereType<Flipper>()
.where((flipper) => flipper.side == BoardSide.left)
.single
.descendants()
.whereType<FlameBlocProvider<FlipperCubit, FlipperState>>()
.first
.bloc;
expect(flipperBloc.state, FlipperState.movingDown);
});
flameTester.test('tap cancel moves flipper down', (game) async {
await game.ready();
final gameBloc = game
.descendants()
.whereType<FlameBlocProvider<GameBloc, GameState>>()
.first
.bloc;
gameBloc.emit(gameBloc.state.copyWith(status: GameStatus.playing));
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(Vector2.zero());
when(() => eventPosition.widget).thenReturn(Vector2.zero());
final raw = _MockTapDownDetails();
when(() => raw.kind).thenReturn(PointerDeviceKind.touch);
final tapDownEvent = _MockTapDownInfo();
when(() => tapDownEvent.eventPosition).thenReturn(eventPosition);
when(() => tapDownEvent.raw).thenReturn(raw);
final flipperBloc = game
.descendants()
.whereType<Flipper>()
.where((flipper) => flipper.side == BoardSide.left)
.single
.descendants()
.whereType<FlameBlocProvider<FlipperCubit, FlipperState>>()
.first
.bloc;
game.onTapDown(0, tapDownEvent);
game.onTapCancel(0);
expect(flipperBloc.state, FlipperState.movingDown);
});
flameTester.test(
'multiple touches control both flippers',
(game) async {
await game.ready();
final gameBloc = game
.descendants()
.whereType<FlameBlocProvider<GameBloc, GameState>>()
.first
.bloc;
gameBloc.emit(gameBloc.state.copyWith(status: GameStatus.playing));
final raw = _MockTapDownDetails();
when(() => raw.kind).thenReturn(PointerDeviceKind.touch);
final leftEventPosition = _MockEventPosition();
when(() => leftEventPosition.game).thenReturn(Vector2.zero());
when(() => leftEventPosition.widget).thenReturn(Vector2.zero());
final rightEventPosition = _MockEventPosition();
when(() => rightEventPosition.game).thenReturn(Vector2.zero());
when(() => rightEventPosition.widget).thenReturn(game.canvasSize);
final leftTapDownEvent = _MockTapDownInfo();
when(() => leftTapDownEvent.eventPosition)
.thenReturn(leftEventPosition);
when(() => leftTapDownEvent.raw).thenReturn(raw);
final rightTapDownEvent = _MockTapDownInfo();
when(() => rightTapDownEvent.eventPosition)
.thenReturn(rightEventPosition);
when(() => rightTapDownEvent.raw).thenReturn(raw);
game.onTapDown(0, leftTapDownEvent);
game.onTapDown(1, rightTapDownEvent);
final flippers = game.descendants().whereType<Flipper>();
final rightFlipper = flippers.elementAt(0);
final leftFlipper = flippers.elementAt(1);
final leftFlipperBloc = leftFlipper
.descendants()
.whereType<FlameBlocProvider<FlipperCubit, FlipperState>>()
.first
.bloc;
final rightFlipperBloc = rightFlipper
.descendants()
.whereType<FlameBlocProvider<FlipperCubit, FlipperState>>()
.first
.bloc;
expect(leftFlipperBloc.state, equals(FlipperState.movingUp));
expect(rightFlipperBloc.state, equals(FlipperState.movingUp));
expect(
game.focusedBoardSide,
equals({0: BoardSide.left, 1: BoardSide.right}),
);
},
);
});
group('plunger control', () {
flameTester.test('plunger control tap down emits plunging', (game) async {
await game.ready();
final gameBloc = game
.descendants()
.whereType<FlameBlocProvider<GameBloc, GameState>>()
.first
.bloc;
gameBloc.emit(gameBloc.state.copyWith(status: GameStatus.playing));
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(Vector2(40, 60));
final raw = _MockTapDownDetails();
when(() => raw.kind).thenReturn(PointerDeviceKind.touch);
final tapDownEvent = _MockTapDownInfo();
when(() => tapDownEvent.eventPosition).thenReturn(eventPosition);
when(() => tapDownEvent.raw).thenReturn(raw);
game.onTapDown(0, tapDownEvent);
final plungerBloc = game
.descendants()
.whereType<FlameBlocProvider<PlungerCubit, PlungerState>>()
.single
.bloc;
expect(plungerBloc.state, PlungerState.autoPulling);
});
});
});
group('DebugPinballGame', () {
final flameTester = FlameTester(_TestDebugPinballGame.new);
flameTester.test(
'adds a ball on tap up',
(game) async {
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(Vector2.all(10));
final raw = _MockTapUpDetails();
when(() => raw.kind).thenReturn(PointerDeviceKind.mouse);
final tapUpEvent = _MockTapUpInfo();
when(() => tapUpEvent.eventPosition).thenReturn(eventPosition);
when(() => tapUpEvent.raw).thenReturn(raw);
await game.ready();
final previousBalls = game.descendants().whereType<Ball>().toList();
game.onTapUp(0, tapUpEvent);
await game.ready();
final currentBalls = game.descendants().whereType<Ball>().toList();
expect(
currentBalls.length,
equals(previousBalls.length + 1),
);
},
);
flameTester.test(
'set lineStart on pan start',
(game) async {
final startPosition = Vector2.all(10);
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(startPosition);
final dragStartInfo = _MockDragStartInfo();
when(() => dragStartInfo.eventPosition).thenReturn(eventPosition);
game.onPanStart(dragStartInfo);
await game.ready();
expect(
game.lineStart,
equals(startPosition),
);
},
);
flameTester.test(
'set lineEnd on pan update',
(game) async {
final endPosition = Vector2.all(10);
final eventPosition = _MockEventPosition();
when(() => eventPosition.game).thenReturn(endPosition);
final dragUpdateInfo = _MockDragUpdateInfo();
when(() => dragUpdateInfo.eventPosition).thenReturn(eventPosition);
game.onPanUpdate(dragUpdateInfo);
await game.ready();
expect(
game.lineEnd,
equals(endPosition),
);
},
);
flameTester.test(
'launch ball on pan end',
(game) async {
final startPosition = Vector2.zero();
final endPosition = Vector2.all(10);
game.lineStart = startPosition;
game.lineEnd = endPosition;
await game.ready();
final previousBalls = game.descendants().whereType<Ball>().toList();
game.onPanEnd(_MockDragEndInfo());
await game.ready();
expect(
game.descendants().whereType<Ball>().length,
equals(previousBalls.length + 1),
);
},
);
});
}
| pinball/test/game/pinball_game_test.dart/0 | {
"file_path": "pinball/test/game/pinball_game_test.dart",
"repo_id": "pinball",
"token_count": 8576
} | 1,195 |
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball_theme/pinball_theme.dart';
void main() {
group('CharacterThemeCubit', () {
test('initial state has Dash character theme', () {
final characterThemeCubit = CharacterThemeCubit();
expect(
characterThemeCubit.state.characterTheme,
equals(const DashTheme()),
);
});
blocTest<CharacterThemeCubit, CharacterThemeState>(
'characterSelected emits selected character theme',
build: CharacterThemeCubit.new,
act: (bloc) => bloc.characterSelected(const SparkyTheme()),
expect: () => [
const CharacterThemeState(SparkyTheme()),
],
);
});
}
| pinball/test/select_character/cubit/character_theme_cubit_test.dart/0 | {
"file_path": "pinball/test/select_character/cubit/character_theme_cubit_test.dart",
"repo_id": "pinball",
"token_count": 293
} | 1,196 |
{
"name": "Pinball",
"short_name": "Pinball",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "Google I/O 2022 Pinball game built with Flutter and Firebase",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
| pinball/web/manifest.json/0 | {
"file_path": "pinball/web/manifest.json",
"repo_id": "pinball",
"token_count": 312
} | 1,197 |
tasks:
- name: prepare tool
script: .ci/scripts/prepare_tool.sh
- name: build examples
script: script/tool_runner.sh
args: ["build-examples", "--macos"]
- name: xcode analyze
script: script/tool_runner.sh
args: ["xcode-analyze", "--macos"]
- name: xcode analyze deprecation
# Ensure we don't accidentally introduce deprecated code.
script: script/tool_runner.sh
args: ["xcode-analyze", "--macos", "--macos-min-version=12.3"]
- name: native test
script: script/tool_runner.sh
args: ["native-test", "--macos"]
- name: drive examples
script: script/tool_runner.sh
args: ["drive-examples", "--macos", "--exclude=script/configs/exclude_integration_macos.yaml"]
| plugins/.ci/targets/macos_platform_tests.yaml/0 | {
"file_path": "plugins/.ci/targets/macos_platform_tests.yaml",
"repo_id": "plugins",
"token_count": 268
} | 1,198 |
# Specify analysis options.
#
# This file is a copy of analysis_options.yaml from flutter repo
# as of 2022-07-27, but with some modifications marked with
# "DIFFERENT FROM FLUTTER/FLUTTER" below. The file is expected to
# be kept in sync with the master file from the flutter repo.
analyzer:
language:
strict-casts: true
strict-raw-types: true
errors:
# allow self-reference to deprecated members (we do this because otherwise we have
# to annotate every member in every test, assert, etc, when we deprecate something)
deprecated_member_use_from_same_package: ignore
# Turned off until null-safe rollout is complete.
unnecessary_null_comparison: ignore
exclude: # DIFFERENT FROM FLUTTER/FLUTTER
# Ignore generated files
- '**/*.g.dart'
- '**/*.mocks.dart' # Mockito @GenerateMocks
linter:
rules:
# This list is derived from the list of all available lints located at
# https://github.com/dart-lang/linter/blob/master/example/all.yaml
- always_declare_return_types
- always_put_control_body_on_new_line
# - always_put_required_named_parameters_first # we prefer having parameters in the same order as fields https://github.com/flutter/flutter/issues/10219
- always_require_non_null_named_parameters
- always_specify_types
# - always_use_package_imports # we do this commonly
- annotate_overrides
# - avoid_annotating_with_dynamic # conflicts with always_specify_types
- avoid_bool_literals_in_conditional_expressions
# - avoid_catches_without_on_clauses # blocked on https://github.com/dart-lang/linter/issues/3023
# - avoid_catching_errors # blocked on https://github.com/dart-lang/linter/issues/3023
- avoid_classes_with_only_static_members
- avoid_double_and_int_checks
- avoid_dynamic_calls
- avoid_empty_else
- avoid_equals_and_hash_code_on_mutable_classes
- avoid_escaping_inner_quotes
- avoid_field_initializers_in_const_classes
# - avoid_final_parameters # incompatible with prefer_final_parameters
- avoid_function_literals_in_foreach_calls
- avoid_implementing_value_types
- avoid_init_to_null
- avoid_js_rounded_ints
# - avoid_multiple_declarations_per_line # seems to be a stylistic choice we don't subscribe to
- avoid_null_checks_in_equality_operators
# - avoid_positional_boolean_parameters # would have been nice to enable this but by now there's too many places that break it
- avoid_print
# - avoid_private_typedef_functions # we prefer having typedef (discussion in https://github.com/flutter/flutter/pull/16356)
- avoid_redundant_argument_values
- avoid_relative_lib_imports
- avoid_renaming_method_parameters
- avoid_return_types_on_setters
- avoid_returning_null
- avoid_returning_null_for_future
- avoid_returning_null_for_void
# - avoid_returning_this # there are enough valid reasons to return `this` that this lint ends up with too many false positives
- avoid_setters_without_getters
- avoid_shadowing_type_parameters
- avoid_single_cascade_in_expression_statements
- avoid_slow_async_io
- avoid_type_to_string
- avoid_types_as_parameter_names
# - avoid_types_on_closure_parameters # conflicts with always_specify_types
- avoid_unnecessary_containers
- avoid_unused_constructor_parameters
- avoid_void_async
# - avoid_web_libraries_in_flutter # we use web libraries in web-specific code, and our tests prevent us from using them elsewhere
- await_only_futures
- camel_case_extensions
- camel_case_types
- cancel_subscriptions
# - cascade_invocations # doesn't match the typical style of this repo
- cast_nullable_to_non_nullable
# - close_sinks # not reliable enough
# - combinators_ordering # DIFFERENT FROM FLUTTER/FLUTTER: This isn't available on stable yet.
# - comment_references # blocked on https://github.com/dart-lang/linter/issues/1142
- conditional_uri_does_not_exist
# - constant_identifier_names # needs an opt-out https://github.com/dart-lang/linter/issues/204
- control_flow_in_finally
- curly_braces_in_flow_control_structures
- depend_on_referenced_packages
- deprecated_consistency
# - diagnostic_describe_all_properties # enabled only at the framework level (packages/flutter/lib)
- directives_ordering
# - discarded_futures # not yet tested
# - do_not_use_environment # there are appropriate times to use the environment, especially in our tests and build logic
- empty_catches
- empty_constructor_bodies
- empty_statements
- eol_at_end_of_file
- exhaustive_cases
- file_names
- flutter_style_todos
- hash_and_equals
- implementation_imports
- iterable_contains_unrelated_type
# - join_return_with_assignment # not required by flutter style
- leading_newlines_in_multiline_strings
- library_names
- library_prefixes
- library_private_types_in_public_api
# - lines_longer_than_80_chars # not required by flutter style
- list_remove_unrelated_type
# - literal_only_boolean_expressions # too many false positives: https://github.com/dart-lang/linter/issues/453
- missing_whitespace_between_adjacent_strings
- no_adjacent_strings_in_list
- no_default_cases
- no_duplicate_case_values
- no_leading_underscores_for_library_prefixes
- no_leading_underscores_for_local_identifiers
- no_logic_in_create_state
- no_runtimeType_toString # DIFFERENT FROM FLUTTER/FLUTTER
- non_constant_identifier_names
- noop_primitive_operations
- null_check_on_nullable_type_parameter
- null_closures
# - omit_local_variable_types # opposite of always_specify_types
# - one_member_abstracts # too many false positives
- only_throw_errors # this does get disabled in a few places where we have legacy code that uses strings et al
- overridden_fields
- package_api_docs
- package_names
- package_prefixed_library_names
# - parameter_assignments # we do this commonly
- prefer_adjacent_string_concatenation
- prefer_asserts_in_initializer_lists
# - prefer_asserts_with_message # not required by flutter style
- prefer_collection_literals
- prefer_conditional_assignment
- prefer_const_constructors
- prefer_const_constructors_in_immutables
- prefer_const_declarations
- prefer_const_literals_to_create_immutables
# - prefer_constructors_over_static_methods # far too many false positives
- prefer_contains
# - prefer_double_quotes # opposite of prefer_single_quotes
- prefer_equal_for_default_values
# - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods
- prefer_final_fields
- prefer_final_in_for_each
- prefer_final_locals
# - prefer_final_parameters # we should enable this one day when it can be auto-fixed (https://github.com/dart-lang/linter/issues/3104), see also parameter_assignments
- prefer_for_elements_to_map_fromIterable
- prefer_foreach
- prefer_function_declarations_over_variables
- prefer_generic_function_type_aliases
- prefer_if_elements_to_conditional_expressions
- prefer_if_null_operators
- prefer_initializing_formals
- prefer_inlined_adds
# - prefer_int_literals # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#use-double-literals-for-double-constants
- prefer_interpolation_to_compose_strings
- prefer_is_empty
- prefer_is_not_empty
- prefer_is_not_operator
- prefer_iterable_whereType
# - prefer_mixin # Has false positives, see https://github.com/dart-lang/linter/issues/3018
# - prefer_null_aware_method_calls # "call()" is confusing to people new to the language since it's not documented anywhere
- prefer_null_aware_operators
- prefer_relative_imports
- prefer_single_quotes
- prefer_spread_collections
- prefer_typing_uninitialized_variables
- prefer_void_to_null
- provide_deprecation_message
- public_member_api_docs # DIFFERENT FROM FLUTTER/FLUTTER
- recursive_getters
# - require_trailing_commas # blocked on https://github.com/dart-lang/sdk/issues/47441
- secure_pubspec_urls
- sized_box_for_whitespace
# - sized_box_shrink_expand # not yet tested
- slash_for_doc_comments
- sort_child_properties_last
- sort_constructors_first
- sort_pub_dependencies # DIFFERENT FROM FLUTTER/FLUTTER: Flutter's use case for not sorting does not apply to this repository.
- sort_unnamed_constructors_first
- test_types_in_equals
- throw_in_finally
- tighten_type_of_initializing_formals
# - type_annotate_public_apis # subset of always_specify_types
- type_init_formals
# - unawaited_futures # too many false positives, especially with the way AnimationController works
- unnecessary_await_in_return
- unnecessary_brace_in_string_interps
- unnecessary_const
- unnecessary_constructor_name
# - unnecessary_final # conflicts with prefer_final_locals
- unnecessary_getters_setters
# - unnecessary_lambdas # has false positives: https://github.com/dart-lang/linter/issues/498
- unnecessary_late
- unnecessary_new
- unnecessary_null_aware_assignments
- unnecessary_null_aware_operator_on_extension_on_nullable
- unnecessary_null_checks
- unnecessary_null_in_if_null_operators
- unnecessary_nullable_for_final_variable_declarations
- unnecessary_overrides
- unnecessary_parenthesis
# - unnecessary_raw_strings # what's "necessary" is a matter of opinion; consistency across strings can help readability more than this lint
- unnecessary_statements
- unnecessary_string_escapes
- unnecessary_string_interpolations
- unnecessary_this
- unnecessary_to_list_in_spreads
- unrelated_type_equality_checks
- unsafe_html
- use_build_context_synchronously
# - use_colored_box # not yet tested
# - use_decorated_box # not yet tested
# - use_enums # not yet tested
- use_full_hex_values_for_flutter_colors
- use_function_type_syntax_for_parameters
- use_if_null_to_convert_nulls_to_bools
- use_is_even_rather_than_modulo
- use_key_in_widget_constructors
- use_late_for_private_fields_and_variables
- use_named_constants
- use_raw_strings
- use_rethrow_when_possible
- use_setters_to_change_properties
# - use_string_buffers # has false positives: https://github.com/dart-lang/sdk/issues/34182
- use_super_parameters
- use_test_throws_matchers
# - use_to_and_as_if_applicable # has false positives, so we prefer to catch this by code-review
- valid_regexps
- void_checks
| plugins/analysis_options.yaml/0 | {
"file_path": "plugins/analysis_options.yaml",
"repo_id": "plugins",
"token_count": 3821
} | 1,199 |
// 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.noisereduction;
import android.hardware.camera2.CaptureRequest;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.Log;
import io.flutter.plugins.camera.CameraProperties;
import io.flutter.plugins.camera.features.CameraFeature;
import java.util.HashMap;
/**
* This can either be enabled or disabled. Only full capability devices can set this to off. Legacy
* and full support the fast mode.
* https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES
*/
public class NoiseReductionFeature extends CameraFeature<NoiseReductionMode> {
private NoiseReductionMode currentSetting = NoiseReductionMode.fast;
private final HashMap<NoiseReductionMode, Integer> NOISE_REDUCTION_MODES = new HashMap<>();
/**
* Creates a new instance of the {@link NoiseReductionFeature}.
*
* @param cameraProperties Collection of the characteristics for the current camera device.
*/
public NoiseReductionFeature(CameraProperties cameraProperties) {
super(cameraProperties);
NOISE_REDUCTION_MODES.put(NoiseReductionMode.off, CaptureRequest.NOISE_REDUCTION_MODE_OFF);
NOISE_REDUCTION_MODES.put(NoiseReductionMode.fast, CaptureRequest.NOISE_REDUCTION_MODE_FAST);
NOISE_REDUCTION_MODES.put(
NoiseReductionMode.highQuality, CaptureRequest.NOISE_REDUCTION_MODE_HIGH_QUALITY);
if (VERSION.SDK_INT >= VERSION_CODES.M) {
NOISE_REDUCTION_MODES.put(
NoiseReductionMode.minimal, CaptureRequest.NOISE_REDUCTION_MODE_MINIMAL);
NOISE_REDUCTION_MODES.put(
NoiseReductionMode.zeroShutterLag, CaptureRequest.NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG);
}
}
@Override
public String getDebugName() {
return "NoiseReductionFeature";
}
@Override
public NoiseReductionMode getValue() {
return currentSetting;
}
@Override
public void setValue(NoiseReductionMode value) {
this.currentSetting = value;
}
@Override
public boolean checkIsSupported() {
/*
* Available settings: public static final int NOISE_REDUCTION_MODE_FAST = 1; public static
* final int NOISE_REDUCTION_MODE_HIGH_QUALITY = 2; public static final int
* NOISE_REDUCTION_MODE_MINIMAL = 3; public static final int NOISE_REDUCTION_MODE_OFF = 0;
* public static final int NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG = 4;
*
* <p>Full-capability camera devices will always support OFF and FAST. Camera devices that
* support YUV_REPROCESSING or PRIVATE_REPROCESSING will support ZERO_SHUTTER_LAG.
* Legacy-capability camera devices will only support FAST mode.
*/
// Can be null on some devices.
int[] modes = cameraProperties.getAvailableNoiseReductionModes();
/// If there's at least one mode available then we are supported.
return modes != null && modes.length > 0;
}
@Override
public void updateBuilder(CaptureRequest.Builder requestBuilder) {
if (!checkIsSupported()) {
return;
}
Log.i("Camera", "updateNoiseReduction | currentSetting: " + currentSetting);
// Always use fast mode.
requestBuilder.set(
CaptureRequest.NOISE_REDUCTION_MODE, NOISE_REDUCTION_MODES.get(currentSetting));
}
}
| plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/noisereduction/NoiseReductionFeature.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/features/noisereduction/NoiseReductionFeature.java",
"repo_id": "plugins",
"token_count": 1163
} | 1,200 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.CaptureResult.Key;
import android.hardware.camera2.TotalCaptureResult;
import io.flutter.plugins.camera.CameraCaptureCallback.CameraCaptureStateListener;
import io.flutter.plugins.camera.types.CameraCaptureProperties;
import io.flutter.plugins.camera.types.CaptureTimeoutsWrapper;
import io.flutter.plugins.camera.types.Timeout;
import io.flutter.plugins.camera.utils.TestUtils;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.mockito.MockedStatic;
public class CameraCaptureCallbackStatesTest extends TestCase {
private final Integer aeState;
private final Integer afState;
private final CameraState cameraState;
private final boolean isTimedOut;
private Runnable validate;
private CameraCaptureCallback cameraCaptureCallback;
private CameraCaptureStateListener mockCaptureStateListener;
private CameraCaptureSession mockCameraCaptureSession;
private CaptureRequest mockCaptureRequest;
private CaptureResult mockPartialCaptureResult;
private CaptureTimeoutsWrapper mockCaptureTimeouts;
private CameraCaptureProperties mockCaptureProps;
private TotalCaptureResult mockTotalCaptureResult;
private MockedStatic<Timeout> mockedStaticTimeout;
private Timeout mockTimeout;
public static TestSuite suite() {
TestSuite suite = new TestSuite();
setUpPreviewStateTest(suite);
setUpWaitingFocusTests(suite);
setUpWaitingPreCaptureStartTests(suite);
setUpWaitingPreCaptureDoneTests(suite);
return suite;
}
protected CameraCaptureCallbackStatesTest(
String name, CameraState cameraState, Integer afState, Integer aeState) {
this(name, cameraState, afState, aeState, false);
}
protected CameraCaptureCallbackStatesTest(
String name, CameraState cameraState, Integer afState, Integer aeState, boolean isTimedOut) {
super(name);
this.aeState = aeState;
this.afState = afState;
this.cameraState = cameraState;
this.isTimedOut = isTimedOut;
}
@Override
@SuppressWarnings("unchecked")
protected void setUp() throws Exception {
super.setUp();
mockedStaticTimeout = mockStatic(Timeout.class);
mockCaptureStateListener = mock(CameraCaptureStateListener.class);
mockCameraCaptureSession = mock(CameraCaptureSession.class);
mockCaptureRequest = mock(CaptureRequest.class);
mockPartialCaptureResult = mock(CaptureResult.class);
mockTotalCaptureResult = mock(TotalCaptureResult.class);
mockTimeout = mock(Timeout.class);
mockCaptureTimeouts = mock(CaptureTimeoutsWrapper.class);
mockCaptureProps = mock(CameraCaptureProperties.class);
when(mockCaptureTimeouts.getPreCaptureFocusing()).thenReturn(mockTimeout);
when(mockCaptureTimeouts.getPreCaptureMetering()).thenReturn(mockTimeout);
Key<Integer> mockAeStateKey = mock(Key.class);
Key<Integer> mockAfStateKey = mock(Key.class);
TestUtils.setFinalStatic(CaptureResult.class, "CONTROL_AE_STATE", mockAeStateKey);
TestUtils.setFinalStatic(CaptureResult.class, "CONTROL_AF_STATE", mockAfStateKey);
mockedStaticTimeout.when(() -> Timeout.create(1000)).thenReturn(mockTimeout);
cameraCaptureCallback =
CameraCaptureCallback.create(
mockCaptureStateListener, mockCaptureTimeouts, mockCaptureProps);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
mockedStaticTimeout.close();
TestUtils.setFinalStatic(CaptureResult.class, "CONTROL_AE_STATE", null);
TestUtils.setFinalStatic(CaptureResult.class, "CONTROL_AF_STATE", null);
}
@Override
protected void runTest() throws Throwable {
when(mockPartialCaptureResult.get(CaptureResult.CONTROL_AF_STATE)).thenReturn(afState);
when(mockPartialCaptureResult.get(CaptureResult.CONTROL_AE_STATE)).thenReturn(aeState);
when(mockTotalCaptureResult.get(CaptureResult.CONTROL_AF_STATE)).thenReturn(afState);
when(mockTotalCaptureResult.get(CaptureResult.CONTROL_AE_STATE)).thenReturn(aeState);
cameraCaptureCallback.setCameraState(cameraState);
if (isTimedOut) {
when(mockTimeout.getIsExpired()).thenReturn(true);
cameraCaptureCallback.onCaptureCompleted(
mockCameraCaptureSession, mockCaptureRequest, mockTotalCaptureResult);
} else {
cameraCaptureCallback.onCaptureProgressed(
mockCameraCaptureSession, mockCaptureRequest, mockPartialCaptureResult);
}
validate.run();
}
private static void setUpPreviewStateTest(TestSuite suite) {
CameraCaptureCallbackStatesTest previewStateTest =
new CameraCaptureCallbackStatesTest(
"process_should_not_converge_or_pre_capture_when_state_is_preview",
CameraState.STATE_PREVIEW,
null,
null);
previewStateTest.validate =
() -> {
verify(previewStateTest.mockCaptureStateListener, never()).onConverged();
verify(previewStateTest.mockCaptureStateListener, never()).onConverged();
assertEquals(
CameraState.STATE_PREVIEW, previewStateTest.cameraCaptureCallback.getCameraState());
};
suite.addTest(previewStateTest);
}
private static void setUpWaitingFocusTests(TestSuite suite) {
Integer[] actionableAfStates =
new Integer[] {
CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED,
CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED
};
Integer[] nonActionableAfStates =
new Integer[] {
CaptureResult.CONTROL_AF_STATE_ACTIVE_SCAN,
CaptureResult.CONTROL_AF_STATE_INACTIVE,
CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED,
CaptureResult.CONTROL_AF_STATE_PASSIVE_SCAN,
CaptureResult.CONTROL_AF_STATE_PASSIVE_UNFOCUSED
};
Map<Integer, Boolean> aeStatesConvergeMap =
new HashMap<Integer, Boolean>() {
{
put(null, true);
put(CaptureResult.CONTROL_AE_STATE_CONVERGED, true);
put(CaptureResult.CONTROL_AE_STATE_PRECAPTURE, false);
put(CaptureResult.CONTROL_AE_STATE_LOCKED, false);
put(CaptureResult.CONTROL_AE_STATE_SEARCHING, false);
put(CaptureResult.CONTROL_AE_STATE_INACTIVE, false);
put(CaptureResult.CONTROL_AE_STATE_FLASH_REQUIRED, false);
}
};
CameraCaptureCallbackStatesTest nullStateTest =
new CameraCaptureCallbackStatesTest(
"process_should_not_converge_or_pre_capture_when_afstate_is_null",
CameraState.STATE_WAITING_FOCUS,
null,
null);
nullStateTest.validate =
() -> {
verify(nullStateTest.mockCaptureStateListener, never()).onConverged();
verify(nullStateTest.mockCaptureStateListener, never()).onConverged();
assertEquals(
CameraState.STATE_WAITING_FOCUS,
nullStateTest.cameraCaptureCallback.getCameraState());
};
suite.addTest(nullStateTest);
for (Integer afState : actionableAfStates) {
aeStatesConvergeMap.forEach(
(aeState, shouldConverge) -> {
CameraCaptureCallbackStatesTest focusLockedTest =
new CameraCaptureCallbackStatesTest(
"process_should_converge_when_af_state_is_"
+ afState
+ "_and_ae_state_is_"
+ aeState,
CameraState.STATE_WAITING_FOCUS,
afState,
aeState);
focusLockedTest.validate =
() -> {
if (shouldConverge) {
verify(focusLockedTest.mockCaptureStateListener, times(1)).onConverged();
verify(focusLockedTest.mockCaptureStateListener, never()).onPrecapture();
} else {
verify(focusLockedTest.mockCaptureStateListener, times(1)).onPrecapture();
verify(focusLockedTest.mockCaptureStateListener, never()).onConverged();
}
assertEquals(
CameraState.STATE_WAITING_FOCUS,
focusLockedTest.cameraCaptureCallback.getCameraState());
};
suite.addTest(focusLockedTest);
});
}
for (Integer afState : nonActionableAfStates) {
CameraCaptureCallbackStatesTest focusLockedTest =
new CameraCaptureCallbackStatesTest(
"process_should_do_nothing_when_af_state_is_" + afState,
CameraState.STATE_WAITING_FOCUS,
afState,
null);
focusLockedTest.validate =
() -> {
verify(focusLockedTest.mockCaptureStateListener, never()).onConverged();
verify(focusLockedTest.mockCaptureStateListener, never()).onPrecapture();
assertEquals(
CameraState.STATE_WAITING_FOCUS,
focusLockedTest.cameraCaptureCallback.getCameraState());
};
suite.addTest(focusLockedTest);
}
for (Integer afState : nonActionableAfStates) {
aeStatesConvergeMap.forEach(
(aeState, shouldConverge) -> {
CameraCaptureCallbackStatesTest focusLockedTest =
new CameraCaptureCallbackStatesTest(
"process_should_converge_when_af_state_is_"
+ afState
+ "_and_ae_state_is_"
+ aeState,
CameraState.STATE_WAITING_FOCUS,
afState,
aeState,
true);
focusLockedTest.validate =
() -> {
if (shouldConverge) {
verify(focusLockedTest.mockCaptureStateListener, times(1)).onConverged();
verify(focusLockedTest.mockCaptureStateListener, never()).onPrecapture();
} else {
verify(focusLockedTest.mockCaptureStateListener, times(1)).onPrecapture();
verify(focusLockedTest.mockCaptureStateListener, never()).onConverged();
}
assertEquals(
CameraState.STATE_WAITING_FOCUS,
focusLockedTest.cameraCaptureCallback.getCameraState());
};
suite.addTest(focusLockedTest);
});
}
}
private static void setUpWaitingPreCaptureStartTests(TestSuite suite) {
Map<Integer, CameraState> cameraStateMap =
new HashMap<Integer, CameraState>() {
{
put(null, CameraState.STATE_WAITING_PRECAPTURE_DONE);
put(
CaptureResult.CONTROL_AE_STATE_INACTIVE,
CameraState.STATE_WAITING_PRECAPTURE_START);
put(
CaptureResult.CONTROL_AE_STATE_SEARCHING,
CameraState.STATE_WAITING_PRECAPTURE_START);
put(
CaptureResult.CONTROL_AE_STATE_CONVERGED,
CameraState.STATE_WAITING_PRECAPTURE_DONE);
put(CaptureResult.CONTROL_AE_STATE_LOCKED, CameraState.STATE_WAITING_PRECAPTURE_START);
put(
CaptureResult.CONTROL_AE_STATE_FLASH_REQUIRED,
CameraState.STATE_WAITING_PRECAPTURE_DONE);
put(
CaptureResult.CONTROL_AE_STATE_PRECAPTURE,
CameraState.STATE_WAITING_PRECAPTURE_DONE);
}
};
cameraStateMap.forEach(
(aeState, cameraState) -> {
CameraCaptureCallbackStatesTest testCase =
new CameraCaptureCallbackStatesTest(
"process_should_update_camera_state_to_waiting_pre_capture_done_when_ae_state_is_"
+ aeState,
CameraState.STATE_WAITING_PRECAPTURE_START,
null,
aeState);
testCase.validate =
() -> assertEquals(cameraState, testCase.cameraCaptureCallback.getCameraState());
suite.addTest(testCase);
});
cameraStateMap.forEach(
(aeState, cameraState) -> {
if (cameraState == CameraState.STATE_WAITING_PRECAPTURE_DONE) {
return;
}
CameraCaptureCallbackStatesTest testCase =
new CameraCaptureCallbackStatesTest(
"process_should_update_camera_state_to_waiting_pre_capture_done_when_ae_state_is_"
+ aeState,
CameraState.STATE_WAITING_PRECAPTURE_START,
null,
aeState,
true);
testCase.validate =
() ->
assertEquals(
CameraState.STATE_WAITING_PRECAPTURE_DONE,
testCase.cameraCaptureCallback.getCameraState());
suite.addTest(testCase);
});
}
private static void setUpWaitingPreCaptureDoneTests(TestSuite suite) {
Integer[] onConvergeStates =
new Integer[] {
null,
CaptureResult.CONTROL_AE_STATE_CONVERGED,
CaptureResult.CONTROL_AE_STATE_LOCKED,
CaptureResult.CONTROL_AE_STATE_SEARCHING,
CaptureResult.CONTROL_AE_STATE_INACTIVE,
CaptureResult.CONTROL_AE_STATE_FLASH_REQUIRED,
};
for (Integer aeState : onConvergeStates) {
CameraCaptureCallbackStatesTest shouldConvergeTest =
new CameraCaptureCallbackStatesTest(
"process_should_converge_when_ae_state_is_" + aeState,
CameraState.STATE_WAITING_PRECAPTURE_DONE,
null,
null);
shouldConvergeTest.validate =
() -> verify(shouldConvergeTest.mockCaptureStateListener, times(1)).onConverged();
suite.addTest(shouldConvergeTest);
}
CameraCaptureCallbackStatesTest shouldNotConvergeTest =
new CameraCaptureCallbackStatesTest(
"process_should_not_converge_when_ae_state_is_pre_capture",
CameraState.STATE_WAITING_PRECAPTURE_DONE,
null,
CaptureResult.CONTROL_AE_STATE_PRECAPTURE);
shouldNotConvergeTest.validate =
() -> verify(shouldNotConvergeTest.mockCaptureStateListener, never()).onConverged();
suite.addTest(shouldNotConvergeTest);
CameraCaptureCallbackStatesTest shouldConvergeWhenTimedOutTest =
new CameraCaptureCallbackStatesTest(
"process_should_not_converge_when_ae_state_is_pre_capture",
CameraState.STATE_WAITING_PRECAPTURE_DONE,
null,
CaptureResult.CONTROL_AE_STATE_PRECAPTURE,
true);
shouldConvergeWhenTimedOutTest.validate =
() ->
verify(shouldConvergeWhenTimedOutTest.mockCaptureStateListener, times(1)).onConverged();
suite.addTest(shouldConvergeWhenTimedOutTest);
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraCaptureCallbackStatesTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraCaptureCallbackStatesTest.java",
"repo_id": "plugins",
"token_count": 6716
} | 1,201 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.camera.features.exposureoffset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
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.hardware.camera2.CaptureRequest;
import io.flutter.plugins.camera.CameraProperties;
import org.junit.Test;
public class ExposureOffsetFeatureTest {
@Test
public void getDebugName_shouldReturnTheNameOfTheFeature() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ExposureOffsetFeature exposureOffsetFeature = new ExposureOffsetFeature(mockCameraProperties);
assertEquals("ExposureOffsetFeature", exposureOffsetFeature.getDebugName());
}
@Test
public void getValue_shouldReturnZeroIfNotSet() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ExposureOffsetFeature exposureOffsetFeature = new ExposureOffsetFeature(mockCameraProperties);
final double actualValue = exposureOffsetFeature.getValue();
assertEquals(0.0, actualValue, 0);
}
@Test
public void getValue_shouldEchoTheSetValue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ExposureOffsetFeature exposureOffsetFeature = new ExposureOffsetFeature(mockCameraProperties);
double expectedValue = 4.0;
when(mockCameraProperties.getControlAutoExposureCompensationStep()).thenReturn(0.5);
exposureOffsetFeature.setValue(2.0);
double actualValue = exposureOffsetFeature.getValue();
assertEquals(expectedValue, actualValue, 0);
}
@Test
public void getExposureOffsetStepSize_shouldReturnTheControlExposureCompensationStepValue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ExposureOffsetFeature exposureOffsetFeature = new ExposureOffsetFeature(mockCameraProperties);
when(mockCameraProperties.getControlAutoExposureCompensationStep()).thenReturn(0.5);
assertEquals(0.5, exposureOffsetFeature.getExposureOffsetStepSize(), 0);
}
@Test
public void checkIsSupported_shouldReturnTrue() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
ExposureOffsetFeature exposureOffsetFeature = new ExposureOffsetFeature(mockCameraProperties);
assertTrue(exposureOffsetFeature.checkIsSupported());
}
@Test
public void updateBuilder_shouldSetControlAeExposureCompensationToOffset() {
CameraProperties mockCameraProperties = mock(CameraProperties.class);
CaptureRequest.Builder mockBuilder = mock(CaptureRequest.Builder.class);
ExposureOffsetFeature exposureOffsetFeature = new ExposureOffsetFeature(mockCameraProperties);
when(mockCameraProperties.getControlAutoExposureCompensationStep()).thenReturn(0.5);
exposureOffsetFeature.setValue(2.0);
exposureOffsetFeature.updateBuilder(mockBuilder);
verify(mockBuilder, times(1)).set(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, 4);
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/exposureoffset/ExposureOffsetFeatureTest.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/features/exposureoffset/ExposureOffsetFeatureTest.java",
"repo_id": "plugins",
"token_count": 923
} | 1,202 |
// 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.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import org.junit.Assert;
public class TestUtils {
public static <T> void setFinalStatic(Class<T> classToModify, String fieldName, Object newValue) {
try {
Field field = classToModify.getField(fieldName);
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
} catch (Exception e) {
Assert.fail("Unable to mock static field: " + fieldName);
}
}
public static <T> void setPrivateField(T instance, String fieldName, Object newValue) {
try {
Field field = instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(instance, newValue);
} catch (Exception e) {
Assert.fail("Unable to mock private field: " + fieldName);
}
}
public static <T> Object getPrivateField(T instance, String fieldName) {
try {
Field field = instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(instance);
} catch (Exception e) {
Assert.fail("Unable to mock private field: " + fieldName);
return null;
}
}
}
| plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/utils/TestUtils.java/0 | {
"file_path": "plugins/packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/utils/TestUtils.java",
"repo_id": "plugins",
"token_count": 538
} | 1,203 |
// 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.app.Activity;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import io.flutter.plugin.common.BinaryMessenger;
/** Utility class used to create CameraX-related objects primarily for testing purposes. */
public class CameraXProxy {
public CameraSelector.Builder createCameraSelectorBuilder() {
return new CameraSelector.Builder();
}
public CameraPermissionsManager createCameraPermissionsManager() {
return new CameraPermissionsManager();
}
public DeviceOrientationManager createDeviceOrientationManager(
@NonNull Activity activity,
@NonNull Boolean isFrontFacing,
@NonNull int sensorOrientation,
@NonNull DeviceOrientationManager.DeviceOrientationChangeCallback callback) {
return new DeviceOrientationManager(activity, isFrontFacing, sensorOrientation, callback);
}
public Preview.Builder createPreviewBuilder() {
return new Preview.Builder();
}
public Surface createSurface(@NonNull SurfaceTexture surfaceTexture) {
return new Surface(surfaceTexture);
}
/**
* Creates an instance of the {@code SystemServicesFlutterApiImpl}.
*
* <p>Included in this class to utilize the callback methods it provides, e.g. {@code
* onCameraError(String)}.
*/
public SystemServicesFlutterApiImpl createSystemServicesFlutterApiImpl(
@NonNull BinaryMessenger binaryMessenger) {
return new SystemServicesFlutterApiImpl(binaryMessenger);
}
}
| plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXProxy.java/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXProxy.java",
"repo_id": "plugins",
"token_count": 513
} | 1,204 |
name: camera_android_camerax
description: Android implementation of the camera plugin using the CameraX library.
repository: https://github.com/flutter/plugins/tree/main/packages/camera/camera_android_camerax
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22
publish_to: 'none'
environment:
sdk: '>=2.17.0 <3.0.0'
flutter: ">=3.0.0"
flutter:
plugin:
implements: camera
platforms:
android:
package: io.flutter.plugins.camerax
pluginClass: CameraAndroidCameraxPlugin
dartPluginClass: AndroidCameraCameraX
dependencies:
camera_platform_interface: ^2.2.0
flutter:
sdk: flutter
integration_test:
sdk: flutter
stream_transform: ^2.1.0
dev_dependencies:
async: ^2.5.0
build_runner: ^2.1.4
flutter_test:
sdk: flutter
mockito: ^5.3.2
pigeon: ^3.2.6
| plugins/packages/camera/camera_android_camerax/pubspec.yaml/0 | {
"file_path": "plugins/packages/camera/camera_android_camerax/pubspec.yaml",
"repo_id": "plugins",
"token_count": 360
} | 1,205 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import camera_avfoundation.Test;
@import AVFoundation;
@import XCTest;
@interface CameraPropertiesTests : XCTestCase
@end
@implementation CameraPropertiesTests
#pragma mark - flash mode tests
- (void)testFLTGetFLTFlashModeForString {
XCTAssertEqual(FLTFlashModeOff, FLTGetFLTFlashModeForString(@"off"));
XCTAssertEqual(FLTFlashModeAuto, FLTGetFLTFlashModeForString(@"auto"));
XCTAssertEqual(FLTFlashModeAlways, FLTGetFLTFlashModeForString(@"always"));
XCTAssertEqual(FLTFlashModeTorch, FLTGetFLTFlashModeForString(@"torch"));
XCTAssertThrows(FLTGetFLTFlashModeForString(@"unkwown"));
}
- (void)testFLTGetAVCaptureFlashModeForFLTFlashMode {
XCTAssertEqual(AVCaptureFlashModeOff, FLTGetAVCaptureFlashModeForFLTFlashMode(FLTFlashModeOff));
XCTAssertEqual(AVCaptureFlashModeAuto, FLTGetAVCaptureFlashModeForFLTFlashMode(FLTFlashModeAuto));
XCTAssertEqual(AVCaptureFlashModeOn, FLTGetAVCaptureFlashModeForFLTFlashMode(FLTFlashModeAlways));
XCTAssertEqual(-1, FLTGetAVCaptureFlashModeForFLTFlashMode(FLTFlashModeTorch));
}
#pragma mark - exposure mode tests
- (void)testFLTGetStringForFLTExposureMode {
XCTAssertEqualObjects(@"auto", FLTGetStringForFLTExposureMode(FLTExposureModeAuto));
XCTAssertEqualObjects(@"locked", FLTGetStringForFLTExposureMode(FLTExposureModeLocked));
XCTAssertThrows(FLTGetStringForFLTExposureMode(-1));
}
- (void)testFLTGetFLTExposureModeForString {
XCTAssertEqual(FLTExposureModeAuto, FLTGetFLTExposureModeForString(@"auto"));
XCTAssertEqual(FLTExposureModeLocked, FLTGetFLTExposureModeForString(@"locked"));
XCTAssertThrows(FLTGetFLTExposureModeForString(@"unknown"));
}
#pragma mark - focus mode tests
- (void)testFLTGetStringForFLTFocusMode {
XCTAssertEqualObjects(@"auto", FLTGetStringForFLTFocusMode(FLTFocusModeAuto));
XCTAssertEqualObjects(@"locked", FLTGetStringForFLTFocusMode(FLTFocusModeLocked));
XCTAssertThrows(FLTGetStringForFLTFocusMode(-1));
}
- (void)testFLTGetFLTFocusModeForString {
XCTAssertEqual(FLTFocusModeAuto, FLTGetFLTFocusModeForString(@"auto"));
XCTAssertEqual(FLTFocusModeLocked, FLTGetFLTFocusModeForString(@"locked"));
XCTAssertThrows(FLTGetFLTFocusModeForString(@"unknown"));
}
#pragma mark - resolution preset tests
- (void)testFLTGetFLTResolutionPresetForString {
XCTAssertEqual(FLTResolutionPresetVeryLow, FLTGetFLTResolutionPresetForString(@"veryLow"));
XCTAssertEqual(FLTResolutionPresetLow, FLTGetFLTResolutionPresetForString(@"low"));
XCTAssertEqual(FLTResolutionPresetMedium, FLTGetFLTResolutionPresetForString(@"medium"));
XCTAssertEqual(FLTResolutionPresetHigh, FLTGetFLTResolutionPresetForString(@"high"));
XCTAssertEqual(FLTResolutionPresetVeryHigh, FLTGetFLTResolutionPresetForString(@"veryHigh"));
XCTAssertEqual(FLTResolutionPresetUltraHigh, FLTGetFLTResolutionPresetForString(@"ultraHigh"));
XCTAssertEqual(FLTResolutionPresetMax, FLTGetFLTResolutionPresetForString(@"max"));
XCTAssertThrows(FLTGetFLTFlashModeForString(@"unknown"));
}
#pragma mark - video format tests
- (void)testFLTGetVideoFormatFromString {
XCTAssertEqual(kCVPixelFormatType_32BGRA, FLTGetVideoFormatFromString(@"bgra8888"));
XCTAssertEqual(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
FLTGetVideoFormatFromString(@"yuv420"));
XCTAssertEqual(kCVPixelFormatType_32BGRA, FLTGetVideoFormatFromString(@"unknown"));
}
#pragma mark - device orientation tests
- (void)testFLTGetUIDeviceOrientationForString {
XCTAssertEqual(UIDeviceOrientationPortraitUpsideDown,
FLTGetUIDeviceOrientationForString(@"portraitDown"));
XCTAssertEqual(UIDeviceOrientationLandscapeRight,
FLTGetUIDeviceOrientationForString(@"landscapeLeft"));
XCTAssertEqual(UIDeviceOrientationLandscapeLeft,
FLTGetUIDeviceOrientationForString(@"landscapeRight"));
XCTAssertEqual(UIDeviceOrientationPortrait, FLTGetUIDeviceOrientationForString(@"portraitUp"));
XCTAssertThrows(FLTGetUIDeviceOrientationForString(@"unknown"));
}
- (void)testFLTGetStringForUIDeviceOrientation {
XCTAssertEqualObjects(@"portraitDown",
FLTGetStringForUIDeviceOrientation(UIDeviceOrientationPortraitUpsideDown));
XCTAssertEqualObjects(@"landscapeLeft",
FLTGetStringForUIDeviceOrientation(UIDeviceOrientationLandscapeRight));
XCTAssertEqualObjects(@"landscapeRight",
FLTGetStringForUIDeviceOrientation(UIDeviceOrientationLandscapeLeft));
XCTAssertEqualObjects(@"portraitUp",
FLTGetStringForUIDeviceOrientation(UIDeviceOrientationPortrait));
XCTAssertEqualObjects(@"portraitUp", FLTGetStringForUIDeviceOrientation(-1));
}
@end
| plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPropertiesTests.m/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPropertiesTests.m",
"repo_id": "plugins",
"token_count": 1907
} | 1,206 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// The state of a [CameraController].
class CameraValue {
/// Creates a new camera controller state.
const CameraValue({
required this.isInitialized,
this.previewSize,
required this.isRecordingVideo,
required this.isTakingPicture,
required this.isStreamingImages,
required this.isRecordingPaused,
required this.flashMode,
required this.exposureMode,
required this.focusMode,
required this.deviceOrientation,
this.lockedCaptureOrientation,
this.recordingOrientation,
this.isPreviewPaused = false,
this.previewPauseOrientation,
});
/// Creates a new camera controller state for an uninitialized controller.
const CameraValue.uninitialized()
: this(
isInitialized: false,
isRecordingVideo: false,
isTakingPicture: false,
isStreamingImages: false,
isRecordingPaused: false,
flashMode: FlashMode.auto,
exposureMode: ExposureMode.auto,
focusMode: FocusMode.auto,
deviceOrientation: DeviceOrientation.portraitUp,
isPreviewPaused: false,
);
/// True after [CameraController.initialize] has completed successfully.
final bool isInitialized;
/// True when a picture capture request has been sent but as not yet returned.
final bool isTakingPicture;
/// True when the camera is recording (not the same as previewing).
final bool isRecordingVideo;
/// True when images from the camera are being streamed.
final bool isStreamingImages;
/// True when video recording is paused.
final bool isRecordingPaused;
/// True when the preview widget has been paused manually.
final bool isPreviewPaused;
/// Set to the orientation the preview was paused in, if it is currently paused.
final DeviceOrientation? previewPauseOrientation;
/// The size of the preview in pixels.
///
/// Is `null` until [isInitialized] is `true`.
final Size? previewSize;
/// The flash mode the camera is currently set to.
final FlashMode flashMode;
/// The exposure mode the camera is currently set to.
final ExposureMode exposureMode;
/// The focus mode the camera is currently set to.
final FocusMode focusMode;
/// The current device UI orientation.
final DeviceOrientation deviceOrientation;
/// The currently locked capture orientation.
final DeviceOrientation? lockedCaptureOrientation;
/// Whether the capture orientation is currently locked.
bool get isCaptureOrientationLocked => lockedCaptureOrientation != null;
/// The orientation of the currently running video recording.
final DeviceOrientation? recordingOrientation;
/// Creates a modified copy of the object.
///
/// Explicitly specified fields get the specified value, all other fields get
/// the same value of the current object.
CameraValue copyWith({
bool? isInitialized,
bool? isRecordingVideo,
bool? isTakingPicture,
bool? isStreamingImages,
Size? previewSize,
bool? isRecordingPaused,
FlashMode? flashMode,
ExposureMode? exposureMode,
FocusMode? focusMode,
bool? exposurePointSupported,
bool? focusPointSupported,
DeviceOrientation? deviceOrientation,
Optional<DeviceOrientation>? lockedCaptureOrientation,
Optional<DeviceOrientation>? recordingOrientation,
bool? isPreviewPaused,
Optional<DeviceOrientation>? previewPauseOrientation,
}) {
return CameraValue(
isInitialized: isInitialized ?? this.isInitialized,
previewSize: previewSize ?? this.previewSize,
isRecordingVideo: isRecordingVideo ?? this.isRecordingVideo,
isTakingPicture: isTakingPicture ?? this.isTakingPicture,
isStreamingImages: isStreamingImages ?? this.isStreamingImages,
isRecordingPaused: isRecordingPaused ?? this.isRecordingPaused,
flashMode: flashMode ?? this.flashMode,
exposureMode: exposureMode ?? this.exposureMode,
focusMode: focusMode ?? this.focusMode,
deviceOrientation: deviceOrientation ?? this.deviceOrientation,
lockedCaptureOrientation: lockedCaptureOrientation == null
? this.lockedCaptureOrientation
: lockedCaptureOrientation.orNull,
recordingOrientation: recordingOrientation == null
? this.recordingOrientation
: recordingOrientation.orNull,
isPreviewPaused: isPreviewPaused ?? this.isPreviewPaused,
previewPauseOrientation: previewPauseOrientation == null
? this.previewPauseOrientation
: previewPauseOrientation.orNull,
);
}
@override
String toString() {
return '${objectRuntimeType(this, 'CameraValue')}('
'isRecordingVideo: $isRecordingVideo, '
'isInitialized: $isInitialized, '
'previewSize: $previewSize, '
'isStreamingImages: $isStreamingImages, '
'flashMode: $flashMode, '
'exposureMode: $exposureMode, '
'focusMode: $focusMode, '
'deviceOrientation: $deviceOrientation, '
'lockedCaptureOrientation: $lockedCaptureOrientation, '
'recordingOrientation: $recordingOrientation, '
'isPreviewPaused: $isPreviewPaused, '
'previewPausedOrientation: $previewPauseOrientation)';
}
}
/// Controls a device camera.
///
/// This is a stripped-down version of the app-facing controller to serve as a
/// utility for the example and integration tests. It wraps only the calls that
/// have state associated with them, to consolidate tracking of camera state
/// outside of the overall example code.
class CameraController extends ValueNotifier<CameraValue> {
/// Creates a new camera controller in an uninitialized state.
CameraController(
this.description,
this.resolutionPreset, {
this.enableAudio = true,
this.imageFormatGroup,
}) : super(const CameraValue.uninitialized());
/// The properties of the camera device controlled by this controller.
final CameraDescription description;
/// The resolution this controller is targeting.
///
/// This resolution preset is not guaranteed to be available on the device,
/// if unavailable a lower resolution will be used.
///
/// See also: [ResolutionPreset].
final ResolutionPreset resolutionPreset;
/// Whether to include audio when recording a video.
final bool enableAudio;
/// The [ImageFormatGroup] describes the output of the raw image format.
///
/// When null the imageFormat will fallback to the platforms default.
final ImageFormatGroup? imageFormatGroup;
late int _cameraId;
bool _isDisposed = false;
StreamSubscription<CameraImageData>? _imageStreamSubscription;
FutureOr<bool>? _initCalled;
StreamSubscription<DeviceOrientationChangedEvent>?
_deviceOrientationSubscription;
/// The camera identifier with which the controller is associated.
int get cameraId => _cameraId;
/// Initializes the camera on the device.
Future<void> initialize() async {
final Completer<CameraInitializedEvent> initializeCompleter =
Completer<CameraInitializedEvent>();
_deviceOrientationSubscription = CameraPlatform.instance
.onDeviceOrientationChanged()
.listen((DeviceOrientationChangedEvent event) {
value = value.copyWith(
deviceOrientation: event.orientation,
);
});
_cameraId = await CameraPlatform.instance.createCamera(
description,
resolutionPreset,
enableAudio: enableAudio,
);
CameraPlatform.instance
.onCameraInitialized(_cameraId)
.first
.then((CameraInitializedEvent event) {
initializeCompleter.complete(event);
});
await CameraPlatform.instance.initializeCamera(
_cameraId,
imageFormatGroup: imageFormatGroup ?? ImageFormatGroup.unknown,
);
value = value.copyWith(
isInitialized: true,
previewSize: await initializeCompleter.future
.then((CameraInitializedEvent event) => Size(
event.previewWidth,
event.previewHeight,
)),
exposureMode: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.exposureMode),
focusMode: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.focusMode),
exposurePointSupported: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.exposurePointSupported),
focusPointSupported: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.focusPointSupported),
);
_initCalled = true;
}
/// Prepare the capture session for video recording.
Future<void> prepareForVideoRecording() async {
await CameraPlatform.instance.prepareForVideoRecording();
}
/// Pauses the current camera preview
Future<void> pausePreview() async {
await CameraPlatform.instance.pausePreview(_cameraId);
value = value.copyWith(
isPreviewPaused: true,
previewPauseOrientation: Optional<DeviceOrientation>.of(
value.lockedCaptureOrientation ?? value.deviceOrientation));
}
/// Resumes the current camera preview
Future<void> resumePreview() async {
await CameraPlatform.instance.resumePreview(_cameraId);
value = value.copyWith(
isPreviewPaused: false,
previewPauseOrientation: const Optional<DeviceOrientation>.absent());
}
/// Captures an image and returns the file where it was saved.
///
/// Throws a [CameraException] if the capture fails.
Future<XFile> takePicture() async {
value = value.copyWith(isTakingPicture: true);
final XFile file = await CameraPlatform.instance.takePicture(_cameraId);
value = value.copyWith(isTakingPicture: false);
return file;
}
/// Start streaming images from platform camera.
Future<void> startImageStream(
Function(CameraImageData image) onAvailable) async {
_imageStreamSubscription = CameraPlatform.instance
.onStreamedFrameAvailable(_cameraId)
.listen((CameraImageData imageData) {
onAvailable(imageData);
});
value = value.copyWith(isStreamingImages: true);
}
/// Stop streaming images from platform camera.
Future<void> stopImageStream() async {
value = value.copyWith(isStreamingImages: false);
await _imageStreamSubscription?.cancel();
_imageStreamSubscription = null;
}
/// Start a video recording.
///
/// The video is returned as a [XFile] after calling [stopVideoRecording].
/// Throws a [CameraException] if the capture fails.
Future<void> startVideoRecording(
{Function(CameraImageData image)? streamCallback}) async {
await CameraPlatform.instance.startVideoCapturing(
VideoCaptureOptions(_cameraId, streamCallback: streamCallback));
value = value.copyWith(
isRecordingVideo: true,
isRecordingPaused: false,
isStreamingImages: streamCallback != null,
recordingOrientation: Optional<DeviceOrientation>.of(
value.lockedCaptureOrientation ?? value.deviceOrientation));
}
/// Stops the video recording and returns the file where it was saved.
///
/// Throws a [CameraException] if the capture failed.
Future<XFile> stopVideoRecording() async {
if (value.isStreamingImages) {
await stopImageStream();
}
final XFile file =
await CameraPlatform.instance.stopVideoRecording(_cameraId);
value = value.copyWith(
isRecordingVideo: false,
recordingOrientation: const Optional<DeviceOrientation>.absent(),
);
return file;
}
/// Pause video recording.
///
/// This feature is only available on iOS and Android sdk 24+.
Future<void> pauseVideoRecording() async {
await CameraPlatform.instance.pauseVideoRecording(_cameraId);
value = value.copyWith(isRecordingPaused: true);
}
/// Resume video recording after pausing.
///
/// This feature is only available on iOS and Android sdk 24+.
Future<void> resumeVideoRecording() async {
await CameraPlatform.instance.resumeVideoRecording(_cameraId);
value = value.copyWith(isRecordingPaused: false);
}
/// Returns a widget showing a live camera preview.
Widget buildPreview() {
return CameraPlatform.instance.buildPreview(_cameraId);
}
/// Sets the flash mode for taking pictures.
Future<void> setFlashMode(FlashMode mode) async {
await CameraPlatform.instance.setFlashMode(_cameraId, mode);
value = value.copyWith(flashMode: mode);
}
/// Sets the exposure mode for taking pictures.
Future<void> setExposureMode(ExposureMode mode) async {
await CameraPlatform.instance.setExposureMode(_cameraId, mode);
value = value.copyWith(exposureMode: mode);
}
/// Sets the exposure offset for the selected camera.
Future<double> setExposureOffset(double offset) async {
// Check if offset is in range
final List<double> range = await Future.wait(<Future<double>>[
CameraPlatform.instance.getMinExposureOffset(_cameraId),
CameraPlatform.instance.getMaxExposureOffset(_cameraId)
]);
// Round to the closest step if needed
final double stepSize =
await CameraPlatform.instance.getExposureOffsetStepSize(_cameraId);
if (stepSize > 0) {
final double inv = 1.0 / stepSize;
double roundedOffset = (offset * inv).roundToDouble() / inv;
if (roundedOffset > range[1]) {
roundedOffset = (offset * inv).floorToDouble() / inv;
} else if (roundedOffset < range[0]) {
roundedOffset = (offset * inv).ceilToDouble() / inv;
}
offset = roundedOffset;
}
return CameraPlatform.instance.setExposureOffset(_cameraId, offset);
}
/// Locks the capture orientation.
///
/// If [orientation] is omitted, the current device orientation is used.
Future<void> lockCaptureOrientation() async {
await CameraPlatform.instance
.lockCaptureOrientation(_cameraId, value.deviceOrientation);
value = value.copyWith(
lockedCaptureOrientation:
Optional<DeviceOrientation>.of(value.deviceOrientation));
}
/// Unlocks the capture orientation.
Future<void> unlockCaptureOrientation() async {
await CameraPlatform.instance.unlockCaptureOrientation(_cameraId);
value = value.copyWith(
lockedCaptureOrientation: const Optional<DeviceOrientation>.absent());
}
/// Sets the focus mode for taking pictures.
Future<void> setFocusMode(FocusMode mode) async {
await CameraPlatform.instance.setFocusMode(_cameraId, mode);
value = value.copyWith(focusMode: mode);
}
/// Releases the resources of this camera.
@override
Future<void> dispose() async {
if (_isDisposed) {
return;
}
_deviceOrientationSubscription?.cancel();
_isDisposed = true;
super.dispose();
if (_initCalled != null) {
await _initCalled;
await CameraPlatform.instance.dispose(_cameraId);
}
}
@override
void removeListener(VoidCallback listener) {
// Prevent ValueListenableBuilder in CameraPreview widget from causing an
// exception to be thrown by attempting to remove its own listener after
// the controller has already been disposed.
if (!_isDisposed) {
super.removeListener(listener);
}
}
}
/// A value that might be absent.
///
/// Used to represent [DeviceOrientation]s that are optional but also able
/// to be cleared.
@immutable
class Optional<T> extends IterableBase<T> {
/// Constructs an empty Optional.
const Optional.absent() : _value = null;
/// Constructs an Optional of the given [value].
///
/// Throws [ArgumentError] if [value] is null.
Optional.of(T value) : _value = value {
// TODO(cbracken): Delete and make this ctor const once mixed-mode
// execution is no longer around.
ArgumentError.checkNotNull(value);
}
/// Constructs an Optional of the given [value].
///
/// If [value] is null, returns [absent()].
const Optional.fromNullable(T? value) : _value = value;
final T? _value;
/// True when this optional contains a value.
bool get isPresent => _value != null;
/// True when this optional contains no value.
bool get isNotPresent => _value == null;
/// Gets the Optional value.
///
/// Throws [StateError] if [value] is null.
T get value {
if (_value == null) {
throw StateError('value called on absent Optional.');
}
return _value!;
}
/// Executes a function if the Optional value is present.
void ifPresent(void Function(T value) ifPresent) {
if (isPresent) {
ifPresent(_value as T);
}
}
/// Execution a function if the Optional value is absent.
void ifAbsent(void Function() ifAbsent) {
if (!isPresent) {
ifAbsent();
}
}
/// Gets the Optional value with a default.
///
/// The default is returned if the Optional is [absent()].
///
/// Throws [ArgumentError] if [defaultValue] is null.
T or(T defaultValue) {
return _value ?? defaultValue;
}
/// Gets the Optional value, or `null` if there is none.
T? get orNull => _value;
/// Transforms the Optional value.
///
/// If the Optional is [absent()], returns [absent()] without applying the transformer.
///
/// The transformer must not return `null`. If it does, an [ArgumentError] is thrown.
Optional<S> transform<S>(S Function(T value) transformer) {
return _value == null
? Optional<S>.absent()
: Optional<S>.of(transformer(_value as T));
}
/// Transforms the Optional value.
///
/// If the Optional is [absent()], returns [absent()] without applying the transformer.
///
/// Returns [absent()] if the transformer returns `null`.
Optional<S> transformNullable<S>(S? Function(T value) transformer) {
return _value == null
? Optional<S>.absent()
: Optional<S>.fromNullable(transformer(_value as T));
}
@override
Iterator<T> get iterator =>
isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
/// Delegates to the underlying [value] hashCode.
@override
int get hashCode => _value.hashCode;
/// Delegates to the underlying [value] operator==.
@override
bool operator ==(Object o) => o is Optional<T> && o._value == _value;
@override
String toString() {
return _value == null
? 'Optional { absent }'
: 'Optional { value: $_value }';
}
}
| plugins/packages/camera/camera_avfoundation/example/lib/camera_controller.dart/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/example/lib/camera_controller.dart",
"repo_id": "plugins",
"token_count": 6034
} | 1,207 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FLTCam.h"
#import "FLTSavePhotoDelegate.h"
@interface FLTImageStreamHandler : NSObject <FlutterStreamHandler>
/// The queue on which `eventSink` property should be accessed.
@property(nonatomic, strong) dispatch_queue_t captureSessionQueue;
/// The event sink to stream camera events to Dart.
///
/// The property should only be accessed on `captureSessionQueue`.
/// The block itself should be invoked on the main queue.
@property FlutterEventSink eventSink;
@end
// APIs exposed for unit testing.
@interface FLTCam ()
/// The output for video capturing.
@property(readonly, nonatomic) AVCaptureVideoDataOutput *captureVideoOutput;
/// The output for photo capturing. Exposed setter for unit tests.
@property(strong, nonatomic) AVCapturePhotoOutput *capturePhotoOutput API_AVAILABLE(ios(10));
/// True when images from the camera are being streamed.
@property(assign, nonatomic) BOOL isStreamingImages;
/// A dictionary to retain all in-progress FLTSavePhotoDelegates. The key of the dictionary is the
/// AVCapturePhotoSettings's uniqueID for each photo capture operation, and the value is the
/// FLTSavePhotoDelegate that handles the result of each photo capture operation. Note that photo
/// capture operations may overlap, so FLTCam has to keep track of multiple delegates in progress,
/// instead of just a single delegate reference.
@property(readonly, nonatomic)
NSMutableDictionary<NSNumber *, FLTSavePhotoDelegate *> *inProgressSavePhotoDelegates;
/// Delegate callback when receiving a new video or audio sample.
/// Exposed for unit tests.
- (void)captureOutput:(AVCaptureOutput *)output
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection;
/// Initializes a camera instance.
/// Allows for injecting dependencies that are usually internal.
- (instancetype)initWithCameraName:(NSString *)cameraName
resolutionPreset:(NSString *)resolutionPreset
enableAudio:(BOOL)enableAudio
orientation:(UIDeviceOrientation)orientation
captureSession:(AVCaptureSession *)captureSession
captureSessionQueue:(dispatch_queue_t)captureSessionQueue
error:(NSError **)error;
/// Start streaming images.
- (void)startImageStreamWithMessenger:(NSObject<FlutterBinaryMessenger> *)messenger
imageStreamHandler:(FLTImageStreamHandler *)imageStreamHandler;
@end
| plugins/packages/camera/camera_avfoundation/ios/Classes/FLTCam_Test.h/0 | {
"file_path": "plugins/packages/camera/camera_avfoundation/ios/Classes/FLTCam_Test.h",
"repo_id": "plugins",
"token_count": 809
} | 1,208 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('CameraInitializedEvent tests', () {
test('Constructor should initialize all properties', () {
const CameraInitializedEvent event = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
expect(event.cameraId, 1);
expect(event.previewWidth, 1024);
expect(event.previewHeight, 640);
expect(event.exposureMode, ExposureMode.auto);
expect(event.focusMode, FocusMode.auto);
expect(event.exposurePointSupported, true);
expect(event.focusPointSupported, true);
});
test('fromJson should initialize all properties', () {
final CameraInitializedEvent event =
CameraInitializedEvent.fromJson(const <String, dynamic>{
'cameraId': 1,
'previewWidth': 1024.0,
'previewHeight': 640.0,
'exposureMode': 'auto',
'exposurePointSupported': true,
'focusMode': 'auto',
'focusPointSupported': true
});
expect(event.cameraId, 1);
expect(event.previewWidth, 1024);
expect(event.previewHeight, 640);
expect(event.exposureMode, ExposureMode.auto);
expect(event.exposurePointSupported, true);
expect(event.focusMode, FocusMode.auto);
expect(event.focusPointSupported, true);
});
test('toJson should return a map with all fields', () {
const CameraInitializedEvent event = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
final Map<String, dynamic> jsonMap = event.toJson();
expect(jsonMap.length, 7);
expect(jsonMap['cameraId'], 1);
expect(jsonMap['previewWidth'], 1024);
expect(jsonMap['previewHeight'], 640);
expect(jsonMap['exposureMode'], 'auto');
expect(jsonMap['exposurePointSupported'], true);
expect(jsonMap['focusMode'], 'auto');
expect(jsonMap['focusPointSupported'], true);
});
test('equals should return true if objects are the same', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, true);
});
test('equals should return false if cameraId is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
2, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if previewWidth is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 2048, 640, ExposureMode.auto, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if previewHeight is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 980, ExposureMode.auto, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if exposureMode is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.locked, true, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if exposurePointSupported is different',
() {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, false, FocusMode.auto, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if focusMode is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.locked, true);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if focusPointSupported is different', () {
const CameraInitializedEvent firstEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
const CameraInitializedEvent secondEvent = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, false);
expect(firstEvent == secondEvent, false);
});
test('hashCode should match hashCode of all properties', () {
const CameraInitializedEvent event = CameraInitializedEvent(
1, 1024, 640, ExposureMode.auto, true, FocusMode.auto, true);
final int expectedHashCode = Object.hash(
event.cameraId.hashCode,
event.previewWidth,
event.previewHeight,
event.exposureMode,
event.exposurePointSupported,
event.focusMode,
event.focusPointSupported);
expect(event.hashCode, expectedHashCode);
});
});
group('CameraResolutionChangesEvent tests', () {
test('Constructor should initialize all properties', () {
const CameraResolutionChangedEvent event =
CameraResolutionChangedEvent(1, 1024, 640);
expect(event.cameraId, 1);
expect(event.captureWidth, 1024);
expect(event.captureHeight, 640);
});
test('fromJson should initialize all properties', () {
final CameraResolutionChangedEvent event =
CameraResolutionChangedEvent.fromJson(const <String, dynamic>{
'cameraId': 1,
'captureWidth': 1024.0,
'captureHeight': 640.0,
});
expect(event.cameraId, 1);
expect(event.captureWidth, 1024);
expect(event.captureHeight, 640);
});
test('toJson should return a map with all fields', () {
const CameraResolutionChangedEvent event =
CameraResolutionChangedEvent(1, 1024, 640);
final Map<String, dynamic> jsonMap = event.toJson();
expect(jsonMap.length, 3);
expect(jsonMap['cameraId'], 1);
expect(jsonMap['captureWidth'], 1024);
expect(jsonMap['captureHeight'], 640);
});
test('equals should return true if objects are the same', () {
const CameraResolutionChangedEvent firstEvent =
CameraResolutionChangedEvent(1, 1024, 640);
const CameraResolutionChangedEvent secondEvent =
CameraResolutionChangedEvent(1, 1024, 640);
expect(firstEvent == secondEvent, true);
});
test('equals should return false if cameraId is different', () {
const CameraResolutionChangedEvent firstEvent =
CameraResolutionChangedEvent(1, 1024, 640);
const CameraResolutionChangedEvent secondEvent =
CameraResolutionChangedEvent(2, 1024, 640);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if captureWidth is different', () {
const CameraResolutionChangedEvent firstEvent =
CameraResolutionChangedEvent(1, 1024, 640);
const CameraResolutionChangedEvent secondEvent =
CameraResolutionChangedEvent(1, 2048, 640);
expect(firstEvent == secondEvent, false);
});
test('equals should return false if captureHeight is different', () {
const CameraResolutionChangedEvent firstEvent =
CameraResolutionChangedEvent(1, 1024, 640);
const CameraResolutionChangedEvent secondEvent =
CameraResolutionChangedEvent(1, 1024, 980);
expect(firstEvent == secondEvent, false);
});
test('hashCode should match hashCode of all properties', () {
const CameraResolutionChangedEvent event =
CameraResolutionChangedEvent(1, 1024, 640);
final int expectedHashCode = Object.hash(
event.cameraId.hashCode,
event.captureWidth,
event.captureHeight,
);
expect(event.hashCode, expectedHashCode);
});
});
group('CameraClosingEvent tests', () {
test('Constructor should initialize all properties', () {
const CameraClosingEvent event = CameraClosingEvent(1);
expect(event.cameraId, 1);
});
test('fromJson should initialize all properties', () {
final CameraClosingEvent event =
CameraClosingEvent.fromJson(const <String, dynamic>{
'cameraId': 1,
});
expect(event.cameraId, 1);
});
test('toJson should return a map with all fields', () {
const CameraClosingEvent event = CameraClosingEvent(1);
final Map<String, dynamic> jsonMap = event.toJson();
expect(jsonMap.length, 1);
expect(jsonMap['cameraId'], 1);
});
test('equals should return true if objects are the same', () {
const CameraClosingEvent firstEvent = CameraClosingEvent(1);
const CameraClosingEvent secondEvent = CameraClosingEvent(1);
expect(firstEvent == secondEvent, true);
});
test('equals should return false if cameraId is different', () {
const CameraClosingEvent firstEvent = CameraClosingEvent(1);
const CameraClosingEvent secondEvent = CameraClosingEvent(2);
expect(firstEvent == secondEvent, false);
});
test('hashCode should match hashCode of all properties', () {
const CameraClosingEvent event = CameraClosingEvent(1);
final int expectedHashCode = event.cameraId.hashCode;
expect(event.hashCode, expectedHashCode);
});
});
group('CameraErrorEvent tests', () {
test('Constructor should initialize all properties', () {
const CameraErrorEvent event = CameraErrorEvent(1, 'Error');
expect(event.cameraId, 1);
expect(event.description, 'Error');
});
test('fromJson should initialize all properties', () {
final CameraErrorEvent event = CameraErrorEvent.fromJson(
const <String, dynamic>{'cameraId': 1, 'description': 'Error'});
expect(event.cameraId, 1);
expect(event.description, 'Error');
});
test('toJson should return a map with all fields', () {
const CameraErrorEvent event = CameraErrorEvent(1, 'Error');
final Map<String, dynamic> jsonMap = event.toJson();
expect(jsonMap.length, 2);
expect(jsonMap['cameraId'], 1);
expect(jsonMap['description'], 'Error');
});
test('equals should return true if objects are the same', () {
const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error');
const CameraErrorEvent secondEvent = CameraErrorEvent(1, 'Error');
expect(firstEvent == secondEvent, true);
});
test('equals should return false if cameraId is different', () {
const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error');
const CameraErrorEvent secondEvent = CameraErrorEvent(2, 'Error');
expect(firstEvent == secondEvent, false);
});
test('equals should return false if description is different', () {
const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error');
const CameraErrorEvent secondEvent = CameraErrorEvent(1, 'Ooops');
expect(firstEvent == secondEvent, false);
});
test('hashCode should match hashCode of all properties', () {
const CameraErrorEvent event = CameraErrorEvent(1, 'Error');
final int expectedHashCode =
Object.hash(event.cameraId.hashCode, event.description);
expect(event.hashCode, expectedHashCode);
});
});
}
| plugins/packages/camera/camera_platform_interface/test/events/camera_event_test.dart/0 | {
"file_path": "plugins/packages/camera/camera_platform_interface/test/events/camera_event_test.dart",
"repo_id": "plugins",
"token_count": 4316
} | 1,209 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "capture_device_info.h"
#include <memory>
#include <string>
namespace camera_windows {
std::string CaptureDeviceInfo::GetUniqueDeviceName() const {
return display_name_ + " <" + device_id_ + ">";
}
bool CaptureDeviceInfo::ParseDeviceInfoFromCameraName(
const std::string& camera_name) {
size_t delimeter_index = camera_name.rfind(' ', camera_name.length());
if (delimeter_index != std::string::npos) {
auto deviceInfo = std::make_unique<CaptureDeviceInfo>();
display_name_ = camera_name.substr(0, delimeter_index);
device_id_ = camera_name.substr(delimeter_index + 2,
camera_name.length() - delimeter_index - 3);
return true;
}
return false;
}
} // namespace camera_windows
| plugins/packages/camera/camera_windows/windows/capture_device_info.cpp/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/capture_device_info.cpp",
"repo_id": "plugins",
"token_count": 324
} | 1,210 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "capture_controller.h"
#include <flutter/method_call.h>
#include <flutter/method_result_functions.h>
#include <flutter/standard_method_codec.h>
#include <flutter/texture_registrar.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <windows.h>
#include <wrl/client.h>
#include <functional>
#include <memory>
#include <string>
#include "mocks.h"
#include "string_utils.h"
namespace camera_windows {
namespace test {
using Microsoft::WRL::ComPtr;
using ::testing::_;
using ::testing::Eq;
using ::testing::Return;
void MockInitCaptureController(CaptureControllerImpl* capture_controller,
MockTextureRegistrar* texture_registrar,
MockCaptureEngine* engine, MockCamera* camera,
int64_t mock_texture_id) {
ComPtr<MockMediaSource> video_source = new MockMediaSource();
ComPtr<MockMediaSource> audio_source = new MockMediaSource();
capture_controller->SetCaptureEngine(
reinterpret_cast<IMFCaptureEngine*>(engine));
capture_controller->SetVideoSource(
reinterpret_cast<IMFMediaSource*>(video_source.Get()));
capture_controller->SetAudioSource(
reinterpret_cast<IMFMediaSource*>(audio_source.Get()));
EXPECT_CALL(*texture_registrar, RegisterTexture)
.Times(1)
.WillOnce([reg = texture_registrar,
mock_texture_id](flutter::TextureVariant* texture) -> int64_t {
EXPECT_TRUE(texture);
reg->texture_ = texture;
reg->texture_id_ = mock_texture_id;
return reg->texture_id_;
});
EXPECT_CALL(*texture_registrar, UnregisterTexture(Eq(mock_texture_id)))
.Times(1);
EXPECT_CALL(*camera, OnCreateCaptureEngineFailed).Times(0);
EXPECT_CALL(*camera, OnCreateCaptureEngineSucceeded(Eq(mock_texture_id)))
.Times(1);
EXPECT_CALL(*engine, Initialize).Times(1);
bool result = capture_controller->InitCaptureDevice(
texture_registrar, MOCK_DEVICE_ID, true, ResolutionPreset::kAuto);
EXPECT_TRUE(result);
// MockCaptureEngine::Initialize is called
EXPECT_TRUE(engine->initialized_);
engine->CreateFakeEvent(S_OK, MF_CAPTURE_ENGINE_INITIALIZED);
}
void MockAvailableMediaTypes(MockCaptureEngine* engine,
MockCaptureSource* capture_source,
uint32_t mock_preview_width,
uint32_t mock_preview_height) {
EXPECT_CALL(*engine, GetSource)
.Times(1)
.WillOnce(
[src_source = capture_source](IMFCaptureSource** target_source) {
*target_source = src_source;
src_source->AddRef();
return S_OK;
});
EXPECT_CALL(
*capture_source,
GetAvailableDeviceMediaType(
Eq((DWORD)
MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_VIDEO_PREVIEW),
_, _))
.WillRepeatedly([mock_preview_width, mock_preview_height](
DWORD stream_index, DWORD media_type_index,
IMFMediaType** media_type) {
// We give only one media type to loop through
if (media_type_index != 0) return MF_E_NO_MORE_TYPES;
*media_type =
new FakeMediaType(MFMediaType_Video, MFVideoFormat_RGB32,
mock_preview_width, mock_preview_height);
(*media_type)->AddRef();
return S_OK;
});
EXPECT_CALL(
*capture_source,
GetAvailableDeviceMediaType(
Eq((DWORD)MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_VIDEO_RECORD),
_, _))
.WillRepeatedly([mock_preview_width, mock_preview_height](
DWORD stream_index, DWORD media_type_index,
IMFMediaType** media_type) {
// We give only one media type to loop through
if (media_type_index != 0) return MF_E_NO_MORE_TYPES;
*media_type =
new FakeMediaType(MFMediaType_Video, MFVideoFormat_RGB32,
mock_preview_width, mock_preview_height);
(*media_type)->AddRef();
return S_OK;
});
}
void MockStartPreview(CaptureControllerImpl* capture_controller,
MockCapturePreviewSink* preview_sink,
MockTextureRegistrar* texture_registrar,
MockCaptureEngine* engine, MockCamera* camera,
std::unique_ptr<uint8_t[]> mock_source_buffer,
uint32_t mock_source_buffer_size,
uint32_t mock_preview_width, uint32_t mock_preview_height,
int64_t mock_texture_id) {
EXPECT_CALL(*engine, GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_PREVIEW, _))
.Times(1)
.WillOnce([src_sink = preview_sink](MF_CAPTURE_ENGINE_SINK_TYPE sink_type,
IMFCaptureSink** target_sink) {
*target_sink = src_sink;
src_sink->AddRef();
return S_OK;
});
EXPECT_CALL(*preview_sink, RemoveAllStreams).Times(1).WillOnce(Return(S_OK));
EXPECT_CALL(*preview_sink, AddStream).Times(1).WillOnce(Return(S_OK));
EXPECT_CALL(*preview_sink, SetSampleCallback)
.Times(1)
.WillOnce([sink = preview_sink](
DWORD dwStreamSinkIndex,
IMFCaptureEngineOnSampleCallback* pCallback) -> HRESULT {
sink->sample_callback_ = pCallback;
return S_OK;
});
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
MockAvailableMediaTypes(engine, capture_source.Get(), mock_preview_width,
mock_preview_height);
EXPECT_CALL(*engine, StartPreview()).Times(1).WillOnce(Return(S_OK));
// Called by destructor
EXPECT_CALL(*engine, StopPreview()).Times(1).WillOnce(Return(S_OK));
// Called after first processed sample
EXPECT_CALL(*camera,
OnStartPreviewSucceeded(mock_preview_width, mock_preview_height))
.Times(1);
EXPECT_CALL(*camera, OnStartPreviewFailed).Times(0);
EXPECT_CALL(*texture_registrar, MarkTextureFrameAvailable(mock_texture_id))
.Times(1);
capture_controller->StartPreview();
EXPECT_EQ(capture_controller->GetPreviewHeight(), mock_preview_height);
EXPECT_EQ(capture_controller->GetPreviewWidth(), mock_preview_width);
// Capture engine is now started and will first send event of started preview
engine->CreateFakeEvent(S_OK, MF_CAPTURE_ENGINE_PREVIEW_STARTED);
// SendFake sample
preview_sink->SendFakeSample(mock_source_buffer.get(),
mock_source_buffer_size);
}
void MockPhotoSink(MockCaptureEngine* engine,
MockCapturePhotoSink* photo_sink) {
EXPECT_CALL(*engine, GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_PHOTO, _))
.Times(1)
.WillOnce([src_sink = photo_sink](MF_CAPTURE_ENGINE_SINK_TYPE sink_type,
IMFCaptureSink** target_sink) {
*target_sink = src_sink;
src_sink->AddRef();
return S_OK;
});
EXPECT_CALL(*photo_sink, RemoveAllStreams).Times(1).WillOnce(Return(S_OK));
EXPECT_CALL(*photo_sink, AddStream).Times(1).WillOnce(Return(S_OK));
EXPECT_CALL(*photo_sink, SetOutputFileName).Times(1).WillOnce(Return(S_OK));
}
void MockRecordStart(CaptureControllerImpl* capture_controller,
MockCaptureEngine* engine,
MockCaptureRecordSink* record_sink, MockCamera* camera,
const std::string& mock_path_to_video) {
EXPECT_CALL(*engine, StartRecord()).Times(1).WillOnce(Return(S_OK));
EXPECT_CALL(*engine, GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_RECORD, _))
.Times(1)
.WillOnce([src_sink = record_sink](MF_CAPTURE_ENGINE_SINK_TYPE sink_type,
IMFCaptureSink** target_sink) {
*target_sink = src_sink;
src_sink->AddRef();
return S_OK;
});
EXPECT_CALL(*record_sink, RemoveAllStreams).Times(1).WillOnce(Return(S_OK));
EXPECT_CALL(*record_sink, AddStream).Times(2).WillRepeatedly(Return(S_OK));
EXPECT_CALL(*record_sink, SetOutputFileName).Times(1).WillOnce(Return(S_OK));
capture_controller->StartRecord(mock_path_to_video, -1);
EXPECT_CALL(*camera, OnStartRecordSucceeded()).Times(1);
engine->CreateFakeEvent(S_OK, MF_CAPTURE_ENGINE_RECORD_STARTED);
}
TEST(CaptureController,
InitCaptureEngineCallsOnCreateCaptureEngineSucceededWithTextureId) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Init capture controller with mocks and tests
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, InitCaptureEngineCanOnlyBeCalledOnce) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Init capture controller once with mocks and tests
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
// Init capture controller a second time.
EXPECT_CALL(*camera, OnCreateCaptureEngineFailed).Times(1);
bool result = capture_controller->InitCaptureDevice(
texture_registrar.get(), MOCK_DEVICE_ID, true, ResolutionPreset::kAuto);
EXPECT_FALSE(result);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, InitCaptureEngineReportsFailure) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
ComPtr<MockMediaSource> video_source = new MockMediaSource();
ComPtr<MockMediaSource> audio_source = new MockMediaSource();
capture_controller->SetCaptureEngine(
reinterpret_cast<IMFCaptureEngine*>(engine.Get()));
capture_controller->SetVideoSource(
reinterpret_cast<IMFMediaSource*>(video_source.Get()));
capture_controller->SetAudioSource(
reinterpret_cast<IMFMediaSource*>(audio_source.Get()));
// Cause initialization to fail
EXPECT_CALL(*engine.Get(), Initialize).Times(1).WillOnce(Return(E_FAIL));
EXPECT_CALL(*texture_registrar, RegisterTexture).Times(0);
EXPECT_CALL(*texture_registrar, UnregisterTexture(_)).Times(0);
EXPECT_CALL(*camera, OnCreateCaptureEngineSucceeded).Times(0);
EXPECT_CALL(*camera,
OnCreateCaptureEngineFailed(Eq(CameraResult::kError),
Eq("Failed to create camera")))
.Times(1);
bool result = capture_controller->InitCaptureDevice(
texture_registrar.get(), MOCK_DEVICE_ID, true, ResolutionPreset::kAuto);
EXPECT_FALSE(result);
EXPECT_FALSE(engine->initialized_);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, InitCaptureEngineReportsAccessDenied) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
ComPtr<MockMediaSource> video_source = new MockMediaSource();
ComPtr<MockMediaSource> audio_source = new MockMediaSource();
capture_controller->SetCaptureEngine(
reinterpret_cast<IMFCaptureEngine*>(engine.Get()));
capture_controller->SetVideoSource(
reinterpret_cast<IMFMediaSource*>(video_source.Get()));
capture_controller->SetAudioSource(
reinterpret_cast<IMFMediaSource*>(audio_source.Get()));
// Cause initialization to fail
EXPECT_CALL(*engine.Get(), Initialize)
.Times(1)
.WillOnce(Return(E_ACCESSDENIED));
EXPECT_CALL(*texture_registrar, RegisterTexture).Times(0);
EXPECT_CALL(*texture_registrar, UnregisterTexture(_)).Times(0);
EXPECT_CALL(*camera, OnCreateCaptureEngineSucceeded).Times(0);
EXPECT_CALL(*camera,
OnCreateCaptureEngineFailed(Eq(CameraResult::kAccessDenied),
Eq("Failed to create camera")))
.Times(1);
bool result = capture_controller->InitCaptureDevice(
texture_registrar.get(), MOCK_DEVICE_ID, true, ResolutionPreset::kAuto);
EXPECT_FALSE(result);
EXPECT_FALSE(engine->initialized_);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, ReportsInitializedErrorEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
EXPECT_CALL(*camera, OnCreateCaptureEngineFailed(
Eq(CameraResult::kError),
Eq("Failed to initialize capture engine")))
.Times(1);
EXPECT_CALL(*camera, OnCreateCaptureEngineSucceeded).Times(0);
// Send initialization failed event
engine->CreateFakeEvent(E_FAIL, MF_CAPTURE_ENGINE_INITIALIZED);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, ReportsInitializedAccessDeniedEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
EXPECT_CALL(*camera, OnCreateCaptureEngineFailed(
Eq(CameraResult::kAccessDenied),
Eq("Failed to initialize capture engine")))
.Times(1);
EXPECT_CALL(*camera, OnCreateCaptureEngineSucceeded).Times(0);
// Send initialization failed event
engine->CreateFakeEvent(E_ACCESSDENIED, MF_CAPTURE_ENGINE_INITIALIZED);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, ReportsCaptureEngineErrorEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
EXPECT_CALL(*(camera.get()),
OnCaptureError(Eq(CameraResult::kError), Eq("Unspecified error")))
.Times(1);
// Send error event.
engine->CreateFakeEvent(E_FAIL, MF_CAPTURE_ENGINE_ERROR);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, ReportsCaptureEngineAccessDeniedEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
EXPECT_CALL(*(camera.get()), OnCaptureError(Eq(CameraResult::kAccessDenied),
Eq("Access is denied.")))
.Times(1);
// Send error event.
engine->CreateFakeEvent(E_ACCESSDENIED, MF_CAPTURE_ENGINE_ERROR);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, StartPreviewStartsProcessingSamples) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCapturePreviewSink> preview_sink = new MockCapturePreviewSink();
// Let's keep these small for mock texture data. Two pixels should be
// enough.
uint32_t mock_preview_width = 2;
uint32_t mock_preview_height = 1;
uint32_t pixels_total = mock_preview_width * mock_preview_height;
uint32_t pixel_size = 4;
// Build mock texture
uint32_t mock_texture_data_size = pixels_total * pixel_size;
std::unique_ptr<uint8_t[]> mock_source_buffer =
std::make_unique<uint8_t[]>(mock_texture_data_size);
uint8_t mock_red_pixel = 0x11;
uint8_t mock_green_pixel = 0x22;
uint8_t mock_blue_pixel = 0x33;
MFVideoFormatRGB32Pixel* mock_source_buffer_data =
(MFVideoFormatRGB32Pixel*)mock_source_buffer.get();
for (uint32_t i = 0; i < pixels_total; i++) {
mock_source_buffer_data[i].r = mock_red_pixel;
mock_source_buffer_data[i].g = mock_green_pixel;
mock_source_buffer_data[i].b = mock_blue_pixel;
}
// Start preview and run preview tests
MockStartPreview(capture_controller.get(), preview_sink.Get(),
texture_registrar.get(), engine.Get(), camera.get(),
std::move(mock_source_buffer), mock_texture_data_size,
mock_preview_width, mock_preview_height, mock_texture_id);
// Test texture processing
EXPECT_TRUE(texture_registrar->texture_);
if (texture_registrar->texture_) {
auto pixel_buffer_texture =
std::get_if<flutter::PixelBufferTexture>(texture_registrar->texture_);
EXPECT_TRUE(pixel_buffer_texture);
if (pixel_buffer_texture) {
auto converted_buffer =
pixel_buffer_texture->CopyPixelBuffer((size_t)100, (size_t)100);
EXPECT_TRUE(converted_buffer);
if (converted_buffer) {
EXPECT_EQ(converted_buffer->height, mock_preview_height);
EXPECT_EQ(converted_buffer->width, mock_preview_width);
FlutterDesktopPixel* converted_buffer_data =
(FlutterDesktopPixel*)(converted_buffer->buffer);
for (uint32_t i = 0; i < pixels_total; i++) {
EXPECT_EQ(converted_buffer_data[i].r, mock_red_pixel);
EXPECT_EQ(converted_buffer_data[i].g, mock_green_pixel);
EXPECT_EQ(converted_buffer_data[i].b, mock_blue_pixel);
}
// Call release callback to get mutex lock unlocked.
converted_buffer->release_callback(converted_buffer->release_context);
}
converted_buffer = nullptr;
}
pixel_buffer_texture = nullptr;
}
capture_controller = nullptr;
engine = nullptr;
camera = nullptr;
texture_registrar = nullptr;
}
TEST(CaptureController, ReportsStartPreviewError) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Cause start preview to fail
EXPECT_CALL(*engine.Get(), GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_PREVIEW, _))
.Times(1)
.WillOnce(Return(E_FAIL));
EXPECT_CALL(*engine.Get(), StartPreview).Times(0);
EXPECT_CALL(*engine.Get(), StopPreview).Times(0);
EXPECT_CALL(*camera, OnStartPreviewSucceeded).Times(0);
EXPECT_CALL(*camera,
OnStartPreviewFailed(Eq(CameraResult::kError),
Eq("Failed to start video preview")))
.Times(1);
capture_controller->StartPreview();
capture_controller = nullptr;
engine = nullptr;
camera = nullptr;
texture_registrar = nullptr;
}
// TODO(loic-sharma): Test duplicate calls to start preview.
TEST(CaptureController, IgnoresStartPreviewErrorEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
EXPECT_CALL(*camera, OnStartPreviewFailed).Times(0);
EXPECT_CALL(*camera, OnCreateCaptureEngineSucceeded).Times(0);
// Send a start preview error event
engine->CreateFakeEvent(E_FAIL, MF_CAPTURE_ENGINE_PREVIEW_STARTED);
capture_controller = nullptr;
camera = nullptr;
texture_registrar = nullptr;
engine = nullptr;
}
TEST(CaptureController, ReportsStartPreviewAccessDenied) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Cause start preview to fail
EXPECT_CALL(*engine.Get(), GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_PREVIEW, _))
.Times(1)
.WillOnce(Return(E_ACCESSDENIED));
EXPECT_CALL(*engine.Get(), StartPreview).Times(0);
EXPECT_CALL(*engine.Get(), StopPreview).Times(0);
EXPECT_CALL(*camera, OnStartPreviewSucceeded).Times(0);
EXPECT_CALL(*camera,
OnStartPreviewFailed(Eq(CameraResult::kAccessDenied),
Eq("Failed to start video preview")))
.Times(1);
capture_controller->StartPreview();
capture_controller = nullptr;
engine = nullptr;
camera = nullptr;
texture_registrar = nullptr;
}
TEST(CaptureController, StartRecordSuccess) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Start record
ComPtr<MockCaptureRecordSink> record_sink = new MockCaptureRecordSink();
std::string mock_path_to_video = "mock_path_to_video";
MockRecordStart(capture_controller.get(), engine.Get(), record_sink.Get(),
camera.get(), mock_path_to_video);
// Called by destructor
EXPECT_CALL(*(engine.Get()), StopRecord(true, false))
.Times(1)
.WillOnce(Return(S_OK));
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
record_sink = nullptr;
}
TEST(CaptureController, ReportsStartRecordError) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Cause start record to fail
EXPECT_CALL(*engine.Get(), GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_RECORD, _))
.Times(1)
.WillOnce(Return(E_FAIL));
EXPECT_CALL(*engine.Get(), StartRecord).Times(0);
EXPECT_CALL(*engine.Get(), StopRecord).Times(0);
EXPECT_CALL(*camera, OnStartRecordSucceeded).Times(0);
EXPECT_CALL(*camera,
OnStartRecordFailed(Eq(CameraResult::kError),
Eq("Failed to start video recording")))
.Times(1);
capture_controller->StartRecord("mock_path", -1);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
}
TEST(CaptureController, ReportsStartRecordAccessDenied) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Cause start record to fail
EXPECT_CALL(*engine.Get(), GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_RECORD, _))
.Times(1)
.WillOnce(Return(E_ACCESSDENIED));
EXPECT_CALL(*engine.Get(), StartRecord).Times(0);
EXPECT_CALL(*engine.Get(), StopRecord).Times(0);
EXPECT_CALL(*camera, OnStartRecordSucceeded).Times(0);
EXPECT_CALL(*camera,
OnStartRecordFailed(Eq(CameraResult::kAccessDenied),
Eq("Failed to start video recording")))
.Times(1);
capture_controller->StartRecord("mock_path", -1);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
}
TEST(CaptureController, ReportsStartRecordErrorEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Start record
ComPtr<MockCaptureRecordSink> record_sink = new MockCaptureRecordSink();
std::string mock_path_to_video = "mock_path_to_video";
EXPECT_CALL(*engine.Get(), StartRecord()).Times(1).WillOnce(Return(S_OK));
EXPECT_CALL(*engine.Get(), GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_RECORD, _))
.Times(1)
.WillOnce([src_sink = record_sink](MF_CAPTURE_ENGINE_SINK_TYPE sink_type,
IMFCaptureSink** target_sink) {
*target_sink = src_sink.Get();
src_sink->AddRef();
return S_OK;
});
EXPECT_CALL(*record_sink.Get(), RemoveAllStreams)
.Times(1)
.WillOnce(Return(S_OK));
EXPECT_CALL(*record_sink.Get(), AddStream)
.Times(2)
.WillRepeatedly(Return(S_OK));
EXPECT_CALL(*record_sink.Get(), SetOutputFileName)
.Times(1)
.WillOnce(Return(S_OK));
capture_controller->StartRecord(mock_path_to_video, -1);
// Send a start record failed event
EXPECT_CALL(*camera, OnStartRecordSucceeded).Times(0);
EXPECT_CALL(*camera, OnStartRecordFailed(Eq(CameraResult::kError),
Eq("Unspecified error")))
.Times(1);
engine->CreateFakeEvent(E_FAIL, MF_CAPTURE_ENGINE_RECORD_STARTED);
// Destructor shouldn't attempt to stop the recording that failed to start.
EXPECT_CALL(*engine.Get(), StopRecord).Times(0);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
record_sink = nullptr;
}
TEST(CaptureController, ReportsStartRecordAccessDeniedEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Start record
ComPtr<MockCaptureRecordSink> record_sink = new MockCaptureRecordSink();
std::string mock_path_to_video = "mock_path_to_video";
EXPECT_CALL(*engine.Get(), StartRecord()).Times(1).WillOnce(Return(S_OK));
EXPECT_CALL(*engine.Get(), GetSink(MF_CAPTURE_ENGINE_SINK_TYPE_RECORD, _))
.Times(1)
.WillOnce([src_sink = record_sink](MF_CAPTURE_ENGINE_SINK_TYPE sink_type,
IMFCaptureSink** target_sink) {
*target_sink = src_sink.Get();
src_sink->AddRef();
return S_OK;
});
EXPECT_CALL(*record_sink.Get(), RemoveAllStreams)
.Times(1)
.WillOnce(Return(S_OK));
EXPECT_CALL(*record_sink.Get(), AddStream)
.Times(2)
.WillRepeatedly(Return(S_OK));
EXPECT_CALL(*record_sink.Get(), SetOutputFileName)
.Times(1)
.WillOnce(Return(S_OK));
// Send a start record failed event
capture_controller->StartRecord(mock_path_to_video, -1);
EXPECT_CALL(*camera, OnStartRecordSucceeded).Times(0);
EXPECT_CALL(*camera, OnStartRecordFailed(Eq(CameraResult::kAccessDenied),
Eq("Access is denied.")))
.Times(1);
engine->CreateFakeEvent(E_ACCESSDENIED, MF_CAPTURE_ENGINE_RECORD_STARTED);
// Destructor shouldn't attempt to stop the recording that failed to start.
EXPECT_CALL(*engine.Get(), StopRecord).Times(0);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
record_sink = nullptr;
}
TEST(CaptureController, StopRecordSuccess) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Start record
ComPtr<MockCaptureRecordSink> record_sink = new MockCaptureRecordSink();
std::string mock_path_to_video = "mock_path_to_video";
MockRecordStart(capture_controller.get(), engine.Get(), record_sink.Get(),
camera.get(), mock_path_to_video);
// Request to stop record
EXPECT_CALL(*(engine.Get()), StopRecord(true, false))
.Times(1)
.WillOnce(Return(S_OK));
capture_controller->StopRecord();
// OnStopRecordSucceeded should be called with mocked file path
EXPECT_CALL(*camera, OnStopRecordSucceeded(Eq(mock_path_to_video))).Times(1);
EXPECT_CALL(*camera, OnStopRecordFailed).Times(0);
engine->CreateFakeEvent(S_OK, MF_CAPTURE_ENGINE_RECORD_STOPPED);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
record_sink = nullptr;
}
TEST(CaptureController, ReportsStopRecordError) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Start record
ComPtr<MockCaptureRecordSink> record_sink = new MockCaptureRecordSink();
MockRecordStart(capture_controller.get(), engine.Get(), record_sink.Get(),
camera.get(), "mock_path_to_video");
// Cause stop record to fail
EXPECT_CALL(*(engine.Get()), StopRecord(true, false))
.Times(1)
.WillOnce(Return(E_FAIL));
EXPECT_CALL(*camera, OnStopRecordSucceeded).Times(0);
EXPECT_CALL(*camera, OnStopRecordFailed(Eq(CameraResult::kError),
Eq("Failed to stop video recording")))
.Times(1);
capture_controller->StopRecord();
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
record_sink = nullptr;
}
TEST(CaptureController, ReportsStopRecordAccessDenied) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Start record
ComPtr<MockCaptureRecordSink> record_sink = new MockCaptureRecordSink();
MockRecordStart(capture_controller.get(), engine.Get(), record_sink.Get(),
camera.get(), "mock_path_to_video");
// Cause stop record to fail
EXPECT_CALL(*(engine.Get()), StopRecord(true, false))
.Times(1)
.WillOnce(Return(E_ACCESSDENIED));
EXPECT_CALL(*camera, OnStopRecordSucceeded).Times(0);
EXPECT_CALL(*camera, OnStopRecordFailed(Eq(CameraResult::kAccessDenied),
Eq("Failed to stop video recording")))
.Times(1);
capture_controller->StopRecord();
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
record_sink = nullptr;
}
TEST(CaptureController, ReportsStopRecordErrorEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Start record
ComPtr<MockCaptureRecordSink> record_sink = new MockCaptureRecordSink();
std::string mock_path_to_video = "mock_path_to_video";
MockRecordStart(capture_controller.get(), engine.Get(), record_sink.Get(),
camera.get(), mock_path_to_video);
// Send a stop record failure event
EXPECT_CALL(*camera, OnStopRecordSucceeded).Times(0);
EXPECT_CALL(*camera, OnStopRecordFailed(Eq(CameraResult::kError),
Eq("Unspecified error")))
.Times(1);
engine->CreateFakeEvent(E_FAIL, MF_CAPTURE_ENGINE_RECORD_STOPPED);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
record_sink = nullptr;
}
TEST(CaptureController, ReportsStopRecordAccessDeniedEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
// Start record
ComPtr<MockCaptureRecordSink> record_sink = new MockCaptureRecordSink();
std::string mock_path_to_video = "mock_path_to_video";
MockRecordStart(capture_controller.get(), engine.Get(), record_sink.Get(),
camera.get(), mock_path_to_video);
// Send a stop record failure event
EXPECT_CALL(*camera, OnStopRecordSucceeded).Times(0);
EXPECT_CALL(*camera, OnStopRecordFailed(Eq(CameraResult::kAccessDenied),
Eq("Access is denied.")))
.Times(1);
engine->CreateFakeEvent(E_ACCESSDENIED, MF_CAPTURE_ENGINE_RECORD_STOPPED);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
record_sink = nullptr;
}
TEST(CaptureController, TakePictureSuccess) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to take picture
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
ComPtr<MockCapturePhotoSink> photo_sink = new MockCapturePhotoSink();
// Initialize photo sink
MockPhotoSink(engine.Get(), photo_sink.Get());
// Request photo
std::string mock_path_to_photo = "mock_path_to_photo";
EXPECT_CALL(*(engine.Get()), TakePhoto()).Times(1).WillOnce(Return(S_OK));
capture_controller->TakePicture(mock_path_to_photo);
// OnTakePictureSucceeded should be called with mocked file path
EXPECT_CALL(*camera, OnTakePictureSucceeded(Eq(mock_path_to_photo))).Times(1);
EXPECT_CALL(*camera, OnTakePictureFailed).Times(0);
engine->CreateFakeEvent(S_OK, MF_CAPTURE_ENGINE_PHOTO_TAKEN);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
photo_sink = nullptr;
}
TEST(CaptureController, ReportsTakePictureError) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to take picture
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
ComPtr<MockCapturePhotoSink> photo_sink = new MockCapturePhotoSink();
// Initialize photo sink
MockPhotoSink(engine.Get(), photo_sink.Get());
// Cause take picture to fail
EXPECT_CALL(*(engine.Get()), TakePhoto).Times(1).WillOnce(Return(E_FAIL));
EXPECT_CALL(*camera, OnTakePictureSucceeded).Times(0);
EXPECT_CALL(*camera, OnTakePictureFailed(Eq(CameraResult::kError),
Eq("Failed to take photo")))
.Times(1);
capture_controller->TakePicture("mock_path_to_photo");
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
photo_sink = nullptr;
}
TEST(CaptureController, ReportsTakePictureAccessDenied) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to take picture
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
ComPtr<MockCapturePhotoSink> photo_sink = new MockCapturePhotoSink();
// Initialize photo sink
MockPhotoSink(engine.Get(), photo_sink.Get());
// Cause take picture to fail.
EXPECT_CALL(*(engine.Get()), TakePhoto)
.Times(1)
.WillOnce(Return(E_ACCESSDENIED));
EXPECT_CALL(*camera, OnTakePictureSucceeded).Times(0);
EXPECT_CALL(*camera, OnTakePictureFailed(Eq(CameraResult::kAccessDenied),
Eq("Failed to take photo")))
.Times(1);
capture_controller->TakePicture("mock_path_to_photo");
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
photo_sink = nullptr;
}
TEST(CaptureController, ReportsPhotoTakenErrorEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to take picture
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
ComPtr<MockCapturePhotoSink> photo_sink = new MockCapturePhotoSink();
// Initialize photo sink
MockPhotoSink(engine.Get(), photo_sink.Get());
// Request photo
std::string mock_path_to_photo = "mock_path_to_photo";
EXPECT_CALL(*(engine.Get()), TakePhoto()).Times(1).WillOnce(Return(S_OK));
capture_controller->TakePicture(mock_path_to_photo);
// Send take picture failed event
EXPECT_CALL(*camera, OnTakePictureSucceeded).Times(0);
EXPECT_CALL(*camera, OnTakePictureFailed(Eq(CameraResult::kError),
Eq("Unspecified error")))
.Times(1);
engine->CreateFakeEvent(E_FAIL, MF_CAPTURE_ENGINE_PHOTO_TAKEN);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
photo_sink = nullptr;
}
TEST(CaptureController, ReportsPhotoTakenAccessDeniedEvent) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to take picture
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCaptureSource> capture_source = new MockCaptureSource();
// Prepare fake media types
MockAvailableMediaTypes(engine.Get(), capture_source.Get(), 1, 1);
ComPtr<MockCapturePhotoSink> photo_sink = new MockCapturePhotoSink();
// Initialize photo sink
MockPhotoSink(engine.Get(), photo_sink.Get());
// Request photo
std::string mock_path_to_photo = "mock_path_to_photo";
EXPECT_CALL(*(engine.Get()), TakePhoto()).Times(1).WillOnce(Return(S_OK));
capture_controller->TakePicture(mock_path_to_photo);
// Send take picture failed event
EXPECT_CALL(*camera, OnTakePictureSucceeded).Times(0);
EXPECT_CALL(*camera, OnTakePictureFailed(Eq(CameraResult::kAccessDenied),
Eq("Access is denied.")))
.Times(1);
engine->CreateFakeEvent(E_ACCESSDENIED, MF_CAPTURE_ENGINE_PHOTO_TAKEN);
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
photo_sink = nullptr;
}
TEST(CaptureController, PauseResumePreviewSuccess) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
ComPtr<MockCapturePreviewSink> preview_sink = new MockCapturePreviewSink();
std::unique_ptr<uint8_t[]> mock_source_buffer =
std::make_unique<uint8_t[]>(0);
// Start preview to be able to start record
MockStartPreview(capture_controller.get(), preview_sink.Get(),
texture_registrar.get(), engine.Get(), camera.get(),
std::move(mock_source_buffer), 0, 1, 1, mock_texture_id);
EXPECT_CALL(*camera, OnPausePreviewSucceeded()).Times(1);
capture_controller->PausePreview();
EXPECT_CALL(*camera, OnResumePreviewSucceeded()).Times(1);
capture_controller->ResumePreview();
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
}
TEST(CaptureController, PausePreviewFailsIfPreviewNotStarted) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
// Pause preview fails if not started
EXPECT_CALL(*camera, OnPausePreviewFailed(Eq(CameraResult::kError),
Eq("Preview not started")))
.Times(1);
capture_controller->PausePreview();
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
}
TEST(CaptureController, ResumePreviewFailsIfPreviewNotStarted) {
ComPtr<MockCaptureEngine> engine = new MockCaptureEngine();
std::unique_ptr<MockCamera> camera =
std::make_unique<MockCamera>(MOCK_DEVICE_ID);
std::unique_ptr<CaptureControllerImpl> capture_controller =
std::make_unique<CaptureControllerImpl>(camera.get());
std::unique_ptr<MockTextureRegistrar> texture_registrar =
std::make_unique<MockTextureRegistrar>();
int64_t mock_texture_id = 1234;
// Initialize capture controller to be able to start preview
MockInitCaptureController(capture_controller.get(), texture_registrar.get(),
engine.Get(), camera.get(), mock_texture_id);
// Resume preview fails if not started.
EXPECT_CALL(*camera, OnResumePreviewFailed(Eq(CameraResult::kError),
Eq("Preview not started")))
.Times(1);
capture_controller->ResumePreview();
capture_controller = nullptr;
texture_registrar = nullptr;
engine = nullptr;
camera = nullptr;
}
} // namespace test
} // namespace camera_windows
| plugins/packages/camera/camera_windows/windows/test/capture_controller_test.cpp/0 | {
"file_path": "plugins/packages/camera/camera_windows/windows/test/capture_controller_test.cpp",
"repo_id": "plugins",
"token_count": 20754
} | 1,211 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.flutter.common.Constants.DEFAULT_INTERACTION_TIMEOUT;
import static androidx.test.espresso.flutter.matcher.FlutterMatchers.isFlutterView;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.hamcrest.Matchers.any;
import android.util.Log;
import android.view.View;
import androidx.test.espresso.UiController;
import androidx.test.espresso.ViewAction;
import androidx.test.espresso.flutter.action.FlutterViewAction;
import androidx.test.espresso.flutter.action.WidgetInfoFetcher;
import androidx.test.espresso.flutter.api.FlutterAction;
import androidx.test.espresso.flutter.api.WidgetAction;
import androidx.test.espresso.flutter.api.WidgetAssertion;
import androidx.test.espresso.flutter.api.WidgetMatcher;
import androidx.test.espresso.flutter.assertion.FlutterViewAssertion;
import androidx.test.espresso.flutter.common.Duration;
import androidx.test.espresso.flutter.exception.NoMatchingWidgetException;
import androidx.test.espresso.flutter.internal.idgenerator.IdGenerator;
import androidx.test.espresso.flutter.internal.idgenerator.IdGenerators;
import androidx.test.espresso.flutter.model.WidgetInfo;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import okhttp3.OkHttpClient;
import org.hamcrest.Matcher;
/** Entry point to the Espresso testing APIs on Flutter. */
public final class EspressoFlutter {
private static final String TAG = EspressoFlutter.class.getSimpleName();
private static final OkHttpClient okHttpClient;
private static final IdGenerator<Integer> idGenerator;
private static final ExecutorService taskExecutor;
static {
okHttpClient = new OkHttpClient();
idGenerator = IdGenerators.newIntegerIdGenerator();
taskExecutor = Executors.newCachedThreadPool();
}
/**
* Creates a {@link WidgetInteraction} for the Flutter widget matched by the given {@code
* widgetMatcher}, which is an entry point to perform actions or asserts.
*
* @param widgetMatcher the matcher used to uniquely match a Flutter widget on the screen.
*/
public static WidgetInteraction onFlutterWidget(@Nonnull WidgetMatcher widgetMatcher) {
return new WidgetInteraction(isFlutterView(), widgetMatcher);
}
/**
* Provides fluent testing APIs for test authors to perform actions or asserts on Flutter widgets,
* similar to {@code ViewInteraction} and {@code WebInteraction}.
*/
public static final class WidgetInteraction {
/**
* Adds a little delay to the interaction timeout so that we make sure not to time out before
* the action or assert does.
*/
private static final Duration INTERACTION_TIMEOUT_DELAY = new Duration(1, TimeUnit.SECONDS);
private final Matcher<View> flutterViewMatcher;
private final WidgetMatcher widgetMatcher;
private final Duration timeout;
private WidgetInteraction(Matcher<View> flutterViewMatcher, WidgetMatcher widgetMatcher) {
this(
flutterViewMatcher,
widgetMatcher,
DEFAULT_INTERACTION_TIMEOUT.plus(INTERACTION_TIMEOUT_DELAY));
}
private WidgetInteraction(
Matcher<View> flutterViewMatcher, WidgetMatcher widgetMatcher, Duration timeout) {
this.flutterViewMatcher = checkNotNull(flutterViewMatcher);
this.widgetMatcher = checkNotNull(widgetMatcher);
this.timeout = checkNotNull(timeout);
}
/**
* Executes the given action(s) with synchronization guarantees: Espresso ensures Flutter's in
* an idle state before interacting with the Flutter UI.
*
* <p>If more than one action is provided, actions are executed in the order provided.
*
* @param widgetActions one or more actions that shall be performed. Cannot be {@code null}.
* @return this interaction for further perform/verification calls.
*/
public WidgetInteraction perform(@Nonnull final WidgetAction... widgetActions) {
checkNotNull(widgetActions);
for (WidgetAction widgetAction : widgetActions) {
// If any error occurred, an unchecked exception will be thrown that stops execution of
// following actions.
performInternal(widgetAction);
}
return this;
}
/**
* Evaluates the given widget assertion.
*
* @param assertion a widget assertion that shall be made on the matched Flutter widget. Cannot
* be {@code null}.
*/
public WidgetInteraction check(@Nonnull WidgetAssertion assertion) {
checkNotNull(
assertion,
"Assertion cannot be null. You must specify an assertion on the matched Flutter widget.");
WidgetInfo widgetInfo = performInternal(new WidgetInfoFetcher());
if (widgetInfo == null) {
Log.w(TAG, String.format("Widget info that matches %s is null.", widgetMatcher));
throw new NoMatchingWidgetException(
String.format("Widget info that matches %s is null.", widgetMatcher));
}
FlutterViewAssertion flutterViewAssertion = new FlutterViewAssertion(assertion, widgetInfo);
onView(flutterViewMatcher).check(flutterViewAssertion);
return this;
}
@SuppressWarnings("unchecked")
private <T> T performInternal(FlutterAction<T> flutterAction) {
checkNotNull(
flutterAction,
"The action cannot be null. You must specify an action to perform on the matched"
+ " Flutter widget.");
FlutterViewAction<T> flutterViewAction =
new FlutterViewAction(
widgetMatcher, flutterAction, okHttpClient, idGenerator, taskExecutor);
onView(flutterViewMatcher).perform(flutterViewAction);
T result;
try {
if (timeout != null && timeout.getQuantity() > 0) {
result = flutterViewAction.waitUntilCompleted(timeout.getQuantity(), timeout.getUnit());
} else {
result = flutterViewAction.waitUntilCompleted();
}
return result;
} catch (ExecutionException e) {
propagateException(e.getCause());
} catch (InterruptedException | TimeoutException | RuntimeException e) {
propagateException(e);
}
return null;
}
/**
* Propagates exception through #onView so that it get a chance to be handled by the registered
* {@code FailureHandler}.
*/
private void propagateException(Throwable t) {
onView(flutterViewMatcher).perform(new ExceptionPropagator(t));
}
/**
* An exception wrapper that propagates an exception through {@code #onView}, so that it can be
* handled by the registered {@code FailureHandler} for the underlying {@code ViewInteraction}.
*/
static class ExceptionPropagator implements ViewAction {
private final RuntimeException exception;
public ExceptionPropagator(RuntimeException exception) {
this.exception = checkNotNull(exception);
}
public ExceptionPropagator(Throwable t) {
this(new RuntimeException(t));
}
@Override
public String getDescription() {
return "Propagate: " + exception;
}
@Override
public void perform(UiController uiController, View view) {
throw exception;
}
@SuppressWarnings("unchecked")
@Override
public Matcher<View> getConstraints() {
return any(View.class);
}
}
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/EspressoFlutter.java",
"repo_id": "plugins",
"token_count": 2642
} | 1,212 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.api;
import static com.google.common.base.Preconditions.checkNotNull;
import androidx.test.espresso.flutter.model.WidgetInfo;
import com.google.common.annotations.Beta;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Nonnull;
import org.hamcrest.TypeSafeMatcher;
/**
* Base matcher for Flutter widgets.
*
* <p>A widget matcher's function is two-fold:
*
* <ul>
* <li>A matcher that can be passed into Flutter for selecting a Flutter widget.
* <li>Works with the {@code MatchesWidgetAssertion} to assert on a widget's properties.
* </ul>
*/
@Beta
public abstract class WidgetMatcher extends TypeSafeMatcher<WidgetInfo> {
@Expose
@SerializedName("finderType")
protected String matcherId;
/**
* Constructs a {@code WidgetMatcher} instance with the given {@code matcherId}.
*
* @param matcherId the matcher id that represents this widget matcher.
*/
public WidgetMatcher(@Nonnull String matcherId) {
this.matcherId = checkNotNull(matcherId);
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/WidgetMatcher.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/api/WidgetMatcher.java",
"repo_id": "plugins",
"token_count": 403
} | 1,213 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.internal.protocol.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import android.util.Log;
import android.view.View;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.dart.DartExecutor;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/** Util class for dealing with Dart VM service protocols. */
public final class DartVmServiceUtil {
private static final String TAG = DartVmServiceUtil.class.getSimpleName();
/**
* Converts the Dart VM observatory http server URL to the service protocol WebSocket URL.
*
* @param observatoryUrl The Dart VM http server URL that can be converted to a service protocol
* URI.
*/
public static URI getServiceProtocolUri(String observatoryUrl) {
if (isNullOrEmpty(observatoryUrl)) {
throw new RuntimeException(
"Dart VM Observatory is not enabled. "
+ "Please make sure your Flutter app is running under debug mode.");
}
try {
new URL(observatoryUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(
String.format("Dart VM Observatory url %s is malformed.", observatoryUrl), e);
}
// Constructs the service protocol URL based on the Observatory http url.
// For example, http://127.0.0.1:39694/qsnVeidc78Y=/ -> ws://127.0.0.1:39694/qsnVeidc78Y=/ws.
int schemaIndex = observatoryUrl.indexOf(":");
String serviceProtocolUri = "ws" + observatoryUrl.substring(schemaIndex);
if (!observatoryUrl.endsWith("/")) {
serviceProtocolUri += "/";
}
serviceProtocolUri += "ws";
Log.i(TAG, "Dart VM service protocol runs at uri: " + serviceProtocolUri);
try {
return new URI(serviceProtocolUri);
} catch (URISyntaxException e) {
// Should never happen.
throw new RuntimeException("Illegal Dart VM service protocol URI: " + serviceProtocolUri, e);
}
}
/** Gets the Dart isolate ID for the given {@code flutterView}. */
public static String getDartIsolateId(View flutterView) {
checkNotNull(flutterView, "The Flutter View instance cannot be null.");
String uiIsolateId = getDartExecutor(flutterView).getIsolateServiceId();
Log.d(
TAG,
String.format(
"Dart isolate ID for the Flutter View [id: %d]: %s.",
flutterView.getId(), uiIsolateId));
return uiIsolateId;
}
/** Gets the Dart executor for the given {@code flutterView}. */
@SuppressWarnings("deprecation")
public static DartExecutor getDartExecutor(View flutterView) {
checkNotNull(flutterView, "The Flutter View instance cannot be null.");
// Flutter's embedding is in the phase of rewriting/refactoring. Let's be compatible with both
// the old and the new FlutterView classes.
if (flutterView instanceof io.flutter.view.FlutterView) {
return ((io.flutter.view.FlutterView) flutterView).getDartExecutor();
} else if (flutterView instanceof io.flutter.embedding.android.FlutterView) {
FlutterEngine flutterEngine =
((io.flutter.embedding.android.FlutterView) flutterView).getAttachedFlutterEngine();
if (flutterEngine == null) {
throw new FlutterProtocolException(
String.format(
"No Flutter engine attached to the Flutter view [id: %d].", flutterView.getId()));
}
return flutterEngine.getDartExecutor();
} else {
throw new FlutterProtocolException(
String.format("This is not a Flutter View instance [id: %d].", flutterView.getId()));
}
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/internal/protocol/impl/DartVmServiceUtil.java",
"repo_id": "plugins",
"token_count": 1383
} | 1,214 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package androidx.test.espresso.flutter.matcher;
import static com.google.common.base.Preconditions.checkNotNull;
import androidx.test.espresso.flutter.api.WidgetMatcher;
import androidx.test.espresso.flutter.model.WidgetInfo;
import com.google.gson.annotations.Expose;
import javax.annotation.Nonnull;
import org.hamcrest.Description;
/** A matcher that matches a Flutter widget with a given text. */
public final class WithTextMatcher extends WidgetMatcher {
@Expose private final String text;
/**
* Constructs the matcher with the given text to be matched with.
*
* @param text the text to be matched with.
*/
WithTextMatcher(@Nonnull String text) {
super("ByText");
this.text = checkNotNull(text);
}
/** Returns the text string that shall be matched for the widget. */
public String getText() {
return text;
}
@Override
public String toString() {
return "with text: " + text;
}
@Override
protected boolean matchesSafely(WidgetInfo widget) {
return text.equals(widget.getText());
}
@Override
public void describeTo(Description description) {
description.appendText("with text: ").appendText(text);
}
}
| plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/WithTextMatcher.java/0 | {
"file_path": "plugins/packages/espresso/android/src/main/java/androidx/test/espresso/flutter/matcher/WithTextMatcher.java",
"repo_id": "plugins",
"token_count": 414
} | 1,215 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
/// Home Page of the application
class HomePage extends StatelessWidget {
/// Default Constructor
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final ButtonStyle style = ElevatedButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: Colors.blue,
// ignore: deprecated_member_use
onPrimary: Colors.white,
);
return Scaffold(
appBar: AppBar(
title: const Text('File Selector Demo Home Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: style,
child: const Text('Open a text file'),
onPressed: () => Navigator.pushNamed(context, '/open/text'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Open an image'),
onPressed: () => Navigator.pushNamed(context, '/open/image'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Open multiple images'),
onPressed: () => Navigator.pushNamed(context, '/open/images'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Save a file'),
onPressed: () => Navigator.pushNamed(context, '/save/text'),
),
const SizedBox(height: 10),
ElevatedButton(
style: style,
child: const Text('Open a get directory dialog'),
onPressed: () => Navigator.pushNamed(context, '/directory'),
),
],
),
),
);
}
}
| plugins/packages/file_selector/file_selector/example/lib/home_page.dart/0 | {
"file_path": "plugins/packages/file_selector/file_selector/example/lib/home_page.dart",
"repo_id": "plugins",
"token_count": 980
} | 1,216 |
name: file_selector
description: Flutter plugin for opening and saving files, or selecting
directories, using native file selection UI.
repository: https://github.com/flutter/plugins/tree/main/packages/file_selector/file_selector
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+file_selector%22
version: 0.9.2+2
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
flutter:
plugin:
platforms:
ios:
default_package: file_selector_ios
linux:
default_package: file_selector_linux
macos:
default_package: file_selector_macos
web:
default_package: file_selector_web
windows:
default_package: file_selector_windows
dependencies:
file_selector_ios: ^0.5.0
file_selector_linux: ^0.9.0
file_selector_macos: ^0.9.0
file_selector_platform_interface: ^2.2.0
file_selector_web: ^0.9.0
file_selector_windows: ^0.9.0
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
plugin_platform_interface: ^2.0.0
test: ^1.16.3
| plugins/packages/file_selector/file_selector/pubspec.yaml/0 | {
"file_path": "plugins/packages/file_selector/file_selector/pubspec.yaml",
"repo_id": "plugins",
"token_count": 468
} | 1,217 |
# file\_selector\_linux
The Linux implementation of [`file_selector`][1].
## Usage
This package is [endorsed][2], which means you can simply use `file_selector`
normally. This package will be automatically included in your app when you do.
[1]: https://pub.dev/packages/file_selector
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
| plugins/packages/file_selector/file_selector_linux/README.md/0 | {
"file_path": "plugins/packages/file_selector/file_selector_linux/README.md",
"repo_id": "plugins",
"token_count": 123
} | 1,218 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'file_selector_macos'
s.version = '0.0.1'
s.summary = 'macOS implementation of file_selector.'
s.description = <<-DESC
Displays native macOS open and save panels.
DESC
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.homepage = 'https://github.com/flutter/plugins/tree/main/packages/file_selector'
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/plugins/tree/main/packages/file_selector/file_selector_macos' }
s.source_files = 'Classes/**/*'
s.dependency 'FlutterMacOS'
s.platform = :osx, '10.11'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.swift_version = '5.0'
end
| plugins/packages/file_selector/file_selector_macos/macos/file_selector_macos.podspec/0 | {
"file_path": "plugins/packages/file_selector/file_selector_macos/macos/file_selector_macos.podspec",
"repo_id": "plugins",
"token_count": 415
} | 1,219 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.