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.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:path_provider_foundation/path_provider_foundation.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
void main() {
runApp(const MyApp());
}
/// Sample app
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String? _tempDirectory = 'Unknown';
String? _downloadsDirectory = 'Unknown';
String? _libraryDirectory = 'Unknown';
String? _appSupportDirectory = 'Unknown';
String? _documentsDirectory = 'Unknown';
String? _containerDirectory = 'Unknown';
String? _cacheDirectory = 'Unknown';
@override
void initState() {
super.initState();
initDirectories();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initDirectories() async {
String? tempDirectory;
String? downloadsDirectory;
String? appSupportDirectory;
String? libraryDirectory;
String? documentsDirectory;
String? containerDirectory;
String? cacheDirectory;
final PathProviderPlatform provider = PathProviderPlatform.instance;
final PathProviderFoundation providerFoundation = PathProviderFoundation();
try {
tempDirectory = await provider.getTemporaryPath();
} catch (exception) {
tempDirectory = 'Failed to get temp directory: $exception';
}
try {
downloadsDirectory = await provider.getDownloadsPath();
} catch (exception) {
downloadsDirectory = 'Failed to get downloads directory: $exception';
}
try {
documentsDirectory = await provider.getApplicationDocumentsPath();
} catch (exception) {
documentsDirectory = 'Failed to get documents directory: $exception';
}
try {
libraryDirectory = await provider.getLibraryPath();
} catch (exception) {
libraryDirectory = 'Failed to get library directory: $exception';
}
try {
appSupportDirectory = await provider.getApplicationSupportPath();
} catch (exception) {
appSupportDirectory = 'Failed to get app support directory: $exception';
}
try {
containerDirectory = await providerFoundation.getContainerPath(
appGroupIdentifier: 'group.flutter.appGroupTest');
} catch (exception) {
containerDirectory =
'Failed to get app group container directory: $exception';
}
try {
cacheDirectory = await provider.getApplicationCachePath();
} catch (exception) {
cacheDirectory = 'Failed to get cache directory: $exception';
}
setState(() {
_tempDirectory = tempDirectory;
_downloadsDirectory = downloadsDirectory;
_libraryDirectory = libraryDirectory;
_appSupportDirectory = appSupportDirectory;
_documentsDirectory = documentsDirectory;
_containerDirectory = containerDirectory;
_cacheDirectory = cacheDirectory;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Path Provider example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text('Temp Directory: $_tempDirectory\n'),
Text('Documents Directory: $_documentsDirectory\n'),
Text('Downloads Directory: $_downloadsDirectory\n'),
Text('Library Directory: $_libraryDirectory\n'),
Text('Application Support Directory: $_appSupportDirectory\n'),
Text('App Group Container Directory: $_containerDirectory\n'),
Text('Cache Directory: $_cacheDirectory\n'),
],
),
),
),
);
}
}
| packages/packages/path_provider/path_provider_foundation/example/lib/main.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_foundation/example/lib/main.dart",
"repo_id": "packages",
"token_count": 1361
} | 1,050 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
input: 'pigeons/messages.dart',
swiftOut: 'macos/Classes/messages.g.swift',
dartOut: 'lib/messages.g.dart',
dartTestOut: 'test/messages_test.g.dart',
copyrightHeader: 'pigeons/copyright.txt',
))
enum DirectoryType {
applicationDocuments,
applicationSupport,
downloads,
library,
temp,
applicationCache,
}
@HostApi(dartHostTestHandler: 'TestPathProviderApi')
abstract class PathProviderApi {
String? getDirectoryPath(DirectoryType type);
String? getContainerPath(String appGroupIdentifier);
}
| packages/packages/path_provider/path_provider_foundation/pigeons/messages.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_foundation/pigeons/messages.dart",
"repo_id": "packages",
"token_count": 249
} | 1,051 |
// 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:path_provider_linux/path_provider_linux.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:xdg_directories/xdg_directories.dart' as xdg;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
PathProviderLinux.registerWith();
test('registered instance', () {
expect(PathProviderPlatform.instance, isA<PathProviderLinux>());
});
test('getTemporaryPath defaults to TMPDIR', () async {
final PathProviderPlatform plugin = PathProviderLinux.private(
environment: <String, String>{'TMPDIR': '/run/user/0/tmp'},
);
expect(await plugin.getTemporaryPath(), '/run/user/0/tmp');
});
test('getTemporaryPath uses fallback if TMPDIR is empty', () async {
final PathProviderPlatform plugin = PathProviderLinux.private(
environment: <String, String>{'TMPDIR': ''},
);
expect(await plugin.getTemporaryPath(), '/tmp');
});
test('getTemporaryPath uses fallback if TMPDIR is unset', () async {
final PathProviderPlatform plugin = PathProviderLinux.private(
environment: <String, String>{},
);
expect(await plugin.getTemporaryPath(), '/tmp');
});
test('getApplicationSupportPath', () async {
final PathProviderPlatform plugin = PathProviderLinux.private(
executableName: 'path_provider_linux_test_binary',
applicationId: 'com.example.Test');
// Note this will fail if ${xdg.dataHome.path}/path_provider_linux_test_binary exists on the local filesystem.
expect(await plugin.getApplicationSupportPath(),
'${xdg.dataHome.path}/com.example.Test');
});
test('getApplicationSupportPath uses executable name if no application Id',
() async {
final PathProviderPlatform plugin = PathProviderLinux.private(
executableName: 'path_provider_linux_test_binary');
expect(await plugin.getApplicationSupportPath(),
'${xdg.dataHome.path}/path_provider_linux_test_binary');
});
test('getApplicationDocumentsPath', () async {
final PathProviderPlatform plugin = PathProviderPlatform.instance;
expect(await plugin.getApplicationDocumentsPath(), startsWith('/'));
});
test('getApplicationCachePath', () async {
final PathProviderPlatform plugin = PathProviderLinux.private(
executableName: 'path_provider_linux_test_binary');
expect(await plugin.getApplicationCachePath(),
'${xdg.cacheHome.path}/path_provider_linux_test_binary');
});
test('getDownloadsPath', () async {
final PathProviderPlatform plugin = PathProviderPlatform.instance;
expect(await plugin.getDownloadsPath(), startsWith('/'));
});
}
| packages/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart",
"repo_id": "packages",
"token_count": 916
} | 1,052 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/pigeon/example/app/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/pigeon/example/app/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 1,053 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'src/messages.g.dart';
// #docregion main-dart-flutter
class _ExampleFlutterApi implements MessageFlutterApi {
@override
String flutterMethod(String? aString) {
return aString ?? '';
}
}
// #enddocregion main-dart-flutter
void main() {
// #docregion main-dart-flutter
MessageFlutterApi.setup(_ExampleFlutterApi());
// #enddocregion main-dart-flutter
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Pigeon Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Pigeon Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final ExampleHostApi _hostApi = ExampleHostApi();
String? _hostCallResult;
// #docregion main-dart
final ExampleHostApi _api = ExampleHostApi();
/// Calls host method `add` with provided arguments.
Future<int> add(int a, int b) async {
try {
return await _api.add(a, b);
} catch (e) {
// handle error.
return 0;
}
}
/// Sends message through host api using `MessageData` class
/// and api `sendMessage` method.
Future<bool> sendMessage(String messageText) {
final MessageData message = MessageData(
code: Code.one,
data: <String?, String?>{'header': 'this is a header'},
description: 'uri text',
);
try {
return _api.sendMessage(message);
} catch (e) {
// handle error.
return Future<bool>(() => true);
}
}
// #enddocregion main-dart
@override
void initState() {
super.initState();
_hostApi.getHostLanguage().then((String response) {
setState(() {
_hostCallResult = 'Hello from $response!';
});
}).onError<PlatformException>((PlatformException error, StackTrace _) {
setState(() {
_hostCallResult = 'Failed to get host language: ${error.message}';
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_hostCallResult ?? 'Waiting for host language...',
),
if (_hostCallResult == null) const CircularProgressIndicator(),
],
),
),
);
}
}
| packages/packages/pigeon/example/app/lib/main.dart/0 | {
"file_path": "packages/packages/pigeon/example/app/lib/main.dart",
"repo_id": "packages",
"token_count": 1193
} | 1,054 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
// #docregion config
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartOptions: DartOptions(),
cppOptions: CppOptions(namespace: 'pigeon_example'),
cppHeaderOut: 'windows/runner/messages.g.h',
cppSourceOut: 'windows/runner/messages.g.cpp',
kotlinOut:
'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt',
kotlinOptions: KotlinOptions(),
javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java',
javaOptions: JavaOptions(),
swiftOut: 'ios/Runner/Messages.g.swift',
swiftOptions: SwiftOptions(),
objcHeaderOut: 'macos/Runner/messages.g.h',
objcSourceOut: 'macos/Runner/messages.g.m',
// Set this to a unique prefix for your plugin or application, per Objective-C naming conventions.
objcOptions: ObjcOptions(prefix: 'PGN'),
copyrightHeader: 'pigeons/copyright.txt',
dartPackageName: 'pigeon_example_package',
))
// #enddocregion config
// This file and ./messages_test.dart must be identical below this line.
// #docregion host-definitions
enum Code { one, two }
class MessageData {
MessageData({required this.code, required this.data});
String? name;
String? description;
Code code;
Map<String?, String?> data;
}
@HostApi()
abstract class ExampleHostApi {
String getHostLanguage();
// These annotations create more idiomatic naming of methods in Objc and Swift.
@ObjCSelector('addNumber:toNumber:')
@SwiftFunction('add(_:to:)')
int add(int a, int b);
@async
bool sendMessage(MessageData message);
}
// #enddocregion host-definitions
// #docregion flutter-definitions
@FlutterApi()
abstract class MessageFlutterApi {
String flutterMethod(String? aString);
}
// #enddocregion flutter-definitions
| packages/packages/pigeon/example/app/pigeons/messages.dart/0 | {
"file_path": "packages/packages/pigeon/example/app/pigeons/messages.dart",
"repo_id": "packages",
"token_count": 649
} | 1,055 |
// 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 'ast.dart';
import 'functional.dart';
import 'generator.dart';
import 'generator_tools.dart';
import 'pigeon_lib.dart' show TaskQueueType;
/// Documentation open symbol.
const String _docCommentPrefix = '/**';
/// Documentation continuation symbol.
const String _docCommentContinuation = ' *';
/// Documentation close symbol.
const String _docCommentSuffix = ' */';
/// Documentation comment spec.
const DocumentCommentSpecification _docCommentSpec =
DocumentCommentSpecification(
_docCommentPrefix,
closeCommentToken: _docCommentSuffix,
blockContinuationToken: _docCommentContinuation,
);
/// Options that control how Kotlin code will be generated.
class KotlinOptions {
/// Creates a [KotlinOptions] object
const KotlinOptions({
this.package,
this.copyrightHeader,
this.errorClassName,
this.includeErrorClass = true,
});
/// The package where the generated class will live.
final String? package;
/// A copyright header that will get prepended to generated code.
final Iterable<String>? copyrightHeader;
/// The name of the error class used for passing custom error parameters.
final String? errorClassName;
/// Whether to include the error class in generation.
///
/// This should only ever be set to false if you have another generated
/// Kotlin file in the same directory.
final bool includeErrorClass;
/// Creates a [KotlinOptions] from a Map representation where:
/// `x = KotlinOptions.fromMap(x.toMap())`.
static KotlinOptions fromMap(Map<String, Object> map) {
return KotlinOptions(
package: map['package'] as String?,
copyrightHeader: map['copyrightHeader'] as Iterable<String>?,
errorClassName: map['errorClassName'] as String?,
includeErrorClass: map['includeErrorClass'] as bool? ?? true,
);
}
/// Converts a [KotlinOptions] to a Map representation where:
/// `x = KotlinOptions.fromMap(x.toMap())`.
Map<String, Object> toMap() {
final Map<String, Object> result = <String, Object>{
if (package != null) 'package': package!,
if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!,
if (errorClassName != null) 'errorClassName': errorClassName!,
'includeErrorClass': includeErrorClass,
};
return result;
}
/// Overrides any non-null parameters from [options] into this to make a new
/// [KotlinOptions].
KotlinOptions merge(KotlinOptions options) {
return KotlinOptions.fromMap(mergeMaps(toMap(), options.toMap()));
}
}
/// Class that manages all Kotlin code generation.
class KotlinGenerator extends StructuredGenerator<KotlinOptions> {
/// Instantiates a Kotlin Generator.
const KotlinGenerator();
@override
void writeFilePrologue(
KotlinOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
if (generatorOptions.copyrightHeader != null) {
addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// ');
}
indent.writeln('// ${getGeneratedCodeWarning()}');
indent.writeln('// $seeAlsoWarning');
}
@override
void writeFileImports(
KotlinOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
indent.newln();
if (generatorOptions.package != null) {
indent.writeln('package ${generatorOptions.package}');
}
indent.newln();
indent.writeln('import android.util.Log');
indent.writeln('import io.flutter.plugin.common.BasicMessageChannel');
indent.writeln('import io.flutter.plugin.common.BinaryMessenger');
indent.writeln('import io.flutter.plugin.common.MessageCodec');
indent.writeln('import io.flutter.plugin.common.StandardMessageCodec');
indent.writeln('import java.io.ByteArrayOutputStream');
indent.writeln('import java.nio.ByteBuffer');
}
@override
void writeEnum(
KotlinOptions generatorOptions,
Root root,
Indent indent,
Enum anEnum, {
required String dartPackageName,
}) {
indent.newln();
addDocumentationComments(
indent, anEnum.documentationComments, _docCommentSpec);
indent.write('enum class ${anEnum.name}(val raw: Int) ');
indent.addScoped('{', '}', () {
enumerate(anEnum.members, (int index, final EnumMember member) {
addDocumentationComments(
indent, member.documentationComments, _docCommentSpec);
final String nameScreamingSnakeCase = member.name
.replaceAllMapped(
RegExp(r'(?<=[a-z])[A-Z]'), (Match m) => '_${m.group(0)}')
.toUpperCase();
indent.write('$nameScreamingSnakeCase($index)');
if (index != anEnum.members.length - 1) {
indent.addln(',');
} else {
indent.addln(';');
}
});
indent.newln();
indent.write('companion object ');
indent.addScoped('{', '}', () {
indent.write('fun ofRaw(raw: Int): ${anEnum.name}? ');
indent.addScoped('{', '}', () {
indent.writeln('return values().firstOrNull { it.raw == raw }');
});
});
});
}
@override
void writeDataClass(
KotlinOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
const List<String> generatedMessages = <String>[
' Generated class from Pigeon that represents data sent in messages.'
];
indent.newln();
addDocumentationComments(
indent, classDefinition.documentationComments, _docCommentSpec,
generatorComments: generatedMessages);
indent.write('data class ${classDefinition.name} ');
indent.addScoped('(', '', () {
for (final NamedType element
in getFieldsInSerializationOrder(classDefinition)) {
_writeClassField(indent, element);
if (getFieldsInSerializationOrder(classDefinition).last != element) {
indent.addln(',');
} else {
indent.newln();
}
}
});
indent.addScoped(') {', '}', () {
writeClassDecode(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
writeClassEncode(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
});
}
@override
void writeClassEncode(
KotlinOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
indent.write('fun toList(): List<Any?> ');
indent.addScoped('{', '}', () {
indent.write('return listOf<Any?>');
indent.addScoped('(', ')', () {
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
final HostDatatype hostDatatype = _getHostDatatype(root, field);
String toWriteValue = '';
final String fieldName = field.name;
final String safeCall = field.type.isNullable ? '?' : '';
if (field.type.isClass) {
toWriteValue = '$fieldName$safeCall.toList()';
} else if (!hostDatatype.isBuiltin && field.type.isEnum) {
toWriteValue = '$fieldName$safeCall.raw';
} else {
toWriteValue = fieldName;
}
indent.writeln('$toWriteValue,');
}
});
});
}
@override
void writeClassDecode(
KotlinOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
final String className = classDefinition.name;
indent.write('companion object ');
indent.addScoped('{', '}', () {
indent.writeln('@Suppress("UNCHECKED_CAST")');
indent.write('fun fromList(list: List<Any?>): $className ');
indent.addScoped('{', '}', () {
enumerate(getFieldsInSerializationOrder(classDefinition),
(int index, final NamedType field) {
final String listValue = 'list[$index]';
final String fieldType = _kotlinTypeForDartType(field.type);
if (field.type.isNullable) {
if (field.type.isClass) {
indent.write('val ${field.name}: $fieldType? = ');
indent.add('($listValue as List<Any?>?)?.let ');
indent.addScoped('{', '}', () {
indent.writeln('$fieldType.fromList(it)');
});
} else if (field.type.isEnum) {
indent.write('val ${field.name}: $fieldType? = ');
indent.add('($listValue as Int?)?.let ');
indent.addScoped('{', '}', () {
indent.writeln('$fieldType.ofRaw(it)');
});
} else {
indent.writeln(
'val ${field.name} = ${_cast(indent, listValue, type: field.type)}');
}
} else {
if (field.type.isClass) {
indent.writeln(
'val ${field.name} = $fieldType.fromList($listValue as List<Any?>)');
} else if (field.type.isEnum) {
indent.writeln(
'val ${field.name} = $fieldType.ofRaw($listValue as Int)!!');
} else {
indent.writeln(
'val ${field.name} = ${_cast(indent, listValue, type: field.type)}');
}
}
});
indent.write('return $className(');
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
final String comma =
getFieldsInSerializationOrder(classDefinition).last == field
? ''
: ', ';
indent.add('${field.name}$comma');
}
indent.addln(')');
});
});
}
void _writeClassField(Indent indent, NamedType field) {
addDocumentationComments(
indent, field.documentationComments, _docCommentSpec);
indent.write(
'val ${field.name}: ${_nullSafeKotlinTypeForDartType(field.type)}');
final String defaultNil = field.type.isNullable ? ' = null' : '';
indent.add(defaultNil);
}
@override
void writeApis(
KotlinOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
if (root.apis.any((Api api) =>
api is AstHostApi &&
api.methods.any((Method it) => it.isAsynchronous))) {
indent.newln();
}
super.writeApis(generatorOptions, root, indent,
dartPackageName: dartPackageName);
}
/// Writes the code for a flutter [Api], [api].
/// Example:
/// class Foo(private val binaryMessenger: BinaryMessenger) {
/// fun add(x: Int, y: Int, callback: (Int?) -> Unit) {...}
/// }
@override
void writeFlutterApi(
KotlinOptions generatorOptions,
Root root,
Indent indent,
AstFlutterApi api, {
required String dartPackageName,
}) {
final bool isCustomCodec = getCodecClasses(api, root).isNotEmpty;
if (isCustomCodec) {
_writeCodec(indent, api, root);
}
const List<String> generatedMessages = <String>[
' Generated class from Pigeon that represents Flutter messages that can be called from Kotlin.'
];
addDocumentationComments(indent, api.documentationComments, _docCommentSpec,
generatorComments: generatedMessages);
final String apiName = api.name;
indent.writeln('@Suppress("UNCHECKED_CAST")');
indent
.write('class $apiName(private val binaryMessenger: BinaryMessenger) ');
indent.addScoped('{', '}', () {
indent.write('companion object ');
indent.addScoped('{', '}', () {
indent.writeln('/** The codec used by $apiName. */');
indent.write('val codec: MessageCodec<Any?> by lazy ');
indent.addScoped('{', '}', () {
if (isCustomCodec) {
indent.writeln(_getCodecName(api));
} else {
indent.writeln('StandardMessageCodec()');
}
});
});
for (final Method method in api.methods) {
_writeFlutterMethod(
indent,
generatorOptions: generatorOptions,
name: method.name,
parameters: method.parameters,
returnType: method.returnType,
channelName: makeChannelName(api, method, dartPackageName),
documentationComments: method.documentationComments,
dartPackageName: dartPackageName,
);
}
});
}
/// Write the kotlin code that represents a host [Api], [api].
/// Example:
/// interface Foo {
/// Int add(x: Int, y: Int);
/// companion object {
/// fun setUp(binaryMessenger: BinaryMessenger, api: Api) {...}
/// }
/// }
///
@override
void writeHostApi(
KotlinOptions generatorOptions,
Root root,
Indent indent,
AstHostApi api, {
required String dartPackageName,
}) {
final String apiName = api.name;
final bool isCustomCodec = getCodecClasses(api, root).isNotEmpty;
if (isCustomCodec) {
_writeCodec(indent, api, root);
}
const List<String> generatedMessages = <String>[
' Generated interface from Pigeon that represents a handler of messages from Flutter.'
];
addDocumentationComments(indent, api.documentationComments, _docCommentSpec,
generatorComments: generatedMessages);
indent.write('interface $apiName ');
indent.addScoped('{', '}', () {
for (final Method method in api.methods) {
_writeMethodDeclaration(
indent,
name: method.name,
documentationComments: method.documentationComments,
returnType: method.returnType,
parameters: method.parameters,
isAsynchronous: method.isAsynchronous,
);
}
indent.newln();
indent.write('companion object ');
indent.addScoped('{', '}', () {
indent.writeln('/** The codec used by $apiName. */');
indent.write('val codec: MessageCodec<Any?> by lazy ');
indent.addScoped('{', '}', () {
if (isCustomCodec) {
indent.writeln(_getCodecName(api));
} else {
indent.writeln('StandardMessageCodec()');
}
});
indent.writeln(
'/** Sets up an instance of `$apiName` to handle messages through the `binaryMessenger`. */');
indent.writeln('@Suppress("UNCHECKED_CAST")');
indent.write(
'fun setUp(binaryMessenger: BinaryMessenger, api: $apiName?) ');
indent.addScoped('{', '}', () {
for (final Method method in api.methods) {
_writeHostMethodMessageHandler(
indent,
api: api,
name: method.name,
channelName: makeChannelName(api, method, dartPackageName),
taskQueueType: method.taskQueueType,
parameters: method.parameters,
returnType: method.returnType,
isAsynchronous: method.isAsynchronous,
);
}
});
});
});
}
/// Writes the codec class that will be used by [api].
/// Example:
/// private static class FooCodec extends StandardMessageCodec {...}
void _writeCodec(Indent indent, Api api, Root root) {
assert(getCodecClasses(api, root).isNotEmpty);
final Iterable<EnumeratedClass> codecClasses = getCodecClasses(api, root);
final String codecName = _getCodecName(api);
indent.writeln('@Suppress("UNCHECKED_CAST")');
indent.write('private object $codecName : StandardMessageCodec() ');
indent.addScoped('{', '}', () {
indent.write(
'override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? ');
indent.addScoped('{', '}', () {
indent.write('return when (type) ');
indent.addScoped('{', '}', () {
for (final EnumeratedClass customClass in codecClasses) {
indent.write('${customClass.enumeration}.toByte() -> ');
indent.addScoped('{', '}', () {
indent.write('return (readValue(buffer) as? List<Any?>)?.let ');
indent.addScoped('{', '}', () {
indent.writeln('${customClass.name}.fromList(it)');
});
});
}
indent.writeln('else -> super.readValueOfType(type, buffer)');
});
});
indent.write(
'override fun writeValue(stream: ByteArrayOutputStream, value: Any?) ');
indent.writeScoped('{', '}', () {
indent.write('when (value) ');
indent.addScoped('{', '}', () {
for (final EnumeratedClass customClass in codecClasses) {
indent.write('is ${customClass.name} -> ');
indent.addScoped('{', '}', () {
indent.writeln('stream.write(${customClass.enumeration})');
indent.writeln('writeValue(stream, value.toList())');
});
}
indent.writeln('else -> super.writeValue(stream, value)');
});
});
});
indent.newln();
}
void _writeWrapResult(Indent indent) {
indent.newln();
indent.write('private fun wrapResult(result: Any?): List<Any?> ');
indent.addScoped('{', '}', () {
indent.writeln('return listOf(result)');
});
}
void _writeWrapError(KotlinOptions generatorOptions, Indent indent) {
indent.newln();
indent.write('private fun wrapError(exception: Throwable): List<Any?> ');
indent.addScoped('{', '}', () {
indent
.write('if (exception is ${_getErrorClassName(generatorOptions)}) ');
indent.addScoped('{', '}', () {
indent.write('return ');
indent.addScoped('listOf(', ')', () {
indent.writeln('exception.code,');
indent.writeln('exception.message,');
indent.writeln('exception.details');
});
}, addTrailingNewline: false);
indent.addScoped(' else {', '}', () {
indent.write('return ');
indent.addScoped('listOf(', ')', () {
indent.writeln('exception.javaClass.simpleName,');
indent.writeln('exception.toString(),');
indent.writeln(
'"Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception)');
});
});
});
}
void _writeErrorClass(KotlinOptions generatorOptions, Indent indent) {
indent.newln();
indent.writeln('/**');
indent.writeln(
' * Error class for passing custom error details to Flutter via a thrown PlatformException.');
indent.writeln(' * @property code The error code.');
indent.writeln(' * @property message The error message.');
indent.writeln(
' * @property details The error details. Must be a datatype supported by the api codec.');
indent.writeln(' */');
indent.write('class ${_getErrorClassName(generatorOptions)} ');
indent.addScoped('(', ')', () {
indent.writeln('val code: String,');
indent.writeln('override val message: String? = null,');
indent.writeln('val details: Any? = null');
}, addTrailingNewline: false);
indent.addln(' : Throwable()');
}
void _writeCreateConnectionError(
KotlinOptions generatorOptions, Indent indent) {
final String errorClassName = _getErrorClassName(generatorOptions);
indent.newln();
indent.write(
'private fun createConnectionError(channelName: String): $errorClassName ');
indent.addScoped('{', '}', () {
indent.write(
'return $errorClassName("channel-error", "Unable to establish connection on channel: \'\$channelName\'.", "")');
});
}
@override
void writeGeneralUtilities(
KotlinOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
final bool hasHostApi = root.apis
.whereType<AstHostApi>()
.any((Api api) => api.methods.isNotEmpty);
final bool hasFlutterApi = root.apis
.whereType<AstFlutterApi>()
.any((Api api) => api.methods.isNotEmpty);
if (hasHostApi) {
_writeWrapResult(indent);
_writeWrapError(generatorOptions, indent);
}
if (hasFlutterApi) {
_writeCreateConnectionError(generatorOptions, indent);
}
if (generatorOptions.includeErrorClass) {
_writeErrorClass(generatorOptions, indent);
}
}
static void _writeMethodDeclaration(
Indent indent, {
required String name,
required TypeDeclaration returnType,
required List<Parameter> parameters,
List<String> documentationComments = const <String>[],
int? minApiRequirement,
bool isAsynchronous = false,
bool isAbstract = false,
String Function(int index, NamedType type) getArgumentName =
_getArgumentName,
}) {
final List<String> argSignature = <String>[];
if (parameters.isNotEmpty) {
final Iterable<String> argTypes = parameters
.map((NamedType e) => _nullSafeKotlinTypeForDartType(e.type));
final Iterable<String> argNames = indexMap(parameters, getArgumentName);
argSignature.addAll(
map2(
argTypes,
argNames,
(String argType, String argName) {
return '$argName: $argType';
},
),
);
}
final String returnTypeString =
returnType.isVoid ? '' : _nullSafeKotlinTypeForDartType(returnType);
final String resultType = returnType.isVoid ? 'Unit' : returnTypeString;
addDocumentationComments(indent, documentationComments, _docCommentSpec);
if (minApiRequirement != null) {
indent.writeln(
'@androidx.annotation.RequiresApi(api = $minApiRequirement)',
);
}
final String abstractKeyword = isAbstract ? 'abstract ' : '';
if (isAsynchronous) {
argSignature.add('callback: (Result<$resultType>) -> Unit');
indent.writeln('${abstractKeyword}fun $name(${argSignature.join(', ')})');
} else if (returnType.isVoid) {
indent.writeln('${abstractKeyword}fun $name(${argSignature.join(', ')})');
} else {
indent.writeln(
'${abstractKeyword}fun $name(${argSignature.join(', ')}): $returnTypeString',
);
}
}
void _writeHostMethodMessageHandler(
Indent indent, {
required Api api,
required String name,
required String channelName,
required TaskQueueType taskQueueType,
required List<Parameter> parameters,
required TypeDeclaration returnType,
bool isAsynchronous = false,
String Function(List<String> safeArgNames, {required String apiVarName})?
onCreateCall,
}) {
indent.write('run ');
indent.addScoped('{', '}', () {
String? taskQueue;
if (taskQueueType != TaskQueueType.serial) {
taskQueue = 'taskQueue';
indent.writeln(
'val $taskQueue = binaryMessenger.makeBackgroundTaskQueue()');
}
indent.write(
'val channel = BasicMessageChannel<Any?>(binaryMessenger, "$channelName", codec');
if (taskQueue != null) {
indent.addln(', $taskQueue)');
} else {
indent.addln(')');
}
indent.write('if (api != null) ');
indent.addScoped('{', '}', () {
final String messageVarName = parameters.isNotEmpty ? 'message' : '_';
indent.write('channel.setMessageHandler ');
indent.addScoped('{ $messageVarName, reply ->', '}', () {
final List<String> methodArguments = <String>[];
if (parameters.isNotEmpty) {
indent.writeln('val args = message as List<Any?>');
enumerate(parameters, (int index, NamedType arg) {
final String argName = _getSafeArgumentName(index, arg);
final String argIndex = 'args[$index]';
indent.writeln(
'val $argName = ${_castForceUnwrap(argIndex, arg.type, indent)}');
methodArguments.add(argName);
});
}
final String call = onCreateCall != null
? onCreateCall(methodArguments, apiVarName: 'api')
: 'api.$name(${methodArguments.join(', ')})';
if (isAsynchronous) {
indent.write('$call ');
final String resultType = returnType.isVoid
? 'Unit'
: _nullSafeKotlinTypeForDartType(returnType);
indent.addScoped('{ result: Result<$resultType> ->', '}', () {
indent.writeln('val error = result.exceptionOrNull()');
indent.writeScoped('if (error != null) {', '}', () {
indent.writeln('reply.reply(wrapError(error))');
}, addTrailingNewline: false);
indent.addScoped(' else {', '}', () {
final String enumTagNullablePrefix =
returnType.isNullable ? '?' : '!!';
final String enumTag =
returnType.isEnum ? '$enumTagNullablePrefix.raw' : '';
if (returnType.isVoid) {
indent.writeln('reply.reply(wrapResult(null))');
} else {
indent.writeln('val data = result.getOrNull()');
indent.writeln('reply.reply(wrapResult(data$enumTag))');
}
});
});
} else {
indent.writeln('var wrapped: List<Any?>');
indent.write('try ');
indent.addScoped('{', '}', () {
if (returnType.isVoid) {
indent.writeln(call);
indent.writeln('wrapped = listOf<Any?>(null)');
} else {
String enumTag = '';
if (returnType.isEnum) {
final String safeUnwrap = returnType.isNullable ? '?' : '';
enumTag = '$safeUnwrap.raw';
}
indent.writeln('wrapped = listOf<Any?>($call$enumTag)');
}
}, addTrailingNewline: false);
indent.add(' catch (exception: Throwable) ');
indent.addScoped('{', '}', () {
indent.writeln('wrapped = wrapError(exception)');
});
indent.writeln('reply.reply(wrapped)');
}
});
}, addTrailingNewline: false);
indent.addScoped(' else {', '}', () {
indent.writeln('channel.setMessageHandler(null)');
});
});
}
void _writeFlutterMethod(
Indent indent, {
required KotlinOptions generatorOptions,
required String name,
required List<Parameter> parameters,
required TypeDeclaration returnType,
required String channelName,
required String dartPackageName,
List<String> documentationComments = const <String>[],
int? minApiRequirement,
void Function(
Indent indent, {
required List<Parameter> parameters,
required TypeDeclaration returnType,
required String channelName,
required String errorClassName,
}) onWriteBody = _writeFlutterMethodMessageCall,
}) {
_writeMethodDeclaration(
indent,
name: name,
returnType: returnType,
parameters: parameters,
documentationComments: documentationComments,
isAsynchronous: true,
minApiRequirement: minApiRequirement,
getArgumentName: _getSafeArgumentName,
);
final String errorClassName = _getErrorClassName(generatorOptions);
indent.addScoped('{', '}', () {
onWriteBody(
indent,
parameters: parameters,
returnType: returnType,
channelName: channelName,
errorClassName: errorClassName,
);
});
}
static void _writeFlutterMethodMessageCall(
Indent indent, {
required List<Parameter> parameters,
required TypeDeclaration returnType,
required String channelName,
required String errorClassName,
}) {
String sendArgument;
if (parameters.isEmpty) {
sendArgument = 'null';
} else {
final Iterable<String> enumSafeArgNames = indexMap(
parameters,
(int count, NamedType type) =>
_getEnumSafeArgumentExpression(count, type));
sendArgument = 'listOf(${enumSafeArgNames.join(', ')})';
}
const String channel = 'channel';
indent.writeln('val channelName = "$channelName"');
indent.writeln(
'val $channel = BasicMessageChannel<Any?>(binaryMessenger, channelName, codec)');
indent.writeScoped('$channel.send($sendArgument) {', '}', () {
indent.writeScoped('if (it is List<*>) {', '} ', () {
indent.writeScoped('if (it.size > 1) {', '} ', () {
indent.writeln(
'callback(Result.failure($errorClassName(it[0] as String, it[1] as String, it[2] as String?)))');
}, addTrailingNewline: false);
if (!returnType.isNullable && !returnType.isVoid) {
indent.addScoped('else if (it[0] == null) {', '} ', () {
indent.writeln(
'callback(Result.failure($errorClassName("null-error", "Flutter api returned null value for non-null return value.", "")))');
}, addTrailingNewline: false);
}
indent.addScoped('else {', '}', () {
if (returnType.isVoid) {
indent.writeln('callback(Result.success(Unit))');
} else {
const String output = 'output';
// Nullable enums require special handling.
if (returnType.isEnum && returnType.isNullable) {
indent.writeScoped('val $output = (it[0] as Int?)?.let {', '}',
() {
indent.writeln('${returnType.baseName}.ofRaw(it)');
});
} else {
indent.writeln(
'val $output = ${_cast(indent, 'it[0]', type: returnType)}');
}
indent.writeln('callback(Result.success($output))');
}
});
}, addTrailingNewline: false);
indent.addScoped('else {', '} ', () {
indent.writeln(
'callback(Result.failure(createConnectionError(channelName)))');
});
});
}
}
HostDatatype _getHostDatatype(Root root, NamedType field) {
return getFieldHostDatatype(
field, (TypeDeclaration x) => _kotlinTypeForBuiltinDartType(x));
}
/// Calculates the name of the codec that will be generated for [api].
String _getCodecName(Api api) => '${api.name}Codec';
String _getErrorClassName(KotlinOptions generatorOptions) =>
generatorOptions.errorClassName ?? 'FlutterError';
String _getArgumentName(int count, NamedType argument) =>
argument.name.isEmpty ? 'arg$count' : argument.name;
/// Returns an argument name that can be used in a context where it is possible to collide
/// and append `.index` to enums.
String _getEnumSafeArgumentExpression(int count, NamedType argument) {
if (argument.type.isEnum) {
return argument.type.isNullable
? '${_getArgumentName(count, argument)}Arg?.raw'
: '${_getArgumentName(count, argument)}Arg.raw';
}
return '${_getArgumentName(count, argument)}Arg';
}
/// Returns an argument name that can be used in a context where it is possible to collide.
String _getSafeArgumentName(int count, NamedType argument) =>
'${_getArgumentName(count, argument)}Arg';
String _castForceUnwrap(String value, TypeDeclaration type, Indent indent) {
if (type.isEnum) {
final String forceUnwrap = type.isNullable ? '' : '!!';
final String nullableConditionPrefix =
type.isNullable ? 'if ($value == null) null else ' : '';
return '$nullableConditionPrefix${_kotlinTypeForDartType(type)}.ofRaw($value as Int)$forceUnwrap';
} else {
return _cast(indent, value, type: type);
}
}
/// Converts a [List] of [TypeDeclaration]s to a comma separated [String] to be
/// used in Kotlin code.
String _flattenTypeArguments(List<TypeDeclaration> args) {
return args.map(_kotlinTypeForDartType).join(', ');
}
String _kotlinTypeForBuiltinGenericDartType(TypeDeclaration type) {
if (type.typeArguments.isEmpty) {
switch (type.baseName) {
case 'List':
return 'List<Any?>';
case 'Map':
return 'Map<Any, Any?>';
default:
return 'Any';
}
} else {
switch (type.baseName) {
case 'List':
return 'List<${_nullSafeKotlinTypeForDartType(type.typeArguments.first)}>';
case 'Map':
return 'Map<${_nullSafeKotlinTypeForDartType(type.typeArguments.first)}, ${_nullSafeKotlinTypeForDartType(type.typeArguments.last)}>';
default:
return '${type.baseName}<${_flattenTypeArguments(type.typeArguments)}>';
}
}
}
String? _kotlinTypeForBuiltinDartType(TypeDeclaration type) {
const Map<String, String> kotlinTypeForDartTypeMap = <String, String>{
'void': 'Void',
'bool': 'Boolean',
'String': 'String',
'int': 'Long',
'double': 'Double',
'Uint8List': 'ByteArray',
'Int32List': 'IntArray',
'Int64List': 'LongArray',
'Float32List': 'FloatArray',
'Float64List': 'DoubleArray',
'Object': 'Any',
};
if (kotlinTypeForDartTypeMap.containsKey(type.baseName)) {
return kotlinTypeForDartTypeMap[type.baseName];
} else if (type.baseName == 'List' || type.baseName == 'Map') {
return _kotlinTypeForBuiltinGenericDartType(type);
} else {
return null;
}
}
String _kotlinTypeForDartType(TypeDeclaration type) {
return _kotlinTypeForBuiltinDartType(type) ?? type.baseName;
}
String _nullSafeKotlinTypeForDartType(TypeDeclaration type) {
final String nullSafe = type.isNullable ? '?' : '';
return '${_kotlinTypeForDartType(type)}$nullSafe';
}
/// Returns an expression to cast [variable] to [kotlinType].
String _cast(Indent indent, String variable, {required TypeDeclaration type}) {
// Special-case Any, since no-op casts cause warnings.
final String typeString = _kotlinTypeForDartType(type);
if (type.isNullable && typeString == 'Any') {
return variable;
}
if (typeString == 'Int' || typeString == 'Long') {
return '$variable${_castInt(type.isNullable)}';
}
if (type.isEnum) {
if (type.isNullable) {
return '($variable as Int?)?.let {\n'
'${indent.str} $typeString.ofRaw(it)\n'
'${indent.str}}';
}
return '${type.baseName}.ofRaw($variable as Int)!!';
}
return '$variable as ${_nullSafeKotlinTypeForDartType(type)}';
}
String _castInt(bool isNullable) {
final String nullability = isNullable ? '?' : '';
return '.let { if (it is Int) it.toLong() else it as Long$nullability }';
}
| packages/packages/pigeon/lib/kotlin_generator.dart/0 | {
"file_path": "packages/packages/pigeon/lib/kotlin_generator.dart",
"repo_id": "packages",
"token_count": 14217
} | 1,056 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is an example pigeon file that is used in compilation, unit, mock
// handler, and e2e tests.
import 'package:pigeon/pigeon.dart';
@HostApi()
abstract class NullableReturnHostApi {
int? doit();
}
@FlutterApi()
abstract class NullableReturnFlutterApi {
int? doit();
}
@HostApi()
abstract class NullableArgHostApi {
int doit(int? x);
}
@FlutterApi()
abstract class NullableArgFlutterApi {
int? doit(int? x);
}
@HostApi()
abstract class NullableCollectionReturnHostApi {
List<String?>? doit();
}
@FlutterApi()
abstract class NullableCollectionReturnFlutterApi {
List<String?>? doit();
}
@HostApi()
abstract class NullableCollectionArgHostApi {
List<String?> doit(List<String?>? x);
}
@FlutterApi()
abstract class NullableCollectionArgFlutterApi {
List<String?> doit(List<String?>? x);
}
| packages/packages/pigeon/pigeons/nullable_returns.dart/0 | {
"file_path": "packages/packages/pigeon/pigeons/nullable_returns.dart",
"repo_id": "packages",
"token_count": 352
} | 1,057 |
// 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 com.example.alternate_language_test_plugin;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
public class EnumTest {
@Test
public void nullValue() {
Enum.DataWithEnum value = new Enum.DataWithEnum();
value.setState(null);
ArrayList<Object> list = value.toList();
Enum.DataWithEnum readValue = Enum.DataWithEnum.fromList(list);
assertEquals(value.getState(), readValue.getState());
}
}
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/EnumTest.java/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/EnumTest.java",
"repo_id": "packages",
"token_count": 209
} | 1,058 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Flutter;
@import XCTest;
@import alternate_language_test_plugin;
#import "EchoMessenger.h"
///////////////////////////////////////////////////////////////////////////////////////////
@interface NonNullFieldsTest : XCTestCase
@end
///////////////////////////////////////////////////////////////////////////////////////////
@implementation NonNullFieldsTest
- (void)testMake {
NonNullFieldSearchRequest *request = [NonNullFieldSearchRequest makeWithQuery:@"hello"];
XCTAssertEqualObjects(@"hello", request.query);
}
@end
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NonNullFieldsTest.m/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NonNullFieldsTest.m",
"repo_id": "packages",
"token_count": 178
} | 1,059 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Autogenerated from Pigeon, do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import <Foundation/Foundation.h>
@protocol FlutterBinaryMessenger;
@protocol FlutterMessageCodec;
@class FlutterError;
@class FlutterStandardTypedData;
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, AnEnum) {
AnEnumOne = 0,
AnEnumTwo = 1,
AnEnumThree = 2,
AnEnumFortyTwo = 3,
AnEnumFourHundredTwentyTwo = 4,
};
/// Wrapper for AnEnum to allow for nullability.
@interface AnEnumBox : NSObject
@property(nonatomic, assign) AnEnum value;
- (instancetype)initWithValue:(AnEnum)value;
@end
@class AllTypes;
@class AllNullableTypes;
@class AllClassesWrapper;
@class TestMessage;
/// A class containing all supported types.
@interface AllTypes : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithABool:(BOOL)aBool
anInt:(NSInteger)anInt
anInt64:(NSInteger)anInt64
aDouble:(double)aDouble
aByteArray:(FlutterStandardTypedData *)aByteArray
a4ByteArray:(FlutterStandardTypedData *)a4ByteArray
a8ByteArray:(FlutterStandardTypedData *)a8ByteArray
aFloatArray:(FlutterStandardTypedData *)aFloatArray
aList:(NSArray *)aList
aMap:(NSDictionary *)aMap
anEnum:(AnEnum)anEnum
aString:(NSString *)aString
anObject:(id)anObject;
@property(nonatomic, assign) BOOL aBool;
@property(nonatomic, assign) NSInteger anInt;
@property(nonatomic, assign) NSInteger anInt64;
@property(nonatomic, assign) double aDouble;
@property(nonatomic, strong) FlutterStandardTypedData *aByteArray;
@property(nonatomic, strong) FlutterStandardTypedData *a4ByteArray;
@property(nonatomic, strong) FlutterStandardTypedData *a8ByteArray;
@property(nonatomic, strong) FlutterStandardTypedData *aFloatArray;
@property(nonatomic, copy) NSArray *aList;
@property(nonatomic, copy) NSDictionary *aMap;
@property(nonatomic, assign) AnEnum anEnum;
@property(nonatomic, copy) NSString *aString;
@property(nonatomic, strong) id anObject;
@end
/// A class containing all supported nullable types.
@interface AllNullableTypes : NSObject
+ (instancetype)makeWithANullableBool:(nullable NSNumber *)aNullableBool
aNullableInt:(nullable NSNumber *)aNullableInt
aNullableInt64:(nullable NSNumber *)aNullableInt64
aNullableDouble:(nullable NSNumber *)aNullableDouble
aNullableByteArray:(nullable FlutterStandardTypedData *)aNullableByteArray
aNullable4ByteArray:(nullable FlutterStandardTypedData *)aNullable4ByteArray
aNullable8ByteArray:(nullable FlutterStandardTypedData *)aNullable8ByteArray
aNullableFloatArray:(nullable FlutterStandardTypedData *)aNullableFloatArray
aNullableList:(nullable NSArray *)aNullableList
aNullableMap:(nullable NSDictionary *)aNullableMap
nullableNestedList:(nullable NSArray<NSArray<NSNumber *> *> *)nullableNestedList
nullableMapWithAnnotations:
(nullable NSDictionary<NSString *, NSString *> *)nullableMapWithAnnotations
nullableMapWithObject:(nullable NSDictionary<NSString *, id> *)nullableMapWithObject
aNullableEnum:(nullable AnEnumBox *)aNullableEnum
aNullableString:(nullable NSString *)aNullableString
aNullableObject:(nullable id)aNullableObject;
@property(nonatomic, strong, nullable) NSNumber *aNullableBool;
@property(nonatomic, strong, nullable) NSNumber *aNullableInt;
@property(nonatomic, strong, nullable) NSNumber *aNullableInt64;
@property(nonatomic, strong, nullable) NSNumber *aNullableDouble;
@property(nonatomic, strong, nullable) FlutterStandardTypedData *aNullableByteArray;
@property(nonatomic, strong, nullable) FlutterStandardTypedData *aNullable4ByteArray;
@property(nonatomic, strong, nullable) FlutterStandardTypedData *aNullable8ByteArray;
@property(nonatomic, strong, nullable) FlutterStandardTypedData *aNullableFloatArray;
@property(nonatomic, copy, nullable) NSArray *aNullableList;
@property(nonatomic, copy, nullable) NSDictionary *aNullableMap;
@property(nonatomic, copy, nullable) NSArray<NSArray<NSNumber *> *> *nullableNestedList;
@property(nonatomic, copy, nullable)
NSDictionary<NSString *, NSString *> *nullableMapWithAnnotations;
@property(nonatomic, copy, nullable) NSDictionary<NSString *, id> *nullableMapWithObject;
@property(nonatomic, strong, nullable) AnEnumBox *aNullableEnum;
@property(nonatomic, copy, nullable) NSString *aNullableString;
@property(nonatomic, strong, nullable) id aNullableObject;
@end
/// A class for testing nested class handling.
///
/// This is needed to test nested nullable and non-nullable classes,
/// `AllNullableTypes` is non-nullable here as it is easier to instantiate
/// than `AllTypes` when testing doesn't require both (ie. testing null classes).
@interface AllClassesWrapper : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithAllNullableTypes:(AllNullableTypes *)allNullableTypes
allTypes:(nullable AllTypes *)allTypes;
@property(nonatomic, strong) AllNullableTypes *allNullableTypes;
@property(nonatomic, strong, nullable) AllTypes *allTypes;
@end
/// A data class containing a List, used in unit tests.
@interface TestMessage : NSObject
+ (instancetype)makeWithTestList:(nullable NSArray *)testList;
@property(nonatomic, copy, nullable) NSArray *testList;
@end
/// The codec used by HostIntegrationCoreApi.
NSObject<FlutterMessageCodec> *HostIntegrationCoreApiGetCodec(void);
/// The core interface that each host language plugin must implement in
/// platform_test integration tests.
@protocol HostIntegrationCoreApi
/// A no-op function taking no arguments and returning no value, to sanity
/// test basic calling.
- (void)noopWithError:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed object, to test serialization and deserialization.
///
/// @return `nil` only when `error != nil`.
- (nullable AllTypes *)echoAllTypes:(AllTypes *)everything
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns an error, to test error handling.
- (nullable id)throwErrorWithError:(FlutterError *_Nullable *_Nonnull)error;
/// Returns an error from a void function, to test error handling.
- (void)throwErrorFromVoidWithError:(FlutterError *_Nullable *_Nonnull)error;
/// Returns a Flutter error, to test error handling.
- (nullable id)throwFlutterErrorWithError:(FlutterError *_Nullable *_Nonnull)error;
/// Returns passed in int.
///
/// @return `nil` only when `error != nil`.
- (nullable NSNumber *)echoInt:(NSInteger)anInt error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns passed in double.
///
/// @return `nil` only when `error != nil`.
- (nullable NSNumber *)echoDouble:(double)aDouble error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in boolean.
///
/// @return `nil` only when `error != nil`.
- (nullable NSNumber *)echoBool:(BOOL)aBool error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in string.
///
/// @return `nil` only when `error != nil`.
- (nullable NSString *)echoString:(NSString *)aString
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in Uint8List.
///
/// @return `nil` only when `error != nil`.
- (nullable FlutterStandardTypedData *)echoUint8List:(FlutterStandardTypedData *)aUint8List
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in generic Object.
///
/// @return `nil` only when `error != nil`.
- (nullable id)echoObject:(id)anObject error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed list, to test serialization and deserialization.
///
/// @return `nil` only when `error != nil`.
- (nullable NSArray<id> *)echoList:(NSArray<id> *)aList
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed map, to test serialization and deserialization.
///
/// @return `nil` only when `error != nil`.
- (nullable NSDictionary<NSString *, id> *)echoMap:(NSDictionary<NSString *, id> *)aMap
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed map to test nested class serialization and deserialization.
///
/// @return `nil` only when `error != nil`.
- (nullable AllClassesWrapper *)echoClassWrapper:(AllClassesWrapper *)wrapper
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed enum to test serialization and deserialization.
///
/// @return `nil` only when `error != nil`.
- (AnEnumBox *_Nullable)echoEnum:(AnEnum)anEnum error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the default string.
///
/// @return `nil` only when `error != nil`.
- (nullable NSString *)echoNamedDefaultString:(NSString *)aString
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns passed in double.
///
/// @return `nil` only when `error != nil`.
- (nullable NSNumber *)echoOptionalDefaultDouble:(double)aDouble
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns passed in int.
///
/// @return `nil` only when `error != nil`.
- (nullable NSNumber *)echoRequiredInt:(NSInteger)anInt
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed object, to test serialization and deserialization.
- (nullable AllNullableTypes *)echoAllNullableTypes:(nullable AllNullableTypes *)everything
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the inner `aString` value from the wrapped object, to test
/// sending of nested objects.
- (nullable NSString *)extractNestedNullableStringFrom:(AllClassesWrapper *)wrapper
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the inner `aString` value from the wrapped object, to test
/// sending of nested objects.
///
/// @return `nil` only when `error != nil`.
- (nullable AllClassesWrapper *)
createNestedObjectWithNullableString:(nullable NSString *)nullableString
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns passed in arguments of multiple types.
///
/// @return `nil` only when `error != nil`.
- (nullable AllNullableTypes *)sendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool
anInt:(nullable NSNumber *)aNullableInt
aString:(nullable NSString *)aNullableString
error:(FlutterError *_Nullable *_Nonnull)
error;
/// Returns passed in int.
- (nullable NSNumber *)echoNullableInt:(nullable NSNumber *)aNullableInt
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns passed in double.
- (nullable NSNumber *)echoNullableDouble:(nullable NSNumber *)aNullableDouble
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in boolean.
- (nullable NSNumber *)echoNullableBool:(nullable NSNumber *)aNullableBool
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in string.
- (nullable NSString *)echoNullableString:(nullable NSString *)aNullableString
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in Uint8List.
- (nullable FlutterStandardTypedData *)
echoNullableUint8List:(nullable FlutterStandardTypedData *)aNullableUint8List
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in generic Object.
- (nullable id)echoNullableObject:(nullable id)aNullableObject
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed list, to test serialization and deserialization.
- (nullable NSArray<id> *)echoNullableList:(nullable NSArray<id> *)aNullableList
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed map, to test serialization and deserialization.
- (nullable NSDictionary<NSString *, id> *)echoNullableMap:
(nullable NSDictionary<NSString *, id> *)aNullableMap
error:(FlutterError *_Nullable *_Nonnull)error;
- (AnEnumBox *_Nullable)echoNullableEnum:(nullable AnEnumBox *)anEnumBoxed
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns passed in int.
- (nullable NSNumber *)echoOptionalNullableInt:(nullable NSNumber *)aNullableInt
error:(FlutterError *_Nullable *_Nonnull)error;
/// Returns the passed in string.
- (nullable NSString *)echoNamedNullableString:(nullable NSString *)aNullableString
error:(FlutterError *_Nullable *_Nonnull)error;
/// A no-op function taking no arguments and returning no value, to sanity
/// test basic asynchronous calling.
- (void)noopAsyncWithCompletion:(void (^)(FlutterError *_Nullable))completion;
/// Returns passed in int asynchronously.
- (void)echoAsyncInt:(NSInteger)anInt
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns passed in double asynchronously.
- (void)echoAsyncDouble:(double)aDouble
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed in boolean asynchronously.
- (void)echoAsyncBool:(BOOL)aBool
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed string asynchronously.
- (void)echoAsyncString:(NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed in Uint8List asynchronously.
- (void)echoAsyncUint8List:(FlutterStandardTypedData *)aUint8List
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion;
/// Returns the passed in generic Object asynchronously.
- (void)echoAsyncObject:(id)anObject
completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion;
/// Returns the passed list, to test asynchronous serialization and deserialization.
- (void)echoAsyncList:(NSArray<id> *)aList
completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed map, to test asynchronous serialization and deserialization.
- (void)echoAsyncMap:(NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion;
/// Returns the passed enum, to test asynchronous serialization and deserialization.
- (void)echoAsyncEnum:(AnEnum)anEnum
completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion;
/// Responds with an error from an async function returning a value.
- (void)throwAsyncErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion;
/// Responds with an error from an async void function.
- (void)throwAsyncErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion;
/// Responds with a Flutter error from an async function returning a value.
- (void)throwAsyncFlutterErrorWithCompletion:(void (^)(id _Nullable,
FlutterError *_Nullable))completion;
/// Returns the passed object, to test async serialization and deserialization.
- (void)echoAsyncAllTypes:(AllTypes *)everything
completion:(void (^)(AllTypes *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed object, to test serialization and deserialization.
- (void)echoAsyncNullableAllNullableTypes:(nullable AllNullableTypes *)everything
completion:(void (^)(AllNullableTypes *_Nullable,
FlutterError *_Nullable))completion;
/// Returns passed in int asynchronously.
- (void)echoAsyncNullableInt:(nullable NSNumber *)anInt
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns passed in double asynchronously.
- (void)echoAsyncNullableDouble:(nullable NSNumber *)aDouble
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed in boolean asynchronously.
- (void)echoAsyncNullableBool:(nullable NSNumber *)aBool
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed string asynchronously.
- (void)echoAsyncNullableString:(nullable NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed in Uint8List asynchronously.
- (void)echoAsyncNullableUint8List:(nullable FlutterStandardTypedData *)aUint8List
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion;
/// Returns the passed in generic Object asynchronously.
- (void)echoAsyncNullableObject:(nullable id)anObject
completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion;
/// Returns the passed list, to test asynchronous serialization and deserialization.
- (void)echoAsyncNullableList:(nullable NSArray<id> *)aList
completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed map, to test asynchronous serialization and deserialization.
- (void)echoAsyncNullableMap:(nullable NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion;
/// Returns the passed enum, to test asynchronous serialization and deserialization.
- (void)echoAsyncNullableEnum:(nullable AnEnumBox *)anEnumBoxed
completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterNoopWithCompletion:(void (^)(FlutterError *_Nullable))completion;
- (void)callFlutterThrowErrorWithCompletion:(void (^)(id _Nullable,
FlutterError *_Nullable))completion;
- (void)callFlutterThrowErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion;
- (void)callFlutterEchoAllTypes:(AllTypes *)everything
completion:(void (^)(AllTypes *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoAllNullableTypes:(nullable AllNullableTypes *)everything
completion:(void (^)(AllNullableTypes *_Nullable,
FlutterError *_Nullable))completion;
- (void)callFlutterSendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool
anInt:(nullable NSNumber *)aNullableInt
aString:(nullable NSString *)aNullableString
completion:(void (^)(AllNullableTypes *_Nullable,
FlutterError *_Nullable))completion;
- (void)callFlutterEchoBool:(BOOL)aBool
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoInt:(NSInteger)anInt
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoDouble:(double)aDouble
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoString:(NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoUint8List:(FlutterStandardTypedData *)aList
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion;
- (void)callFlutterEchoList:(NSArray<id> *)aList
completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoMap:(NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion;
- (void)callFlutterEchoEnum:(AnEnum)anEnum
completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoNullableBool:(nullable NSNumber *)aBool
completion:
(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoNullableInt:(nullable NSNumber *)anInt
completion:
(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoNullableDouble:(nullable NSNumber *)aDouble
completion:
(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoNullableString:(nullable NSString *)aString
completion:
(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoNullableUint8List:(nullable FlutterStandardTypedData *)aList
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion;
- (void)callFlutterEchoNullableList:(nullable NSArray<id> *)aList
completion:
(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion;
- (void)callFlutterEchoNullableMap:(nullable NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion;
- (void)callFlutterEchoNullableEnum:(nullable AnEnumBox *)anEnumBoxed
completion:
(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion;
@end
extern void SetUpHostIntegrationCoreApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<HostIntegrationCoreApi> *_Nullable api);
/// The codec used by FlutterIntegrationCoreApi.
NSObject<FlutterMessageCodec> *FlutterIntegrationCoreApiGetCodec(void);
/// The core interface that the Dart platform_test code implements for host
/// integration tests to call into.
@interface FlutterIntegrationCoreApi : NSObject
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;
/// A no-op function taking no arguments and returning no value, to sanity
/// test basic calling.
- (void)noopWithCompletion:(void (^)(FlutterError *_Nullable))completion;
/// Responds with an error from an async function returning a value.
- (void)throwErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion;
/// Responds with an error from an async void function.
- (void)throwErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion;
/// Returns the passed object, to test serialization and deserialization.
- (void)echoAllTypes:(AllTypes *)everything
completion:(void (^)(AllTypes *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed object, to test serialization and deserialization.
- (void)echoAllNullableTypes:(nullable AllNullableTypes *)everything
completion:
(void (^)(AllNullableTypes *_Nullable, FlutterError *_Nullable))completion;
/// Returns passed in arguments of multiple types.
///
/// Tests multiple-arity FlutterApi handling.
- (void)sendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool
anInt:(nullable NSNumber *)aNullableInt
aString:(nullable NSString *)aNullableString
completion:(void (^)(AllNullableTypes *_Nullable,
FlutterError *_Nullable))completion;
/// Returns the passed boolean, to test serialization and deserialization.
- (void)echoBool:(BOOL)aBool
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed int, to test serialization and deserialization.
- (void)echoInt:(NSInteger)anInt
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed double, to test serialization and deserialization.
- (void)echoDouble:(double)aDouble
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed string, to test serialization and deserialization.
- (void)echoString:(NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed byte list, to test serialization and deserialization.
- (void)echoUint8List:(FlutterStandardTypedData *)aList
completion:
(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed list, to test serialization and deserialization.
- (void)echoList:(NSArray<id> *)aList
completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed map, to test serialization and deserialization.
- (void)echoMap:(NSDictionary<NSString *, id> *)aMap
completion:
(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed enum to test serialization and deserialization.
- (void)echoEnum:(AnEnum)anEnum
completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed boolean, to test serialization and deserialization.
- (void)echoNullableBool:(nullable NSNumber *)aBool
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed int, to test serialization and deserialization.
- (void)echoNullableInt:(nullable NSNumber *)anInt
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed double, to test serialization and deserialization.
- (void)echoNullableDouble:(nullable NSNumber *)aDouble
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed string, to test serialization and deserialization.
- (void)echoNullableString:(nullable NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed byte list, to test serialization and deserialization.
- (void)echoNullableUint8List:(nullable FlutterStandardTypedData *)aList
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion;
/// Returns the passed list, to test serialization and deserialization.
- (void)echoNullableList:(nullable NSArray<id> *)aList
completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion;
/// Returns the passed map, to test serialization and deserialization.
- (void)echoNullableMap:(nullable NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion;
/// Returns the passed enum to test serialization and deserialization.
- (void)echoNullableEnum:(nullable AnEnumBox *)anEnumBoxed
completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion;
/// A no-op function taking no arguments and returning no value, to sanity
/// test basic asynchronous calling.
- (void)noopAsyncWithCompletion:(void (^)(FlutterError *_Nullable))completion;
/// Returns the passed in generic Object asynchronously.
- (void)echoAsyncString:(NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
@end
/// The codec used by HostTrivialApi.
NSObject<FlutterMessageCodec> *HostTrivialApiGetCodec(void);
/// An API that can be implemented for minimal, compile-only tests.
@protocol HostTrivialApi
- (void)noopWithError:(FlutterError *_Nullable *_Nonnull)error;
@end
extern void SetUpHostTrivialApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<HostTrivialApi> *_Nullable api);
/// The codec used by HostSmallApi.
NSObject<FlutterMessageCodec> *HostSmallApiGetCodec(void);
/// A simple API implemented in some unit tests.
@protocol HostSmallApi
- (void)echoString:(NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
- (void)voidVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion;
@end
extern void SetUpHostSmallApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<HostSmallApi> *_Nullable api);
/// The codec used by FlutterSmallApi.
NSObject<FlutterMessageCodec> *FlutterSmallApiGetCodec(void);
/// A simple API called in some unit tests.
@interface FlutterSmallApi : NSObject
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;
- (void)echoWrappedList:(TestMessage *)msg
completion:(void (^)(TestMessage *_Nullable, FlutterError *_Nullable))completion;
- (void)echoString:(NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion;
@end
NS_ASSUME_NONNULL_END
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/macos/Classes/CoreTests.gen.h/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/macos/Classes/CoreTests.gen.h",
"repo_id": "packages",
"token_count": 12092
} | 1,060 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Autogenerated from Pigeon, do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
PlatformException _createConnectionError(String channelName) {
return PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel: "$channelName".',
);
}
List<Object?> wrapResponse(
{Object? result, PlatformException? error, bool empty = false}) {
if (empty) {
return <Object?>[];
}
if (error == null) {
return <Object?>[result];
}
return <Object?>[error.code, error.message, error.details];
}
enum ReplyType {
success,
error,
}
class NonNullFieldSearchRequest {
NonNullFieldSearchRequest({
required this.query,
});
String query;
Object encode() {
return <Object?>[
query,
];
}
static NonNullFieldSearchRequest decode(Object result) {
result as List<Object?>;
return NonNullFieldSearchRequest(
query: result[0]! as String,
);
}
}
class ExtraData {
ExtraData({
required this.detailA,
required this.detailB,
});
String detailA;
String detailB;
Object encode() {
return <Object?>[
detailA,
detailB,
];
}
static ExtraData decode(Object result) {
result as List<Object?>;
return ExtraData(
detailA: result[0]! as String,
detailB: result[1]! as String,
);
}
}
class NonNullFieldSearchReply {
NonNullFieldSearchReply({
required this.result,
required this.error,
required this.indices,
required this.extraData,
required this.type,
});
String result;
String error;
List<int?> indices;
ExtraData extraData;
ReplyType type;
Object encode() {
return <Object?>[
result,
error,
indices,
extraData.encode(),
type.index,
];
}
static NonNullFieldSearchReply decode(Object result) {
result as List<Object?>;
return NonNullFieldSearchReply(
result: result[0]! as String,
error: result[1]! as String,
indices: (result[2] as List<Object?>?)!.cast<int?>(),
extraData: ExtraData.decode(result[3]! as List<Object?>),
type: ReplyType.values[result[4]! as int],
);
}
}
class _NonNullFieldHostApiCodec extends StandardMessageCodec {
const _NonNullFieldHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is ExtraData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is NonNullFieldSearchReply) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is NonNullFieldSearchRequest) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return ExtraData.decode(readValue(buffer)!);
case 129:
return NonNullFieldSearchReply.decode(readValue(buffer)!);
case 130:
return NonNullFieldSearchRequest.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class NonNullFieldHostApi {
/// Constructor for [NonNullFieldHostApi]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
NonNullFieldHostApi({BinaryMessenger? binaryMessenger})
: __pigeon_binaryMessenger = binaryMessenger;
final BinaryMessenger? __pigeon_binaryMessenger;
static const MessageCodec<Object?> pigeonChannelCodec =
_NonNullFieldHostApiCodec();
Future<NonNullFieldSearchReply> search(
NonNullFieldSearchRequest nested) async {
const String __pigeon_channelName =
'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldHostApi.search';
final BasicMessageChannel<Object?> __pigeon_channel =
BasicMessageChannel<Object?>(
__pigeon_channelName,
pigeonChannelCodec,
binaryMessenger: __pigeon_binaryMessenger,
);
final List<Object?>? __pigeon_replyList =
await __pigeon_channel.send(<Object?>[nested]) as List<Object?>?;
if (__pigeon_replyList == null) {
throw _createConnectionError(__pigeon_channelName);
} else if (__pigeon_replyList.length > 1) {
throw PlatformException(
code: __pigeon_replyList[0]! as String,
message: __pigeon_replyList[1] as String?,
details: __pigeon_replyList[2],
);
} else if (__pigeon_replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (__pigeon_replyList[0] as NonNullFieldSearchReply?)!;
}
}
}
class _NonNullFieldFlutterApiCodec extends StandardMessageCodec {
const _NonNullFieldFlutterApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is ExtraData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is NonNullFieldSearchReply) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is NonNullFieldSearchRequest) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return ExtraData.decode(readValue(buffer)!);
case 129:
return NonNullFieldSearchReply.decode(readValue(buffer)!);
case 130:
return NonNullFieldSearchRequest.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class NonNullFieldFlutterApi {
static const MessageCodec<Object?> pigeonChannelCodec =
_NonNullFieldFlutterApiCodec();
NonNullFieldSearchReply search(NonNullFieldSearchRequest request);
static void setup(NonNullFieldFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<
Object?>(
'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search',
pigeonChannelCodec,
binaryMessenger: binaryMessenger);
if (api == null) {
__pigeon_channel.setMessageHandler(null);
} else {
__pigeon_channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search was null.');
final List<Object?> args = (message as List<Object?>?)!;
final NonNullFieldSearchRequest? arg_request =
(args[0] as NonNullFieldSearchRequest?);
assert(arg_request != null,
'Argument for dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search was null, expected non-null NonNullFieldSearchRequest.');
try {
final NonNullFieldSearchReply output = api.search(arg_request!);
return wrapResponse(result: output);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart",
"repo_id": "packages",
"token_count": 3111
} | 1,061 |
// Mocks generated by Mockito 5.4.1 from annotations
// in shared_test_plugin_code/test/primitive_test.dart.
// Do not manually edit this file.
// @dart=2.19
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'dart:typed_data' as _i4;
import 'dart:ui' as _i5;
import 'package:flutter/services.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
import 'package:shared_test_plugin_code/src/generated/primitive.gen.dart'
as _i6;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [BinaryMessenger].
///
/// See the documentation for Mockito's code generation for more information.
class MockBinaryMessenger extends _i1.Mock implements _i2.BinaryMessenger {
MockBinaryMessenger() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<void> handlePlatformMessage(
String? channel,
_i4.ByteData? data,
_i5.PlatformMessageResponseCallback? callback,
) =>
(super.noSuchMethod(
Invocation.method(
#handlePlatformMessage,
[
channel,
data,
callback,
],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<_i4.ByteData?>? send(
String? channel,
_i4.ByteData? message,
) =>
(super.noSuchMethod(Invocation.method(
#send,
[
channel,
message,
],
)) as _i3.Future<_i4.ByteData?>?);
@override
void setMessageHandler(
String? channel,
_i2.MessageHandler? handler,
) =>
super.noSuchMethod(
Invocation.method(
#setMessageHandler,
[
channel,
handler,
],
),
returnValueForMissingStub: null,
);
}
/// A class which mocks [PrimitiveFlutterApi].
///
/// See the documentation for Mockito's code generation for more information.
class MockPrimitiveFlutterApi extends _i1.Mock
implements _i6.PrimitiveFlutterApi {
MockPrimitiveFlutterApi() {
_i1.throwOnMissingStub(this);
}
@override
int anInt(int? value) => (super.noSuchMethod(
Invocation.method(
#anInt,
[value],
),
returnValue: 0,
) as int);
@override
bool aBool(bool? value) => (super.noSuchMethod(
Invocation.method(
#aBool,
[value],
),
returnValue: false,
) as bool);
@override
String aString(String? value) => (super.noSuchMethod(
Invocation.method(
#aString,
[value],
),
returnValue: '',
) as String);
@override
double aDouble(double? value) => (super.noSuchMethod(
Invocation.method(
#aDouble,
[value],
),
returnValue: 0.0,
) as double);
@override
Map<Object?, Object?> aMap(Map<Object?, Object?>? value) =>
(super.noSuchMethod(
Invocation.method(
#aMap,
[value],
),
returnValue: <Object?, Object?>{},
) as Map<Object?, Object?>);
@override
List<Object?> aList(List<Object?>? value) => (super.noSuchMethod(
Invocation.method(
#aList,
[value],
),
returnValue: <Object?>[],
) as List<Object?>);
@override
_i4.Int32List anInt32List(_i4.Int32List? value) => (super.noSuchMethod(
Invocation.method(
#anInt32List,
[value],
),
returnValue: _i4.Int32List(0),
) as _i4.Int32List);
@override
List<bool?> aBoolList(List<bool?>? value) => (super.noSuchMethod(
Invocation.method(
#aBoolList,
[value],
),
returnValue: <bool?>[],
) as List<bool?>);
@override
Map<String?, int?> aStringIntMap(Map<String?, int?>? value) =>
(super.noSuchMethod(
Invocation.method(
#aStringIntMap,
[value],
),
returnValue: <String?, int?>{},
) as Map<String?, int?>);
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.mocks.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.mocks.dart",
"repo_id": "packages",
"token_count": 2051
} | 1,062 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package com.example.test_plugin
import io.flutter.plugin.common.BinaryMessenger
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import java.nio.ByteBuffer
import java.util.ArrayList
import junit.framework.TestCase
import org.junit.Test
internal class EnumTest : TestCase() {
@Test
fun testEchoHost() {
val binaryMessenger = mockk<BinaryMessenger>()
val api = mockk<EnumApi2Host>()
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Host.echo"
val input = DataWithEnum(EnumState.SNAKE_CASE)
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.echo(any()) } returnsArgument 0
EnumApi2Host.setUp(binaryMessenger, api)
val codec = EnumApi2Host.codec
val message = codec.encodeMessage(listOf(input))
message?.rewind()
handlerSlot.captured.onMessage(message) {
it?.rewind()
@Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped)
wrapped?.let {
assertNotNull(wrapped[0])
assertEquals(input, wrapped[0])
}
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.echo(input) }
}
@Test
fun testEchoFlutter() {
val binaryMessenger = mockk<BinaryMessenger>()
val api = EnumApi2Flutter(binaryMessenger)
val input = DataWithEnum(EnumState.SNAKE_CASE)
every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = EnumApi2Flutter.codec
val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2)
message.position(0)
val args = codec.decodeMessage(message) as ArrayList<*>
val replyData = codec.encodeMessage(args)
replyData?.position(0)
reply.reply(replyData)
}
var didCall = false
api.echo(input) {
didCall = true
assertEquals(input, it.getOrNull())
}
assertTrue(didCall)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/EnumTest.kt/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/EnumTest.kt",
"repo_id": "packages",
"token_count": 908
} | 1,063 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Autogenerated from Pigeon, do not edit directly.
// See also: https://pub.dev/packages/pigeon
#ifndef PIGEON_CORE_TESTS_GEN_H_
#define PIGEON_CORE_TESTS_GEN_H_
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
namespace core_tests_pigeontest {
class CoreTestsTest;
// Generated class from Pigeon.
class FlutterError {
public:
explicit FlutterError(const std::string& code) : code_(code) {}
explicit FlutterError(const std::string& code, const std::string& message)
: code_(code), message_(message) {}
explicit FlutterError(const std::string& code, const std::string& message,
const flutter::EncodableValue& details)
: code_(code), message_(message), details_(details) {}
const std::string& code() const { return code_; }
const std::string& message() const { return message_; }
const flutter::EncodableValue& details() const { return details_; }
private:
std::string code_;
std::string message_;
flutter::EncodableValue details_;
};
template <class T>
class ErrorOr {
public:
ErrorOr(const T& rhs) : v_(rhs) {}
ErrorOr(const T&& rhs) : v_(std::move(rhs)) {}
ErrorOr(const FlutterError& rhs) : v_(rhs) {}
ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {}
bool has_error() const { return std::holds_alternative<FlutterError>(v_); }
const T& value() const { return std::get<T>(v_); };
const FlutterError& error() const { return std::get<FlutterError>(v_); };
private:
friend class HostIntegrationCoreApi;
friend class FlutterIntegrationCoreApi;
friend class HostTrivialApi;
friend class HostSmallApi;
friend class FlutterSmallApi;
ErrorOr() = default;
T TakeValue() && { return std::get<T>(std::move(v_)); }
std::variant<T, FlutterError> v_;
};
enum class AnEnum {
one = 0,
two = 1,
three = 2,
fortyTwo = 3,
fourHundredTwentyTwo = 4
};
// A class containing all supported types.
//
// Generated class from Pigeon that represents data sent in messages.
class AllTypes {
public:
// Constructs an object setting all fields.
explicit AllTypes(bool a_bool, int64_t an_int, int64_t an_int64,
double a_double, const std::vector<uint8_t>& a_byte_array,
const std::vector<int32_t>& a4_byte_array,
const std::vector<int64_t>& a8_byte_array,
const std::vector<double>& a_float_array,
const flutter::EncodableList& a_list,
const flutter::EncodableMap& a_map, const AnEnum& an_enum,
const std::string& a_string,
const flutter::EncodableValue& an_object);
bool a_bool() const;
void set_a_bool(bool value_arg);
int64_t an_int() const;
void set_an_int(int64_t value_arg);
int64_t an_int64() const;
void set_an_int64(int64_t value_arg);
double a_double() const;
void set_a_double(double value_arg);
const std::vector<uint8_t>& a_byte_array() const;
void set_a_byte_array(const std::vector<uint8_t>& value_arg);
const std::vector<int32_t>& a4_byte_array() const;
void set_a4_byte_array(const std::vector<int32_t>& value_arg);
const std::vector<int64_t>& a8_byte_array() const;
void set_a8_byte_array(const std::vector<int64_t>& value_arg);
const std::vector<double>& a_float_array() const;
void set_a_float_array(const std::vector<double>& value_arg);
const flutter::EncodableList& a_list() const;
void set_a_list(const flutter::EncodableList& value_arg);
const flutter::EncodableMap& a_map() const;
void set_a_map(const flutter::EncodableMap& value_arg);
const AnEnum& an_enum() const;
void set_an_enum(const AnEnum& value_arg);
const std::string& a_string() const;
void set_a_string(std::string_view value_arg);
const flutter::EncodableValue& an_object() const;
void set_an_object(const flutter::EncodableValue& value_arg);
private:
static AllTypes FromEncodableList(const flutter::EncodableList& list);
flutter::EncodableList ToEncodableList() const;
friend class AllClassesWrapper;
friend class HostIntegrationCoreApi;
friend class HostIntegrationCoreApiCodecSerializer;
friend class FlutterIntegrationCoreApi;
friend class FlutterIntegrationCoreApiCodecSerializer;
friend class HostTrivialApi;
friend class HostTrivialApiCodecSerializer;
friend class HostSmallApi;
friend class HostSmallApiCodecSerializer;
friend class FlutterSmallApi;
friend class FlutterSmallApiCodecSerializer;
friend class CoreTestsTest;
bool a_bool_;
int64_t an_int_;
int64_t an_int64_;
double a_double_;
std::vector<uint8_t> a_byte_array_;
std::vector<int32_t> a4_byte_array_;
std::vector<int64_t> a8_byte_array_;
std::vector<double> a_float_array_;
flutter::EncodableList a_list_;
flutter::EncodableMap a_map_;
AnEnum an_enum_;
std::string a_string_;
flutter::EncodableValue an_object_;
};
// A class containing all supported nullable types.
//
// Generated class from Pigeon that represents data sent in messages.
class AllNullableTypes {
public:
// Constructs an object setting all non-nullable fields.
AllNullableTypes();
// Constructs an object setting all fields.
explicit AllNullableTypes(
const bool* a_nullable_bool, const int64_t* a_nullable_int,
const int64_t* a_nullable_int64, const double* a_nullable_double,
const std::vector<uint8_t>* a_nullable_byte_array,
const std::vector<int32_t>* a_nullable4_byte_array,
const std::vector<int64_t>* a_nullable8_byte_array,
const std::vector<double>* a_nullable_float_array,
const flutter::EncodableList* a_nullable_list,
const flutter::EncodableMap* a_nullable_map,
const flutter::EncodableList* nullable_nested_list,
const flutter::EncodableMap* nullable_map_with_annotations,
const flutter::EncodableMap* nullable_map_with_object,
const AnEnum* a_nullable_enum, const std::string* a_nullable_string,
const flutter::EncodableValue* a_nullable_object);
const bool* a_nullable_bool() const;
void set_a_nullable_bool(const bool* value_arg);
void set_a_nullable_bool(bool value_arg);
const int64_t* a_nullable_int() const;
void set_a_nullable_int(const int64_t* value_arg);
void set_a_nullable_int(int64_t value_arg);
const int64_t* a_nullable_int64() const;
void set_a_nullable_int64(const int64_t* value_arg);
void set_a_nullable_int64(int64_t value_arg);
const double* a_nullable_double() const;
void set_a_nullable_double(const double* value_arg);
void set_a_nullable_double(double value_arg);
const std::vector<uint8_t>* a_nullable_byte_array() const;
void set_a_nullable_byte_array(const std::vector<uint8_t>* value_arg);
void set_a_nullable_byte_array(const std::vector<uint8_t>& value_arg);
const std::vector<int32_t>* a_nullable4_byte_array() const;
void set_a_nullable4_byte_array(const std::vector<int32_t>* value_arg);
void set_a_nullable4_byte_array(const std::vector<int32_t>& value_arg);
const std::vector<int64_t>* a_nullable8_byte_array() const;
void set_a_nullable8_byte_array(const std::vector<int64_t>* value_arg);
void set_a_nullable8_byte_array(const std::vector<int64_t>& value_arg);
const std::vector<double>* a_nullable_float_array() const;
void set_a_nullable_float_array(const std::vector<double>* value_arg);
void set_a_nullable_float_array(const std::vector<double>& value_arg);
const flutter::EncodableList* a_nullable_list() const;
void set_a_nullable_list(const flutter::EncodableList* value_arg);
void set_a_nullable_list(const flutter::EncodableList& value_arg);
const flutter::EncodableMap* a_nullable_map() const;
void set_a_nullable_map(const flutter::EncodableMap* value_arg);
void set_a_nullable_map(const flutter::EncodableMap& value_arg);
const flutter::EncodableList* nullable_nested_list() const;
void set_nullable_nested_list(const flutter::EncodableList* value_arg);
void set_nullable_nested_list(const flutter::EncodableList& value_arg);
const flutter::EncodableMap* nullable_map_with_annotations() const;
void set_nullable_map_with_annotations(
const flutter::EncodableMap* value_arg);
void set_nullable_map_with_annotations(
const flutter::EncodableMap& value_arg);
const flutter::EncodableMap* nullable_map_with_object() const;
void set_nullable_map_with_object(const flutter::EncodableMap* value_arg);
void set_nullable_map_with_object(const flutter::EncodableMap& value_arg);
const AnEnum* a_nullable_enum() const;
void set_a_nullable_enum(const AnEnum* value_arg);
void set_a_nullable_enum(const AnEnum& value_arg);
const std::string* a_nullable_string() const;
void set_a_nullable_string(const std::string_view* value_arg);
void set_a_nullable_string(std::string_view value_arg);
const flutter::EncodableValue* a_nullable_object() const;
void set_a_nullable_object(const flutter::EncodableValue* value_arg);
void set_a_nullable_object(const flutter::EncodableValue& value_arg);
private:
static AllNullableTypes FromEncodableList(const flutter::EncodableList& list);
flutter::EncodableList ToEncodableList() const;
friend class AllClassesWrapper;
friend class HostIntegrationCoreApi;
friend class HostIntegrationCoreApiCodecSerializer;
friend class FlutterIntegrationCoreApi;
friend class FlutterIntegrationCoreApiCodecSerializer;
friend class HostTrivialApi;
friend class HostTrivialApiCodecSerializer;
friend class HostSmallApi;
friend class HostSmallApiCodecSerializer;
friend class FlutterSmallApi;
friend class FlutterSmallApiCodecSerializer;
friend class CoreTestsTest;
std::optional<bool> a_nullable_bool_;
std::optional<int64_t> a_nullable_int_;
std::optional<int64_t> a_nullable_int64_;
std::optional<double> a_nullable_double_;
std::optional<std::vector<uint8_t>> a_nullable_byte_array_;
std::optional<std::vector<int32_t>> a_nullable4_byte_array_;
std::optional<std::vector<int64_t>> a_nullable8_byte_array_;
std::optional<std::vector<double>> a_nullable_float_array_;
std::optional<flutter::EncodableList> a_nullable_list_;
std::optional<flutter::EncodableMap> a_nullable_map_;
std::optional<flutter::EncodableList> nullable_nested_list_;
std::optional<flutter::EncodableMap> nullable_map_with_annotations_;
std::optional<flutter::EncodableMap> nullable_map_with_object_;
std::optional<AnEnum> a_nullable_enum_;
std::optional<std::string> a_nullable_string_;
std::optional<flutter::EncodableValue> a_nullable_object_;
};
// A class for testing nested class handling.
//
// This is needed to test nested nullable and non-nullable classes,
// `AllNullableTypes` is non-nullable here as it is easier to instantiate
// than `AllTypes` when testing doesn't require both (ie. testing null classes).
//
// Generated class from Pigeon that represents data sent in messages.
class AllClassesWrapper {
public:
// Constructs an object setting all non-nullable fields.
explicit AllClassesWrapper(const AllNullableTypes& all_nullable_types);
// Constructs an object setting all fields.
explicit AllClassesWrapper(const AllNullableTypes& all_nullable_types,
const AllTypes* all_types);
const AllNullableTypes& all_nullable_types() const;
void set_all_nullable_types(const AllNullableTypes& value_arg);
const AllTypes* all_types() const;
void set_all_types(const AllTypes* value_arg);
void set_all_types(const AllTypes& value_arg);
private:
static AllClassesWrapper FromEncodableList(
const flutter::EncodableList& list);
flutter::EncodableList ToEncodableList() const;
friend class HostIntegrationCoreApi;
friend class HostIntegrationCoreApiCodecSerializer;
friend class FlutterIntegrationCoreApi;
friend class FlutterIntegrationCoreApiCodecSerializer;
friend class HostTrivialApi;
friend class HostTrivialApiCodecSerializer;
friend class HostSmallApi;
friend class HostSmallApiCodecSerializer;
friend class FlutterSmallApi;
friend class FlutterSmallApiCodecSerializer;
friend class CoreTestsTest;
AllNullableTypes all_nullable_types_;
std::optional<AllTypes> all_types_;
};
// A data class containing a List, used in unit tests.
//
// Generated class from Pigeon that represents data sent in messages.
class TestMessage {
public:
// Constructs an object setting all non-nullable fields.
TestMessage();
// Constructs an object setting all fields.
explicit TestMessage(const flutter::EncodableList* test_list);
const flutter::EncodableList* test_list() const;
void set_test_list(const flutter::EncodableList* value_arg);
void set_test_list(const flutter::EncodableList& value_arg);
private:
static TestMessage FromEncodableList(const flutter::EncodableList& list);
flutter::EncodableList ToEncodableList() const;
friend class HostIntegrationCoreApi;
friend class HostIntegrationCoreApiCodecSerializer;
friend class FlutterIntegrationCoreApi;
friend class FlutterIntegrationCoreApiCodecSerializer;
friend class HostTrivialApi;
friend class HostTrivialApiCodecSerializer;
friend class HostSmallApi;
friend class HostSmallApiCodecSerializer;
friend class FlutterSmallApi;
friend class FlutterSmallApiCodecSerializer;
friend class CoreTestsTest;
std::optional<flutter::EncodableList> test_list_;
};
class HostIntegrationCoreApiCodecSerializer
: public flutter::StandardCodecSerializer {
public:
HostIntegrationCoreApiCodecSerializer();
inline static HostIntegrationCoreApiCodecSerializer& GetInstance() {
static HostIntegrationCoreApiCodecSerializer sInstance;
return sInstance;
}
void WriteValue(const flutter::EncodableValue& value,
flutter::ByteStreamWriter* stream) const override;
protected:
flutter::EncodableValue ReadValueOfType(
uint8_t type, flutter::ByteStreamReader* stream) const override;
};
// The core interface that each host language plugin must implement in
// platform_test integration tests.
//
// Generated interface from Pigeon that represents a handler of messages from
// Flutter.
class HostIntegrationCoreApi {
public:
HostIntegrationCoreApi(const HostIntegrationCoreApi&) = delete;
HostIntegrationCoreApi& operator=(const HostIntegrationCoreApi&) = delete;
virtual ~HostIntegrationCoreApi() {}
// A no-op function taking no arguments and returning no value, to sanity
// test basic calling.
virtual std::optional<FlutterError> Noop() = 0;
// Returns the passed object, to test serialization and deserialization.
virtual ErrorOr<AllTypes> EchoAllTypes(const AllTypes& everything) = 0;
// Returns an error, to test error handling.
virtual ErrorOr<std::optional<flutter::EncodableValue>> ThrowError() = 0;
// Returns an error from a void function, to test error handling.
virtual std::optional<FlutterError> ThrowErrorFromVoid() = 0;
// Returns a Flutter error, to test error handling.
virtual ErrorOr<std::optional<flutter::EncodableValue>>
ThrowFlutterError() = 0;
// Returns passed in int.
virtual ErrorOr<int64_t> EchoInt(int64_t an_int) = 0;
// Returns passed in double.
virtual ErrorOr<double> EchoDouble(double a_double) = 0;
// Returns the passed in boolean.
virtual ErrorOr<bool> EchoBool(bool a_bool) = 0;
// Returns the passed in string.
virtual ErrorOr<std::string> EchoString(const std::string& a_string) = 0;
// Returns the passed in Uint8List.
virtual ErrorOr<std::vector<uint8_t>> EchoUint8List(
const std::vector<uint8_t>& a_uint8_list) = 0;
// Returns the passed in generic Object.
virtual ErrorOr<flutter::EncodableValue> EchoObject(
const flutter::EncodableValue& an_object) = 0;
// Returns the passed list, to test serialization and deserialization.
virtual ErrorOr<flutter::EncodableList> EchoList(
const flutter::EncodableList& a_list) = 0;
// Returns the passed map, to test serialization and deserialization.
virtual ErrorOr<flutter::EncodableMap> EchoMap(
const flutter::EncodableMap& a_map) = 0;
// Returns the passed map to test nested class serialization and
// deserialization.
virtual ErrorOr<AllClassesWrapper> EchoClassWrapper(
const AllClassesWrapper& wrapper) = 0;
// Returns the passed enum to test serialization and deserialization.
virtual ErrorOr<AnEnum> EchoEnum(const AnEnum& an_enum) = 0;
// Returns the default string.
virtual ErrorOr<std::string> EchoNamedDefaultString(
const std::string& a_string) = 0;
// Returns passed in double.
virtual ErrorOr<double> EchoOptionalDefaultDouble(double a_double) = 0;
// Returns passed in int.
virtual ErrorOr<int64_t> EchoRequiredInt(int64_t an_int) = 0;
// Returns the passed object, to test serialization and deserialization.
virtual ErrorOr<std::optional<AllNullableTypes>> EchoAllNullableTypes(
const AllNullableTypes* everything) = 0;
// Returns the inner `aString` value from the wrapped object, to test
// sending of nested objects.
virtual ErrorOr<std::optional<std::string>> ExtractNestedNullableString(
const AllClassesWrapper& wrapper) = 0;
// Returns the inner `aString` value from the wrapped object, to test
// sending of nested objects.
virtual ErrorOr<AllClassesWrapper> CreateNestedNullableString(
const std::string* nullable_string) = 0;
// Returns passed in arguments of multiple types.
virtual ErrorOr<AllNullableTypes> SendMultipleNullableTypes(
const bool* a_nullable_bool, const int64_t* a_nullable_int,
const std::string* a_nullable_string) = 0;
// Returns passed in int.
virtual ErrorOr<std::optional<int64_t>> EchoNullableInt(
const int64_t* a_nullable_int) = 0;
// Returns passed in double.
virtual ErrorOr<std::optional<double>> EchoNullableDouble(
const double* a_nullable_double) = 0;
// Returns the passed in boolean.
virtual ErrorOr<std::optional<bool>> EchoNullableBool(
const bool* a_nullable_bool) = 0;
// Returns the passed in string.
virtual ErrorOr<std::optional<std::string>> EchoNullableString(
const std::string* a_nullable_string) = 0;
// Returns the passed in Uint8List.
virtual ErrorOr<std::optional<std::vector<uint8_t>>> EchoNullableUint8List(
const std::vector<uint8_t>* a_nullable_uint8_list) = 0;
// Returns the passed in generic Object.
virtual ErrorOr<std::optional<flutter::EncodableValue>> EchoNullableObject(
const flutter::EncodableValue* a_nullable_object) = 0;
// Returns the passed list, to test serialization and deserialization.
virtual ErrorOr<std::optional<flutter::EncodableList>> EchoNullableList(
const flutter::EncodableList* a_nullable_list) = 0;
// Returns the passed map, to test serialization and deserialization.
virtual ErrorOr<std::optional<flutter::EncodableMap>> EchoNullableMap(
const flutter::EncodableMap* a_nullable_map) = 0;
virtual ErrorOr<std::optional<AnEnum>> EchoNullableEnum(
const AnEnum* an_enum) = 0;
// Returns passed in int.
virtual ErrorOr<std::optional<int64_t>> EchoOptionalNullableInt(
const int64_t* a_nullable_int) = 0;
// Returns the passed in string.
virtual ErrorOr<std::optional<std::string>> EchoNamedNullableString(
const std::string* a_nullable_string) = 0;
// A no-op function taking no arguments and returning no value, to sanity
// test basic asynchronous calling.
virtual void NoopAsync(
std::function<void(std::optional<FlutterError> reply)> result) = 0;
// Returns passed in int asynchronously.
virtual void EchoAsyncInt(
int64_t an_int, std::function<void(ErrorOr<int64_t> reply)> result) = 0;
// Returns passed in double asynchronously.
virtual void EchoAsyncDouble(
double a_double, std::function<void(ErrorOr<double> reply)> result) = 0;
// Returns the passed in boolean asynchronously.
virtual void EchoAsyncBool(
bool a_bool, std::function<void(ErrorOr<bool> reply)> result) = 0;
// Returns the passed string asynchronously.
virtual void EchoAsyncString(
const std::string& a_string,
std::function<void(ErrorOr<std::string> reply)> result) = 0;
// Returns the passed in Uint8List asynchronously.
virtual void EchoAsyncUint8List(
const std::vector<uint8_t>& a_uint8_list,
std::function<void(ErrorOr<std::vector<uint8_t>> reply)> result) = 0;
// Returns the passed in generic Object asynchronously.
virtual void EchoAsyncObject(
const flutter::EncodableValue& an_object,
std::function<void(ErrorOr<flutter::EncodableValue> reply)> result) = 0;
// Returns the passed list, to test asynchronous serialization and
// deserialization.
virtual void EchoAsyncList(
const flutter::EncodableList& a_list,
std::function<void(ErrorOr<flutter::EncodableList> reply)> result) = 0;
// Returns the passed map, to test asynchronous serialization and
// deserialization.
virtual void EchoAsyncMap(
const flutter::EncodableMap& a_map,
std::function<void(ErrorOr<flutter::EncodableMap> reply)> result) = 0;
// Returns the passed enum, to test asynchronous serialization and
// deserialization.
virtual void EchoAsyncEnum(
const AnEnum& an_enum,
std::function<void(ErrorOr<AnEnum> reply)> result) = 0;
// Responds with an error from an async function returning a value.
virtual void ThrowAsyncError(
std::function<void(ErrorOr<std::optional<flutter::EncodableValue>> reply)>
result) = 0;
// Responds with an error from an async void function.
virtual void ThrowAsyncErrorFromVoid(
std::function<void(std::optional<FlutterError> reply)> result) = 0;
// Responds with a Flutter error from an async function returning a value.
virtual void ThrowAsyncFlutterError(
std::function<void(ErrorOr<std::optional<flutter::EncodableValue>> reply)>
result) = 0;
// Returns the passed object, to test async serialization and deserialization.
virtual void EchoAsyncAllTypes(
const AllTypes& everything,
std::function<void(ErrorOr<AllTypes> reply)> result) = 0;
// Returns the passed object, to test serialization and deserialization.
virtual void EchoAsyncNullableAllNullableTypes(
const AllNullableTypes* everything,
std::function<void(ErrorOr<std::optional<AllNullableTypes>> reply)>
result) = 0;
// Returns passed in int asynchronously.
virtual void EchoAsyncNullableInt(
const int64_t* an_int,
std::function<void(ErrorOr<std::optional<int64_t>> reply)> result) = 0;
// Returns passed in double asynchronously.
virtual void EchoAsyncNullableDouble(
const double* a_double,
std::function<void(ErrorOr<std::optional<double>> reply)> result) = 0;
// Returns the passed in boolean asynchronously.
virtual void EchoAsyncNullableBool(
const bool* a_bool,
std::function<void(ErrorOr<std::optional<bool>> reply)> result) = 0;
// Returns the passed string asynchronously.
virtual void EchoAsyncNullableString(
const std::string* a_string,
std::function<void(ErrorOr<std::optional<std::string>> reply)>
result) = 0;
// Returns the passed in Uint8List asynchronously.
virtual void EchoAsyncNullableUint8List(
const std::vector<uint8_t>* a_uint8_list,
std::function<void(ErrorOr<std::optional<std::vector<uint8_t>>> reply)>
result) = 0;
// Returns the passed in generic Object asynchronously.
virtual void EchoAsyncNullableObject(
const flutter::EncodableValue* an_object,
std::function<void(ErrorOr<std::optional<flutter::EncodableValue>> reply)>
result) = 0;
// Returns the passed list, to test asynchronous serialization and
// deserialization.
virtual void EchoAsyncNullableList(
const flutter::EncodableList* a_list,
std::function<void(ErrorOr<std::optional<flutter::EncodableList>> reply)>
result) = 0;
// Returns the passed map, to test asynchronous serialization and
// deserialization.
virtual void EchoAsyncNullableMap(
const flutter::EncodableMap* a_map,
std::function<void(ErrorOr<std::optional<flutter::EncodableMap>> reply)>
result) = 0;
// Returns the passed enum, to test asynchronous serialization and
// deserialization.
virtual void EchoAsyncNullableEnum(
const AnEnum* an_enum,
std::function<void(ErrorOr<std::optional<AnEnum>> reply)> result) = 0;
virtual void CallFlutterNoop(
std::function<void(std::optional<FlutterError> reply)> result) = 0;
virtual void CallFlutterThrowError(
std::function<void(ErrorOr<std::optional<flutter::EncodableValue>> reply)>
result) = 0;
virtual void CallFlutterThrowErrorFromVoid(
std::function<void(std::optional<FlutterError> reply)> result) = 0;
virtual void CallFlutterEchoAllTypes(
const AllTypes& everything,
std::function<void(ErrorOr<AllTypes> reply)> result) = 0;
virtual void CallFlutterEchoAllNullableTypes(
const AllNullableTypes* everything,
std::function<void(ErrorOr<std::optional<AllNullableTypes>> reply)>
result) = 0;
virtual void CallFlutterSendMultipleNullableTypes(
const bool* a_nullable_bool, const int64_t* a_nullable_int,
const std::string* a_nullable_string,
std::function<void(ErrorOr<AllNullableTypes> reply)> result) = 0;
virtual void CallFlutterEchoBool(
bool a_bool, std::function<void(ErrorOr<bool> reply)> result) = 0;
virtual void CallFlutterEchoInt(
int64_t an_int, std::function<void(ErrorOr<int64_t> reply)> result) = 0;
virtual void CallFlutterEchoDouble(
double a_double, std::function<void(ErrorOr<double> reply)> result) = 0;
virtual void CallFlutterEchoString(
const std::string& a_string,
std::function<void(ErrorOr<std::string> reply)> result) = 0;
virtual void CallFlutterEchoUint8List(
const std::vector<uint8_t>& a_list,
std::function<void(ErrorOr<std::vector<uint8_t>> reply)> result) = 0;
virtual void CallFlutterEchoList(
const flutter::EncodableList& a_list,
std::function<void(ErrorOr<flutter::EncodableList> reply)> result) = 0;
virtual void CallFlutterEchoMap(
const flutter::EncodableMap& a_map,
std::function<void(ErrorOr<flutter::EncodableMap> reply)> result) = 0;
virtual void CallFlutterEchoEnum(
const AnEnum& an_enum,
std::function<void(ErrorOr<AnEnum> reply)> result) = 0;
virtual void CallFlutterEchoNullableBool(
const bool* a_bool,
std::function<void(ErrorOr<std::optional<bool>> reply)> result) = 0;
virtual void CallFlutterEchoNullableInt(
const int64_t* an_int,
std::function<void(ErrorOr<std::optional<int64_t>> reply)> result) = 0;
virtual void CallFlutterEchoNullableDouble(
const double* a_double,
std::function<void(ErrorOr<std::optional<double>> reply)> result) = 0;
virtual void CallFlutterEchoNullableString(
const std::string* a_string,
std::function<void(ErrorOr<std::optional<std::string>> reply)>
result) = 0;
virtual void CallFlutterEchoNullableUint8List(
const std::vector<uint8_t>* a_list,
std::function<void(ErrorOr<std::optional<std::vector<uint8_t>>> reply)>
result) = 0;
virtual void CallFlutterEchoNullableList(
const flutter::EncodableList* a_list,
std::function<void(ErrorOr<std::optional<flutter::EncodableList>> reply)>
result) = 0;
virtual void CallFlutterEchoNullableMap(
const flutter::EncodableMap* a_map,
std::function<void(ErrorOr<std::optional<flutter::EncodableMap>> reply)>
result) = 0;
virtual void CallFlutterEchoNullableEnum(
const AnEnum* an_enum,
std::function<void(ErrorOr<std::optional<AnEnum>> reply)> result) = 0;
// The codec used by HostIntegrationCoreApi.
static const flutter::StandardMessageCodec& GetCodec();
// Sets up an instance of `HostIntegrationCoreApi` to handle messages through
// the `binary_messenger`.
static void SetUp(flutter::BinaryMessenger* binary_messenger,
HostIntegrationCoreApi* api);
static flutter::EncodableValue WrapError(std::string_view error_message);
static flutter::EncodableValue WrapError(const FlutterError& error);
protected:
HostIntegrationCoreApi() = default;
};
class FlutterIntegrationCoreApiCodecSerializer
: public flutter::StandardCodecSerializer {
public:
FlutterIntegrationCoreApiCodecSerializer();
inline static FlutterIntegrationCoreApiCodecSerializer& GetInstance() {
static FlutterIntegrationCoreApiCodecSerializer sInstance;
return sInstance;
}
void WriteValue(const flutter::EncodableValue& value,
flutter::ByteStreamWriter* stream) const override;
protected:
flutter::EncodableValue ReadValueOfType(
uint8_t type, flutter::ByteStreamReader* stream) const override;
};
// The core interface that the Dart platform_test code implements for host
// integration tests to call into.
//
// Generated class from Pigeon that represents Flutter messages that can be
// called from C++.
class FlutterIntegrationCoreApi {
public:
FlutterIntegrationCoreApi(flutter::BinaryMessenger* binary_messenger);
static const flutter::StandardMessageCodec& GetCodec();
// A no-op function taking no arguments and returning no value, to sanity
// test basic calling.
void Noop(std::function<void(void)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Responds with an error from an async function returning a value.
void ThrowError(
std::function<void(const flutter::EncodableValue*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Responds with an error from an async void function.
void ThrowErrorFromVoid(std::function<void(void)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed object, to test serialization and deserialization.
void EchoAllTypes(const AllTypes& everything,
std::function<void(const AllTypes&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed object, to test serialization and deserialization.
void EchoAllNullableTypes(
const AllNullableTypes* everything,
std::function<void(const AllNullableTypes*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns passed in arguments of multiple types.
//
// Tests multiple-arity FlutterApi handling.
void SendMultipleNullableTypes(
const bool* a_nullable_bool, const int64_t* a_nullable_int,
const std::string* a_nullable_string,
std::function<void(const AllNullableTypes&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed boolean, to test serialization and deserialization.
void EchoBool(bool a_bool, std::function<void(bool)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed int, to test serialization and deserialization.
void EchoInt(int64_t an_int, std::function<void(int64_t)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed double, to test serialization and deserialization.
void EchoDouble(double a_double, std::function<void(double)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed string, to test serialization and deserialization.
void EchoString(const std::string& a_string,
std::function<void(const std::string&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed byte list, to test serialization and deserialization.
void EchoUint8List(
const std::vector<uint8_t>& a_list,
std::function<void(const std::vector<uint8_t>&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed list, to test serialization and deserialization.
void EchoList(const flutter::EncodableList& a_list,
std::function<void(const flutter::EncodableList&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed map, to test serialization and deserialization.
void EchoMap(const flutter::EncodableMap& a_map,
std::function<void(const flutter::EncodableMap&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed enum to test serialization and deserialization.
void EchoEnum(const AnEnum& an_enum,
std::function<void(const AnEnum&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed boolean, to test serialization and deserialization.
void EchoNullableBool(const bool* a_bool,
std::function<void(const bool*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed int, to test serialization and deserialization.
void EchoNullableInt(const int64_t* an_int,
std::function<void(const int64_t*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed double, to test serialization and deserialization.
void EchoNullableDouble(const double* a_double,
std::function<void(const double*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed string, to test serialization and deserialization.
void EchoNullableString(const std::string* a_string,
std::function<void(const std::string*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed byte list, to test serialization and deserialization.
void EchoNullableUint8List(
const std::vector<uint8_t>* a_list,
std::function<void(const std::vector<uint8_t>*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed list, to test serialization and deserialization.
void EchoNullableList(
const flutter::EncodableList* a_list,
std::function<void(const flutter::EncodableList*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed map, to test serialization and deserialization.
void EchoNullableMap(
const flutter::EncodableMap* a_map,
std::function<void(const flutter::EncodableMap*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed enum to test serialization and deserialization.
void EchoNullableEnum(const AnEnum* an_enum,
std::function<void(const AnEnum*)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// A no-op function taking no arguments and returning no value, to sanity
// test basic asynchronous calling.
void NoopAsync(std::function<void(void)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
// Returns the passed in generic Object asynchronously.
void EchoAsyncString(const std::string& a_string,
std::function<void(const std::string&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
private:
flutter::BinaryMessenger* binary_messenger_;
};
// An API that can be implemented for minimal, compile-only tests.
//
// Generated interface from Pigeon that represents a handler of messages from
// Flutter.
class HostTrivialApi {
public:
HostTrivialApi(const HostTrivialApi&) = delete;
HostTrivialApi& operator=(const HostTrivialApi&) = delete;
virtual ~HostTrivialApi() {}
virtual std::optional<FlutterError> Noop() = 0;
// The codec used by HostTrivialApi.
static const flutter::StandardMessageCodec& GetCodec();
// Sets up an instance of `HostTrivialApi` to handle messages through the
// `binary_messenger`.
static void SetUp(flutter::BinaryMessenger* binary_messenger,
HostTrivialApi* api);
static flutter::EncodableValue WrapError(std::string_view error_message);
static flutter::EncodableValue WrapError(const FlutterError& error);
protected:
HostTrivialApi() = default;
};
// A simple API implemented in some unit tests.
//
// Generated interface from Pigeon that represents a handler of messages from
// Flutter.
class HostSmallApi {
public:
HostSmallApi(const HostSmallApi&) = delete;
HostSmallApi& operator=(const HostSmallApi&) = delete;
virtual ~HostSmallApi() {}
virtual void Echo(const std::string& a_string,
std::function<void(ErrorOr<std::string> reply)> result) = 0;
virtual void VoidVoid(
std::function<void(std::optional<FlutterError> reply)> result) = 0;
// The codec used by HostSmallApi.
static const flutter::StandardMessageCodec& GetCodec();
// Sets up an instance of `HostSmallApi` to handle messages through the
// `binary_messenger`.
static void SetUp(flutter::BinaryMessenger* binary_messenger,
HostSmallApi* api);
static flutter::EncodableValue WrapError(std::string_view error_message);
static flutter::EncodableValue WrapError(const FlutterError& error);
protected:
HostSmallApi() = default;
};
class FlutterSmallApiCodecSerializer : public flutter::StandardCodecSerializer {
public:
FlutterSmallApiCodecSerializer();
inline static FlutterSmallApiCodecSerializer& GetInstance() {
static FlutterSmallApiCodecSerializer sInstance;
return sInstance;
}
void WriteValue(const flutter::EncodableValue& value,
flutter::ByteStreamWriter* stream) const override;
protected:
flutter::EncodableValue ReadValueOfType(
uint8_t type, flutter::ByteStreamReader* stream) const override;
};
// A simple API called in some unit tests.
//
// Generated class from Pigeon that represents Flutter messages that can be
// called from C++.
class FlutterSmallApi {
public:
FlutterSmallApi(flutter::BinaryMessenger* binary_messenger);
static const flutter::StandardMessageCodec& GetCodec();
void EchoWrappedList(const TestMessage& msg,
std::function<void(const TestMessage&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
void EchoString(const std::string& a_string,
std::function<void(const std::string&)>&& on_success,
std::function<void(const FlutterError&)>&& on_error);
private:
flutter::BinaryMessenger* binary_messenger_;
};
} // namespace core_tests_pigeontest
#endif // PIGEON_CORE_TESTS_GEN_H_
| packages/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.h/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.h",
"repo_id": "packages",
"token_count": 13802
} | 1,064 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/ast.dart';
import 'package:pigeon/cpp_generator.dart';
import 'package:pigeon/generator_tools.dart';
import 'package:pigeon/pigeon.dart' show Error;
import 'package:test/test.dart';
const String DEFAULT_PACKAGE_NAME = 'test_package';
final Class emptyClass = Class(name: 'className', fields: <NamedType>[
NamedType(
name: 'namedTypeName',
type: const TypeDeclaration(baseName: 'baseName', isNullable: false),
)
]);
final Enum emptyEnum = Enum(
name: 'enumName',
members: <EnumMember>[EnumMember(name: 'enumMemberName')],
);
void main() {
test('gen one api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
isNullable: false,
associatedClass: emptyClass,
),
name: 'input')
],
location: ApiLocation.host,
returnType: TypeDeclaration(
baseName: 'Output',
isNullable: false,
associatedClass: emptyClass,
),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
])
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(generatorOptions, root, sink,
dartPackageName: DEFAULT_PACKAGE_NAME);
final String code = sink.toString();
expect(code, contains('class Input'));
expect(code, contains('class Output'));
expect(code, contains('class Api'));
expect(code, contains('virtual ~Api() {}\n'));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(generatorOptions, root, sink,
dartPackageName: DEFAULT_PACKAGE_NAME);
final String code = sink.toString();
expect(code, contains('Input::Input()'));
expect(code, contains('Output::Output'));
expect(
code,
contains(RegExp(r'void Api::SetUp\(\s*'
r'flutter::BinaryMessenger\* binary_messenger,\s*'
r'Api\* api\s*\)')));
}
});
test('naming follows style', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
isNullable: false,
associatedClass: emptyClass,
),
name: 'someInput')
],
location: ApiLocation.host,
returnType: TypeDeclaration(
baseName: 'Output',
isNullable: false,
associatedClass: emptyClass,
),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'inputField')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'outputField')
])
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(generatorOptions, root, sink,
dartPackageName: DEFAULT_PACKAGE_NAME);
final String code = sink.toString();
// Method name and argument names should be adjusted.
expect(code, contains(' DoSomething(const Input& some_input)'));
// Getters and setters should use optional getter/setter style.
expect(code, contains('bool input_field()'));
expect(code, contains('void set_input_field(bool value_arg)'));
expect(code, contains('bool output_field()'));
expect(code, contains('void set_output_field(bool value_arg)'));
// Instance variables should be adjusted.
expect(code, contains('bool input_field_'));
expect(code, contains('bool output_field_'));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(generatorOptions, root, sink,
dartPackageName: DEFAULT_PACKAGE_NAME);
final String code = sink.toString();
expect(code, contains('encodable_some_input'));
expect(code, contains('Output::output_field()'));
expect(code, contains('Output::set_output_field(bool value_arg)'));
}
});
test('FlutterError fields are private with public accessors', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
),
name: 'someInput')
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code.split('\n'),
containsAllInOrder(<Matcher>[
contains('class FlutterError {'),
contains(' public:'),
contains(' const std::string& code() const { return code_; }'),
contains(
' const std::string& message() const { return message_; }'),
contains(
' const flutter::EncodableValue& details() const { return details_; }'),
contains(' private:'),
contains(' std::string code_;'),
contains(' std::string message_;'),
contains(' flutter::EncodableValue details_;'),
]));
}
});
test('Error field is private with public accessors', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
),
name: 'someInput')
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(generatorOptions, root, sink,
dartPackageName: DEFAULT_PACKAGE_NAME);
final String code = sink.toString();
expect(
code.split('\n'),
containsAllInOrder(<Matcher>[
contains('class ErrorOr {'),
contains(' public:'),
contains(' bool has_error() const {'),
contains(' const T& value() const {'),
contains(' const FlutterError& error() const {'),
contains(' private:'),
contains(' std::variant<T, FlutterError> v_;'),
]));
}
});
test('Spaces before {', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
isNullable: false,
associatedClass: emptyClass,
),
name: 'input')
],
returnType: TypeDeclaration(
baseName: 'Output',
isNullable: false,
associatedClass: emptyClass,
),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
])
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains('){')));
expect(code, isNot(contains('const{')));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains('){')));
expect(code, isNot(contains('const{')));
}
});
test('include blocks follow style', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('''
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
'''));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(headerIncludePath: 'a_header.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('''
#include "a_header.h"
#include <flutter/basic_message_channel.h>
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/standard_message_codec.h>
#include <map>
#include <optional>
#include <string>
'''));
}
});
test('namespaces follows style', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(namespace: 'foo'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('namespace foo {'));
expect(code, contains('} // namespace foo'));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(namespace: 'foo'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('namespace foo {'));
expect(code, contains('} // namespace foo'));
}
});
test('data classes handle nullable fields', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
isNullable: false,
associatedClass: emptyClass,
),
name: 'someInput')
],
returnType: const TypeDeclaration.voidDeclaration(),
)
])
], classes: <Class>[
Class(name: 'Nested', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: true,
),
name: 'nestedValue'),
]),
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: true,
),
name: 'nullableBool'),
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
name: 'nullableInt'),
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'nullableString'),
NamedType(
type: TypeDeclaration(
baseName: 'Nested',
isNullable: true,
associatedClass: emptyClass,
),
name: 'nullableNested'),
]),
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// There should be a default constructor.
expect(code, contains('Nested();'));
// There should be a convenience constructor.
expect(
code,
contains(
RegExp(r'explicit Nested\(\s*const bool\* nested_value\s*\)')));
// Getters should return const pointers.
expect(code, contains('const bool* nullable_bool()'));
expect(code, contains('const int64_t* nullable_int()'));
expect(code, contains('const std::string* nullable_string()'));
expect(code, contains('const Nested* nullable_nested()'));
// Setters should take const pointers.
expect(code, contains('void set_nullable_bool(const bool* value_arg)'));
expect(code, contains('void set_nullable_int(const int64_t* value_arg)'));
// Strings should be string_view rather than string as an argument.
expect(
code,
contains(
'void set_nullable_string(const std::string_view* value_arg)'));
expect(
code, contains('void set_nullable_nested(const Nested* value_arg)'));
// Setters should have non-null-style variants.
expect(code, contains('void set_nullable_bool(bool value_arg)'));
expect(code, contains('void set_nullable_int(int64_t value_arg)'));
expect(code,
contains('void set_nullable_string(std::string_view value_arg)'));
expect(
code, contains('void set_nullable_nested(const Nested& value_arg)'));
// Instance variables should be std::optionals.
expect(code, contains('std::optional<bool> nullable_bool_'));
expect(code, contains('std::optional<int64_t> nullable_int_'));
expect(code, contains('std::optional<std::string> nullable_string_'));
expect(code, contains('std::optional<Nested> nullable_nested_'));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// There should be a default constructor.
expect(code, contains('Nested::Nested() {}'));
// There should be a convenience constructor.
expect(
code,
contains(RegExp(r'Nested::Nested\(\s*const bool\* nested_value\s*\)'
r'\s*:\s*nested_value_\(nested_value \? '
r'std::optional<bool>\(\*nested_value\) : std::nullopt\)\s*{}')));
// Getters extract optionals.
expect(code,
contains('return nullable_bool_ ? &(*nullable_bool_) : nullptr;'));
expect(code,
contains('return nullable_int_ ? &(*nullable_int_) : nullptr;'));
expect(
code,
contains(
'return nullable_string_ ? &(*nullable_string_) : nullptr;'));
expect(
code,
contains(
'return nullable_nested_ ? &(*nullable_nested_) : nullptr;'));
// Setters convert to optionals.
expect(
code,
contains('nullable_bool_ = value_arg ? '
'std::optional<bool>(*value_arg) : std::nullopt;'));
expect(
code,
contains('nullable_int_ = value_arg ? '
'std::optional<int64_t>(*value_arg) : std::nullopt;'));
expect(
code,
contains('nullable_string_ = value_arg ? '
'std::optional<std::string>(*value_arg) : std::nullopt;'));
expect(
code,
contains('nullable_nested_ = value_arg ? '
'std::optional<Nested>(*value_arg) : std::nullopt;'));
// Serialization handles optionals.
expect(
code,
contains('nullable_bool_ ? EncodableValue(*nullable_bool_) '
': EncodableValue()'));
expect(
code,
contains(
'nullable_nested_ ? EncodableValue(nullable_nested_->ToEncodableList()) '
': EncodableValue()'));
// Serialization should use push_back, not initializer lists, to avoid
// copies.
expect(code, contains('list.reserve(4)'));
expect(
code,
contains('list.push_back(nullable_bool_ ? '
'EncodableValue(*nullable_bool_) : '
'EncodableValue())'));
}
});
test('data classes handle non-nullable fields', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
isNullable: false,
associatedClass: emptyClass,
),
name: 'someInput')
],
returnType: const TypeDeclaration.voidDeclaration(),
)
])
], classes: <Class>[
Class(name: 'Nested', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'nestedValue'),
]),
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'nonNullableBool'),
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
),
name: 'nonNullableInt'),
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: false,
),
name: 'nonNullableString'),
NamedType(
type: TypeDeclaration(
baseName: 'Nested',
isNullable: false,
associatedClass: emptyClass,
),
name: 'nonNullableNested'),
]),
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// There should not be a default constructor.
expect(code, isNot(contains('Nested();')));
// There should be a convenience constructor.
expect(code,
contains(RegExp(r'explicit Nested\(\s*bool nested_value\s*\)')));
// POD getters should return copies references.
expect(code, contains('bool non_nullable_bool()'));
expect(code, contains('int64_t non_nullable_int()'));
// Non-POD getters should return const references.
expect(code, contains('const std::string& non_nullable_string()'));
expect(code, contains('const Nested& non_nullable_nested()'));
// POD setters should take values.
expect(code, contains('void set_non_nullable_bool(bool value_arg)'));
expect(code, contains('void set_non_nullable_int(int64_t value_arg)'));
// Strings should be string_view as an argument.
expect(code,
contains('void set_non_nullable_string(std::string_view value_arg)'));
// Other non-POD setters should take const references.
expect(code,
contains('void set_non_nullable_nested(const Nested& value_arg)'));
// Instance variables should be plain types.
expect(code, contains('bool non_nullable_bool_;'));
expect(code, contains('int64_t non_nullable_int_;'));
expect(code, contains('std::string non_nullable_string_;'));
expect(code, contains('Nested non_nullable_nested_;'));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// There should not be a default constructor.
expect(code, isNot(contains('Nested::Nested() {}')));
// There should be a convenience constructor.
expect(
code,
contains(RegExp(r'Nested::Nested\(\s*bool nested_value\s*\)'
r'\s*:\s*nested_value_\(nested_value\)\s*{}')));
// Getters just return the value.
expect(code, contains('return non_nullable_bool_;'));
expect(code, contains('return non_nullable_int_;'));
expect(code, contains('return non_nullable_string_;'));
expect(code, contains('return non_nullable_nested_;'));
// Setters just assign the value.
expect(code, contains('non_nullable_bool_ = value_arg;'));
expect(code, contains('non_nullable_int_ = value_arg;'));
expect(code, contains('non_nullable_string_ = value_arg;'));
expect(code, contains('non_nullable_nested_ = value_arg;'));
// Serialization uses the value directly.
expect(code, contains('EncodableValue(non_nullable_bool_)'));
expect(code, contains('non_nullable_nested_.ToEncodableList()'));
// Serialization should use push_back, not initializer lists, to avoid
// copies.
expect(code, contains('list.reserve(4)'));
expect(
code, contains('list.push_back(EncodableValue(non_nullable_bool_))'));
}
});
test('host nullable return types map correctly', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'returnNullableBool',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'bool',
isNullable: true,
),
),
Method(
name: 'returnNullableInt',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
Method(
name: 'returnNullableString',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
),
Method(
name: 'returnNullableList',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'List',
typeArguments: <TypeDeclaration>[
TypeDeclaration(
baseName: 'String',
isNullable: true,
)
],
isNullable: true,
),
),
Method(
name: 'returnNullableMap',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'Map',
typeArguments: <TypeDeclaration>[
TypeDeclaration(
baseName: 'String',
isNullable: true,
),
TypeDeclaration(
baseName: 'String',
isNullable: true,
)
],
isNullable: true,
),
),
Method(
name: 'returnNullableDataClass',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: TypeDeclaration(
baseName: 'ReturnData',
isNullable: true,
associatedClass: emptyClass,
),
),
])
], classes: <Class>[
Class(name: 'ReturnData', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'aValue'),
]),
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code, contains('ErrorOr<std::optional<bool>> ReturnNullableBool()'));
expect(code,
contains('ErrorOr<std::optional<int64_t>> ReturnNullableInt()'));
expect(
code,
contains(
'ErrorOr<std::optional<std::string>> ReturnNullableString()'));
expect(
code,
contains(
'ErrorOr<std::optional<flutter::EncodableList>> ReturnNullableList()'));
expect(
code,
contains(
'ErrorOr<std::optional<flutter::EncodableMap>> ReturnNullableMap()'));
expect(
code,
contains(
'ErrorOr<std::optional<ReturnData>> ReturnNullableDataClass()'));
}
});
test('host non-nullable return types map correctly', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'returnBool',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
),
Method(
name: 'returnInt',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'int',
isNullable: false,
),
),
Method(
name: 'returnString',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'String',
isNullable: false,
),
),
Method(
name: 'returnList',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'List',
typeArguments: <TypeDeclaration>[
TypeDeclaration(
baseName: 'String',
isNullable: true,
)
],
isNullable: false,
),
),
Method(
name: 'returnMap',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration(
baseName: 'Map',
typeArguments: <TypeDeclaration>[
TypeDeclaration(
baseName: 'String',
isNullable: true,
),
TypeDeclaration(
baseName: 'String',
isNullable: true,
)
],
isNullable: false,
),
),
Method(
name: 'returnDataClass',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: TypeDeclaration(
baseName: 'ReturnData',
isNullable: false,
associatedClass: emptyClass,
),
),
])
], classes: <Class>[
Class(name: 'ReturnData', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'aValue'),
]),
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('ErrorOr<bool> ReturnBool()'));
expect(code, contains('ErrorOr<int64_t> ReturnInt()'));
expect(code, contains('ErrorOr<std::string> ReturnString()'));
expect(code, contains('ErrorOr<flutter::EncodableList> ReturnList()'));
expect(code, contains('ErrorOr<flutter::EncodableMap> ReturnMap()'));
expect(code, contains('ErrorOr<ReturnData> ReturnDataClass()'));
}
});
test('host nullable arguments map correctly', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
name: 'aBool',
type: const TypeDeclaration(
baseName: 'bool',
isNullable: true,
)),
Parameter(
name: 'anInt',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
)),
Parameter(
name: 'aString',
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
)),
Parameter(
name: 'aList',
type: const TypeDeclaration(
baseName: 'List',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'Object', isNullable: true)
],
isNullable: true,
)),
Parameter(
name: 'aMap',
type: const TypeDeclaration(
baseName: 'Map',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'Object', isNullable: true),
],
isNullable: true,
)),
Parameter(
name: 'anObject',
type: TypeDeclaration(
baseName: 'ParameterObject',
isNullable: true,
associatedClass: emptyClass,
)),
Parameter(
name: 'aGenericObject',
type: const TypeDeclaration(
baseName: 'Object',
isNullable: true,
)),
],
returnType: const TypeDeclaration.voidDeclaration(),
),
])
], classes: <Class>[
Class(name: 'ParameterObject', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'aValue'),
]),
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(RegExp(r'DoSomething\(\s*'
r'const bool\* a_bool,\s*'
r'const int64_t\* an_int,\s*'
r'const std::string\* a_string,\s*'
r'const flutter::EncodableList\* a_list,\s*'
r'const flutter::EncodableMap\* a_map,\s*'
r'const ParameterObject\* an_object,\s*'
r'const flutter::EncodableValue\* a_generic_object\s*\)')));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// Most types should just use get_if, since the parameter is a pointer,
// and get_if will automatically handle null values (since a null
// EncodableValue will not match the queried type, so get_if will return
// nullptr).
expect(
code,
contains(
'const auto* a_bool_arg = std::get_if<bool>(&encodable_a_bool_arg);'));
expect(
code,
contains(
'const auto* a_string_arg = std::get_if<std::string>(&encodable_a_string_arg);'));
expect(
code,
contains(
'const auto* a_list_arg = std::get_if<EncodableList>(&encodable_a_list_arg);'));
expect(
code,
contains(
'const auto* a_map_arg = std::get_if<EncodableMap>(&encodable_a_map_arg);'));
// Ints are complicated since there are two possible pointer types, but
// the parameter always needs an int64_t*.
expect(
code,
contains(
'const int64_t an_int_arg_value = encodable_an_int_arg.IsNull() ? 0 : encodable_an_int_arg.LongValue();'));
expect(
code,
contains(
'const auto* an_int_arg = encodable_an_int_arg.IsNull() ? nullptr : &an_int_arg_value;'));
// Custom class types require an extra layer of extraction.
expect(
code,
contains(
'const auto* an_object_arg = &(std::any_cast<const ParameterObject&>(std::get<CustomEncodableValue>(encodable_an_object_arg)));'));
// "Object" requires no extraction at all since it has to use
// EncodableValue directly.
expect(
code,
contains(
'const auto* a_generic_object_arg = &encodable_a_generic_object_arg;'));
}
});
test('host non-nullable arguments map correctly', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
name: 'aBool',
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
)),
Parameter(
name: 'anInt',
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
)),
Parameter(
name: 'aString',
type: const TypeDeclaration(
baseName: 'String',
isNullable: false,
)),
Parameter(
name: 'aList',
type: const TypeDeclaration(
baseName: 'List',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'Object', isNullable: true)
],
isNullable: false,
)),
Parameter(
name: 'aMap',
type: const TypeDeclaration(
baseName: 'Map',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'Object', isNullable: true),
],
isNullable: false,
)),
Parameter(
name: 'anObject',
type: TypeDeclaration(
baseName: 'ParameterObject',
isNullable: false,
associatedClass: emptyClass,
)),
Parameter(
name: 'aGenericObject',
type: const TypeDeclaration(
baseName: 'Object',
isNullable: false,
)),
],
returnType: const TypeDeclaration.voidDeclaration(),
),
])
], classes: <Class>[
Class(name: 'ParameterObject', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'aValue'),
]),
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(RegExp(r'DoSomething\(\s*'
r'bool a_bool,\s*'
r'int64_t an_int,\s*'
r'const std::string& a_string,\s*'
r'const flutter::EncodableList& a_list,\s*'
r'const flutter::EncodableMap& a_map,\s*'
r'const ParameterObject& an_object,\s*'
r'const flutter::EncodableValue& a_generic_object\s*\)')));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// Most types should extract references. Since the type is non-nullable,
// there's only one possible type.
expect(
code,
contains(
'const auto& a_bool_arg = std::get<bool>(encodable_a_bool_arg);'));
expect(
code,
contains(
'const auto& a_string_arg = std::get<std::string>(encodable_a_string_arg);'));
expect(
code,
contains(
'const auto& a_list_arg = std::get<EncodableList>(encodable_a_list_arg);'));
expect(
code,
contains(
'const auto& a_map_arg = std::get<EncodableMap>(encodable_a_map_arg);'));
// Ints use a copy since there are two possible reference types, but
// the parameter always needs an int64_t.
expect(
code,
contains(
'const int64_t an_int_arg = encodable_an_int_arg.LongValue();',
));
// Custom class types require an extra layer of extraction.
expect(
code,
contains(
'const auto& an_object_arg = std::any_cast<const ParameterObject&>(std::get<CustomEncodableValue>(encodable_an_object_arg));'));
// "Object" requires no extraction at all since it has to use
// EncodableValue directly.
expect(
code,
contains(
'const auto& a_generic_object_arg = encodable_a_generic_object_arg;'));
}
});
test('flutter nullable arguments map correctly', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
name: 'aBool',
type: const TypeDeclaration(
baseName: 'bool',
isNullable: true,
)),
Parameter(
name: 'anInt',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
)),
Parameter(
name: 'aString',
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
)),
Parameter(
name: 'aList',
type: const TypeDeclaration(
baseName: 'List',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'Object', isNullable: true)
],
isNullable: true,
)),
Parameter(
name: 'aMap',
type: const TypeDeclaration(
baseName: 'Map',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'Object', isNullable: true),
],
isNullable: true,
)),
Parameter(
name: 'anObject',
type: TypeDeclaration(
baseName: 'ParameterObject',
isNullable: true,
associatedClass: emptyClass,
)),
Parameter(
name: 'aGenericObject',
type: const TypeDeclaration(
baseName: 'Object',
isNullable: true,
)),
],
returnType: const TypeDeclaration(
baseName: 'bool',
isNullable: true,
),
),
])
], classes: <Class>[
Class(name: 'ParameterObject', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'aValue'),
]),
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// Nullable arguments should all be pointers. This will make them somewhat
// awkward for some uses (literals, values that could be inlined) but
// unlike setters there's no way to provide reference-based alternatives
// since it's not always just one argument.
// TODO(stuartmorgan): Consider generating a second variant using
// `std::optional`s; that may be more ergonomic, but the perf implications
// would need to be considered.
expect(
code,
contains(RegExp(r'DoSomething\(\s*'
r'const bool\* a_bool,\s*'
r'const int64_t\* an_int,\s*'
// Nullable strings use std::string* rather than std::string_view*
// since there's no implicit conversion for pointer types.
r'const std::string\* a_string,\s*'
r'const flutter::EncodableList\* a_list,\s*'
r'const flutter::EncodableMap\* a_map,\s*'
r'const ParameterObject\* an_object,\s*'
r'const flutter::EncodableValue\* a_generic_object,')));
// The callback should pass a pointer as well.
expect(
code,
contains(
RegExp(r'std::function<void\(const bool\*\)>&& on_success,\s*'
r'std::function<void\(const FlutterError&\)>&& on_error\)')));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// All types pass nulls values when the pointer is null.
// Standard types are wrapped an EncodableValues.
expect(
code,
contains(
'a_bool_arg ? EncodableValue(*a_bool_arg) : EncodableValue()'));
expect(
code,
contains(
'an_int_arg ? EncodableValue(*an_int_arg) : EncodableValue()'));
expect(
code,
contains(
'a_string_arg ? EncodableValue(*a_string_arg) : EncodableValue()'));
expect(
code,
contains(
'a_list_arg ? EncodableValue(*a_list_arg) : EncodableValue()'));
expect(
code,
contains(
'a_map_arg ? EncodableValue(*a_map_arg) : EncodableValue()'));
// Class types use ToEncodableList.
expect(
code,
contains(
'an_object_arg ? CustomEncodableValue(*an_object_arg) : EncodableValue()'));
}
});
test('flutter non-nullable arguments map correctly', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
name: 'aBool',
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
)),
Parameter(
name: 'anInt',
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
)),
Parameter(
name: 'aString',
type: const TypeDeclaration(
baseName: 'String',
isNullable: false,
)),
Parameter(
name: 'aList',
type: const TypeDeclaration(
baseName: 'List',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'Object', isNullable: true)
],
isNullable: false,
)),
Parameter(
name: 'aMap',
type: const TypeDeclaration(
baseName: 'Map',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'Object', isNullable: true),
],
isNullable: false,
)),
Parameter(
name: 'anObject',
type: TypeDeclaration(
baseName: 'ParameterObject',
isNullable: false,
associatedClass: emptyClass,
)),
Parameter(
name: 'aGenericObject',
type: const TypeDeclaration(
baseName: 'Object',
isNullable: false,
)),
],
returnType: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
),
])
], classes: <Class>[
Class(name: 'ParameterObject', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'aValue'),
]),
], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(RegExp(r'DoSomething\(\s*'
r'bool a_bool,\s*'
r'int64_t an_int,\s*'
// Non-nullable strings use std::string for consistency with
// nullable strings.
r'const std::string& a_string,\s*'
// Non-POD types use const references.
r'const flutter::EncodableList& a_list,\s*'
r'const flutter::EncodableMap& a_map,\s*'
r'const ParameterObject& an_object,\s*'
r'const flutter::EncodableValue& a_generic_object,\s*')));
// The callback should pass a value.
expect(
code,
contains(RegExp(r'std::function<void\(bool\)>&& on_success,\s*'
r'std::function<void\(const FlutterError&\)>&& on_error\s*\)')));
}
{
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// Standard types are wrapped an EncodableValues.
expect(code, contains('EncodableValue(a_bool_arg)'));
expect(code, contains('EncodableValue(an_int_arg)'));
expect(code, contains('EncodableValue(a_string_arg)'));
expect(code, contains('EncodableValue(a_list_arg)'));
expect(code, contains('EncodableValue(a_map_arg)'));
// Class types use ToEncodableList.
expect(code, contains('CustomEncodableValue(an_object_arg)'));
}
});
test('host API argument extraction uses references', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
name: 'anArg',
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
)),
],
returnType: const TypeDeclaration.voidDeclaration(),
),
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// A bare 'auto' here would create a copy, not a reference, which is
// inefficient.
expect(
code, contains('const auto& args = std::get<EncodableList>(message);'));
expect(code, contains('const auto& encodable_an_arg_arg = args.at(0);'));
});
test('enum argument', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Bar', methods: <Method>[
Method(
name: 'bar',
location: ApiLocation.host,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'foo',
type: TypeDeclaration(
baseName: 'Foo',
isNullable: false,
associatedEnum: emptyEnum,
),
)
])
])
],
classes: <Class>[],
enums: <Enum>[
Enum(name: 'Foo', members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
])
],
);
final List<Error> errors = validateCpp(const CppOptions(), root);
expect(errors.length, 1);
});
test('transfers documentation comments', () {
final List<String> comments = <String>[
' api comment',
' api method comment',
' class comment',
' class field comment',
' enum comment',
' enum member comment',
];
int count = 0;
final List<String> unspacedComments = <String>['////////'];
int unspacedCount = 0;
final Root root = Root(
apis: <Api>[
AstFlutterApi(
name: 'Api',
documentationComments: <String>[comments[count++]],
methods: <Method>[
Method(
name: 'method',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
documentationComments: <String>[comments[count++]],
parameters: <Parameter>[
Parameter(
name: 'field',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
],
)
],
)
],
classes: <Class>[
Class(
name: 'class',
documentationComments: <String>[comments[count++]],
fields: <NamedType>[
NamedType(
documentationComments: <String>[comments[count++]],
type: const TypeDeclaration(
baseName: 'Map',
isNullable: true,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'int', isNullable: true),
]),
name: 'field1'),
],
),
],
enums: <Enum>[
Enum(
name: 'enum',
documentationComments: <String>[
comments[count++],
unspacedComments[unspacedCount++]
],
members: <EnumMember>[
EnumMember(
name: 'one',
documentationComments: <String>[comments[count++]],
),
EnumMember(name: 'two'),
],
),
],
);
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(headerIncludePath: 'foo'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
for (final String comment in comments) {
expect(code, contains('//$comment'));
}
expect(code, contains('// ///'));
});
test("doesn't create codecs if no custom datatypes", () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(
name: 'Api',
methods: <Method>[
Method(
name: 'method',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'field',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
],
)
],
)
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains(' : public flutter::StandardCodecSerializer')));
});
test('creates custom codecs if custom datatypes present', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
isNullable: false,
associatedClass: emptyClass,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
isNullable: false,
associatedClass: emptyClass,
),
isAsynchronous: true,
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.header,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains(' : public flutter::StandardCodecSerializer'));
});
test('Does not send unwrapped EncodableLists', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
name: 'aBool',
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
)),
Parameter(
name: 'anInt',
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
)),
Parameter(
name: 'aString',
type: const TypeDeclaration(
baseName: 'String',
isNullable: false,
)),
Parameter(
name: 'aList',
type: const TypeDeclaration(
baseName: 'List',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'Object', isNullable: true)
],
isNullable: false,
)),
Parameter(
name: 'aMap',
type: const TypeDeclaration(
baseName: 'Map',
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'Object', isNullable: true),
],
isNullable: false,
)),
Parameter(
name: 'anObject',
type: TypeDeclaration(
baseName: 'ParameterObject',
isNullable: false,
associatedClass: emptyClass,
)),
],
returnType: const TypeDeclaration.voidDeclaration(),
),
])
], classes: <Class>[
Class(name: 'ParameterObject', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: false,
),
name: 'aValue'),
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains('reply(wrap')));
expect(code, contains('reply(EncodableValue('));
});
test('does not keep unowned references in async handlers', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'HostApi', methods: <Method>[
Method(
name: 'noop',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration.voidDeclaration(),
isAsynchronous: true,
),
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
),
name: '')
],
returnType:
const TypeDeclaration(baseName: 'double', isNullable: false),
isAsynchronous: true,
),
]),
AstFlutterApi(name: 'FlutterApi', methods: <Method>[
Method(
name: 'noop',
location: ApiLocation.flutter,
parameters: <Parameter>[],
returnType: const TypeDeclaration.voidDeclaration(),
isAsynchronous: true,
),
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'String',
isNullable: false,
),
name: '')
],
returnType:
const TypeDeclaration(baseName: 'bool', isNullable: false),
isAsynchronous: true,
),
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// Nothing should be captured by reference for async handlers, since their
// lifetime is unknown (and expected to be longer than the stack's).
expect(code, isNot(contains('&reply')));
expect(code, isNot(contains('&wrapped')));
// Check for the exact capture format that is currently being used, to
// ensure that the negative tests above get updated if there are any
// changes to lambda capture.
expect(code, contains('[reply]('));
});
test('connection error contains channel name', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(
name: 'Api',
methods: <Method>[
Method(
name: 'method',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'field',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
],
)
],
)
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'"Unable to establish connection on channel: \'" + channel_name + "\'."'));
expect(code, contains('on_error(CreateConnectionError(channel_name));'));
});
test('stack allocates the message channel.', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(
name: 'Api',
methods: <Method>[
Method(
name: 'method',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'field',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
],
)
],
)
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const CppGenerator generator = CppGenerator();
final OutputFileOptions<CppOptions> generatorOptions =
OutputFileOptions<CppOptions>(
fileType: FileType.source,
languageOptions: const CppOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec());'));
expect(code, contains('channel.Send'));
});
}
| packages/packages/pigeon/test/cpp_generator_test.dart/0 | {
"file_path": "packages/packages/pigeon/test/cpp_generator_test.dart",
"repo_id": "packages",
"token_count": 35379
} | 1,065 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'flutter_utils.dart';
import 'process_utils.dart';
Future<int> runFlutterCommand(
String projectDirectory,
String command, [
List<String> commandArguments = const <String>[],
]) {
return runProcess(
getFlutterCommand(),
<String>[
command,
...commandArguments,
],
workingDirectory: projectDirectory,
);
}
Future<int> runFlutterBuild(
String projectDirectory,
String target, {
bool debug = true,
List<String> flags = const <String>[],
}) {
return runFlutterCommand(
projectDirectory,
'build',
<String>[
target,
if (debug) '--debug',
...flags,
],
);
}
Future<int> runXcodeBuild(
String nativeProjectDirectory, {
String? sdk,
String? destination,
List<String> extraArguments = const <String>[],
}) {
return runProcess(
'xcodebuild',
<String>[
'-workspace',
'Runner.xcworkspace',
'-scheme',
'Runner',
if (sdk != null) ...<String>['-sdk', sdk],
if (destination != null) ...<String>['-destination', destination],
...extraArguments,
],
workingDirectory: nativeProjectDirectory,
);
}
Future<int> runGradleBuild(String nativeProjectDirectory, [String? command]) {
return runProcess(
'./gradlew',
<String>[
if (command != null) command,
],
workingDirectory: nativeProjectDirectory,
);
}
| packages/packages/pigeon/tool/shared/native_project_runners.dart/0 | {
"file_path": "packages/packages/pigeon/tool/shared/native_project_runners.dart",
"repo_id": "packages",
"token_count": 558
} | 1,066 |
test_on: vm
| packages/packages/platform/example/dart_test.yaml/0 | {
"file_path": "packages/packages/platform/example/dart_test.yaml",
"repo_id": "packages",
"token_count": 6
} | 1,067 |
#include "ephemeral/Flutter-Generated.xcconfig"
| packages/packages/platform/example/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "packages/packages/platform/example/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "packages",
"token_count": 19
} | 1,068 |
{
"numberOfProcessors": 8,
"pathSeparator": "/",
"operatingSystem": "macos",
"operatingSystemVersion": "10.14.5",
"localHostname": "platform.test.org",
"environment": {
"PATH": "/bin",
"PWD": "/platform"
},
"executable": "/bin/dart",
"resolvedExecutable": "/bin/dart",
"script": "file:///platform/test/fake_platform_test.dart",
"executableArguments": [
"--checked"
],
"packageConfig": null,
"version": "1.22.0",
"localeName": "de/de"
} | packages/packages/platform/test/platform.json/0 | {
"file_path": "packages/packages/platform/test/platform.json",
"repo_id": "packages",
"token_count": 193
} | 1,069 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html' as html;
import 'dart:ui_web' as ui_web;
import 'package:flutter/material.dart';
/// The html.Element that will be rendered underneath the flutter UI.
html.Element htmlElement = html.DivElement()
..style.width = '100%'
..style.height = '100%'
..style.backgroundColor = '#fabada'
..style.cursor = 'auto'
..id = 'background-html-view';
// See other examples commented out below...
// html.Element htmlElement = html.VideoElement()
// ..style.width = '100%'
// ..style.height = '100%'
// ..style.cursor = 'auto'
// ..style.backgroundColor = 'black'
// ..id = 'background-html-view'
// ..src = 'https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4'
// ..poster = 'https://peach.blender.org/wp-content/uploads/title_anouncement.jpg?x11217'
// ..controls = true;
// html.Element htmlElement = html.IFrameElement()
// ..width = '100%'
// ..height = '100%'
// ..id = 'background-html-view'
// ..src = 'https://www.youtube.com/embed/IyFZznAk69U'
// ..style.border = 'none';
const String _htmlElementViewType = '_htmlElementViewType';
/// A widget representing an underlying html view
class NativeWidget extends StatelessWidget {
/// Constructor
const NativeWidget({super.key, required this.onClick});
/// A function to run when the element is clicked
final VoidCallback onClick;
@override
Widget build(BuildContext context) {
htmlElement.onClick.listen((_) {
onClick();
});
ui_web.platformViewRegistry.registerViewFactory(
_htmlElementViewType,
(int viewId) => htmlElement,
);
return const HtmlElementView(
viewType: _htmlElementViewType,
);
}
}
| packages/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_web.dart/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_web.dart",
"repo_id": "packages",
"token_count": 668
} | 1,070 |
## NEXT
* Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6.
## 0.10.0+2
* Adds privacy manifest.
## 0.10.0+1
* Updates minimum required plugin_platform_interface version to 2.1.7.
## 0.10.0
* Initial release.
| packages/packages/pointer_interceptor/pointer_interceptor_ios/CHANGELOG.md/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/CHANGELOG.md",
"repo_id": "packages",
"token_count": 86
} | 1,071 |
name: pointer_interceptor_ios_example
description: "Demonstrates how to use the pointer_interceptor_ios plugin."
publish_to: 'none'
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
pointer_interceptor_ios:
path: ../../pointer_interceptor_ios
pointer_interceptor_platform_interface: ^0.10.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| packages/packages/pointer_interceptor/pointer_interceptor_ios/example/pubspec.yaml/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 194
} | 1,072 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' show ProcessException;
/// A specialized exception class for this package, so that it can throw
/// customized exceptions with more information.
class ProcessPackageException extends ProcessException {
/// Create a const ProcessPackageException.
///
/// The [executable] should be the name of the executable to be run.
///
/// The optional [workingDirectory] is the directory where the command
/// execution is attempted.
///
/// The optional [arguments] is a list of the arguments to given to the
/// executable, already separated.
///
/// The optional [message] is an additional message to be included in the
/// exception string when printed.
///
/// The optional [errorCode] is the error code received when the executable
/// was run. Zero means it ran successfully, or that no error code was
/// available.
///
/// See [ProcessException] for more information.
const ProcessPackageException(
String executable, {
List<String> arguments = const <String>[],
String message = '',
int errorCode = 0,
this.workingDirectory,
}) : super(executable, arguments, message, errorCode);
/// Creates a [ProcessPackageException] from a [ProcessException].
factory ProcessPackageException.fromProcessException(
ProcessException exception, {
String? workingDirectory,
}) {
return ProcessPackageException(
exception.executable,
arguments: exception.arguments,
message: exception.message,
errorCode: exception.errorCode,
workingDirectory: workingDirectory,
);
}
/// The optional working directory that the command was being executed in.
final String? workingDirectory;
// Don't implement a toString() for this exception, since code may be
// depending upon the format of ProcessException.toString().
}
/// An exception for when an executable is not found that was expected to be found.
class ProcessPackageExecutableNotFoundException
extends ProcessPackageException {
/// Creates a const ProcessPackageExecutableNotFoundException
///
/// The optional [candidates] are the files matching the expected executable
/// on the [searchPath].
///
/// The optional [searchPath] is the list of directories searched for the
/// expected executable.
///
/// See [ProcessPackageException] for more information.
const ProcessPackageExecutableNotFoundException(
super.executable, {
super.arguments,
super.message,
super.errorCode,
super.workingDirectory,
this.candidates = const <String>[],
this.searchPath = const <String>[],
});
/// The list of non-viable executable candidates found.
final List<String> candidates;
/// The search path used to find candidates.
final List<String> searchPath;
@override
String toString() {
final StringBuffer buffer =
StringBuffer('ProcessPackageExecutableNotFoundException: $message\n');
// Don't add an extra space if there are no arguments.
final String args = arguments.isNotEmpty ? ' ${arguments.join(' ')}' : '';
buffer.writeln(' Command: $executable$args');
if (workingDirectory != null && workingDirectory!.isNotEmpty) {
buffer.writeln(' Working Directory: $workingDirectory');
}
if (candidates.isNotEmpty) {
buffer.writeln(' Candidates:\n ${candidates.join('\n ')}');
}
buffer.writeln(' Search Path:\n ${searchPath.join('\n ')}');
return buffer.toString();
}
}
| packages/packages/process/lib/src/interface/exceptions.dart/0 | {
"file_path": "packages/packages/process/lib/src/interface/exceptions.dart",
"repo_id": "packages",
"token_count": 1020
} | 1,073 |
// 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:integration_test/integration_test.dart';
import 'package:quick_actions/quick_actions.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Can set shortcuts', (WidgetTester tester) async {
const QuickActions quickActions = QuickActions();
await quickActions.initialize((String _) {});
const ShortcutItem shortCutItem = ShortcutItem(
type: 'action_one',
localizedTitle: 'Action one',
icon: 'AppIcon',
);
expect(
quickActions.setShortcutItems(<ShortcutItem>[shortCutItem]), completes);
});
}
| packages/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart/0 | {
"file_path": "packages/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart",
"repo_id": "packages",
"token_count": 267
} | 1,074 |
// 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 quick_actions;
@import XCTest;
@interface QuickActionsTests : XCTestCase
@end
@implementation QuickActionsTests
- (void)testPlugin {
FLTQuickActionsPlugin *plugin = [[FLTQuickActionsPlugin alloc] init];
XCTAssertNotNil(plugin);
}
@end
| packages/packages/quick_actions/quick_actions/example/ios/RunnerTests/RunnerTests.m/0 | {
"file_path": "packages/packages/quick_actions/quick_actions/example/ios/RunnerTests/RunnerTests.m",
"repo_id": "packages",
"token_count": 132
} | 1,075 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v11.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
package io.flutter.plugins.quickactions;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StandardMessageCodec;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Generated class from Pigeon. */
@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"})
public class Messages {
/** Error class for passing custom error details to Flutter via a thrown PlatformException. */
public static class FlutterError extends RuntimeException {
/** The error code. */
public final String code;
/** The error details. Must be a datatype supported by the api codec. */
public final Object details;
public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) {
super(message);
this.code = code;
this.details = details;
}
}
@NonNull
protected static ArrayList<Object> wrapError(@NonNull Throwable exception) {
ArrayList<Object> errorList = new ArrayList<Object>(3);
if (exception instanceof FlutterError) {
FlutterError error = (FlutterError) exception;
errorList.add(error.code);
errorList.add(error.getMessage());
errorList.add(error.details);
} else {
errorList.add(exception.toString());
errorList.add(exception.getClass().getSimpleName());
errorList.add(
"Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception));
}
return errorList;
}
/**
* Home screen quick-action shortcut item.
*
* <p>Generated class from Pigeon that represents data sent in messages.
*/
public static final class ShortcutItemMessage {
/** The identifier of this item; should be unique within the app. */
private @NonNull String type;
public @NonNull String getType() {
return type;
}
public void setType(@NonNull String setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"type\" is null.");
}
this.type = setterArg;
}
/** Localized title of the item. */
private @NonNull String localizedTitle;
public @NonNull String getLocalizedTitle() {
return localizedTitle;
}
public void setLocalizedTitle(@NonNull String setterArg) {
if (setterArg == null) {
throw new IllegalStateException("Nonnull field \"localizedTitle\" is null.");
}
this.localizedTitle = setterArg;
}
/** Name of native resource to be displayed as the icon for this item. */
private @Nullable String icon;
public @Nullable String getIcon() {
return icon;
}
public void setIcon(@Nullable String setterArg) {
this.icon = setterArg;
}
/** Constructor is non-public to enforce null safety; use Builder. */
ShortcutItemMessage() {}
public static final class Builder {
private @Nullable String type;
public @NonNull Builder setType(@NonNull String setterArg) {
this.type = setterArg;
return this;
}
private @Nullable String localizedTitle;
public @NonNull Builder setLocalizedTitle(@NonNull String setterArg) {
this.localizedTitle = setterArg;
return this;
}
private @Nullable String icon;
public @NonNull Builder setIcon(@Nullable String setterArg) {
this.icon = setterArg;
return this;
}
public @NonNull ShortcutItemMessage build() {
ShortcutItemMessage pigeonReturn = new ShortcutItemMessage();
pigeonReturn.setType(type);
pigeonReturn.setLocalizedTitle(localizedTitle);
pigeonReturn.setIcon(icon);
return pigeonReturn;
}
}
@NonNull
ArrayList<Object> toList() {
ArrayList<Object> toListResult = new ArrayList<Object>(3);
toListResult.add(type);
toListResult.add(localizedTitle);
toListResult.add(icon);
return toListResult;
}
static @NonNull ShortcutItemMessage fromList(@NonNull ArrayList<Object> list) {
ShortcutItemMessage pigeonResult = new ShortcutItemMessage();
Object type = list.get(0);
pigeonResult.setType((String) type);
Object localizedTitle = list.get(1);
pigeonResult.setLocalizedTitle((String) localizedTitle);
Object icon = list.get(2);
pigeonResult.setIcon((String) icon);
return pigeonResult;
}
}
public interface Result<T> {
@SuppressWarnings("UnknownNullness")
void success(T result);
void error(@NonNull Throwable error);
}
private static class AndroidQuickActionsApiCodec extends StandardMessageCodec {
public static final AndroidQuickActionsApiCodec INSTANCE = new AndroidQuickActionsApiCodec();
private AndroidQuickActionsApiCodec() {}
@Override
protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) {
switch (type) {
case (byte) 128:
return ShortcutItemMessage.fromList((ArrayList<Object>) readValue(buffer));
default:
return super.readValueOfType(type, buffer);
}
}
@Override
protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) {
if (value instanceof ShortcutItemMessage) {
stream.write(128);
writeValue(stream, ((ShortcutItemMessage) value).toList());
} else {
super.writeValue(stream, value);
}
}
}
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */
public interface AndroidQuickActionsApi {
/** Checks for, and returns the action that launched the app. */
@Nullable
String getLaunchAction();
/** Sets the dynamic shortcuts for the app. */
void setShortcutItems(
@NonNull List<ShortcutItemMessage> itemsList, @NonNull Result<Void> result);
/** Removes all dynamic shortcuts. */
void clearShortcutItems();
/** The codec used by AndroidQuickActionsApi. */
static @NonNull MessageCodec<Object> getCodec() {
return AndroidQuickActionsApiCodec.INSTANCE;
}
/**
* Sets up an instance of `AndroidQuickActionsApi` to handle messages through the
* `binaryMessenger`.
*/
static void setup(
@NonNull BinaryMessenger binaryMessenger, @Nullable AndroidQuickActionsApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.getLaunchAction",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
String output = api.getLaunchAction();
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.setShortcutItems",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
List<ShortcutItemMessage> itemsListArg = (List<ShortcutItemMessage>) args.get(0);
Result<Void> resultCallback =
new Result<Void>() {
public void success(Void result) {
wrapped.add(0, null);
reply.reply(wrapped);
}
public void error(Throwable error) {
ArrayList<Object> wrappedError = wrapError(error);
reply.reply(wrappedError);
}
};
api.setShortcutItems(itemsListArg, resultCallback);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.clearShortcutItems",
getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
api.clearShortcutItems();
wrapped.add(0, null);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
/** Generated class from Pigeon that represents Flutter messages that can be called from Java. */
public static class AndroidQuickActionsFlutterApi {
private final @NonNull BinaryMessenger binaryMessenger;
public AndroidQuickActionsFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) {
this.binaryMessenger = argBinaryMessenger;
}
/** Public interface for sending reply. */
@SuppressWarnings("UnknownNullness")
public interface Reply<T> {
void reply(T reply);
}
/** The codec used by AndroidQuickActionsFlutterApi. */
static @NonNull MessageCodec<Object> getCodec() {
return new StandardMessageCodec();
}
/** Sends a string representing a shortcut from the native platform to the app. */
public void launchAction(@NonNull String actionArg, @NonNull Reply<Void> callback) {
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction",
getCodec());
channel.send(
new ArrayList<Object>(Collections.singletonList(actionArg)),
channelReply -> callback.reply(null));
}
}
}
| packages/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/Messages.java/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/Messages.java",
"repo_id": "packages",
"token_count": 4422
} | 1,076 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
javaOut:
'android/src/main/java/io/flutter/plugins/quickactions/Messages.java',
javaOptions: JavaOptions(
package: 'io.flutter.plugins.quickactions',
),
copyrightHeader: 'pigeons/copyright.txt',
))
/// Home screen quick-action shortcut item.
class ShortcutItemMessage {
ShortcutItemMessage(
this.type,
this.localizedTitle,
this.icon,
);
/// The identifier of this item; should be unique within the app.
String type;
/// Localized title of the item.
String localizedTitle;
/// Name of native resource to be displayed as the icon for this item.
String? icon;
}
@HostApi()
abstract class AndroidQuickActionsApi {
/// Checks for, and returns the action that launched the app.
String? getLaunchAction();
/// Sets the dynamic shortcuts for the app.
@async
void setShortcutItems(List<ShortcutItemMessage> itemsList);
/// Removes all dynamic shortcuts.
void clearShortcutItems();
}
@FlutterApi()
abstract class AndroidQuickActionsFlutterApi {
/// Sends a string representing a shortcut from the native platform to the app.
void launchAction(String action);
}
| packages/packages/quick_actions/quick_actions_android/pigeons/messages.dart/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/pigeons/messages.dart",
"repo_id": "packages",
"token_count": 430
} | 1,077 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Flutter
public final class QuickActionsPlugin: NSObject, FlutterPlugin, IOSQuickActionsApi {
public static func register(with registrar: FlutterPluginRegistrar) {
let messenger = registrar.messenger()
let flutterApi = IOSQuickActionsFlutterApi(binaryMessenger: messenger)
let instance = QuickActionsPlugin(flutterApi: flutterApi)
IOSQuickActionsApiSetup.setUp(binaryMessenger: messenger, api: instance)
registrar.addApplicationDelegate(instance)
}
private let shortcutItemProvider: ShortcutItemProviding
private let flutterApi: IOSQuickActionsFlutterApiProtocol
/// The type of the shortcut item selected when launching the app.
private var launchingShortcutType: String? = nil
init(
flutterApi: IOSQuickActionsFlutterApiProtocol,
shortcutItemProvider: ShortcutItemProviding = UIApplication.shared
) {
self.flutterApi = flutterApi
self.shortcutItemProvider = shortcutItemProvider
}
func setShortcutItems(itemsList: [ShortcutItemMessage]) {
shortcutItemProvider.shortcutItems =
convertShortcutItemMessageListToUIApplicationShortcutItemList(itemsList)
}
func clearShortcutItems() {
shortcutItemProvider.shortcutItems = []
}
public func application(
_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem,
completionHandler: @escaping (Bool) -> Void
) -> Bool {
handleShortcut(shortcutItem.type)
return true
}
public func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [AnyHashable: Any] = [:]
) -> Bool {
if let shortcutItem = launchOptions[UIApplication.LaunchOptionsKey.shortcutItem]
as? UIApplicationShortcutItem
{
// Keep hold of the shortcut type and handle it in the
// `applicationDidBecomeActive:` method once the Dart MethodChannel
// is initialized.
launchingShortcutType = shortcutItem.type
// Return false to indicate we handled the quick action to ensure
// the `application:performActionFor:` method is not called (as
// per Apple's documentation:
// https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622935-application).
return false
}
return true
}
public func applicationDidBecomeActive(_ application: UIApplication) {
if let shortcutType = launchingShortcutType {
handleShortcut(shortcutType)
launchingShortcutType = nil
}
}
func handleShortcut(_ shortcut: String) {
flutterApi.launchAction(action: shortcut) { _ in
// noop
}
}
private func convertShortcutItemMessageListToUIApplicationShortcutItemList(
_ items: [ShortcutItemMessage]
) -> [UIApplicationShortcutItem] {
return items.compactMap { convertShortcutItemMessageToUIApplicationShortcutItem(with: $0) }
}
private func convertShortcutItemMessageToUIApplicationShortcutItem(
with shortcut: ShortcutItemMessage
)
-> UIApplicationShortcutItem?
{
let type = shortcut.type
let localizedTitle = shortcut.localizedTitle
let icon = (shortcut.icon).map {
UIApplicationShortcutIcon(templateImageName: $0)
}
// type and localizedTitle are required.
return UIApplicationShortcutItem(
type: type,
localizedTitle: localizedTitle,
localizedSubtitle: nil,
icon: icon,
userInfo: nil)
}
}
| packages/packages/quick_actions/quick_actions_ios/ios/Classes/QuickActionsPlugin.swift/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_ios/ios/Classes/QuickActionsPlugin.swift",
"repo_id": "packages",
"token_count": 1157
} | 1,078 |
# Use the analysis options settings from the top level of the repo (not
# the ones from above, which include the `public_member_api_docs` rule).
include: ../../../analysis_options.yaml
linter:
rules:
public_member_api_docs: false
| packages/packages/rfw/example/analysis_options.yaml/0 | {
"file_path": "packages/packages/rfw/example/analysis_options.yaml",
"repo_id": "packages",
"token_count": 73
} | 1,079 |
#include "Generated.xcconfig"
| packages/packages/rfw/example/local/ios/Flutter/Release.xcconfig/0 | {
"file_path": "packages/packages/rfw/example/local/ios/Flutter/Release.xcconfig",
"repo_id": "packages",
"token_count": 12
} | 1,080 |
# Example of fetching remote widgets for RFW
This example shows how one can fetch remote widget library files from
a remote server.
| packages/packages/rfw/example/remote/README.md/0 | {
"file_path": "packages/packages/rfw/example/remote/README.md",
"repo_id": "packages",
"token_count": 30
} | 1,081 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is hand-formatted.
import 'dart:async';
import 'dart:io';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:rfw/rfw.dart';
import 'package:wasm/wasm.dart';
const String urlPrefix = 'https://raw.githubusercontent.com/flutter/packages/main/packages/rfw/example/wasm/logic';
const String interfaceUrl = '$urlPrefix/calculator.rfw';
const String logicUrl = '$urlPrefix/calculator.wasm';
void main() {
runApp(WidgetsApp(color: const Color(0xFF000000), builder: (BuildContext context, Widget? navigator) => const Example()));
}
class Example extends StatefulWidget {
const Example({super.key});
@override
State<Example> createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
final Runtime _runtime = Runtime();
final DynamicContent _data = DynamicContent();
late final WasmInstance _logic;
@override
void initState() {
super.initState();
RendererBinding.instance.deferFirstFrame();
_runtime.update(const LibraryName(<String>['core', 'widgets']), createCoreWidgets());
_loadLogic();
}
late final WasmFunction _dataFetcher;
Future<void> _loadLogic() async {
final DateTime expiryDate = DateTime.now().subtract(const Duration(hours: 6));
final Directory home = await getApplicationSupportDirectory();
final File interfaceFile = File(path.join(home.path, 'cache.rfw'));
if (!interfaceFile.existsSync() || interfaceFile.lastModifiedSync().isBefore(expiryDate)) {
final HttpClientResponse client = await (await HttpClient().getUrl(Uri.parse(interfaceUrl))).close();
await interfaceFile.writeAsBytes(await client.expand((List<int> chunk) => chunk).toList());
}
final File logicFile = File(path.join(home.path, 'cache.wasm'));
if (!logicFile.existsSync() || logicFile.lastModifiedSync().isBefore(expiryDate)) {
final HttpClientResponse client = await (await HttpClient().getUrl(Uri.parse(logicUrl))).close();
await logicFile.writeAsBytes(await client.expand((List<int> chunk) => chunk).toList());
}
_runtime.update(const LibraryName(<String>['main']), decodeLibraryBlob(await interfaceFile.readAsBytes()));
_logic = WasmModule(await logicFile.readAsBytes()).builder().build();
_dataFetcher = _logic.lookupFunction('value') as WasmFunction;
_updateData();
setState(() { RendererBinding.instance.allowFirstFrame(); });
}
void _updateData() {
final dynamic value = _dataFetcher.apply(const <Object?>[]);
_data.update('value', <String, Object?>{ 'numeric': value, 'string': value.toString() });
}
List<Object?> _asList(Object? value) {
if (value is List<Object?>) {
return value;
}
return const <Object?>[];
}
@override
Widget build(BuildContext context) {
if (!RendererBinding.instance.sendFramesToEngine) {
return const SizedBox.shrink();
}
return RemoteWidget(
runtime: _runtime,
data: _data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['main']), 'root'),
onEvent: (String name, DynamicMap arguments) {
final WasmFunction function = _logic.lookupFunction(name) as WasmFunction;
function.apply(_asList(arguments['arguments']));
_updateData();
},
);
}
}
| packages/packages/rfw/example/wasm/lib/main.dart/0 | {
"file_path": "packages/packages/rfw/example/wasm/lib/main.dart",
"repo_id": "packages",
"token_count": 1229
} | 1,082 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is hand-formatted.
// This file must not import `dart:ui`, directly or indirectly, as it is
// intended to function even in pure Dart server or CLI environments.
import 'model.dart';
/// Parse a Remote Flutter Widgets text data file.
///
/// This data is usually used in conjunction with [DynamicContent].
///
/// Parsing this format is about ten times slower than parsing the binary
/// variant; see [decodeDataBlob]. As such it is strongly discouraged,
/// especially in resource-constrained contexts like mobile applications.
///
/// ## Format
///
/// This format is inspired by JSON, but with the following changes:
///
/// * end-of-line comments are supported, using the "//" syntax from C (and
/// Dart).
///
/// * block comments are supported, using the "/*...*/" syntax from C (and
/// Dart).
///
/// * map keys may be unquoted when they are alphanumeric.
///
/// * "null" is not a valid value except as a value in maps, where it is
/// equivalent to omitting the corresponding key entirely. This is allowed
/// primarily as a development aid to explicitly indicate missing keys. (The
/// data model itself, and the binary format (see [decodeDataBlob]), do not
/// contain this feature.)
///
/// * integers and doubles are distinguished explicitly, via the presence of
/// the decimal point and/or exponent characters. Integers may also be
/// expressed as hex literals. Numbers are explicitly 64 bit precision;
/// specifically, signed 64 bit integers, or binary64 floating point numbers.
///
/// * files are always rooted at a map. (Different versions of JSON are
/// ambiguous or contradictory about this.)
///
/// Here is the BNF:
///
/// ```bnf
/// root ::= WS* map WS*
/// ```
///
/// Every Remote Flutter Widget text data file must match the `root` production.
///
/// ```bnf
/// map ::= "{" ( WS* entry WS* "," )* WS* entry? WS* "}"
/// entry ::= ( identifier | string ) WS* ":" WS* ( value | "null" )
/// ```
///
/// Maps are comma-separated lists of name-value pairs (a single trailing comma
/// is permitted), surrounded by braces. The key must be either a quoted string
/// or an unquoted identifier. The value must be either the keyword "null",
/// which is equivalent to the entry being omitted, or a value as defined below.
/// Duplicates (notwithstanding entries that use the keyword "null") are not
/// permitted. In general the use of the "null" keyword is discouraged and is
/// supported only to allow mechanically-generated data to consistently include
/// every key even when one has no value.
///
/// ```bnf
/// value ::= map | list | integer | double | string | "true" | "false"
/// ```
///
/// The "true" and "false" keywords represented the boolean true and false
/// values respectively.
///
/// ```bnf
/// list ::= "[" ( WS* value WS* "," )* WS* value? WS* "]"
/// ```
///
/// Following the pattern set by maps, lists are comma-separated lists of values
/// (a single trailing comma is permitted), surrounded by brackets.
///
/// ```bnf
/// identifier ::= letter ( letter | digit )*
/// letter ::= <a character in the ranges A-Z, a-z, or the underscore>
/// digit ::= <a character in the range 0-9>
/// ```
///
/// Identifiers are alphanumeric sequences (with the underscore considered a
/// letter) that do not start with a digit.
///
/// ```bnf
/// string ::= DQ stringbodyDQ* DQ | SQ stringbodySQ* SQ
/// DQ ::= <U+0022>
/// stringbodyDQ ::= escape | characterDQ
/// characterDQ ::= <U+0000..U+10FFFF except U+000A, U+0022, U+005C>
/// SQ ::= <U+0027>
/// stringbodySQ ::= escape | characterSQ
/// characterSQ ::= <U+0000..U+10FFFF except U+000A, U+0027, U+005C>
/// escape ::= <U+005C> ("b" | "f" | "n" | "r" | "t" | symbol | unicode)
/// symbol ::= <U+0022, U+0027, U+005C, or U+002F>
/// unicode ::= "u" hex hex hex hex
/// hex ::= <a character in the ranges A-F, a-f, or 0-9>
/// ```
///
/// Strings are double-quoted (U+0022, ") or single-quoted (U+0027, ') sequences
/// of zero or more Unicode characters that do not include a newline, the quote
/// character used, or the backslash character, mixed with zero or more escapes.
///
/// Escapes are a backslash character followed by another character, as follows:
///
/// * `\b`: represents U+0008
/// * `\f`: represents U+000C
/// * `\n`: represents U+000A
/// * `\r`: represents U+000D
/// * `\t`: represents U+0009
/// * `"`: represents U+0022 (")
/// * `'`: represents U+0027 (')
/// * `/`: represents U+002F (/)
/// * `\`: represents U+005C (\)
/// * `\uXXXX`: represents the UTF-16 codepoint with code XXXX.
///
/// Characters outside the basic multilingual plane must be represented either
/// as literal characters, or as two escapes identifying UTF-16 surrogate pairs.
/// (This is for compatibility with JSON.)
///
/// ```bnf
/// integer ::= "-"? decimal | hexadecimal
/// decimal ::= digit+
/// hexadecimal ::= ("0x" | "0X") hex+
/// ```
///
/// The "digit" (0-9) and "hex" (0-9, A-F, a-f) terminals are described earlier.
///
/// In the "decimal" form, the digits represent their value in base ten. A
/// leading hyphen indicates the number is negative. In the "hexadecimal" form,
/// the number is always positive, and is represented by the hex digits
/// interpreted in base sixteen.
///
/// The numbers represented must be in the range -9,223,372,036,854,775,808 to
/// 9,223,372,036,854,775,807.
///
/// ```
/// double ::= "-"? digit+ ("." digit+)? (("e" | "E") "-"? digit+)?
/// ```
///
/// Floating point numbers are represented by an optional negative sign
/// indicating the number is negative, a significand with optional fractional
/// component in the form of digits in base ten giving the integer component
/// followed optionally by a decimal point and further base ten digits giving
/// the fractional component, and an exponent which itself is represented by an
/// optional negative sign indicating a negative exponent and a sequence of
/// digits giving the base ten exponent itself.
///
/// The numbers represented must be values that can be expressed in the IEEE754
/// binary64 format.
///
/// ```bnf
/// WS ::= ( <U+0020> | <U+000A> | "//" comment* <U+000A or EOF> | "/*" blockcomment "*/" )
/// comment ::= <U+0000..U+10FFFF except U+000A>
/// blockcomment ::= <any number of U+0000..U+10FFFF characters not containing the sequence U+002A U+002F>
/// ```
///
/// The `WS` token is used to represent where whitespace and comments are
/// allowed.
///
/// See also:
///
/// * [parseLibraryFile], which uses a superset of this format to decode
/// Remote Flutter Widgets text library files.
/// * [decodeDataBlob], which decodes the binary variant of this format.
DynamicMap parseDataFile(String file) {
final _Parser parser = _Parser(_tokenize(file), null);
return parser.readDataFile();
}
/// Parses a Remote Flutter Widgets text library file.
///
/// Remote widget libraries are usually used in conjunction with a [Runtime].
///
/// Parsing this format is about ten times slower than parsing the binary
/// variant; see [decodeLibraryBlob]. As such it is strongly discouraged,
/// especially in resource-constrained contexts like mobile applications.
///
/// ## Format
///
/// The format is a superset of the format defined by [parseDataFile].
///
/// Remote Flutter Widgets text library files consist of a list of imports
/// followed by a list of widget declarations.
///
/// ### Imports
///
/// A remote widget library file is identified by a name which consists of
/// several parts, which are by convention expressed separated by periods; for
/// example, `core.widgets` or `net.example.x`.
///
/// A library's name is specified when the library is provided to the runtime
/// using [Runtime.update].
///
/// A remote widget library depends on one or more other libraries that define
/// the widgets that the primary library depends on. These dependencies can
/// themselves be remote widget libraries, for example describing commonly-used
/// widgets like branded buttons, or "local widget libraries" which are declared
/// and hard-coded in the client itself and that provide a way to reference
/// actual Flutter widgets (see [LocalWidgetLibrary]).
///
/// The Remote Flutter Widgets package ships with two local widget libraries,
/// usually given the names `core.widgets` (see [createCoreWidgets]) and
/// `core.material` (see [createMaterialWidgets]). An application can declare
/// other local widget libraries for use by their remote widgets. These could
/// correspond to UI controls, e.g. branded widgets used by other parts of the
/// application, or to complete experiences, e.g. core parts of the application.
/// For example, a blogging application might use Remote Flutter Widgets to
/// represent the CRM parts of the experience, with the rich text editor being
/// implemented on the client as a custom widget exposed to the remote libraries
/// as a widget in a local widget library.
///
/// A library lists the other libraries that it depends on by name. When a
/// widget is referenced, it is looked up by name first by examining the widget
/// declarations in the file itself, then by examining the declarations of each
/// dependency in turn, in a depth-first search.
///
/// It is an error for there to be a loop in the imports.
///
/// Imports have this form:
///
/// ```
/// import library.name;
/// ```
///
/// For example:
///
/// ```
/// import core.widgets;
/// ```
///
/// ### Widget declarations
///
/// The primary purpose of a remote widget library is to provide widget
/// declarations. Each declaration defines a new widget. Widgets are defined in
/// terms of other widgets, like stateless and stateful widgets in Flutter
/// itself. As such, a widget declaration consists of a widget constructor call.
///
/// The widget declarations come after the imports.
///
/// To declare a widget named A in terms of a widget B, the following form is used:
///
/// ```
/// widget A = B();
/// ```
///
/// This declares a widget A, whose implementation is simply to use widget B.
///
/// If the widget A is to be stateful, a map is inserted before the equals sign:
///
/// ```
/// widget A { } = B();
/// ```
///
/// The map describes the default values of the state. For example, a button
/// might have a "down" state, which is initially false:
///
/// ```
/// widget Button { down: false } = Container();
/// ```
///
/// _See the section on State below._
///
/// ### Widget constructor calls
///
/// A widget constructor call is an invocation of a remote or local widget
/// declaration, along with its arguments. Arguments are a map of key-value
/// pairs, where the values can be any of the types in the data model defined
/// above plus any of the types defined below in this section, such as
/// references to arguments, the data model, widget builders, loops, state,
/// switches or event handlers.
///
/// In this example, several constructor calls are nested together:
///
/// ```
/// widget Foo = Column(
/// children: [
/// Container(
/// child: Text(text: "Hello"),
/// ),
/// Builder(
/// builder: (scope) => Text(text: scope.world),
/// ),
/// ],
/// );
/// ```
///
/// The `Foo` widget is defined to create a `Column` widget. The `Column(...)`
/// is a constructor call with one argument, named `children`, whose value is a
/// list which itself contains a single constructor call, to `Container`. That
/// constructor call also has only one argument, `child`, whose value, again, is
/// a constructor call, in this case creating a `Text` widget.
///
/// ### Widget Builders
///
/// Widget builders take a single argument and return a widget.
/// The [DynamicMap] argument consists of key-value pairs where values
/// can be of any types in the data model. Widget builders arguments are lexically
/// scoped so a given constructor call has access to any arguments where it is
/// defined plus arguments defined by its parents (if any).
///
/// In this example several widget builders are nested together:
///
/// ```
/// widget Foo {text: 'this is cool'} = Builder(
/// builder: (foo) => Builder(
/// builder: (bar) => Builder(
/// builder: (baz) => Text(
/// text: [
/// args.text,
/// state.text,
/// data.text,
/// foo.text,
/// bar.text,
/// baz.text,
/// ],
/// ),
/// ),
/// ),
/// );
/// ```
///
/// ### References
///
/// Remote widget libraries typically contain _references_, e.g. to the
/// arguments of a widget, or to the [DynamicContent] data, or to a stateful
/// widget's state.
///
/// The various kinds of references all have the same basic pattern, a prefix
/// followed by period-separated identifiers, strings, or integers. Identifiers
/// and strings are used to index into maps, while integers are used to index
/// into lists.
///
/// For example, "foo.2.fruit" would reference the key with the value "Kiwi" in
/// the following structure:
///
/// ```c
/// {
/// foo: [
/// { fruit: "Apple" },
/// { fruit: "Banana" },
/// { fruit: "Kiwi" }, // foo.2.fruit is the string "Kiwi" here
/// ],
/// bar: [ ],
/// }
/// ```
///
/// Peferences to a widget's arguments use "args" as the first component:
///
/// <code>args<i>.foo.bar</i></code>
///
/// References to the data model use use "data" as the first component, and
/// references to state use "state" as the first component:
///
/// <code>data<i>.foo.bar</i></code>
///
/// <code>state<i>.foo.bar</i></code>
///
/// Finally, references to loop variables use the identifier specified in the
/// loop as the first component:
///
/// <code><i>ident.foo.bar</i></code>
///
/// #### Argument references
///
/// Instead of passing literal values as arguments in widget constructor calls,
/// a reference to one of the arguments of the remote widget being defined
/// itself can be provided instead.
///
/// For example, suppose one instantiated a widget Foo as follows:
///
/// ```
/// Foo(name: "Bobbins")
/// ```
///
/// ...then in the definition of Foo, one might pass the value of this "name"
/// argument to another widget, say a Text widget, as follows:
///
/// ```
/// widget Foo = Text(text: args.name);
/// ```
///
/// The arguments can have structure. For example, if the argument passed to Foo
/// was:
///
/// ```
/// Foo(show: { name: "Cracking the Cryptic", phrase: "Bobbins" })
/// ```
///
/// ...then to specify the leaf node whose value is the string "Bobbins", one
/// would specify an argument reference consisting of the values "show" and
/// "phrase", as in `args.show.phrase`. For example:
///
/// ```
/// widget Foo = Text(text: args.show.phrase);
/// ```
///
/// #### Data model references
///
/// Instead of passing literal values as arguments in widget constructor calls,
/// or references to one's own arguments, a reference to one of the nodes in the
/// data model can be provided instead.
///
/// The data model is a tree of maps and lists with leaves formed of integers,
/// doubles, bools, and strings (see [DynamicContent]). For example, if the data
/// model looks like this:
///
/// ```
/// { server: { cart: [ { name: "Apple"}, { name: "Banana"} ] }
/// ```
///
/// ...then to specify the leaf node whose value is the string "Banana", one
/// would specify a data model reference consisting of the values "server",
/// "cart", 1, and "name", as in `data.server.cart.1.name`. For example:
///
/// ```
/// Text(text: data.server.cart.1.name)
/// ```
///
/// ### Loops
///
/// In a list, a loop can be employed to map another list into the host list,
/// mapping values of the embedded list according to a provided template. Within
/// the template, references to the value from the embedded list being expanded
/// can be provided using a loop reference, which is similar to argument and
/// data references.
///
/// A widget that shows all the values from a list in a [ListView] might look
/// like this:
///
/// ```
/// widget Items = ListView(
/// children: [
/// ...for item in args.list:
/// Text(text: item),
/// ],
/// );
/// ```
///
/// Such a widget would be used like this:
///
/// ```
/// Items(list: [ "Hello", "World" ])
/// ```
///
/// The syntax for a loop uses the following form:
///
/// <code>...for <i>ident</i> in <i>list</i>: <i>template</i></code>
///
/// ...where _ident_ is the identifier to bind to each value in the list, _list_
/// is some value that evaluates to a list, and _template_ is a value that is to
/// be evaluated for each item in _list_.
///
/// This loop syntax is only valid inside lists.
///
/// Loop references use the _ident_. In the example above, that is `item`. In
/// more elaborate examples, it can include subreferences. For example:
///
/// ```
/// widget Items = ListView(
/// children: [
/// Text(text: 'Products:'),
/// ...for item in args.products:
/// Text(text: product.name.displayName),
/// Text(text: 'End of list.'),
/// ],
/// );
/// ```
///
/// This might be used as follows:
///
/// ```
/// Items(products: [
/// { name: { abbreviation: "TI4", displayName: "Twilight Imperium IV" }, price: 120.0 },
/// { name: { abbreviation: "POK", displayName: "Prophecy of Kings" }, price: 100.0 },
/// ])
/// ```
///
/// ### State
///
/// A widget declaration can say that it has an "initial state", the structure
/// of which is the same as the data model structure (maps and lists of
/// primitive types, the root is a map).
///
/// Here a button is described as having a "down" state whose first value is
/// "false":
///
/// ```
/// widget Button { down: false } = Container(
/// // ...
/// );
/// ```
///
/// If a widget has state, then it can be referenced in the same way as the
/// widget's arguments and the data model can be referenced, and it can be
/// changed using event handlers as described below.
///
/// Here, the button's state is referenced (in a pretty nonsensical way;
/// controlling whether its label wraps based on the value of the state):
///
/// ```
/// widget Button { down: false } = Container(
/// child: Text(text: 'Hello World', softWrap: state.down),
/// );
/// ```
///
/// State is usually used with Switches and state-setting handlers.
///
/// ### Switches
///
/// Anywhere in a widget declaration, a switch can be employed to change the
/// evaluated value used at runtime. A switch has a value that is being used to
/// control the switch, and then a series of cases with values to use if the
/// control value matches the case value. A default can be provided.
///
/// The control value is usually a reference to arguments, data, state, or a
/// loop variable.
///
/// The syntax for a switch uses the following form:
///
/// ```
/// switch value {
/// case1: template1,
/// case2: template2,
/// case3: template3,
/// // ...
/// default: templateD,
/// }
/// ```
///
/// ...where _value_ is the control value that will be compared to each case,
/// the _caseX_ values are the values to which the control value is compared,
/// _templateX_ are the templates to use, and _templateD_ is the default
/// template to use if none of the cases can be met. Any number of cases can be
/// specified; the template of the first one that exactly matches the given
/// control value is the one that is used. The default entry is optional. If no
/// value matches and there is no default, the switch evaluates to the "missing"
/// value (null).
///
/// Extending the earlier button, this would move the margin around so that it
/// appeared pressed when the "down" state was true (but note that we still
/// don't have anything to toggle that state!):
///
/// ```
/// widget Button { down: false } = Container(
/// margin: switch state.down {
/// false: [ 0.0, 0.0, 8.0, 8.0 ],
/// true: [ 8.0, 8.0, 0.0, 0.0 ],
/// },
/// decoration: { type: "box", border: [ {} ] },
/// child: args.child,
/// );
/// ```
///
/// ### Event handlers
///
/// There are two kinds of event handlers: those that signal an event for the
/// host to handle (potentially by forwarding it to a server), and those that
/// change the widget's state.
///
/// Signalling event handlers have a name and an arguments map:
///
/// ```
/// event "..." { }
/// ```
///
/// The string is the name of the event, and the arguments map is the data to
/// send with the event.
///
/// For example, the event handler in the following sequence sends the event
/// called "hello" with a map containing just one key, "id", whose value is 1:
///
/// ```
/// Button(
/// onPressed: event "hello" { id: 1 },
/// child: Text(text: "Greetings"),
/// );
/// ```
///
/// Event handlers that set state have a reference to a state, and a new value
/// to assign to that state. Such handlers are only meaningful within widgets
/// that have state, as described above. They have this form:
///
/// ```
/// set state.foo.bar = value
/// ```
///
/// The `state.foo.bar` part is a state reference (which must identify a part of
/// the state that exists), and `value` is the new value to assign to that state.
///
/// This lets us finish the earlier button:
///
/// ```
/// widget Button { down: false } = GestureDetector(
/// onTapDown: set state.down = true,
/// onTapUp: set state.down = false,
/// onTapCancel: set state.down = false,
/// onTap: args.onPressed,
/// child: Container(
/// margin: switch state.down {
/// false: [ 0.0, 0.0, 8.0, 8.0 ],
/// true: [ 8.0, 8.0, 0.0, 0.0 ],
/// },
/// decoration: { type: "box", border: [ {} ] },
/// child: args.child,
/// ),
/// );
/// ```
///
/// ## Source identifier
///
/// The optional `sourceIdentifier` parameter can be provided to cause the
/// parser to track source locations for [BlobNode] subclasses included in the
/// parsed subtree. If the value is null (the default), then source locations
/// are not tracked. If the value is non-null, it is used as the value of the
/// [SourceLocation.source] for each [SourceRange] of each [BlobNode.source].
///
/// See also:
///
/// * [encodeLibraryBlob], which encodes the output of this method
/// into the binary variant of this format.
/// * [parseDataFile], which uses a subset of this format to decode
/// Remote Flutter Widgets text data files.
/// * [decodeLibraryBlob], which decodes the binary variant of this format.
RemoteWidgetLibrary parseLibraryFile(String file, { Object? sourceIdentifier }) {
final _Parser parser = _Parser(_tokenize(file), sourceIdentifier);
return parser.readLibraryFile();
}
const Set<String> _reservedWords = <String>{
'args',
'data',
'event',
'false',
'set',
'state',
'true',
};
void _checkIsNotReservedWord(String identifier, _Token identifierToken) {
if (_reservedWords.contains(identifier)) {
throw ParserException._fromToken('$identifier is a reserved word', identifierToken);
}
}
sealed class _Token {
_Token(this.line, this.column, this.start, this.end);
final int line;
final int column;
final int start;
final int end;
}
class _SymbolToken extends _Token {
_SymbolToken(this.symbol, int line, int column, int start, int end): super(line, column, start, end);
final int symbol;
static const int dot = 0x2E;
static const int tripleDot = 0x2026;
static const int openParen = 0x28; // U+0028 LEFT PARENTHESIS character (()
static const int closeParen = 0x29; // U+0029 RIGHT PARENTHESIS character ())
static const int comma = 0x2C; // U+002C COMMA character (,)
static const int colon = 0x3A; // U+003A COLON character (:)
static const int semicolon = 0x3B; // U+003B SEMICOLON character (;)
static const int equals = 0x3D; // U+003D EQUALS SIGN character (=)
static const int greatherThan = 0x3E; // U+003D GREATHER THAN character (>)
static const int openBracket = 0x5B; // U+005B LEFT SQUARE BRACKET character ([)
static const int closeBracket = 0x5D; // U+005D RIGHT SQUARE BRACKET character (])
static const int openBrace = 0x7B; // U+007B LEFT CURLY BRACKET character ({)
static const int closeBrace = 0x7D; // U+007D RIGHT CURLY BRACKET character (})
@override
String toString() => String.fromCharCode(symbol);
}
class _IntegerToken extends _Token {
_IntegerToken(this.value, int line, int column, int start, int end): super(line, column, start, end);
final int value;
@override
String toString() => '$value';
}
class _DoubleToken extends _Token {
_DoubleToken(this.value, int line, int column, int start, int end): super(line, column, start, end);
final double value;
@override
String toString() => '$value';
}
class _IdentifierToken extends _Token {
_IdentifierToken(this.value, int line, int column, int start, int end): super(line, column, start, end);
final String value;
@override
String toString() => value;
}
class _StringToken extends _Token {
_StringToken(this.value, int line, int column, int start, int end): super(line, column, start, end);
final String value;
@override
String toString() => '"$value"';
}
class _EofToken extends _Token {
_EofToken(super.line, super.column, super.start, super.end);
@override
String toString() => '<EOF>';
}
/// Indicates that there an error was detected while parsing a file.
///
/// This is used by [parseDataFile] and [parseLibraryFile] to indicate that the
/// given file has a syntax or semantic error.
///
/// The [line] and [column] describe how far the parser had reached when the
/// error was detected (this may not precisely indicate the actual location of
/// the error).
///
/// The [message] property is a human-readable string describing the error.
class ParserException implements Exception {
/// Create an instance of [ParserException].
///
/// The arguments must not be null. See [message] for details on
/// the expected syntax of the error description.
const ParserException(this.message, this.line, this.column);
factory ParserException._fromToken(String message, _Token token) {
return ParserException(message, token.line, token.column);
}
factory ParserException._expected(String what, _Token token) {
return ParserException('Expected $what but found $token', token.line, token.column);
}
factory ParserException._unexpected(_Token token) {
return ParserException('Unexpected $token', token.line, token.column);
}
/// The error that was detected by the parser.
///
/// This should be the start of a sentence which will make sense when " at
/// line ... column ..." is appended. So, for example, it should not end with
/// a period.
final String message;
/// The line number (using 1-based indexing) that the parser had reached when
/// the error was detected.
final int line;
/// The column number (using 1-based indexing) that the parser had reached
/// when the error was detected.
///
/// This is measured in UTF-16 code units, even if the source file was UTF-8.
final int column;
@override
String toString() => '$message at line $line column $column.';
}
enum _TokenizerMode {
main,
minus,
zero,
minusInteger,
integer,
integerOnly,
numericDot,
fraction,
e,
negativeExponent,
exponent,
x,
hex,
dot1,
dot2,
identifier,
quote,
doubleQuote,
quoteEscape,
quoteEscapeUnicode1,
quoteEscapeUnicode2,
quoteEscapeUnicode3,
quoteEscapeUnicode4,
doubleQuoteEscape,
doubleQuoteEscapeUnicode1,
doubleQuoteEscapeUnicode2,
doubleQuoteEscapeUnicode3,
doubleQuoteEscapeUnicode4,
endQuote,
slash,
comment,
blockComment,
blockCommentEnd,
}
String _describeRune(int current) {
assert(current >= 0);
assert(current < 0x10FFFF);
if (current > 0x20) {
return 'U+${current.toRadixString(16).toUpperCase().padLeft(4, "0")} ("${String.fromCharCode(current)}")';
}
return 'U+${current.toRadixString(16).toUpperCase().padLeft(4, "0")}';
}
Iterable<_Token> _tokenize(String file) sync* {
final List<int> characters = file.runes.toList();
int start = 0;
int index = 0;
int line = 1;
int column = 0;
final List<int> buffer = <int>[];
final List<int> buffer2 = <int>[];
_TokenizerMode mode = _TokenizerMode.main;
while (true) {
final int current;
if (index >= characters.length) {
current = -1;
} else {
current = characters[index];
if (current == 0x0A) {
line += 1;
column = 0;
} else {
column += 1;
}
}
index += 1;
switch (mode) {
case _TokenizerMode.main:
switch (current) {
case -1:
yield _EofToken(line, column, start, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
start = index;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x3E: // U+003E GREATHER THAN SIGN character (>)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _SymbolToken(current, line, column, start, index);
start = index;
case 0x22: // U+0022 QUOTATION MARK character (")
assert(buffer.isEmpty);
mode = _TokenizerMode.doubleQuote;
case 0x27: // U+0027 APOSTROPHE character (')
assert(buffer.isEmpty);
mode = _TokenizerMode.quote;
case 0x2D: // U+002D HYPHEN-MINUS character (-)
assert(buffer.isEmpty);
mode = _TokenizerMode.minus;
buffer.add(current);
case 0x2E: // U+002E FULL STOP character (.)
mode = _TokenizerMode.dot1;
case 0x2F: // U+002F SOLIDUS character (/)
mode = _TokenizerMode.slash;
case 0x30: // U+0030 DIGIT ZERO character (0)
assert(buffer.isEmpty);
mode = _TokenizerMode.zero;
buffer.add(current);
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
assert(buffer.isEmpty);
mode = _TokenizerMode.integer;
buffer.add(current);
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x47: // U+0047 LATIN CAPITAL LETTER G character
case 0x48: // U+0048 LATIN CAPITAL LETTER H character
case 0x49: // U+0049 LATIN CAPITAL LETTER I character
case 0x4A: // U+004A LATIN CAPITAL LETTER J character
case 0x4B: // U+004B LATIN CAPITAL LETTER K character
case 0x4C: // U+004C LATIN CAPITAL LETTER L character
case 0x4D: // U+004D LATIN CAPITAL LETTER M character
case 0x4E: // U+004E LATIN CAPITAL LETTER N character
case 0x4F: // U+004F LATIN CAPITAL LETTER O character
case 0x50: // U+0050 LATIN CAPITAL LETTER P character
case 0x51: // U+0051 LATIN CAPITAL LETTER Q character
case 0x52: // U+0052 LATIN CAPITAL LETTER R character
case 0x53: // U+0053 LATIN CAPITAL LETTER S character
case 0x54: // U+0054 LATIN CAPITAL LETTER T character
case 0x55: // U+0055 LATIN CAPITAL LETTER U character
case 0x56: // U+0056 LATIN CAPITAL LETTER V character
case 0x57: // U+0057 LATIN CAPITAL LETTER W character
case 0x58: // U+0058 LATIN CAPITAL LETTER X character
case 0x59: // U+0059 LATIN CAPITAL LETTER Y character
case 0x5A: // U+005A LATIN CAPITAL LETTER Z character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
case 0x67: // U+0067 LATIN SMALL LETTER G character
case 0x68: // U+0068 LATIN SMALL LETTER H character
case 0x69: // U+0069 LATIN SMALL LETTER I character
case 0x6A: // U+006A LATIN SMALL LETTER J character
case 0x6B: // U+006B LATIN SMALL LETTER K character
case 0x6C: // U+006C LATIN SMALL LETTER L character
case 0x6D: // U+006D LATIN SMALL LETTER M character
case 0x6E: // U+006E LATIN SMALL LETTER N character
case 0x6F: // U+006F LATIN SMALL LETTER O character
case 0x70: // U+0070 LATIN SMALL LETTER P character
case 0x71: // U+0071 LATIN SMALL LETTER Q character
case 0x72: // U+0072 LATIN SMALL LETTER R character
case 0x73: // U+0073 LATIN SMALL LETTER S character
case 0x74: // U+0074 LATIN SMALL LETTER T character
case 0x75: // U+0075 LATIN SMALL LETTER U character
case 0x76: // U+0076 LATIN SMALL LETTER V character
case 0x77: // U+0077 LATIN SMALL LETTER W character
case 0x78: // U+0078 LATIN SMALL LETTER X character
case 0x79: // U+0079 LATIN SMALL LETTER Y character
case 0x7A: // U+007A LATIN SMALL LETTER Z character
case 0x5F: // U+005F LOW LINE character (_)
assert(buffer.isEmpty);
mode = _TokenizerMode.identifier;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)}', line, column);
}
case _TokenizerMode.minus: // "-"
assert(buffer.length == 1 && buffer[0] == 0x2D);
switch (current) {
case -1:
throw ParserException('Unexpected end of file after minus sign', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
mode = _TokenizerMode.minusInteger;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} after minus sign (expected digit)', line, column);
}
case _TokenizerMode.zero: // "0"
assert(buffer.length == 1 && buffer[0] == 0x30);
switch (current) {
case -1:
yield _IntegerToken(0, line, column, start, index - 1);
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _IntegerToken(0, line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _IntegerToken(0, line, column, start, index - 1);
buffer.clear();
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x2E: // U+002E FULL STOP character (.)
mode = _TokenizerMode.numericDot;
buffer.add(current);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
mode = _TokenizerMode.integer;
buffer.add(current);
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x65: // U+0065 LATIN SMALL LETTER E character
mode = _TokenizerMode.e;
buffer.add(current);
case 0x58: // U+0058 LATIN CAPITAL LETTER X character
case 0x78: // U+0078 LATIN SMALL LETTER X character
mode = _TokenizerMode.x;
buffer.clear();
default:
throw ParserException('Unexpected character ${_describeRune(current)} after zero', line, column);
}
case _TokenizerMode.minusInteger: // "-0"
switch (current) {
case -1:
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x2E: // U+002E FULL STOP character (.)
mode = _TokenizerMode.numericDot;
buffer.add(current);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
mode = _TokenizerMode.integer;
buffer.add(current);
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x65: // U+0065 LATIN SMALL LETTER E character
mode = _TokenizerMode.e;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} after negative zero', line, column);
}
case _TokenizerMode.integer: // "00", "1", "-00"
switch (current) {
case -1:
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x2E: // U+002E FULL STOP character (.)
mode = _TokenizerMode.numericDot;
buffer.add(current);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
buffer.add(current);
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x65: // U+0065 LATIN SMALL LETTER E character
mode = _TokenizerMode.e;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)}', line, column);
}
case _TokenizerMode.integerOnly:
switch (current) {
case -1:
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x2E: // U+002E FULL STOP character (.)
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.dot1;
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
buffer.add(current); // https://github.com/dart-lang/sdk/issues/53349
default:
throw ParserException('Unexpected character ${_describeRune(current)} in integer', line, column);
}
case _TokenizerMode.numericDot: // "0.", "-0.", "00.", "1.", "-00."
switch (current) {
case -1:
throw ParserException('Unexpected end of file after decimal point', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
mode = _TokenizerMode.fraction;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} in fraction component', line, column);
}
case _TokenizerMode.fraction: // "0.0", "-0.0", "00.0", "1.0", "-00.0"
switch (current) {
case -1:
yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1);
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1);
buffer.clear();
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
buffer.add(current);
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x65: // U+0065 LATIN SMALL LETTER E character
mode = _TokenizerMode.e;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} in fraction component', line, column);
}
case _TokenizerMode.e: // "0e", "-0e", "00e", "1e", "-00e", "0.0e", "-0.0e", "00.0e", "1.0e", "-00.0e"
switch (current) {
case -1:
throw ParserException('Unexpected end of file after exponent separator', line, column);
case 0x2D: // U+002D HYPHEN-MINUS character (-)
mode = _TokenizerMode.negativeExponent;
buffer.add(current);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
mode = _TokenizerMode.exponent;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} after exponent separator', line, column);
}
case _TokenizerMode.negativeExponent: // "0e-", "-0e-", "00e-", "1e-", "-00e-", "0.0e-", "-0.0e-", "00.0e-", "1.0e-", "-00.0e-"
switch (current) {
case -1:
throw ParserException('Unexpected end of file after exponent separator and minus sign', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
mode = _TokenizerMode.exponent;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} in exponent', line, column);
}
case _TokenizerMode.exponent: // "0e0", "-0e0", "00e0", "1e0", "-00e0", "0.0e0", "-0.0e0", "00.0e0", "1.0e0", "-00.0e0", "0e-0", "-0e-0", "00e-0", "1e-0", "-00e-0", "0.0e-0", "-0.0e-0", "00.0e-0", "1.0e-0", "-00.0e-0"
switch (current) {
case -1:
yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1);
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1);
buffer.clear();
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} in exponent', line, column);
}
case _TokenizerMode.x: // "0x", "0X"
switch (current) {
case -1:
throw ParserException('Unexpected end of file after 0x prefix', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
mode = _TokenizerMode.hex;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} after 0x prefix', line, column);
}
case _TokenizerMode.hex:
switch (current) {
case -1:
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 16), line, column, start, index - 1);
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 16), line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 16), line, column, start, index - 1);
buffer.clear();
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} in hex literal', line, column);
}
case _TokenizerMode.dot1: // "."
switch (current) {
case -1:
yield _SymbolToken(0x2E, line, column, start, index - 1);
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _SymbolToken(0x2E, line, column, start, index - 1);
start = index;
mode = _TokenizerMode.main;
case 0x22: // U+0022 QUOTATION MARK character (")
yield _SymbolToken(0x2E, line, column, start, index);
assert(buffer.isEmpty);
start = index;
mode = _TokenizerMode.doubleQuote;
case 0x27: // U+0027 APOSTROPHE character (')
yield _SymbolToken(0x2E, line, column, start, index);
assert(buffer.isEmpty);
start = index;
mode = _TokenizerMode.quote;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _SymbolToken(0x2E, line, column, start, index - 1);
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x2E: // U+002E FULL STOP character (.)
mode = _TokenizerMode.dot2;
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
yield _SymbolToken(0x2E, line, column, start, index - 1);
assert(buffer.isEmpty);
start = index - 1;
mode = _TokenizerMode.integerOnly;
buffer.add(current);
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x47: // U+0047 LATIN CAPITAL LETTER G character
case 0x48: // U+0048 LATIN CAPITAL LETTER H character
case 0x49: // U+0049 LATIN CAPITAL LETTER I character
case 0x4A: // U+004A LATIN CAPITAL LETTER J character
case 0x4B: // U+004B LATIN CAPITAL LETTER K character
case 0x4C: // U+004C LATIN CAPITAL LETTER L character
case 0x4D: // U+004D LATIN CAPITAL LETTER M character
case 0x4E: // U+004E LATIN CAPITAL LETTER N character
case 0x4F: // U+004F LATIN CAPITAL LETTER O character
case 0x50: // U+0050 LATIN CAPITAL LETTER P character
case 0x51: // U+0051 LATIN CAPITAL LETTER Q character
case 0x52: // U+0052 LATIN CAPITAL LETTER R character
case 0x53: // U+0053 LATIN CAPITAL LETTER S character
case 0x54: // U+0054 LATIN CAPITAL LETTER T character
case 0x55: // U+0055 LATIN CAPITAL LETTER U character
case 0x56: // U+0056 LATIN CAPITAL LETTER V character
case 0x57: // U+0057 LATIN CAPITAL LETTER W character
case 0x58: // U+0058 LATIN CAPITAL LETTER X character
case 0x59: // U+0059 LATIN CAPITAL LETTER Y character
case 0x5A: // U+005A LATIN CAPITAL LETTER Z character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
case 0x67: // U+0067 LATIN SMALL LETTER G character
case 0x68: // U+0068 LATIN SMALL LETTER H character
case 0x69: // U+0069 LATIN SMALL LETTER I character
case 0x6A: // U+006A LATIN SMALL LETTER J character
case 0x6B: // U+006B LATIN SMALL LETTER K character
case 0x6C: // U+006C LATIN SMALL LETTER L character
case 0x6D: // U+006D LATIN SMALL LETTER M character
case 0x6E: // U+006E LATIN SMALL LETTER N character
case 0x6F: // U+006F LATIN SMALL LETTER O character
case 0x70: // U+0070 LATIN SMALL LETTER P character
case 0x71: // U+0071 LATIN SMALL LETTER Q character
case 0x72: // U+0072 LATIN SMALL LETTER R character
case 0x73: // U+0073 LATIN SMALL LETTER S character
case 0x74: // U+0074 LATIN SMALL LETTER T character
case 0x75: // U+0075 LATIN SMALL LETTER U character
case 0x76: // U+0076 LATIN SMALL LETTER V character
case 0x77: // U+0077 LATIN SMALL LETTER W character
case 0x78: // U+0078 LATIN SMALL LETTER X character
case 0x79: // U+0079 LATIN SMALL LETTER Y character
case 0x7A: // U+007A LATIN SMALL LETTER Z character
case 0x5F: // U+005F LOW LINE character (_)
yield _SymbolToken(0x2E, line, column, start, index - 1);
assert(buffer.isEmpty);
start = index - 1;
mode = _TokenizerMode.identifier;
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} after period', line, column);
}
case _TokenizerMode.dot2: // ".."
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside "..." symbol', line, column);
case 0x2E: // U+002E FULL STOP character (.)
yield _SymbolToken(_SymbolToken.tripleDot, line, column, start, index);
start = index;
mode = _TokenizerMode.main;
default:
throw ParserException('Unexpected character ${_describeRune(current)} inside "..." symbol', line, column);
}
case _TokenizerMode.identifier:
switch (current) {
case -1:
yield _IdentifierToken(String.fromCharCodes(buffer), line, column, start, index - 1);
yield _EofToken(line, column, index - 1, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
yield _IdentifierToken(String.fromCharCodes(buffer), line, column, start, index - 1);
buffer.clear();
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _IdentifierToken(String.fromCharCodes(buffer), line, column, start, index - 1);
buffer.clear();
yield _SymbolToken(current, line, column, index - 1, index);
start = index;
mode = _TokenizerMode.main;
case 0x2E: // U+002E FULL STOP character (.)
yield _IdentifierToken(String.fromCharCodes(buffer), line, column, start, index);
buffer.clear();
start = index;
mode = _TokenizerMode.dot1;
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x47: // U+0047 LATIN CAPITAL LETTER G character
case 0x48: // U+0048 LATIN CAPITAL LETTER H character
case 0x49: // U+0049 LATIN CAPITAL LETTER I character
case 0x4A: // U+004A LATIN CAPITAL LETTER J character
case 0x4B: // U+004B LATIN CAPITAL LETTER K character
case 0x4C: // U+004C LATIN CAPITAL LETTER L character
case 0x4D: // U+004D LATIN CAPITAL LETTER M character
case 0x4E: // U+004E LATIN CAPITAL LETTER N character
case 0x4F: // U+004F LATIN CAPITAL LETTER O character
case 0x50: // U+0050 LATIN CAPITAL LETTER P character
case 0x51: // U+0051 LATIN CAPITAL LETTER Q character
case 0x52: // U+0052 LATIN CAPITAL LETTER R character
case 0x53: // U+0053 LATIN CAPITAL LETTER S character
case 0x54: // U+0054 LATIN CAPITAL LETTER T character
case 0x55: // U+0055 LATIN CAPITAL LETTER U character
case 0x56: // U+0056 LATIN CAPITAL LETTER V character
case 0x57: // U+0057 LATIN CAPITAL LETTER W character
case 0x58: // U+0058 LATIN CAPITAL LETTER X character
case 0x59: // U+0059 LATIN CAPITAL LETTER Y character
case 0x5A: // U+005A LATIN CAPITAL LETTER Z character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
case 0x67: // U+0067 LATIN SMALL LETTER G character
case 0x68: // U+0068 LATIN SMALL LETTER H character
case 0x69: // U+0069 LATIN SMALL LETTER I character
case 0x6A: // U+006A LATIN SMALL LETTER J character
case 0x6B: // U+006B LATIN SMALL LETTER K character
case 0x6C: // U+006C LATIN SMALL LETTER L character
case 0x6D: // U+006D LATIN SMALL LETTER M character
case 0x6E: // U+006E LATIN SMALL LETTER N character
case 0x6F: // U+006F LATIN SMALL LETTER O character
case 0x70: // U+0070 LATIN SMALL LETTER P character
case 0x71: // U+0071 LATIN SMALL LETTER Q character
case 0x72: // U+0072 LATIN SMALL LETTER R character
case 0x73: // U+0073 LATIN SMALL LETTER S character
case 0x74: // U+0074 LATIN SMALL LETTER T character
case 0x75: // U+0075 LATIN SMALL LETTER U character
case 0x76: // U+0076 LATIN SMALL LETTER V character
case 0x77: // U+0077 LATIN SMALL LETTER W character
case 0x78: // U+0078 LATIN SMALL LETTER X character
case 0x79: // U+0079 LATIN SMALL LETTER Y character
case 0x7A: // U+007A LATIN SMALL LETTER Z character
case 0x5F: // U+005F LOW LINE character (_)
buffer.add(current);
default:
throw ParserException('Unexpected character ${_describeRune(current)} inside identifier', line, column);
}
case _TokenizerMode.quote:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside string', line, column);
case 0x0A: // U+000A LINE FEED (LF)
throw ParserException('Unexpected end of line inside string', line, column);
case 0x27: // U+0027 APOSTROPHE character (')
yield _StringToken(String.fromCharCodes(buffer), line, column, start, index);
buffer.clear();
start = index;
mode = _TokenizerMode.endQuote;
case 0x5C: // U+005C REVERSE SOLIDUS character (\)
mode = _TokenizerMode.quoteEscape;
default:
buffer.add(current);
}
case _TokenizerMode.quoteEscape:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside string', line, column);
case 0x22: // U+0022 QUOTATION MARK character (")
case 0x27: // U+0027 APOSTROPHE character (')
case 0x5C: // U+005C REVERSE SOLIDUS character (\)
case 0x2F: // U+002F SOLIDUS character (/)
buffer.add(current);
mode = _TokenizerMode.quote;
case 0x62: // U+0062 LATIN SMALL LETTER B character
buffer.add(0x08);
mode = _TokenizerMode.quote;
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer.add(0x0C);
mode = _TokenizerMode.quote;
case 0x6E: // U+006E LATIN SMALL LETTER N character
buffer.add(0x0A);
mode = _TokenizerMode.quote;
case 0x72: // U+0072 LATIN SMALL LETTER R character
buffer.add(0x0D);
mode = _TokenizerMode.quote;
case 0x74: // U+0074 LATIN SMALL LETTER T character
buffer.add(0x09);
mode = _TokenizerMode.quote;
case 0x75: // U+0075 LATIN SMALL LETTER U character
assert(buffer2.isEmpty);
mode = _TokenizerMode.quoteEscapeUnicode1;
default:
throw ParserException('Unexpected character ${_describeRune(current)} after backslash in string', line, column);
}
case _TokenizerMode.quoteEscapeUnicode1:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside Unicode escape', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer2.add(current);
mode = _TokenizerMode.quoteEscapeUnicode2;
default:
throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column);
}
case _TokenizerMode.quoteEscapeUnicode2:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside Unicode escape', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer2.add(current);
mode = _TokenizerMode.quoteEscapeUnicode3;
default:
throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column);
}
case _TokenizerMode.quoteEscapeUnicode3:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside Unicode escape', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer2.add(current);
mode = _TokenizerMode.quoteEscapeUnicode4;
default:
throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column);
}
case _TokenizerMode.quoteEscapeUnicode4:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside Unicode escape', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer2.add(current);
buffer.add(int.parse(String.fromCharCodes(buffer2), radix: 16));
buffer2.clear();
mode = _TokenizerMode.quote;
default:
throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column);
}
case _TokenizerMode.doubleQuote:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside string', line, column);
case 0x0A: // U+000A LINE FEED (LF)
throw ParserException('Unexpected end of line inside string', line, column);
case 0x22: // U+0022 QUOTATION MARK character (")
yield _StringToken(String.fromCharCodes(buffer), line, column, start, index);
buffer.clear();
start = index;
mode = _TokenizerMode.endQuote;
case 0x5C: // U+005C REVERSE SOLIDUS character (\)
mode = _TokenizerMode.doubleQuoteEscape;
default:
buffer.add(current);
}
case _TokenizerMode.doubleQuoteEscape:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside string', line, column);
case 0x22: // U+0022 QUOTATION MARK character (")
case 0x27: // U+0027 APOSTROPHE character (')
case 0x5C: // U+005C REVERSE SOLIDUS character (\)
case 0x2F: // U+002F SOLIDUS character (/)
buffer.add(current);
mode = _TokenizerMode.doubleQuote;
case 0x62: // U+0062 LATIN SMALL LETTER B character
buffer.add(0x08);
mode = _TokenizerMode.doubleQuote;
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer.add(0x0C);
mode = _TokenizerMode.doubleQuote;
case 0x6E: // U+006E LATIN SMALL LETTER N character
buffer.add(0x0A);
mode = _TokenizerMode.doubleQuote;
case 0x72: // U+0072 LATIN SMALL LETTER R character
buffer.add(0x0D);
mode = _TokenizerMode.doubleQuote;
case 0x74: // U+0074 LATIN SMALL LETTER T character
buffer.add(0x09);
mode = _TokenizerMode.doubleQuote;
case 0x75: // U+0075 LATIN SMALL LETTER U character
assert(buffer2.isEmpty);
mode = _TokenizerMode.doubleQuoteEscapeUnicode1;
default:
throw ParserException('Unexpected character ${_describeRune(current)} after backslash in string', line, column);
}
case _TokenizerMode.doubleQuoteEscapeUnicode1:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside Unicode escape', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer2.add(current);
mode = _TokenizerMode.doubleQuoteEscapeUnicode2;
default:
throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column);
}
case _TokenizerMode.doubleQuoteEscapeUnicode2:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside Unicode escape', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer2.add(current);
mode = _TokenizerMode.doubleQuoteEscapeUnicode3;
default:
throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column);
}
case _TokenizerMode.doubleQuoteEscapeUnicode3:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside Unicode escape', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer2.add(current);
mode = _TokenizerMode.doubleQuoteEscapeUnicode4;
default:
throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column);
}
case _TokenizerMode.doubleQuoteEscapeUnicode4:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside Unicode escape', line, column);
case 0x30: // U+0030 DIGIT ZERO character (0)
case 0x31: // U+0031 DIGIT ONE character (1)
case 0x32: // U+0032 DIGIT TWO character (2)
case 0x33: // U+0033 DIGIT THREE character (3)
case 0x34: // U+0034 DIGIT FOUR character (4)
case 0x35: // U+0035 DIGIT FIVE character (5)
case 0x36: // U+0036 DIGIT SIX character (6)
case 0x37: // U+0037 DIGIT SEVEN character (7)
case 0x38: // U+0038 DIGIT EIGHT character (8)
case 0x39: // U+0039 DIGIT NINE character (9)
case 0x41: // U+0041 LATIN CAPITAL LETTER A character
case 0x42: // U+0042 LATIN CAPITAL LETTER B character
case 0x43: // U+0043 LATIN CAPITAL LETTER C character
case 0x44: // U+0044 LATIN CAPITAL LETTER D character
case 0x45: // U+0045 LATIN CAPITAL LETTER E character
case 0x46: // U+0046 LATIN CAPITAL LETTER F character
case 0x61: // U+0061 LATIN SMALL LETTER A character
case 0x62: // U+0062 LATIN SMALL LETTER B character
case 0x63: // U+0063 LATIN SMALL LETTER C character
case 0x64: // U+0064 LATIN SMALL LETTER D character
case 0x65: // U+0065 LATIN SMALL LETTER E character
case 0x66: // U+0066 LATIN SMALL LETTER F character
buffer2.add(current);
buffer.add(int.parse(String.fromCharCodes(buffer2), radix: 16));
buffer2.clear();
mode = _TokenizerMode.doubleQuote;
default:
throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column);
}
case _TokenizerMode.endQuote:
switch (current) {
case -1:
yield _EofToken(line, column, start, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
case 0x20: // U+0020 SPACE character
start = index;
mode = _TokenizerMode.main;
case 0x28: // U+0028 LEFT PARENTHESIS character (()
case 0x29: // U+0029 RIGHT PARENTHESIS character ())
case 0x2C: // U+002C COMMA character (,)
case 0x3A: // U+003A COLON character (:)
case 0x3B: // U+003B SEMICOLON character (;)
case 0x3D: // U+003D EQUALS SIGN character (=)
case 0x5B: // U+005B LEFT SQUARE BRACKET character ([)
case 0x5D: // U+005D RIGHT SQUARE BRACKET character (])
case 0x7B: // U+007B LEFT CURLY BRACKET character ({)
case 0x7D: // U+007D RIGHT CURLY BRACKET character (})
yield _SymbolToken(current, line, column, start, index);
start = index;
mode = _TokenizerMode.main;
case 0x2E: // U+002E FULL STOP character (.)
mode = _TokenizerMode.dot1;
default:
throw ParserException('Unexpected character ${_describeRune(current)} after end quote', line, column);
}
case _TokenizerMode.slash:
switch (current) {
case -1:
throw ParserException('Unexpected end of file inside comment delimiter', line, column);
case 0x2A: // U+002A ASTERISK character (*)
mode = _TokenizerMode.blockComment;
case 0x2F: // U+002F SOLIDUS character (/)
mode = _TokenizerMode.comment;
default:
throw ParserException('Unexpected character ${_describeRune(current)} inside comment delimiter', line, column);
}
case _TokenizerMode.comment:
switch (current) {
case -1:
yield _EofToken(line, column, start, index);
return;
case 0x0A: // U+000A LINE FEED (LF)
mode = _TokenizerMode.main;
default:
// ignored, comment
break;
}
case _TokenizerMode.blockComment:
switch (current) {
case -1:
throw ParserException('Unexpected end of file in block comment', line, column);
case 0x2A: // U+002A ASTERISK character (*)
mode = _TokenizerMode.blockCommentEnd;
default:
// ignored, comment
break;
}
case _TokenizerMode.blockCommentEnd:
switch (current) {
case -1:
throw ParserException('Unexpected end of file in block comment', line, column);
case 0x2F: // U+002F SOLIDUS character (/)
mode = _TokenizerMode.main;
default:
// ignored, comment
mode = _TokenizerMode.blockComment;
break;
}
}
}
}
/// API for parsing Remote Flutter Widgets text files.
///
/// Text data files can be parsed by using [readDataFile]. (Unlike the binary
/// variant of this format, the root of a text data file is always a map.)
///
/// Test library files can be parsed by using [readLibraryFile].
class _Parser {
_Parser(Iterable<_Token> source, this.sourceIdentifier) : _source = source.iterator..moveNext();
final Iterator<_Token> _source;
final Object? sourceIdentifier;
int _previousEnd = 0;
void _advance() {
assert(_source.current is! _EofToken);
_previousEnd = _source.current.end;
final bool advanced = _source.moveNext();
assert(advanced);
}
SourceLocation? _getSourceLocation() {
if (sourceIdentifier != null) {
return SourceLocation(sourceIdentifier!, _source.current.start);
}
return null;
}
T _withSourceRange<T extends BlobNode>(T node, SourceLocation? start) {
if (sourceIdentifier != null && start != null) {
node.associateSource(SourceRange(
start,
SourceLocation(sourceIdentifier!, _previousEnd),
));
}
return node;
}
bool _foundIdentifier(String identifier) {
return (_source.current is _IdentifierToken)
&& ((_source.current as _IdentifierToken).value == identifier);
}
void _expectIdentifier(String value) {
if (_source.current is! _IdentifierToken) {
throw ParserException._expected('identifier', _source.current);
}
if ((_source.current as _IdentifierToken).value != value) {
throw ParserException._expected(value, _source.current);
}
_advance();
}
String _readIdentifier() {
if (_source.current is! _IdentifierToken) {
throw ParserException._expected('identifier', _source.current);
}
final String result = (_source.current as _IdentifierToken).value;
_advance();
return result;
}
String _readString() {
if (_source.current is! _StringToken) {
throw ParserException._expected('string', _source.current);
}
final String result = (_source.current as _StringToken).value;
_advance();
return result;
}
bool _foundSymbol(int symbol) {
return (_source.current is _SymbolToken)
&& ((_source.current as _SymbolToken).symbol == symbol);
}
bool _maybeReadSymbol(int symbol) {
if (_foundSymbol(symbol)) {
_advance();
return true;
}
return false;
}
void _expectSymbol(int symbol) {
if (_source.current is! _SymbolToken) {
throw ParserException._expected('symbol "${String.fromCharCode(symbol)}"', _source.current);
}
if ((_source.current as _SymbolToken).symbol != symbol) {
throw ParserException._expected('symbol "${String.fromCharCode(symbol)}"', _source.current);
}
_advance();
}
String _readKey() {
if (_source.current is _IdentifierToken) {
return _readIdentifier();
}
return _readString();
}
DynamicMap _readMap({
required bool extended,
List<String> widgetBuilderScope = const <String>[],
}) {
_expectSymbol(_SymbolToken.openBrace);
final DynamicMap results = _readMapBody(
widgetBuilderScope: widgetBuilderScope,
extended: extended,
);
_expectSymbol(_SymbolToken.closeBrace);
return results;
}
DynamicMap _readMapBody({
required bool extended,
List<String> widgetBuilderScope = const <String>[],
}) {
final DynamicMap results = DynamicMap(); // ignore: prefer_collection_literals
while (_source.current is! _SymbolToken) {
final String key = _readKey();
if (results.containsKey(key)) {
throw ParserException._fromToken('Duplicate key "$key" in map', _source.current);
}
_expectSymbol(_SymbolToken.colon);
final Object value = _readValue(
extended: extended,
nullOk: true,
widgetBuilderScope: widgetBuilderScope,
);
if (value != missing) {
results[key] = value;
}
if (_foundSymbol(_SymbolToken.comma)) {
_advance();
} else {
break;
}
}
return results;
}
final List<String> _loopIdentifiers = <String>[];
DynamicList _readList({
required bool extended,
List<String> widgetBuilderScope = const <String>[],
}) {
final DynamicList results = DynamicList.empty(growable: true);
_expectSymbol(_SymbolToken.openBracket);
while (!_foundSymbol(_SymbolToken.closeBracket)) {
if (extended && _foundSymbol(_SymbolToken.tripleDot)) {
final SourceLocation? start = _getSourceLocation();
_advance();
_expectIdentifier('for');
final _Token loopIdentifierToken = _source.current;
final String loopIdentifier = _readIdentifier();
_checkIsNotReservedWord(loopIdentifier, loopIdentifierToken);
_expectIdentifier('in');
final Object collection = _readValue(
widgetBuilderScope: widgetBuilderScope,
extended: true,
);
_expectSymbol(_SymbolToken.colon);
_loopIdentifiers.add(loopIdentifier);
final Object template = _readValue(
widgetBuilderScope: widgetBuilderScope,
extended: extended,
);
assert(_loopIdentifiers.last == loopIdentifier);
_loopIdentifiers.removeLast();
results.add(_withSourceRange(Loop(collection, template), start));
} else {
final Object value = _readValue(
widgetBuilderScope: widgetBuilderScope,
extended: extended,
);
results.add(value);
}
if (_foundSymbol(_SymbolToken.comma)) {
_advance();
} else if (!_foundSymbol(_SymbolToken.closeBracket)) {
throw ParserException._expected('comma', _source.current);
}
}
_expectSymbol(_SymbolToken.closeBracket);
return results;
}
Switch _readSwitch(SourceLocation? start, {
List<String> widgetBuilderScope = const <String>[],
}) {
final Object value = _readValue(extended: true, widgetBuilderScope: widgetBuilderScope);
final Map<Object?, Object> cases = <Object?, Object>{};
_expectSymbol(_SymbolToken.openBrace);
while (_source.current is! _SymbolToken) {
final Object? key;
if (_foundIdentifier('default')) {
if (cases.containsKey(null)) {
throw ParserException._fromToken('Switch has multiple default cases', _source.current);
}
key = null;
_advance();
} else {
key = _readValue(extended: true, widgetBuilderScope: widgetBuilderScope);
if (cases.containsKey(key)) {
throw ParserException._fromToken('Switch has duplicate cases for key $key', _source.current);
}
}
_expectSymbol(_SymbolToken.colon);
final Object value = _readValue(extended: true, widgetBuilderScope: widgetBuilderScope);
cases[key] = value;
if (_foundSymbol(_SymbolToken.comma)) {
_advance();
} else {
break;
}
}
_expectSymbol(_SymbolToken.closeBrace);
return _withSourceRange(Switch(value, cases), start);
}
List<Object> _readParts({ bool optional = false }) {
if (optional && !_foundSymbol(_SymbolToken.dot)) {
return const <Object>[];
}
final List<Object> results = <Object>[];
do {
_expectSymbol(_SymbolToken.dot);
if (_source.current is _IntegerToken) {
results.add((_source.current as _IntegerToken).value);
} else if (_source.current is _StringToken) {
results.add((_source.current as _StringToken).value);
} else if (_source.current is _IdentifierToken) {
results.add((_source.current as _IdentifierToken).value);
} else {
throw ParserException._unexpected(_source.current);
}
_advance();
} while (_foundSymbol(_SymbolToken.dot));
return results;
}
Object _readValue({
required bool extended,
bool nullOk = false,
List<String> widgetBuilderScope = const <String>[],
}) {
if (_source.current is _SymbolToken) {
switch ((_source.current as _SymbolToken).symbol) {
case _SymbolToken.openBracket:
return _readList(widgetBuilderScope: widgetBuilderScope, extended: extended);
case _SymbolToken.openBrace:
return _readMap(widgetBuilderScope: widgetBuilderScope, extended: extended);
case _SymbolToken.openParen:
return _readWidgetBuilderDeclaration(widgetBuilderScope: widgetBuilderScope);
}
} else if (_source.current is _IntegerToken) {
final Object result = (_source.current as _IntegerToken).value;
_advance();
return result;
} else if (_source.current is _DoubleToken) {
final Object result = (_source.current as _DoubleToken).value;
_advance();
return result;
} else if (_source.current is _StringToken) {
final Object result = (_source.current as _StringToken).value;
_advance();
return result;
} else if (_source.current is _IdentifierToken) {
final String identifier = (_source.current as _IdentifierToken).value;
if (identifier == 'true') {
_advance();
return true;
}
if (identifier == 'false') {
_advance();
return false;
}
if (identifier == 'null' && nullOk) {
_advance();
return missing;
}
if (!extended) {
throw ParserException._unexpected(_source.current);
}
if (identifier == 'event') {
final SourceLocation? start = _getSourceLocation();
_advance();
return _withSourceRange(
EventHandler(
_readString(),
_readMap(widgetBuilderScope: widgetBuilderScope, extended: true),
),
start,
);
}
if (identifier == 'args') {
final SourceLocation? start = _getSourceLocation();
_advance();
return _withSourceRange(ArgsReference(_readParts()), start);
}
if (identifier == 'data') {
final SourceLocation? start = _getSourceLocation();
_advance();
return _withSourceRange(DataReference(_readParts()), start);
}
if (identifier == 'state') {
final SourceLocation? start = _getSourceLocation();
_advance();
return _withSourceRange(StateReference(_readParts()), start);
}
if (identifier == 'switch') {
final SourceLocation? start = _getSourceLocation();
_advance();
return _readSwitch(start, widgetBuilderScope: widgetBuilderScope);
}
if (identifier == 'set') {
final SourceLocation? start = _getSourceLocation();
_advance();
final SourceLocation? innerStart = _getSourceLocation();
_expectIdentifier('state');
final StateReference stateReference = _withSourceRange(StateReference(_readParts()), innerStart);
_expectSymbol(_SymbolToken.equals);
final Object value = _readValue(widgetBuilderScope: widgetBuilderScope, extended: true);
return _withSourceRange(SetStateHandler(stateReference, value), start);
}
if (widgetBuilderScope.contains(identifier)) {
final SourceLocation? start = _getSourceLocation();
_advance();
return _withSourceRange(WidgetBuilderArgReference(identifier, _readParts()), start);
}
final int index = _loopIdentifiers.lastIndexOf(identifier) + 1;
if (index > 0) {
final SourceLocation? start = _getSourceLocation();
_advance();
return _withSourceRange(LoopReference(_loopIdentifiers.length - index, _readParts(optional: true)), start);
}
return _readConstructorCall(widgetBuilderScope: widgetBuilderScope);
}
throw ParserException._unexpected(_source.current);
}
WidgetBuilderDeclaration _readWidgetBuilderDeclaration({
List<String> widgetBuilderScope = const <String>[],
}) {
_expectSymbol(_SymbolToken.openParen);
final _Token argumentNameToken = _source.current;
final String argumentName = _readIdentifier();
_checkIsNotReservedWord(argumentName, argumentNameToken);
_expectSymbol(_SymbolToken.closeParen);
_expectSymbol(_SymbolToken.equals);
_expectSymbol(_SymbolToken.greatherThan);
final _Token valueToken = _source.current;
final Object widget = _readValue(
extended: true,
widgetBuilderScope: <String>[...widgetBuilderScope, argumentName],
);
if (widget is! ConstructorCall && widget is! Switch) {
throw ParserException._fromToken('Expecting a switch or constructor call got $widget', valueToken);
}
return WidgetBuilderDeclaration(argumentName, widget as BlobNode);
}
ConstructorCall _readConstructorCall({
List<String> widgetBuilderScope = const <String>[],
}) {
final SourceLocation? start = _getSourceLocation();
final String name = _readIdentifier();
_expectSymbol(_SymbolToken.openParen);
final DynamicMap arguments = _readMapBody(
extended: true,
widgetBuilderScope: widgetBuilderScope,
);
_expectSymbol(_SymbolToken.closeParen);
return _withSourceRange(ConstructorCall(name, arguments), start);
}
WidgetDeclaration _readWidgetDeclaration() {
final SourceLocation? start = _getSourceLocation();
_expectIdentifier('widget');
final String name = _readIdentifier();
DynamicMap? initialState;
if (_foundSymbol(_SymbolToken.openBrace)) {
initialState = _readMap(extended: false);
}
_expectSymbol(_SymbolToken.equals);
final BlobNode root;
if (_foundIdentifier('switch')) {
final SourceLocation? switchStart = _getSourceLocation();
_advance();
root = _readSwitch(switchStart);
} else {
root = _readConstructorCall();
}
_expectSymbol(_SymbolToken.semicolon);
return _withSourceRange(WidgetDeclaration(name, initialState, root), start);
}
Iterable<WidgetDeclaration> _readWidgetDeclarations() sync* {
while (_foundIdentifier('widget')) {
yield _readWidgetDeclaration();
}
}
Import _readImport() {
final SourceLocation? start = _getSourceLocation();
_expectIdentifier('import');
final List<String> parts = <String>[];
do {
parts.add(_readKey());
} while (_maybeReadSymbol(_SymbolToken.dot));
_expectSymbol(_SymbolToken.semicolon);
return _withSourceRange(Import(LibraryName(parts)), start);
}
Iterable<Import> _readImports() sync* {
while (_foundIdentifier('import')) {
yield _readImport();
}
}
DynamicMap readDataFile() {
final DynamicMap result = _readMap(extended: false);
_expectEof('end of file');
return result;
}
RemoteWidgetLibrary readLibraryFile() {
final RemoteWidgetLibrary result = RemoteWidgetLibrary(
_readImports().toList(),
_readWidgetDeclarations().toList(),
);
if (result.widgets.isEmpty) {
_expectEof('keywords "import" or "widget", or end of file');
} else {
_expectEof('keyword "widget" or end of file');
}
return result;
}
void _expectEof(String expectation) {
if (_source.current is! _EofToken) {
throw ParserException._expected(expectation, _source.current);
}
final bool more = _source.moveNext();
assert(!more);
}
}
| packages/packages/rfw/lib/src/dart/text.dart/0 | {
"file_path": "packages/packages/rfw/lib/src/dart/text.dart",
"repo_id": "packages",
"token_count": 44534
} | 1,083 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is hand-formatted.
// ignore_for_file: avoid_dynamic_calls
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:rfw/formats.dart' show parseDataFile, parseLibraryFile;
import 'package:rfw/rfw.dart';
void main() {
testWidgets('list lookup', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent(<String, Object?>{
'list': <Object?>[ 0, 1, 2, 3, 4 ],
});
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(find.byType(RemoteWidget), findsOneWidget);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(find.byType(ErrorWidget), findsOneWidget);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = Column(
children: [
...for v in data.list: Text(text: v, textDirection: "ltr"),
],
);
'''));
await tester.pump();
expect(find.byType(Text), findsNWidgets(5));
});
testWidgets('data updates', (WidgetTester tester) async {
int buildCount = 0;
int? lastValue;
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), LocalWidgetLibrary(<String, LocalWidgetBuilder>{
'Test': (BuildContext context, DataSource source) {
buildCount += 1;
lastValue = source.v<int>(<Object>['value']);
return const SizedBox.shrink();
},
}));
final DynamicContent data = DynamicContent(<String, Object?>{
'list': <Object?>[
<String, Object?>{ 'a': 0 },
<String, Object?>{ 'a': 1 },
<String, Object?>{ 'a': 2 },
],
});
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(buildCount, 0);
expect(lastValue, isNull);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = Test(value: data.list.1.a);
'''));
await tester.pump();
expect(buildCount, 1);
expect(lastValue, 1);
data.update('list', <Object?>[
<String, Object?>{ 'a': 0 },
<String, Object?>{ 'a': 3 },
<String, Object?>{ 'a': 2 },
]);
await tester.pump();
expect(buildCount, 2);
expect(lastValue, 3);
data.update('list', <Object?>[
<String, Object?>{ 'a': 1 },
<String, Object?>{ 'a': 3 },
]);
await tester.pump();
expect(buildCount, 2);
expect(lastValue, 3);
data.update('list', <Object?>[
<String, Object?>{ 'a': 1 },
<String, Object?>{ },
]);
await tester.pump();
expect(buildCount, 3);
expect(lastValue, null);
data.update('list', <Object?>[
<String, Object?>{ 'a': 1 },
]);
await tester.pump();
expect(buildCount, 3);
expect(lastValue, null);
});
testWidgets('$RemoteFlutterWidgetsException', (WidgetTester tester) async {
expect(const RemoteFlutterWidgetsException('test').toString(), 'test');
});
testWidgets('deepClone', (WidgetTester tester) async {
final Map<String, Object> map = <String, Object>{
'outer': <String, Object>{
'inner': true,
}
};
expect(identical(deepClone(map), map), isFalse);
expect(deepClone(map), equals(map));
});
testWidgets('updateText, updateBinary, clearLibraries', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(find.byType(RemoteWidget), findsOneWidget);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(find.byType(ErrorWidget), findsOneWidget);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = ColoredBox(color: 0xFF000000);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000000));
runtime.update(const LibraryName(<String>['test']), decodeLibraryBlob(encodeLibraryBlob(parseLibraryFile('''
import core;
widget root = ColoredBox(color: 0xFF000001);
'''))));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000001));
runtime.clearLibraries();
await tester.pump();
expect(find.byType(RemoteWidget), findsOneWidget);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(find.byType(ErrorWidget), findsOneWidget);
});
testWidgets('Runtime cached build', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['core']), 'Placeholder'),
),
);
expect(find.byType(Placeholder), findsOneWidget);
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['core']), 'SizedBoxShrink'),
),
);
expect(find.byType(Placeholder), findsNothing);
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['core']), 'Placeholder'),
),
);
expect(find.byType(Placeholder), findsOneWidget);
});
testWidgets('Import loops', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['a']), parseLibraryFile('''
import b;
'''))
..update(const LibraryName(<String>['b']), parseLibraryFile('''
import a;
'''));
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['a']), 'widget'),
),
);
expect(tester.takeException().toString(), 'Library a indirectly depends on itself via b which depends on a.');
});
testWidgets('Import loops', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['a']), parseLibraryFile('''
import a;
'''));
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['a']), 'widget'),
),
);
expect(tester.takeException().toString(), 'Library a depends on itself.');
});
testWidgets('Missing libraries in import', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['a']), parseLibraryFile('''
import b;
'''));
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['a']), 'widget'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(tester.widget<ErrorWidget>(find.byType(ErrorWidget)).message, contains('Could not find remote widget named widget in a, possibly because some dependencies were missing: b'));
});
testWidgets('Missing libraries in specified widget', (WidgetTester tester) async {
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['a']), 'widget'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(tester.widget<ErrorWidget>(find.byType(ErrorWidget)).message, contains('Could not find remote widget named widget in a, possibly because some dependencies were missing: a'));
});
testWidgets('Missing libraries in import via dependency', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['a']), parseLibraryFile('''
import b;
widget widget = test();
'''));
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['a']), 'widget'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(tester.widget<ErrorWidget>(find.byType(ErrorWidget)).message, contains('Could not find remote widget named test in a, possibly because some dependencies were missing: b'));
});
testWidgets('Missing widget', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['a']), parseLibraryFile(''));
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['a']), 'widget'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(tester.widget<ErrorWidget>(find.byType(ErrorWidget)).message, contains('Could not find remote widget named widget in a.'));
});
testWidgets('Runtime', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { level: 0 } = inner(level: state.level);
widget inner { level: 1 } = ColoredBox(color: args.level);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000000));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { level: 0 } = inner(level: state.level);
widget inner { level: 1 } = ColoredBox(color: state.level);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000001));
});
testWidgets('Runtime', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { level: 0 } = switch state.level {
0: ColoredBox(color: 2),
};
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000002));
});
testWidgets('Runtime', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
expect(runtime.libraries.length, 1);
final LibraryName libraryName = runtime.libraries.entries.first.key;
expect('$libraryName', 'core');
final WidgetLibrary widgetLibrary = runtime.libraries.entries.first.value;
expect(widgetLibrary, isA<LocalWidgetLibrary>());
widgetLibrary as LocalWidgetLibrary;
expect(widgetLibrary.widgets.length, greaterThan(1));
});
testWidgets('Runtime', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { level: 0 } = GestureDetector(
onTap: set state.level = 1,
child: ColoredBox(color: state.level),
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000000));
await tester.tap(find.byType(ColoredBox));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000001));
});
testWidgets('DynamicContent', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = ColoredBox(color: data.color.value);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000000));
data.update('color', json.decode('{"value":1}') as Object);
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000001));
data.update('color', parseDataFile('{value:2}'));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000002));
data.update('color', decodeDataBlob(Uint8List.fromList(<int>[
0xFE, 0x52, 0x57, 0x44, // signature
0x07, // data is a map
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which has one key
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which has five letters
0x76, 0x61, 0x6c, 0x75, 0x65, // ...which are "value"
0x02, // and the value is an integer
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which is the number 2
])));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000002));
});
testWidgets('DynamicContent', (WidgetTester tester) async {
final DynamicContent data = DynamicContent(<String, Object?>{'hello': 'world'});
expect(data.toString(), 'DynamicContent({hello: world})');
});
testWidgets('binding loop variables', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent(<String, Object?>{
'list': <Object?>[
<String, Object?>{
'a': <String, Object?>{ 'b': 0xEE },
'c': <Object?>[ 0xDD ],
},
],
});
final List<String> eventLog = <String>[];
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
onEvent: (String eventName, DynamicMap eventArguments) {
eventLog.add('$eventName $eventArguments');
},
),
);
expect(find.byType(RemoteWidget), findsOneWidget);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(find.byType(ErrorWidget), findsOneWidget);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget verify = ColoredBox(color: args.value.0.q.0);
widget root = verify(
value: [
...for v in data.list: {
q: [ v.a.b ],
},
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x000000EE));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget verify = ColoredBox(color: args.value.0.q.0);
widget root = verify(
value: [
...for v in data.list: {
q: [ ...for w in v.c: w ],
},
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x000000DD));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget verify = ColoredBox(color: args.value.0.q);
widget root = verify(
value: [
...for v in data.list: {
q: switch v.a.b {
0xEE: 0xCC,
default: 0xFF,
},
},
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x000000CC));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget verify { state: true } = ColoredBox(color: args.value.c.0);
widget remote = SizedBox(child: args.corn.0);
widget root = remote(
corn: [
...for v in data.list:
verify(value: v),
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x000000DD));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget verify { state: true } = ColoredBox(color: args.value);
widget remote = SizedBox(child: args.corn.0);
widget root = remote(
corn: [
...for v in data.list:
verify(value: switch v.c.0 {
0: 0xFF000000,
0xDD: 0xFF0D0D0D,
default: v,
}),
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF0D0D0D));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget verify { state: true } = switch args.value.c.0 {
0xDD: ColoredBox(color: 0xFF0D0D0D),
default: ColoredBox(color: args.value),
};
widget remote = SizedBox(child: args.corn.0);
widget root = remote(
corn: [
...for v in data.list:
verify(value: v),
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF0D0D0D));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget verify { state: true } = GestureDetector(
onTap: event 'test' { test: args.value.a.b },
child: ColoredBox(),
);
widget remote = SizedBox(child: args.corn.0);
widget root = remote(
corn: [
...for v in data.list:
verify(value: v),
],
);
'''));
expect(eventLog, isEmpty);
await tester.pump();
await tester.tap(find.byType(ColoredBox));
expect(eventLog, <String>['test {test: ${0xEE}}']);
eventLog.clear();
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget verify { state: 0x00 } = GestureDetector(
onTap: set state.state = args.value.a.b,
child: ColoredBox(color: switch state.state {
0x00: 0xFF000001,
0xEE: 0xFF000002,
}),
);
widget remote = SizedBox(child: args.corn.0);
widget root = remote(
corn: [
...for v in data.list:
verify(value: v),
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000001));
await tester.tap(find.byType(ColoredBox));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000002));
});
testWidgets('list lookup of esoteric values', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = test(list: ['A'], loop: [...for b in ["B", "C"]: b]);
widget test = Text(
textDirection: "ltr",
text: [
'>',
...for a in args.list: a,
...for b in args.loop: b,
'<',
],
);
'''));
await tester.pump();
expect(find.text('>ABC<'), findsOneWidget);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = Text(
textDirection: "ltr",
text: [
'>',
...for a in root(): a,
'<',
],
);
'''));
await tester.pump();
expect(find.text('><'), findsOneWidget);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = test(list: [test()]);
widget test = Text(
textDirection: "ltr",
text: [
'>',
...for a in args.list: a,
'<',
],
);
'''));
await tester.pump();
expect(find.text('><'), findsOneWidget);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { list: [ 0x01 ] } = GestureDetector(
onTap: set state.list = [ 0x02, 0x03 ],
child: Column(
children: [
...for v in state.list:
SizedBox(height: 10.0, width: 10.0, child: ColoredBox(color: v)),
],
),
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000001));
await tester.tap(find.byType(ColoredBox));
await tester.pump();
expect(tester.firstWidget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000002));
expect(find.byType(ColoredBox), findsNWidgets(2));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = Column(
children: [
...for v in switch 0 {
0: [ColoredBox(color: 0x00000001)],
default: [ColoredBox(color: 0xFFFF0000)],
}: v,
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000001));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = Column(
children: [
...for v in {
a: [ColoredBox(color: 0x00000001)],
b: [ColoredBox(color: 0xFFFF0000)],
}: v,
],
);
'''));
await tester.pump();
expect(find.byType(ColoredBox), findsNothing);
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = test(
list: [...for w in [ColoredBox(color: 0xFF00FF00)]: w],
);
widget test = Column(
children: [
...for v in args.list: v,
],
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF00FF00));
});
testWidgets('data lookup', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent(<String, Object?>{
'map': <String, Object?>{ 'list': <Object?>[ 0xAB ] },
});
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = test(list: data.map.list);
widget test = ColoredBox(color: args.list.0);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x000000AB));
});
testWidgets('args lookup', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = test1(map: { 'list': [ 0xAC ] });
widget test1 = test2(list: args.map.list);
widget test2 = ColoredBox(color: args.list.0);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x000000AC));
});
testWidgets('state lookup', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { map: { 'list': [ 0xAD ] } } = test(list: state.map.list);
widget test = ColoredBox(color: args.list.0);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x000000AD));
});
testWidgets('switch', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = ColoredBox(color: switch data.a.b {
0: 0x11111111,
default: 0x22222222,
});
'''));
data.update('a', parseDataFile('{ b: 1 }'));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x22222222));
data.update('a', parseDataFile('{ b: 0 }'));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x11111111));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = switch true {};
'''));
await tester.pump();
expect(tester.takeException().toString(), 'Switch in test:root did not resolve to a widget (got <missing>).');
});
testWidgets('events with arguments', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
final List<String> eventLog = <String>[];
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
onEvent: (String eventName, DynamicMap eventArguments) {
eventLog.add('$eventName $eventArguments');
},
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = GestureDetector(
onTap: event 'tap' {
list: [...for a in [0,1]: a],
},
child: ColoredBox(),
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000000));
expect(eventLog, isEmpty);
await tester.tap(find.byType(ColoredBox));
expect(eventLog, <String>['tap {list: [0, 1]}']);
eventLog.clear();
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root = GestureDetector(
onTap: [ event 'tap' { a: 1 }, event 'tap' { a: 2 }, event 'final tap' { } ],
child: ColoredBox(),
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000000));
expect(eventLog, isEmpty);
await tester.tap(find.byType(ColoredBox));
expect(eventLog, <String>['tap {a: 1}', 'tap {a: 2}', 'final tap {}']);
eventLog.clear();
});
testWidgets('_CurriedWidget toStrings', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget stateless = ColoredBox(color: 0xAA);
widget stateful { test: false } = ColoredBox(color: 0xBB);
widget switchy = switch true { default: ColoredBox(color: 0xCC) };
'''));
expect(
(runtime.build(
tester.element(find.byType(Container)),
const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'stateless'),
data,
(String eventName, DynamicMap eventArguments) {},
) as dynamic).curriedWidget.toString(),
'core:ColoredBox {} {color: 170}',
);
expect(
(runtime.build(
tester.element(find.byType(Container)),
const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'stateful'),
data,
(String eventName, DynamicMap eventArguments) {},
) as dynamic).curriedWidget.toString(),
'test:stateful {test: false} {} = core:ColoredBox {} {color: 187}',
);
expect(
(runtime.build(
tester.element(find.byType(Container)),
const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'switchy'),
data,
(String eventName, DynamicMap eventArguments) {},
) as dynamic).curriedWidget.toString(),
'test:switchy {} {} = switch true {null: core:ColoredBox {} {color: 204}}',
);
});
testWidgets('state setting', (WidgetTester tester) async {
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['core']), createCoreWidgets());
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['test']), 'root'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: 0 } = GestureDetector(
onTap: set state.b = 0,
child: ColoredBox(),
);
'''));
await tester.pump();
await tester.tap(find.byType(ColoredBox));
expect(tester.takeException().toString(), 'b does not identify existing state.');
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: 0 } = GestureDetector(
onTap: set state.0 = 0,
child: ColoredBox(),
);
'''));
await tester.pump();
await tester.tap(find.byType(ColoredBox));
expect(tester.takeException().toString(), '0 does not identify existing state.');
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: [] } = GestureDetector(
onTap: set state.a.b = 0,
child: ColoredBox(),
);
'''));
await tester.pump();
await tester.tap(find.byType(ColoredBox));
expect(tester.takeException().toString(), 'a.b does not identify existing state.');
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: [] } = GestureDetector(
onTap: set state.a.0 = 0,
child: ColoredBox(),
);
'''));
await tester.pump();
await tester.tap(find.byType(ColoredBox));
expect(tester.takeException().toString(), 'a.0 does not identify existing state.');
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: true } = GestureDetector(
onTap: set state.a.0 = 0,
child: ColoredBox(),
);
'''));
await tester.pump();
await tester.tap(find.byType(ColoredBox));
expect(tester.takeException().toString(), 'a.0 does not identify existing state.');
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: true } = GestureDetector(
onTap: set state.a.b = 0,
child: ColoredBox(),
);
'''));
await tester.pump();
await tester.tap(find.byType(ColoredBox));
expect(tester.takeException().toString(), 'a.b does not identify existing state.');
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: { b: 0 } } = GestureDetector(
onTap: set state.a = 15,
child: ColoredBox(color: state.a),
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000000));
await tester.tap(find.byType(ColoredBox));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x0000000F));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: [ 0 ] } = GestureDetector(
onTap: set state.a = 10,
child: ColoredBox(color: state.a),
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xFF000000));
await tester.tap(find.byType(ColoredBox));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x0000000A));
runtime.update(const LibraryName(<String>['test']), parseLibraryFile('''
import core;
widget root { a: [ [ 1 ] ] } = GestureDetector(
onTap: set state.a.0.0 = 11,
child: ColoredBox(color: state.a.0.0),
);
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x00000001));
await tester.tap(find.byType(ColoredBox));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0x0000000B));
});
testWidgets('DataSource', (WidgetTester tester) async {
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
final List<String> eventLog = <String>[];
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['remote']), 'test'),
onEvent: (String name, DynamicMap arguments) {
eventLog.add('$name $arguments');
},
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
runtime.update(const LibraryName(<String>['local']), LocalWidgetLibrary(<String, LocalWidgetBuilder>{
'Test': (BuildContext context, DataSource source) {
expect(source.isList(<Object>['a']), isFalse);
expect(source.isList(<Object>['b']), isTrue);
expect(source.length(<Object>['b']), 1);
expect(source.child(<Object>['missing']), isA<ErrorWidget>());
expect(tester.takeException().toString(), 'Not a widget at [missing] (got <missing>) for local:Test.');
expect(source.childList(<Object>['a']), <Matcher>[isA<ErrorWidget>()]);
expect(tester.takeException().toString(), 'Not a widget list at [a] (got 0) for local:Test.');
expect(source.childList(<Object>['b']), <Matcher>[isA<ErrorWidget>()]);
expect(tester.takeException().toString(), 'Not a widget at [b] (got 1) for local:Test.');
expect(eventLog, isEmpty);
source.voidHandler(<Object>['callback'], <String, Object?>{ 'extra': 4, 'b': 3 })!();
expect(eventLog, <String>['e {a: 1, b: 3, extra: 4}']);
return const ColoredBox(color: Color(0xAABBCCDD));
},
}));
runtime.update(const LibraryName(<String>['remote']), parseLibraryFile('''
import local;
widget test = Test(a: 0, b: [1], callback: event 'e' { a: 1, b: 2 });
'''));
await tester.pump();
expect(tester.widget<ColoredBox>(find.byType(ColoredBox)).color, const Color(0xAABBCCDD));
bool tested = false;
tester.element(find.byType(ColoredBox)).visitAncestorElements((Element node) {
expect(node.toString(), equalsIgnoringHashCodes('_Widget(state: _WidgetState#00000(name: "local:Test"))'));
tested = true;
return false;
});
expect(tested, isTrue);
});
testWidgets('DynamicContent subscriptions', (WidgetTester tester) async {
final List<String> log = <String>[];
final DynamicContent data = DynamicContent(<String, Object?>{
'a': <Object>[0, 1],
'b': <Object>['q', 'r'],
});
data.subscribe(<Object>[], (Object value) { log.add('root: $value'); });
data.subscribe(<Object>['a', 0], (Object value) { log.add('leaf: $value'); });
data.update('a', <Object>[2, 3]);
expect(log, <String>['leaf: 2', 'root: {a: [2, 3], b: [q, r]}']);
data.update('c', 'test');
expect(log, <String>['leaf: 2', 'root: {a: [2, 3], b: [q, r]}', 'root: {a: [2, 3], b: [q, r], c: test}']);
});
testWidgets('Data source - optional builder works', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'Builder': (BuildContext context, DataSource source) {
final Widget? builder = source.optionalBuilder(<String>['builder'], <String, Object?>{});
return builder ?? const Text('Hello World!', textDirection: TextDirection.ltr);
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test = Builder(
builder: Text(text: 'Not a builder :/'),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, 'Hello World!');
});
testWidgets('Data source - builder returns an error widget', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
const String expectedErrorMessage = 'Not a builder at [builder] (got core:Text {} {text: Not a builder :/}) for local:Builder.';
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'Builder': (BuildContext context, DataSource source) {
return source.builder(<String>['builder'], <String, Object?>{});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test = Builder(
builder: Text(text: 'Not a builder :/'),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(tester.takeException().toString(), contains(expectedErrorMessage));
expect(find.byType(ErrorWidget), findsOneWidget);
expect(tester.widget<ErrorWidget>(find.byType(ErrorWidget)).message, contains(expectedErrorMessage));
});
testWidgets('Customized error widget', (WidgetTester tester) async {
final ErrorWidgetBuilder oldBuilder = ErrorWidget.builder;
ErrorWidget.builder = (FlutterErrorDetails details) {
return const Text('oopsie!', textDirection: TextDirection.ltr);
};
final Runtime runtime = Runtime()
..update(const LibraryName(<String>['a']), parseLibraryFile(''));
final DynamicContent data = DynamicContent();
await tester.pumpWidget(
RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(LibraryName(<String>['a']), 'widget'),
),
);
expect(tester.takeException().toString(), contains('Could not find remote widget named'));
expect(find.text('oopsie!'), findsOneWidget);
expect(find.byType(ErrorWidget), findsNothing);
ErrorWidget.builder = oldBuilder;
});
testWidgets('Widget builders - work when scope is not used', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'Builder': (BuildContext context, DataSource source) {
return source.builder(<String>['builder'], <String, Object?>{});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test = Builder(
builder: (scope) => Text(text: 'Hello World!', textDirection: 'ltr'),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, 'Hello World!');
});
testWidgets('Widget builders - work when scope is used', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'HelloWorld': (BuildContext context, DataSource source) {
const String result = 'Hello World!';
return source.builder(<String>['builder'], <String, Object?>{'result': result});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test = HelloWorld(
builder: (result) => Text(text: result.result, textDirection: 'ltr'),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, 'Hello World!');
});
testWidgets('Widget builders - work with state', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'IntToString': (BuildContext context, DataSource source) {
final int value = source.v<int>(<String>['value'])!;
final String result = value.toString();
return source.builder(<String>['builder'], <String, Object?>{'result': result});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test {value: 0} = IntToString(
value: state.value,
builder: (result) => Text(text: result.result, textDirection: 'ltr'),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, '0');
});
testWidgets('Widget builders - work with data', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent(<String, Object>{'value': 0});
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'IntToString': (BuildContext context, DataSource source) {
final int value = source.v<int>(<String>['value'])!;
final String result = value.toString();
return source.builder(<String>['builder'], <String, Object?>{'result': result});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test = IntToString(
value: data.value,
builder: (result) => Text(text: result.result, textDirection: 'ltr'),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, '0');
data.update('value', 1);
await tester.pump();
expect(tester.widget<Text>(textFinder).data, '1');
});
testWidgets('Widget builders - work with events', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
final List<RfwEvent> dispatchedEvents = <RfwEvent>[];
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'Zero': (BuildContext context, DataSource source) {
return source.builder(<String>['builder'], <String, Object?>{'result': 0});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test = Zero(
builder: (result) => GestureDetector(
onTap: event 'works' {number: result.result},
child: Text(text: 'Tap to trigger an event.', textDirection: 'ltr'),
),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
onEvent: (String eventName, DynamicMap eventArguments) =>
dispatchedEvents.add(RfwEvent(eventName, eventArguments)),
));
await tester.tap(textFinder);
await tester.pump();
expect(dispatchedEvents, hasLength(1));
expect(dispatchedEvents.single.name, 'works');
expect(dispatchedEvents.single.arguments['number'], 0);
});
testWidgets('Widget builders - works nested', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'Sum': (BuildContext context, DataSource source) {
final int operand1 = source.v<int>(<String>['operand1'])!;
final int operand2 = source.v<int>(<String>['operand2'])!;
final int result = operand1 + operand2;
return source.builder(<String>['builder'], <String, Object?>{'result': result});
},
'IntToString': (BuildContext context, DataSource source) {
final int value = source.v<int>(<String>['value'])!;
final String result = value.toString();
return source.builder(<String>['builder'], <String, Object?>{'result': result});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test = Sum(
operand1: 1,
operand2: 2,
builder: (result1) => IntToString(
value: result1.result,
builder: (result2) => Text(text: ['1 + 2 = ', result2.result], textDirection: 'ltr'),
),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, '1 + 2 = 3');
});
testWidgets('Widget builders - works nested dynamically', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Map<String, VoidCallback> handlers = <String, VoidCallback>{};
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent(<String, Object?>{
'a1': 'apricot',
'b1': 'blueberry',
});
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'Builder': (BuildContext context, DataSource source) {
final String? id = source.v<String>(<String>['id']);
if (id != null) {
handlers[id] = source.voidHandler(<String>['handler'])!;
}
return source.builder(<String>['builder'], <String, Object?>{
'param1': source.v<String>(<String>['arg1']),
'param2': source.v<String>(<String>['arg2']),
});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test { state1: 'strawberry' } = Builder(
arg1: data.a1,
arg2: 'apple',
id: 'A',
handler: set state.state1 = 'STRAWBERRY',
builder: (builder1) => Builder(
arg1: data.b1,
arg2: 'banana',
builder: (builder2) => Text(
textDirection: 'ltr',
text: [
state.state1, ' ', builder1.param1, ' ', builder1.param2, ' ', builder2.param1, ' ', builder2.param2,
],
),
),
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(tester.widget<Text>(textFinder).data, 'strawberry apricot apple blueberry banana');
data.update('a1', 'APRICOT');
await tester.pump();
expect(tester.widget<Text>(textFinder).data, 'strawberry APRICOT apple blueberry banana');
data.update('b1', 'BLUEBERRY');
await tester.pump();
expect(tester.widget<Text>(textFinder).data, 'strawberry APRICOT apple BLUEBERRY banana');
handlers['A']!();
await tester.pump();
expect(tester.widget<Text>(textFinder).data, 'STRAWBERRY APRICOT apple BLUEBERRY banana');
});
testWidgets('Widget builders - switch works with builder', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'Builder': (BuildContext context, DataSource source) {
return source.builder(<String>['builder'], <String, Object?>{});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test {enabled: false} = Builder(
value: state.value,
builder: switch state.enabled {
true: (scope) => GestureDetector(
onTap: set state.enabled = false,
child: Text(text: 'The builder is enabled.', textDirection: 'ltr'),
),
false: (scope) => GestureDetector(
onTap: set state.enabled = true,
child: Text(text: 'The builder is disabled.', textDirection: 'ltr'),
),
},
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, 'The builder is disabled.');
await tester.tap(textFinder);
await tester.pump();
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, 'The builder is enabled.');
});
testWidgets('Widget builders - builder works with switch', (WidgetTester tester) async {
const LibraryName coreLibraryName = LibraryName(<String>['core']);
const LibraryName localLibraryName = LibraryName(<String>['local']);
const LibraryName remoteLibraryName = LibraryName(<String>['remote']);
final Runtime runtime = Runtime();
final DynamicContent data = DynamicContent();
final Finder textFinder = find.byType(Text);
runtime.update(coreLibraryName, createCoreWidgets());
runtime.update(localLibraryName, LocalWidgetLibrary(<String, LocalWidgetBuilder> {
'Inverter': (BuildContext context, DataSource source) {
final bool value = source.v<bool>(<String>['value'])!;
return source.builder(<String>['builder'], <String, Object?>{'result': !value});
},
}));
runtime.update(remoteLibraryName, parseLibraryFile('''
import core;
import local;
widget test {value: false} = Inverter(
value: state.value,
builder: (result) => switch result.result {
true: GestureDetector(
onTap: set state.value = switch state.value {
true: false,
false: true,
},
child: Text(text: 'The input is false, the output is true', textDirection: 'ltr'),
),
false: GestureDetector(
onTap: set state.value = switch state.value {
true: false,
false: true,
},
child: Text(text: 'The input is true, the output is false', textDirection: 'ltr'),
),
},
);
'''));
await tester.pumpWidget(RemoteWidget(
runtime: runtime,
data: data,
widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'),
));
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, 'The input is false, the output is true');
await tester.tap(textFinder);
await tester.pump();
expect(textFinder, findsOneWidget);
expect(tester.widget<Text>(textFinder).data, 'The input is true, the output is false');
});
}
final class RfwEvent {
RfwEvent(this.name, this.arguments);
final String name;
final DynamicMap arguments;
}
| packages/packages/rfw/test/runtime_test.dart/0 | {
"file_path": "packages/packages/rfw/test/runtime_test.dart",
"repo_id": "packages",
"token_count": 23025
} | 1,084 |
// 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, unused_local_variable, invalid_use_of_visible_for_testing_member
import 'package:shared_preferences/shared_preferences.dart';
Future<void> readmeSnippets() async {
// #docregion Write
// Obtain shared preferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();
// Save an integer value to 'counter' key.
await prefs.setInt('counter', 10);
// Save an boolean value to 'repeat' key.
await prefs.setBool('repeat', true);
// Save an double value to 'decimal' key.
await prefs.setDouble('decimal', 1.5);
// Save an String value to 'action' key.
await prefs.setString('action', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
// #enddocregion Write
// #docregion Read
// Try reading data from the 'counter' key. If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter');
// Try reading data from the 'repeat' key. If it doesn't exist, returns null.
final bool? repeat = prefs.getBool('repeat');
// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
final double? decimal = prefs.getDouble('decimal');
// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');
// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');
// #enddocregion Read
// #docregion Clear
// Remove data for the 'counter' key.
await prefs.remove('counter');
// #enddocregion Clear
}
// Uses test-only code. invalid_use_of_visible_for_testing_member is suppressed
// for the whole file since otherwise there's no way to avoid it showing up in
// the excerpt, and that is definitely not something people should be copying
// from examples.
Future<void> readmeTestSnippets() async {
// #docregion Tests
final Map<String, Object> values = <String, Object>{'counter': 1};
SharedPreferences.setMockInitialValues(values);
// #enddocregion Tests
}
| packages/packages/shared_preferences/shared_preferences/example/lib/readme_excerpts.dart/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences/example/lib/readme_excerpts.dart",
"repo_id": "packages",
"token_count": 675
} | 1,085 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/shared_preferences/shared_preferences_android/example/android/gradle.properties/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_android/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 30
} | 1,086 |
// 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:web/web.dart' as html;
/// An extension on [html.Storage] that adds a convenience [keys] getter.
extension KeysExtension on html.Storage {
/// Gets all the [keys] set in this [html.Storage].
List<String> get keys {
return <String>[for (int i = 0; i < length; i++) key(i)!];
}
}
| packages/packages/shared_preferences/shared_preferences_web/lib/src/keys_extension.dart/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_web/lib/src/keys_extension.dart",
"repo_id": "packages",
"token_count": 146
} | 1,087 |
// 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 'src/serialization.dart';
export 'src/serialization.dart' show ReadBuffer, WriteBuffer;
const int _writeBufferStartCapacity = 64;
/// A message encoding/decoding mechanism.
///
/// Both operations throw an exception, if conversion fails. Such situations
/// should be treated as programming errors.
///
/// See also:
///
/// * [BasicMessageChannel], which use [MessageCodec]s for communication
/// between Flutter and platform plugins.
abstract class MessageCodec<T> {
/// Encodes the specified [message] in binary.
///
/// Returns null if the message is null.
ByteData? encodeMessage(T message);
/// Decodes the specified [message] from binary.
///
/// Returns null if the message is null.
T? decodeMessage(ByteData? message);
}
/// [MessageCodec] using the Flutter standard binary encoding.
///
/// Supported messages are acyclic values of these forms:
///
/// * null
/// * [bool]s
/// * [num]s
/// * [String]s
/// * [Uint8List]s, [Int32List]s, [Int64List]s, [Float64List]s
/// * [List]s of supported values
/// * [Map]s from supported values to supported values
///
/// Decoded values will use `List<Object?>` and `Map<Object?, Object?>`
/// irrespective of content.
///
/// The type returned from [decodeMessage] is `dynamic` (not `Object?`), which
/// means *no type checking is performed on its return value*. It is strongly
/// recommended that the return value be immediately cast to a known type to
/// prevent runtime errors due to typos that the type checker could otherwise
/// catch.
///
/// The codec is extensible by subclasses overriding [writeValue] and
/// [readValueOfType].
///
/// ## Android specifics
///
/// On Android, messages are represented as follows:
///
/// * null: null
/// * [bool]\: `java.lang.Boolean`
/// * [int]\: `java.lang.Integer` for values that are representable using 32-bit
/// two's complement; `java.lang.Long` otherwise
/// * [double]\: `java.lang.Double`
/// * [String]\: `java.lang.String`
/// * [Uint8List]\: `byte[]`
/// * [Int32List]\: `int[]`
/// * [Int64List]\: `long[]`
/// * [Float64List]\: `double[]`
/// * [List]\: `java.util.ArrayList`
/// * [Map]\: `java.util.HashMap`
///
/// When sending a `java.math.BigInteger` from Java, it is converted into a
/// [String] with the hexadecimal representation of the integer. (The value is
/// tagged as being a big integer; subclasses of this class could be made to
/// support it natively; see the discussion at [writeValue].) This codec does
/// not support sending big integers from Dart.
///
/// ## iOS specifics
///
/// On iOS, messages are represented as follows:
///
/// * null: nil
/// * [bool]\: `NSNumber numberWithBool:`
/// * [int]\: `NSNumber numberWithInt:` for values that are representable using
/// 32-bit two's complement; `NSNumber numberWithLong:` otherwise
/// * [double]\: `NSNumber numberWithDouble:`
/// * [String]\: `NSString`
/// * [Uint8List], [Int32List], [Int64List], [Float64List]\:
/// `FlutterStandardTypedData`
/// * [List]\: `NSArray`
/// * [Map]\: `NSDictionary`
class StandardMessageCodec implements MessageCodec<Object?> {
/// Creates a [MessageCodec] using the Flutter standard binary encoding.
const StandardMessageCodec();
// The codec serializes messages as outlined below. This format must match the
// Android and iOS counterparts and cannot change (as it's possible for
// someone to end up using this for persistent storage).
//
// * A single byte with one of the constant values below determines the
// type of the value.
// * The serialization of the value itself follows the type byte.
// * Numbers are represented using the host endianness throughout.
// * Lengths and sizes of serialized parts are encoded using an expanding
// format optimized for the common case of small non-negative integers:
// * values 0..253 inclusive using one byte with that value;
// * values 254..2^16 inclusive using three bytes, the first of which is
// 254, the next two the usual unsigned representation of the value;
// * values 2^16+1..2^32 inclusive using five bytes, the first of which is
// 255, the next four the usual unsigned representation of the value.
// * null, true, and false have empty serialization; they are encoded directly
// in the type byte (using _valueNull, _valueTrue, _valueFalse)
// * Integers representable in 32 bits are encoded using 4 bytes two's
// complement representation.
// * Larger integers are encoded using 8 bytes two's complement
// representation.
// * doubles are encoded using the IEEE 754 64-bit double-precision binary
// format. Zero bytes are added before the encoded double value to align it
// to a 64 bit boundary in the full message.
// * Strings are encoded using their UTF-8 representation. First the length
// of that in bytes is encoded using the expanding format, then follows the
// UTF-8 encoding itself.
// * Uint8Lists, Int32Lists, Int64Lists, Float32Lists, and Float64Lists are
// encoded by first encoding the list's element count in the expanding
// format, then the smallest number of zero bytes needed to align the
// position in the full message with a multiple of the number of bytes per
// element, then the encoding of the list elements themselves, end-to-end
// with no additional type information, using two's complement or IEEE 754
// as applicable.
// * Lists are encoded by first encoding their length in the expanding format,
// then follows the recursive encoding of each element value, including the
// type byte (Lists are assumed to be heterogeneous).
// * Maps are encoded by first encoding their length in the expanding format,
// then follows the recursive encoding of each key/value pair, including the
// type byte for both (Maps are assumed to be heterogeneous).
//
// The type labels below must not change, since it's possible for this interface
// to be used for persistent storage.
static const int _valueNull = 0;
static const int _valueTrue = 1;
static const int _valueFalse = 2;
static const int _valueInt32 = 3;
static const int _valueInt64 = 4;
static const int _valueLargeInt = 5;
static const int _valueFloat64 = 6;
static const int _valueString = 7;
static const int _valueUint8List = 8;
static const int _valueInt32List = 9;
static const int _valueInt64List = 10;
static const int _valueFloat64List = 11;
static const int _valueList = 12;
static const int _valueMap = 13;
static const int _valueFloat32List = 14;
@override
ByteData? encodeMessage(Object? message) {
if (message == null) {
return null;
}
final WriteBuffer buffer =
WriteBuffer(startCapacity: _writeBufferStartCapacity);
writeValue(buffer, message);
return buffer.done();
}
@override
dynamic decodeMessage(ByteData? message) {
if (message == null) {
return null;
}
final ReadBuffer buffer = ReadBuffer(message);
final Object? result = readValue(buffer);
if (buffer.hasRemaining) {
throw const FormatException('Message corrupted');
}
return result;
}
/// Writes [value] to [buffer] by first writing a type discriminator
/// byte, then the value itself.
///
/// This method may be called recursively to serialize container values.
///
/// Type discriminators 0 through 127 inclusive are reserved for use by the
/// base class, as follows:
///
/// * null = 0
/// * true = 1
/// * false = 2
/// * 32 bit integer = 3
/// * 64 bit integer = 4
/// * larger integers = 5 (see below)
/// * 64 bit floating-point number = 6
/// * String = 7
/// * Uint8List = 8
/// * Int32List = 9
/// * Int64List = 10
/// * Float64List = 11
/// * List = 12
/// * Map = 13
/// * Float32List = 14
/// * Reserved for future expansion: 15..127
///
/// The codec can be extended by overriding this method, calling super
/// for values that the extension does not handle. Type discriminators
/// used by extensions must be greater than or equal to 128 in order to avoid
/// clashes with any later extensions to the base class.
///
/// The "larger integers" type, 5, is never used by [writeValue]. A subclass
/// could represent big integers from another package using that type. The
/// format is first the type byte (0x05), then the actual number as an ASCII
/// string giving the hexadecimal representation of the integer, with the
/// string's length as encoded by [writeSize] followed by the string bytes. On
/// Android, that would get converted to a `java.math.BigInteger` object. On
/// iOS, the string representation is returned.
void writeValue(WriteBuffer buffer, Object? value) {
if (value == null) {
buffer.putUint8(_valueNull);
} else if (value is bool) {
buffer.putUint8(value ? _valueTrue : _valueFalse);
} else if (value is double) {
// Double precedes int because in JS everything is a double.
// Therefore in JS, both `is int` and `is double` always
// return `true`. If we check int first, we'll end up treating
// all numbers as ints and attempt the int32/int64 conversion,
// which is wrong. This precedence rule is irrelevant when
// decoding because we use tags to detect the type of value.
buffer.putUint8(_valueFloat64);
buffer.putFloat64(value);
// ignore: avoid_double_and_int_checks, JS code always goes through the `double` path above
} else if (value is int) {
if (-0x7fffffff - 1 <= value && value <= 0x7fffffff) {
buffer.putUint8(_valueInt32);
buffer.putInt32(value);
} else {
buffer.putUint8(_valueInt64);
buffer.putInt64(value);
}
} else if (value is String) {
buffer.putUint8(_valueString);
final Uint8List asciiBytes = Uint8List(value.length);
Uint8List? utf8Bytes;
int utf8Offset = 0;
// Only do utf8 encoding if we encounter non-ascii characters.
for (int i = 0; i < value.length; i += 1) {
final int char = value.codeUnitAt(i);
if (char <= 0x7f) {
asciiBytes[i] = char;
} else {
utf8Bytes = utf8.encoder.convert(value.substring(i));
utf8Offset = i;
break;
}
}
if (utf8Bytes != null) {
writeSize(buffer, utf8Offset + utf8Bytes.length);
buffer.putUint8List(Uint8List.sublistView(asciiBytes, 0, utf8Offset));
buffer.putUint8List(utf8Bytes);
} else {
writeSize(buffer, asciiBytes.length);
buffer.putUint8List(asciiBytes);
}
} else if (value is Uint8List) {
buffer.putUint8(_valueUint8List);
writeSize(buffer, value.length);
buffer.putUint8List(value);
} else if (value is Int32List) {
buffer.putUint8(_valueInt32List);
writeSize(buffer, value.length);
buffer.putInt32List(value);
} else if (value is Int64List) {
buffer.putUint8(_valueInt64List);
writeSize(buffer, value.length);
buffer.putInt64List(value);
} else if (value is Float32List) {
buffer.putUint8(_valueFloat32List);
writeSize(buffer, value.length);
buffer.putFloat32List(value);
} else if (value is Float64List) {
buffer.putUint8(_valueFloat64List);
writeSize(buffer, value.length);
buffer.putFloat64List(value);
} else if (value is List) {
buffer.putUint8(_valueList);
writeSize(buffer, value.length);
for (final Object? item in value) {
writeValue(buffer, item);
}
} else if (value is Map) {
buffer.putUint8(_valueMap);
writeSize(buffer, value.length);
value.forEach((Object? key, Object? value) {
writeValue(buffer, key);
writeValue(buffer, value);
});
} else {
throw ArgumentError.value(value);
}
}
/// Reads a value from [buffer] as written by [writeValue].
///
/// This method is intended for use by subclasses overriding
/// [readValueOfType].
Object? readValue(ReadBuffer buffer) {
if (!buffer.hasRemaining) {
throw const FormatException('Message corrupted');
}
final int type = buffer.getUint8();
return readValueOfType(type, buffer);
}
/// Reads a value of the indicated [type] from [buffer].
///
/// The codec can be extended by overriding this method, calling super for
/// types that the extension does not handle. See the discussion at
/// [writeValue].
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case _valueNull:
return null;
case _valueTrue:
return true;
case _valueFalse:
return false;
case _valueInt32:
return buffer.getInt32();
case _valueInt64:
return buffer.getInt64();
case _valueFloat64:
return buffer.getFloat64();
case _valueLargeInt:
case _valueString:
final int length = readSize(buffer);
return utf8.decoder.convert(buffer.getUint8List(length));
case _valueUint8List:
final int length = readSize(buffer);
return buffer.getUint8List(length);
case _valueInt32List:
final int length = readSize(buffer);
return buffer.getInt32List(length);
case _valueInt64List:
final int length = readSize(buffer);
return buffer.getInt64List(length);
case _valueFloat32List:
final int length = readSize(buffer);
return buffer.getFloat32List(length);
case _valueFloat64List:
final int length = readSize(buffer);
return buffer.getFloat64List(length);
case _valueList:
final int length = readSize(buffer);
final List<Object?> result = List<Object?>.filled(length, null);
for (int i = 0; i < length; i++) {
result[i] = readValue(buffer);
}
return result;
case _valueMap:
final int length = readSize(buffer);
final Map<Object?, Object?> result = <Object?, Object?>{};
for (int i = 0; i < length; i++) {
result[readValue(buffer)] = readValue(buffer);
}
return result;
default:
throw const FormatException('Message corrupted');
}
}
/// Writes a non-negative 32-bit integer [value] to [buffer]
/// using an expanding 1-5 byte encoding that optimizes for small values.
///
/// This method is intended for use by subclasses overriding
/// [writeValue].
void writeSize(WriteBuffer buffer, int value) {
assert(0 <= value && value <= 0xffffffff);
if (value < 254) {
buffer.putUint8(value);
} else if (value <= 0xffff) {
buffer.putUint8(254);
buffer.putUint16(value);
} else {
buffer.putUint8(255);
buffer.putUint32(value);
}
}
/// Reads a non-negative int from [buffer] as written by [writeSize].
///
/// This method is intended for use by subclasses overriding
/// [readValueOfType].
int readSize(ReadBuffer buffer) {
final int value = buffer.getUint8();
switch (value) {
case 254:
return buffer.getUint16();
case 255:
return buffer.getUint32();
default:
return value;
}
}
}
| packages/packages/standard_message_codec/lib/standard_message_codec.dart/0 | {
"file_path": "packages/packages/standard_message_codec/lib/standard_message_codec.dart",
"repo_id": "packages",
"token_count": 5242
} | 1,088 |
#include "ephemeral/Flutter-Generated.xcconfig"
| packages/packages/two_dimensional_scrollables/example/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "packages/packages/two_dimensional_scrollables/example/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "packages",
"token_count": 19
} | 1,089 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/url_launcher/url_launcher/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/url_launcher/url_launcher/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 1,090 |
rootProject.name = 'url_launcher_android'
| packages/packages/url_launcher/url_launcher_android/android/settings.gradle/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_android/android/settings.gradle",
"repo_id": "packages",
"token_count": 14
} | 1,091 |
name: url_launcher_android
description: Android implementation of the url_launcher plugin.
repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
version: 6.3.0
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: url_launcher
platforms:
android:
package: io.flutter.plugins.urllauncher
pluginClass: UrlLauncherPlugin
dartPluginClass: UrlLauncherAndroid
dependencies:
flutter:
sdk: flutter
url_launcher_platform_interface: ^2.3.1
dev_dependencies:
flutter_test:
sdk: flutter
mockito: 5.4.4
pigeon: ^10.0.0
plugin_platform_interface: ^2.1.7
test: ^1.16.3
topics:
- links
- os-integration
- url-launcher
- urls
| packages/packages/url_launcher/url_launcher_android/pubspec.yaml/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_android/pubspec.yaml",
"repo_id": "packages",
"token_count": 360
} | 1,092 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Flutter
import UIKit
public final class URLLauncherPlugin: NSObject, FlutterPlugin, UrlLauncherApi {
public static func register(with registrar: FlutterPluginRegistrar) {
let plugin = URLLauncherPlugin()
UrlLauncherApiSetup.setUp(binaryMessenger: registrar.messenger(), api: plugin)
registrar.publish(plugin)
}
private var currentSession: URLLaunchSession?
private let launcher: Launcher
private var topViewController: UIViewController? {
// TODO(stuartmorgan) Provide a non-deprecated codepath. See
// https://github.com/flutter/flutter/issues/104117
UIApplication.shared.keyWindow?.rootViewController?.topViewController
}
init(launcher: Launcher = UIApplication.shared) {
self.launcher = launcher
}
func canLaunchUrl(url: String) -> LaunchResult {
guard let url = URL(string: url) else {
return .invalidUrl
}
let canOpen = launcher.canOpenURL(url)
return canOpen ? .success : .failure
}
func launchUrl(
url: String,
universalLinksOnly: Bool,
completion: @escaping (Result<LaunchResult, Error>) -> Void
) {
guard let url = URL(string: url) else {
completion(.success(.invalidUrl))
return
}
let options = [UIApplication.OpenExternalURLOptionsKey.universalLinksOnly: universalLinksOnly]
launcher.open(url, options: options) { result in
completion(.success(result ? .success : .failure))
}
}
func openUrlInSafariViewController(
url: String,
completion: @escaping (Result<InAppLoadResult, Error>) -> Void
) {
guard let url = URL(string: url) else {
completion(.success(.invalidUrl))
return
}
let session = URLLaunchSession(url: url, completion: completion)
currentSession = session
session.didFinish = { [weak self] in
self?.currentSession = nil
}
topViewController?.present(session.safariViewController, animated: true, completion: nil)
}
func closeSafariViewController() {
currentSession?.close()
}
}
/// This method recursively iterates through the view hierarchy
/// to return the top-most view controller.
///
/// It supports the following scenarios:
///
/// - The view controller is presenting another view.
/// - The view controller is a UINavigationController.
/// - The view controller is a UITabBarController.
///
/// @return The top most view controller.
extension UIViewController {
var topViewController: UIViewController {
if let navigationController = self as? UINavigationController {
return navigationController.viewControllers.last?.topViewController
?? navigationController
.visibleViewController ?? navigationController
}
if let tabBarController = self as? UITabBarController {
return tabBarController.selectedViewController?.topViewController ?? tabBarController
}
if let presented = presentedViewController {
return presented.topViewController
}
return self
}
}
| packages/packages/url_launcher/url_launcher_ios/ios/Classes/URLLauncherPlugin.swift/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_ios/ios/Classes/URLLauncherPlugin.swift",
"repo_id": "packages",
"token_count": 998
} | 1,093 |
# url\_launcher\_linux
The Linux implementation of [`url_launcher`][1].
## Usage
This package is [endorsed][2], which means you can simply use `url_launcher`
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your `pubspec.yaml`.
However, if you `import` this package to use any of its APIs directly, you
should add it to your `pubspec.yaml` as usual.
[1]: https://pub.dev/packages/url_launcher
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
| packages/packages/url_launcher/url_launcher_linux/README.md/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_linux/README.md",
"repo_id": "packages",
"token_count": 177
} | 1,094 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/url_launcher/url_launcher_macos/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_macos/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,095 |
// 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:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:url_launcher_platform_interface/link.dart';
void main() {
testWidgets('Link with Navigator', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: const Placeholder(key: Key('home')),
routes: <String, WidgetBuilder>{
'/a': (BuildContext context) => const Placeholder(key: Key('a')),
},
));
expect(find.byKey(const Key('home')), findsOneWidget);
expect(find.byKey(const Key('a')), findsNothing);
await tester.runAsync(() => pushRouteNameToFramework(null, '/a'));
// start animation
await tester.pump();
// skip past animation (5s is arbitrary, just needs to be long enough)
await tester.pump(const Duration(seconds: 5));
expect(find.byKey(const Key('a')), findsOneWidget);
expect(find.byKey(const Key('home')), findsNothing);
});
testWidgets('Link with Navigator', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp.router(
routeInformationParser: _RouteInformationParser(),
routerDelegate: _RouteDelegate(),
));
expect(find.byKey(const Key('/')), findsOneWidget);
expect(find.byKey(const Key('/a')), findsNothing);
await tester.runAsync(() => pushRouteNameToFramework(null, '/a'));
// start animation
await tester.pump();
// skip past animation (5s is arbitrary, just needs to be long enough)
await tester.pump(const Duration(seconds: 5));
expect(find.byKey(const Key('/a')), findsOneWidget);
expect(find.byKey(const Key('/')), findsNothing);
});
}
class _RouteInformationParser extends RouteInformationParser<RouteInformation> {
@override
Future<RouteInformation> parseRouteInformation(
RouteInformation routeInformation) {
return SynchronousFuture<RouteInformation>(routeInformation);
}
@override
RouteInformation? restoreRouteInformation(RouteInformation configuration) {
return configuration;
}
}
class _RouteDelegate extends RouterDelegate<RouteInformation>
with ChangeNotifier {
final Queue<RouteInformation> _history = Queue<RouteInformation>();
@override
Future<void> setNewRoutePath(RouteInformation configuration) {
_history.add(configuration);
return SynchronousFuture<void>(null);
}
@override
Future<bool> popRoute() {
if (_history.isEmpty) {
return SynchronousFuture<bool>(false);
}
_history.removeLast();
return SynchronousFuture<bool>(true);
}
@override
Widget build(BuildContext context) {
if (_history.isEmpty) {
return const Placeholder(key: Key('empty'));
}
return Placeholder(key: Key(_history.last.uri.path));
}
}
| packages/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart",
"repo_id": "packages",
"token_count": 984
} | 1,096 |
name: url_launcher_web
description: Web platform implementation of url_launcher
repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
version: 2.3.0
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
flutter:
plugin:
implements: url_launcher
platforms:
web:
pluginClass: UrlLauncherPlugin
fileName: url_launcher_web.dart
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
url_launcher_platform_interface: ^2.2.0
web: ^0.5.0
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- links
- os-integration
- url-launcher
- urls
| packages/packages/url_launcher/url_launcher_web/pubspec.yaml/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_web/pubspec.yaml",
"repo_id": "packages",
"token_count": 325
} | 1,097 |
// 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 "url_launcher_plugin.h"
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <windows.h>
#include <memory>
#include <optional>
#include <sstream>
#include <string>
#include "messages.g.h"
namespace url_launcher_windows {
namespace {
using flutter::EncodableMap;
using flutter::EncodableValue;
// Converts the given UTF-8 string to UTF-16.
std::wstring Utf16FromUtf8(const std::string& utf8_string) {
if (utf8_string.empty()) {
return std::wstring();
}
int target_length =
::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(),
static_cast<int>(utf8_string.length()), nullptr, 0);
if (target_length == 0) {
return std::wstring();
}
std::wstring utf16_string;
utf16_string.resize(target_length);
int converted_length =
::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8_string.data(),
static_cast<int>(utf8_string.length()),
utf16_string.data(), target_length);
if (converted_length == 0) {
return std::wstring();
}
return utf16_string;
}
// Returns the URL argument from |method_call| if it is present, otherwise
// returns an empty string.
std::string GetUrlArgument(const flutter::MethodCall<>& method_call) {
std::string url;
const auto* arguments = std::get_if<EncodableMap>(method_call.arguments());
if (arguments) {
auto url_it = arguments->find(EncodableValue("url"));
if (url_it != arguments->end()) {
url = std::get<std::string>(url_it->second);
}
}
return url;
}
} // namespace
// static
void UrlLauncherPlugin::RegisterWithRegistrar(
flutter::PluginRegistrar* registrar) {
std::unique_ptr<UrlLauncherPlugin> plugin =
std::make_unique<UrlLauncherPlugin>();
UrlLauncherApi::SetUp(registrar->messenger(), plugin.get());
registrar->AddPlugin(std::move(plugin));
}
UrlLauncherPlugin::UrlLauncherPlugin()
: system_apis_(std::make_unique<SystemApisImpl>()) {}
UrlLauncherPlugin::UrlLauncherPlugin(std::unique_ptr<SystemApis> system_apis)
: system_apis_(std::move(system_apis)) {}
UrlLauncherPlugin::~UrlLauncherPlugin() = default;
ErrorOr<bool> UrlLauncherPlugin::CanLaunchUrl(const std::string& url) {
size_t separator_location = url.find(":");
if (separator_location == std::string::npos) {
return false;
}
std::wstring scheme = Utf16FromUtf8(url.substr(0, separator_location));
HKEY key = nullptr;
if (system_apis_->RegOpenKeyExW(HKEY_CLASSES_ROOT, scheme.c_str(), 0,
KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
return false;
}
bool has_handler =
system_apis_->RegQueryValueExW(key, L"URL Protocol", nullptr, nullptr,
nullptr) == ERROR_SUCCESS;
system_apis_->RegCloseKey(key);
return has_handler;
}
ErrorOr<bool> UrlLauncherPlugin::LaunchUrl(const std::string& url) {
std::wstring url_wide = Utf16FromUtf8(url);
int status = static_cast<int>(reinterpret_cast<INT_PTR>(
system_apis_->ShellExecuteW(nullptr, TEXT("open"), url_wide.c_str(),
nullptr, nullptr, SW_SHOWNORMAL)));
// Per ::ShellExecuteW documentation, anything >32 indicates success.
if (status <= 32) {
if (status == SE_ERR_NOASSOC) {
// NOASSOC just means there's nothing registered to handle launching;
// return false rather than an error for better consistency with other
// platforms.
return false;
}
std::ostringstream error_message;
error_message << "Failed to open " << url << ": ShellExecute error code "
<< status;
return FlutterError("open_error", error_message.str());
}
return true;
}
} // namespace url_launcher_windows
| packages/packages/url_launcher/url_launcher_windows/windows/url_launcher_plugin.cpp/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_windows/windows/url_launcher_plugin.cpp",
"repo_id": "packages",
"token_count": 1586
} | 1,098 |
1
00:00:00,200 --> 00:00:01,750
[ Birds chirping ]
2
00:00:02,300 --> 00:00:05,000
[ Buzzing ]
| packages/packages/video_player/video_player/example/assets/bumble_bee_captions.srt/0 | {
"file_path": "packages/packages/video_player/video_player/example/assets/bumble_bee_captions.srt",
"repo_id": "packages",
"token_count": 49
} | 1,099 |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
</resources>
| packages/packages/video_player/video_player_android/example/android/app/src/main/res/values/styles.xml/0 | {
"file_path": "packages/packages/video_player/video_player_android/example/android/app/src/main/res/values/styles.xml",
"repo_id": "packages",
"token_count": 84
} | 1,100 |
// 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 "FVPVideoPlayerPlugin.h"
#import "FVPVideoPlayerPlugin_Test.h"
#import <AVFoundation/AVFoundation.h>
#import <GLKit/GLKit.h>
#import "AVAssetTrackUtils.h"
#import "FVPDisplayLink.h"
#import "messages.g.h"
#if !__has_feature(objc_arc)
#error Code Requires ARC.
#endif
@interface FVPFrameUpdater : NSObject
@property(nonatomic) int64_t textureId;
@property(nonatomic, weak, readonly) NSObject<FlutterTextureRegistry> *registry;
// The output that this updater is managing.
@property(nonatomic, weak) AVPlayerItemVideoOutput *videoOutput;
// The last time that has been validated as avaliable according to hasNewPixelBufferForItemTime:.
@property(nonatomic, assign) CMTime lastKnownAvailableTime;
// If YES, the engine is informed that a new texture is available any time the display link
// callback is fired, regardless of the videoOutput state.
//
// TODO(stuartmorgan): Investigate removing this; it exists only to preserve existing iOS behavior
// while implementing macOS, but iOS should very likely be doing the check as well. See
// https://github.com/flutter/flutter/issues/138427.
@property(nonatomic, assign) BOOL skipBufferAvailabilityCheck;
@end
@implementation FVPFrameUpdater
- (FVPFrameUpdater *)initWithRegistry:(NSObject<FlutterTextureRegistry> *)registry {
NSAssert(self, @"super init cannot be nil");
if (self == nil) return nil;
_registry = registry;
_lastKnownAvailableTime = kCMTimeInvalid;
return self;
}
- (void)displayLinkFired {
// Only report a new frame if one is actually available, or the check is being skipped.
BOOL reportFrame = NO;
if (self.skipBufferAvailabilityCheck) {
reportFrame = YES;
} else {
CMTime outputItemTime = [self.videoOutput itemTimeForHostTime:CACurrentMediaTime()];
if ([self.videoOutput hasNewPixelBufferForItemTime:outputItemTime]) {
_lastKnownAvailableTime = outputItemTime;
reportFrame = YES;
}
}
if (reportFrame) {
[_registry textureFrameAvailable:_textureId];
}
}
@end
@interface FVPDefaultAVFactory : NSObject <FVPAVFactory>
@end
@implementation FVPDefaultAVFactory
- (AVPlayer *)playerWithPlayerItem:(AVPlayerItem *)playerItem {
return [AVPlayer playerWithPlayerItem:playerItem];
}
- (AVPlayerItemVideoOutput *)videoOutputWithPixelBufferAttributes:
(NSDictionary<NSString *, id> *)attributes {
return [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:attributes];
}
@end
/// Non-test implementation of the diplay link factory.
@interface FVPDefaultDisplayLinkFactory : NSObject <FVPDisplayLinkFactory>
@end
@implementation FVPDefaultDisplayLinkFactory
- (FVPDisplayLink *)displayLinkWithRegistrar:(id<FlutterPluginRegistrar>)registrar
callback:(void (^)(void))callback {
return [[FVPDisplayLink alloc] initWithRegistrar:registrar callback:callback];
}
@end
#pragma mark -
@interface FVPVideoPlayer ()
@property(readonly, nonatomic) AVPlayerItemVideoOutput *videoOutput;
// The plugin registrar, to obtain view information from.
@property(nonatomic, weak) NSObject<FlutterPluginRegistrar> *registrar;
// The CALayer associated with the Flutter view this plugin is associated with, if any.
@property(nonatomic, readonly) CALayer *flutterViewLayer;
@property(nonatomic) FlutterEventChannel *eventChannel;
@property(nonatomic) FlutterEventSink eventSink;
@property(nonatomic) CGAffineTransform preferredTransform;
@property(nonatomic, readonly) BOOL disposed;
@property(nonatomic, readonly) BOOL isPlaying;
@property(nonatomic) BOOL isLooping;
@property(nonatomic, readonly) BOOL isInitialized;
// The updater that drives callbacks to the engine to indicate that a new frame is ready.
@property(nonatomic) FVPFrameUpdater *frameUpdater;
// The display link that drives frameUpdater.
@property(nonatomic) FVPDisplayLink *displayLink;
// Whether a new frame needs to be provided to the engine regardless of the current play/pause state
// (e.g., after a seek while paused). If YES, the display link should continue to run until the next
// frame is successfully provided.
@property(nonatomic, assign) BOOL waitingForFrame;
- (instancetype)initWithURL:(NSURL *)url
frameUpdater:(FVPFrameUpdater *)frameUpdater
displayLink:(FVPDisplayLink *)displayLink
httpHeaders:(nonnull NSDictionary<NSString *, NSString *> *)headers
avFactory:(id<FVPAVFactory>)avFactory
registrar:(NSObject<FlutterPluginRegistrar> *)registrar;
// Tells the player to run its frame updater until it receives a frame, regardless of the
// play/pause state.
- (void)expectFrame;
@end
static void *timeRangeContext = &timeRangeContext;
static void *statusContext = &statusContext;
static void *presentationSizeContext = &presentationSizeContext;
static void *durationContext = &durationContext;
static void *playbackLikelyToKeepUpContext = &playbackLikelyToKeepUpContext;
static void *rateContext = &rateContext;
@implementation FVPVideoPlayer
- (instancetype)initWithAsset:(NSString *)asset
frameUpdater:(FVPFrameUpdater *)frameUpdater
displayLink:(FVPDisplayLink *)displayLink
avFactory:(id<FVPAVFactory>)avFactory
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
NSString *path = [[NSBundle mainBundle] pathForResource:asset ofType:nil];
#if TARGET_OS_OSX
// See https://github.com/flutter/flutter/issues/135302
// TODO(stuartmorgan): Remove this if the asset APIs are adjusted to work better for macOS.
if (!path) {
path = [NSURL URLWithString:asset relativeToURL:NSBundle.mainBundle.bundleURL].path;
}
#endif
return [self initWithURL:[NSURL fileURLWithPath:path]
frameUpdater:frameUpdater
displayLink:displayLink
httpHeaders:@{}
avFactory:avFactory
registrar:registrar];
}
- (void)dealloc {
if (!_disposed) {
[self removeKeyValueObservers];
}
}
- (void)addObserversForItem:(AVPlayerItem *)item player:(AVPlayer *)player {
[item addObserver:self
forKeyPath:@"loadedTimeRanges"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:timeRangeContext];
[item addObserver:self
forKeyPath:@"status"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:statusContext];
[item addObserver:self
forKeyPath:@"presentationSize"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:presentationSizeContext];
[item addObserver:self
forKeyPath:@"duration"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:durationContext];
[item addObserver:self
forKeyPath:@"playbackLikelyToKeepUp"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:playbackLikelyToKeepUpContext];
// Add observer to AVPlayer instead of AVPlayerItem since the AVPlayerItem does not have a "rate"
// property
[player addObserver:self
forKeyPath:@"rate"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:rateContext];
// Add an observer that will respond to itemDidPlayToEndTime
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(itemDidPlayToEndTime:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:item];
}
- (void)itemDidPlayToEndTime:(NSNotification *)notification {
if (_isLooping) {
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero completionHandler:nil];
} else {
if (_eventSink) {
_eventSink(@{@"event" : @"completed"});
}
}
}
const int64_t TIME_UNSET = -9223372036854775807;
NS_INLINE int64_t FVPCMTimeToMillis(CMTime time) {
// When CMTIME_IS_INDEFINITE return a value that matches TIME_UNSET from ExoPlayer2 on Android.
// Fixes https://github.com/flutter/flutter/issues/48670
if (CMTIME_IS_INDEFINITE(time)) return TIME_UNSET;
if (time.timescale == 0) return 0;
return time.value * 1000 / time.timescale;
}
NS_INLINE CGFloat radiansToDegrees(CGFloat radians) {
// Input range [-pi, pi] or [-180, 180]
CGFloat degrees = GLKMathRadiansToDegrees((float)radians);
if (degrees < 0) {
// Convert -90 to 270 and -180 to 180
return degrees + 360;
}
// Output degrees in between [0, 360]
return degrees;
};
- (AVMutableVideoComposition *)getVideoCompositionWithTransform:(CGAffineTransform)transform
withAsset:(AVAsset *)asset
withVideoTrack:(AVAssetTrack *)videoTrack {
AVMutableVideoCompositionInstruction *instruction =
[AVMutableVideoCompositionInstruction videoCompositionInstruction];
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, [asset duration]);
AVMutableVideoCompositionLayerInstruction *layerInstruction =
[AVMutableVideoCompositionLayerInstruction
videoCompositionLayerInstructionWithAssetTrack:videoTrack];
[layerInstruction setTransform:_preferredTransform atTime:kCMTimeZero];
AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];
instruction.layerInstructions = @[ layerInstruction ];
videoComposition.instructions = @[ instruction ];
// If in portrait mode, switch the width and height of the video
CGFloat width = videoTrack.naturalSize.width;
CGFloat height = videoTrack.naturalSize.height;
NSInteger rotationDegrees =
(NSInteger)round(radiansToDegrees(atan2(_preferredTransform.b, _preferredTransform.a)));
if (rotationDegrees == 90 || rotationDegrees == 270) {
width = videoTrack.naturalSize.height;
height = videoTrack.naturalSize.width;
}
videoComposition.renderSize = CGSizeMake(width, height);
// TODO(@recastrodiaz): should we use videoTrack.nominalFrameRate ?
// Currently set at a constant 30 FPS
videoComposition.frameDuration = CMTimeMake(1, 30);
return videoComposition;
}
- (instancetype)initWithURL:(NSURL *)url
frameUpdater:(FVPFrameUpdater *)frameUpdater
displayLink:(FVPDisplayLink *)displayLink
httpHeaders:(nonnull NSDictionary<NSString *, NSString *> *)headers
avFactory:(id<FVPAVFactory>)avFactory
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
NSDictionary<NSString *, id> *options = nil;
if ([headers count] != 0) {
options = @{@"AVURLAssetHTTPHeaderFieldsKey" : headers};
}
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:options];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:urlAsset];
return [self initWithPlayerItem:item
frameUpdater:frameUpdater
displayLink:(FVPDisplayLink *)displayLink
avFactory:avFactory
registrar:registrar];
}
- (instancetype)initWithPlayerItem:(AVPlayerItem *)item
frameUpdater:(FVPFrameUpdater *)frameUpdater
displayLink:(FVPDisplayLink *)displayLink
avFactory:(id<FVPAVFactory>)avFactory
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
self = [super init];
NSAssert(self, @"super init cannot be nil");
_registrar = registrar;
_frameUpdater = frameUpdater;
AVAsset *asset = [item asset];
void (^assetCompletionHandler)(void) = ^{
if ([asset statusOfValueForKey:@"tracks" error:nil] == AVKeyValueStatusLoaded) {
NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
if ([tracks count] > 0) {
AVAssetTrack *videoTrack = tracks[0];
void (^trackCompletionHandler)(void) = ^{
if (self->_disposed) return;
if ([videoTrack statusOfValueForKey:@"preferredTransform"
error:nil] == AVKeyValueStatusLoaded) {
// Rotate the video by using a videoComposition and the preferredTransform
self->_preferredTransform = FVPGetStandardizedTransformForTrack(videoTrack);
// Note:
// https://developer.apple.com/documentation/avfoundation/avplayeritem/1388818-videocomposition
// Video composition can only be used with file-based media and is not supported for
// use with media served using HTTP Live Streaming.
AVMutableVideoComposition *videoComposition =
[self getVideoCompositionWithTransform:self->_preferredTransform
withAsset:asset
withVideoTrack:videoTrack];
item.videoComposition = videoComposition;
}
};
[videoTrack loadValuesAsynchronouslyForKeys:@[ @"preferredTransform" ]
completionHandler:trackCompletionHandler];
}
}
};
_player = [avFactory playerWithPlayerItem:item];
_player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
// This is to fix 2 bugs: 1. blank video for encrypted video streams on iOS 16
// (https://github.com/flutter/flutter/issues/111457) and 2. swapped width and height for some
// video streams (not just iOS 16). (https://github.com/flutter/flutter/issues/109116). An
// invisible AVPlayerLayer is used to overwrite the protection of pixel buffers in those streams
// for issue #1, and restore the correct width and height for issue #2.
_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
[self.flutterViewLayer addSublayer:_playerLayer];
// Configure output.
_displayLink = displayLink;
NSDictionary *pixBuffAttributes = @{
(id)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA),
(id)kCVPixelBufferIOSurfacePropertiesKey : @{}
};
_videoOutput = [avFactory videoOutputWithPixelBufferAttributes:pixBuffAttributes];
frameUpdater.videoOutput = _videoOutput;
#if TARGET_OS_IOS
// See TODO on this property in FVPFrameUpdater.
frameUpdater.skipBufferAvailabilityCheck = YES;
#endif
[self addObserversForItem:item player:_player];
[asset loadValuesAsynchronouslyForKeys:@[ @"tracks" ] completionHandler:assetCompletionHandler];
return self;
}
- (void)observeValueForKeyPath:(NSString *)path
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (context == timeRangeContext) {
if (_eventSink != nil) {
NSMutableArray<NSArray<NSNumber *> *> *values = [[NSMutableArray alloc] init];
for (NSValue *rangeValue in [object loadedTimeRanges]) {
CMTimeRange range = [rangeValue CMTimeRangeValue];
int64_t start = FVPCMTimeToMillis(range.start);
[values addObject:@[ @(start), @(start + FVPCMTimeToMillis(range.duration)) ]];
}
_eventSink(@{@"event" : @"bufferingUpdate", @"values" : values});
}
} else if (context == statusContext) {
AVPlayerItem *item = (AVPlayerItem *)object;
switch (item.status) {
case AVPlayerItemStatusFailed:
if (_eventSink != nil) {
_eventSink([FlutterError
errorWithCode:@"VideoError"
message:[@"Failed to load video: "
stringByAppendingString:[item.error localizedDescription]]
details:nil]);
}
break;
case AVPlayerItemStatusUnknown:
break;
case AVPlayerItemStatusReadyToPlay:
[item addOutput:_videoOutput];
[self setupEventSinkIfReadyToPlay];
[self updatePlayingState];
break;
}
} else if (context == presentationSizeContext || context == durationContext) {
AVPlayerItem *item = (AVPlayerItem *)object;
if (item.status == AVPlayerItemStatusReadyToPlay) {
// Due to an apparent bug, when the player item is ready, it still may not have determined
// its presentation size or duration. When these properties are finally set, re-check if
// all required properties and instantiate the event sink if it is not already set up.
[self setupEventSinkIfReadyToPlay];
[self updatePlayingState];
}
} else if (context == playbackLikelyToKeepUpContext) {
[self updatePlayingState];
if ([[_player currentItem] isPlaybackLikelyToKeepUp]) {
if (_eventSink != nil) {
_eventSink(@{@"event" : @"bufferingEnd"});
}
} else {
if (_eventSink != nil) {
_eventSink(@{@"event" : @"bufferingStart"});
}
}
} else if (context == rateContext) {
// Important: Make sure to cast the object to AVPlayer when observing the rate property,
// as it is not available in AVPlayerItem.
AVPlayer *player = (AVPlayer *)object;
if (_eventSink != nil) {
_eventSink(
@{@"event" : @"isPlayingStateUpdate", @"isPlaying" : player.rate > 0 ? @YES : @NO});
}
}
}
- (void)updatePlayingState {
if (!_isInitialized) {
return;
}
if (_isPlaying) {
[_player play];
} else {
[_player pause];
}
// If the texture is still waiting for an expected frame, the display link needs to keep
// running until it arrives regardless of the play/pause state.
_displayLink.running = _isPlaying || self.waitingForFrame;
}
- (void)setupEventSinkIfReadyToPlay {
if (_eventSink && !_isInitialized) {
AVPlayerItem *currentItem = self.player.currentItem;
CGSize size = currentItem.presentationSize;
CGFloat width = size.width;
CGFloat height = size.height;
// Wait until tracks are loaded to check duration or if there are any videos.
AVAsset *asset = currentItem.asset;
if ([asset statusOfValueForKey:@"tracks" error:nil] != AVKeyValueStatusLoaded) {
void (^trackCompletionHandler)(void) = ^{
if ([asset statusOfValueForKey:@"tracks" error:nil] != AVKeyValueStatusLoaded) {
// Cancelled, or something failed.
return;
}
// This completion block will run on an AVFoundation background queue.
// Hop back to the main thread to set up event sink.
[self performSelector:_cmd onThread:NSThread.mainThread withObject:self waitUntilDone:NO];
};
[asset loadValuesAsynchronouslyForKeys:@[ @"tracks" ]
completionHandler:trackCompletionHandler];
return;
}
BOOL hasVideoTracks = [asset tracksWithMediaType:AVMediaTypeVideo].count != 0;
BOOL hasNoTracks = asset.tracks.count == 0;
// The player has not yet initialized when it has no size, unless it is an audio-only track.
// HLS m3u8 video files never load any tracks, and are also not yet initialized until they have
// a size.
if ((hasVideoTracks || hasNoTracks) && height == CGSizeZero.height &&
width == CGSizeZero.width) {
return;
}
// The player may be initialized but still needs to determine the duration.
int64_t duration = [self duration];
if (duration == 0) {
return;
}
_isInitialized = YES;
_eventSink(@{
@"event" : @"initialized",
@"duration" : @(duration),
@"width" : @(width),
@"height" : @(height)
});
}
}
- (void)play {
_isPlaying = YES;
[self updatePlayingState];
}
- (void)pause {
_isPlaying = NO;
[self updatePlayingState];
}
- (int64_t)position {
return FVPCMTimeToMillis([_player currentTime]);
}
- (int64_t)duration {
// Note: https://openradar.appspot.com/radar?id=4968600712511488
// `[AVPlayerItem duration]` can be `kCMTimeIndefinite`,
// use `[[AVPlayerItem asset] duration]` instead.
return FVPCMTimeToMillis([[[_player currentItem] asset] duration]);
}
- (void)seekTo:(int64_t)location completionHandler:(void (^)(BOOL))completionHandler {
CMTime previousCMTime = _player.currentTime;
CMTime targetCMTime = CMTimeMake(location, 1000);
CMTimeValue duration = _player.currentItem.asset.duration.value;
// Without adding tolerance when seeking to duration,
// seekToTime will never complete, and this call will hang.
// see issue https://github.com/flutter/flutter/issues/124475.
CMTime tolerance = location == duration ? CMTimeMake(1, 1000) : kCMTimeZero;
[_player seekToTime:targetCMTime
toleranceBefore:tolerance
toleranceAfter:tolerance
completionHandler:^(BOOL completed) {
if (CMTimeCompare(self.player.currentTime, previousCMTime) != 0) {
// Ensure that a frame is drawn once available, even if currently paused. In theory a race
// is possible here where the new frame has already drawn by the time this code runs, and
// the display link stays on indefinitely, but that should be relatively harmless. This
// must use the display link rather than just informing the engine that a new frame is
// available because the seek completing doesn't guarantee that the pixel buffer is
// already available.
[self expectFrame];
}
if (completionHandler) {
completionHandler(completed);
}
}];
}
- (void)expectFrame {
self.waitingForFrame = YES;
self.displayLink.running = YES;
}
- (void)setIsLooping:(BOOL)isLooping {
_isLooping = isLooping;
}
- (void)setVolume:(double)volume {
_player.volume = (float)((volume < 0.0) ? 0.0 : ((volume > 1.0) ? 1.0 : volume));
}
- (void)setPlaybackSpeed:(double)speed {
// See https://developer.apple.com/library/archive/qa/qa1772/_index.html for an explanation of
// these checks.
if (speed > 2.0 && !_player.currentItem.canPlayFastForward) {
if (_eventSink != nil) {
_eventSink([FlutterError errorWithCode:@"VideoError"
message:@"Video cannot be fast-forwarded beyond 2.0x"
details:nil]);
}
return;
}
if (speed < 1.0 && !_player.currentItem.canPlaySlowForward) {
if (_eventSink != nil) {
_eventSink([FlutterError errorWithCode:@"VideoError"
message:@"Video cannot be slow-forwarded"
details:nil]);
}
return;
}
_player.rate = speed;
}
- (CVPixelBufferRef)copyPixelBuffer {
CVPixelBufferRef buffer = NULL;
CMTime outputItemTime = [_videoOutput itemTimeForHostTime:CACurrentMediaTime()];
if ([_videoOutput hasNewPixelBufferForItemTime:outputItemTime]) {
buffer = [_videoOutput copyPixelBufferForItemTime:outputItemTime itemTimeForDisplay:NULL];
} else {
// If the current time isn't available yet, use the time that was checked when informing the
// engine that a frame was available (if any).
CMTime lastAvailableTime = self.frameUpdater.lastKnownAvailableTime;
if (CMTIME_IS_VALID(lastAvailableTime)) {
buffer = [_videoOutput copyPixelBufferForItemTime:lastAvailableTime itemTimeForDisplay:NULL];
}
}
if (self.waitingForFrame && buffer) {
self.waitingForFrame = NO;
// If the display link was only running temporarily to pick up a new frame while the video was
// paused, stop it again.
if (!self.isPlaying) {
self.displayLink.running = NO;
}
}
return buffer;
}
- (void)onTextureUnregistered:(NSObject<FlutterTexture> *)texture {
dispatch_async(dispatch_get_main_queue(), ^{
[self dispose];
});
}
- (FlutterError *_Nullable)onCancelWithArguments:(id _Nullable)arguments {
_eventSink = nil;
return nil;
}
- (FlutterError *_Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(nonnull FlutterEventSink)events {
_eventSink = events;
// TODO(@recastrodiaz): remove the line below when the race condition is resolved:
// https://github.com/flutter/flutter/issues/21483
// This line ensures the 'initialized' event is sent when the event
// 'AVPlayerItemStatusReadyToPlay' fires before _eventSink is set (this function
// onListenWithArguments is called)
[self setupEventSinkIfReadyToPlay];
return nil;
}
/// This method allows you to dispose without touching the event channel. This
/// is useful for the case where the Engine is in the process of deconstruction
/// so the channel is going to die or is already dead.
- (void)disposeSansEventChannel {
// This check prevents the crash caused by removing the KVO observers twice.
// When performing a Hot Restart, the leftover players are disposed once directly
// by [FVPVideoPlayerPlugin initialize:] method and then disposed again by
// [FVPVideoPlayer onTextureUnregistered:] call leading to possible over-release.
if (_disposed) {
return;
}
_disposed = YES;
[_playerLayer removeFromSuperlayer];
_displayLink = nil;
[self removeKeyValueObservers];
[self.player replaceCurrentItemWithPlayerItem:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dispose {
[self disposeSansEventChannel];
[_eventChannel setStreamHandler:nil];
}
- (CALayer *)flutterViewLayer {
#if TARGET_OS_OSX
return self.registrar.view.layer;
#else
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// TODO(hellohuanlin): Provide a non-deprecated codepath. See
// https://github.com/flutter/flutter/issues/104117
UIViewController *root = UIApplication.sharedApplication.keyWindow.rootViewController;
#pragma clang diagnostic pop
return root.view.layer;
#endif
}
/// Removes all key-value observers set up for the player.
///
/// This is called from dealloc, so must not use any methods on self.
- (void)removeKeyValueObservers {
AVPlayerItem *currentItem = _player.currentItem;
[currentItem removeObserver:self forKeyPath:@"status"];
[currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
[currentItem removeObserver:self forKeyPath:@"presentationSize"];
[currentItem removeObserver:self forKeyPath:@"duration"];
[currentItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
[_player removeObserver:self forKeyPath:@"rate"];
}
@end
@interface FVPVideoPlayerPlugin ()
@property(readonly, weak, nonatomic) NSObject<FlutterTextureRegistry> *registry;
@property(readonly, weak, nonatomic) NSObject<FlutterBinaryMessenger> *messenger;
@property(readonly, strong, nonatomic) NSObject<FlutterPluginRegistrar> *registrar;
@property(nonatomic, strong) id<FVPDisplayLinkFactory> displayLinkFactory;
@property(nonatomic, strong) id<FVPAVFactory> avFactory;
@end
@implementation FVPVideoPlayerPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FVPVideoPlayerPlugin *instance = [[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
[registrar publish:instance];
SetUpFVPAVFoundationVideoPlayerApi(registrar.messenger, instance);
}
- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
return [self initWithAVFactory:[[FVPDefaultAVFactory alloc] init]
displayLinkFactory:[[FVPDefaultDisplayLinkFactory alloc] init]
registrar:registrar];
}
- (instancetype)initWithAVFactory:(id<FVPAVFactory>)avFactory
displayLinkFactory:(id<FVPDisplayLinkFactory>)displayLinkFactory
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
self = [super init];
NSAssert(self, @"super init cannot be nil");
_registry = [registrar textures];
_messenger = [registrar messenger];
_registrar = registrar;
_displayLinkFactory = displayLinkFactory ?: [[FVPDefaultDisplayLinkFactory alloc] init];
_avFactory = avFactory ?: [[FVPDefaultAVFactory alloc] init];
_playersByTextureId = [NSMutableDictionary dictionaryWithCapacity:1];
return self;
}
- (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
[self.playersByTextureId.allValues makeObjectsPerformSelector:@selector(disposeSansEventChannel)];
[self.playersByTextureId removeAllObjects];
// TODO(57151): This should be commented out when 57151's fix lands on stable.
// This is the correct behavior we never did it in the past and the engine
// doesn't currently support it.
// FVPAVFoundationVideoPlayerApiSetup(registrar.messenger, nil);
}
- (FVPTextureMessage *)onPlayerSetup:(FVPVideoPlayer *)player
frameUpdater:(FVPFrameUpdater *)frameUpdater {
int64_t textureId = [self.registry registerTexture:player];
frameUpdater.textureId = textureId;
FlutterEventChannel *eventChannel = [FlutterEventChannel
eventChannelWithName:[NSString stringWithFormat:@"flutter.io/videoPlayer/videoEvents%lld",
textureId]
binaryMessenger:_messenger];
[eventChannel setStreamHandler:player];
player.eventChannel = eventChannel;
self.playersByTextureId[@(textureId)] = player;
// Ensure that the first frame is drawn once available, even if the video isn't played, since
// the engine is now expecting the texture to be populated.
[player expectFrame];
FVPTextureMessage *result = [FVPTextureMessage makeWithTextureId:textureId];
return result;
}
- (void)initialize:(FlutterError *__autoreleasing *)error {
#if TARGET_OS_IOS
// Allow audio playback when the Ring/Silent switch is set to silent
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
#endif
[self.playersByTextureId
enumerateKeysAndObjectsUsingBlock:^(NSNumber *textureId, FVPVideoPlayer *player, BOOL *stop) {
[self.registry unregisterTexture:textureId.unsignedIntegerValue];
[player dispose];
}];
[self.playersByTextureId removeAllObjects];
}
- (FVPTextureMessage *)create:(FVPCreateMessage *)input error:(FlutterError **)error {
FVPFrameUpdater *frameUpdater = [[FVPFrameUpdater alloc] initWithRegistry:_registry];
FVPDisplayLink *displayLink =
[self.displayLinkFactory displayLinkWithRegistrar:_registrar
callback:^() {
[frameUpdater displayLinkFired];
}];
FVPVideoPlayer *player;
if (input.asset) {
NSString *assetPath;
if (input.packageName) {
assetPath = [_registrar lookupKeyForAsset:input.asset fromPackage:input.packageName];
} else {
assetPath = [_registrar lookupKeyForAsset:input.asset];
}
@try {
player = [[FVPVideoPlayer alloc] initWithAsset:assetPath
frameUpdater:frameUpdater
displayLink:displayLink
avFactory:_avFactory
registrar:self.registrar];
return [self onPlayerSetup:player frameUpdater:frameUpdater];
} @catch (NSException *exception) {
*error = [FlutterError errorWithCode:@"video_player" message:exception.reason details:nil];
return nil;
}
} else if (input.uri) {
player = [[FVPVideoPlayer alloc] initWithURL:[NSURL URLWithString:input.uri]
frameUpdater:frameUpdater
displayLink:displayLink
httpHeaders:input.httpHeaders
avFactory:_avFactory
registrar:self.registrar];
return [self onPlayerSetup:player frameUpdater:frameUpdater];
} else {
*error = [FlutterError errorWithCode:@"video_player" message:@"not implemented" details:nil];
return nil;
}
}
- (void)dispose:(FVPTextureMessage *)input error:(FlutterError **)error {
NSNumber *playerKey = @(input.textureId);
FVPVideoPlayer *player = self.playersByTextureId[playerKey];
[self.registry unregisterTexture:input.textureId];
[self.playersByTextureId removeObjectForKey:playerKey];
// If the Flutter contains https://github.com/flutter/engine/pull/12695,
// the `player` is disposed via `onTextureUnregistered` at the right time.
// Without https://github.com/flutter/engine/pull/12695, there is no guarantee that the
// texture has completed the un-reregistration. It may leads a crash if we dispose the
// `player` before the texture is unregistered. We add a dispatch_after hack to make sure the
// texture is unregistered before we dispose the `player`.
//
// TODO(cyanglaz): Remove this dispatch block when
// https://github.com/flutter/flutter/commit/8159a9906095efc9af8b223f5e232cb63542ad0b is in
// stable And update the min flutter version of the plugin to the stable version.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
if (!player.disposed) {
[player dispose];
}
});
}
- (void)setLooping:(FVPLoopingMessage *)input error:(FlutterError **)error {
FVPVideoPlayer *player = self.playersByTextureId[@(input.textureId)];
player.isLooping = input.isLooping;
}
- (void)setVolume:(FVPVolumeMessage *)input error:(FlutterError **)error {
FVPVideoPlayer *player = self.playersByTextureId[@(input.textureId)];
[player setVolume:input.volume];
}
- (void)setPlaybackSpeed:(FVPPlaybackSpeedMessage *)input error:(FlutterError **)error {
FVPVideoPlayer *player = self.playersByTextureId[@(input.textureId)];
[player setPlaybackSpeed:input.speed];
}
- (void)play:(FVPTextureMessage *)input error:(FlutterError **)error {
FVPVideoPlayer *player = self.playersByTextureId[@(input.textureId)];
[player play];
}
- (FVPPositionMessage *)position:(FVPTextureMessage *)input error:(FlutterError **)error {
FVPVideoPlayer *player = self.playersByTextureId[@(input.textureId)];
FVPPositionMessage *result = [FVPPositionMessage makeWithTextureId:input.textureId
position:[player position]];
return result;
}
- (void)seekTo:(FVPPositionMessage *)input
completion:(void (^)(FlutterError *_Nullable))completion {
FVPVideoPlayer *player = self.playersByTextureId[@(input.textureId)];
[player seekTo:input.position
completionHandler:^(BOOL finished) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
});
}];
}
- (void)pause:(FVPTextureMessage *)input error:(FlutterError **)error {
FVPVideoPlayer *player = self.playersByTextureId[@(input.textureId)];
[player pause];
}
- (void)setMixWithOthers:(FVPMixWithOthersMessage *)input
error:(FlutterError *_Nullable __autoreleasing *)error {
#if TARGET_OS_OSX
// AVAudioSession doesn't exist on macOS, and audio always mixes, so just no-op.
#else
if (input.mixWithOthers) {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
withOptions:AVAudioSessionCategoryOptionMixWithOthers
error:nil];
} else {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
}
#endif
}
@end
| packages/packages/video_player/video_player_avfoundation/darwin/Classes/FVPVideoPlayerPlugin.m/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/FVPVideoPlayerPlugin.m",
"repo_id": "packages",
"token_count": 13298
} | 1,101 |
name: video_player_platform_interface
description: A common platform interface for the video_player plugin.
repository: https://github.com/flutter/packages/tree/main/packages/video_player/video_player_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 6.2.2
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.7
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- video
- video-player
| packages/packages/video_player/video_player_platform_interface/pubspec.yaml/0 | {
"file_path": "packages/packages/video_player/video_player_platform_interface/pubspec.yaml",
"repo_id": "packages",
"token_count": 257
} | 1,102 |
name: video_player_for_web_integration_tests
publish_to: none
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
dependencies:
flutter:
sdk: flutter
video_player_platform_interface: ^6.1.0
video_player_web:
path: ../
web: ^0.5.1
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
| packages/packages/video_player/video_player_web/example/pubspec.yaml/0 | {
"file_path": "packages/packages/video_player/video_player_web/example/pubspec.yaml",
"repo_id": "packages",
"token_count": 150
} | 1,103 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert' show json;
import 'dart:js_interop';
import 'dart:math' as math;
import 'package:web/web.dart';
import 'src/common.dart';
import 'src/recorder.dart';
export 'src/recorder.dart';
/// Signature for a function that creates a [Recorder].
typedef RecorderFactory = Recorder Function();
/// List of all benchmarks that run in the devicelab.
///
/// When adding a new benchmark, add it to this map. Make sure that the name
/// of your benchmark is unique.
late Map<String, RecorderFactory> _benchmarks;
final LocalBenchmarkServerClient _client = LocalBenchmarkServerClient();
/// Starts a local benchmark client to run [benchmarks].
///
/// Usually used in combination with a benchmark server, which orders the
/// client to run each benchmark in order.
///
/// When used without a server, prompts the user to select a benchmark to
/// run next.
Future<void> runBenchmarks(
Map<String, RecorderFactory> benchmarks, {
String initialPage = defaultInitialPage,
}) async {
// Set local benchmarks.
_benchmarks = benchmarks;
// Check if the benchmark server wants us to run a specific benchmark.
final String nextBenchmark = await _client.requestNextBenchmark();
if (nextBenchmark == LocalBenchmarkServerClient.kManualFallback) {
_fallbackToManual(
'The server did not tell us which benchmark to run next.');
return;
}
await _runBenchmark(nextBenchmark);
final Uri currentUri = Uri.parse(window.location.href);
// Create a new URI with the current 'page' value set to [initialPage] to
// ensure the benchmark app is reloaded at the proper location.
final String newUri = Uri(
scheme: currentUri.scheme,
host: currentUri.host,
port: currentUri.port,
path: initialPage,
).toString();
// Reloading the window will trigger the next benchmark to run.
await _client.printToConsole(
'Client preparing to reload the window to: "$newUri"',
);
window.location.replace(newUri);
}
Future<void> _runBenchmark(String? benchmarkName) async {
final RecorderFactory? recorderFactory = _benchmarks[benchmarkName];
if (recorderFactory == null) {
_fallbackToManual('Benchmark $benchmarkName not found.');
return;
}
await runZoned<Future<void>>(
() async {
final Recorder recorder = recorderFactory();
final Runner runner = recorder.isTracingEnabled && !_client.isInManualMode
? Runner(
recorder: recorder,
setUpAllDidRun: () =>
_client.startPerformanceTracing(benchmarkName),
tearDownAllWillRun: _client.stopPerformanceTracing,
)
: Runner(recorder: recorder);
final Profile profile = await runner.run();
if (!_client.isInManualMode) {
await _client.sendProfileData(profile);
} else {
_printResultsToScreen(profile);
print(profile); // ignore: avoid_print
}
},
zoneSpecification: ZoneSpecification(
print: (Zone self, ZoneDelegate parent, Zone zone, String line) async {
if (_client.isInManualMode) {
parent.print(zone, '[$benchmarkName] $line');
} else {
await _client.printToConsole(line);
}
},
handleUncaughtError: (
Zone self,
ZoneDelegate parent,
Zone zone,
Object error,
StackTrace stackTrace,
) async {
if (_client.isInManualMode) {
parent.print(zone, '[$benchmarkName] $error, $stackTrace');
parent.handleUncaughtError(zone, error, stackTrace);
} else {
await _client.reportError(error, stackTrace);
}
},
),
);
}
void _fallbackToManual(String error) {
document.body!.appendHtml('''
<div id="manual-panel">
<h3>$error</h3>
<p>Choose one of the following benchmarks:</p>
<!-- Absolutely position it so it receives the clicks and not the glasspane -->
<ul style="position: absolute">
${_benchmarks.keys.map((String name) => '<li><button id="$name">$name</button></li>').join('\n')}
</ul>
</div>
''');
for (final String benchmarkName in _benchmarks.keys) {
// Find the button elements added above.
final Element button = document.querySelector('#$benchmarkName')!;
button.addEventListener(
'click',
(JSAny? arg) {
final Element? manualPanel = document.querySelector('#manual-panel');
manualPanel?.remove();
_runBenchmark(benchmarkName);
}.toJS);
}
}
/// Visualizes results on the Web page for manual inspection.
void _printResultsToScreen(Profile profile) {
final HTMLBodyElement body = document.body! as HTMLBodyElement;
body.innerHTML = '<h2>${profile.name}</h2>';
profile.scoreData.forEach((String scoreKey, Timeseries timeseries) {
body.appendHtml('<h2>$scoreKey</h2>');
body.appendHtml('<pre>${timeseries.computeStats()}</pre>');
body.appendChild(TimeseriesVisualization(timeseries).render());
});
}
/// Draws timeseries data and statistics on a canvas.
class TimeseriesVisualization {
/// Creates a visualization for a [Timeseries].
TimeseriesVisualization(this._timeseries) {
_stats = _timeseries.computeStats();
_canvas = HTMLCanvasElement();
_screenWidth = window.screen.width;
_canvas.width = _screenWidth;
_canvas.height = (_kCanvasHeight * window.devicePixelRatio).round();
_canvas.style
..width = '100%'
..height = '${_kCanvasHeight}px'
..outline = '1px solid green';
_ctx = _canvas.context2D;
// The amount of vertical space available on the chart. Because some
// outliers can be huge they can dwarf all the useful values. So we
// limit it to 1.5 x the biggest non-outlier.
_maxValueChartRange = 1.5 *
_stats.samples
.where((AnnotatedSample sample) => !sample.isOutlier)
.map<double>((AnnotatedSample sample) => sample.magnitude)
.fold<double>(0, math.max);
}
static const double _kCanvasHeight = 200;
final Timeseries _timeseries;
late TimeseriesStats _stats;
late HTMLCanvasElement _canvas;
late CanvasRenderingContext2D _ctx;
late int _screenWidth;
// Used to normalize benchmark values to chart height.
late double _maxValueChartRange;
/// Converts a sample value to vertical canvas coordinates.
///
/// This does not work for horizontal coordinates.
double _normalized(double value) {
return _kCanvasHeight * value / _maxValueChartRange;
}
/// A utility for drawing lines.
void drawLine(num x1, num y1, num x2, num y2) {
_ctx.beginPath();
_ctx.moveTo(x1, y1);
_ctx.lineTo(x2, y2);
_ctx.stroke();
}
/// Renders the timeseries into a `<canvas>` and returns the canvas element.
HTMLCanvasElement render() {
_ctx.translate(0, _kCanvasHeight * window.devicePixelRatio);
_ctx.scale(1, -window.devicePixelRatio);
final double barWidth = _screenWidth / _stats.samples.length;
double xOffset = 0;
for (int i = 0; i < _stats.samples.length; i++) {
final AnnotatedSample sample = _stats.samples[i];
if (sample.isWarmUpValue) {
// Put gray background behind warm-up samples.
_ctx.fillStyle = 'rgba(200,200,200,1)'.toJS;
_ctx.fillRect(xOffset, 0, barWidth, _normalized(_maxValueChartRange));
}
if (sample.magnitude > _maxValueChartRange) {
// The sample value is so big it doesn't fit on the chart. Paint it purple.
_ctx.fillStyle = 'rgba(100,50,100,0.8)'.toJS;
} else if (sample.isOutlier) {
// The sample is an outlier, color it light red.
_ctx.fillStyle = 'rgba(255,50,50,0.6)'.toJS;
} else {
// A non-outlier sample, color it light blue.
_ctx.fillStyle = 'rgba(50,50,255,0.6)'.toJS;
}
_ctx.fillRect(xOffset, 0, barWidth - 1, _normalized(sample.magnitude));
xOffset += barWidth;
}
// Draw a horizontal solid line corresponding to the average.
_ctx.lineWidth = 1;
drawLine(0, _normalized(_stats.average), _screenWidth,
_normalized(_stats.average));
// Draw a horizontal dashed line corresponding to the outlier cut off.
_ctx.setLineDash(<JSNumber>[5.toJS, 5.toJS].toJS);
drawLine(0, _normalized(_stats.outlierCutOff), _screenWidth,
_normalized(_stats.outlierCutOff));
// Draw a light red band that shows the noise (1 stddev in each direction).
_ctx.fillStyle = 'rgba(255,50,50,0.3)'.toJS;
_ctx.fillRect(
0,
_normalized(_stats.average * (1 - _stats.noise)),
_screenWidth,
_normalized(2 * _stats.average * _stats.noise),
);
return _canvas;
}
}
/// Implements the client REST API for the local benchmark server.
///
/// The local server is optional. If it is not available the benchmark UI must
/// implement a manual fallback. This allows debugging benchmarks using plain
/// `flutter run`.
class LocalBenchmarkServerClient {
/// This value is returned by [requestNextBenchmark].
static const String kManualFallback = '__manual_fallback__';
/// Whether we fell back to manual mode.
///
/// This happens when you run benchmarks using plain `flutter run` rather than
/// devicelab test harness. The test harness spins up a special server that
/// provides API for automatically picking the next benchmark to run.
late bool isInManualMode;
/// Asks the local server for the name of the next benchmark to run.
///
/// Returns [kManualFallback] if local server is not available (uses 404 as a
/// signal).
Future<String> requestNextBenchmark() async {
final XMLHttpRequest request = await _requestXhr(
'/next-benchmark',
method: 'POST',
mimeType: 'application/json',
sendData: json.encode(_benchmarks.keys.toList()),
);
// `kEndOfBenchmarks` is expected when the benchmark server is telling us there are no more benchmarks to run.
// 404 is expected when the benchmark is run using plain `flutter run`, which does not provide "next-benchmark" handler.
if (request.responseText == kEndOfBenchmarks || request.status == 404) {
isInManualMode = true;
return kManualFallback;
}
isInManualMode = false;
return request.responseText;
}
void _checkNotManualMode() {
if (isInManualMode) {
throw StateError('Operation not supported in manual fallback mode.');
}
}
/// Asks the local server to begin tracing performance.
///
/// This uses the chrome://tracing tracer, which is not available from within
/// the page itself, and therefore must be controlled from outside using the
/// DevTools Protocol.
Future<void> startPerformanceTracing(String? benchmarkName) async {
_checkNotManualMode();
await _requestXhr(
'/start-performance-tracing?label=$benchmarkName',
method: 'POST',
mimeType: 'application/json',
);
}
/// Stops the performance tracing session started by [startPerformanceTracing].
Future<void> stopPerformanceTracing() async {
_checkNotManualMode();
await _requestXhr(
'/stop-performance-tracing',
method: 'POST',
mimeType: 'application/json',
);
}
/// Sends the profile data collected by the benchmark to the local benchmark
/// server.
Future<void> sendProfileData(Profile profile) async {
_checkNotManualMode();
final XMLHttpRequest request = await _requestXhr(
'/profile-data',
method: 'POST',
mimeType: 'application/json',
sendData: json.encode(profile.toJson()),
);
if (request.status != 200) {
throw Exception('Failed to report profile data to benchmark server. '
'The server responded with status code ${request.status}.');
}
}
/// Reports an error to the benchmark server.
///
/// The server will halt the devicelab task and log the error.
Future<void> reportError(dynamic error, StackTrace stackTrace) async {
_checkNotManualMode();
await _requestXhr(
'/on-error',
method: 'POST',
mimeType: 'application/json',
sendData: json.encode(<String, dynamic>{
'error': '$error',
'stackTrace': '$stackTrace',
}),
);
}
/// Reports a message about the demo to the benchmark server.
Future<void> printToConsole(String report) async {
_checkNotManualMode();
await _requestXhr(
'/print-to-console',
method: 'POST',
mimeType: 'text/plain',
sendData: report,
);
}
/// This is the same as calling [XMLHttpRequest.request] but it doesn't
/// crash on 404, which we use to detect `flutter run`.
Future<XMLHttpRequest> _requestXhr(
String url, {
required String method,
required String mimeType,
String? sendData,
}) {
final Completer<XMLHttpRequest> completer = Completer<XMLHttpRequest>();
final XMLHttpRequest xhr = XMLHttpRequest();
xhr.open(method, url, true);
xhr.overrideMimeType(mimeType);
xhr.onLoad.listen((ProgressEvent e) {
completer.complete(xhr);
});
xhr.onError.listen(completer.completeError);
if (sendData != null) {
xhr.send(sendData.toJS);
} else {
xhr.send();
}
return completer.future;
}
}
extension on HTMLElement {
void appendHtml(String input) => insertAdjacentHTML('beforeend', input);
}
| packages/packages/web_benchmarks/lib/client.dart/0 | {
"file_path": "packages/packages/web_benchmarks/lib/client.dart",
"repo_id": "packages",
"token_count": 4853
} | 1,104 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
// Runs `dart test -p chrome` in the root of the cross_file package.
//
// Called from the custom-tests CI action.
//
// usage: dart run tool/run_tests.dart
// (needs a `chrome` executable in $PATH, or a tweak to dart_test.yaml)
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as p;
Future<void> main(List<String> args) async {
if (!Platform.isLinux) {
// The test was migrated from a Linux-only task, so this preserves behavior.
// If desired, it can be enabled for other platforms in the future.
print('Skipping for non-Linux host');
exit(0);
}
final Directory packageDir =
Directory(p.dirname(Platform.script.path)).parent;
final String testingAppDirPath =
p.join(packageDir.path, 'testing', 'test_app');
// Fetch the test app's dependencies.
int status = await _runProcess(
'flutter',
<String>[
'pub',
'get',
],
workingDirectory: testingAppDirPath,
);
if (status != 0) {
exit(status);
}
// Run the tests.
status = await _runProcess(
'flutter',
<String>[
'test',
'testing',
],
workingDirectory: packageDir.path,
);
exit(status);
}
Future<Process> _streamOutput(Future<Process> processFuture) async {
final Process process = await processFuture;
await Future.wait(<Future<void>>[
stdout.addStream(process.stdout),
stderr.addStream(process.stderr),
]);
return process;
}
Future<int> _runProcess(
String command,
List<String> arguments, {
String? workingDirectory,
}) async {
final Process process = await _streamOutput(Process.start(
command,
arguments,
workingDirectory: workingDirectory,
));
return process.exitCode;
}
| packages/packages/web_benchmarks/tool/run_tests.dart/0 | {
"file_path": "packages/packages/web_benchmarks/tool/run_tests.dart",
"repo_id": "packages",
"token_count": 653
} | 1,105 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'
show
HttpAuthRequest,
JavaScriptAlertDialogRequest,
JavaScriptConfirmDialogRequest,
JavaScriptConsoleMessage,
JavaScriptLogLevel,
JavaScriptMessage,
JavaScriptMode,
JavaScriptTextInputDialogRequest,
LoadRequestMethod,
NavigationDecision,
NavigationRequest,
NavigationRequestCallback,
PageEventCallback,
PlatformNavigationDelegateCreationParams,
PlatformWebViewControllerCreationParams,
PlatformWebViewCookieManagerCreationParams,
PlatformWebViewPermissionRequest,
PlatformWebViewWidgetCreationParams,
ProgressCallback,
ScrollPositionChange,
UrlChange,
WebResourceError,
WebResourceErrorCallback,
WebResourceErrorType,
WebViewCookie,
WebViewCredential,
WebViewPermissionResourceType,
WebViewPlatform;
export 'src/navigation_delegate.dart';
export 'src/webview_controller.dart';
export 'src/webview_cookie_manager.dart';
export 'src/webview_widget.dart';
| packages/packages/webview_flutter/webview_flutter/lib/webview_flutter.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/lib/webview_flutter.dart",
"repo_id": "packages",
"token_count": 503
} | 1,106 |
# webview\_flutter\_android
The Android implementation of [`webview_flutter`][1].
## Usage
This package is [endorsed][2], which means you can simply use `webview_flutter`
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your `pubspec.yaml`.
However, if you `import` this package to use any of its APIs directly, you
should add it to your `pubspec.yaml` as usual.
## Display Mode
This plugin supports two different platform view display modes. The default display mode is subject
to change in the future, and will not be considered a breaking change, so if you want to ensure a
specific mode, you can set it explicitly.
### Texture Layer Hybrid Composition
This is the current default mode for versions >=23. This is a new display mode used by most
plugins starting with Flutter 3.0. This is more performant than Hybrid Composition, but has some
limitations from using an Android [SurfaceTexture](https://developer.android.com/reference/android/graphics/SurfaceTexture).
See:
* https://github.com/flutter/flutter/issues/104889
* https://github.com/flutter/flutter/issues/116954
### Hybrid Composition
This is the current default mode for versions <23. It ensures that the WebView will display and work
as expected, at the cost of some performance. See:
* https://flutter.dev/docs/development/platform-integration/platform-views#performance
This can be configured for versions >=23 with
`AndroidWebViewWidgetCreationParams.displayWithHybridComposition`. See https://pub.dev/packages/webview_flutter#platform-specific-features
for more details on setting platform-specific features in the main plugin.
## External Native API
The plugin also provides a native API accessible by the native code of Android applications or
packages. This API follows the convention of breaking changes of the Dart API, which means that any
changes to the class that are not backwards compatible will only be made with a major version change
of the plugin. Native code other than this external API does not follow breaking change conventions,
so app or plugin clients should not use any other native APIs.
The API can be accessed by importing the native class `WebViewFlutterAndroidExternalApi`:
Java:
```java
import io.flutter.plugins.webviewflutter.WebViewFlutterAndroidExternalApi;
```
## Fullscreen Video
To display a video as fullscreen, an app must manually handle the notification that the current page
has entered fullscreen mode. This can be done by calling
`AndroidWebViewController.setCustomWidgetCallbacks`. Below is an example implementation.
<?code-excerpt "example/lib/main.dart (fullscreen_example)"?>
```dart
androidController.setCustomWidgetCallbacks(
onShowCustomWidget: (Widget widget, OnHideCustomWidgetCallback callback) {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) => widget,
fullscreenDialog: true,
));
},
onHideCustomWidget: () {
Navigator.of(context).pop();
},
);
```
## Contributing
This package uses [pigeon][3] to generate the communication layer between Flutter and the host
platform (Android). The communication interface is defined in the `pigeons/android_webview.dart`
file. After editing the communication interface regenerate the communication layer by running
`dart run pigeon --input pigeons/android_webview.dart`.
Besides [pigeon][3] this package also uses [mockito][4] to generate mock objects for testing
purposes. To generate the mock objects run the following command:
```bash
dart run build_runner build --delete-conflicting-outputs
```
If you would like to contribute to the plugin, check out our [contribution guide][5].
[1]: https://pub.dev/packages/webview_flutter
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
[3]: https://pub.dev/packages/pigeon
[4]: https://pub.dev/packages/mockito
[5]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md
| packages/packages/webview_flutter/webview_flutter_android/README.md/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/README.md",
"repo_id": "packages",
"token_count": 1078
} | 1,107 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import android.webkit.GeolocationPermissions;
import androidx.annotation.NonNull;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.GeolocationPermissionsCallbackHostApi;
import java.util.Objects;
/**
* Host API implementation for `GeolocationPermissionsCallback`.
*
* <p>This class may handle instantiating and adding native object instances that are attached to a
* Dart instance or handle method calls on the associated native class or an instance of the class.
*/
public class GeolocationPermissionsCallbackHostApiImpl
implements GeolocationPermissionsCallbackHostApi {
// To ease adding additional methods, this value is added prematurely.
@SuppressWarnings({"unused", "FieldCanBeLocal"})
private final BinaryMessenger binaryMessenger;
private final InstanceManager instanceManager;
/**
* Constructs a {@link GeolocationPermissionsCallbackHostApiImpl}.
*
* @param binaryMessenger used to communicate with Dart over asynchronous messages
* @param instanceManager maintains instances stored to communicate with attached Dart objects
*/
public GeolocationPermissionsCallbackHostApiImpl(
@NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) {
this.binaryMessenger = binaryMessenger;
this.instanceManager = instanceManager;
}
@Override
public void invoke(
@NonNull Long instanceId,
@NonNull String origin,
@NonNull Boolean allow,
@NonNull Boolean retain) {
getGeolocationPermissionsCallbackInstance(instanceId).invoke(origin, allow, retain);
}
private GeolocationPermissions.Callback getGeolocationPermissionsCallbackInstance(
@NonNull Long identifier) {
return Objects.requireNonNull(instanceManager.getInstance(identifier));
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/GeolocationPermissionsCallbackHostApiImpl.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/GeolocationPermissionsCallbackHostApiImpl.java",
"repo_id": "packages",
"token_count": 560
} | 1,108 |
// 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.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.view.KeyEvent;
import android.webkit.HttpAuthHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.webkit.WebResourceErrorCompat;
import androidx.webkit.WebViewClientCompat;
import java.util.Objects;
/**
* Host api implementation for {@link WebViewClient}.
*
* <p>Handles creating {@link WebViewClient}s that intercommunicate with a paired Dart object.
*/
public class WebViewClientHostApiImpl implements GeneratedAndroidWebView.WebViewClientHostApi {
private final InstanceManager instanceManager;
private final WebViewClientCreator webViewClientCreator;
private final WebViewClientFlutterApiImpl flutterApi;
/** Implementation of {@link WebViewClient} that passes arguments of callback methods to Dart. */
@RequiresApi(Build.VERSION_CODES.N)
public static class WebViewClientImpl extends WebViewClient {
private final WebViewClientFlutterApiImpl flutterApi;
private boolean returnValueForShouldOverrideUrlLoading = false;
/**
* Creates a {@link WebViewClient} that passes arguments of callbacks methods to Dart.
*
* @param flutterApi handles sending messages to Dart.
*/
public WebViewClientImpl(@NonNull WebViewClientFlutterApiImpl flutterApi) {
this.flutterApi = flutterApi;
}
@Override
public void onPageStarted(@NonNull WebView view, @NonNull String url, @NonNull Bitmap favicon) {
flutterApi.onPageStarted(this, view, url, reply -> {});
}
@Override
public void onPageFinished(@NonNull WebView view, @NonNull String url) {
flutterApi.onPageFinished(this, view, url, reply -> {});
}
@Override
public void onReceivedHttpError(
@NonNull WebView view,
@NonNull WebResourceRequest request,
@NonNull WebResourceResponse response) {
flutterApi.onReceivedHttpError(this, view, request, response, reply -> {});
}
@Override
public void onReceivedError(
@NonNull WebView view,
@NonNull WebResourceRequest request,
@NonNull WebResourceError error) {
flutterApi.onReceivedRequestError(this, view, request, error, reply -> {});
}
// Legacy codepath for < 23; newer versions use the variant above.
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(
@NonNull WebView view,
int errorCode,
@NonNull String description,
@NonNull String failingUrl) {
flutterApi.onReceivedError(
this, view, (long) errorCode, description, failingUrl, reply -> {});
}
@Override
public boolean shouldOverrideUrlLoading(
@NonNull WebView view, @NonNull WebResourceRequest request) {
flutterApi.requestLoading(this, view, request, reply -> {});
return returnValueForShouldOverrideUrlLoading;
}
// Legacy codepath for < 24; newer versions use the variant above.
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(@NonNull WebView view, @NonNull String url) {
flutterApi.urlLoading(this, view, url, reply -> {});
return returnValueForShouldOverrideUrlLoading;
}
@Override
public void doUpdateVisitedHistory(
@NonNull WebView view, @NonNull String url, boolean isReload) {
flutterApi.doUpdateVisitedHistory(this, view, url, isReload, reply -> {});
}
@Override
public void onReceivedHttpAuthRequest(
@NonNull WebView view,
@NonNull HttpAuthHandler handler,
@NonNull String host,
@NonNull String realm) {
flutterApi.onReceivedHttpAuthRequest(this, view, handler, host, realm, reply -> {});
}
@Override
public void onUnhandledKeyEvent(@NonNull WebView view, @NonNull KeyEvent event) {
// Deliberately empty. Occasionally the webview will mark events as having failed to be
// handled even though they were handled. We don't want to propagate those as they're not
// truly lost.
}
/** Sets return value for {@link #shouldOverrideUrlLoading}. */
public void setReturnValueForShouldOverrideUrlLoading(boolean value) {
returnValueForShouldOverrideUrlLoading = value;
}
}
/**
* Implementation of {@link WebViewClientCompat} that passes arguments of callback methods to
* Dart.
*/
public static class WebViewClientCompatImpl extends WebViewClientCompat {
private final WebViewClientFlutterApiImpl flutterApi;
private boolean returnValueForShouldOverrideUrlLoading = false;
public WebViewClientCompatImpl(@NonNull WebViewClientFlutterApiImpl flutterApi) {
this.flutterApi = flutterApi;
}
@Override
public void onPageStarted(@NonNull WebView view, @NonNull String url, @NonNull Bitmap favicon) {
flutterApi.onPageStarted(this, view, url, reply -> {});
}
@Override
public void onPageFinished(@NonNull WebView view, @NonNull String url) {
flutterApi.onPageFinished(this, view, url, reply -> {});
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceivedHttpError(
@NonNull WebView view,
@NonNull WebResourceRequest request,
@NonNull WebResourceResponse response) {
flutterApi.onReceivedHttpError(this, view, request, response, reply -> {});
}
// This method is only called when the WebViewFeature.RECEIVE_WEB_RESOURCE_ERROR feature is
// enabled. The deprecated method is called when a device doesn't support this.
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("RequiresFeature")
@Override
public void onReceivedError(
@NonNull WebView view,
@NonNull WebResourceRequest request,
@NonNull WebResourceErrorCompat error) {
flutterApi.onReceivedRequestError(this, view, request, error, reply -> {});
}
// Legacy codepath for versions that don't support the variant above.
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(
@NonNull WebView view,
int errorCode,
@NonNull String description,
@NonNull String failingUrl) {
flutterApi.onReceivedError(
this, view, (long) errorCode, description, failingUrl, reply -> {});
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(
@NonNull WebView view, @NonNull WebResourceRequest request) {
flutterApi.requestLoading(this, view, request, reply -> {});
return returnValueForShouldOverrideUrlLoading;
}
// Legacy codepath for < Lollipop; newer versions use the variant above.
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(@NonNull WebView view, @NonNull String url) {
flutterApi.urlLoading(this, view, url, reply -> {});
return returnValueForShouldOverrideUrlLoading;
}
@Override
public void doUpdateVisitedHistory(
@NonNull WebView view, @NonNull String url, boolean isReload) {
flutterApi.doUpdateVisitedHistory(this, view, url, isReload, reply -> {});
}
// Handles an HTTP authentication request.
//
// This callback is invoked when the WebView encounters a website requiring HTTP authentication.
// [host] and [realm] are provided for matching against stored credentials, if any.
@Override
public void onReceivedHttpAuthRequest(
@NonNull WebView view, HttpAuthHandler handler, String host, String realm) {
flutterApi.onReceivedHttpAuthRequest(this, view, handler, host, realm, reply -> {});
}
@Override
public void onUnhandledKeyEvent(@NonNull WebView view, @NonNull KeyEvent event) {
// Deliberately empty. Occasionally the webview will mark events as having failed to be
// handled even though they were handled. We don't want to propagate those as they're not
// truly lost.
}
/** Sets return value for {@link #shouldOverrideUrlLoading}. */
public void setReturnValueForShouldOverrideUrlLoading(boolean value) {
returnValueForShouldOverrideUrlLoading = value;
}
}
/** Handles creating {@link WebViewClient}s for a {@link WebViewClientHostApiImpl}. */
public static class WebViewClientCreator {
/**
* Creates a {@link WebViewClient}.
*
* @param flutterApi handles sending messages to Dart
* @return the created {@link WebViewClient}
*/
@NonNull
public WebViewClient createWebViewClient(@NonNull WebViewClientFlutterApiImpl flutterApi) {
// WebViewClientCompat is used to get
// shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
// invoked by the webview on older Android devices, without it pages that use iframes will
// be broken when a navigationDelegate is set on Android version earlier than N.
//
// However, this if statement attempts to avoid using WebViewClientCompat on versions >= N due
// to bug https://bugs.chromium.org/p/chromium/issues/detail?id=925887. Also, see
// https://github.com/flutter/flutter/issues/29446.
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return new WebViewClientImpl(flutterApi);
} else {
return new WebViewClientCompatImpl(flutterApi);
}
}
}
/**
* Creates a host API that handles creating {@link WebViewClient}s.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param webViewClientCreator handles creating {@link WebViewClient}s
* @param flutterApi handles sending messages to Dart
*/
public WebViewClientHostApiImpl(
@NonNull InstanceManager instanceManager,
@NonNull WebViewClientCreator webViewClientCreator,
@NonNull WebViewClientFlutterApiImpl flutterApi) {
this.instanceManager = instanceManager;
this.webViewClientCreator = webViewClientCreator;
this.flutterApi = flutterApi;
}
@Override
public void create(@NonNull Long instanceId) {
final WebViewClient webViewClient = webViewClientCreator.createWebViewClient(flutterApi);
instanceManager.addDartCreatedInstance(webViewClient, instanceId);
}
@Override
public void setSynchronousReturnValueForShouldOverrideUrlLoading(
@NonNull Long instanceId, @NonNull Boolean value) {
final WebViewClient webViewClient =
Objects.requireNonNull(instanceManager.getInstance(instanceId));
if (webViewClient instanceof WebViewClientCompatImpl) {
((WebViewClientCompatImpl) webViewClient).setReturnValueForShouldOverrideUrlLoading(value);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
&& webViewClient instanceof WebViewClientImpl) {
((WebViewClientImpl) webViewClient).setReturnValueForShouldOverrideUrlLoading(value);
} else {
throw new IllegalStateException(
"This WebViewClient doesn't support setting the returnValueForShouldOverrideUrlLoading.");
}
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewClientHostApiImpl.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewClientHostApiImpl.java",
"repo_id": "packages",
"token_count": 3854
} | 1,109 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.webviewflutter;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import android.webkit.PermissionRequest;
import io.flutter.plugin.common.BinaryMessenger;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class PermissionRequestTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public PermissionRequest mockPermissionRequest;
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock
public io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.PermissionRequestFlutterApi
mockFlutterApi;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
// These values MUST equal the constants for the Dart PermissionRequest class.
@Test
public void enums() {
assertEquals(PermissionRequest.RESOURCE_AUDIO_CAPTURE, "android.webkit.resource.AUDIO_CAPTURE");
assertEquals(PermissionRequest.RESOURCE_VIDEO_CAPTURE, "android.webkit.resource.VIDEO_CAPTURE");
assertEquals(PermissionRequest.RESOURCE_MIDI_SYSEX, "android.webkit.resource.MIDI_SYSEX");
assertEquals(
PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID,
"android.webkit.resource.PROTECTED_MEDIA_ID");
}
@Test
public void grant() {
final List<String> resources =
Collections.singletonList(PermissionRequest.RESOURCE_AUDIO_CAPTURE);
final long instanceIdentifier = 0;
instanceManager.addDartCreatedInstance(mockPermissionRequest, instanceIdentifier);
final PermissionRequestHostApiImpl hostApi =
new PermissionRequestHostApiImpl(mockBinaryMessenger, instanceManager);
hostApi.grant(instanceIdentifier, resources);
verify(mockPermissionRequest).grant(new String[] {PermissionRequest.RESOURCE_AUDIO_CAPTURE});
}
@Test
public void deny() {
final long instanceIdentifier = 0;
instanceManager.addDartCreatedInstance(mockPermissionRequest, instanceIdentifier);
final PermissionRequestHostApiImpl hostApi =
new PermissionRequestHostApiImpl(mockBinaryMessenger, instanceManager);
hostApi.deny(instanceIdentifier);
verify(mockPermissionRequest).deny();
}
@Test
public void flutterApiCreate() {
final PermissionRequestFlutterApiImpl flutterApi =
new PermissionRequestFlutterApiImpl(mockBinaryMessenger, instanceManager);
flutterApi.setApi(mockFlutterApi);
final List<String> resources =
Collections.singletonList(PermissionRequest.RESOURCE_AUDIO_CAPTURE);
flutterApi.create(mockPermissionRequest, resources.toArray(new String[0]), reply -> {});
final long instanceIdentifier =
Objects.requireNonNull(
instanceManager.getIdentifierForStrongReference(mockPermissionRequest));
verify(mockFlutterApi).create(eq(instanceIdentifier), eq(resources), any());
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/PermissionRequestTest.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/PermissionRequestTest.java",
"repo_id": "packages",
"token_count": 1159
} | 1,110 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/webview_flutter/webview_flutter_android/example/android/gradle.properties/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 30
} | 1,111 |
name: webview_flutter_android
description: A Flutter plugin that provides a WebView widget on Android.
repository: https://github.com/flutter/packages/tree/main/packages/webview_flutter/webview_flutter_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22
version: 3.16.0
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: webview_flutter
platforms:
android:
package: io.flutter.plugins.webviewflutter
pluginClass: WebViewFlutterPlugin
dartPluginClass: AndroidWebViewPlatform
dependencies:
flutter:
sdk: flutter
webview_flutter_platform_interface: ^2.10.0
dev_dependencies:
build_runner: ^2.1.4
flutter_test:
sdk: flutter
mockito: 5.4.4
pigeon: ^11.0.0
topics:
- html
- webview
- webview-flutter | packages/packages/webview_flutter/webview_flutter_android/pubspec.yaml/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/pubspec.yaml",
"repo_id": "packages",
"token_count": 347
} | 1,112 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v11.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import
// ignore_for_file: avoid_relative_lib_imports
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:webview_flutter_android/src/android_webview.g.dart';
/// Host API for managing the native `InstanceManager`.
abstract class TestInstanceManagerHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Clear the native `InstanceManager`.
///
/// This is typically only used after a hot restart.
void clear();
static void setup(TestInstanceManagerHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.InstanceManagerHostApi.clear',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
// ignore message
api.clear();
return <Object?>[];
});
}
}
}
}
/// Handles methods calls to the native Java Object class.
///
/// Also handles calls to remove the reference to an instance with `dispose`.
///
/// See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html.
abstract class TestJavaObjectHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
void dispose(int identifier);
static void setup(TestJavaObjectHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.JavaObjectHostApi.dispose',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.JavaObjectHostApi.dispose was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.JavaObjectHostApi.dispose was null, expected non-null int.');
api.dispose(arg_identifier!);
return <Object?>[];
});
}
}
}
}
/// Host API for `CookieManager`.
///
/// This class may handle instantiating and adding native object instances that
/// are attached to a Dart instance or handle method calls on the associated
/// native class or an instance of the class.
abstract class TestCookieManagerHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Handles attaching `CookieManager.instance` to a native instance.
void attachInstance(int instanceIdentifier);
/// Handles Dart method `CookieManager.setCookie`.
void setCookie(int identifier, String url, String value);
/// Handles Dart method `CookieManager.removeAllCookies`.
Future<bool> removeAllCookies(int identifier);
/// Handles Dart method `CookieManager.setAcceptThirdPartyCookies`.
void setAcceptThirdPartyCookies(
int identifier, int webViewIdentifier, bool accept);
static void setup(TestCookieManagerHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.attachInstance',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.attachInstance was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceIdentifier = (args[0] as int?);
assert(arg_instanceIdentifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.attachInstance was null, expected non-null int.');
api.attachInstance(arg_instanceIdentifier!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setCookie',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setCookie was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setCookie was null, expected non-null int.');
final String? arg_url = (args[1] as String?);
assert(arg_url != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setCookie was null, expected non-null String.');
final String? arg_value = (args[2] as String?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setCookie was null, expected non-null String.');
api.setCookie(arg_identifier!, arg_url!, arg_value!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.removeAllCookies',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.removeAllCookies was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.removeAllCookies was null, expected non-null int.');
final bool output = await api.removeAllCookies(arg_identifier!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setAcceptThirdPartyCookies',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setAcceptThirdPartyCookies was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setAcceptThirdPartyCookies was null, expected non-null int.');
final int? arg_webViewIdentifier = (args[1] as int?);
assert(arg_webViewIdentifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setAcceptThirdPartyCookies was null, expected non-null int.');
final bool? arg_accept = (args[2] as bool?);
assert(arg_accept != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setAcceptThirdPartyCookies was null, expected non-null bool.');
api.setAcceptThirdPartyCookies(
arg_identifier!, arg_webViewIdentifier!, arg_accept!);
return <Object?>[];
});
}
}
}
}
class _TestWebViewHostApiCodec extends StandardMessageCodec {
const _TestWebViewHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is WebViewPoint) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return WebViewPoint.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestWebViewHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = _TestWebViewHostApiCodec();
void create(int instanceId);
void loadData(
int instanceId, String data, String? mimeType, String? encoding);
void loadDataWithBaseUrl(int instanceId, String? baseUrl, String data,
String? mimeType, String? encoding, String? historyUrl);
void loadUrl(int instanceId, String url, Map<String?, String?> headers);
void postUrl(int instanceId, String url, Uint8List data);
String? getUrl(int instanceId);
bool canGoBack(int instanceId);
bool canGoForward(int instanceId);
void goBack(int instanceId);
void goForward(int instanceId);
void reload(int instanceId);
void clearCache(int instanceId, bool includeDiskFiles);
Future<String?> evaluateJavascript(int instanceId, String javascriptString);
String? getTitle(int instanceId);
void scrollTo(int instanceId, int x, int y);
void scrollBy(int instanceId, int x, int y);
int getScrollX(int instanceId);
int getScrollY(int instanceId);
WebViewPoint getScrollPosition(int instanceId);
void setWebContentsDebuggingEnabled(bool enabled);
void setWebViewClient(int instanceId, int webViewClientInstanceId);
void addJavaScriptChannel(int instanceId, int javaScriptChannelInstanceId);
void removeJavaScriptChannel(int instanceId, int javaScriptChannelInstanceId);
void setDownloadListener(int instanceId, int? listenerInstanceId);
void setWebChromeClient(int instanceId, int? clientInstanceId);
void setBackgroundColor(int instanceId, int color);
static void setup(TestWebViewHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.create was null, expected non-null int.');
api.create(arg_instanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadData',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadData was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadData was null, expected non-null int.');
final String? arg_data = (args[1] as String?);
assert(arg_data != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadData was null, expected non-null String.');
final String? arg_mimeType = (args[2] as String?);
final String? arg_encoding = (args[3] as String?);
api.loadData(arg_instanceId!, arg_data!, arg_mimeType, arg_encoding);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadDataWithBaseUrl',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadDataWithBaseUrl was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadDataWithBaseUrl was null, expected non-null int.');
final String? arg_baseUrl = (args[1] as String?);
final String? arg_data = (args[2] as String?);
assert(arg_data != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadDataWithBaseUrl was null, expected non-null String.');
final String? arg_mimeType = (args[3] as String?);
final String? arg_encoding = (args[4] as String?);
final String? arg_historyUrl = (args[5] as String?);
api.loadDataWithBaseUrl(arg_instanceId!, arg_baseUrl, arg_data!,
arg_mimeType, arg_encoding, arg_historyUrl);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadUrl',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadUrl was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadUrl was null, expected non-null int.');
final String? arg_url = (args[1] as String?);
assert(arg_url != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadUrl was null, expected non-null String.');
final Map<String?, String?>? arg_headers =
(args[2] as Map<Object?, Object?>?)?.cast<String?, String?>();
assert(arg_headers != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadUrl was null, expected non-null Map<String?, String?>.');
api.loadUrl(arg_instanceId!, arg_url!, arg_headers!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.postUrl',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.postUrl was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.postUrl was null, expected non-null int.');
final String? arg_url = (args[1] as String?);
assert(arg_url != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.postUrl was null, expected non-null String.');
final Uint8List? arg_data = (args[2] as Uint8List?);
assert(arg_data != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.postUrl was null, expected non-null Uint8List.');
api.postUrl(arg_instanceId!, arg_url!, arg_data!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getUrl',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getUrl was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getUrl was null, expected non-null int.');
final String? output = api.getUrl(arg_instanceId!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoBack',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoBack was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoBack was null, expected non-null int.');
final bool output = api.canGoBack(arg_instanceId!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoForward',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoForward was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoForward was null, expected non-null int.');
final bool output = api.canGoForward(arg_instanceId!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goBack',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goBack was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goBack was null, expected non-null int.');
api.goBack(arg_instanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goForward',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goForward was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goForward was null, expected non-null int.');
api.goForward(arg_instanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.reload',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.reload was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.reload was null, expected non-null int.');
api.reload(arg_instanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.clearCache',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.clearCache was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.clearCache was null, expected non-null int.');
final bool? arg_includeDiskFiles = (args[1] as bool?);
assert(arg_includeDiskFiles != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.clearCache was null, expected non-null bool.');
api.clearCache(arg_instanceId!, arg_includeDiskFiles!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.evaluateJavascript',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.evaluateJavascript was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.evaluateJavascript was null, expected non-null int.');
final String? arg_javascriptString = (args[1] as String?);
assert(arg_javascriptString != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.evaluateJavascript was null, expected non-null String.');
final String? output = await api.evaluateJavascript(
arg_instanceId!, arg_javascriptString!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getTitle',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getTitle was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getTitle was null, expected non-null int.');
final String? output = api.getTitle(arg_instanceId!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollTo',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollTo was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollTo was null, expected non-null int.');
final int? arg_x = (args[1] as int?);
assert(arg_x != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollTo was null, expected non-null int.');
final int? arg_y = (args[2] as int?);
assert(arg_y != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollTo was null, expected non-null int.');
api.scrollTo(arg_instanceId!, arg_x!, arg_y!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollBy',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollBy was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollBy was null, expected non-null int.');
final int? arg_x = (args[1] as int?);
assert(arg_x != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollBy was null, expected non-null int.');
final int? arg_y = (args[2] as int?);
assert(arg_y != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollBy was null, expected non-null int.');
api.scrollBy(arg_instanceId!, arg_x!, arg_y!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollX',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollX was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollX was null, expected non-null int.');
final int output = api.getScrollX(arg_instanceId!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollY',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollY was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollY was null, expected non-null int.');
final int output = api.getScrollY(arg_instanceId!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollPosition',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollPosition was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollPosition was null, expected non-null int.');
final WebViewPoint output = api.getScrollPosition(arg_instanceId!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebContentsDebuggingEnabled',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebContentsDebuggingEnabled was null.');
final List<Object?> args = (message as List<Object?>?)!;
final bool? arg_enabled = (args[0] as bool?);
assert(arg_enabled != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebContentsDebuggingEnabled was null, expected non-null bool.');
api.setWebContentsDebuggingEnabled(arg_enabled!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebViewClient',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebViewClient was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebViewClient was null, expected non-null int.');
final int? arg_webViewClientInstanceId = (args[1] as int?);
assert(arg_webViewClientInstanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebViewClient was null, expected non-null int.');
api.setWebViewClient(arg_instanceId!, arg_webViewClientInstanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.addJavaScriptChannel',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.addJavaScriptChannel was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.addJavaScriptChannel was null, expected non-null int.');
final int? arg_javaScriptChannelInstanceId = (args[1] as int?);
assert(arg_javaScriptChannelInstanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.addJavaScriptChannel was null, expected non-null int.');
api.addJavaScriptChannel(
arg_instanceId!, arg_javaScriptChannelInstanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.removeJavaScriptChannel',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.removeJavaScriptChannel was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.removeJavaScriptChannel was null, expected non-null int.');
final int? arg_javaScriptChannelInstanceId = (args[1] as int?);
assert(arg_javaScriptChannelInstanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.removeJavaScriptChannel was null, expected non-null int.');
api.removeJavaScriptChannel(
arg_instanceId!, arg_javaScriptChannelInstanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setDownloadListener',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setDownloadListener was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setDownloadListener was null, expected non-null int.');
final int? arg_listenerInstanceId = (args[1] as int?);
api.setDownloadListener(arg_instanceId!, arg_listenerInstanceId);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebChromeClient',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebChromeClient was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebChromeClient was null, expected non-null int.');
final int? arg_clientInstanceId = (args[1] as int?);
api.setWebChromeClient(arg_instanceId!, arg_clientInstanceId);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setBackgroundColor',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setBackgroundColor was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setBackgroundColor was null, expected non-null int.');
final int? arg_color = (args[1] as int?);
assert(arg_color != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setBackgroundColor was null, expected non-null int.');
api.setBackgroundColor(arg_instanceId!, arg_color!);
return <Object?>[];
});
}
}
}
}
abstract class TestWebSettingsHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
void create(int instanceId, int webViewInstanceId);
void setDomStorageEnabled(int instanceId, bool flag);
void setJavaScriptCanOpenWindowsAutomatically(int instanceId, bool flag);
void setSupportMultipleWindows(int instanceId, bool support);
void setJavaScriptEnabled(int instanceId, bool flag);
void setUserAgentString(int instanceId, String? userAgentString);
void setMediaPlaybackRequiresUserGesture(int instanceId, bool require);
void setSupportZoom(int instanceId, bool support);
void setLoadWithOverviewMode(int instanceId, bool overview);
void setUseWideViewPort(int instanceId, bool use);
void setDisplayZoomControls(int instanceId, bool enabled);
void setBuiltInZoomControls(int instanceId, bool enabled);
void setAllowFileAccess(int instanceId, bool enabled);
void setTextZoom(int instanceId, int textZoom);
String getUserAgentString(int instanceId);
static void setup(TestWebSettingsHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.create was null, expected non-null int.');
final int? arg_webViewInstanceId = (args[1] as int?);
assert(arg_webViewInstanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.create was null, expected non-null int.');
api.create(arg_instanceId!, arg_webViewInstanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDomStorageEnabled',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDomStorageEnabled was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDomStorageEnabled was null, expected non-null int.');
final bool? arg_flag = (args[1] as bool?);
assert(arg_flag != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDomStorageEnabled was null, expected non-null bool.');
api.setDomStorageEnabled(arg_instanceId!, arg_flag!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptCanOpenWindowsAutomatically',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptCanOpenWindowsAutomatically was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptCanOpenWindowsAutomatically was null, expected non-null int.');
final bool? arg_flag = (args[1] as bool?);
assert(arg_flag != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptCanOpenWindowsAutomatically was null, expected non-null bool.');
api.setJavaScriptCanOpenWindowsAutomatically(
arg_instanceId!, arg_flag!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportMultipleWindows',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportMultipleWindows was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportMultipleWindows was null, expected non-null int.');
final bool? arg_support = (args[1] as bool?);
assert(arg_support != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportMultipleWindows was null, expected non-null bool.');
api.setSupportMultipleWindows(arg_instanceId!, arg_support!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptEnabled',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptEnabled was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptEnabled was null, expected non-null int.');
final bool? arg_flag = (args[1] as bool?);
assert(arg_flag != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptEnabled was null, expected non-null bool.');
api.setJavaScriptEnabled(arg_instanceId!, arg_flag!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUserAgentString',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUserAgentString was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUserAgentString was null, expected non-null int.');
final String? arg_userAgentString = (args[1] as String?);
api.setUserAgentString(arg_instanceId!, arg_userAgentString);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setMediaPlaybackRequiresUserGesture',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setMediaPlaybackRequiresUserGesture was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setMediaPlaybackRequiresUserGesture was null, expected non-null int.');
final bool? arg_require = (args[1] as bool?);
assert(arg_require != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setMediaPlaybackRequiresUserGesture was null, expected non-null bool.');
api.setMediaPlaybackRequiresUserGesture(
arg_instanceId!, arg_require!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportZoom',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportZoom was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportZoom was null, expected non-null int.');
final bool? arg_support = (args[1] as bool?);
assert(arg_support != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportZoom was null, expected non-null bool.');
api.setSupportZoom(arg_instanceId!, arg_support!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setLoadWithOverviewMode',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setLoadWithOverviewMode was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setLoadWithOverviewMode was null, expected non-null int.');
final bool? arg_overview = (args[1] as bool?);
assert(arg_overview != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setLoadWithOverviewMode was null, expected non-null bool.');
api.setLoadWithOverviewMode(arg_instanceId!, arg_overview!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUseWideViewPort',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUseWideViewPort was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUseWideViewPort was null, expected non-null int.');
final bool? arg_use = (args[1] as bool?);
assert(arg_use != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUseWideViewPort was null, expected non-null bool.');
api.setUseWideViewPort(arg_instanceId!, arg_use!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDisplayZoomControls',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDisplayZoomControls was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDisplayZoomControls was null, expected non-null int.');
final bool? arg_enabled = (args[1] as bool?);
assert(arg_enabled != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDisplayZoomControls was null, expected non-null bool.');
api.setDisplayZoomControls(arg_instanceId!, arg_enabled!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setBuiltInZoomControls',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setBuiltInZoomControls was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setBuiltInZoomControls was null, expected non-null int.');
final bool? arg_enabled = (args[1] as bool?);
assert(arg_enabled != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setBuiltInZoomControls was null, expected non-null bool.');
api.setBuiltInZoomControls(arg_instanceId!, arg_enabled!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setAllowFileAccess',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setAllowFileAccess was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setAllowFileAccess was null, expected non-null int.');
final bool? arg_enabled = (args[1] as bool?);
assert(arg_enabled != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setAllowFileAccess was null, expected non-null bool.');
api.setAllowFileAccess(arg_instanceId!, arg_enabled!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setTextZoom',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setTextZoom was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setTextZoom was null, expected non-null int.');
final int? arg_textZoom = (args[1] as int?);
assert(arg_textZoom != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setTextZoom was null, expected non-null int.');
api.setTextZoom(arg_instanceId!, arg_textZoom!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.getUserAgentString',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.getUserAgentString was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.getUserAgentString was null, expected non-null int.');
final String output = api.getUserAgentString(arg_instanceId!);
return <Object?>[output];
});
}
}
}
}
abstract class TestJavaScriptChannelHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
void create(int instanceId, String channelName);
static void setup(TestJavaScriptChannelHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelHostApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelHostApi.create was null, expected non-null int.');
final String? arg_channelName = (args[1] as String?);
assert(arg_channelName != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelHostApi.create was null, expected non-null String.');
api.create(arg_instanceId!, arg_channelName!);
return <Object?>[];
});
}
}
}
}
abstract class TestWebViewClientHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
void create(int instanceId);
void setSynchronousReturnValueForShouldOverrideUrlLoading(
int instanceId, bool value);
static void setup(TestWebViewClientHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.create was null, expected non-null int.');
api.create(arg_instanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading was null, expected non-null int.');
final bool? arg_value = (args[1] as bool?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading was null, expected non-null bool.');
api.setSynchronousReturnValueForShouldOverrideUrlLoading(
arg_instanceId!, arg_value!);
return <Object?>[];
});
}
}
}
}
abstract class TestDownloadListenerHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
void create(int instanceId);
static void setup(TestDownloadListenerHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.DownloadListenerHostApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.DownloadListenerHostApi.create was null, expected non-null int.');
api.create(arg_instanceId!);
return <Object?>[];
});
}
}
}
}
abstract class TestWebChromeClientHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
void create(int instanceId);
void setSynchronousReturnValueForOnShowFileChooser(
int instanceId, bool value);
void setSynchronousReturnValueForOnConsoleMessage(int instanceId, bool value);
void setSynchronousReturnValueForOnJsAlert(int instanceId, bool value);
void setSynchronousReturnValueForOnJsConfirm(int instanceId, bool value);
void setSynchronousReturnValueForOnJsPrompt(int instanceId, bool value);
static void setup(TestWebChromeClientHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.create was null, expected non-null int.');
api.create(arg_instanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnShowFileChooser',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnShowFileChooser was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnShowFileChooser was null, expected non-null int.');
final bool? arg_value = (args[1] as bool?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnShowFileChooser was null, expected non-null bool.');
api.setSynchronousReturnValueForOnShowFileChooser(
arg_instanceId!, arg_value!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnConsoleMessage',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnConsoleMessage was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnConsoleMessage was null, expected non-null int.');
final bool? arg_value = (args[1] as bool?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnConsoleMessage was null, expected non-null bool.');
api.setSynchronousReturnValueForOnConsoleMessage(
arg_instanceId!, arg_value!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsAlert',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsAlert was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsAlert was null, expected non-null int.');
final bool? arg_value = (args[1] as bool?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsAlert was null, expected non-null bool.');
api.setSynchronousReturnValueForOnJsAlert(
arg_instanceId!, arg_value!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsConfirm',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsConfirm was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsConfirm was null, expected non-null int.');
final bool? arg_value = (args[1] as bool?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsConfirm was null, expected non-null bool.');
api.setSynchronousReturnValueForOnJsConfirm(
arg_instanceId!, arg_value!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsPrompt',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsPrompt was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsPrompt was null, expected non-null int.');
final bool? arg_value = (args[1] as bool?);
assert(arg_value != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsPrompt was null, expected non-null bool.');
api.setSynchronousReturnValueForOnJsPrompt(
arg_instanceId!, arg_value!);
return <Object?>[];
});
}
}
}
}
abstract class TestAssetManagerHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
List<String?> list(String path);
String getAssetFilePathByName(String name);
static void setup(TestAssetManagerHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.list',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.list was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_path = (args[0] as String?);
assert(arg_path != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.list was null, expected non-null String.');
final List<String?> output = api.list(arg_path!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.getAssetFilePathByName',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.getAssetFilePathByName was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_name = (args[0] as String?);
assert(arg_name != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.getAssetFilePathByName was null, expected non-null String.');
final String output = api.getAssetFilePathByName(arg_name!);
return <Object?>[output];
});
}
}
}
}
abstract class TestWebStorageHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
void create(int instanceId);
void deleteAllData(int instanceId);
static void setup(TestWebStorageHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.create was null, expected non-null int.');
api.create(arg_instanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.deleteAllData',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.deleteAllData was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.deleteAllData was null, expected non-null int.');
api.deleteAllData(arg_instanceId!);
return <Object?>[];
});
}
}
}
}
/// Host API for `PermissionRequest`.
///
/// This class may handle instantiating and adding native object instances that
/// are attached to a Dart instance or handle method calls on the associated
/// native class or an instance of the class.
///
/// See https://developer.android.com/reference/android/webkit/PermissionRequest.
abstract class TestPermissionRequestHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Handles Dart method `PermissionRequest.grant`.
void grant(int instanceId, List<String?> resources);
/// Handles Dart method `PermissionRequest.deny`.
void deny(int instanceId);
static void setup(TestPermissionRequestHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.grant',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.grant was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.grant was null, expected non-null int.');
final List<String?>? arg_resources =
(args[1] as List<Object?>?)?.cast<String?>();
assert(arg_resources != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.grant was null, expected non-null List<String?>.');
api.grant(arg_instanceId!, arg_resources!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.deny',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.deny was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.deny was null, expected non-null int.');
api.deny(arg_instanceId!);
return <Object?>[];
});
}
}
}
}
/// Host API for `CustomViewCallback`.
///
/// This class may handle instantiating and adding native object instances that
/// are attached to a Dart instance or handle method calls on the associated
/// native class or an instance of the class.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.CustomViewCallback.
abstract class TestCustomViewCallbackHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Handles Dart method `CustomViewCallback.onCustomViewHidden`.
void onCustomViewHidden(int identifier);
static void setup(TestCustomViewCallbackHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackHostApi.onCustomViewHidden',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackHostApi.onCustomViewHidden was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackHostApi.onCustomViewHidden was null, expected non-null int.');
api.onCustomViewHidden(arg_identifier!);
return <Object?>[];
});
}
}
}
}
/// Host API for `GeolocationPermissionsCallback`.
///
/// This class may handle instantiating and adding native object instances that
/// are attached to a Dart instance or handle method calls on the associated
/// native class or an instance of the class.
///
/// See https://developer.android.com/reference/android/webkit/GeolocationPermissions.Callback.
abstract class TestGeolocationPermissionsCallbackHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Handles Dart method `GeolocationPermissionsCallback.invoke`.
void invoke(int instanceId, String origin, bool allow, bool retain);
static void setup(TestGeolocationPermissionsCallbackHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackHostApi.invoke',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackHostApi.invoke was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackHostApi.invoke was null, expected non-null int.');
final String? arg_origin = (args[1] as String?);
assert(arg_origin != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackHostApi.invoke was null, expected non-null String.');
final bool? arg_allow = (args[2] as bool?);
assert(arg_allow != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackHostApi.invoke was null, expected non-null bool.');
final bool? arg_retain = (args[3] as bool?);
assert(arg_retain != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackHostApi.invoke was null, expected non-null bool.');
api.invoke(arg_instanceId!, arg_origin!, arg_allow!, arg_retain!);
return <Object?>[];
});
}
}
}
}
/// Host API for `HttpAuthHandler`.
///
/// This class may handle instantiating and adding native object instances that
/// are attached to a Dart instance or handle method calls on the associated
/// native class or an instance of the class.
///
/// See https://developer.android.com/reference/android/webkit/HttpAuthHandler.
abstract class TestHttpAuthHandlerHostApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Handles Dart method `HttpAuthHandler.useHttpAuthUsernamePassword`.
bool useHttpAuthUsernamePassword(int instanceId);
/// Handles Dart method `HttpAuthHandler.cancel`.
void cancel(int instanceId);
/// Handles Dart method `HttpAuthHandler.proceed`.
void proceed(int instanceId, String username, String password);
static void setup(TestHttpAuthHandlerHostApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.useHttpAuthUsernamePassword',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.useHttpAuthUsernamePassword was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.useHttpAuthUsernamePassword was null, expected non-null int.');
final bool output = api.useHttpAuthUsernamePassword(arg_instanceId!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.cancel',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.cancel was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.cancel was null, expected non-null int.');
api.cancel(arg_instanceId!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.proceed',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.proceed was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_instanceId = (args[0] as int?);
assert(arg_instanceId != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.proceed was null, expected non-null int.');
final String? arg_username = (args[1] as String?);
assert(arg_username != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.proceed was null, expected non-null String.');
final String? arg_password = (args[2] as String?);
assert(arg_password != null,
'Argument for dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.proceed was null, expected non-null String.');
api.proceed(arg_instanceId!, arg_username!, arg_password!);
return <Object?>[];
});
}
}
}
}
| packages/packages/webview_flutter/webview_flutter_android/test/test_android_webview.g.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/test/test_android_webview.g.dart",
"repo_id": "packages",
"token_count": 42817
} | 1,113 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:meta/meta.dart';
import '../types/http_auth_request.dart';
/// Defines the response parameters of a pending [HttpAuthRequest] received by
/// the webview.
@immutable
class WebViewCredential {
/// Creates a [WebViewCredential].
const WebViewCredential({
required this.user,
required this.password,
});
/// The user name.
final String user;
/// The password.
final String password;
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/webview_credential.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/webview_credential.dart",
"repo_id": "packages",
"token_count": 176
} | 1,114 |
// Mocks generated by Mockito 5.4.4 from annotations
// in webview_flutter_web/test/web_webview_controller_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'dart:html' as _i2;
import 'package:mockito/mockito.dart' as _i1;
import 'package:mockito/src/dummies.dart' as _i3;
import 'package:webview_flutter_web/src/http_request_factory.dart' as _i5;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeHttpRequestUpload_0 extends _i1.SmartFake
implements _i2.HttpRequestUpload {
_FakeHttpRequestUpload_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeEvents_1 extends _i1.SmartFake implements _i2.Events {
_FakeEvents_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeHttpRequest_2 extends _i1.SmartFake implements _i2.HttpRequest {
_FakeHttpRequest_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [HttpRequest].
///
/// See the documentation for Mockito's code generation for more information.
class MockHttpRequest extends _i1.Mock implements _i2.HttpRequest {
@override
Map<String, String> get responseHeaders => (super.noSuchMethod(
Invocation.getter(#responseHeaders),
returnValue: <String, String>{},
returnValueForMissingStub: <String, String>{},
) as Map<String, String>);
@override
int get readyState => (super.noSuchMethod(
Invocation.getter(#readyState),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
String get responseType => (super.noSuchMethod(
Invocation.getter(#responseType),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#responseType),
),
returnValueForMissingStub: _i3.dummyValue<String>(
this,
Invocation.getter(#responseType),
),
) as String);
@override
set responseType(String? value) => super.noSuchMethod(
Invocation.setter(
#responseType,
value,
),
returnValueForMissingStub: null,
);
@override
set timeout(int? value) => super.noSuchMethod(
Invocation.setter(
#timeout,
value,
),
returnValueForMissingStub: null,
);
@override
_i2.HttpRequestUpload get upload => (super.noSuchMethod(
Invocation.getter(#upload),
returnValue: _FakeHttpRequestUpload_0(
this,
Invocation.getter(#upload),
),
returnValueForMissingStub: _FakeHttpRequestUpload_0(
this,
Invocation.getter(#upload),
),
) as _i2.HttpRequestUpload);
@override
set withCredentials(bool? value) => super.noSuchMethod(
Invocation.setter(
#withCredentials,
value,
),
returnValueForMissingStub: null,
);
@override
_i4.Stream<_i2.Event> get onReadyStateChange => (super.noSuchMethod(
Invocation.getter(#onReadyStateChange),
returnValue: _i4.Stream<_i2.Event>.empty(),
returnValueForMissingStub: _i4.Stream<_i2.Event>.empty(),
) as _i4.Stream<_i2.Event>);
@override
_i4.Stream<_i2.ProgressEvent> get onAbort => (super.noSuchMethod(
Invocation.getter(#onAbort),
returnValue: _i4.Stream<_i2.ProgressEvent>.empty(),
returnValueForMissingStub: _i4.Stream<_i2.ProgressEvent>.empty(),
) as _i4.Stream<_i2.ProgressEvent>);
@override
_i4.Stream<_i2.ProgressEvent> get onError => (super.noSuchMethod(
Invocation.getter(#onError),
returnValue: _i4.Stream<_i2.ProgressEvent>.empty(),
returnValueForMissingStub: _i4.Stream<_i2.ProgressEvent>.empty(),
) as _i4.Stream<_i2.ProgressEvent>);
@override
_i4.Stream<_i2.ProgressEvent> get onLoad => (super.noSuchMethod(
Invocation.getter(#onLoad),
returnValue: _i4.Stream<_i2.ProgressEvent>.empty(),
returnValueForMissingStub: _i4.Stream<_i2.ProgressEvent>.empty(),
) as _i4.Stream<_i2.ProgressEvent>);
@override
_i4.Stream<_i2.ProgressEvent> get onLoadEnd => (super.noSuchMethod(
Invocation.getter(#onLoadEnd),
returnValue: _i4.Stream<_i2.ProgressEvent>.empty(),
returnValueForMissingStub: _i4.Stream<_i2.ProgressEvent>.empty(),
) as _i4.Stream<_i2.ProgressEvent>);
@override
_i4.Stream<_i2.ProgressEvent> get onLoadStart => (super.noSuchMethod(
Invocation.getter(#onLoadStart),
returnValue: _i4.Stream<_i2.ProgressEvent>.empty(),
returnValueForMissingStub: _i4.Stream<_i2.ProgressEvent>.empty(),
) as _i4.Stream<_i2.ProgressEvent>);
@override
_i4.Stream<_i2.ProgressEvent> get onProgress => (super.noSuchMethod(
Invocation.getter(#onProgress),
returnValue: _i4.Stream<_i2.ProgressEvent>.empty(),
returnValueForMissingStub: _i4.Stream<_i2.ProgressEvent>.empty(),
) as _i4.Stream<_i2.ProgressEvent>);
@override
_i4.Stream<_i2.ProgressEvent> get onTimeout => (super.noSuchMethod(
Invocation.getter(#onTimeout),
returnValue: _i4.Stream<_i2.ProgressEvent>.empty(),
returnValueForMissingStub: _i4.Stream<_i2.ProgressEvent>.empty(),
) as _i4.Stream<_i2.ProgressEvent>);
@override
_i2.Events get on => (super.noSuchMethod(
Invocation.getter(#on),
returnValue: _FakeEvents_1(
this,
Invocation.getter(#on),
),
returnValueForMissingStub: _FakeEvents_1(
this,
Invocation.getter(#on),
),
) as _i2.Events);
@override
void open(
String? method,
String? url, {
bool? async,
String? user,
String? password,
}) =>
super.noSuchMethod(
Invocation.method(
#open,
[
method,
url,
],
{
#async: async,
#user: user,
#password: password,
},
),
returnValueForMissingStub: null,
);
@override
void abort() => super.noSuchMethod(
Invocation.method(
#abort,
[],
),
returnValueForMissingStub: null,
);
@override
String getAllResponseHeaders() => (super.noSuchMethod(
Invocation.method(
#getAllResponseHeaders,
[],
),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(
#getAllResponseHeaders,
[],
),
),
returnValueForMissingStub: _i3.dummyValue<String>(
this,
Invocation.method(
#getAllResponseHeaders,
[],
),
),
) as String);
@override
String? getResponseHeader(String? name) => (super.noSuchMethod(
Invocation.method(
#getResponseHeader,
[name],
),
returnValueForMissingStub: null,
) as String?);
@override
void overrideMimeType(String? mime) => super.noSuchMethod(
Invocation.method(
#overrideMimeType,
[mime],
),
returnValueForMissingStub: null,
);
@override
void send([dynamic body_OR_data]) => super.noSuchMethod(
Invocation.method(
#send,
[body_OR_data],
),
returnValueForMissingStub: null,
);
@override
void setRequestHeader(
String? name,
String? value,
) =>
super.noSuchMethod(
Invocation.method(
#setRequestHeader,
[
name,
value,
],
),
returnValueForMissingStub: null,
);
@override
void addEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#addEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
void removeEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#removeEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod(
Invocation.method(
#dispatchEvent,
[event],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
}
/// A class which mocks [HttpRequestFactory].
///
/// See the documentation for Mockito's code generation for more information.
class MockHttpRequestFactory extends _i1.Mock
implements _i5.HttpRequestFactory {
@override
_i4.Future<_i2.HttpRequest> request(
String? url, {
String? method,
bool? withCredentials,
String? responseType,
String? mimeType,
Map<String, String>? requestHeaders,
dynamic sendData,
void Function(_i2.ProgressEvent)? onProgress,
}) =>
(super.noSuchMethod(
Invocation.method(
#request,
[url],
{
#method: method,
#withCredentials: withCredentials,
#responseType: responseType,
#mimeType: mimeType,
#requestHeaders: requestHeaders,
#sendData: sendData,
#onProgress: onProgress,
},
),
returnValue: _i4.Future<_i2.HttpRequest>.value(_FakeHttpRequest_2(
this,
Invocation.method(
#request,
[url],
{
#method: method,
#withCredentials: withCredentials,
#responseType: responseType,
#mimeType: mimeType,
#requestHeaders: requestHeaders,
#sendData: sendData,
#onProgress: onProgress,
},
),
)),
returnValueForMissingStub:
_i4.Future<_i2.HttpRequest>.value(_FakeHttpRequest_2(
this,
Invocation.method(
#request,
[url],
{
#method: method,
#withCredentials: withCredentials,
#responseType: responseType,
#mimeType: mimeType,
#requestHeaders: requestHeaders,
#sendData: sendData,
#onProgress: onProgress,
},
),
)),
) as _i4.Future<_i2.HttpRequest>);
}
| packages/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.mocks.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_web/test/web_webview_controller_test.mocks.dart",
"repo_id": "packages",
"token_count": 5280
} | 1,115 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@import Flutter;
@import XCTest;
@import webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFURLCredentialHostApiTests : XCTestCase
@end
@implementation FWFURLCredentialHostApiTests
- (void)testHostApiCreate {
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
FWFURLCredentialHostApiImpl *hostApi = [[FWFURLCredentialHostApiImpl alloc]
initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger))
instanceManager:instanceManager];
FlutterError *error;
[hostApi createWithUserWithIdentifier:0
user:@"user"
password:@"password"
persistence:FWFNSUrlCredentialPersistencePermanent
error:&error];
XCTAssertNil(error);
NSURLCredential *credential = (NSURLCredential *)[instanceManager instanceForIdentifier:0];
XCTAssertEqualObjects(credential.user, @"user");
XCTAssertEqualObjects(credential.password, @"password");
XCTAssertEqual(credential.persistence, NSURLCredentialPersistencePermanent);
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFURLCredentialHostApiTests.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFURLCredentialHostApiTests.m",
"repo_id": "packages",
"token_count": 526
} | 1,116 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFObjectHostApi.h"
#import <objc/runtime.h>
#import "FWFDataConverters.h"
#import "FWFURLHostApi.h"
@interface FWFObjectFlutterApiImpl ()
// 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;
@end
@implementation FWFObjectFlutterApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self initWithBinaryMessenger:binaryMessenger];
if (self) {
_binaryMessenger = binaryMessenger;
_instanceManager = instanceManager;
}
return self;
}
- (long)identifierForObject:(NSObject *)instance {
return [self.instanceManager identifierWithStrongReferenceForInstance:instance];
}
- (void)observeValueForObject:(NSObject *)instance
keyPath:(NSString *)keyPath
object:(NSObject *)object
change:(NSDictionary<NSKeyValueChangeKey, id> *)change
completion:(void (^)(FlutterError *_Nullable))completion {
NSMutableArray<FWFNSKeyValueChangeKeyEnumData *> *changeKeys = [NSMutableArray array];
NSMutableArray<id> *changeValues = [NSMutableArray array];
[change enumerateKeysAndObjectsUsingBlock:^(NSKeyValueChangeKey key, id value, BOOL *stop) {
[changeKeys addObject:FWFNSKeyValueChangeKeyEnumDataFromNativeNSKeyValueChangeKey(key)];
BOOL isIdentifier = NO;
if ([self.instanceManager containsInstance:value]) {
isIdentifier = YES;
} else if (object_getClass(value) == [NSURL class]) {
FWFURLFlutterApiImpl *flutterApi =
[[FWFURLFlutterApiImpl alloc] initWithBinaryMessenger:self.binaryMessenger
instanceManager:self.instanceManager];
[flutterApi create:value
completion:^(FlutterError *error) {
NSAssert(!error, @"%@", error);
}];
isIdentifier = YES;
}
id returnValue = isIdentifier
? @([self.instanceManager identifierWithStrongReferenceForInstance:value])
: value;
[changeValues addObject:[FWFObjectOrIdentifier makeWithValue:returnValue
isIdentifier:isIdentifier]];
}];
NSInteger objectIdentifier =
[self.instanceManager identifierWithStrongReferenceForInstance:object];
[self observeValueForObjectWithIdentifier:[self identifierForObject:instance]
keyPath:keyPath
objectIdentifier:objectIdentifier
changeKeys:changeKeys
changeValues:changeValues
completion:completion];
}
@end
@implementation FWFObject
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_objectApi = [[FWFObjectFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager];
}
return self;
}
- (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);
}];
}
@end
@interface FWFObjectHostApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFObjectHostApiImpl
- (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (NSObject *)objectForIdentifier:(NSInteger)identifier {
return (NSObject *)[self.instanceManager instanceForIdentifier:identifier];
}
- (void)addObserverForObjectWithIdentifier:(NSInteger)identifier
observerIdentifier:(NSInteger)observer
keyPath:(nonnull NSString *)keyPath
options:
(nonnull NSArray<FWFNSKeyValueObservingOptionsEnumData *> *)
options
error:(FlutterError *_Nullable *_Nonnull)error {
NSKeyValueObservingOptions optionsInt = 0;
for (FWFNSKeyValueObservingOptionsEnumData *data in options) {
optionsInt |= FWFNativeNSKeyValueObservingOptionsFromEnumData(data);
}
[[self objectForIdentifier:identifier] addObserver:[self objectForIdentifier:observer]
forKeyPath:keyPath
options:optionsInt
context:nil];
}
- (void)removeObserverForObjectWithIdentifier:(NSInteger)identifier
observerIdentifier:(NSInteger)observer
keyPath:(nonnull NSString *)keyPath
error:(FlutterError *_Nullable *_Nonnull)error {
[[self objectForIdentifier:identifier] removeObserver:[self objectForIdentifier:observer]
forKeyPath:keyPath];
}
- (void)disposeObjectWithIdentifier:(NSInteger)identifier
error:(FlutterError *_Nullable *_Nonnull)error {
[self.instanceManager removeInstanceWithIdentifier:identifier];
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFObjectHostApi.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFObjectHostApi.m",
"repo_id": "packages",
"token_count": 2856
} | 1,117 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FWFURLCredentialHostApi.h"
@interface FWFURLCredentialHostApiImpl ()
// 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;
@end
@implementation FWFURLCredentialHostApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_binaryMessenger = binaryMessenger;
_instanceManager = instanceManager;
}
return self;
}
- (void)createWithUserWithIdentifier:(NSInteger)identifier
user:(nonnull NSString *)user
password:(nonnull NSString *)password
persistence:(FWFNSUrlCredentialPersistence)persistence
error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
[self.instanceManager
addDartCreatedInstance:
[NSURLCredential
credentialWithUser:user
password:password
persistence:
FWFNativeNSURLCredentialPersistenceFromFWFNSUrlCredentialPersistence(
persistence)]
withIdentifier:identifier];
}
- (nullable NSURL *)credentialForIdentifier:(NSNumber *)identifier
error:
(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
NSURL *instance = (NSURL *)[self.instanceManager instanceForIdentifier:identifier.longValue];
if (!instance) {
NSString *message =
[NSString stringWithFormat:@"InstanceManager does not contain an NSURL with identifier: %@",
identifier];
*error = [FlutterError errorWithCode:NSInternalInconsistencyException
message:message
details:nil];
}
return instance;
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLCredentialHostApi.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLCredentialHostApi.m",
"repo_id": "packages",
"token_count": 1011
} | 1,118 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Foundation/Foundation.h>
#import "FLTWebViewFlutterPlugin.h"
#import "FWFDataConverters.h"
#import "FWFGeneratedWebKitApis.h"
#import "FWFHTTPCookieStoreHostApi.h"
#import "FWFInstanceManager.h"
#import "FWFNavigationDelegateHostApi.h"
#import "FWFObjectHostApi.h"
#import "FWFPreferencesHostApi.h"
#import "FWFScriptMessageHandlerHostApi.h"
#import "FWFScrollViewDelegateHostApi.h"
#import "FWFScrollViewHostApi.h"
#import "FWFUIDelegateHostApi.h"
#import "FWFUIViewHostApi.h"
#import "FWFURLAuthenticationChallengeHostApi.h"
#import "FWFURLCredentialHostApi.h"
#import "FWFURLHostApi.h"
#import "FWFURLProtectionSpaceHostApi.h"
#import "FWFUserContentControllerHostApi.h"
#import "FWFWebViewConfigurationHostApi.h"
#import "FWFWebViewFlutterWKWebViewExternalAPI.h"
#import "FWFWebViewHostApi.h"
#import "FWFWebsiteDataStoreHostApi.h"
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/webview-umbrella.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/webview-umbrella.h",
"repo_id": "packages",
"token_count": 384
} | 1,119 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as path;
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'common/instance_manager.dart';
import 'common/weak_reference_utils.dart';
import 'foundation/foundation.dart';
import 'ui_kit/ui_kit.dart';
import 'web_kit/web_kit.dart';
import 'webkit_proxy.dart';
/// Media types that can require a user gesture to begin playing.
///
/// See [WebKitWebViewControllerCreationParams.mediaTypesRequiringUserAction].
enum PlaybackMediaTypes {
/// A media type that contains audio.
audio,
/// A media type that contains video.
video;
WKAudiovisualMediaType _toWKAudiovisualMediaType() {
switch (this) {
case PlaybackMediaTypes.audio:
return WKAudiovisualMediaType.audio;
case PlaybackMediaTypes.video:
return WKAudiovisualMediaType.video;
}
}
}
/// Object specifying creation parameters for a [WebKitWebViewController].
@immutable
class WebKitWebViewControllerCreationParams
extends PlatformWebViewControllerCreationParams {
/// Constructs a [WebKitWebViewControllerCreationParams].
WebKitWebViewControllerCreationParams({
@visibleForTesting this.webKitProxy = const WebKitProxy(),
this.mediaTypesRequiringUserAction = const <PlaybackMediaTypes>{
PlaybackMediaTypes.audio,
PlaybackMediaTypes.video,
},
this.allowsInlineMediaPlayback = false,
this.limitsNavigationsToAppBoundDomains = false,
@visibleForTesting InstanceManager? instanceManager,
}) : _instanceManager = instanceManager ?? NSObject.globalInstanceManager {
_configuration = webKitProxy.createWebViewConfiguration(
instanceManager: _instanceManager,
);
if (mediaTypesRequiringUserAction.isEmpty) {
_configuration.setMediaTypesRequiringUserActionForPlayback(
<WKAudiovisualMediaType>{WKAudiovisualMediaType.none},
);
} else {
_configuration.setMediaTypesRequiringUserActionForPlayback(
mediaTypesRequiringUserAction
.map<WKAudiovisualMediaType>(
(PlaybackMediaTypes type) => type._toWKAudiovisualMediaType(),
)
.toSet(),
);
}
_configuration.setAllowsInlineMediaPlayback(allowsInlineMediaPlayback);
// `WKWebViewConfiguration.limitsNavigationsToAppBoundDomains` is only
// supported on iOS versions 14+. So this only calls it if the value is set
// to true.
if (limitsNavigationsToAppBoundDomains) {
_configuration.setLimitsNavigationsToAppBoundDomains(
limitsNavigationsToAppBoundDomains,
);
}
}
/// Constructs a [WebKitWebViewControllerCreationParams] using a
/// [PlatformWebViewControllerCreationParams].
WebKitWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebViewControllerCreationParams params, {
@visibleForTesting WebKitProxy webKitProxy = const WebKitProxy(),
Set<PlaybackMediaTypes> mediaTypesRequiringUserAction =
const <PlaybackMediaTypes>{
PlaybackMediaTypes.audio,
PlaybackMediaTypes.video,
},
bool allowsInlineMediaPlayback = false,
bool limitsNavigationsToAppBoundDomains = false,
@visibleForTesting InstanceManager? instanceManager,
}) : this(
webKitProxy: webKitProxy,
mediaTypesRequiringUserAction: mediaTypesRequiringUserAction,
allowsInlineMediaPlayback: allowsInlineMediaPlayback,
limitsNavigationsToAppBoundDomains:
limitsNavigationsToAppBoundDomains,
instanceManager: instanceManager,
);
late final WKWebViewConfiguration _configuration;
/// Media types that require a user gesture to begin playing.
///
/// Defaults to include [PlaybackMediaTypes.audio] and
/// [PlaybackMediaTypes.video].
final Set<PlaybackMediaTypes> mediaTypesRequiringUserAction;
/// Whether inline playback of HTML5 videos is allowed.
///
/// Defaults to false.
final bool allowsInlineMediaPlayback;
/// Whether to limit navigation to configured domains.
///
/// See https://webkit.org/blog/10882/app-bound-domains/
/// (Only available for iOS > 14.0)
/// Defaults to false.
final bool limitsNavigationsToAppBoundDomains;
/// Handles constructing objects and calling static methods for the WebKit
/// native library.
@visibleForTesting
final WebKitProxy webKitProxy;
// Maintains instances used to communicate with the native objects they
// represent.
final InstanceManager _instanceManager;
}
/// An implementation of [PlatformWebViewController] with the WebKit api.
class WebKitWebViewController extends PlatformWebViewController {
/// Constructs a [WebKitWebViewController].
WebKitWebViewController(PlatformWebViewControllerCreationParams params)
: super.implementation(params is WebKitWebViewControllerCreationParams
? params
: WebKitWebViewControllerCreationParams
.fromPlatformWebViewControllerCreationParams(params)) {
_webView.addObserver(
_webView,
keyPath: 'estimatedProgress',
options: <NSKeyValueObservingOptions>{
NSKeyValueObservingOptions.newValue,
},
);
_webView.addObserver(
_webView,
keyPath: 'URL',
options: <NSKeyValueObservingOptions>{
NSKeyValueObservingOptions.newValue,
},
);
final WeakReference<WebKitWebViewController> weakThis =
WeakReference<WebKitWebViewController>(this);
_uiDelegate = _webKitParams.webKitProxy.createUIDelegate(
instanceManager: _webKitParams._instanceManager,
onCreateWebView: (
WKWebView webView,
WKWebViewConfiguration configuration,
WKNavigationAction navigationAction,
) {
if (!navigationAction.targetFrame.isMainFrame) {
webView.loadRequest(navigationAction.request);
}
},
requestMediaCapturePermission: (
WKUIDelegate instance,
WKWebView webView,
WKSecurityOrigin origin,
WKFrameInfo frame,
WKMediaCaptureType type,
) async {
final void Function(PlatformWebViewPermissionRequest)? callback =
weakThis.target?._onPermissionRequestCallback;
if (callback == null) {
// The default response for iOS is to prompt. See
// https://developer.apple.com/documentation/webkit/wkuidelegate/3763087-webview?language=objc
return WKPermissionDecision.prompt;
} else {
late final Set<WebViewPermissionResourceType> types;
switch (type) {
case WKMediaCaptureType.camera:
types = <WebViewPermissionResourceType>{
WebViewPermissionResourceType.camera
};
case WKMediaCaptureType.cameraAndMicrophone:
types = <WebViewPermissionResourceType>{
WebViewPermissionResourceType.camera,
WebViewPermissionResourceType.microphone
};
case WKMediaCaptureType.microphone:
types = <WebViewPermissionResourceType>{
WebViewPermissionResourceType.microphone
};
case WKMediaCaptureType.unknown:
// The default response for iOS is to prompt. See
// https://developer.apple.com/documentation/webkit/wkuidelegate/3763087-webview?language=objc
return WKPermissionDecision.prompt;
}
final Completer<WKPermissionDecision> decisionCompleter =
Completer<WKPermissionDecision>();
callback(
WebKitWebViewPermissionRequest._(
types: types,
onDecision: decisionCompleter.complete,
),
);
return decisionCompleter.future;
}
},
runJavaScriptAlertDialog: (String message, WKFrameInfo frame) async {
final Future<void> Function(JavaScriptAlertDialogRequest request)?
callback = weakThis.target?._onJavaScriptAlertDialog;
if (callback != null) {
final JavaScriptAlertDialogRequest request =
JavaScriptAlertDialogRequest(
message: message, url: frame.request.url);
await callback.call(request);
return;
}
},
runJavaScriptConfirmDialog: (String message, WKFrameInfo frame) async {
final Future<bool> Function(JavaScriptConfirmDialogRequest request)?
callback = weakThis.target?._onJavaScriptConfirmDialog;
if (callback != null) {
final JavaScriptConfirmDialogRequest request =
JavaScriptConfirmDialogRequest(
message: message, url: frame.request.url);
final bool result = await callback.call(request);
return result;
}
return false;
},
runJavaScriptTextInputDialog:
(String prompt, String defaultText, WKFrameInfo frame) async {
final Future<String> Function(JavaScriptTextInputDialogRequest request)?
callback = weakThis.target?._onJavaScriptTextInputDialog;
if (callback != null) {
final JavaScriptTextInputDialogRequest request =
JavaScriptTextInputDialogRequest(
message: prompt,
url: frame.request.url,
defaultText: defaultText);
final String result = await callback.call(request);
return result;
}
return '';
},
);
_webView.setUIDelegate(_uiDelegate);
}
/// The WebKit WebView being controlled.
late final WKWebView _webView = _webKitParams.webKitProxy.createWebView(
_webKitParams._configuration,
observeValue: withWeakReferenceTo(this, (
WeakReference<WebKitWebViewController> weakReference,
) {
return (
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) async {
final WebKitWebViewController? controller = weakReference.target;
if (controller == null) {
return;
}
switch (keyPath) {
case 'estimatedProgress':
final ProgressCallback? progressCallback =
controller._currentNavigationDelegate?._onProgress;
if (progressCallback != null) {
final double progress =
change[NSKeyValueChangeKey.newValue]! as double;
progressCallback((progress * 100).round());
}
case 'URL':
final UrlChangeCallback? urlChangeCallback =
controller._currentNavigationDelegate?._onUrlChange;
if (urlChangeCallback != null) {
final NSUrl? url = change[NSKeyValueChangeKey.newValue] as NSUrl?;
urlChangeCallback(UrlChange(url: await url?.getAbsoluteString()));
}
}
};
}),
instanceManager: _webKitParams._instanceManager,
);
late final WKUIDelegate _uiDelegate;
late final UIScrollViewDelegate? _uiScrollViewDelegate;
final Map<String, WebKitJavaScriptChannelParams> _javaScriptChannelParams =
<String, WebKitJavaScriptChannelParams>{};
bool _zoomEnabled = true;
WebKitNavigationDelegate? _currentNavigationDelegate;
void Function(JavaScriptConsoleMessage)? _onConsoleMessageCallback;
void Function(PlatformWebViewPermissionRequest)? _onPermissionRequestCallback;
Future<void> Function(JavaScriptAlertDialogRequest request)?
_onJavaScriptAlertDialog;
Future<bool> Function(JavaScriptConfirmDialogRequest request)?
_onJavaScriptConfirmDialog;
Future<String> Function(JavaScriptTextInputDialogRequest request)?
_onJavaScriptTextInputDialog;
void Function(ScrollPositionChange scrollPositionChange)?
_onScrollPositionChangeCallback;
WebKitWebViewControllerCreationParams get _webKitParams =>
params as WebKitWebViewControllerCreationParams;
/// Identifier used to retrieve the underlying native `WKWebView`.
///
/// This is typically used by other plugins to retrieve the native `WKWebView`
/// from an `FWFInstanceManager`.
///
/// See Objective-C method
/// `FLTWebViewFlutterPlugin:webViewForIdentifier:withPluginRegistry`.
int get webViewIdentifier =>
_webKitParams._instanceManager.getIdentifier(_webView)!;
@override
Future<void> loadFile(String absoluteFilePath) {
return _webView.loadFileUrl(
absoluteFilePath,
readAccessUrl: path.dirname(absoluteFilePath),
);
}
@override
Future<void> loadFlutterAsset(String key) {
assert(key.isNotEmpty);
return _webView.loadFlutterAsset(key);
}
@override
Future<void> loadHtmlString(String html, {String? baseUrl}) {
return _webView.loadHtmlString(html, baseUrl: baseUrl);
}
@override
Future<void> loadRequest(LoadRequestParams params) {
if (!params.uri.hasScheme) {
throw ArgumentError(
'LoadRequestParams#uri is required to have a scheme.',
);
}
return _webView.loadRequest(NSUrlRequest(
url: params.uri.toString(),
allHttpHeaderFields: params.headers,
httpMethod: params.method.name,
httpBody: params.body,
));
}
@override
Future<void> addJavaScriptChannel(
JavaScriptChannelParams javaScriptChannelParams,
) {
final String channelName = javaScriptChannelParams.name;
if (_javaScriptChannelParams.containsKey(channelName)) {
throw ArgumentError(
'A JavaScriptChannel with name `$channelName` already exists.',
);
}
final WebKitJavaScriptChannelParams webKitParams =
javaScriptChannelParams is WebKitJavaScriptChannelParams
? javaScriptChannelParams
: WebKitJavaScriptChannelParams.fromJavaScriptChannelParams(
javaScriptChannelParams,
);
_javaScriptChannelParams[webKitParams.name] = webKitParams;
final String wrapperSource =
'window.${webKitParams.name} = webkit.messageHandlers.${webKitParams.name};';
final WKUserScript wrapperScript = WKUserScript(
wrapperSource,
WKUserScriptInjectionTime.atDocumentStart,
isMainFrameOnly: false,
);
_webView.configuration.userContentController.addUserScript(wrapperScript);
return _webView.configuration.userContentController.addScriptMessageHandler(
webKitParams._messageHandler,
webKitParams.name,
);
}
@override
Future<void> removeJavaScriptChannel(String javaScriptChannelName) async {
assert(javaScriptChannelName.isNotEmpty);
if (!_javaScriptChannelParams.containsKey(javaScriptChannelName)) {
return;
}
await _resetUserScripts(removedJavaScriptChannel: javaScriptChannelName);
}
@override
Future<String?> currentUrl() => _webView.getUrl();
@override
Future<bool> canGoBack() => _webView.canGoBack();
@override
Future<bool> canGoForward() => _webView.canGoForward();
@override
Future<void> goBack() => _webView.goBack();
@override
Future<void> goForward() => _webView.goForward();
@override
Future<void> reload() => _webView.reload();
@override
Future<void> clearCache() {
return _webView.configuration.websiteDataStore.removeDataOfTypes(
<WKWebsiteDataType>{
WKWebsiteDataType.memoryCache,
WKWebsiteDataType.diskCache,
WKWebsiteDataType.offlineWebApplicationCache,
},
DateTime.fromMillisecondsSinceEpoch(0),
);
}
@override
Future<void> clearLocalStorage() {
return _webView.configuration.websiteDataStore.removeDataOfTypes(
<WKWebsiteDataType>{WKWebsiteDataType.localStorage},
DateTime.fromMillisecondsSinceEpoch(0),
);
}
@override
Future<void> runJavaScript(String javaScript) async {
try {
await _webView.evaluateJavaScript(javaScript);
} on PlatformException catch (exception) {
// WebKit will throw an error when the type of the evaluated value is
// unsupported. This also goes for `null` and `undefined` on iOS 14+. For
// example, when running a void function. For ease of use, this specific
// error is ignored when no return value is expected.
final Object? details = exception.details;
if (details is! NSError ||
details.code != WKErrorCode.javaScriptResultTypeIsUnsupported) {
rethrow;
}
}
}
@override
Future<Object> runJavaScriptReturningResult(String javaScript) async {
final Object? result = await _webView.evaluateJavaScript(javaScript);
if (result == null) {
throw ArgumentError(
'Result of JavaScript execution returned a `null` value. '
'Use `runJavascript` when expecting a null return value.',
);
}
return result;
}
@override
Future<String?> getTitle() => _webView.getTitle();
@override
Future<void> scrollTo(int x, int y) {
return _webView.scrollView.setContentOffset(Point<double>(
x.toDouble(),
y.toDouble(),
));
}
@override
Future<void> scrollBy(int x, int y) {
return _webView.scrollView.scrollBy(Point<double>(
x.toDouble(),
y.toDouble(),
));
}
@override
Future<Offset> getScrollPosition() async {
final Point<double> offset = await _webView.scrollView.getContentOffset();
return Offset(offset.x, offset.y);
}
/// Whether horizontal swipe gestures trigger page navigation.
Future<void> setAllowsBackForwardNavigationGestures(bool enabled) {
return _webView.setAllowsBackForwardNavigationGestures(enabled);
}
@override
Future<void> setBackgroundColor(Color color) {
return Future.wait(<Future<void>>[
_webView.setOpaque(false),
_webView.setBackgroundColor(Colors.transparent),
// This method must be called last.
_webView.scrollView.setBackgroundColor(color),
]);
}
@override
Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) {
switch (javaScriptMode) {
case JavaScriptMode.disabled:
return _webView.configuration.preferences.setJavaScriptEnabled(false);
case JavaScriptMode.unrestricted:
return _webView.configuration.preferences.setJavaScriptEnabled(true);
}
}
@override
Future<void> setUserAgent(String? userAgent) {
return _webView.setCustomUserAgent(userAgent);
}
@override
Future<void> enableZoom(bool enabled) async {
if (_zoomEnabled == enabled) {
return;
}
_zoomEnabled = enabled;
if (enabled) {
await _resetUserScripts();
} else {
await _disableZoom();
}
}
@override
Future<void> setPlatformNavigationDelegate(
covariant WebKitNavigationDelegate handler,
) {
_currentNavigationDelegate = handler;
return _webView.setNavigationDelegate(handler._navigationDelegate);
}
Future<void> _disableZoom() {
const WKUserScript userScript = WKUserScript(
"var meta = document.createElement('meta');\n"
"meta.name = 'viewport';\n"
"meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, "
"user-scalable=no';\n"
"var head = document.getElementsByTagName('head')[0];head.appendChild(meta);",
WKUserScriptInjectionTime.atDocumentEnd,
isMainFrameOnly: true,
);
return _webView.configuration.userContentController
.addUserScript(userScript);
}
/// Sets a callback that notifies the host application of any log messages
/// written to the JavaScript console.
///
/// Because the iOS WKWebView doesn't provide a built-in way to access the
/// console, setting this callback will inject a custom [WKUserScript] which
/// overrides the JavaScript `console.debug`, `console.error`, `console.info`,
/// `console.log` and `console.warn` methods and forwards the console message
/// via a `JavaScriptChannel` to the host application.
@override
Future<void> setOnConsoleMessage(
void Function(JavaScriptConsoleMessage consoleMessage) onConsoleMessage,
) {
_onConsoleMessageCallback = onConsoleMessage;
final JavaScriptChannelParams channelParams = WebKitJavaScriptChannelParams(
name: 'fltConsoleMessage',
webKitProxy: _webKitParams.webKitProxy,
onMessageReceived: (JavaScriptMessage message) {
if (_onConsoleMessageCallback == null) {
return;
}
final Map<String, dynamic> consoleLog =
jsonDecode(message.message) as Map<String, dynamic>;
JavaScriptLogLevel level;
switch (consoleLog['level']) {
case 'error':
level = JavaScriptLogLevel.error;
case 'warning':
level = JavaScriptLogLevel.warning;
case 'debug':
level = JavaScriptLogLevel.debug;
case 'info':
level = JavaScriptLogLevel.info;
case 'log':
default:
level = JavaScriptLogLevel.log;
break;
}
_onConsoleMessageCallback!(
JavaScriptConsoleMessage(
level: level,
message: consoleLog['message']! as String,
),
);
});
addJavaScriptChannel(channelParams);
return _injectConsoleOverride();
}
Future<void> _injectConsoleOverride() {
const WKUserScript overrideScript = WKUserScript(
'''
function log(type, args) {
var message = Object.values(args)
.map(v => typeof(v) === "undefined" ? "undefined" : typeof(v) === "object" ? JSON.stringify(v) : v.toString())
.map(v => v.substring(0, 3000)) // Limit msg to 3000 chars
.join(", ");
var log = {
level: type,
message: message
};
window.webkit.messageHandlers.fltConsoleMessage.postMessage(JSON.stringify(log));
}
let originalLog = console.log;
let originalInfo = console.info;
let originalWarn = console.warn;
let originalError = console.error;
let originalDebug = console.debug;
console.log = function() { log("log", arguments); originalLog.apply(null, arguments) };
console.info = function() { log("info", arguments); originalInfo.apply(null, arguments) };
console.warn = function() { log("warning", arguments); originalWarn.apply(null, arguments) };
console.error = function() { log("error", arguments); originalError.apply(null, arguments) };
console.debug = function() { log("debug", arguments); originalDebug.apply(null, arguments) };
window.addEventListener("error", function(e) {
log("error", e.message + " at " + e.filename + ":" + e.lineno + ":" + e.colno);
});
''',
WKUserScriptInjectionTime.atDocumentStart,
isMainFrameOnly: true,
);
return _webView.configuration.userContentController
.addUserScript(overrideScript);
}
// WKWebView does not support removing a single user script, so all user
// scripts and all message handlers are removed instead. And the JavaScript
// channels that shouldn't be removed are re-registered. Note that this
// workaround could interfere with exposing support for custom scripts from
// applications.
Future<void> _resetUserScripts({String? removedJavaScriptChannel}) async {
unawaited(
_webView.configuration.userContentController.removeAllUserScripts(),
);
// TODO(bparrishMines): This can be replaced with
// `removeAllScriptMessageHandlers` once Dart supports runtime version
// checking. (e.g. The equivalent to @availability in Objective-C.)
_javaScriptChannelParams.keys.forEach(
_webView.configuration.userContentController.removeScriptMessageHandler,
);
_javaScriptChannelParams.remove(removedJavaScriptChannel);
await Future.wait(<Future<void>>[
for (final JavaScriptChannelParams params
in _javaScriptChannelParams.values)
addJavaScriptChannel(params),
// Zoom is disabled with a WKUserScript, so this adds it back if it was
// removed above.
if (!_zoomEnabled) _disableZoom(),
// Console logs are forwarded with a WKUserScript, so this adds it back
// if a console callback was registered with [setOnConsoleMessage].
if (_onConsoleMessageCallback != null) _injectConsoleOverride(),
]);
}
@override
Future<void> setOnPlatformPermissionRequest(
void Function(PlatformWebViewPermissionRequest request) onPermissionRequest,
) async {
_onPermissionRequestCallback = onPermissionRequest;
}
@override
Future<void> setOnScrollPositionChange(
void Function(ScrollPositionChange scrollPositionChange)?
onScrollPositionChange) async {
_onScrollPositionChangeCallback = onScrollPositionChange;
if (onScrollPositionChange != null) {
final WeakReference<WebKitWebViewController> weakThis =
WeakReference<WebKitWebViewController>(this);
_uiScrollViewDelegate =
_webKitParams.webKitProxy.createUIScrollViewDelegate(
scrollViewDidScroll: (UIScrollView uiScrollView, double x, double y) {
weakThis.target?._onScrollPositionChangeCallback?.call(
ScrollPositionChange(x, y),
);
},
);
return _webView.scrollView.setDelegate(_uiScrollViewDelegate);
} else {
_uiScrollViewDelegate = null;
return _webView.scrollView.setDelegate(null);
}
}
/// Whether to enable tools for debugging the current WKWebView content.
///
/// It needs to be activated in each WKWebView where you want to enable it.
///
/// Starting from macOS version 13.3, iOS version 16.4, and tvOS version 16.4,
/// the default value is set to false.
///
/// Defaults to true in previous versions.
Future<void> setInspectable(bool inspectable) {
return _webView.setInspectable(inspectable);
}
@override
Future<String?> getUserAgent() async {
final String? customUserAgent = await _webView.getCustomUserAgent();
// Despite the official documentation of `WKWebView.customUserAgent`, the
// default value seems to be an empty String and not null. It's possible it
// could depend on the iOS version, so this checks for both.
if (customUserAgent != null && customUserAgent.isNotEmpty) {
return customUserAgent;
}
return (await _webView.evaluateJavaScript('navigator.userAgent;')
as String?)!;
}
@override
Future<void> setOnJavaScriptAlertDialog(
Future<void> Function(JavaScriptAlertDialogRequest request)
onJavaScriptAlertDialog) async {
_onJavaScriptAlertDialog = onJavaScriptAlertDialog;
}
@override
Future<void> setOnJavaScriptConfirmDialog(
Future<bool> Function(JavaScriptConfirmDialogRequest request)
onJavaScriptConfirmDialog) async {
_onJavaScriptConfirmDialog = onJavaScriptConfirmDialog;
}
@override
Future<void> setOnJavaScriptTextInputDialog(
Future<String> Function(JavaScriptTextInputDialogRequest request)
onJavaScriptTextInputDialog) async {
_onJavaScriptTextInputDialog = onJavaScriptTextInputDialog;
}
}
/// An implementation of [JavaScriptChannelParams] with the WebKit api.
///
/// See [WebKitWebViewController.addJavaScriptChannel].
@immutable
class WebKitJavaScriptChannelParams extends JavaScriptChannelParams {
/// Constructs a [WebKitJavaScriptChannelParams].
WebKitJavaScriptChannelParams({
required super.name,
required super.onMessageReceived,
@visibleForTesting WebKitProxy webKitProxy = const WebKitProxy(),
}) : assert(name.isNotEmpty),
_messageHandler = webKitProxy.createScriptMessageHandler(
didReceiveScriptMessage: withWeakReferenceTo(
onMessageReceived,
(WeakReference<void Function(JavaScriptMessage)> weakReference) {
return (
WKUserContentController controller,
WKScriptMessage message,
) {
if (weakReference.target != null) {
weakReference.target!(
JavaScriptMessage(message: message.body!.toString()),
);
}
};
},
),
);
/// Constructs a [WebKitJavaScriptChannelParams] using a
/// [JavaScriptChannelParams].
WebKitJavaScriptChannelParams.fromJavaScriptChannelParams(
JavaScriptChannelParams params, {
@visibleForTesting WebKitProxy webKitProxy = const WebKitProxy(),
}) : this(
name: params.name,
onMessageReceived: params.onMessageReceived,
webKitProxy: webKitProxy,
);
final WKScriptMessageHandler _messageHandler;
}
/// Object specifying creation parameters for a [WebKitWebViewWidget].
@immutable
class WebKitWebViewWidgetCreationParams
extends PlatformWebViewWidgetCreationParams {
/// Constructs a [WebKitWebViewWidgetCreationParams].
WebKitWebViewWidgetCreationParams({
super.key,
required super.controller,
super.layoutDirection,
super.gestureRecognizers,
@visibleForTesting InstanceManager? instanceManager,
}) : _instanceManager = instanceManager ?? NSObject.globalInstanceManager;
/// Constructs a [WebKitWebViewWidgetCreationParams] using a
/// [PlatformWebViewWidgetCreationParams].
WebKitWebViewWidgetCreationParams.fromPlatformWebViewWidgetCreationParams(
PlatformWebViewWidgetCreationParams params, {
InstanceManager? instanceManager,
}) : this(
key: params.key,
controller: params.controller,
layoutDirection: params.layoutDirection,
gestureRecognizers: params.gestureRecognizers,
instanceManager: instanceManager,
);
// Maintains instances used to communicate with the native objects they
// represent.
final InstanceManager _instanceManager;
@override
int get hashCode => Object.hash(
controller,
layoutDirection,
_instanceManager,
);
@override
bool operator ==(Object other) {
return other is WebKitWebViewWidgetCreationParams &&
controller == other.controller &&
layoutDirection == other.layoutDirection &&
_instanceManager == other._instanceManager;
}
}
/// An implementation of [PlatformWebViewWidget] with the WebKit api.
class WebKitWebViewWidget extends PlatformWebViewWidget {
/// Constructs a [WebKitWebViewWidget].
WebKitWebViewWidget(PlatformWebViewWidgetCreationParams params)
: super.implementation(
params is WebKitWebViewWidgetCreationParams
? params
: WebKitWebViewWidgetCreationParams
.fromPlatformWebViewWidgetCreationParams(params),
);
WebKitWebViewWidgetCreationParams get _webKitParams =>
params as WebKitWebViewWidgetCreationParams;
@override
Widget build(BuildContext context) {
return UiKitView(
// Setting a default key using `params` ensures the `UIKitView` recreates
// the PlatformView when changes are made.
key: _webKitParams.key ??
ValueKey<WebKitWebViewWidgetCreationParams>(
params as WebKitWebViewWidgetCreationParams),
viewType: 'plugins.flutter.io/webview',
onPlatformViewCreated: (_) {},
layoutDirection: params.layoutDirection,
gestureRecognizers: params.gestureRecognizers,
creationParams: _webKitParams._instanceManager.getIdentifier(
(params.controller as WebKitWebViewController)._webView),
creationParamsCodec: const StandardMessageCodec(),
);
}
}
/// An implementation of [WebResourceError] with the WebKit API.
class WebKitWebResourceError extends WebResourceError {
WebKitWebResourceError._(
this._nsError, {
required bool isForMainFrame,
required super.url,
}) : super(
errorCode: _nsError.code,
description: _nsError.localizedDescription ?? '',
errorType: _toWebResourceErrorType(_nsError.code),
isForMainFrame: isForMainFrame,
);
static WebResourceErrorType? _toWebResourceErrorType(int code) {
switch (code) {
case WKErrorCode.unknown:
return WebResourceErrorType.unknown;
case WKErrorCode.webContentProcessTerminated:
return WebResourceErrorType.webContentProcessTerminated;
case WKErrorCode.webViewInvalidated:
return WebResourceErrorType.webViewInvalidated;
case WKErrorCode.javaScriptExceptionOccurred:
return WebResourceErrorType.javaScriptExceptionOccurred;
case WKErrorCode.javaScriptResultTypeIsUnsupported:
return WebResourceErrorType.javaScriptResultTypeIsUnsupported;
}
return null;
}
/// A string representing the domain of the error.
String? get domain => _nsError.domain;
final NSError _nsError;
}
/// Object specifying creation parameters for a [WebKitNavigationDelegate].
@immutable
class WebKitNavigationDelegateCreationParams
extends PlatformNavigationDelegateCreationParams {
/// Constructs a [WebKitNavigationDelegateCreationParams].
const WebKitNavigationDelegateCreationParams({
@visibleForTesting this.webKitProxy = const WebKitProxy(),
});
/// Constructs a [WebKitNavigationDelegateCreationParams] using a
/// [PlatformNavigationDelegateCreationParams].
const WebKitNavigationDelegateCreationParams.fromPlatformNavigationDelegateCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformNavigationDelegateCreationParams params, {
@visibleForTesting WebKitProxy webKitProxy = const WebKitProxy(),
}) : this(webKitProxy: webKitProxy);
/// Handles constructing objects and calling static methods for the WebKit
/// native library.
@visibleForTesting
final WebKitProxy webKitProxy;
}
/// An implementation of [PlatformNavigationDelegate] with the WebKit API.
class WebKitNavigationDelegate extends PlatformNavigationDelegate {
/// Constructs a [WebKitNavigationDelegate].
WebKitNavigationDelegate(PlatformNavigationDelegateCreationParams params)
: super.implementation(params is WebKitNavigationDelegateCreationParams
? params
: WebKitNavigationDelegateCreationParams
.fromPlatformNavigationDelegateCreationParams(params)) {
final WeakReference<WebKitNavigationDelegate> weakThis =
WeakReference<WebKitNavigationDelegate>(this);
_navigationDelegate =
(this.params as WebKitNavigationDelegateCreationParams)
.webKitProxy
.createNavigationDelegate(
didFinishNavigation: (WKWebView webView, String? url) {
if (weakThis.target?._onPageFinished != null) {
weakThis.target!._onPageFinished!(url ?? '');
}
},
didStartProvisionalNavigation: (WKWebView webView, String? url) {
if (weakThis.target?._onPageStarted != null) {
weakThis.target!._onPageStarted!(url ?? '');
}
},
decidePolicyForNavigationResponse:
(WKWebView webView, WKNavigationResponse response) async {
if (weakThis.target?._onHttpError != null &&
response.response.statusCode >= 400) {
weakThis.target!._onHttpError!(
HttpResponseError(
response: WebResourceResponse(
uri: null,
statusCode: response.response.statusCode,
),
),
);
}
return WKNavigationResponsePolicy.allow;
},
decidePolicyForNavigationAction: (
WKWebView webView,
WKNavigationAction action,
) async {
if (weakThis.target?._onNavigationRequest != null) {
final NavigationDecision decision =
await weakThis.target!._onNavigationRequest!(NavigationRequest(
url: action.request.url,
isMainFrame: action.targetFrame.isMainFrame,
));
switch (decision) {
case NavigationDecision.prevent:
return WKNavigationActionPolicy.cancel;
case NavigationDecision.navigate:
return WKNavigationActionPolicy.allow;
}
}
return WKNavigationActionPolicy.allow;
},
didFailNavigation: (WKWebView webView, NSError error) {
if (weakThis.target?._onWebResourceError != null) {
weakThis.target!._onWebResourceError!(
WebKitWebResourceError._(
error,
isForMainFrame: true,
url: error.userInfo[NSErrorUserInfoKey
.NSURLErrorFailingURLStringError] as String?,
),
);
}
},
didFailProvisionalNavigation: (WKWebView webView, NSError error) {
if (weakThis.target?._onWebResourceError != null) {
weakThis.target!._onWebResourceError!(
WebKitWebResourceError._(
error,
isForMainFrame: true,
url: error.userInfo[NSErrorUserInfoKey
.NSURLErrorFailingURLStringError] as String?,
),
);
}
},
webViewWebContentProcessDidTerminate: (WKWebView webView) {
if (weakThis.target?._onWebResourceError != null) {
weakThis.target!._onWebResourceError!(
WebKitWebResourceError._(
const NSError(
code: WKErrorCode.webContentProcessTerminated,
// Value from https://developer.apple.com/documentation/webkit/wkerrordomain?language=objc.
domain: 'WKErrorDomain',
),
isForMainFrame: true,
url: null,
),
);
}
},
didReceiveAuthenticationChallenge: (
WKWebView webView,
NSUrlAuthenticationChallenge challenge,
void Function(
NSUrlSessionAuthChallengeDisposition disposition,
NSUrlCredential? credential,
) completionHandler,
) {
if (challenge.protectionSpace.authenticationMethod ==
NSUrlAuthenticationMethod.httpBasic) {
final void Function(HttpAuthRequest)? callback =
weakThis.target?._onHttpAuthRequest;
final String? host = challenge.protectionSpace.host;
final String? realm = challenge.protectionSpace.realm;
if (callback != null && host != null) {
callback(
HttpAuthRequest(
onProceed: (WebViewCredential credential) {
completionHandler(
NSUrlSessionAuthChallengeDisposition.useCredential,
NSUrlCredential.withUser(
user: credential.user,
password: credential.password,
persistence: NSUrlCredentialPersistence.session,
),
);
},
onCancel: () {
completionHandler(
NSUrlSessionAuthChallengeDisposition
.cancelAuthenticationChallenge,
null,
);
},
host: host,
realm: realm,
),
);
return;
}
}
completionHandler(
NSUrlSessionAuthChallengeDisposition.performDefaultHandling,
null,
);
},
);
}
// Used to set `WKWebView.setNavigationDelegate` in `WebKitWebViewController`.
late final WKNavigationDelegate _navigationDelegate;
PageEventCallback? _onPageFinished;
PageEventCallback? _onPageStarted;
HttpResponseErrorCallback? _onHttpError;
ProgressCallback? _onProgress;
WebResourceErrorCallback? _onWebResourceError;
NavigationRequestCallback? _onNavigationRequest;
UrlChangeCallback? _onUrlChange;
HttpAuthRequestCallback? _onHttpAuthRequest;
@override
Future<void> setOnPageFinished(PageEventCallback onPageFinished) async {
_onPageFinished = onPageFinished;
}
@override
Future<void> setOnPageStarted(PageEventCallback onPageStarted) async {
_onPageStarted = onPageStarted;
}
@override
Future<void> setOnHttpError(HttpResponseErrorCallback onHttpError) async {
_onHttpError = onHttpError;
}
@override
Future<void> setOnProgress(ProgressCallback onProgress) async {
_onProgress = onProgress;
}
@override
Future<void> setOnWebResourceError(
WebResourceErrorCallback onWebResourceError,
) async {
_onWebResourceError = onWebResourceError;
}
@override
Future<void> setOnNavigationRequest(
NavigationRequestCallback onNavigationRequest,
) async {
_onNavigationRequest = onNavigationRequest;
}
@override
Future<void> setOnUrlChange(UrlChangeCallback onUrlChange) async {
_onUrlChange = onUrlChange;
}
@override
Future<void> setOnHttpAuthRequest(
HttpAuthRequestCallback onHttpAuthRequest,
) async {
_onHttpAuthRequest = onHttpAuthRequest;
}
}
/// WebKit implementation of [PlatformWebViewPermissionRequest].
class WebKitWebViewPermissionRequest extends PlatformWebViewPermissionRequest {
const WebKitWebViewPermissionRequest._({
required super.types,
required void Function(WKPermissionDecision decision) onDecision,
}) : _onDecision = onDecision;
final void Function(WKPermissionDecision) _onDecision;
@override
Future<void> grant() async {
_onDecision(WKPermissionDecision.grant);
}
@override
Future<void> deny() async {
_onDecision(WKPermissionDecision.deny);
}
/// Prompt the user for permission for the requested resource.
Future<void> prompt() async {
_onDecision(WKPermissionDecision.prompt);
}
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_controller.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/webkit_webview_controller.dart",
"repo_id": "packages",
"token_count": 15721
} | 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.
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart';
import 'package:webview_flutter_wkwebview/src/common/web_kit.g.dart';
import 'package:webview_flutter_wkwebview/src/ui_kit/ui_kit.dart';
import 'package:webview_flutter_wkwebview/src/ui_kit/ui_kit_api_impls.dart';
import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart';
import '../common/test_web_kit.g.dart';
import 'ui_kit_test.mocks.dart';
@GenerateMocks(<Type>[
TestWKWebViewConfigurationHostApi,
TestWKWebViewHostApi,
TestUIScrollViewHostApi,
TestUIScrollViewDelegateHostApi,
TestUIViewHostApi,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('UIKit', () {
late InstanceManager instanceManager;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
});
group('UIScrollView', () {
late MockTestUIScrollViewHostApi mockPlatformHostApi;
late UIScrollView scrollView;
late int scrollViewInstanceId;
setUp(() {
mockPlatformHostApi = MockTestUIScrollViewHostApi();
TestUIScrollViewHostApi.setup(mockPlatformHostApi);
TestWKWebViewConfigurationHostApi.setup(
MockTestWKWebViewConfigurationHostApi(),
);
TestWKWebViewHostApi.setup(MockTestWKWebViewHostApi());
final WKWebView webView = WKWebView(
WKWebViewConfiguration(instanceManager: instanceManager),
instanceManager: instanceManager,
);
scrollView = UIScrollView.fromWebView(
webView,
instanceManager: instanceManager,
);
scrollViewInstanceId = instanceManager.getIdentifier(scrollView)!;
});
tearDown(() {
TestUIScrollViewHostApi.setup(null);
TestWKWebViewConfigurationHostApi.setup(null);
TestWKWebViewHostApi.setup(null);
});
test('getContentOffset', () async {
when(mockPlatformHostApi.getContentOffset(scrollViewInstanceId))
.thenReturn(<double>[4.0, 10.0]);
expect(
scrollView.getContentOffset(),
completion(const Point<double>(4.0, 10.0)),
);
});
test('scrollBy', () async {
await scrollView.scrollBy(const Point<double>(4.0, 10.0));
verify(mockPlatformHostApi.scrollBy(scrollViewInstanceId, 4.0, 10.0));
});
test('setContentOffset', () async {
await scrollView.setContentOffset(const Point<double>(4.0, 10.0));
verify(mockPlatformHostApi.setContentOffset(
scrollViewInstanceId,
4.0,
10.0,
));
});
test('setDelegate', () async {
final UIScrollViewDelegate delegate = UIScrollViewDelegate.detached(
instanceManager: instanceManager,
);
const int delegateIdentifier = 10;
instanceManager.addHostCreatedInstance(delegate, delegateIdentifier);
await scrollView.setDelegate(delegate);
verify(mockPlatformHostApi.setDelegate(
scrollViewInstanceId,
delegateIdentifier,
));
});
});
group('UIScrollViewDelegate', () {
// Ensure the test host api is removed after each test run.
tearDown(() => TestUIScrollViewDelegateHostApi.setup(null));
test('Host API create', () {
final MockTestUIScrollViewDelegateHostApi mockApi =
MockTestUIScrollViewDelegateHostApi();
TestUIScrollViewDelegateHostApi.setup(mockApi);
UIScrollViewDelegate(instanceManager: instanceManager);
verify(mockApi.create(0));
});
test('scrollViewDidScroll', () {
final UIScrollViewDelegateFlutterApi flutterApi =
UIScrollViewDelegateFlutterApiImpl(
instanceManager: instanceManager,
);
final UIScrollView scrollView = UIScrollView.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(scrollView, 0);
List<Object?>? args;
final UIScrollViewDelegate scrollViewDelegate =
UIScrollViewDelegate.detached(
scrollViewDidScroll: (UIScrollView scrollView, double x, double y) {
args = <Object?>[scrollView, x, y];
},
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(scrollViewDelegate, 1);
flutterApi.scrollViewDidScroll(1, 0, 5, 6);
expect(args, <Object?>[scrollView, 5, 6]);
});
});
group('UIView', () {
late MockTestUIViewHostApi mockPlatformHostApi;
late UIView view;
late int viewInstanceId;
setUp(() {
mockPlatformHostApi = MockTestUIViewHostApi();
TestUIViewHostApi.setup(mockPlatformHostApi);
view = UIView.detached(instanceManager: instanceManager);
viewInstanceId = instanceManager.addDartCreatedInstance(view);
});
tearDown(() {
TestUIViewHostApi.setup(null);
});
test('setBackgroundColor', () async {
await view.setBackgroundColor(Colors.red);
verify(mockPlatformHostApi.setBackgroundColor(
viewInstanceId,
Colors.red.value,
));
});
test('setOpaque', () async {
await view.setOpaque(false);
verify(mockPlatformHostApi.setOpaque(viewInstanceId, false));
});
});
});
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/test/src/ui_kit/ui_kit_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/src/ui_kit/ui_kit_test.dart",
"repo_id": "packages",
"token_count": 2413
} | 1,121 |
# `xdg_directories`
A Dart package for reading XDG directory configuration information on Linux.
## Getting Started
On Linux, `xdg` is a system developed by [freedesktop.org](freedesktop.org), a
project to work on interoperability and shared base technology for free software
desktop environments for Linux.
This Dart package can be used to determine the directory configuration
information defined by `xdg`, such as where the Documents or Desktop directories
are. These are called "user directories" and are defined in configuration file
in the user's home directory.
See [this wiki](https://wiki.archlinux.org/index.php/XDG_Base_Directory) for
more details of the XDG Base Directory implementation.
To use this package, the basic XDG values for the following are available via a Dart API:
- `dataHome` - The single base directory relative to which user-specific data
files should be written. (Corresponds to `$XDG_DATA_HOME`).
- `configHome` - The a single base directory relative to which user-specific
configuration files should be written. (Corresponds to `$XDG_CONFIG_HOME`).
- `dataDirs` - The list of preference-ordered base directories relative to
which data files should be searched. (Corresponds to `$XDG_DATA_DIRS`).
- `configDirs` - The list of preference-ordered base directories relative to
which configuration files should be searched. (Corresponds to
`$XDG_CONFIG_DIRS`).
- `cacheHome` - The base directory relative to which user-specific
non-essential (cached) data should be written. (Corresponds to
`$XDG_CACHE_HOME`).
- `runtimeDir` - The base directory relative to which user-specific runtime
files and other file objects should be placed. (Corresponds to
`$XDG_RUNTIME_DIR`).
- `getUserDirectoryNames()` - Returns a set of the names of user directories
defined in the `xdg` configuration files.
- `getUserDirectory(String dirName)` - Gets the value of the user dir with the
given name. Requesting a user dir that doesn't exist returns `null`. The
`dirName` argument is case-insensitive. See [this
wiki](https://wiki.archlinux.org/index.php/XDG_user_directories) for more
details and what values of `dirName` might be available.
| packages/packages/xdg_directories/README.md/0 | {
"file_path": "packages/packages/xdg_directories/README.md",
"repo_id": "packages",
"token_count": 612
} | 1,122 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
// From errno definitions.
const int _noSuchFileError = 2;
/// An override function used by the tests to override the environment variable
/// lookups using [xdgEnvironmentOverride].
typedef EnvironmentAccessor = String? Function(String envVar);
/// A testing setter that replaces the real environment lookups with an override.
///
/// Set to null to stop overriding.
///
/// Only available to tests.
@visibleForTesting
set xdgEnvironmentOverride(EnvironmentAccessor? override) {
_xdgEnvironmentOverride = override;
_getenv = _xdgEnvironmentOverride ?? _productionGetEnv;
}
/// A testing getter that returns the current value of the override that
/// replaces the real environment lookups with an override.
///
/// Only available to tests.
@visibleForTesting
EnvironmentAccessor? get xdgEnvironmentOverride => _xdgEnvironmentOverride;
EnvironmentAccessor? _xdgEnvironmentOverride;
EnvironmentAccessor _getenv = _productionGetEnv;
String? _productionGetEnv(String value) => Platform.environment[value];
/// A wrapper around Process.runSync to allow injection of a fake in tests.
@visibleForTesting
abstract class XdgProcessRunner {
/// Runs the given command synchronously.
ProcessResult runSync(
String executable,
List<String> arguments, {
Encoding? stdoutEncoding = systemEncoding,
Encoding? stderrEncoding = systemEncoding,
});
}
class _DefaultProcessRunner implements XdgProcessRunner {
const _DefaultProcessRunner();
@override
ProcessResult runSync(String executable, List<String> arguments,
{Encoding? stdoutEncoding = systemEncoding,
Encoding? stderrEncoding = systemEncoding}) {
return Process.runSync(
executable,
arguments,
stdoutEncoding: stdoutEncoding,
stderrEncoding: stderrEncoding,
);
}
}
/// A testing function that replaces the process runner used to run
/// xdg-user-path with the one supplied.
///
/// Only available to tests.
@visibleForTesting
set xdgProcessRunner(XdgProcessRunner processRunner) {
_processRunner = processRunner;
}
XdgProcessRunner _processRunner = const _DefaultProcessRunner();
List<Directory> _directoryListFromEnvironment(
String envVar, List<Directory> fallback) {
ArgumentError.checkNotNull(envVar);
ArgumentError.checkNotNull(fallback);
final String? value = _getenv(envVar);
if (value == null || value.isEmpty) {
return fallback;
}
return value.split(':').where((String value) {
return value.isNotEmpty;
}).map<Directory>((String entry) {
return Directory(entry);
}).toList();
}
Directory? _directoryFromEnvironment(String envVar) {
ArgumentError.checkNotNull(envVar);
final String? value = _getenv(envVar);
if (value == null || value.isEmpty) {
return null;
}
return Directory(value);
}
Directory _directoryFromEnvironmentWithFallback(
String envVar, String fallback) {
ArgumentError.checkNotNull(envVar);
final String? value = _getenv(envVar);
if (value == null || value.isEmpty) {
return _getDirectory(fallback);
}
return Directory(value);
}
// Creates a Directory from a fallback path.
Directory _getDirectory(String subdir) {
ArgumentError.checkNotNull(subdir);
assert(subdir.isNotEmpty);
final String? homeDir = _getenv('HOME');
if (homeDir == null || homeDir.isEmpty) {
throw StateError(
'The "HOME" environment variable is not set. This package (and POSIX) '
'requires that HOME be set.');
}
return Directory(path.joinAll(<String>[homeDir, subdir]));
}
/// The base directory relative to which user-specific
/// non-essential (cached) data should be written. (Corresponds to
/// `$XDG_CACHE_HOME`).
///
/// Throws [StateError] if the HOME environment variable is not set.
Directory get cacheHome =>
_directoryFromEnvironmentWithFallback('XDG_CACHE_HOME', '.cache');
/// The list of preference-ordered base directories relative to
/// which configuration files should be searched. (Corresponds to
/// `$XDG_CONFIG_DIRS`).
///
/// Throws [StateError] if the HOME environment variable is not set.
List<Directory> get configDirs {
return _directoryListFromEnvironment(
'XDG_CONFIG_DIRS',
<Directory>[Directory('/etc/xdg')],
);
}
/// The a single base directory relative to which user-specific
/// configuration files should be written. (Corresponds to `$XDG_CONFIG_HOME`).
///
/// Throws [StateError] if the HOME environment variable is not set.
Directory get configHome =>
_directoryFromEnvironmentWithFallback('XDG_CONFIG_HOME', '.config');
/// The list of preference-ordered base directories relative to
/// which data files should be searched. (Corresponds to `$XDG_DATA_DIRS`).
///
/// Throws [StateError] if the HOME environment variable is not set.
List<Directory> get dataDirs {
return _directoryListFromEnvironment(
'XDG_DATA_DIRS',
<Directory>[Directory('/usr/local/share'), Directory('/usr/share')],
);
}
/// The base directory relative to which user-specific data files should be
/// written. (Corresponds to `$XDG_DATA_HOME`).
///
/// Throws [StateError] if the HOME environment variable is not set.
Directory get dataHome =>
_directoryFromEnvironmentWithFallback('XDG_DATA_HOME', '.local/share');
/// The base directory relative to which user-specific runtime
/// files and other file objects should be placed. (Corresponds to
/// `$XDG_RUNTIME_DIR`).
///
/// Throws [StateError] if the HOME environment variable is not set.
Directory? get runtimeDir => _directoryFromEnvironment('XDG_RUNTIME_DIR');
/// Gets the xdg user directory named by `dirName`.
///
/// Use [getUserDirectoryNames] to find out the list of available names.
///
/// If the `xdg-user-dir` executable is not present this returns null.
Directory? getUserDirectory(String dirName) {
final ProcessResult result;
try {
result = _processRunner.runSync(
'xdg-user-dir',
<String>[dirName],
stdoutEncoding: utf8,
);
} on ProcessException catch (e) {
// Silently return null if it's missing, otherwise pass the exception up.
if (e.errorCode == _noSuchFileError) {
return null;
}
rethrow;
}
final String path = (result.stdout as String).split('\n')[0];
return Directory(path);
}
/// Gets the set of user directory names that xdg knows about.
///
/// These are not paths, they are names of xdg values. Call [getUserDirectory]
/// to get the associated directory.
///
/// These are the names of the variables in "[configHome]/user-dirs.dirs", with
/// the `XDG_` prefix removed and the `_DIR` suffix removed.
Set<String> getUserDirectoryNames() {
final File configFile = File(path.join(configHome.path, 'user-dirs.dirs'));
List<String> contents;
try {
contents = configFile.readAsLinesSync();
} on FileSystemException {
return const <String>{};
}
final Set<String> result = <String>{};
final RegExp dirRegExp =
RegExp(r'^\s*XDG_(?<dirname>[^=]*)_DIR\s*=\s*(?<dir>.*)\s*$');
for (final String line in contents) {
final RegExpMatch? match = dirRegExp.firstMatch(line);
if (match == null) {
continue;
}
result.add(match.namedGroup('dirname')!);
}
return result;
}
| packages/packages/xdg_directories/lib/xdg_directories.dart/0 | {
"file_path": "packages/packages/xdg_directories/lib/xdg_directories.dart",
"repo_id": "packages",
"token_count": 2320
} | 1,123 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:colorize/colorize.dart';
import 'package:meta/meta.dart';
export 'package:colorize/colorize.dart' show Styles;
/// True if color should be applied.
///
/// Defaults to autodetecting stdout.
@visibleForTesting
bool useColorForOutput = stdout.supportsAnsiEscapes;
String _colorizeIfAppropriate(String string, Styles color) {
if (!useColorForOutput) {
return string;
}
return Colorize(string).apply(color).toString();
}
/// Prints [message] in green, if the environment supports color.
void printSuccess(String message) {
print(_colorizeIfAppropriate(message, Styles.GREEN));
}
/// Prints [message] in yellow, if the environment supports color.
void printWarning(String message) {
print(_colorizeIfAppropriate(message, Styles.YELLOW));
}
/// Prints [message] in red, if the environment supports color.
void printError(String message) {
print(_colorizeIfAppropriate(message, Styles.RED));
}
/// Returns [message] with escapes to print it in [color], if the environment
/// supports color.
String colorizeString(String message, Styles color) {
return _colorizeIfAppropriate(message, color);
}
| packages/script/tool/lib/src/common/output_utils.dart/0 | {
"file_path": "packages/script/tool/lib/src/common/output_utils.dart",
"repo_id": "packages",
"token_count": 388
} | 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 'common/core.dart';
import 'common/gradle.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/plugin_utils.dart';
import 'common/repository_package.dart';
const int _exitPrecacheFailed = 3;
const int _exitNothingRequested = 4;
/// Download dependencies, both Dart and native.
///
/// Specficially each platform runs:
/// Android: 'gradlew dependencies'.
/// Dart: 'flutter pub get'.
/// iOS/macOS: 'pod install'.
///
/// See https://docs.gradle.org/6.4/userguide/core_dependency_management.html#sec:dependency-mgmt-in-gradle.
class FetchDepsCommand extends PackageLoopingCommand {
/// Creates an instance of the fetch-deps command.
FetchDepsCommand(
super.packagesDir, {
super.processRunner,
super.platform,
}) {
argParser.addFlag(_dartFlag, defaultsTo: true, help: 'Run "pub get"');
argParser.addFlag(_supportingTargetPlatformsOnlyFlag,
help: 'Restricts "pub get" runs to packages that have at least one '
'example supporting at least one of the platform flags passed.\n'
'If no platform flags are passed, this will exclude all packages.');
argParser.addFlag(platformAndroid,
help: 'Run "gradlew dependencies" for Android plugins.\n'
'Include packages with Android examples when used with '
'--$_supportingTargetPlatformsOnlyFlag');
argParser.addFlag(platformIOS,
help: 'Run "pod install" for iOS plugins.\n'
'Include packages with iOS examples when used with '
'--$_supportingTargetPlatformsOnlyFlag');
argParser.addFlag(platformLinux,
help: 'Include packages with Linux examples when used with '
'--$_supportingTargetPlatformsOnlyFlag');
argParser.addFlag(platformMacOS,
help: 'Run "pod install" for macOS plugins.\n'
'Include packages with macOS examples when used with '
'--$_supportingTargetPlatformsOnlyFlag');
argParser.addFlag(platformWeb,
help: 'Include packages with Web examples when used with '
'--$_supportingTargetPlatformsOnlyFlag');
argParser.addFlag(platformWindows,
help: 'Include packages with Windows examples when used with '
'--$_supportingTargetPlatformsOnlyFlag');
}
static const String _dartFlag = 'dart';
static const String _supportingTargetPlatformsOnlyFlag =
'supporting-target-platforms-only';
static const Iterable<String> _platforms = <String>[
platformAndroid,
platformIOS,
platformLinux,
platformMacOS,
platformWeb,
platformWindows,
];
@override
final String name = 'fetch-deps';
@override
final String description = 'Fetches dependencies for packages';
@override
Future<void> initializeRun() async {
// `pod install` requires having the platform artifacts precached. See
// https://github.com/flutter/flutter/blob/fb7a763c640d247d090cbb373e4b3a0459ac171b/packages/flutter_tools/bin/podhelper.rb#L47
// https://github.com/flutter/flutter/blob/fb7a763c640d247d090cbb373e4b3a0459ac171b/packages/flutter_tools/bin/podhelper.rb#L130
if (getBoolArg(platformIOS)) {
final int exitCode = await processRunner.runAndStream(
flutterCommand,
<String>['precache', '--ios'],
);
if (exitCode != 0) {
throw ToolExit(_exitPrecacheFailed);
}
}
if (getBoolArg(platformMacOS)) {
final int exitCode = await processRunner.runAndStream(
flutterCommand,
<String>['precache', '--macos'],
);
if (exitCode != 0) {
throw ToolExit(_exitPrecacheFailed);
}
}
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
bool fetchedDeps = false;
final List<String> skips = <String>[];
if (getBoolArg(_dartFlag)) {
final bool filterPlatforms =
getBoolArg(_supportingTargetPlatformsOnlyFlag);
if (!filterPlatforms || _hasExampleSupportingRequestedPlatform(package)) {
fetchedDeps = true;
if (!await _fetchDartPackages(package)) {
// If Dart-level depenendencies fail, fail immediately since the
// native dependencies won't be useful.
return PackageResult.fail(<String>['Failed to "pub get".']);
}
} else {
skips.add('Skipping Dart dependencies; no examples support requested '
'platforms.');
}
}
final List<String> errors = <String>[];
for (final FlutterPlatform platform in _targetPlatforms) {
final PackageResult result;
switch (platform) {
case FlutterPlatform.android:
result = await _fetchAndroidDeps(package);
case FlutterPlatform.ios:
result = await _fetchDarwinDeps(package, platformIOS);
case FlutterPlatform.macos:
result = await _fetchDarwinDeps(package, platformMacOS);
case FlutterPlatform.linux:
case FlutterPlatform.web:
case FlutterPlatform.windows:
// No native dependency handling yet.
result = PackageResult.skip('Nothing to do for $platform.');
}
switch (result.state) {
case RunState.succeeded:
fetchedDeps = true;
case RunState.skipped:
skips.add(result.details.first);
case RunState.failed:
errors.addAll(result.details);
case RunState.excluded:
throw StateError('Unreachable');
}
}
if (errors.isNotEmpty) {
return PackageResult.fail(errors);
}
if (fetchedDeps) {
return PackageResult.success();
}
if (skips.isNotEmpty) {
return PackageResult.skip(<String>['', ...skips].join('\n- '));
}
printError('At least one type of dependency must be requested');
throw ToolExit(_exitNothingRequested);
}
Future<PackageResult> _fetchAndroidDeps(RepositoryPackage package) async {
if (!pluginSupportsPlatform(platformAndroid, package,
requiredMode: PlatformSupport.inline)) {
return PackageResult.skip(
'Package does not have native Android dependencies.');
}
for (final RepositoryPackage example in package.getExamples()) {
final GradleProject gradleProject = GradleProject(example,
processRunner: processRunner, platform: platform);
if (!gradleProject.isConfigured()) {
final int exitCode = await processRunner.runAndStream(
flutterCommand,
<String>['build', 'apk', '--config-only'],
workingDir: example.directory,
);
if (exitCode != 0) {
printError('Unable to configure Gradle project.');
return PackageResult.fail(<String>['Unable to configure Gradle.']);
}
}
final String packageName = package.directory.basename;
final int exitCode =
await gradleProject.runCommand('$packageName:dependencies');
if (exitCode != 0) {
return PackageResult.fail();
}
}
return PackageResult.success();
}
Future<PackageResult> _fetchDarwinDeps(
RepositoryPackage package, final String platform) async {
if (!pluginSupportsPlatform(platform, package,
requiredMode: PlatformSupport.inline)) {
// Convert from the flag (lower case ios/macos) to the actual name.
final String displayPlatform = platform.replaceFirst('os', 'OS');
return PackageResult.skip(
'Package does not have native $displayPlatform dependencies.');
}
for (final RepositoryPackage example in package.getExamples()) {
// Create the necessary native build files, which will run pub get and pod install if needed.
final int exitCode = await processRunner.runAndStream(
flutterCommand,
<String>['build', platform, '--config-only'],
workingDir: example.directory,
);
if (exitCode != 0) {
printError('Unable to prepare native project files.');
return PackageResult.fail(<String>['Unable to configure project.']);
}
}
return PackageResult.success();
}
Future<bool> _fetchDartPackages(RepositoryPackage package) async {
final String command = package.requiresFlutter() ? flutterCommand : 'dart';
final int exitCode = await processRunner.runAndStream(
command, <String>['pub', 'get'],
workingDir: package.directory);
return exitCode == 0;
}
bool _hasExampleSupportingRequestedPlatform(RepositoryPackage package) {
return package.getExamples().any((RepositoryPackage example) {
return _targetPlatforms.any(
(FlutterPlatform platform) => example.appSupportsPlatform(platform));
});
}
Iterable<FlutterPlatform> get _targetPlatforms => _platforms
.where((String platform) => getBoolArg(platform))
.map((String platformName) => getPlatformByName(platformName));
}
| packages/script/tool/lib/src/fetch_deps_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/fetch_deps_command.dart",
"repo_id": "packages",
"token_count": 3337
} | 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:yaml/yaml.dart';
import 'package:yaml_edit/yaml_edit.dart';
import 'common/package_looping_command.dart';
import 'common/repository_package.dart';
/// A command to remove dev_dependencies, which are not used by package clients.
///
/// This is intended for use with legacy Flutter version testing, to allow
/// running analysis (with --lib-only) with versions that are supported for
/// clients of the library, but not for development of the library.
class RemoveDevDependenciesCommand extends PackageLoopingCommand {
/// Creates a publish metadata updater command instance.
RemoveDevDependenciesCommand(super.packagesDir);
@override
final String name = 'remove-dev-dependencies';
@override
final String description = 'Removes any dev_dependencies section from a '
'package, to allow more legacy testing.';
@override
bool get hasLongOutput => false;
@override
PackageLoopingType get packageLoopingType =>
PackageLoopingType.includeAllSubpackages;
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
bool changed = false;
final YamlEditor editablePubspec =
YamlEditor(package.pubspecFile.readAsStringSync());
const String devDependenciesKey = 'dev_dependencies';
final YamlNode root = editablePubspec.parseAt(<String>[]);
final YamlMap? devDependencies =
(root as YamlMap)[devDependenciesKey] as YamlMap?;
if (devDependencies != null) {
changed = true;
print('${indentation}Removed dev_dependencies');
editablePubspec.remove(<String>[devDependenciesKey]);
}
if (changed) {
package.pubspecFile.writeAsStringSync(editablePubspec.toString());
}
return changed
? PackageResult.success()
: PackageResult.skip('Nothing to remove.');
}
}
| packages/script/tool/lib/src/remove_dev_dependencies_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/remove_dev_dependencies_command.dart",
"repo_id": "packages",
"token_count": 624
} | 1,126 |
// Mocks generated by Mockito 5.4.4 from annotations
// in flutter_plugin_tools/test/common/package_command_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i6;
import 'dart:io' as _i10;
import 'package:git/src/branch_reference.dart' as _i3;
import 'package:git/src/commit.dart' as _i2;
import 'package:git/src/commit_reference.dart' as _i8;
import 'package:git/src/git_dir.dart' as _i4;
import 'package:git/src/tag.dart' as _i7;
import 'package:git/src/tree_entry.dart' as _i9;
import 'package:mockito/mockito.dart' as _i1;
import 'package:mockito/src/dummies.dart' as _i5;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeCommit_0 extends _i1.SmartFake implements _i2.Commit {
_FakeCommit_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeBranchReference_1 extends _i1.SmartFake
implements _i3.BranchReference {
_FakeBranchReference_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [GitDir].
///
/// See the documentation for Mockito's code generation for more information.
class MockGitDir extends _i1.Mock implements _i4.GitDir {
MockGitDir() {
_i1.throwOnMissingStub(this);
}
@override
String get path => (super.noSuchMethod(
Invocation.getter(#path),
returnValue: _i5.dummyValue<String>(
this,
Invocation.getter(#path),
),
) as String);
@override
_i6.Future<int> commitCount([String? branchName = r'HEAD']) =>
(super.noSuchMethod(
Invocation.method(
#commitCount,
[branchName],
),
returnValue: _i6.Future<int>.value(0),
) as _i6.Future<int>);
@override
_i6.Future<_i2.Commit> commitFromRevision(String? revision) =>
(super.noSuchMethod(
Invocation.method(
#commitFromRevision,
[revision],
),
returnValue: _i6.Future<_i2.Commit>.value(_FakeCommit_0(
this,
Invocation.method(
#commitFromRevision,
[revision],
),
)),
) as _i6.Future<_i2.Commit>);
@override
_i6.Future<Map<String, _i2.Commit>> commits([String? branchName = r'HEAD']) =>
(super.noSuchMethod(
Invocation.method(
#commits,
[branchName],
),
returnValue:
_i6.Future<Map<String, _i2.Commit>>.value(<String, _i2.Commit>{}),
) as _i6.Future<Map<String, _i2.Commit>>);
@override
_i6.Future<_i3.BranchReference?> branchReference(String? branchName) =>
(super.noSuchMethod(
Invocation.method(
#branchReference,
[branchName],
),
returnValue: _i6.Future<_i3.BranchReference?>.value(),
) as _i6.Future<_i3.BranchReference?>);
@override
_i6.Future<List<_i3.BranchReference>> branches() => (super.noSuchMethod(
Invocation.method(
#branches,
[],
),
returnValue: _i6.Future<List<_i3.BranchReference>>.value(
<_i3.BranchReference>[]),
) as _i6.Future<List<_i3.BranchReference>>);
@override
_i6.Stream<_i7.Tag> tags() => (super.noSuchMethod(
Invocation.method(
#tags,
[],
),
returnValue: _i6.Stream<_i7.Tag>.empty(),
) as _i6.Stream<_i7.Tag>);
@override
_i6.Future<List<_i8.CommitReference>> showRef({
bool? heads = false,
bool? tags = false,
}) =>
(super.noSuchMethod(
Invocation.method(
#showRef,
[],
{
#heads: heads,
#tags: tags,
},
),
returnValue: _i6.Future<List<_i8.CommitReference>>.value(
<_i8.CommitReference>[]),
) as _i6.Future<List<_i8.CommitReference>>);
@override
_i6.Future<_i3.BranchReference> currentBranch() => (super.noSuchMethod(
Invocation.method(
#currentBranch,
[],
),
returnValue:
_i6.Future<_i3.BranchReference>.value(_FakeBranchReference_1(
this,
Invocation.method(
#currentBranch,
[],
),
)),
) as _i6.Future<_i3.BranchReference>);
@override
_i6.Future<List<_i9.TreeEntry>> lsTree(
String? treeish, {
bool? subTreesOnly = false,
String? path,
}) =>
(super.noSuchMethod(
Invocation.method(
#lsTree,
[treeish],
{
#subTreesOnly: subTreesOnly,
#path: path,
},
),
returnValue: _i6.Future<List<_i9.TreeEntry>>.value(<_i9.TreeEntry>[]),
) as _i6.Future<List<_i9.TreeEntry>>);
@override
_i6.Future<String?> createOrUpdateBranch(
String? branchName,
String? treeSha,
String? commitMessage,
) =>
(super.noSuchMethod(
Invocation.method(
#createOrUpdateBranch,
[
branchName,
treeSha,
commitMessage,
],
),
returnValue: _i6.Future<String?>.value(),
) as _i6.Future<String?>);
@override
_i6.Future<String> commitTree(
String? treeSha,
String? commitMessage, {
List<String>? parentCommitShas,
}) =>
(super.noSuchMethod(
Invocation.method(
#commitTree,
[
treeSha,
commitMessage,
],
{#parentCommitShas: parentCommitShas},
),
returnValue: _i6.Future<String>.value(_i5.dummyValue<String>(
this,
Invocation.method(
#commitTree,
[
treeSha,
commitMessage,
],
{#parentCommitShas: parentCommitShas},
),
)),
) as _i6.Future<String>);
@override
_i6.Future<Map<String, String>> writeObjects(List<String>? paths) =>
(super.noSuchMethod(
Invocation.method(
#writeObjects,
[paths],
),
returnValue: _i6.Future<Map<String, String>>.value(<String, String>{}),
) as _i6.Future<Map<String, String>>);
@override
_i6.Future<_i10.ProcessResult> runCommand(
Iterable<String>? args, {
bool? throwOnError = true,
}) =>
(super.noSuchMethod(
Invocation.method(
#runCommand,
[args],
{#throwOnError: throwOnError},
),
returnValue: _i6.Future<_i10.ProcessResult>.value(
_i5.dummyValue<_i10.ProcessResult>(
this,
Invocation.method(
#runCommand,
[args],
{#throwOnError: throwOnError},
),
)),
) as _i6.Future<_i10.ProcessResult>);
@override
_i6.Future<bool> isWorkingTreeClean() => (super.noSuchMethod(
Invocation.method(
#isWorkingTreeClean,
[],
),
returnValue: _i6.Future<bool>.value(false),
) as _i6.Future<bool>);
@override
_i6.Future<_i2.Commit?> updateBranch(
String? branchName,
_i6.Future<dynamic> Function(_i10.Directory)? populater,
String? commitMessage,
) =>
(super.noSuchMethod(
Invocation.method(
#updateBranch,
[
branchName,
populater,
commitMessage,
],
),
returnValue: _i6.Future<_i2.Commit?>.value(),
) as _i6.Future<_i2.Commit?>);
@override
_i6.Future<_i2.Commit?> updateBranchWithDirectoryContents(
String? branchName,
String? sourceDirectoryPath,
String? commitMessage,
) =>
(super.noSuchMethod(
Invocation.method(
#updateBranchWithDirectoryContents,
[
branchName,
sourceDirectoryPath,
commitMessage,
],
),
returnValue: _i6.Future<_i2.Commit?>.value(),
) as _i6.Future<_i2.Commit?>);
}
| packages/script/tool/test/common/package_command_test.mocks.dart/0 | {
"file_path": "packages/script/tool/test/common/package_command_test.mocks.dart",
"repo_id": "packages",
"token_count": 4164
} | 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: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/fix_command.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
late RecordingProcessRunner processRunner;
late CommandRunner<void> runner;
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
processRunner = RecordingProcessRunner();
final FixCommand command = FixCommand(
packagesDir,
processRunner: processRunner,
platform: mockPlatform,
);
runner = CommandRunner<void>('fix_command', 'Test for fix_command');
runner.addCommand(command);
});
test('runs fix in top-level packages and subpackages', () async {
final RepositoryPackage package = createFakePackage('a', packagesDir);
final RepositoryPackage plugin = createFakePlugin('b', packagesDir);
await runCapturingPrint(runner, <String>['fix']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall('dart', const <String>['fix', '--apply'], package.path),
ProcessCall('dart', const <String>['fix', '--apply'],
package.getExamples().first.path),
ProcessCall('dart', const <String>['fix', '--apply'], plugin.path),
ProcessCall('dart', const <String>['fix', '--apply'],
plugin.getExamples().first.path),
]));
});
test('fails if "dart fix" fails', () async {
createFakePlugin('foo', packagesDir);
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['fix']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>['fix'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Unable to automatically fix package.'),
]),
);
});
}
| packages/script/tool/test/fix_command_test.dart/0 | {
"file_path": "packages/script/tool/test/fix_command_test.dart",
"repo_id": "packages",
"token_count": 867
} | 1,128 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '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/update_dependency_command.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
FileSystem fileSystem;
late Directory packagesDir;
late RecordingProcessRunner processRunner;
late CommandRunner<void> runner;
Future<http.Response> Function(http.Request request)? mockHttpResponse;
setUp(() {
fileSystem = MemoryFileSystem();
processRunner = RecordingProcessRunner();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
final UpdateDependencyCommand command = UpdateDependencyCommand(
packagesDir,
processRunner: processRunner,
httpClient:
MockClient((http.Request request) => mockHttpResponse!(request)),
);
runner = CommandRunner<void>(
'update_dependency_command', 'Test for update-dependency command.');
runner.addCommand(command);
});
/// Adds a dummy 'dependencies:' entries for [dependency] to [package].
void addDependency(RepositoryPackage package, String dependency,
{String version = '^1.0.0'}) {
final List<String> lines = package.pubspecFile.readAsLinesSync();
final int dependenciesStartIndex = lines.indexOf('dependencies:');
assert(dependenciesStartIndex != -1);
lines.insert(dependenciesStartIndex + 1, ' $dependency: $version');
package.pubspecFile.writeAsStringSync(lines.join('\n'));
}
/// Adds a 'dev_dependencies:' section with an entry for [dependency] to
/// [package].
void addDevDependency(RepositoryPackage package, String dependency,
{String version = '^1.0.0'}) {
final String originalContent = package.pubspecFile.readAsStringSync();
package.pubspecFile.writeAsStringSync('''
$originalContent
dev_dependencies:
$dependency: $version
''');
}
test('throws if no target is provided', () async {
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['update-dependency'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Exactly one of the target flags must be provided:'),
]),
);
});
test('throws if multiple dependencies specified', () async {
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--android-dependency',
'gradle'
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Exactly one of the target flags must be provided:'),
]),
);
});
group('pub dependencies', () {
test('throws if no version is given for an unpublished target', () async {
mockHttpResponse = (http.Request request) async {
return http.Response('', 404);
};
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package'
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('target_package does not exist on pub'),
]),
);
});
test('skips if there is no dependency', () async {
createFakePackage('a_package', packagesDir, examples: <String>[]);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
'1.5.0'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('SKIPPING: Does not depend on target_package'),
]),
);
});
test('skips if the dependency is already the target version', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDependency(package, 'target_package', version: '^1.5.0');
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
'1.5.0'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('SKIPPING: Already depends on ^1.5.0'),
]),
);
});
test('logs updates', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDependency(package, 'target_package');
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
'1.5.0'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Updating to "^1.5.0"'),
]),
);
});
test('updates normal dependency', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDependency(package, 'target_package');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
'1.5.0'
]);
final Dependency? dep =
package.parsePubspec().dependencies['target_package'];
expect(dep, isA<HostedDependency>());
expect((dep! as HostedDependency).version.toString(), '^1.5.0');
});
test('updates dev dependency', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDevDependency(package, 'target_package');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
'1.5.0'
]);
final Dependency? dep =
package.parsePubspec().devDependencies['target_package'];
expect(dep, isA<HostedDependency>());
expect((dep! as HostedDependency).version.toString(), '^1.5.0');
});
test('updates dependency in example', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
final RepositoryPackage example = package.getExamples().first;
addDevDependency(example, 'target_package');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
'1.5.0'
]);
final Dependency? dep =
example.parsePubspec().devDependencies['target_package'];
expect(dep, isA<HostedDependency>());
expect((dep! as HostedDependency).version.toString(), '^1.5.0');
});
test('uses provided constraint as-is', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDependency(package, 'target_package');
const String providedConstraint = '>=1.6.0 <3.0.0';
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
providedConstraint
]);
final Dependency? dep =
package.parsePubspec().dependencies['target_package'];
expect(dep, isA<HostedDependency>());
expect((dep! as HostedDependency).version.toString(), providedConstraint);
});
test('uses provided version as lower bound for unpinned', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDependency(package, 'target_package');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
'1.5.0'
]);
final Dependency? dep =
package.parsePubspec().dependencies['target_package'];
expect(dep, isA<HostedDependency>());
expect((dep! as HostedDependency).version.toString(), '^1.5.0');
});
test('uses provided version as exact version for pinned', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDependency(package, 'target_package', version: '1.0.0');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
'--version',
'1.5.0'
]);
final Dependency? dep =
package.parsePubspec().dependencies['target_package'];
expect(dep, isA<HostedDependency>());
expect((dep! as HostedDependency).version.toString(), '1.5.0');
});
test('uses latest pub version as lower bound for unpinned', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDependency(package, 'target_package');
const Map<String, dynamic> targetPackagePubResponse = <String, dynamic>{
'name': 'a',
'versions': <String>[
'0.0.1',
'1.0.0',
'1.5.0',
],
};
mockHttpResponse = (http.Request request) async {
if (request.url.pathSegments.last == 'target_package.json') {
return http.Response(json.encode(targetPackagePubResponse), 200);
}
return http.Response('', 500);
};
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
]);
final Dependency? dep =
package.parsePubspec().dependencies['target_package'];
expect(dep, isA<HostedDependency>());
expect((dep! as HostedDependency).version.toString(), '^1.5.0');
});
test('uses latest pub version as exact version for pinned', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, examples: <String>[]);
addDependency(package, 'target_package', version: '1.0.0');
const Map<String, dynamic> targetPackagePubResponse = <String, dynamic>{
'name': 'a',
'versions': <String>[
'0.0.1',
'1.0.0',
'1.5.0',
],
};
mockHttpResponse = (http.Request request) async {
if (request.url.pathSegments.last == 'target_package.json') {
return http.Response(json.encode(targetPackagePubResponse), 200);
}
return http.Response('', 500);
};
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'target_package',
]);
final Dependency? dep =
package.parsePubspec().dependencies['target_package'];
expect(dep, isA<HostedDependency>());
expect((dep! as HostedDependency).version.toString(), '1.5.0');
});
test('regenerates all pigeon files when updating pigeon', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir, extraFiles: <String>[
'pigeons/foo.dart',
'pigeons/bar.dart',
]);
addDependency(package, 'pigeon', version: '1.0.0');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'pigeon',
'--version',
'1.5.0',
]);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'dart',
const <String>['pub', 'get'],
package.path,
),
ProcessCall(
'dart',
const <String>['run', 'pigeon', '--input', 'pigeons/foo.dart'],
package.path,
),
ProcessCall(
'dart',
const <String>['run', 'pigeon', '--input', 'pigeons/bar.dart'],
package.path,
),
]),
);
});
test('warns when regenerating pigeon if there are no pigeon files',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
addDependency(package, 'pigeon', version: '1.0.0');
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'pigeon',
'--version',
'1.5.0',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('No pigeon input files found'),
]),
);
});
test('updating pigeon fails if pub get fails', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
extraFiles: <String>['pigeons/foo.dart']);
addDependency(package, 'pigeon', version: '1.0.0');
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get'])
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'pigeon',
'--version',
'1.5.0',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Fetching dependencies failed'),
contains('Failed to update pigeon files'),
]),
);
});
test('updating pigeon fails if running pigeon fails', () async {
final RepositoryPackage package = createFakePackage(
'a_package', packagesDir,
extraFiles: <String>['pigeons/foo.dart']);
addDependency(package, 'pigeon', version: '1.0.0');
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(), <String>['pub', 'get']),
FakeProcessInfo(MockProcess(exitCode: 1), <String>['run', 'pigeon']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'pigeon',
'--version',
'1.5.0',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('dart run pigeon failed'),
contains('Failed to update pigeon files'),
]),
);
});
test('regenerates mocks when updating mockito if necessary', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
addDependency(package, 'mockito', version: '1.0.0');
addDevDependency(package, 'build_runner');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'mockito',
'--version',
'1.5.0',
]);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'dart',
const <String>['pub', 'get'],
package.path,
),
ProcessCall(
'dart',
const <String>[
'run',
'build_runner',
'build',
'--delete-conflicting-outputs'
],
package.path,
),
]),
);
});
test('skips regenerating mocks when there is no build_runner dependency',
() async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
addDependency(package, 'mockito', version: '1.0.0');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'mockito',
'--version',
'1.5.0',
]);
expect(processRunner.recordedCalls.isEmpty, true);
});
test('updating mockito fails if pub get fails', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
addDependency(package, 'mockito', version: '1.0.0');
addDevDependency(package, 'build_runner');
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['pub', 'get'])
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'mockito',
'--version',
'1.5.0',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Fetching dependencies failed'),
contains('Failed to update mocks'),
]),
);
});
test('updating mockito fails if running build_runner fails', () async {
final RepositoryPackage package =
createFakePackage('a_package', packagesDir);
addDependency(package, 'mockito', version: '1.0.0');
addDevDependency(package, 'build_runner');
processRunner.mockProcessesForExecutable['dart'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(), <String>['pub', 'get']),
FakeProcessInfo(
MockProcess(exitCode: 1), <String>['run', 'build_runner']),
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--pub-package',
'mockito',
'--version',
'1.5.0',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('"dart run build_runner build" failed'),
contains('Failed to update mocks'),
]),
);
});
});
group('Android dependencies', () {
group('gradle', () {
test('throws if version format is invalid', () async {
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--android-dependency',
'gradle',
'--version',
'83',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'A version with a valid format (maximum 2-3 numbers separated by period) must be provided.'),
]),
);
});
test('skips if example app does not run on Android', () async {
final RepositoryPackage package =
createFakePlugin('fake_plugin', packagesDir);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'gradle',
'--version',
'8.8.8',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('SKIPPING: No example apps run on Android.'),
]),
);
});
test(
'throws if wrapper does not have distribution URL with expected format',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir, extraFiles: <String>[
'example/android/app/gradle/wrapper/gradle-wrapper.properties'
]);
final File gradleWrapperPropertiesFile = package.directory
.childDirectory('example')
.childDirectory('android')
.childDirectory('app')
.childDirectory('gradle')
.childDirectory('wrapper')
.childFile('gradle-wrapper.properties');
gradleWrapperPropertiesFile.writeAsStringSync('''
How is it even possible that I didn't specify a Gradle distribution?
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'gradle',
'--version',
'8.8.8',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Unable to find a gradle version entry to update for ${package.displayName}/example.'),
]),
);
});
test('succeeds if example app has android/app/gradle directory structure',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir, extraFiles: <String>[
'example/android/app/gradle/wrapper/gradle-wrapper.properties'
]);
const String newGradleVersion = '8.8.8';
final File gradleWrapperPropertiesFile = package.directory
.childDirectory('example')
.childDirectory('android')
.childDirectory('app')
.childDirectory('gradle')
.childDirectory('wrapper')
.childFile('gradle-wrapper.properties');
gradleWrapperPropertiesFile.writeAsStringSync(r'''
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip
''');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'gradle',
'--version',
newGradleVersion,
]);
final String updatedGradleWrapperPropertiesContents =
gradleWrapperPropertiesFile.readAsStringSync();
expect(
updatedGradleWrapperPropertiesContents,
contains(
r'distributionUrl=https\://services.gradle.org/distributions/'
'gradle-$newGradleVersion-all.zip'));
});
test('succeeds if example app has android/gradle directory structure',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir, extraFiles: <String>[
'example/android/gradle/wrapper/gradle-wrapper.properties'
]);
const String newGradleVersion = '9.9';
final File gradleWrapperPropertiesFile = package.directory
.childDirectory('example')
.childDirectory('android')
.childDirectory('gradle')
.childDirectory('wrapper')
.childFile('gradle-wrapper.properties');
gradleWrapperPropertiesFile.writeAsStringSync(r'''
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip
''');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'gradle',
'--version',
newGradleVersion,
]);
final String updatedGradleWrapperPropertiesContents =
gradleWrapperPropertiesFile.readAsStringSync();
expect(
updatedGradleWrapperPropertiesContents,
contains(
r'distributionUrl=https\://services.gradle.org/distributions/'
'gradle-$newGradleVersion-all.zip'));
});
test(
'succeeds if example app has android/gradle and android/app/gradle directory structure',
() async {
final RepositoryPackage package =
createFakePlugin('fake_plugin', packagesDir, extraFiles: <String>[
'example/android/gradle/wrapper/gradle-wrapper.properties',
'example/android/app/gradle/wrapper/gradle-wrapper.properties'
]);
const String newGradleVersion = '9.9';
final File gradleWrapperPropertiesFile = package.directory
.childDirectory('example')
.childDirectory('android')
.childDirectory('gradle')
.childDirectory('wrapper')
.childFile('gradle-wrapper.properties');
final File gradleAppWrapperPropertiesFile = package.directory
.childDirectory('example')
.childDirectory('android')
.childDirectory('app')
.childDirectory('gradle')
.childDirectory('wrapper')
.childFile('gradle-wrapper.properties');
gradleWrapperPropertiesFile.writeAsStringSync(r'''
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip
''');
gradleAppWrapperPropertiesFile.writeAsStringSync(r'''
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip
''');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'gradle',
'--version',
newGradleVersion,
]);
final String updatedGradleWrapperPropertiesContents =
gradleWrapperPropertiesFile.readAsStringSync();
final String updatedGradleAppWrapperPropertiesContents =
gradleAppWrapperPropertiesFile.readAsStringSync();
expect(
updatedGradleWrapperPropertiesContents,
contains(
r'distributionUrl=https\://services.gradle.org/distributions/'
'gradle-$newGradleVersion-all.zip'));
expect(
updatedGradleAppWrapperPropertiesContents,
contains(
r'distributionUrl=https\://services.gradle.org/distributions/'
'gradle-$newGradleVersion-all.zip'));
});
test('succeeds if one example app runs on Android and another does not',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir, examples: <String>[
'example_1',
'example_2'
], extraFiles: <String>[
'example/example_2/android/app/gradle/wrapper/gradle-wrapper.properties'
]);
const String newGradleVersion = '8.8.8';
final File gradleWrapperPropertiesFile = package.directory
.childDirectory('example')
.childDirectory('example_2')
.childDirectory('android')
.childDirectory('app')
.childDirectory('gradle')
.childDirectory('wrapper')
.childFile('gradle-wrapper.properties');
gradleWrapperPropertiesFile.writeAsStringSync(r'''
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip
''');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'gradle',
'--version',
newGradleVersion,
]);
final String updatedGradleWrapperPropertiesContents =
gradleWrapperPropertiesFile.readAsStringSync();
expect(
updatedGradleWrapperPropertiesContents,
contains(
r'distributionUrl=https\://services.gradle.org/distributions/'
'gradle-$newGradleVersion-all.zip'));
});
});
group('compileSdk/compileSdkForExamples', () {
// Tests if the compileSdk version is updated for the provided
// build.gradle file and new compileSdk version to update to.
Future<void> testCompileSdkVersionUpdated(
{required RepositoryPackage package,
required File buildGradleFile,
required String oldCompileSdkVersion,
required String newCompileSdkVersion,
bool runForExamples = false,
bool checkForDeprecatedCompileSdkVersion = false}) async {
buildGradleFile.writeAsStringSync('''
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'io.flutter.plugins.pathprovider'
}
${checkForDeprecatedCompileSdkVersion ? 'compileSdkVersion' : 'compileSdk'} $oldCompileSdkVersion
''');
await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
if (runForExamples) 'compileSdkForExamples' else 'compileSdk',
'--version',
newCompileSdkVersion,
]);
final String updatedBuildGradleContents =
buildGradleFile.readAsStringSync();
// compileSdkVersion is now deprecated, so if the tool finds any
// instances of compileSdk OR compileSdkVersion, it should change it
// to compileSdk. See https://developer.android.com/reference/tools/gradle-api/7.2/com/android/build/api/dsl/CommonExtension#compileSdkVersion(kotlin.Int).
expect(updatedBuildGradleContents,
contains('compileSdk $newCompileSdkVersion'));
}
test('throws if version format is invalid for compileSdk', () async {
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--android-dependency',
'compileSdk',
'--version',
'834',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'A valid Android SDK version number (1-2 digit numbers) must be provided.'),
]),
);
});
test('throws if version format is invalid for compileSdkForExamples',
() async {
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--android-dependency',
'compileSdkForExamples',
'--version',
'438',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'A valid Android SDK version number (1-2 digit numbers) must be provided.'),
]),
);
});
test('skips if plugin does not run on Android', () async {
final RepositoryPackage package =
createFakePlugin('fake_plugin', packagesDir);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'compileSdk',
'--version',
'34',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'SKIPPING: Package ${package.displayName} does not run on Android.'),
]),
);
});
test('skips if plugin example does not run on Android', () async {
final RepositoryPackage package =
createFakePlugin('fake_plugin', packagesDir);
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'compileSdkForExamples',
'--version',
'34',
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('SKIPPING: No example apps run on Android.'),
]),
);
});
test(
'throws if build configuration file does not have compileSdk version with expected format for compileSdk',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir,
extraFiles: <String>['android/build.gradle']);
final File buildGradleFile = package.directory
.childDirectory('android')
.childFile('build.gradle');
buildGradleFile.writeAsStringSync('''
How is it even possible that I didn't specify a compileSdk version?
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'compileSdk',
'--version',
'34',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Unable to find a compileSdk version entry to update for ${package.displayName}.'),
]),
);
});
test(
'throws if build configuration file does not have compileSdk version with expected format for compileSdkForExamples',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir,
extraFiles: <String>['example/android/app/build.gradle']);
final File buildGradleFile = package.directory
.childDirectory('example')
.childDirectory('android')
.childDirectory('app')
.childFile('build.gradle');
buildGradleFile.writeAsStringSync('''
How is it even possible that I didn't specify a compileSdk version?
''');
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'update-dependency',
'--packages',
package.displayName,
'--android-dependency',
'compileSdkForExamples',
'--version',
'34',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'Unable to find a compileSdkForExamples version entry to update for ${package.displayName}/example.'),
]),
);
});
test(
'succeeds if plugin runs on Android and valid version is supplied for compileSdkVersion entry',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir, extraFiles: <String>[
'android/build.gradle',
'example/android/app/build.gradle'
]);
final File buildGradleFile = package.directory
.childDirectory('android')
.childFile('build.gradle');
await testCompileSdkVersionUpdated(
package: package,
buildGradleFile: buildGradleFile,
oldCompileSdkVersion: '8',
newCompileSdkVersion: '16',
checkForDeprecatedCompileSdkVersion: true);
});
test(
'succeeds if plugin example runs on Android and valid version is supplied for compileSdkVersion entry',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir, extraFiles: <String>[
'android/build.gradle',
'example/android/app/build.gradle'
]);
final File exampleBuildGradleFile = package.directory
.childDirectory('example')
.childDirectory('android')
.childDirectory('app')
.childFile('build.gradle');
await testCompileSdkVersionUpdated(
package: package,
buildGradleFile: exampleBuildGradleFile,
oldCompileSdkVersion: '8',
newCompileSdkVersion: '16',
runForExamples: true,
checkForDeprecatedCompileSdkVersion: true);
});
test(
'succeeds if plugin runs on Android and valid version is supplied for compileSdk entry',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir, extraFiles: <String>[
'android/build.gradle',
'example/android/app/build.gradle'
]);
final File buildGradleFile = package.directory
.childDirectory('android')
.childFile('build.gradle');
await testCompileSdkVersionUpdated(
package: package,
buildGradleFile: buildGradleFile,
oldCompileSdkVersion: '8',
newCompileSdkVersion: '16');
});
test(
'succeeds if plugin example runs on Android and valid version is supplied for compileSdk entry',
() async {
final RepositoryPackage package = createFakePlugin(
'fake_plugin', packagesDir, extraFiles: <String>[
'android/build.gradle',
'example/android/app/build.gradle'
]);
final File exampleBuildGradleFile = package.directory
.childDirectory('example')
.childDirectory('android')
.childDirectory('app')
.childFile('build.gradle');
await testCompileSdkVersionUpdated(
package: package,
buildGradleFile: exampleBuildGradleFile,
oldCompileSdkVersion: '33',
newCompileSdkVersion: '34',
runForExamples: true);
});
});
});
}
| packages/script/tool/test/update_dependency_command_test.dart/0 | {
"file_path": "packages/script/tool/test/update_dependency_command_test.dart",
"repo_id": "packages",
"token_count": 16826
} | 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.
// File to create a lib/ directory for a well-formed .packages file and to
// conform to pub analyzer.
//
// This is an asset package. No dart import needed.
| packages/third_party/packages/cupertino_icons/lib/cupertino_icons.dart/0 | {
"file_path": "packages/third_party/packages/cupertino_icons/lib/cupertino_icons.dart",
"repo_id": "packages",
"token_count": 84
} | 1,130 |
arb-dir: lib/l10n/arb
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
| photobooth/l10n.yaml/0 | {
"file_path": "photobooth/l10n.yaml",
"repo_id": "photobooth",
"token_count": 39
} | 1,131 |
{
"@@locale": "ne",
"landingPageHeading": "I∕O फोटो बुथमा स्वागत छ",
"landingPageSubheading": "फोटो लिनुहोस् र समुदायसँग साझा गर्नुहोस्!",
"landingPageTakePhotoButtonText": "सुरु गर्नुहोस्",
"footerMadeWithText": "द्वारा बनाइएको ",
"footerMadeWithFlutterLinkText": "Flutter",
"footerMadeWithFirebaseLinkText": "Firebase",
"footerGoogleIOLinkText": "Google I∕O",
"footerCodelabLinkText": "Codelab",
"footerHowItsMadeLinkText": "यो कसरी बनेको छ",
"footerTermsOfServiceLinkText": "सेवाका सर्तहरु",
"footerPrivacyPolicyLinkText": "गोपनीयता नीति",
"sharePageHeading": "समुदाय संग आफ्नो फोटो साझा गर्नुहोस्!",
"sharePageSubheading": "समुदाय संग आफ्नो फोटो साझा गर्नुहोस्!",
"sharePageSuccessHeading": "फोटो साझा गरियो!",
"sharePageSuccessSubheading": "हाम्रो Flutter वेब अनुप्रयोग प्रयोग गर्नुभएकोमा धन्यबाद! तपाईंको फोटो यस अद्वितीय URL मा प्रकाशित गरिएको छ",
"sharePageSuccessCaption1": "तपाईंको फोटो ३० दिनको लागि त्यस URL मा उपलब्ध हुनेछ र स्वचालित रूपमा मेटाइनेछ। तपाईको तस्विरलाई हटाउनका लागि अनुरोध गर्नुहोस् ",
"sharePageSuccessCaption2": "[email protected]",
"sharePageSuccessCaption3": " र तपाइँको अनुरोध मा तपाइँको अद्वितीय URL समावेश गर्न निश्चित हुनुहोस्।",
"sharePageRetakeButtonText": "नयाँ फोटो लिनुहोस्",
"sharePageShareButtonText": "सेयर गर्नुहोस्",
"sharePageDownloadButtonText": "डाउनलोड गर्नुहोस्",
"socialMediaShareLinkText": "भर्खरै #IOPhotoBooth मा एउटा सेल्फी लिएँ। #GoogleIO मा भेटौंला!",
"previewPageCameraNotAllowedText": "तपाईंले क्यामेरा अनुमति अस्वीकार गर्नुभयो। कृपया अनुप्रयोग प्रयोग गर्न अनुमति दिनुहोस्।",
"sharePageSocialMediaShareClarification1": "यदि तपाइँ सोशल मिडियामा तपाइँको फोटो साझेदारी गर्न छनौट गर्नुहुन्छ भने, यो ३० दिनको लागि अद्वितीय URL उपलब्ध हुनेछ र स्वचालित रूपमा मेटाइनेछ। साझेदारी नभएका तस्विरहरु भण्डार गरिने छैन। तपाईको तस्विरलाई हटाउनका लागि अनुरोध गर्नुहोस्",
"sharePageSocialMediaShareClarification2": "[email protected]",
"sharePageSocialMediaShareClarification3": " र तपाइँको अनुरोध मा तपाइँको अद्वितीय URL समावेश गर्न निश्चित गर्नुहोस्।",
"sharePageCopyLinkButton": "प्रतिलिपि",
"sharePageLinkedCopiedButton": "प्रतिलिपि गरियो",
"sharePageErrorHeading": "हामीलाई तपाईंको छवि प्रशोधन गर्न समस्या भइरहेको छ",
"sharePageErrorSubheading": "कृपया निश्चित गर्नुहोस् कि तपाईंको उपकरण र ब्राउजर अप-टु-डेट छन्। यदि यो मुद्दा जारी रहन्छ भने, कृपया [email protected] मा सम्पर्क गर्नुहोस्।",
"shareDialogHeading": "तपाईंको फोटो साझा गर्नुहोस्!",
"shareDialogSubheading": "तपाईं Google I∕O मा हुनुहुन्छ भनेर र कार्यक्रमको समयमा तपाईंको प्रोफाइल तस्वीर अपडेट गरेर सबैलाई थाहा दिनुहोस्!",
"shareErrorDialogHeading": "उफ्!",
"shareErrorDialogTryAgainButton": "पछाडि जानुहोस्",
"shareErrorDialogSubheading": "केही गलत भयो र हामी तपाईंको फोटो लोड गर्न सक्दैनौं।",
"sharePageProgressOverlayHeading": "हामी तपाईंको फोटोलाई Flutter को साथ उत्तम बनाउँदैछौं!",
"sharePageProgressOverlaySubheading": "कृपया यो ट्याब बन्द नगर्नुहोस्।",
"shareDialogTwitterButtonText": "Twitter",
"shareDialogFacebookButtonText": "Facebook",
"photoBoothCameraAccessDeniedHeadline": "क्यामेरा पहुँच अस्वीकृत",
"photoBoothCameraAccessDeniedSubheadline": "फोटो लिनका लागि तपाईले आफ्नो क्यामेरामा ब्राउजर पहुँच अनुमति दिनुपर्दछ।",
"photoBoothCameraNotFoundHeadline": "हामी तपाईंको क्यामेरा फेला पार्न सकेनौ",
"photoBoothCameraNotFoundSubheadline1": "तपाईंको उपकरणमा क्यामेरा छैन वा यसले काम गरिरहेको छैन।",
"photoBoothCameraNotFoundSubheadline2": "फोटो लिनका लागि कृपया I∕O फोटो बुथ क्यामेरा भएको उपकरणबाट पुन: भ्रमण गर्नुहोस्।",
"photoBoothCameraErrorHeadline": "उफ्! केहि गलत भयो",
"photoBoothCameraErrorSubheadline1": "कृपया तपाइँको ब्राउजर ताजा गर्नुहोस् र फेरि प्रयास गर्नुहोस्।",
"photoBoothCameraErrorSubheadline2": "यदि यो मुद्दा जारी रहन्छ भने, कृपया [email protected] मा सम्पर्क गर्नुहोस्",
"photoBoothCameraNotSupportedHeadline": "उफ्! केहि गलत भयो",
"photoBoothCameraNotSupportedSubheadline": "कृपया निश्चित गर्नुहोस् कि तपाईंको उपकरण र ब्राउजर अप-टु-डेट छन्।",
"stickersDrawerTitle": "प्रोप्स थप्नुहोस्",
"openStickersTooltip": "प्रोप्स थप्नुहोस्",
"retakeButtonTooltip": "पुनः लिनुहोस्",
"clearStickersButtonTooltip": "प्रोपहरू खाली गर्नुहोस्",
"charactersCaptionText": "साथीहरू थप्नुहोस्",
"sharePageLearnMoreAboutTextPart1": "को बारे मा अधिक जान्नुहोस् ",
"sharePageLearnMoreAboutTextPart2": " र ",
"sharePageLearnMoreAboutTextPart3": " जानुहोस् ",
"sharePageLearnMoreAboutTextPart4": "खुला स्रोत कोड",
"goToGoogleIOButtonText": "Google I∕O मा जानुहोस्",
"clearStickersDialogHeading": "सबै प्रोपहरू हटाउने?",
"clearStickersDialogSubheading": "के तपाइँ स्क्रिनबाट सबै प्रोपहरू हटाउन चाहानुहुन्छ?",
"clearStickersDialogCancelButtonText": "होइन, मलाई फिर्ता लग्नुहोस् ",
"clearStickersDialogConfirmButtonText": "हो, सबै प्रोपहरू खाली गर्नुहोस्",
"propsReminderText": "केहि प्रोप्स थप्नुहोस्",
"stickersNextConfirmationHeading": "अन्तिम फोटो हेर्न तयार हुनुहुन्छ?",
"stickersNextConfirmationSubheading": "एकचोटि तपाईंले यो स्क्रिन छोड्नुभयो भने तपाईं कुनै परिवर्तन गर्न सक्नुहुनेछैन",
"stickersNextConfirmationCancelButtonText": "होइन, म अझै सिर्जना गर्दैछु",
"stickersNextConfirmationConfirmButtonText": "हो, मलाई देखाउनुहोस्",
"stickersRetakeConfirmationHeading": "साच्चै हो?",
"stickersRetakeConfirmationSubheading": "फोटो पुन: खिच्दै खिच्दा तपाईंले थपेको सबै प्रोपहरू हट्नेछन् ",
"stickersRetakeConfirmationCancelButtonText": "होइन, यहाँ बस्नुहोस्",
"stickersRetakeConfirmationConfirmButtonText": "हो, फोटो पुनः लिनुहोस्",
"shareRetakeConfirmationHeading": "नयाँ फोटो लिन तयार हुनुहुन्छ?",
"shareRetakeConfirmationSubheading": "पहिले यसलाई डाउनलोड वा साझेदारी गर्न सम्झनुहोस्",
"shareRetakeConfirmationCancelButtonText": "होइन, यहाँ बस्नुहोस्",
"shareRetakeConfirmationConfirmButtonText": "हो, फोटो पुनः लिनुहोस्",
"shutterButtonLabelText": "तस्बिर लेउ",
"stickersNextButtonLabelText": "अन्तिम फोटो सिर्जना गर्नुहोस्",
"dashButtonLabelText": "Dash मित्र जोड्नुहोस्",
"sparkyButtonLabelText": "Sparky मित्र जोड्नुहोस्",
"dinoButtonLabelText": "Dino मित्र जोड्नुहोस्",
"androidButtonLabelText": "Android Jetpack मित्र जोड्नुहोस्",
"addStickersButtonLabelText": "प्रोपहरू जोड्नुहोस्",
"retakePhotoButtonLabelText": "फोटो पुनः लिनुहोस्",
"clearAllStickersButtonLabelText": "सबै सहाराहरू हटाउनुहोस्"
}
| photobooth/lib/l10n/arb/app_ne.arb/0 | {
"file_path": "photobooth/lib/l10n/arb/app_ne.arb",
"repo_id": "photobooth",
"token_count": 5954
} | 1,132 |
import 'package:bloc/bloc.dart';
import 'package:camera/camera.dart';
import 'package:equatable/equatable.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:rxdart/rxdart.dart';
import 'package:uuid/uuid.dart';
part 'photobooth_event.dart';
part 'photobooth_state.dart';
typedef UuidGetter = String Function();
const _debounceDuration = Duration(milliseconds: 16);
class PhotoboothBloc extends Bloc<PhotoboothEvent, PhotoboothState> {
PhotoboothBloc([UuidGetter? uuid])
: uuid = uuid ?? const Uuid().v4,
super(const PhotoboothState()) {
EventTransformer<E> debounce<E extends PhotoboothEvent>() =>
(Stream<E> events, EventMapper<E> mapper) =>
events.debounceTime(_debounceDuration).asyncExpand(mapper);
on<PhotoCharacterDragged>(
_onPhotoCharacterDragged,
transformer: debounce(),
);
on<PhotoStickerDragged>(
_onPhotoStickerDragged,
transformer: debounce(),
);
on<PhotoCaptured>(_onPhotoCaptured);
on<PhotoCharacterToggled>(_onPhotoCharacterToggled);
on<PhotoStickerTapped>(_onPhotoStickerTapped);
on<PhotoClearStickersTapped>(_onPhotoClearStickersTapped);
on<PhotoClearAllTapped>(_onPhotoClearAllTapped);
on<PhotoDeleteSelectedStickerTapped>(_onPhotoDeleteSelectedStickerTapped);
on<PhotoTapped>(_onPhotoTapped);
}
final UuidGetter uuid;
void _onPhotoCaptured(PhotoCaptured event, Emitter<PhotoboothState> emit) {
emit(
state.copyWith(
aspectRatio: event.aspectRatio,
image: event.image,
imageId: uuid(),
selectedAssetId: emptyAssetId,
),
);
}
void _onPhotoCharacterToggled(
PhotoCharacterToggled event,
Emitter<PhotoboothState> emit,
) {
final asset = event.character;
final characters = List.of(state.characters);
final index = characters.indexWhere((c) => c.asset.name == asset.name);
final characterExists = index != -1;
if (characterExists) {
characters.removeAt(index);
return emit(
state.copyWith(
characters: characters,
),
);
}
final newCharacter = PhotoAsset(id: uuid(), asset: asset);
characters.add(newCharacter);
emit(
state.copyWith(
characters: characters,
selectedAssetId: newCharacter.id,
),
);
}
void _onPhotoCharacterDragged(
PhotoCharacterDragged event,
Emitter<PhotoboothState> emit,
) {
final asset = event.character;
final characters = List.of(state.characters);
final index = characters.indexWhere((element) => element.id == asset.id);
final character = characters.removeAt(index);
characters.add(
character.copyWith(
angle: event.update.angle,
position: PhotoAssetPosition(
dx: event.update.position.dx,
dy: event.update.position.dy,
),
size: PhotoAssetSize(
width: event.update.size.width,
height: event.update.size.height,
),
constraint: PhotoConstraint(
width: event.update.constraints.width,
height: event.update.constraints.height,
),
),
);
emit(
state.copyWith(
characters: characters,
selectedAssetId: asset.id,
),
);
}
void _onPhotoStickerTapped(
PhotoStickerTapped event,
Emitter<PhotoboothState> emit,
) {
final asset = event.sticker;
final newSticker = PhotoAsset(id: uuid(), asset: asset);
emit(
state.copyWith(
stickers: List.of(state.stickers)..add(newSticker),
selectedAssetId: newSticker.id,
),
);
}
void _onPhotoStickerDragged(
PhotoStickerDragged event,
Emitter<PhotoboothState> emit,
) {
final asset = event.sticker;
final stickers = List.of(state.stickers);
final index = stickers.indexWhere((element) => element.id == asset.id);
final sticker = stickers.removeAt(index);
stickers.add(
sticker.copyWith(
angle: event.update.angle,
position: PhotoAssetPosition(
dx: event.update.position.dx,
dy: event.update.position.dy,
),
size: PhotoAssetSize(
width: event.update.size.width,
height: event.update.size.height,
),
constraint: PhotoConstraint(
width: event.update.constraints.width,
height: event.update.constraints.height,
),
),
);
emit(
state.copyWith(
stickers: stickers,
selectedAssetId: asset.id,
),
);
}
void _onPhotoClearStickersTapped(
PhotoClearStickersTapped event,
Emitter<PhotoboothState> emit,
) {
emit(
state.copyWith(
stickers: const <PhotoAsset>[],
selectedAssetId: emptyAssetId,
),
);
}
void _onPhotoClearAllTapped(
PhotoClearAllTapped event,
Emitter<PhotoboothState> emit,
) {
emit(
state.copyWith(
characters: const <PhotoAsset>[],
stickers: const <PhotoAsset>[],
selectedAssetId: emptyAssetId,
),
);
}
void _onPhotoDeleteSelectedStickerTapped(
PhotoDeleteSelectedStickerTapped event,
Emitter<PhotoboothState> emit,
) {
final stickers = List.of(state.stickers);
final index = stickers.indexWhere(
(element) => element.id == state.selectedAssetId,
);
final stickerExists = index != -1;
if (stickerExists) {
stickers.removeAt(index);
}
emit(
state.copyWith(
stickers: stickers,
selectedAssetId: emptyAssetId,
),
);
}
void _onPhotoTapped(PhotoTapped event, Emitter<PhotoboothState> emit) {
emit(
state.copyWith(selectedAssetId: emptyAssetId),
);
}
}
| photobooth/lib/photobooth/bloc/photobooth_bloc.dart/0 | {
"file_path": "photobooth/lib/photobooth/bloc/photobooth_bloc.dart",
"repo_id": "photobooth",
"token_count": 2379
} | 1,133 |
import 'package:analytics/analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/assets.g.dart';
import 'package:io_photobooth/footer/footer.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
const _initialCharacterScale = 0.25;
const _minCharacterScale = 0.1;
class PhotoboothPreview extends StatelessWidget {
const PhotoboothPreview({
required this.preview,
required this.onSnapPressed,
super.key,
});
final Widget preview;
final VoidCallback onSnapPressed;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final state = context.watch<PhotoboothBloc>().state;
final children = <Widget>[
CharacterIconButton(
key: const Key('photoboothView_dash_characterIconButton'),
icon: const AssetImage('assets/icons/dash_icon.png'),
label: l10n.dashButtonLabelText,
isSelected: state.isDashSelected,
onPressed: () {
trackEvent(
category: 'button',
action: 'click-add-friend',
label: 'add-dash-friend',
);
context
.read<PhotoboothBloc>()
.add(const PhotoCharacterToggled(character: Assets.dash));
},
),
CharacterIconButton(
key: const Key('photoboothView_sparky_characterIconButton'),
icon: const AssetImage('assets/icons/sparky_icon.png'),
label: l10n.sparkyButtonLabelText,
isSelected: state.isSparkySelected,
onPressed: () {
trackEvent(
category: 'button',
action: 'click-add-friend',
label: 'add-sparky-friend',
);
context
.read<PhotoboothBloc>()
.add(const PhotoCharacterToggled(character: Assets.sparky));
},
),
CharacterIconButton(
key: const Key('photoboothView_android_characterIconButton'),
icon: const AssetImage('assets/icons/android_icon.png'),
label: l10n.androidButtonLabelText,
isSelected: state.isAndroidSelected,
onPressed: () {
trackEvent(
category: 'button',
action: 'click-add-friend',
label: 'add-bugdroid-friend',
);
context
.read<PhotoboothBloc>()
.add(const PhotoCharacterToggled(character: Assets.android));
},
),
CharacterIconButton(
key: const Key('photoboothView_dino_characterIconButton'),
icon: const AssetImage('assets/icons/dino_icon.png'),
label: l10n.dinoButtonLabelText,
isSelected: state.isDinoSelected,
onPressed: () {
trackEvent(
category: 'button',
action: 'click-add-friend',
label: 'add-dino-friend',
);
context
.read<PhotoboothBloc>()
.add(const PhotoCharacterToggled(character: Assets.dino));
},
),
];
return Stack(
fit: StackFit.expand,
children: [
preview,
Positioned.fill(
child: GestureDetector(
key: const Key('photoboothPreview_background_gestureDetector'),
onTap: () {
context.read<PhotoboothBloc>().add(const PhotoTapped());
},
),
),
const Align(
alignment: Alignment.bottomLeft,
child: Padding(
padding: EdgeInsets.only(left: 16, bottom: 24),
child: MadeWithIconLinks(),
),
),
for (final character in state.characters)
DraggableResizable(
key: Key(
'''photoboothPreview_${character.asset.name}_draggableResizableAsset''',
),
canTransform: character.id == state.selectedAssetId,
onUpdate: (update) {
context.read<PhotoboothBloc>().add(
PhotoCharacterDragged(character: character, update: update),
);
},
constraints: _getAnimatedSpriteConstraints(character.asset.name),
size: _getAnimatedSpriteSize(character.asset.name),
child: _AnimatedCharacter(name: character.asset.name),
),
CharactersIconLayout(children: children),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 30),
child: ShutterButton(
key: const Key('photoboothPreview_photo_shutterButton'),
onCountdownComplete: onSnapPressed,
),
),
),
],
);
}
}
BoxConstraints? _getAnimatedSpriteConstraints(String name) {
final sprite = _getAnimatedSprite(name);
if (sprite == null) return null;
final size = sprite.sprites.size;
return BoxConstraints(
minWidth: size.width * _minCharacterScale,
minHeight: size.height * _minCharacterScale,
);
}
Size _getAnimatedSpriteSize(String name) {
final sprite = _getAnimatedSprite(name);
if (sprite != null) return sprite.sprites.size * _initialCharacterScale;
return Size.zero;
}
AnimatedSprite? _getAnimatedSprite(String name) {
switch (name) {
case 'android':
return const AnimatedAndroid();
case 'dash':
return const AnimatedDash();
case 'dino':
return const AnimatedDino();
case 'sparky':
return const AnimatedSparky();
default:
return null;
}
}
class _AnimatedCharacter extends StatelessWidget {
const _AnimatedCharacter({required this.name});
final String name;
@override
Widget build(BuildContext context) {
return _getAnimatedSprite(name) ?? const SizedBox();
}
}
class CharactersIconLayout extends StatelessWidget {
const CharactersIconLayout({
required this.children,
super.key,
});
final List<Widget> children;
@override
Widget build(BuildContext context) {
final orientation = MediaQuery.of(context).orientation;
return orientation == Orientation.landscape
? LandscapeCharactersIconLayout(children: children)
: PortraitCharactersIconLayout(children: children);
}
}
@visibleForTesting
class LandscapeCharactersIconLayout extends StatelessWidget {
const LandscapeCharactersIconLayout({
required this.children,
super.key,
});
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.only(right: 15),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CharactersCaption(),
Flexible(
child: SingleChildScrollView(
child: Column(
children: children,
),
),
)
],
),
),
);
}
}
@visibleForTesting
class PortraitCharactersIconLayout extends StatelessWidget {
const PortraitCharactersIconLayout({
required this.children,
super.key,
});
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topCenter,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisSize: MainAxisSize.min,
children: children,
),
),
),
BlocBuilder<PhotoboothBloc, PhotoboothState>(
builder: (context, state) {
if (state.isAnyCharacterSelected) return const SizedBox();
return const CharactersCaption();
},
)
],
),
);
}
}
| photobooth/lib/photobooth/widgets/photobooth_preview.dart/0 | {
"file_path": "photobooth/lib/photobooth/widgets/photobooth_preview.dart",
"repo_id": "photobooth",
"token_count": 3548
} | 1,134 |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class FacebookButton extends StatelessWidget {
const FacebookButton({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return ElevatedButton(
onPressed: () {
final state = context.read<ShareBloc>().state;
if (state.uploadStatus.isSuccess) {
Navigator.of(context).pop();
openLink(state.facebookShareUrl);
return;
}
context.read<ShareBloc>().add(const ShareOnFacebookTapped());
Navigator.of(context).pop();
},
child: Text(l10n.shareDialogFacebookButtonText),
);
}
}
| photobooth/lib/share/widgets/facebook_button.dart/0 | {
"file_path": "photobooth/lib/share/widgets/facebook_button.dart",
"repo_id": "photobooth",
"token_count": 345
} | 1,135 |
part of 'stickers_bloc.dart';
abstract class StickersEvent extends Equatable {
const StickersEvent();
@override
List<Object> get props => [];
}
class StickersDrawerToggled extends StickersEvent {
const StickersDrawerToggled();
}
class StickersDrawerTabTapped extends StickersEvent {
const StickersDrawerTabTapped({required this.index});
final int index;
}
| photobooth/lib/stickers/bloc/stickers_event.dart/0 | {
"file_path": "photobooth/lib/stickers/bloc/stickers_event.dart",
"repo_id": "photobooth",
"token_count": 116
} | 1,136 |
# example
A new Flutter project.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
| photobooth/packages/camera/camera/example/README.md/0 | {
"file_path": "photobooth/packages/camera/camera/example/README.md",
"repo_id": "photobooth",
"token_count": 146
} | 1,137 |
import 'package:camera_platform_interface/camera_platform_interface.dart';
/// An implementation of [CameraPlatform] that uses a `MethodChannel`
/// to communicate with the native code.
///
/// The `camera` plugin code itself never talks to the native code directly.
/// It delegates all calls to an instance of a class
/// that extends the [CameraPlatform].
///
/// The architecture above allows for platforms that communicate differently
/// with the native side (like web) to have a common interface to extend.
///
/// This is the instance that runs when the native side talks
/// to your Flutter app through MethodChannels (Android and iOS platforms).
class MethodChannelCamera extends CameraPlatform {}
| photobooth/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart/0 | {
"file_path": "photobooth/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart",
"repo_id": "photobooth",
"token_count": 158
} | 1,138 |
export 'src/unsupported.dart' if (dart.library.html) 'src/web.dart';
/// {@template vector_2d}
/// A 2 dimensional vector representation.
/// {@endtemplate}
class Vector2D {
/// {@macro vector_2d}
const Vector2D(this.x, this.y);
/// Factory which returns a [Vector2D] based on the provided [json].
factory Vector2D.fromJson(Map<dynamic, dynamic> json) {
return Vector2D(
double.parse(json['x'] as String),
double.parse(json['y'] as String),
);
}
/// Converts the current instance to a Map.
Map<String, dynamic> toJson() {
return <String, dynamic>{'x': '$x', 'y': '$y'};
}
/// The x value.
final double x;
/// The y value.
final double y;
}
/// {@template composite_layer}
/// A representation of a layer that can be composited.
/// {@endtemplate}
class CompositeLayer {
/// {@macro composite_layer}
const CompositeLayer({
required this.angle,
required this.assetPath,
required this.constraints,
required this.position,
required this.size,
});
/// Factory which returns a [CompositeLayer] based on the provided [json].
factory CompositeLayer.fromJson(Map<dynamic, dynamic> json) {
return CompositeLayer(
angle: double.parse(json['angle'] as String),
assetPath: json['assetPath'] as String,
constraints: Vector2D.fromJson(json['constraints'] as Map),
position: Vector2D.fromJson(json['position'] as Map),
size: Vector2D.fromJson(json['size'] as Map),
);
}
/// Converts the current instance to a Map.
Map<String, dynamic> toJson() {
return <String, dynamic>{
'angle': '$angle',
'assetPath': assetPath,
'constraints': constraints.toJson(),
'position': position.toJson(),
'size': size.toJson(),
};
}
/// The angle of rotation in radians.
final double angle;
/// The absolute path to the asset.
final String assetPath;
/// The constraints used to normalize the asset.
final Vector2D constraints;
/// The relative position of the asset.
final Vector2D position;
/// The size of the asset.
final Vector2D size;
}
| photobooth/packages/image_compositor/lib/image_compositor.dart/0 | {
"file_path": "photobooth/packages/image_compositor/lib/image_compositor.dart",
"repo_id": "photobooth",
"token_count": 737
} | 1,139 |
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
const _smallTextScaleFactor = 0.80;
/// Namespace for the Photobooth [ThemeData].
class PhotoboothTheme {
/// Standard `ThemeData` for Photobooth UI.
static ThemeData get standard {
return ThemeData(
colorScheme: ColorScheme.fromSwatch(accentColor: PhotoboothColors.blue),
appBarTheme: _appBarTheme,
elevatedButtonTheme: _elevatedButtonTheme,
outlinedButtonTheme: _outlinedButtonTheme,
textTheme: _textTheme,
dialogBackgroundColor: PhotoboothColors.whiteBackground,
dialogTheme: _dialogTheme,
tooltipTheme: _tooltipTheme,
bottomSheetTheme: _bottomSheetTheme,
tabBarTheme: _tabBarTheme,
dividerTheme: _dividerTheme,
);
}
/// `ThemeData` for Photobooth UI for small screens.
static ThemeData get small {
return standard.copyWith(textTheme: _smallTextTheme);
}
/// `ThemeData` for Photobooth UI for medium screens.
static ThemeData get medium {
return standard.copyWith(textTheme: _smallTextTheme);
}
static TextTheme get _textTheme {
return TextTheme(
displayLarge: PhotoboothTextStyle.headline1,
displayMedium: PhotoboothTextStyle.headline2,
displaySmall: PhotoboothTextStyle.headline3,
headlineMedium: PhotoboothTextStyle.headline4,
headlineSmall: PhotoboothTextStyle.headline5,
titleLarge: PhotoboothTextStyle.headline6,
titleMedium: PhotoboothTextStyle.subtitle1,
titleSmall: PhotoboothTextStyle.subtitle2,
bodyLarge: PhotoboothTextStyle.bodyText1,
bodyMedium: PhotoboothTextStyle.bodyText2,
bodySmall: PhotoboothTextStyle.caption,
labelSmall: PhotoboothTextStyle.overline,
labelLarge: PhotoboothTextStyle.button,
);
}
static TextTheme get _smallTextTheme {
return TextTheme(
displayLarge: PhotoboothTextStyle.headline1.copyWith(
fontSize: _textTheme.displayLarge!.fontSize! * _smallTextScaleFactor,
),
displayMedium: PhotoboothTextStyle.headline2.copyWith(
fontSize: _textTheme.displayMedium!.fontSize! * _smallTextScaleFactor,
),
displaySmall: PhotoboothTextStyle.headline3.copyWith(
fontSize: _textTheme.displaySmall!.fontSize! * _smallTextScaleFactor,
),
headlineMedium: PhotoboothTextStyle.headline4.copyWith(
fontSize: _textTheme.headlineMedium!.fontSize! * _smallTextScaleFactor,
),
headlineSmall: PhotoboothTextStyle.headline5.copyWith(
fontSize: _textTheme.headlineSmall!.fontSize! * _smallTextScaleFactor,
),
titleLarge: PhotoboothTextStyle.headline6.copyWith(
fontSize: _textTheme.titleLarge!.fontSize! * _smallTextScaleFactor,
),
titleMedium: PhotoboothTextStyle.subtitle1.copyWith(
fontSize: _textTheme.titleMedium!.fontSize! * _smallTextScaleFactor,
),
titleSmall: PhotoboothTextStyle.subtitle2.copyWith(
fontSize: _textTheme.titleSmall!.fontSize! * _smallTextScaleFactor,
),
bodyLarge: PhotoboothTextStyle.bodyText1.copyWith(
fontSize: _textTheme.bodyLarge!.fontSize! * _smallTextScaleFactor,
),
bodyMedium: PhotoboothTextStyle.bodyText2.copyWith(
fontSize: _textTheme.bodyMedium!.fontSize! * _smallTextScaleFactor,
),
bodySmall: PhotoboothTextStyle.caption.copyWith(
fontSize: _textTheme.bodySmall!.fontSize! * _smallTextScaleFactor,
),
labelSmall: PhotoboothTextStyle.overline.copyWith(
fontSize: _textTheme.labelSmall!.fontSize! * _smallTextScaleFactor,
),
labelLarge: PhotoboothTextStyle.button.copyWith(
fontSize: _textTheme.labelLarge!.fontSize! * _smallTextScaleFactor,
),
);
}
static AppBarTheme get _appBarTheme {
return const AppBarTheme(color: PhotoboothColors.blue);
}
static ElevatedButtonThemeData get _elevatedButtonTheme {
return ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
elevation: 0,
backgroundColor: PhotoboothColors.blue,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30)),
),
padding: const EdgeInsets.symmetric(vertical: 16),
minimumSize: const Size(208, 54),
),
);
}
static OutlinedButtonThemeData get _outlinedButtonTheme {
return OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
foregroundColor: PhotoboothColors.white,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30)),
),
side: const BorderSide(color: PhotoboothColors.white, width: 2),
padding: const EdgeInsets.symmetric(vertical: 16),
minimumSize: const Size(208, 54),
),
);
}
static TooltipThemeData get _tooltipTheme {
return const TooltipThemeData(
decoration: BoxDecoration(
color: PhotoboothColors.charcoal,
borderRadius: BorderRadius.all(Radius.circular(5)),
),
padding: EdgeInsets.all(10),
textStyle: TextStyle(color: PhotoboothColors.white),
);
}
static DialogTheme get _dialogTheme {
return DialogTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
);
}
static BottomSheetThemeData get _bottomSheetTheme {
return const BottomSheetThemeData(
backgroundColor: PhotoboothColors.whiteBackground,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
),
);
}
static TabBarTheme get _tabBarTheme {
return const TabBarTheme(
indicator: UnderlineTabIndicator(
borderSide: BorderSide(
width: 2,
color: PhotoboothColors.blue,
),
),
labelColor: PhotoboothColors.blue,
unselectedLabelColor: PhotoboothColors.black25,
indicatorSize: TabBarIndicatorSize.tab,
);
}
static DividerThemeData get _dividerTheme {
return const DividerThemeData(
space: 0,
thickness: 1,
color: PhotoboothColors.black25,
);
}
}
| photobooth/packages/photobooth_ui/lib/src/theme.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/theme.dart",
"repo_id": "photobooth",
"token_count": 2373
} | 1,140 |
import 'package:flutter/material.dart';
/// {@template preview_image}
/// A wrapper around [Image.memory]
/// {@endtemplate}
class PreviewImage extends StatelessWidget {
/// {@macro preview_image}
const PreviewImage({
required this.data,
this.height,
this.width,
super.key,
});
/// Data URI representing the data of the image
final String data;
/// [double?] representing the height of the image
final double? height;
/// [double?] representing the width of the image
final double? width;
@override
Widget build(BuildContext context) {
return Image.network(
data,
filterQuality: FilterQuality.high,
isAntiAlias: true,
fit: BoxFit.cover,
height: height,
width: width,
errorBuilder: (context, error, stackTrace) {
return Text(
'$error, $stackTrace',
key: const Key('previewImage_errorText'),
);
},
);
}
}
| photobooth/packages/photobooth_ui/lib/src/widgets/preview_image.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/preview_image.dart",
"repo_id": "photobooth",
"token_count": 346
} | 1,141 |
// ignore_for_file: prefer_const_constructors
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flame/cache.dart';
import 'package:flame/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import '../../helpers/helpers.dart';
class MockImages extends Mock implements Images {}
class MockImage extends Mock implements ui.Image {}
void main() async {
TestWidgetsFlutterBinding.ensureInitialized();
group('AnimatedSprite', () {
late ui.Image image;
late Images images;
setUpAll(() async {
image = await decodeImageFromList(Uint8List.fromList(transparentImage));
});
setUp(() {
images = MockImages();
Flame.images = images;
});
testWidgets('renders AppCircularProgressIndicator when loading asset',
(tester) async {
await tester.pumpWidget(
AnimatedSprite(
sprites: Sprites(asset: 'test.png', size: Size(1, 1), frames: 1),
),
);
expect(find.byType(AppCircularProgressIndicator), findsOneWidget);
});
testWidgets(
'does not render AppCircularProgressIndicator'
' when loading asset and showLoadingIndicator is false',
(tester) async {
await tester.pumpWidget(
AnimatedSprite(
sprites: Sprites(asset: 'test.png', size: Size(1, 1), frames: 1),
showLoadingIndicator: false,
),
);
expect(find.byType(AppCircularProgressIndicator), findsNothing);
});
testWidgets('renders SpriteAnimationWidget when asset is loaded (loop)',
(tester) async {
await tester.runAsync(() async {
final images = MockImages();
when(() => images.load(any())).thenAnswer((_) async => image);
Flame.images = images;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: AnimatedSprite(
sprites: Sprites(
asset: 'test.png',
size: Size(1, 1),
frames: 1,
),
),
),
),
);
await tester.pump();
final spriteAnimationFinder = find.byType(SpriteAnimationWidget);
final widget = tester.widget<SpriteAnimationWidget>(
spriteAnimationFinder,
);
expect(widget.playing, isTrue);
});
});
testWidgets('renders SpriteAnimationWidget when asset is loaded (oneTime)',
(tester) async {
await tester.runAsync(() async {
final images = MockImages();
when(() => images.load(any())).thenAnswer((_) async => image);
Flame.images = images;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: AnimatedSprite(
sprites: Sprites(
asset: 'test.png',
size: Size(1, 1),
frames: 1,
),
mode: AnimationMode.oneTime,
),
),
),
);
await tester.pump();
final spriteAnimationFinder = find.byType(SpriteAnimationWidget);
final widget = tester.widget<SpriteAnimationWidget>(
spriteAnimationFinder,
);
expect(widget.playing, isTrue);
});
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/animated_sprite_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/widgets/animated_sprite_test.dart",
"repo_id": "photobooth",
"token_count": 1548
} | 1,142 |
import 'dart:typed_data';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_compositor/image_compositor.dart';
/// {@template upload_photo_exception}
/// Exception thrown when upload photo operation failed.
///
/// It contains a [message] field which describes the error.
/// {@endtemplate}
class UploadPhotoException implements Exception {
/// {@macro upload_photo_exception}
const UploadPhotoException(this.message);
/// Description of the failure
final String message;
@override
String toString() => message;
}
/// {@template composite_photo_exception}
/// Exception thrown when composite photo operation failed.
///
/// It contains a [message] field which describes the error.
/// {@endtemplate}
class CompositePhotoException implements Exception {
/// {@macro composite_photo_exception}
const CompositePhotoException(this.message);
/// Description of the failure
final String message;
@override
String toString() => message;
}
/// {@template share_urls}
/// A list of social share urls which are returned by the `sharePhoto` API.
/// {@endtemplate}
class ShareUrls {
/// {@macro share_urls}
const ShareUrls({
required this.explicitShareUrl,
required this.facebookShareUrl,
required this.twitterShareUrl,
});
/// The share url for explicit sharing.
final String explicitShareUrl;
/// The share url for sharing on Facebook.
final String facebookShareUrl;
/// The share url for sharing on Twitter.
final String twitterShareUrl;
}
const _shareUrl = 'https://io-photobooth-dev.web.app/share';
/// {@template photos_repository}
/// Repository that persists photos in a Firebase Storage.
/// {@endtemplate
class PhotosRepository {
/// {@macro photos_repository}
PhotosRepository({
required FirebaseStorage firebaseStorage,
ImageCompositor? imageCompositor,
}) : _firebaseStorage = firebaseStorage,
_imageCompositor = imageCompositor ?? ImageCompositor();
final FirebaseStorage _firebaseStorage;
final ImageCompositor _imageCompositor;
/// Uploads photo to the [FirebaseStorage] if it doesn't already exist
/// and returns [ShareUrls].
Future<ShareUrls> sharePhoto({
required String fileName,
required Uint8List data,
required String shareText,
}) async {
Reference reference;
try {
reference = _firebaseStorage.ref('uploads/$fileName');
} catch (e, st) {
throw UploadPhotoException(
'Uploading photo $fileName failed. '
"Couldn't get storage reference 'uploads/$fileName'.\n"
'Error: $e. StackTrace: $st',
);
}
if (await _photoExists(reference)) {
return ShareUrls(
explicitShareUrl: _getSharePhotoUrl(fileName),
facebookShareUrl: _facebookShareUrl(fileName, shareText),
twitterShareUrl: _twitterShareUrl(fileName, shareText),
);
}
try {
await reference.putData(data);
} catch (error, stackTrace) {
throw UploadPhotoException(
'Uploading photo $fileName failed. '
"Couldn't upload data to ${reference.fullPath}.\n"
'Error: $error. StackTrace: $stackTrace',
);
}
return ShareUrls(
explicitShareUrl: _getSharePhotoUrl(fileName),
facebookShareUrl: _facebookShareUrl(fileName, shareText),
twitterShareUrl: _twitterShareUrl(fileName, shareText),
);
}
/// Given an image ([data]) with the provided [layers]
/// it will return a ByteArray ([Uint8List]) which represents a
/// composite of the original [data] and [layers] which is cropped for
/// the provided [aspectRatio].
Future<Uint8List> composite({
required int width,
required int height,
required String data,
required List<CompositeLayer> layers,
required double aspectRatio,
}) async {
try {
final image = await _imageCompositor.composite(
data: data,
width: width,
height: height,
layers: layers.map((l) => l.toJson()).toList(),
aspectRatio: aspectRatio,
);
return Uint8List.fromList(image);
} catch (error, stackTrace) {
throw CompositePhotoException(
'compositing photo failed. '
'Error: $error. StackTrace: $stackTrace',
);
}
}
Future<bool> _photoExists(Reference reference) async {
try {
await reference.getDownloadURL();
return true;
} catch (_) {
return false;
}
}
String _twitterShareUrl(String photoName, String shareText) {
final encodedShareText = Uri.encodeComponent(shareText);
return 'https://twitter.com/intent/tweet?url=${_getSharePhotoUrl(photoName)}&text=$encodedShareText';
}
String _facebookShareUrl(String photoName, String shareText) {
final encodedShareText = Uri.encodeComponent(shareText);
return 'https://www.facebook.com/sharer.php?u=${_getSharePhotoUrl(photoName)}"e=$encodedShareText';
}
String _getSharePhotoUrl(String photoName) => '$_shareUrl/$photoName';
}
| photobooth/packages/photos_repository/lib/src/photos_repository.dart/0 | {
"file_path": "photobooth/packages/photos_repository/lib/src/photos_repository.dart",
"repo_id": "photobooth",
"token_count": 1686
} | 1,143 |
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{folder}/{imageId} {
allow read: if imageId.matches(".*\\.png") || imageId.matches(".*\\.jpg");
allow write: if false;
}
}
}
| photobooth/storage.rules/0 | {
"file_path": "photobooth/storage.rules",
"repo_id": "photobooth",
"token_count": 100
} | 1,144 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/photobooth/widgets/widgets.dart';
import '../../helpers/helpers.dart';
void main() {
group('CharacterIconButton', () {
testWidgets('renders', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: CharacterIconButton(
isSelected: true,
icon: const AssetImage('assets/icons/dash_icon.png'),
label: 'Dash',
),
),
),
);
expect(find.byType(CharacterIconButton), findsOneWidget);
});
testWidgets('is tappable', (tester) async {
var tapCounter = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: CharacterIconButton(
isSelected: true,
icon: const AssetImage('assets/icons/dash_icon.png'),
label: 'Dash',
onPressed: () => tapCounter++,
),
),
),
);
await tester.tap(find.byType(CharacterIconButton));
await tester.pumpAndSettle();
expect(tapCounter, equals(1));
});
testWidgets('renders big Ink widget when orientation is landscape',
(tester) async {
tester.setDisplaySize(landscapeDisplaySize);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: CharacterIconButton(
isSelected: true,
icon: const AssetImage('assets/icons/dash_icon.png'),
label: 'Dash',
),
),
),
);
final inkWidget = tester.widget<Ink>(
find.descendant(
of: find.byType(CharacterIconButton),
matching: find.byType(Ink),
),
);
expect(inkWidget.height, equals(90));
expect(inkWidget.width, equals(90));
});
testWidgets('renders small Ink widget when orientation is portrait',
(tester) async {
tester.setDisplaySize(portraitDisplaySize);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: CharacterIconButton(
isSelected: true,
icon: const AssetImage('assets/icons/dash_icon.png'),
label: 'Dash',
),
),
),
);
final inkWidget = tester.widget<Ink>(
find.descendant(
of: find.byType(CharacterIconButton),
matching: find.byType(Ink),
),
);
expect(inkWidget.height, equals(60));
expect(inkWidget.width, equals(60));
});
testWidgets('has a semantic label', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: CharacterIconButton(
isSelected: true,
icon: const AssetImage('assets/icons/dash_icon.png'),
label: 'Dash',
onPressed: () {},
),
),
),
);
expect(find.bySemanticsLabel('Dash'), findsOneWidget);
});
});
}
| photobooth/test/photobooth/widgets/character_icon_button_test.dart/0 | {
"file_path": "photobooth/test/photobooth/widgets/character_icon_button_test.dart",
"repo_id": "photobooth",
"token_count": 1526
} | 1,145 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/share/share.dart';
import '../../helpers/helpers.dart';
class MockClipboard {
Object get clipboardData => _clipboardData;
Object _clipboardData = <String, dynamic>{
'text': null,
};
Future<dynamic> handleMethodCall(MethodCall methodCall) async {
switch (methodCall.method) {
case 'Clipboard.getData':
return _clipboardData;
case 'Clipboard.setData':
_clipboardData = methodCall.arguments as Object;
break;
}
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const link = 'https://example.com/share/image.png';
const suspendDuration = Duration(seconds: 5);
group('ShareCopyableLink', () {
MockClipboard? clipboard;
setUp(() {
clipboard = MockClipboard();
SystemChannels.platform
.setMockMethodCallHandler(clipboard?.handleMethodCall);
});
testWidgets(
'tapping on copy button '
'sets link in the clipboard', (tester) async {
await tester.pumpApp(ShareCopyableLink(link: link));
await tester.tap(find.byKey(Key('shareCopyableLink_copyButton')));
await tester.pumpAndSettle();
expect(clipboard?.clipboardData, equals({'text': link}));
});
testWidgets(
'tapping on copy button '
'sets copied to true', (tester) async {
await tester.pumpApp(ShareCopyableLink(link: link));
await tester.tap(find.byKey(Key('shareCopyableLink_copyButton')));
await tester.pumpAndSettle();
final state = tester.state<ShareCopyableLinkState>(
find.byType(ShareCopyableLink),
);
expect(state.copied, isTrue);
});
testWidgets(
'tapping on copy button '
'sets copied to true '
'and resets copied to false after suspendDuration time',
(tester) async {
await tester.pumpApp(ShareCopyableLink(link: link));
await tester.tap(find.byKey(Key('shareCopyableLink_copyButton')));
await tester.pumpAndSettle();
final state1 = tester.state<ShareCopyableLinkState>(
find.byType(ShareCopyableLink),
);
expect(state1.copied, isTrue);
await tester.pump(suspendDuration);
final state2 = tester.state<ShareCopyableLinkState>(
find.byType(ShareCopyableLink),
);
expect(state2.copied, isFalse);
});
testWidgets(
'tapping on copy button '
'hides copy button for suspendDuration time', (tester) async {
await tester.pumpApp(ShareCopyableLink(link: link));
await tester.tap(find.byKey(Key('shareCopyableLink_copyButton')));
await tester.pumpAndSettle();
expect(find.byKey(Key('shareCopyableLink_copyButton')), findsNothing);
await tester.pump(suspendDuration);
expect(find.byKey(Key('shareCopyableLink_copyButton')), findsOneWidget);
});
testWidgets(
'tapping on copy button '
'reveals copied button for suspendDuration time', (tester) async {
await tester.pumpApp(ShareCopyableLink(link: link));
expect(find.byKey(Key('shareCopyableLink_copiedButton')), findsNothing);
await tester.tap(find.byKey(Key('shareCopyableLink_copyButton')));
await tester.pumpAndSettle();
expect(find.byKey(Key('shareCopyableLink_copiedButton')), findsOneWidget);
await tester.pump(suspendDuration);
await tester.pump();
expect(find.byKey(Key('shareCopyableLink_copiedButton')), findsNothing);
});
testWidgets(
'tapping on copied button '
'resets copied to false', (tester) async {
await tester.pumpApp(ShareCopyableLink(link: link));
await tester.tap(find.byKey(Key('shareCopyableLink_copyButton')));
await tester.pumpAndSettle();
final state1 = tester.state<ShareCopyableLinkState>(
find.byType(ShareCopyableLink),
);
expect(state1.copied, isTrue);
await tester.tap(find.byKey(Key('shareCopyableLink_copiedButton')));
await tester.pumpAndSettle();
final state2 = tester.state<ShareCopyableLinkState>(
find.byType(ShareCopyableLink),
);
expect(state2.copied, isFalse);
});
testWidgets('timer is closed when widget is disposed', (tester) async {
await tester.pumpApp(ShareCopyableLink(link: link));
await tester.tap(find.byKey(Key('shareCopyableLink_copyButton')));
await tester.pumpAndSettle();
final state = tester.state<ShareCopyableLinkState>(
find.byType(ShareCopyableLink),
);
expect(state.timer?.isActive, isTrue);
await tester.pumpWidget(Container());
expect(state.timer?.isActive, isFalse);
});
});
}
| photobooth/test/share/widgets/share_copyable_link_test.dart/0 | {
"file_path": "photobooth/test/share/widgets/share_copyable_link_test.dart",
"repo_id": "photobooth",
"token_count": 1917
} | 1,146 |
if (typeof firebase === 'undefined') throw new Error('hosting/init-error: Firebase SDK not detected. You must include it before /__/firebase/init.js');
var firebaseConfig = {
"projectId": "io-photobooth-dev",
"appId": "1:931695903758:web:33a07d199e97fa53f4a85f",
"storageBucket": "io-photobooth-dev.appspot.com",
"locationId": "us-central",
"apiKey": "AIzaSyAwrGoDm6syeESeWV1HApzDKZEomMEtR4U",
"authDomain": "io-photobooth-dev.firebaseapp.com",
"messagingSenderId": "931695903758"
};
if (firebaseConfig) {
firebase.initializeApp(firebaseConfig);
var firebaseEmulators = undefined;
if (firebaseEmulators) {
console.log("Automatically connecting Firebase SDKs to running emulators:");
Object.keys(firebaseEmulators).forEach(function(key) {
console.log('\t' + key + ': http://' + firebaseEmulators[key].host + ':' + firebaseEmulators[key].port );
});
if (firebaseEmulators.database && typeof firebase.database === 'function') {
firebase.database().useEmulator(firebaseEmulators.database.host, firebaseEmulators.database.port);
}
if (firebaseEmulators.firestore && typeof firebase.firestore === 'function') {
firebase.firestore().useEmulator(firebaseEmulators.firestore.host, firebaseEmulators.firestore.port);
}
if (firebaseEmulators.functions && typeof firebase.functions === 'function') {
firebase.functions().useEmulator(firebaseEmulators.functions.host, firebaseEmulators.functions.port);
}
if (firebaseEmulators.auth && typeof firebase.auth === 'function') {
firebase.auth().useEmulator('http://' + firebaseEmulators.auth.host + ':' + firebaseEmulators.auth.port);
}
} else {
console.log("To automatically connect the Firebase SDKs to running emulators, replace '/__/firebase/init.js' with '/__/firebase/init.js?useEmulator=true' in your index.html");
}
}
| photobooth/web/__/firebase/init.js/0 | {
"file_path": "photobooth/web/__/firebase/init.js",
"repo_id": "photobooth",
"token_count": 666
} | 1,147 |
import 'dart:async';
import 'dart:developer';
import 'package:bloc/bloc.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/widgets.dart';
class AppBlocObserver extends BlocObserver {
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
log('onChange(${bloc.runtimeType}, $change)');
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
log('onError(${bloc.runtimeType}, $error, $stackTrace)');
super.onError(bloc, error, stackTrace);
}
}
typedef BootstrapBuilder = Future<Widget> Function(
FirebaseFirestore firestore,
FirebaseAuth firebaseAuth,
);
Future<void> bootstrap(BootstrapBuilder builder) async {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (details) {
log(details.exceptionAsString(), stackTrace: details.stack);
};
await runZonedGuarded(
() async {
await BlocOverrides.runZoned(
() async => runApp(
await builder(
FirebaseFirestore.instance,
FirebaseAuth.instance,
),
),
blocObserver: AppBlocObserver(),
);
},
(error, stackTrace) => log(error.toString(), stackTrace: stackTrace),
);
}
| pinball/lib/bootstrap.dart/0 | {
"file_path": "pinball/lib/bootstrap.dart",
"repo_id": "pinball",
"token_count": 509
} | 1,148 |
// ignore_for_file: avoid_renaming_method_parameters
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flutter/material.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart';
import 'package:pinball_components/pinball_components.dart';
/// {@template android_acres}
/// Area positioned on the left side of the board containing the
/// [AndroidSpaceship], [SpaceshipRamp], [SpaceshipRail], and [AndroidBumper]s.
/// {@endtemplate}
class AndroidAcres extends Component {
/// {@macro android_acres}
AndroidAcres()
: super(
children: [
SpaceshipRamp(
children: [
RampShotBehavior(points: Points.fiveThousand),
RampBonusBehavior(points: Points.oneMillion),
RampProgressBehavior(),
RampMultiplierBehavior(),
RampResetBehavior(),
],
),
SpaceshipRail(),
AndroidBumper.a(
children: [
ScoringContactBehavior(points: Points.twentyThousand),
BumperNoiseBehavior(),
],
)..initialPosition = Vector2(-25.2, 1.5),
AndroidBumper.b(
children: [
ScoringContactBehavior(points: Points.twentyThousand),
BumperNoiseBehavior(),
],
)..initialPosition = Vector2(-32.9, -9.3),
AndroidBumper.cow(
children: [
ScoringContactBehavior(points: Points.twentyThousand),
BumperNoiseBehavior(),
CowBumperNoiseBehavior(),
],
)..initialPosition = Vector2(-20.7, -13),
FlameBlocProvider<AndroidSpaceshipCubit, AndroidSpaceshipState>(
create: AndroidSpaceshipCubit.new,
children: [
AndroidSpaceship(position: Vector2(-26.5, -28.5)),
AndroidAnimatronic(
children: [
ScoringContactBehavior(points: Points.twoHundredThousand),
],
)..initialPosition = Vector2(-26, -28.25),
AndroidSpaceshipBonusBehavior(),
],
),
],
);
/// Creates [AndroidAcres] without any children.
///
/// This can be used for testing [AndroidAcres]'s behaviors in isolation.
@visibleForTesting
AndroidAcres.test();
}
| pinball/lib/game/components/android_acres/android_acres.dart/0 | {
"file_path": "pinball/lib/game/components/android_acres/android_acres.dart",
"repo_id": "pinball",
"token_count": 1221
} | 1,149 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.