text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:google_identity_services_web/id.dart';
import 'jsify_as.dart';
/// A CredentialResponse with null `credential`.
final CredentialResponse nullCredential =
jsifyAs<CredentialResponse>(<String, Object?>{
'credential': null,
});
/// A CredentialResponse wrapping a known good JWT Token as its `credential`.
final CredentialResponse goodCredential =
jsifyAs<CredentialResponse>(<String, Object?>{
'credential': goodJwtToken,
});
/// A CredentialResponse wrapping a known good JWT Token as its `credential`.
final CredentialResponse minimalCredential =
jsifyAs<CredentialResponse>(<String, Object?>{
'credential': minimalJwtToken,
});
final CredentialResponse expiredCredential =
jsifyAs<CredentialResponse>(<String, Object?>{
'credential': expiredJwtToken,
});
/// A JWT token with predefined values.
///
/// 'email': '[email protected]',
/// 'sub': '123456',
/// 'name': 'Vincent Adultman',
/// 'picture': 'https://thispersondoesnotexist.com/image?x=.jpg',
///
/// Signed with HS256 and the private key: 'symmetric-encryption-is-weak'
const String goodJwtToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.$goodPayload.lqzULA_U3YzEl_-fL7YLU-kFXmdD2ttJLTv-UslaNQ4';
/// The payload of a JWT token that contains predefined values.
///
/// 'email': '[email protected]',
/// 'sub': '123456',
/// 'name': 'Vincent Adultman',
/// 'picture': 'https://thispersondoesnotexist.com/image?x=.jpg',
const String goodPayload =
'eyJlbWFpbCI6ImFkdWx0bWFuQGV4YW1wbGUuY29tIiwic3ViIjoiMTIzNDU2IiwibmFtZSI6IlZpbmNlbnQgQWR1bHRtYW4iLCJwaWN0dXJlIjoiaHR0cHM6Ly90aGlzcGVyc29uZG9lc25vdGV4aXN0LmNvbS9pbWFnZT94PS5qcGcifQ';
/// A JWT token with minimal set of predefined values.
///
/// 'email': '[email protected]',
/// 'sub': '123456'
///
/// Signed with HS256 and the private key: 'symmetric-encryption-is-weak'
const String minimalJwtToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.$minimalPayload.UTAe7dpdtFIMwsOqkZkjyjqyHnho5xHCcQylUFmOutM';
/// The payload of a JWT token that contains only non-nullable values.
///
/// 'email': '[email protected]',
/// 'sub': '123456'
const String minimalPayload =
'eyJlbWFpbCI6ImFkdWx0bWFuQGV4YW1wbGUuY29tIiwic3ViIjoiMTIzNDU2In0';
/// A JWT token with minimal set of predefined values and an expiration timestamp.
///
/// 'email': '[email protected]',
/// 'sub': '123456',
/// 'exp': 1430330400
///
/// Signed with HS256 and the private key: 'symmetric-encryption-is-weak'
const String expiredJwtToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.$expiredPayload.--gb5tnVSSsLg4zjjVH0FUUvT4rbehIcnBhB-8Iekm4';
/// The payload of a JWT token that contains only non-nullable values, and an
/// expiration timestamp of 1430330400 (Wednesday, April 29, 2015 6:00:00 PM UTC)
///
/// 'email': '[email protected]',
/// 'sub': '123456',
/// 'exp': 1430330400
const String expiredPayload =
'eyJlbWFpbCI6ImFkdWx0bWFuQGV4YW1wbGUuY29tIiwic3ViIjoiMTIzNDU2IiwiZXhwIjoxNDMwMzMwNDAwfQ';
// More encrypted JWT Tokens may be created on https://jwt.io.
//
// First, decode the `goodJwtToken` above, modify to your heart's
// content, and add a new credential here.
//
// (New tokens can also be created with `package:jose` and `dart:convert`.)
| packages/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart",
"repo_id": "packages",
"token_count": 1339
} | 979 |
// 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:google_identity_services_web/id.dart';
import 'package:google_identity_services_web/oauth2.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
/// A codec that can encode/decode JWT payloads.
///
/// See https://www.rfc-editor.org/rfc/rfc7519#section-3
final Codec<Object?, String> jwtCodec = json.fuse(utf8).fuse(base64);
/// A RegExp that can match, and extract parts from a JWT Token.
///
/// A JWT token consists of 3 base-64 encoded parts of data separated by periods:
///
/// header.payload.signature
///
/// More info: https://regexr.com/789qc
final RegExp jwtTokenRegexp = RegExp(
r'^(?<header>[^\.\s]+)\.(?<payload>[^\.\s]+)\.(?<signature>[^\.\s]+)$');
/// Decodes the `claims` of a JWT token and returns them as a Map.
///
/// JWT `claims` are stored as a JSON object in the `payload` part of the token.
///
/// (This method does not validate the signature of the token.)
///
/// See https://www.rfc-editor.org/rfc/rfc7519#section-3
Map<String, Object?>? getJwtTokenPayload(String? token) {
if (token != null) {
final RegExpMatch? match = jwtTokenRegexp.firstMatch(token);
if (match != null) {
return decodeJwtPayload(match.namedGroup('payload'));
}
}
return null;
}
/// Decodes a JWT payload using the [jwtCodec].
Map<String, Object?>? decodeJwtPayload(String? payload) {
try {
// Payload must be normalized before passing it to the codec
return jwtCodec.decode(base64.normalize(payload!)) as Map<String, Object?>?;
} catch (_) {
// Do nothing, we always return null for any failure.
}
return null;
}
/// Returns the payload of a [CredentialResponse].
Map<String, Object?>? getResponsePayload(CredentialResponse? response) {
if (response?.credential == null) {
return null;
}
return getJwtTokenPayload(response!.credential);
}
/// Converts a [CredentialResponse] into a [GoogleSignInUserData].
///
/// May return `null`, if the `credentialResponse` is null, or its `credential`
/// cannot be decoded.
GoogleSignInUserData? gisResponsesToUserData(
CredentialResponse? credentialResponse) {
final Map<String, Object?>? payload = getResponsePayload(credentialResponse);
if (payload == null) {
return null;
}
assert(credentialResponse?.credential != null,
'The CredentialResponse cannot be null and have a payload.');
return GoogleSignInUserData(
email: payload['email']! as String,
id: payload['sub']! as String,
displayName: payload['name'] as String?,
photoUrl: payload['picture'] as String?,
idToken: credentialResponse!.credential,
);
}
/// Returns the expiration timestamp ('exp') of a [CredentialResponse].
///
/// May return `null` if the `credentialResponse` is null, its `credential`
/// cannot be decoded, or the `exp` field is not set on the JWT payload.
DateTime? getCredentialResponseExpirationTimestamp(
CredentialResponse? credentialResponse) {
final Map<String, Object?>? payload = getResponsePayload(credentialResponse);
// Get the 'exp' field from the payload, if present.
final int? exp = (payload != null) ? payload['exp'] as int? : null;
// Return 'exp' (a timestamp in seconds since Epoch) as a DateTime.
return (exp != null) ? DateTime.fromMillisecondsSinceEpoch(exp * 1000) : null;
}
/// Converts responses from the GIS library into TokenData for the plugin.
GoogleSignInTokenData gisResponsesToTokenData(
CredentialResponse? credentialResponse,
TokenResponse? tokenResponse, [
CodeResponse? codeResponse,
]) {
return GoogleSignInTokenData(
idToken: credentialResponse?.credential,
accessToken: tokenResponse?.access_token,
serverAuthCode: codeResponse?.code,
);
}
| packages/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart",
"repo_id": "packages",
"token_count": 1289
} | 980 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/image_picker/image_picker/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "packages/packages/image_picker/image_picker/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 981 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'image_picker_test.mocks.dart' as base_mock;
// Add the mixin to make the platform interface accept the mock.
class _MockImagePickerPlatform extends base_mock.MockImagePickerPlatform
with MockPlatformInterfaceMixin {}
@GenerateMocks(<Type>[],
customMocks: <MockSpec<dynamic>>[MockSpec<ImagePickerPlatform>()])
void main() {
group('ImagePicker', () {
late _MockImagePickerPlatform mockPlatform;
setUp(() {
mockPlatform = _MockImagePickerPlatform();
ImagePickerPlatform.instance = mockPlatform;
});
group('#Single image/video', () {
group('#pickImage', () {
setUp(() {
when(mockPlatform.getImageFromSource(
source: anyNamed('source'), options: anyNamed('options')))
.thenAnswer((Invocation _) async => null);
});
test('passes the image source argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(source: ImageSource.camera);
await picker.pickImage(source: ImageSource.gallery);
verifyInOrder(<Object>[
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>(),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.gallery,
options: argThat(
isInstanceOf<ImagePickerOptions>(),
named: 'options',
),
),
]);
});
test('passes the width and height arguments correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(source: ImageSource.camera);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
);
await picker.pickImage(
source: ImageSource.camera,
maxHeight: 10.0,
);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.pickImage(
source: ImageSource.camera, maxWidth: 10.0, imageQuality: 70);
await picker.pickImage(
source: ImageSource.camera, maxHeight: 10.0, imageQuality: 70);
await picker.pickImage(
source: ImageSource.camera,
maxWidth: 10.0,
maxHeight: 20.0,
imageQuality: 70);
verifyInOrder(<Object>[
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', isNull)
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', isNull)
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
isNull),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', equals(10.0))
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', isNull)
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
isNull),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', isNull)
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', equals(10.0))
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
isNull),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', equals(10.0))
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', equals(20.0))
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
isNull),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', equals(10.0))
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', isNull)
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', isNull)
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', equals(10.0))
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>()
.having((ImagePickerOptions options) => options.maxWidth,
'maxWidth', equals(10.0))
.having((ImagePickerOptions options) => options.maxHeight,
'maxHeight', equals(20.0))
.having(
(ImagePickerOptions options) => options.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
]);
});
test('does not accept a negative width or height argument', () {
final ImagePicker picker = ImagePicker();
expect(
() => picker.pickImage(source: ImageSource.camera, maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickImage(source: ImageSource.camera, maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles a null image file response gracefully', () async {
final ImagePicker picker = ImagePicker();
expect(await picker.pickImage(source: ImageSource.gallery), isNull);
expect(await picker.pickImage(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(source: ImageSource.camera);
verify(mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>().having(
(ImagePickerOptions options) => options.preferredCameraDevice,
'preferredCameraDevice',
equals(CameraDevice.rear)),
named: 'options',
),
));
});
test('camera position can set to front', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
verify(mockPlatform.getImageFromSource(
source: ImageSource.camera,
options: argThat(
isInstanceOf<ImagePickerOptions>().having(
(ImagePickerOptions options) => options.preferredCameraDevice,
'preferredCameraDevice',
equals(CameraDevice.front)),
named: 'options',
),
));
});
test('full metadata argument defaults to true', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(source: ImageSource.gallery);
verify(mockPlatform.getImageFromSource(
source: ImageSource.gallery,
options: argThat(
isInstanceOf<ImagePickerOptions>().having(
(ImagePickerOptions options) => options.requestFullMetadata,
'requestFullMetadata',
isTrue),
named: 'options',
),
));
});
test('passes the full metadata argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickImage(
source: ImageSource.gallery,
requestFullMetadata: false,
);
verify(mockPlatform.getImageFromSource(
source: ImageSource.gallery,
options: argThat(
isInstanceOf<ImagePickerOptions>().having(
(ImagePickerOptions options) => options.requestFullMetadata,
'requestFullMetadata',
isFalse),
named: 'options',
),
));
});
});
group('#pickVideo', () {
setUp(() {
when(mockPlatform.getVideo(
source: anyNamed('source'),
preferredCameraDevice: anyNamed('preferredCameraDevice'),
maxDuration: anyNamed('maxDuration')))
.thenAnswer((Invocation _) async => null);
});
test('passes the image source argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickVideo(source: ImageSource.camera);
await picker.pickVideo(source: ImageSource.gallery);
verifyInOrder(<Object>[
mockPlatform.getVideo(source: ImageSource.camera),
mockPlatform.getVideo(source: ImageSource.gallery),
]);
});
test('passes the duration argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickVideo(source: ImageSource.camera);
await picker.pickVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 10));
verifyInOrder(<Object>[
mockPlatform.getVideo(source: ImageSource.camera),
mockPlatform.getVideo(
source: ImageSource.camera,
maxDuration: const Duration(seconds: 10)),
]);
});
test('handles a null video file response gracefully', () async {
final ImagePicker picker = ImagePicker();
expect(await picker.pickVideo(source: ImageSource.gallery), isNull);
expect(await picker.pickVideo(source: ImageSource.camera), isNull);
});
test('camera position defaults to back', () async {
final ImagePicker picker = ImagePicker();
await picker.pickVideo(source: ImageSource.camera);
verify(mockPlatform.getVideo(source: ImageSource.camera));
});
test('camera position can set to front', () async {
final ImagePicker picker = ImagePicker();
await picker.pickVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front);
verify(mockPlatform.getVideo(
source: ImageSource.camera,
preferredCameraDevice: CameraDevice.front));
});
});
group('#retrieveLostData', () {
test('retrieveLostData get success response', () async {
final ImagePicker picker = ImagePicker();
final XFile lostFile = XFile('/example/path');
when(mockPlatform.getLostData()).thenAnswer((Invocation _) async =>
LostDataResponse(
file: lostFile,
files: <XFile>[lostFile],
type: RetrieveType.image));
final LostDataResponse response = await picker.retrieveLostData();
expect(response.type, RetrieveType.image);
expect(response.file!.path, '/example/path');
});
test('retrieveLostData should successfully retrieve multiple files',
() async {
final ImagePicker picker = ImagePicker();
final List<XFile> lostFiles = <XFile>[
XFile('/example/path0'),
XFile('/example/path1'),
];
when(mockPlatform.getLostData()).thenAnswer((Invocation _) async =>
LostDataResponse(
file: lostFiles.last,
files: lostFiles,
type: RetrieveType.image));
final LostDataResponse response = await picker.retrieveLostData();
expect(response.type, RetrieveType.image);
expect(response.file, isNotNull);
expect(response.file!.path, '/example/path1');
expect(response.files!.first.path, '/example/path0');
expect(response.files!.length, 2);
});
test('retrieveLostData get error response', () async {
final ImagePicker picker = ImagePicker();
when(mockPlatform.getLostData()).thenAnswer((Invocation _) async =>
LostDataResponse(
exception: PlatformException(
code: 'test_error_code', message: 'test_error_message'),
type: RetrieveType.video));
final LostDataResponse response = await picker.retrieveLostData();
expect(response.type, RetrieveType.video);
expect(response.exception!.code, 'test_error_code');
expect(response.exception!.message, 'test_error_message');
});
});
});
group('#Multi images', () {
setUp(() {
when(
mockPlatform.getMultiImageWithOptions(
options: anyNamed('options'),
),
).thenAnswer((Invocation _) async => <XFile>[]);
});
group('#pickMultiImage', () {
test('passes the width and height arguments correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultiImage();
await picker.pickMultiImage(
maxWidth: 10.0,
);
await picker.pickMultiImage(
maxHeight: 10.0,
);
await picker.pickMultiImage(
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.pickMultiImage(
maxWidth: 10.0,
imageQuality: 70,
);
await picker.pickMultiImage(
maxHeight: 10.0,
imageQuality: 70,
);
await picker.pickMultiImage(
maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70);
verifyInOrder(<Object>[
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>(),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>().having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxWidth',
equals(10.0)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>().having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(10.0)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>()
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(20.0)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>()
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>()
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>()
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.maxWidth,
'maxHeight',
equals(10.0))
.having(
(MultiImagePickerOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
]);
});
test('does not accept a negative width or height argument', () {
final ImagePicker picker = ImagePicker();
expect(
() => picker.pickMultiImage(maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickMultiImage(maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles an empty image file response gracefully', () async {
final ImagePicker picker = ImagePicker();
expect(await picker.pickMultiImage(), isEmpty);
expect(await picker.pickMultiImage(), isEmpty);
});
test('full metadata argument defaults to true', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultiImage();
verify(mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>().having(
(MultiImagePickerOptions options) =>
options.imageOptions.requestFullMetadata,
'requestFullMetadata',
isTrue),
named: 'options',
),
));
});
test('passes the full metadata argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultiImage(
requestFullMetadata: false,
);
verify(mockPlatform.getMultiImageWithOptions(
options: argThat(
isInstanceOf<MultiImagePickerOptions>().having(
(MultiImagePickerOptions options) =>
options.imageOptions.requestFullMetadata,
'requestFullMetadata',
isFalse),
named: 'options',
),
));
});
});
});
group('#Media', () {
setUp(() {
when(
mockPlatform.getMedia(
options: anyNamed('options'),
),
).thenAnswer((Invocation _) async => <XFile>[]);
});
group('#pickMedia', () {
test('passes the width and height arguments correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMedia();
await picker.pickMedia(
maxWidth: 10.0,
);
await picker.pickMedia(
maxHeight: 10.0,
);
await picker.pickMedia(
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.pickMedia(
maxWidth: 10.0,
imageQuality: 70,
);
await picker.pickMedia(
maxHeight: 10.0,
imageQuality: 70,
);
await picker.pickMedia(
maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70);
verifyInOrder(<Object>[
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>(),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>().having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxWidth',
equals(10.0)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>().having(
(MediaOptions options) => options.imageOptions.maxHeight,
'maxHeight',
equals(10.0)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>()
.having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MediaOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(20.0)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>()
.having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MediaOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>()
.having(
(MediaOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(10.0))
.having(
(MediaOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>()
.having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxHeight',
equals(10.0))
.having(
(MediaOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
]);
});
test('does not accept a negative width or height argument', () {
final ImagePicker picker = ImagePicker();
expect(
() => picker.pickMedia(maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickMedia(maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles an empty image file response gracefully', () async {
final ImagePicker picker = ImagePicker();
expect(await picker.pickMedia(), isNull);
expect(await picker.pickMedia(), isNull);
});
test('full metadata argument defaults to true', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMedia();
verify(mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>().having(
(MediaOptions options) =>
options.imageOptions.requestFullMetadata,
'requestFullMetadata',
isTrue),
named: 'options',
),
));
});
test('passes the full metadata argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMedia(
requestFullMetadata: false,
);
verify(mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>().having(
(MediaOptions options) =>
options.imageOptions.requestFullMetadata,
'requestFullMetadata',
isFalse),
named: 'options',
),
));
});
});
group('#pickMultipleMedia', () {
test('passes the width and height arguments correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultipleMedia();
await picker.pickMultipleMedia(
maxWidth: 10.0,
);
await picker.pickMultipleMedia(
maxHeight: 10.0,
);
await picker.pickMultipleMedia(
maxWidth: 10.0,
maxHeight: 20.0,
);
await picker.pickMultipleMedia(
maxWidth: 10.0,
imageQuality: 70,
);
await picker.pickMultipleMedia(
maxHeight: 10.0,
imageQuality: 70,
);
await picker.pickMultipleMedia(
maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70);
verifyInOrder(<Object>[
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>(),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>().having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxWidth',
equals(10.0)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>().having(
(MediaOptions options) => options.imageOptions.maxHeight,
'maxHeight',
equals(10.0)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>()
.having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MediaOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(20.0)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>()
.having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MediaOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>()
.having(
(MediaOptions options) =>
options.imageOptions.maxHeight,
'maxHeight',
equals(10.0))
.having(
(MediaOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>()
.having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxWidth',
equals(10.0))
.having(
(MediaOptions options) => options.imageOptions.maxWidth,
'maxHeight',
equals(10.0))
.having(
(MediaOptions options) =>
options.imageOptions.imageQuality,
'imageQuality',
equals(70)),
named: 'options',
),
),
]);
});
test('does not accept a negative width or height argument', () {
final ImagePicker picker = ImagePicker();
expect(
() => picker.pickMultipleMedia(maxWidth: -1.0),
throwsArgumentError,
);
expect(
() => picker.pickMultipleMedia(maxHeight: -1.0),
throwsArgumentError,
);
});
test('handles an empty image file response gracefully', () async {
final ImagePicker picker = ImagePicker();
expect(await picker.pickMultipleMedia(), isEmpty);
expect(await picker.pickMultipleMedia(), isEmpty);
});
test('full metadata argument defaults to true', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultipleMedia();
verify(mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>().having(
(MediaOptions options) =>
options.imageOptions.requestFullMetadata,
'requestFullMetadata',
isTrue),
named: 'options',
),
));
});
test('passes the full metadata argument correctly', () async {
final ImagePicker picker = ImagePicker();
await picker.pickMultipleMedia(
requestFullMetadata: false,
);
verify(mockPlatform.getMedia(
options: argThat(
isInstanceOf<MediaOptions>().having(
(MediaOptions options) =>
options.imageOptions.requestFullMetadata,
'requestFullMetadata',
isFalse),
named: 'options',
),
));
});
});
test('supportsImageSource calls through to platform', () async {
final ImagePicker picker = ImagePicker();
when(mockPlatform.supportsImageSource(any)).thenReturn(true);
final bool supported = picker.supportsImageSource(ImageSource.camera);
expect(supported, true);
verify(mockPlatform.supportsImageSource(ImageSource.camera));
});
});
});
}
| packages/packages/image_picker/image_picker/test/image_picker_test.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker/test/image_picker_test.dart",
"repo_id": "packages",
"token_count": 18656
} | 982 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.imagepicker;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.embedding.engine.plugins.lifecycle.FlutterLifecycleAdapter;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.imagepicker.Messages.CacheRetrievalResult;
import io.flutter.plugins.imagepicker.Messages.FlutterError;
import io.flutter.plugins.imagepicker.Messages.GeneralOptions;
import io.flutter.plugins.imagepicker.Messages.ImagePickerApi;
import io.flutter.plugins.imagepicker.Messages.ImageSelectionOptions;
import io.flutter.plugins.imagepicker.Messages.MediaSelectionOptions;
import io.flutter.plugins.imagepicker.Messages.Result;
import io.flutter.plugins.imagepicker.Messages.SourceCamera;
import io.flutter.plugins.imagepicker.Messages.SourceSpecification;
import io.flutter.plugins.imagepicker.Messages.VideoSelectionOptions;
import java.util.List;
@SuppressWarnings("deprecation")
public class ImagePickerPlugin implements FlutterPlugin, ActivityAware, ImagePickerApi {
private class LifeCycleObserver
implements Application.ActivityLifecycleCallbacks, DefaultLifecycleObserver {
private final Activity thisActivity;
LifeCycleObserver(Activity activity) {
this.thisActivity = activity;
}
@Override
public void onCreate(@NonNull LifecycleOwner owner) {}
@Override
public void onStart(@NonNull LifecycleOwner owner) {}
@Override
public void onResume(@NonNull LifecycleOwner owner) {}
@Override
public void onPause(@NonNull LifecycleOwner owner) {}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
onActivityStopped(thisActivity);
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
onActivityDestroyed(thisActivity);
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
@Override
public void onActivityDestroyed(Activity activity) {
if (thisActivity == activity && activity.getApplicationContext() != null) {
((Application) activity.getApplicationContext())
.unregisterActivityLifecycleCallbacks(
this); // Use getApplicationContext() to avoid casting failures
}
}
@Override
public void onActivityStopped(Activity activity) {
if (thisActivity == activity) {
activityState.getDelegate().saveStateBeforeResult();
}
}
}
/**
* Move all activity-lifetime-bound states into this helper object, so that {@code setup} and
* {@code tearDown} would just become constructor and finalize calls of the helper object.
*/
private class ActivityState {
private Application application;
private Activity activity;
private ImagePickerDelegate delegate;
private LifeCycleObserver observer;
private ActivityPluginBinding activityBinding;
private BinaryMessenger messenger;
// This is null when not using v2 embedding;
private Lifecycle lifecycle;
// Default constructor
ActivityState(
final Application application,
final Activity activity,
final BinaryMessenger messenger,
final ImagePickerApi handler,
final PluginRegistry.Registrar registrar,
final ActivityPluginBinding activityBinding) {
this.application = application;
this.activity = activity;
this.activityBinding = activityBinding;
this.messenger = messenger;
delegate = constructDelegate(activity);
ImagePickerApi.setup(messenger, handler);
observer = new LifeCycleObserver(activity);
if (registrar != null) {
// V1 embedding setup for activity listeners.
application.registerActivityLifecycleCallbacks(observer);
registrar.addActivityResultListener(delegate);
registrar.addRequestPermissionsResultListener(delegate);
} else {
// V2 embedding setup for activity listeners.
activityBinding.addActivityResultListener(delegate);
activityBinding.addRequestPermissionsResultListener(delegate);
lifecycle = FlutterLifecycleAdapter.getActivityLifecycle(activityBinding);
lifecycle.addObserver(observer);
}
}
// Only invoked by {@link #ImagePickerPlugin(ImagePickerDelegate, Activity)} for testing.
ActivityState(final ImagePickerDelegate delegate, final Activity activity) {
this.activity = activity;
this.delegate = delegate;
}
void release() {
if (activityBinding != null) {
activityBinding.removeActivityResultListener(delegate);
activityBinding.removeRequestPermissionsResultListener(delegate);
activityBinding = null;
}
if (lifecycle != null) {
lifecycle.removeObserver(observer);
lifecycle = null;
}
ImagePickerApi.setup(messenger, null);
if (application != null) {
application.unregisterActivityLifecycleCallbacks(observer);
application = null;
}
activity = null;
observer = null;
delegate = null;
}
Activity getActivity() {
return activity;
}
ImagePickerDelegate getDelegate() {
return delegate;
}
}
private FlutterPluginBinding pluginBinding;
ActivityState activityState;
@SuppressWarnings("deprecation")
public static void registerWith(
@NonNull io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
if (registrar.activity() == null) {
// If a background flutter view tries to register the plugin, there will be no activity from the registrar,
// we stop the registering process immediately because the ImagePicker requires an activity.
return;
}
Activity activity = registrar.activity();
Application application = (Application) (registrar.context().getApplicationContext());
ImagePickerPlugin plugin = new ImagePickerPlugin();
plugin.setup(registrar.messenger(), application, activity, registrar, null);
}
/**
* Default constructor for the plugin.
*
* <p>Use this constructor for production code.
*/
// See also: * {@link #ImagePickerPlugin(ImagePickerDelegate, Activity)} for testing.
public ImagePickerPlugin() {}
@VisibleForTesting
ImagePickerPlugin(final ImagePickerDelegate delegate, final Activity activity) {
activityState = new ActivityState(delegate, activity);
}
@VisibleForTesting
final ActivityState getActivityState() {
return activityState;
}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
pluginBinding = binding;
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
pluginBinding = null;
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
setup(
pluginBinding.getBinaryMessenger(),
(Application) pluginBinding.getApplicationContext(),
binding.getActivity(),
null,
binding);
}
@Override
public void onDetachedFromActivity() {
tearDown();
}
@Override
public void onDetachedFromActivityForConfigChanges() {
onDetachedFromActivity();
}
@Override
public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
onAttachedToActivity(binding);
}
private void setup(
final BinaryMessenger messenger,
final Application application,
final Activity activity,
final PluginRegistry.Registrar registrar,
final ActivityPluginBinding activityBinding) {
activityState =
new ActivityState(application, activity, messenger, this, registrar, activityBinding);
}
private void tearDown() {
if (activityState != null) {
activityState.release();
activityState = null;
}
}
@VisibleForTesting
final ImagePickerDelegate constructDelegate(final Activity setupActivity) {
final ImagePickerCache cache = new ImagePickerCache(setupActivity);
final ExifDataCopier exifDataCopier = new ExifDataCopier();
final ImageResizer imageResizer = new ImageResizer(setupActivity, exifDataCopier);
return new ImagePickerDelegate(setupActivity, imageResizer, cache);
}
private @Nullable ImagePickerDelegate getImagePickerDelegate() {
if (activityState == null || activityState.getActivity() == null) {
return null;
}
return activityState.getDelegate();
}
private void setCameraDevice(
@NonNull ImagePickerDelegate delegate, @NonNull SourceSpecification source) {
SourceCamera camera = source.getCamera();
if (camera != null) {
ImagePickerDelegate.CameraDevice device;
switch (camera) {
case FRONT:
device = ImagePickerDelegate.CameraDevice.FRONT;
break;
case REAR:
default:
device = ImagePickerDelegate.CameraDevice.REAR;
break;
}
delegate.setCameraDevice(device);
}
}
@Override
public void pickImages(
@NonNull SourceSpecification source,
@NonNull ImageSelectionOptions options,
@NonNull GeneralOptions generalOptions,
@NonNull Result<List<String>> result) {
ImagePickerDelegate delegate = getImagePickerDelegate();
if (delegate == null) {
result.error(
new FlutterError(
"no_activity", "image_picker plugin requires a foreground activity.", null));
return;
}
setCameraDevice(delegate, source);
if (generalOptions.getAllowMultiple()) {
delegate.chooseMultiImageFromGallery(options, generalOptions.getUsePhotoPicker(), result);
} else {
switch (source.getType()) {
case GALLERY:
delegate.chooseImageFromGallery(options, generalOptions.getUsePhotoPicker(), result);
break;
case CAMERA:
delegate.takeImageWithCamera(options, result);
break;
}
}
}
@Override
public void pickMedia(
@NonNull MediaSelectionOptions mediaSelectionOptions,
@NonNull GeneralOptions generalOptions,
@NonNull Result<List<String>> result) {
ImagePickerDelegate delegate = getImagePickerDelegate();
if (delegate == null) {
result.error(
new FlutterError(
"no_activity", "image_picker plugin requires a foreground activity.", null));
return;
}
delegate.chooseMediaFromGallery(mediaSelectionOptions, generalOptions, result);
}
@Override
public void pickVideos(
@NonNull SourceSpecification source,
@NonNull VideoSelectionOptions options,
@NonNull GeneralOptions generalOptions,
@NonNull Result<List<String>> result) {
ImagePickerDelegate delegate = getImagePickerDelegate();
if (delegate == null) {
result.error(
new FlutterError(
"no_activity", "image_picker plugin requires a foreground activity.", null));
return;
}
setCameraDevice(delegate, source);
if (generalOptions.getAllowMultiple()) {
result.error(new RuntimeException("Multi-video selection is not implemented"));
} else {
switch (source.getType()) {
case GALLERY:
delegate.chooseVideoFromGallery(options, generalOptions.getUsePhotoPicker(), result);
break;
case CAMERA:
delegate.takeVideoWithCamera(options, result);
break;
}
}
}
@Nullable
@Override
public CacheRetrievalResult retrieveLostResults() {
ImagePickerDelegate delegate = getImagePickerDelegate();
if (delegate == null) {
throw new FlutterError(
"no_activity", "image_picker plugin requires a foreground activity.", null);
}
return delegate.retrieveLostImage();
}
}
| packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerPlugin.java/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerPlugin.java",
"repo_id": "packages",
"token_count": 4275
} | 983 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/image_picker/image_picker_android/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 984 |
name: image_picker_android
description: Android implementation of the image_picker plugin.
repository: https://github.com/flutter/packages/tree/main/packages/image_picker/image_picker_android
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22
version: 0.8.9+4
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: image_picker
platforms:
android:
package: io.flutter.plugins.imagepicker
pluginClass: ImagePickerPlugin
dartPluginClass: ImagePickerAndroid
dependencies:
flutter:
sdk: flutter
flutter_plugin_android_lifecycle: ^2.0.1
image_picker_platform_interface: ^2.8.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: 5.4.4
pigeon: ^9.2.5
topics:
- camera
- image-picker
- files
- file-selection
| packages/packages/image_picker/image_picker_android/pubspec.yaml/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/pubspec.yaml",
"repo_id": "packages",
"token_count": 352
} | 985 |
// 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 'dart:ui';
import 'package:flutter/material.dart';
///a function that checks if an image needs to be resized or not
bool imageResizeNeeded(double? maxWidth, double? maxHeight, int? imageQuality) {
return imageQuality != null
? isImageQualityValid(imageQuality)
: (maxWidth != null || maxHeight != null);
}
/// a function that checks if image quality is between 0 to 100
bool isImageQualityValid(int imageQuality) {
return imageQuality >= 0 && imageQuality <= 100;
}
/// a function that calculates the size of the downScaled image.
/// imageWidth is the width of the image
/// imageHeight is the height of the image
/// maxWidth is the maximum width of the scaled image
/// maxHeight is the maximum height of the scaled image
Size calculateSizeOfDownScaledImage(
Size imageSize, double? maxWidth, double? maxHeight) {
final double widthFactor = maxWidth != null ? imageSize.width / maxWidth : 1;
final double heightFactor =
maxHeight != null ? imageSize.height / maxHeight : 1;
final double resizeFactor = max(widthFactor, heightFactor);
return resizeFactor > 1 ? imageSize ~/ resizeFactor : imageSize;
}
| packages/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart",
"repo_id": "packages",
"token_count": 371
} | 986 |
// 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 "ImagePickerTestImages.h"
@import image_picker_ios;
@import image_picker_ios.Test;
@import XCTest;
// Corner colors of test image scaled to 3x2. Format is "R G B A".
static NSString *const kColorRepresentation3x2BottomLeftYellow = @"1 0.776471 0 1";
static NSString *const kColorRepresentation3x2TopLeftRed = @"1 0.0666667 0 1";
static NSString *const kColorRepresentation3x2BottomRightCyan = @"0 0.772549 1 1";
static NSString *const kColorRepresentation3x2TopRightBlue = @"0 0.0705882 0.996078 1";
@interface ImageUtilTests : XCTestCase
@end
@implementation ImageUtilTests
static NSString *ColorStringAtPixel(UIImage *image, int pixelX, int pixelY) {
CGImageRef cgImage = image.CGImage;
uint32_t argb;
CGContextRef context1 = CGBitmapContextCreate(
&argb, 1, 1, CGImageGetBitsPerComponent(cgImage), CGImageGetBytesPerRow(cgImage),
CGColorSpaceCreateDeviceRGB(), CGImageGetBitmapInfo(cgImage));
CGContextDrawImage(
context1, CGRectMake(-pixelX, -pixelY, CGImageGetWidth(cgImage), CGImageGetHeight(cgImage)),
cgImage);
CGContextRelease(context1);
int blue = argb & 0xff;
int green = argb >> 8 & 0xff;
int red = argb >> 16 & 0xff;
int alpha = argb >> 24 & 0xff;
return [CIColor colorWithRed:red / 255.f
green:green / 255.f
blue:blue / 255.f
alpha:alpha / 255.f]
.stringRepresentation;
}
- (void)testScaledImage_EqualSizeReturnsSameImage {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData];
UIImage *scaledImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@(image.size.width)
maxHeight:@(image.size.height)
isMetadataAvailable:YES];
// Assert the same bytes pointer (not just equal objects).
XCTAssertEqual(image, scaledImage);
}
- (void)testScaledImage_NilSizeReturnsSameImage {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData];
UIImage *scaledImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:nil
maxHeight:nil
isMetadataAvailable:YES];
// Assert the same bytes pointer (not just equal objects).
XCTAssertEqual(image, scaledImage);
}
- (void)testScaledImage_ShouldBeScaled {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData];
CGFloat scaledWidth = 3;
CGFloat scaledHeight = 2;
UIImage *scaledImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@(scaledWidth)
maxHeight:@(scaledHeight)
isMetadataAvailable:YES];
XCTAssertEqual(scaledImage.size.width, scaledWidth);
XCTAssertEqual(scaledImage.size.height, scaledHeight);
// Check the corners to make sure nothing has been rotated.
XCTAssertEqualObjects(ColorStringAtPixel(scaledImage, 0, 0),
kColorRepresentation3x2BottomLeftYellow);
XCTAssertEqualObjects(ColorStringAtPixel(scaledImage, 0, scaledHeight - 1),
kColorRepresentation3x2TopLeftRed);
XCTAssertEqualObjects(ColorStringAtPixel(scaledImage, scaledWidth - 1, 0),
kColorRepresentation3x2BottomRightCyan);
XCTAssertEqualObjects(ColorStringAtPixel(scaledImage, scaledWidth - 1, scaledHeight - 1),
kColorRepresentation3x2TopRightBlue);
}
- (void)testScaledImage_ShouldBeScaledWithNoMetadata {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData];
CGFloat scaledWidth = 3;
CGFloat scaledHeight = 2;
UIImage *scaledImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@(scaledWidth)
maxHeight:@(scaledHeight)
isMetadataAvailable:NO];
XCTAssertEqual(scaledImage.size.width, scaledWidth);
XCTAssertEqual(scaledImage.size.height, scaledHeight);
// Check the corners to make sure nothing has been rotated.
XCTAssertEqualObjects(ColorStringAtPixel(scaledImage, 0, 0),
kColorRepresentation3x2BottomLeftYellow);
XCTAssertEqualObjects(ColorStringAtPixel(scaledImage, 0, scaledHeight - 1),
kColorRepresentation3x2TopLeftRed);
XCTAssertEqualObjects(ColorStringAtPixel(scaledImage, scaledWidth - 1, 0),
kColorRepresentation3x2BottomRightCyan);
XCTAssertEqualObjects(ColorStringAtPixel(scaledImage, scaledWidth - 1, scaledHeight - 1),
kColorRepresentation3x2TopRightBlue);
}
- (void)testScaledImage_ShouldBeCorrectRotation {
NSURL *imageURL =
[[NSBundle bundleForClass:[self class]] URLForResource:@"jpgImageWithRightOrientation"
withExtension:@"jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
XCTAssertEqual(image.size.width, 130);
XCTAssertEqual(image.size.height, 174);
XCTAssertEqual(image.imageOrientation, UIImageOrientationRight);
UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@10
maxHeight:@10
isMetadataAvailable:YES];
XCTAssertEqual(newImage.size.width, 10);
XCTAssertEqual(newImage.size.height, 7);
XCTAssertEqual(newImage.imageOrientation, UIImageOrientationUp);
}
- (void)testScaledGIFImage_ShouldBeScaled {
// gif image that frame size is 3 and the duration is 1 second.
GIFInfo *info = [FLTImagePickerImageUtil scaledGIFImage:ImagePickerTestImages.GIFTestData
maxWidth:@3
maxHeight:@2];
NSArray<UIImage *> *images = info.images;
NSTimeInterval duration = info.interval;
XCTAssertEqual(images.count, 3);
XCTAssertEqual(duration, 1);
for (UIImage *newImage in images) {
XCTAssertEqual(newImage.size.width, 3);
XCTAssertEqual(newImage.size.height, 2);
}
}
- (void)testScaledImage_TallImage_ShouldBeScaledBelowMaxHeight {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTallTestData];
XCTAssertEqual(image.size.width, 4);
XCTAssertEqual(image.size.height, 7);
UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@5
maxHeight:@5
isMetadataAvailable:YES];
XCTAssertEqual(newImage.size.width, 3);
XCTAssertEqual(newImage.size.height, 5);
}
- (void)testScaledImage_TallImage_ShouldBeScaledBelowMaxWidth {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTallTestData];
UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@3
maxHeight:@10
isMetadataAvailable:YES];
XCTAssertEqual(newImage.size.width, 3);
XCTAssertEqual(newImage.size.height, 5);
}
- (void)testScaledImage_TallImage_ShouldNotBeScaledAboveOriginaWidthOrHeight {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTallTestData];
UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@10
maxHeight:@10
isMetadataAvailable:YES];
XCTAssertEqual(newImage.size.width, 4);
XCTAssertEqual(newImage.size.height, 7);
}
- (void)testScaledImage_WideImage_ShouldBeScaledBelowMaxHeight {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData];
XCTAssertEqual(image.size.width, 12);
XCTAssertEqual(image.size.height, 7);
UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@20
maxHeight:@6
isMetadataAvailable:YES];
XCTAssertEqual(newImage.size.width, 10);
XCTAssertEqual(newImage.size.height, 6);
}
- (void)testScaledImage_WideImage_ShouldBeScaledBelowMaxWidth {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData];
UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@10
maxHeight:@10
isMetadataAvailable:YES];
XCTAssertEqual(newImage.size.width, 10);
XCTAssertEqual(newImage.size.height, 6);
}
- (void)testScaledImage_WideImage_ShouldNotBeScaledAboveOriginaWidthOrHeight {
UIImage *image = [UIImage imageWithData:ImagePickerTestImages.JPGTestData];
UIImage *newImage = [FLTImagePickerImageUtil scaledImage:image
maxWidth:@100
maxHeight:@100
isMetadataAvailable:YES];
XCTAssertEqual(newImage.size.width, 12);
XCTAssertEqual(newImage.size.height, 7);
}
@end
| packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImageUtilTests.m/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/example/ios/RunnerTests/ImageUtilTests.m",
"repo_id": "packages",
"token_count": 4662
} | 987 |
// 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 "FLTImagePickerPlugin.h"
#import "FLTImagePickerPlugin_Test.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <Photos/Photos.h>
#import <PhotosUI/PHPhotoLibrary+PhotosUISupport.h>
#import <PhotosUI/PhotosUI.h>
#import <UIKit/UIKit.h>
#import "FLTImagePickerImageUtil.h"
#import "FLTImagePickerMetaDataUtil.h"
#import "FLTImagePickerPhotoAssetUtil.h"
#import "FLTPHPickerSaveImageToPathOperation.h"
#import "messages.g.h"
@implementation FLTImagePickerMethodCallContext
- (instancetype)initWithResult:(nonnull FlutterResultAdapter)result {
if (self = [super init]) {
_result = [result copy];
}
return self;
}
@end
#pragma mark -
@interface FLTImagePickerPlugin ()
/// The UIImagePickerController instances that will be used when a new
/// controller would normally be created. Each call to
/// createImagePickerController will remove the current first element from
/// the array.
@property(strong, nonatomic)
NSMutableArray<UIImagePickerController *> *imagePickerControllerOverrides;
@end
typedef NS_ENUM(NSInteger, ImagePickerClassType) { UIImagePickerClassType, PHPickerClassType };
@implementation FLTImagePickerPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FLTImagePickerPlugin *instance = [[FLTImagePickerPlugin alloc] init];
SetUpFLTImagePickerApi(registrar.messenger, instance);
}
- (UIImagePickerController *)createImagePickerController {
if ([self.imagePickerControllerOverrides count] > 0) {
UIImagePickerController *controller = [self.imagePickerControllerOverrides firstObject];
[self.imagePickerControllerOverrides removeObjectAtIndex:0];
return controller;
}
return [[UIImagePickerController alloc] init];
}
- (void)setImagePickerControllerOverrides:
(NSArray<UIImagePickerController *> *)imagePickerControllers {
_imagePickerControllerOverrides = [imagePickerControllers mutableCopy];
}
- (UIViewController *)viewControllerWithWindow:(UIWindow *)window {
UIWindow *windowToUse = window;
if (windowToUse == nil) {
for (UIWindow *window in [UIApplication sharedApplication].windows) {
if (window.isKeyWindow) {
windowToUse = window;
break;
}
}
}
UIViewController *topController = windowToUse.rootViewController;
while (topController.presentedViewController) {
topController = topController.presentedViewController;
}
return topController;
}
/// Returns the UIImagePickerControllerCameraDevice to use given [source].
///
/// @param source The source specification from Dart.
- (UIImagePickerControllerCameraDevice)cameraDeviceForSource:(FLTSourceSpecification *)source {
switch (source.camera) {
case FLTSourceCameraFront:
return UIImagePickerControllerCameraDeviceFront;
case FLTSourceCameraRear:
return UIImagePickerControllerCameraDeviceRear;
}
}
- (void)launchPHPickerWithContext:(nonnull FLTImagePickerMethodCallContext *)context
API_AVAILABLE(ios(14)) {
PHPickerConfiguration *config =
[[PHPickerConfiguration alloc] initWithPhotoLibrary:PHPhotoLibrary.sharedPhotoLibrary];
config.selectionLimit = context.maxImageCount;
if (context.includeVideo) {
config.filter = [PHPickerFilter anyFilterMatchingSubfilters:@[
[PHPickerFilter imagesFilter], [PHPickerFilter videosFilter]
]];
} else {
config.filter = [PHPickerFilter imagesFilter];
}
PHPickerViewController *pickerViewController =
[[PHPickerViewController alloc] initWithConfiguration:config];
pickerViewController.delegate = self;
pickerViewController.presentationController.delegate = self;
self.callContext = context;
if (context.requestFullMetadata) {
[self checkPhotoAuthorizationWithPHPicker:pickerViewController];
} else {
[self showPhotoLibraryWithPHPicker:pickerViewController];
}
}
- (void)launchUIImagePickerWithSource:(nonnull FLTSourceSpecification *)source
context:(nonnull FLTImagePickerMethodCallContext *)context {
UIImagePickerController *imagePickerController = [self createImagePickerController];
imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
imagePickerController.delegate = self;
if (context.includeVideo) {
imagePickerController.mediaTypes = @[ (NSString *)kUTTypeImage, (NSString *)kUTTypeMovie ];
} else {
imagePickerController.mediaTypes = @[ (NSString *)kUTTypeImage ];
}
self.callContext = context;
switch (source.type) {
case FLTSourceTypeCamera:
[self checkCameraAuthorizationWithImagePicker:imagePickerController
camera:[self cameraDeviceForSource:source]];
break;
case FLTSourceTypeGallery:
if (context.requestFullMetadata) {
[self checkPhotoAuthorizationWithImagePicker:imagePickerController];
} else {
[self showPhotoLibraryWithImagePicker:imagePickerController];
}
break;
default:
[self sendCallResultWithError:[FlutterError errorWithCode:@"invalid_source"
message:@"Invalid image source."
details:nil]];
break;
}
}
#pragma mark - FLTImagePickerApi
- (void)pickImageWithSource:(nonnull FLTSourceSpecification *)source
maxSize:(nonnull FLTMaxSize *)maxSize
quality:(nullable NSNumber *)imageQuality
fullMetadata:(BOOL)fullMetadata
completion:
(nonnull void (^)(NSString *_Nullable, FlutterError *_Nullable))completion {
[self cancelInProgressCall];
FLTImagePickerMethodCallContext *context = [[FLTImagePickerMethodCallContext alloc]
initWithResult:^void(NSArray<NSString *> *paths, FlutterError *error) {
if (paths.count > 1) {
completion(nil, [FlutterError errorWithCode:@"invalid_result"
message:@"Incorrect number of return paths provided"
details:nil]);
}
completion(paths.firstObject, error);
}];
context.maxSize = maxSize;
context.imageQuality = imageQuality;
context.maxImageCount = 1;
context.requestFullMetadata = fullMetadata;
if (source.type == FLTSourceTypeGallery) { // Capture is not possible with PHPicker
if (@available(iOS 14, *)) {
[self launchPHPickerWithContext:context];
} else {
[self launchUIImagePickerWithSource:source context:context];
}
} else {
[self launchUIImagePickerWithSource:source context:context];
}
}
- (void)pickMultiImageWithMaxSize:(nonnull FLTMaxSize *)maxSize
quality:(nullable NSNumber *)imageQuality
fullMetadata:(BOOL)fullMetadata
completion:(nonnull void (^)(NSArray<NSString *> *_Nullable,
FlutterError *_Nullable))completion {
[self cancelInProgressCall];
FLTImagePickerMethodCallContext *context =
[[FLTImagePickerMethodCallContext alloc] initWithResult:completion];
context.maxSize = maxSize;
context.imageQuality = imageQuality;
context.requestFullMetadata = fullMetadata;
if (@available(iOS 14, *)) {
[self launchPHPickerWithContext:context];
} else {
// Camera is ignored for gallery mode, so the value here is arbitrary.
[self launchUIImagePickerWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeGallery
camera:FLTSourceCameraRear]
context:context];
}
}
- (void)pickMediaWithMediaSelectionOptions:(nonnull FLTMediaSelectionOptions *)mediaSelectionOptions
completion:(nonnull void (^)(NSArray<NSString *> *_Nullable,
FlutterError *_Nullable))completion {
[self cancelInProgressCall];
FLTImagePickerMethodCallContext *context =
[[FLTImagePickerMethodCallContext alloc] initWithResult:completion];
context.maxSize = [mediaSelectionOptions maxSize];
context.imageQuality = [mediaSelectionOptions imageQuality];
context.requestFullMetadata = [mediaSelectionOptions requestFullMetadata];
context.includeVideo = YES;
if (!mediaSelectionOptions.allowMultiple) {
context.maxImageCount = 1;
}
if (@available(iOS 14, *)) {
[self launchPHPickerWithContext:context];
} else {
// Camera is ignored for gallery mode, so the value here is arbitrary.
[self launchUIImagePickerWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeGallery
camera:FLTSourceCameraRear]
context:context];
}
}
- (void)pickVideoWithSource:(nonnull FLTSourceSpecification *)source
maxDuration:(nullable NSNumber *)maxDurationSeconds
completion:
(nonnull void (^)(NSString *_Nullable, FlutterError *_Nullable))completion {
[self cancelInProgressCall];
FLTImagePickerMethodCallContext *context = [[FLTImagePickerMethodCallContext alloc]
initWithResult:^void(NSArray<NSString *> *paths, FlutterError *error) {
if (paths.count > 1) {
completion(nil, [FlutterError errorWithCode:@"invalid_result"
message:@"Incorrect number of return paths provided"
details:nil]);
}
completion(paths.firstObject, error);
}];
context.maxImageCount = 1;
UIImagePickerController *imagePickerController = [self createImagePickerController];
imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
imagePickerController.delegate = self;
imagePickerController.mediaTypes = @[
(NSString *)kUTTypeMovie, (NSString *)kUTTypeAVIMovie, (NSString *)kUTTypeVideo,
(NSString *)kUTTypeMPEG4
];
imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
if (maxDurationSeconds) {
NSTimeInterval max = [maxDurationSeconds doubleValue];
imagePickerController.videoMaximumDuration = max;
}
self.callContext = context;
switch (source.type) {
case FLTSourceTypeCamera:
[self checkCameraAuthorizationWithImagePicker:imagePickerController
camera:[self cameraDeviceForSource:source]];
break;
case FLTSourceTypeGallery:
[self checkPhotoAuthorizationWithImagePicker:imagePickerController];
break;
default:
[self sendCallResultWithError:[FlutterError errorWithCode:@"invalid_source"
message:@"Invalid video source."
details:nil]];
break;
}
}
#pragma mark -
/// If a call is still in progress, cancels it by returning an error and then clearing state.
///
/// TODO(stuartmorgan): Eliminate this, and instead track context per image picker (e.g., using
/// associated objects).
- (void)cancelInProgressCall {
if (self.callContext) {
[self sendCallResultWithError:[FlutterError errorWithCode:@"multiple_request"
message:@"Cancelled by a second request"
details:nil]];
self.callContext = nil;
}
}
- (void)showCamera:(UIImagePickerControllerCameraDevice)device
withImagePicker:(UIImagePickerController *)imagePickerController {
@synchronized(self) {
if (imagePickerController.beingPresented) {
return;
}
}
// Camera is not available on simulators
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] &&
[UIImagePickerController isCameraDeviceAvailable:device]) {
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePickerController.cameraDevice = device;
[[self viewControllerWithWindow:nil] presentViewController:imagePickerController
animated:YES
completion:nil];
} else {
UIAlertController *cameraErrorAlert = [UIAlertController
alertControllerWithTitle:NSLocalizedString(@"Error", @"Alert title when camera unavailable")
message:NSLocalizedString(@"Camera not available.",
"Alert message when camera unavailable")
preferredStyle:UIAlertControllerStyleAlert];
[cameraErrorAlert
addAction:[UIAlertAction actionWithTitle:NSLocalizedString(
@"OK", @"Alert button when camera unavailable")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action){
}]];
[[self viewControllerWithWindow:nil] presentViewController:cameraErrorAlert
animated:YES
completion:nil];
[self sendCallResultWithSavedPathList:nil];
}
}
- (void)checkCameraAuthorizationWithImagePicker:(UIImagePickerController *)imagePickerController
camera:(UIImagePickerControllerCameraDevice)device {
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
switch (status) {
case AVAuthorizationStatusAuthorized:
[self showCamera:device withImagePicker:imagePickerController];
break;
case AVAuthorizationStatusNotDetermined: {
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
completionHandler:^(BOOL granted) {
dispatch_async(dispatch_get_main_queue(), ^{
if (granted) {
[self showCamera:device withImagePicker:imagePickerController];
} else {
[self errorNoCameraAccess:AVAuthorizationStatusDenied];
}
});
}];
break;
}
case AVAuthorizationStatusDenied:
case AVAuthorizationStatusRestricted:
default:
[self errorNoCameraAccess:status];
break;
}
}
- (void)checkPhotoAuthorizationWithImagePicker:(UIImagePickerController *)imagePickerController {
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
switch (status) {
case PHAuthorizationStatusNotDetermined: {
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
dispatch_async(dispatch_get_main_queue(), ^{
if (status == PHAuthorizationStatusAuthorized) {
[self showPhotoLibraryWithImagePicker:imagePickerController];
} else {
[self errorNoPhotoAccess:status];
}
});
}];
break;
}
case PHAuthorizationStatusAuthorized:
[self showPhotoLibraryWithImagePicker:imagePickerController];
break;
case PHAuthorizationStatusDenied:
case PHAuthorizationStatusRestricted:
default:
[self errorNoPhotoAccess:status];
break;
}
}
- (void)checkPhotoAuthorizationWithPHPicker:(PHPickerViewController *)pickerViewController
API_AVAILABLE(ios(14)) {
PHAccessLevel requestedAccessLevel = PHAccessLevelReadWrite;
PHAuthorizationStatus status =
[PHPhotoLibrary authorizationStatusForAccessLevel:requestedAccessLevel];
switch (status) {
case PHAuthorizationStatusNotDetermined: {
[PHPhotoLibrary
requestAuthorizationForAccessLevel:requestedAccessLevel
handler:^(PHAuthorizationStatus status) {
dispatch_async(dispatch_get_main_queue(), ^{
if (status == PHAuthorizationStatusAuthorized) {
[self showPhotoLibraryWithPHPicker:pickerViewController];
} else if (status == PHAuthorizationStatusLimited) {
[self showPhotoLibraryWithPHPicker:pickerViewController];
} else {
[self errorNoPhotoAccess:status];
}
});
}];
break;
}
case PHAuthorizationStatusAuthorized:
case PHAuthorizationStatusLimited:
[self showPhotoLibraryWithPHPicker:pickerViewController];
break;
case PHAuthorizationStatusDenied:
case PHAuthorizationStatusRestricted:
default:
[self errorNoPhotoAccess:status];
break;
}
}
- (void)errorNoCameraAccess:(AVAuthorizationStatus)status {
switch (status) {
case AVAuthorizationStatusRestricted:
[self sendCallResultWithError:[FlutterError
errorWithCode:@"camera_access_restricted"
message:@"The user is not allowed to use the camera."
details:nil]];
break;
case AVAuthorizationStatusDenied:
default:
[self sendCallResultWithError:[FlutterError
errorWithCode:@"camera_access_denied"
message:@"The user did not allow camera access."
details:nil]];
break;
}
}
- (void)errorNoPhotoAccess:(PHAuthorizationStatus)status {
switch (status) {
case PHAuthorizationStatusRestricted:
[self sendCallResultWithError:[FlutterError
errorWithCode:@"photo_access_restricted"
message:@"The user is not allowed to use the photo."
details:nil]];
break;
case PHAuthorizationStatusDenied:
default:
[self sendCallResultWithError:[FlutterError
errorWithCode:@"photo_access_denied"
message:@"The user did not allow photo access."
details:nil]];
break;
}
}
- (void)showPhotoLibraryWithPHPicker:(PHPickerViewController *)pickerViewController
API_AVAILABLE(ios(14)) {
[[self viewControllerWithWindow:nil] presentViewController:pickerViewController
animated:YES
completion:nil];
}
- (void)showPhotoLibraryWithImagePicker:(UIImagePickerController *)imagePickerController {
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[[self viewControllerWithWindow:nil] presentViewController:imagePickerController
animated:YES
completion:nil];
}
- (NSNumber *)getDesiredImageQuality:(NSNumber *)imageQuality {
if (![imageQuality isKindOfClass:[NSNumber class]]) {
imageQuality = @1;
} else if (imageQuality.intValue < 0 || imageQuality.intValue > 100) {
imageQuality = @1;
} else {
imageQuality = @([imageQuality floatValue] / 100);
}
return imageQuality;
}
#pragma mark - UIAdaptivePresentationControllerDelegate
- (void)presentationControllerDidDismiss:(UIPresentationController *)presentationController {
[self sendCallResultWithSavedPathList:nil];
}
#pragma mark - PHPickerViewControllerDelegate
- (void)picker:(PHPickerViewController *)picker
didFinishPicking:(NSArray<PHPickerResult *> *)results API_AVAILABLE(ios(14)) {
[picker dismissViewControllerAnimated:YES completion:nil];
if (results.count == 0) {
[self sendCallResultWithSavedPathList:nil];
return;
}
__block NSOperationQueue *saveQueue = [[NSOperationQueue alloc] init];
saveQueue.name = @"Flutter Save Image Queue";
saveQueue.qualityOfService = NSQualityOfServiceUserInitiated;
FLTImagePickerMethodCallContext *currentCallContext = self.callContext;
NSNumber *maxWidth = currentCallContext.maxSize.width;
NSNumber *maxHeight = currentCallContext.maxSize.height;
NSNumber *imageQuality = currentCallContext.imageQuality;
NSNumber *desiredImageQuality = [self getDesiredImageQuality:imageQuality];
BOOL requestFullMetadata = currentCallContext.requestFullMetadata;
NSMutableArray *pathList = [[NSMutableArray alloc] initWithCapacity:results.count];
__block FlutterError *saveError = nil;
__weak typeof(self) weakSelf = self;
// This operation will be executed on the main queue after
// all selected files have been saved.
NSBlockOperation *sendListOperation = [NSBlockOperation blockOperationWithBlock:^{
if (saveError != nil) {
[weakSelf sendCallResultWithError:saveError];
} else {
[weakSelf sendCallResultWithSavedPathList:pathList];
}
// Retain queue until here.
saveQueue = nil;
}];
[results enumerateObjectsUsingBlock:^(PHPickerResult *result, NSUInteger index, BOOL *stop) {
// NSNull means it hasn't saved yet.
[pathList addObject:[NSNull null]];
FLTPHPickerSaveImageToPathOperation *saveOperation =
[[FLTPHPickerSaveImageToPathOperation alloc]
initWithResult:result
maxHeight:maxHeight
maxWidth:maxWidth
desiredImageQuality:desiredImageQuality
fullMetadata:requestFullMetadata
savedPathBlock:^(NSString *savedPath, FlutterError *error) {
if (savedPath != nil) {
pathList[index] = savedPath;
} else {
saveError = error;
}
}];
[sendListOperation addDependency:saveOperation];
[saveQueue addOperation:saveOperation];
}];
// Schedule the final Flutter callback on the main queue
// to be run after all images have been saved.
[NSOperationQueue.mainQueue addOperation:sendListOperation];
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
NSURL *videoURL = info[UIImagePickerControllerMediaURL];
[picker dismissViewControllerAnimated:YES completion:nil];
// The method dismissViewControllerAnimated does not immediately prevent
// further didFinishPickingMediaWithInfo invocations. A nil check is necessary
// to prevent below code to be unwantly executed multiple times and cause a
// crash.
if (!self.callContext) {
return;
}
if (videoURL != nil) {
if (@available(iOS 13.0, *)) {
NSURL *destination = [FLTImagePickerPhotoAssetUtil saveVideoFromURL:videoURL];
if (destination == nil) {
[self sendCallResultWithError:[FlutterError
errorWithCode:@"flutter_image_picker_copy_video_error"
message:@"Could not cache the video file."
details:nil]];
return;
}
videoURL = destination;
}
[self sendCallResultWithSavedPathList:@[ videoURL.path ]];
} else {
UIImage *image = info[UIImagePickerControllerEditedImage];
if (image == nil) {
image = info[UIImagePickerControllerOriginalImage];
}
NSNumber *maxWidth = self.callContext.maxSize.width;
NSNumber *maxHeight = self.callContext.maxSize.height;
NSNumber *imageQuality = self.callContext.imageQuality;
NSNumber *desiredImageQuality = [self getDesiredImageQuality:imageQuality];
PHAsset *originalAsset;
if (_callContext.requestFullMetadata) {
// Full metadata are available only in PHAsset, which requires gallery permission.
originalAsset = [FLTImagePickerPhotoAssetUtil getAssetFromImagePickerInfo:info];
}
if (maxWidth != nil || maxHeight != nil) {
image = [FLTImagePickerImageUtil scaledImage:image
maxWidth:maxWidth
maxHeight:maxHeight
isMetadataAvailable:YES];
}
if (!originalAsset) {
// Image picked without an original asset (e.g. User took a photo directly)
[self saveImageWithPickerInfo:info image:image imageQuality:desiredImageQuality];
} else {
void (^resultHandler)(NSData *imageData, NSString *dataUTI, NSDictionary *info) = ^(
NSData *_Nullable imageData, NSString *_Nullable dataUTI, NSDictionary *_Nullable info) {
// maxWidth and maxHeight are used only for GIF images.
[self saveImageWithOriginalImageData:imageData
image:image
maxWidth:maxWidth
maxHeight:maxHeight
imageQuality:desiredImageQuality];
};
if (@available(iOS 13.0, *)) {
[[PHImageManager defaultManager]
requestImageDataAndOrientationForAsset:originalAsset
options:nil
resultHandler:^(NSData *_Nullable imageData,
NSString *_Nullable dataUTI,
CGImagePropertyOrientation orientation,
NSDictionary *_Nullable info) {
resultHandler(imageData, dataUTI, info);
}];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[PHImageManager defaultManager]
requestImageDataForAsset:originalAsset
options:nil
resultHandler:^(NSData *_Nullable imageData, NSString *_Nullable dataUTI,
UIImageOrientation orientation,
NSDictionary *_Nullable info) {
resultHandler(imageData, dataUTI, info);
}];
#pragma clang diagnostic pop
}
}
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
[self sendCallResultWithSavedPathList:nil];
}
#pragma mark -
- (void)saveImageWithOriginalImageData:(NSData *)originalImageData
image:(UIImage *)image
maxWidth:(NSNumber *)maxWidth
maxHeight:(NSNumber *)maxHeight
imageQuality:(NSNumber *)imageQuality {
NSString *savedPath =
[FLTImagePickerPhotoAssetUtil saveImageWithOriginalImageData:originalImageData
image:image
maxWidth:maxWidth
maxHeight:maxHeight
imageQuality:imageQuality];
[self sendCallResultWithSavedPathList:@[ savedPath ]];
}
- (void)saveImageWithPickerInfo:(NSDictionary *)info
image:(UIImage *)image
imageQuality:(NSNumber *)imageQuality {
NSString *savedPath = [FLTImagePickerPhotoAssetUtil saveImageWithPickerInfo:info
image:image
imageQuality:imageQuality];
[self sendCallResultWithSavedPathList:@[ savedPath ]];
}
- (void)sendCallResultWithSavedPathList:(nullable NSArray *)pathList {
if (!self.callContext) {
return;
}
if ([pathList containsObject:[NSNull null]]) {
self.callContext.result(nil, [FlutterError errorWithCode:@"create_error"
message:@"pathList's items should not be null"
details:nil]);
} else {
self.callContext.result(pathList ?: [NSArray array], nil);
}
self.callContext = nil;
}
/// Sends the given error via `callContext.result` as the result of the original platform channel
/// method call, clearing the in-progress call state.
///
/// @param error The error to return.
- (void)sendCallResultWithError:(FlutterError *)error {
if (!self.callContext) {
return;
}
self.callContext.result(nil, error);
self.callContext = nil;
}
@end
| packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerPlugin.m/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerPlugin.m",
"repo_id": "packages",
"token_count": 12715
} | 988 |
// 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 (v13.0.0), 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:image_picker_ios/src/messages.g.dart';
class _TestHostImagePickerApiCodec extends StandardMessageCodec {
const _TestHostImagePickerApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is MaxSize) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is MediaSelectionOptions) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is SourceSpecification) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return MaxSize.decode(readValue(buffer)!);
case 129:
return MediaSelectionOptions.decode(readValue(buffer)!);
case 130:
return SourceSpecification.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestHostImagePickerApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = _TestHostImagePickerApiCodec();
Future<String?> pickImage(SourceSpecification source, MaxSize maxSize,
int? imageQuality, bool requestFullMetadata);
Future<List<String?>> pickMultiImage(
MaxSize maxSize, int? imageQuality, bool requestFullMetadata);
Future<String?> pickVideo(
SourceSpecification source, int? maxDurationSeconds);
/// Selects images and videos and returns their paths.
Future<List<String?>> pickMedia(MediaSelectionOptions mediaSelectionOptions);
static void setup(TestHostImagePickerApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickImage', 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.image_picker_ios.ImagePickerApi.pickImage was null.');
final List<Object?> args = (message as List<Object?>?)!;
final SourceSpecification? arg_source =
(args[0] as SourceSpecification?);
assert(arg_source != null,
'Argument for dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickImage was null, expected non-null SourceSpecification.');
final MaxSize? arg_maxSize = (args[1] as MaxSize?);
assert(arg_maxSize != null,
'Argument for dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickImage was null, expected non-null MaxSize.');
final int? arg_imageQuality = (args[2] as int?);
final bool? arg_requestFullMetadata = (args[3] as bool?);
assert(arg_requestFullMetadata != null,
'Argument for dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickImage was null, expected non-null bool.');
try {
final String? output = await api.pickImage(arg_source!,
arg_maxSize!, arg_imageQuality, arg_requestFullMetadata!);
return <Object?>[output];
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMultiImage',
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.image_picker_ios.ImagePickerApi.pickMultiImage was null.');
final List<Object?> args = (message as List<Object?>?)!;
final MaxSize? arg_maxSize = (args[0] as MaxSize?);
assert(arg_maxSize != null,
'Argument for dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMultiImage was null, expected non-null MaxSize.');
final int? arg_imageQuality = (args[1] as int?);
final bool? arg_requestFullMetadata = (args[2] as bool?);
assert(arg_requestFullMetadata != null,
'Argument for dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMultiImage was null, expected non-null bool.');
try {
final List<String?> output = await api.pickMultiImage(
arg_maxSize!, arg_imageQuality, arg_requestFullMetadata!);
return <Object?>[output];
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickVideo', 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.image_picker_ios.ImagePickerApi.pickVideo was null.');
final List<Object?> args = (message as List<Object?>?)!;
final SourceSpecification? arg_source =
(args[0] as SourceSpecification?);
assert(arg_source != null,
'Argument for dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickVideo was null, expected non-null SourceSpecification.');
final int? arg_maxDurationSeconds = (args[1] as int?);
try {
final String? output =
await api.pickVideo(arg_source!, arg_maxDurationSeconds);
return <Object?>[output];
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMedia', 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.image_picker_ios.ImagePickerApi.pickMedia was null.');
final List<Object?> args = (message as List<Object?>?)!;
final MediaSelectionOptions? arg_mediaSelectionOptions =
(args[0] as MediaSelectionOptions?);
assert(arg_mediaSelectionOptions != null,
'Argument for dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMedia was null, expected non-null MediaSelectionOptions.');
try {
final List<String?> output =
await api.pickMedia(arg_mediaSelectionOptions!);
return <Object?>[output];
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
| packages/packages/image_picker/image_picker_ios/test/test_api.g.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/test/test_api.g.dart",
"repo_id": "packages",
"token_count": 3905
} | 989 |
name: image_picker_linux
description: Linux platform implementation of image_picker
repository: https://github.com/flutter/packages/tree/main/packages/image_picker/image_picker_linux
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22
version: 0.2.1+1
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: image_picker
platforms:
linux:
dartPluginClass: ImagePickerLinux
dependencies:
file_selector_linux: ^0.9.1+3
file_selector_platform_interface: ^2.2.0
flutter:
sdk: flutter
image_picker_platform_interface: ^2.8.0
dev_dependencies:
build_runner: ^2.1.5
flutter_test:
sdk: flutter
mockito: 5.4.4
topics:
- image-picker
- files
- file-selection
| packages/packages/image_picker/image_picker_linux/pubspec.yaml/0 | {
"file_path": "packages/packages/image_picker/image_picker_linux/pubspec.yaml",
"repo_id": "packages",
"token_count": 329
} | 990 |
// 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:cross_file/cross_file.dart';
import 'package:flutter/foundation.dart' show immutable;
import 'camera_device.dart';
/// Options for [ImagePickerCameraDelegate] methods.
///
/// New options may be added in the future.
@immutable
class ImagePickerCameraDelegateOptions {
/// Creates a new set of options for taking an image or video.
const ImagePickerCameraDelegateOptions({
this.preferredCameraDevice = CameraDevice.rear,
this.maxVideoDuration,
});
/// The camera device to default to, if available.
///
/// Defaults to [CameraDevice.rear].
final CameraDevice preferredCameraDevice;
/// The maximum duration to allow when recording a video.
///
/// Defaults to null, meaning no maximum duration.
final Duration? maxVideoDuration;
}
/// A delegate for `ImagePickerPlatform` implementations that do not provide
/// a camera implementation, or that have a default but allow substituting an
/// alternate implementation.
abstract class ImagePickerCameraDelegate {
/// Takes a photo with the given [options] and returns an [XFile] to the
/// resulting image file.
///
/// Returns null if the photo could not be taken, or the user cancelled.
Future<XFile?> takePhoto({
ImagePickerCameraDelegateOptions options =
const ImagePickerCameraDelegateOptions(),
});
/// Records a video with the given [options] and returns an [XFile] to the
/// resulting video file.
///
/// Returns null if the video could not be recorded, or the user cancelled.
Future<XFile?> takeVideo({
ImagePickerCameraDelegateOptions options =
const ImagePickerCameraDelegateOptions(),
});
}
| packages/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_delegate.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_delegate.dart",
"repo_id": "packages",
"token_count": 500
} | 991 |
name: image_picker_platform_interface
description: A common platform interface for the image_picker plugin.
repository: https://github.com/flutter/packages/tree/main/packages/image_picker/image_picker_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%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: 2.9.4
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
dependencies:
cross_file: ^0.3.1+1
flutter:
sdk: flutter
http: ">=0.13.0 <2.0.0"
plugin_platform_interface: ^2.1.7
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- image-picker
- files
- file-selection
| packages/packages/image_picker/image_picker_platform_interface/pubspec.yaml/0 | {
"file_path": "packages/packages/image_picker/image_picker_platform_interface/pubspec.yaml",
"repo_id": "packages",
"token_count": 302
} | 992 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_android/billing_client_wrappers.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
InAppPurchaseAndroidPlatform.registerPlatform();
});
testWidgets('Can create InAppPurchaseAndroid instance',
(WidgetTester tester) async {
final InAppPurchasePlatform androidPlatform =
InAppPurchasePlatform.instance;
expect(androidPlatform, isNotNull);
});
group('Method channel interaction works for', () {
late final BillingClient billingClient;
setUpAll(() {
billingClient = BillingClient(
(PurchasesResultWrapper _) {}, (UserChoiceDetailsWrapper _) {});
});
testWidgets('BillingClient.acknowledgePurchase',
(WidgetTester tester) async {
try {
await billingClient.acknowledgePurchase('purchaseToken');
} on MissingPluginException {
fail('Method channel is not setup correctly');
}
});
testWidgets('BillingClient.consumeAsync', (WidgetTester tester) async {
try {
await billingClient.consumeAsync('purchaseToken');
} on MissingPluginException {
fail('Method channel is not setup correctly');
}
});
testWidgets('BillingClient.endConnection', (WidgetTester tester) async {
try {
await billingClient.endConnection();
} on MissingPluginException {
fail('Method channel is not setup correctly');
}
});
testWidgets('BillingClient.isFeatureSupported',
(WidgetTester tester) async {
try {
await billingClient
.isFeatureSupported(BillingClientFeature.productDetails);
} on MissingPluginException {
fail('Method channel is not setup correctly');
}
});
testWidgets('BillingClient.isReady', (WidgetTester tester) async {
try {
await billingClient.isReady();
} on MissingPluginException {
fail('Method channel is not setup correctly');
}
});
testWidgets('BillingClient.launchBillingFlow', (WidgetTester tester) async {
try {
await billingClient.launchBillingFlow(product: 'product');
} on MissingPluginException {
fail('Method channel is not setup correctly');
} on PlatformException catch (e) {
// A [PlatformException] is expected, as we do not fetch products first.
if (e.code != 'NOT_FOUND') {
rethrow;
}
}
});
testWidgets('BillingClient.queryProductDetails',
(WidgetTester tester) async {
try {
await billingClient
.queryProductDetails(productList: <ProductWrapper>[]);
} on MissingPluginException {
fail('Method channel is not setup correctly');
} on PlatformException catch (e) {
// A [PlatformException] is expected, as we send an empty product list.
if (!(e.message?.startsWith('Product list cannot be empty.') ??
false)) {
rethrow;
}
}
});
testWidgets('BillingClient.queryPurchaseHistory',
(WidgetTester tester) async {
try {
await billingClient.queryPurchaseHistory(ProductType.inapp);
} on MissingPluginException {
fail('Method channel is not setup correctly');
}
});
testWidgets('BillingClient.queryPurchases', (WidgetTester tester) async {
try {
await billingClient.queryPurchases(ProductType.inapp);
} on MissingPluginException {
fail('Method channel is not setup correctly');
}
});
testWidgets('BillingClient.startConnection', (WidgetTester tester) async {
try {
await billingClient.startConnection(
onBillingServiceDisconnected: () {});
} on MissingPluginException {
fail('Method channel is not setup correctly');
}
});
});
}
| packages/packages/in_app_purchase/in_app_purchase_android/example/integration_test/in_app_purchase_test.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/example/integration_test/in_app_purchase_test.dart",
"repo_id": "packages",
"token_count": 1597
} | 993 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
import '../../billing_client_wrappers.dart';
// WARNING: Changes to `@JsonSerializable` classes need to be reflected in the
// below generated file. Run `flutter packages pub run build_runner watch` to
// rebuild and watch for further changes.
part 'billing_response_wrapper.g.dart';
/// The error message shown when the map represents billing result is invalid from method channel.
///
/// This usually indicates a serious underlining code issue in the plugin.
@visibleForTesting
const String kInvalidBillingResultErrorMessage =
'Invalid billing result map from method channel.';
/// Params containing the response code and the debug message from the Play Billing API response.
@JsonSerializable()
@BillingResponseConverter()
@immutable
class BillingResultWrapper implements HasBillingResponse {
/// Constructs the object with [responseCode] and [debugMessage].
const BillingResultWrapper({required this.responseCode, this.debugMessage});
/// Constructs an instance of this from a key value map of data.
///
/// The map needs to have named string keys with values matching the names and
/// types of all of the members on this class.
factory BillingResultWrapper.fromJson(Map<String, dynamic>? map) {
if (map == null || map.isEmpty) {
return const BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: kInvalidBillingResultErrorMessage);
}
return _$BillingResultWrapperFromJson(map);
}
/// Response code returned in the Play Billing API calls.
@override
final BillingResponse responseCode;
/// Debug message returned in the Play Billing API calls.
///
/// Defaults to `null`.
/// This message uses an en-US locale and should not be shown to users.
final String? debugMessage;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is BillingResultWrapper &&
other.responseCode == responseCode &&
other.debugMessage == debugMessage;
}
@override
int get hashCode => Object.hash(responseCode, debugMessage);
}
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_response_wrapper.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_response_wrapper.dart",
"repo_id": "packages",
"token_count": 677
} | 994 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import '../billing_client_wrappers.dart';
import '../in_app_purchase_android.dart';
import 'billing_client_wrappers/billing_config_wrapper.dart';
import 'types/translator.dart';
/// Contains InApp Purchase features that are only available on PlayStore.
class InAppPurchaseAndroidPlatformAddition
extends InAppPurchasePlatformAddition {
/// Creates a [InAppPurchaseAndroidPlatformAddition] which uses the supplied
/// `BillingClientManager` to provide Android specific features.
InAppPurchaseAndroidPlatformAddition(this._billingClientManager) {
_billingClientManager.userChoiceDetailsStream
.map(Translator.convertToUserChoiceDetails)
.listen(_userChoiceDetailsStreamController.add);
}
final StreamController<GooglePlayUserChoiceDetails>
_userChoiceDetailsStreamController =
StreamController<GooglePlayUserChoiceDetails>.broadcast();
/// [GooglePlayUserChoiceDetails] emits each time user selects alternative billing.
late final Stream<GooglePlayUserChoiceDetails> userChoiceDetailsStream =
_userChoiceDetailsStreamController.stream;
/// Whether pending purchase is enabled.
///
/// **Deprecation warning:** it is no longer required to call
/// [enablePendingPurchases] when initializing your application. From now on
/// this is handled internally and the [enablePendingPurchase] property will
/// always return `true`.
///
/// See also [enablePendingPurchases] for more on pending purchases.
@Deprecated(
'The requirement to call `enablePendingPurchases()` has become obsolete '
"since Google Play no longer accepts app submissions that don't support "
'pending purchases.')
static bool get enablePendingPurchase => true;
/// Enable the [InAppPurchaseConnection] to handle pending purchases.
///
/// **Deprecation warning:** it is no longer required to call
/// [enablePendingPurchases] when initializing your application.
@Deprecated(
'The requirement to call `enablePendingPurchases()` has become obsolete '
"since Google Play no longer accepts app submissions that don't support "
'pending purchases.')
static void enablePendingPurchases() {
// No-op, until it is time to completely remove this method from the API.
}
final BillingClientManager _billingClientManager;
/// Mark that the user has consumed a product.
///
/// You are responsible for consuming all consumable purchases once they are
/// delivered. The user won't be able to buy the same product again until the
/// purchase of the product is consumed.
Future<BillingResultWrapper> consumePurchase(PurchaseDetails purchase) {
return _billingClientManager.runWithClient(
(BillingClient client) =>
client.consumeAsync(purchase.verificationData.serverVerificationData),
);
}
/// Query all previous purchases.
///
/// The `applicationUserName` should match whatever was sent in the initial
/// `PurchaseParam`, if anything. If no `applicationUserName` was specified in
/// the initial `PurchaseParam`, use `null`.
///
/// This does not return consumed products. If you want to restore unused
/// consumable products, you need to persist consumable product information
/// for your user on your own server.
///
/// See also:
///
/// * [refreshPurchaseVerificationData], for reloading failed
/// [PurchaseDetails.verificationData].
Future<QueryPurchaseDetailsResponse> queryPastPurchases(
{String? applicationUserName}) async {
List<PurchasesResultWrapper> responses;
PlatformException? exception;
try {
responses = await Future.wait(<Future<PurchasesResultWrapper>>[
_billingClientManager.runWithClient(
(BillingClient client) => client.queryPurchases(ProductType.inapp),
),
_billingClientManager.runWithClient(
(BillingClient client) => client.queryPurchases(ProductType.subs),
),
]);
} on PlatformException catch (e) {
exception = e;
responses = <PurchasesResultWrapper>[
PurchasesResultWrapper(
responseCode: BillingResponse.error,
purchasesList: const <PurchaseWrapper>[],
billingResult: BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: e.details.toString(),
),
),
PurchasesResultWrapper(
responseCode: BillingResponse.error,
purchasesList: const <PurchaseWrapper>[],
billingResult: BillingResultWrapper(
responseCode: BillingResponse.error,
debugMessage: e.details.toString(),
),
)
];
}
final Set<String> errorCodeSet = responses
.where((PurchasesResultWrapper response) =>
response.responseCode != BillingResponse.ok)
.map((PurchasesResultWrapper response) =>
response.responseCode.toString())
.toSet();
final String errorMessage =
errorCodeSet.isNotEmpty ? errorCodeSet.join(', ') : '';
final List<GooglePlayPurchaseDetails> pastPurchases = responses
.expand((PurchasesResultWrapper response) => response.purchasesList)
.expand((PurchaseWrapper purchaseWrapper) =>
GooglePlayPurchaseDetails.fromPurchase(purchaseWrapper))
.toList();
IAPError? error;
if (exception != null) {
error = IAPError(
source: kIAPSource,
code: exception.code,
message: exception.message ?? '',
details: exception.details);
} else if (errorMessage.isNotEmpty) {
error = IAPError(
source: kIAPSource,
code: kRestoredPurchaseErrorCode,
message: errorMessage);
}
return QueryPurchaseDetailsResponse(
pastPurchases: pastPurchases, error: error);
}
/// Checks if the specified feature or capability is supported by the Play Store.
/// Call this to check if a [BillingClientFeature] is supported by the device.
Future<bool> isFeatureSupported(BillingClientFeature feature) async {
return _billingClientManager.runWithClientNonRetryable(
(BillingClient client) => client.isFeatureSupported(feature),
);
}
/// Returns Play billing country code based on ISO-3166-1 alpha2 format.
///
/// See: https://developer.android.com/reference/com/android/billingclient/api/BillingConfig
/// See: https://unicode.org/cldr/charts/latest/supplemental/territory_containment_un_m_49.html
Future<String> getCountryCode() async {
final BillingConfigWrapper billingConfig = await _billingClientManager
.runWithClient((BillingClient client) => client.getBillingConfig());
return billingConfig.countryCode;
}
/// Returns if the caller can use alternative billing only without giving the
/// user a choice to use Play billing.
///
/// See: https://developer.android.com/reference/com/android/billingclient/api/BillingClient#isAlternativeBillingOnlyAvailableAsync(com.android.billingclient.api.AlternativeBillingOnlyAvailabilityListener)
Future<BillingResultWrapper> isAlternativeBillingOnlyAvailable() async {
final BillingResultWrapper wrapper =
await _billingClientManager.runWithClient((BillingClient client) =>
client.isAlternativeBillingOnlyAvailable());
return wrapper;
}
/// Shows the alternative billing only information dialog on top of the calling app.
///
/// See: https://developer.android.com/reference/com/android/billingclient/api/BillingClient#showAlternativeBillingOnlyInformationDialog(android.app.Activity,%20com.android.billingclient.api.AlternativeBillingOnlyInformationDialogListener)
Future<BillingResultWrapper>
showAlternativeBillingOnlyInformationDialog() async {
final BillingResultWrapper wrapper =
await _billingClientManager.runWithClient((BillingClient client) =>
client.showAlternativeBillingOnlyInformationDialog());
return wrapper;
}
/// The details used to report transactions made via alternative billing
/// without user choice to use Google Play billing.
///
/// See: https://developer.android.com/reference/com/android/billingclient/api/AlternativeBillingOnlyReportingDetails
Future<AlternativeBillingOnlyReportingDetailsWrapper>
createAlternativeBillingOnlyReportingDetails() async {
final AlternativeBillingOnlyReportingDetailsWrapper wrapper =
await _billingClientManager.runWithClient((BillingClient client) =>
client.createAlternativeBillingOnlyReportingDetails());
return wrapper;
}
/// Disconnects, sets AlternativeBillingOnly to true, and reconnects to
/// the [BillingClient].
///
/// [BillingChoiceMode.playBillingOnly] is the default state used.
/// [BillingChoiceMode.alternativeBillingOnly] will enable alternative billing only.
///
/// Play apis have requirements for when this method can be called.
/// See: https://developer.android.com/google/play/billing/alternative/alternative-billing-without-user-choice-in-app
Future<void> setBillingChoice(BillingChoiceMode billingChoiceMode) {
return _billingClientManager
.reconnectWithBillingChoiceMode(billingChoiceMode);
}
}
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart",
"repo_id": "packages",
"token_count": 2985
} | 995 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' as widgets;
import 'package:flutter_test/flutter_test.dart';
import 'package:in_app_purchase_android/billing_client_wrappers.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_android/src/billing_client_wrappers/billing_config_wrapper.dart';
import 'package:in_app_purchase_android/src/channel.dart';
import 'package:in_app_purchase_android/src/types/translator.dart';
import 'billing_client_wrappers/billing_client_wrapper_test.dart';
import 'billing_client_wrappers/purchase_wrapper_test.dart';
import 'stub_in_app_purchase_platform.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final StubInAppPurchasePlatform stubPlatform = StubInAppPurchasePlatform();
late InAppPurchaseAndroidPlatformAddition iapAndroidPlatformAddition;
const String startConnectionCall =
'BillingClient#startConnection(BillingClientStateListener)';
const String endConnectionCall = 'BillingClient#endConnection()';
const String onBillingServiceDisconnectedCallback =
'BillingClientStateListener#onBillingServiceDisconnected()';
late BillingClientManager manager;
setUpAll(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, stubPlatform.fakeMethodCallHandler);
});
setUp(() {
widgets.WidgetsFlutterBinding.ensureInitialized();
const String debugMessage = 'dummy message';
const BillingResponse responseCode = BillingResponse.ok;
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
stubPlatform.addResponse(
name: startConnectionCall,
value: buildBillingResultMap(expectedBillingResult));
stubPlatform.addResponse(name: endConnectionCall);
manager = BillingClientManager();
iapAndroidPlatformAddition = InAppPurchaseAndroidPlatformAddition(manager);
});
group('consume purchases', () {
const String consumeMethodName =
'BillingClient#consumeAsync(ConsumeParams, ConsumeResponseListener)';
test('consume purchase async success', () async {
const BillingResponse expectedCode = BillingResponse.ok;
const String debugMessage = 'dummy message';
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: expectedCode, debugMessage: debugMessage);
stubPlatform.addResponse(
name: consumeMethodName,
value: buildBillingResultMap(expectedBillingResult),
);
final BillingResultWrapper billingResultWrapper =
await iapAndroidPlatformAddition.consumePurchase(
GooglePlayPurchaseDetails.fromPurchase(dummyPurchase).first);
expect(billingResultWrapper, equals(expectedBillingResult));
});
});
group('billingConfig', () {
test('getCountryCode success', () async {
const String expectedCountryCode = 'US';
const BillingConfigWrapper expected = BillingConfigWrapper(
countryCode: expectedCountryCode,
responseCode: BillingResponse.ok,
debugMessage: 'dummy message');
stubPlatform.addResponse(
name: BillingClient.getBillingConfigMethodString,
value: buildBillingConfigMap(expected),
);
final String countryCode =
await iapAndroidPlatformAddition.getCountryCode();
expect(countryCode, equals(expectedCountryCode));
});
});
group('setBillingChoice', () {
late Map<Object?, Object?> arguments;
test('setAlternativeBillingOnlyState', () async {
stubPlatform.reset();
stubPlatform.addResponse(
name: startConnectionCall,
additionalStepBeforeReturn: (dynamic value) =>
arguments = value as Map<dynamic, dynamic>,
);
stubPlatform.addResponse(name: endConnectionCall);
await iapAndroidPlatformAddition
.setBillingChoice(BillingChoiceMode.alternativeBillingOnly);
// Fake the disconnect that we would expect from a endConnectionCall.
await manager.client.callHandler(
const MethodCall(onBillingServiceDisconnectedCallback,
<String, dynamic>{'handle': 0}),
);
// Verify that after connection ended reconnect was called.
expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(2));
expect(
arguments['billingChoiceMode'],
const BillingChoiceModeConverter()
.toJson(BillingChoiceMode.alternativeBillingOnly));
});
test('setPlayBillingState', () async {
stubPlatform.reset();
stubPlatform.addResponse(
name: startConnectionCall,
additionalStepBeforeReturn: (dynamic value) =>
arguments = value as Map<dynamic, dynamic>,
);
stubPlatform.addResponse(name: endConnectionCall);
await iapAndroidPlatformAddition
.setBillingChoice(BillingChoiceMode.playBillingOnly);
// Fake the disconnect that we would expect from a endConnectionCall.
await manager.client.callHandler(
const MethodCall(onBillingServiceDisconnectedCallback,
<String, dynamic>{'handle': 0}),
);
// Verify that after connection ended reconnect was called.
expect(stubPlatform.countPreviousCalls(startConnectionCall), equals(2));
expect(
arguments['billingChoiceMode'],
const BillingChoiceModeConverter()
.toJson(BillingChoiceMode.playBillingOnly));
});
});
group('isAlternativeBillingOnlyAvailable', () {
test('isAlternativeBillingOnlyAvailable success', () async {
const BillingResultWrapper expected = BillingResultWrapper(
responseCode: BillingResponse.ok, debugMessage: 'dummy message');
stubPlatform.addResponse(
name: BillingClient.isAlternativeBillingOnlyAvailableMethodString,
value: buildBillingResultMap(expected),
);
final BillingResultWrapper result =
await iapAndroidPlatformAddition.isAlternativeBillingOnlyAvailable();
expect(result, equals(expected));
});
});
group('showAlternativeBillingOnlyInformationDialog', () {
test('showAlternativeBillingOnlyInformationDialog success', () async {
const BillingResultWrapper expected = BillingResultWrapper(
responseCode: BillingResponse.ok, debugMessage: 'dummy message');
stubPlatform.addResponse(
name: BillingClient
.showAlternativeBillingOnlyInformationDialogMethodString,
value: buildBillingResultMap(expected),
);
final BillingResultWrapper result =
await iapAndroidPlatformAddition.isAlternativeBillingOnlyAvailable();
expect(result, equals(expected));
});
});
group('queryPastPurchase', () {
group('queryPurchaseDetails', () {
const String queryMethodName =
'BillingClient#queryPurchasesAsync(QueryPurchaseParams, PurchaseResponseListener)';
test('handles error', () async {
const String debugMessage = 'dummy message';
const BillingResponse responseCode = BillingResponse.developerError;
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
stubPlatform
.addResponse(name: queryMethodName, value: <dynamic, dynamic>{
'billingResult': buildBillingResultMap(expectedBillingResult),
'responseCode': const BillingResponseConverter().toJson(responseCode),
'purchasesList': <Map<String, dynamic>>[]
});
final QueryPurchaseDetailsResponse response =
await iapAndroidPlatformAddition.queryPastPurchases();
expect(response.pastPurchases, isEmpty);
expect(response.error, isNotNull);
expect(
response.error!.message, BillingResponse.developerError.toString());
expect(response.error!.source, kIAPSource);
});
test('returns ProductDetailsResponseWrapper', () async {
const String debugMessage = 'dummy message';
const BillingResponse responseCode = BillingResponse.ok;
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
stubPlatform
.addResponse(name: queryMethodName, value: <String, dynamic>{
'billingResult': buildBillingResultMap(expectedBillingResult),
'responseCode': const BillingResponseConverter().toJson(responseCode),
'purchasesList': <Map<String, dynamic>>[
buildPurchaseMap(dummyPurchase),
]
});
// Since queryPastPurchases makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead
// of 1.
final QueryPurchaseDetailsResponse response =
await iapAndroidPlatformAddition.queryPastPurchases();
expect(response.error, isNull);
expect(response.pastPurchases.first.purchaseID, dummyPurchase.orderId);
});
test('should store platform exception in the response', () async {
const String debugMessage = 'dummy message';
const BillingResponse responseCode = BillingResponse.developerError;
const BillingResultWrapper expectedBillingResult = BillingResultWrapper(
responseCode: responseCode, debugMessage: debugMessage);
stubPlatform.addResponse(
name: queryMethodName,
value: <dynamic, dynamic>{
'responseCode':
const BillingResponseConverter().toJson(responseCode),
'billingResult': buildBillingResultMap(expectedBillingResult),
'purchasesList': <Map<String, dynamic>>[]
},
additionalStepBeforeReturn: (dynamic _) {
throw PlatformException(
code: 'error_code',
message: 'error_message',
details: <dynamic, dynamic>{'info': 'error_info'},
);
});
final QueryPurchaseDetailsResponse response =
await iapAndroidPlatformAddition.queryPastPurchases();
expect(response.pastPurchases, isEmpty);
expect(response.error, isNotNull);
expect(response.error!.code, 'error_code');
expect(response.error!.message, 'error_message');
expect(
response.error!.details, <String, dynamic>{'info': 'error_info'});
});
});
});
group('isFeatureSupported', () {
const String isFeatureSupportedMethodName =
'BillingClient#isFeatureSupported(String)';
test('isFeatureSupported returns false', () async {
late Map<Object?, Object?> arguments;
stubPlatform.addResponse(
name: isFeatureSupportedMethodName,
value: false,
additionalStepBeforeReturn: (dynamic value) =>
arguments = value as Map<dynamic, dynamic>,
);
final bool isSupported = await iapAndroidPlatformAddition
.isFeatureSupported(BillingClientFeature.subscriptions);
expect(isSupported, isFalse);
expect(arguments['feature'], equals('subscriptions'));
});
test('isFeatureSupported returns true', () async {
late Map<Object?, Object?> arguments;
stubPlatform.addResponse(
name: isFeatureSupportedMethodName,
value: true,
additionalStepBeforeReturn: (dynamic value) =>
arguments = value as Map<dynamic, dynamic>,
);
final bool isSupported = await iapAndroidPlatformAddition
.isFeatureSupported(BillingClientFeature.subscriptions);
expect(isSupported, isTrue);
expect(arguments['feature'], equals('subscriptions'));
});
});
group('userChoiceDetails', () {
test('called', () async {
final Future<GooglePlayUserChoiceDetails> futureDetails =
iapAndroidPlatformAddition.userChoiceDetailsStream.first;
const UserChoiceDetailsWrapper expected = UserChoiceDetailsWrapper(
originalExternalTransactionId: 'TransactionId',
externalTransactionToken: 'TransactionToken',
products: <UserChoiceDetailsProductWrapper>[
UserChoiceDetailsProductWrapper(
id: 'id1',
offerToken: 'offerToken1',
productType: ProductType.inapp),
UserChoiceDetailsProductWrapper(
id: 'id2',
offerToken: 'offerToken2',
productType: ProductType.inapp),
],
);
manager.onUserChoiceAlternativeBilling(expected);
expect(
await futureDetails, Translator.convertToUserChoiceDetails(expected));
});
});
}
| packages/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_addition_test.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_addition_test.dart",
"repo_id": "packages",
"token_count": 4655
} | 996 |
// 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 <StoreKit/StoreKit.h>
#import "messages.g.h"
NS_ASSUME_NONNULL_BEGIN
@interface FIAObjectTranslator : NSObject
// Converts an instance of SKProduct into a dictionary.
+ (NSDictionary *)getMapFromSKProduct:(SKProduct *)product;
// Converts an instance of SKProductSubscriptionPeriod into a dictionary.
+ (NSDictionary *)getMapFromSKProductSubscriptionPeriod:(SKProductSubscriptionPeriod *)period
API_AVAILABLE(ios(11.2));
// Converts an instance of SKProductDiscount into a dictionary.
+ (NSDictionary *)getMapFromSKProductDiscount:(SKProductDiscount *)discount
API_AVAILABLE(ios(11.2));
// Converts an array of SKProductDiscount instances into an array of dictionaries.
+ (nonnull NSArray *)getMapArrayFromSKProductDiscounts:
(nonnull NSArray<SKProductDiscount *> *)productDiscounts API_AVAILABLE(ios(12.2));
// Converts an instance of SKProductsResponse into a dictionary.
+ (NSDictionary *)getMapFromSKProductsResponse:(SKProductsResponse *)productResponse;
// Converts an instance of SKPayment into a dictionary.
+ (NSDictionary *)getMapFromSKPayment:(SKPayment *)payment;
// Converts an instance of NSLocale into a dictionary.
+ (NSDictionary *)getMapFromNSLocale:(NSLocale *)locale;
// Creates an instance of the SKMutablePayment class based on the supplied dictionary.
+ (SKMutablePayment *)getSKMutablePaymentFromMap:(NSDictionary *)map;
// Converts an instance of SKPaymentTransaction into a dictionary.
+ (NSDictionary *)getMapFromSKPaymentTransaction:(SKPaymentTransaction *)transaction;
// Converts an instance of NSError into a dictionary.
+ (NSDictionary *)getMapFromNSError:(NSError *)error;
// Converts an instance of SKStorefront into a dictionary.
+ (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront
API_AVAILABLE(ios(13), macos(10.15), watchos(6.2));
// Converts the supplied instances of SKStorefront and SKPaymentTransaction into a dictionary.
+ (NSDictionary *)getMapFromSKStorefront:(SKStorefront *)storefront
andSKPaymentTransaction:(SKPaymentTransaction *)transaction
API_AVAILABLE(ios(13), macos(10.15), watchos(6.2));
// Creates an instance of the SKPaymentDiscount class based on the supplied dictionary.
+ (nullable SKPaymentDiscount *)getSKPaymentDiscountFromMap:(NSDictionary *)map
withError:(NSString *_Nullable *_Nullable)error
API_AVAILABLE(ios(12.2));
+ (nullable SKPaymentTransactionMessage *)convertTransactionToPigeon:
(nullable SKPaymentTransaction *)transaction;
+ (nullable SKStorefrontMessage *)convertStorefrontToPigeon:(nullable SKStorefront *)storefront
API_AVAILABLE(ios(13.0));
+ (nullable SKPaymentDiscountMessage *)convertPaymentDiscountToPigeon:
(nullable SKPaymentDiscount *)discount API_AVAILABLE(ios(12.2));
+ (nullable SKPaymentMessage *)convertPaymentToPigeon:(nullable SKPayment *)payment
API_AVAILABLE(ios(12.2));
+ (nullable SKErrorMessage *)convertSKErrorToPigeon:(nullable NSError *)error;
+ (nullable SKProductsResponseMessage *)convertProductsResponseToPigeon:
(nullable SKProductsResponse *)payment;
+ (nullable SKProductMessage *)convertProductToPigeon:(nullable SKProduct *)product
API_AVAILABLE(ios(12.2));
+ (nullable SKProductDiscountMessage *)convertProductDiscountToPigeon:
(nullable SKProductDiscount *)productDiscount API_AVAILABLE(ios(12.2));
+ (nullable SKPriceLocaleMessage *)convertNSLocaleToPigeon:(nullable NSLocale *)locale
API_AVAILABLE(ios(12.2));
+ (nullable SKProductSubscriptionPeriodMessage *)convertSKProductSubscriptionPeriodToPigeon:
(nullable SKProductSubscriptionPeriod *)period API_AVAILABLE(ios(12.2));
@end
NS_ASSUME_NONNULL_END
| packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAObjectTranslator.h/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAObjectTranslator.h",
"repo_id": "packages",
"token_count": 1292
} | 997 |
// 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 (v16.0.4), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import "messages.g.h"
#if TARGET_OS_OSX
#import <FlutterMacOS/FlutterMacOS.h>
#else
#import <Flutter/Flutter.h>
#endif
#if !__has_feature(objc_arc)
#error File requires ARC to be enabled.
#endif
static NSArray *wrapResult(id result, FlutterError *error) {
if (error) {
return @[
error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null]
];
}
return @[ result ?: [NSNull null] ];
}
static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) {
id result = array[key];
return (result == [NSNull null]) ? nil : result;
}
@implementation SKPaymentTransactionStateMessageBox
- (instancetype)initWithValue:(SKPaymentTransactionStateMessage)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
@implementation SKProductDiscountTypeMessageBox
- (instancetype)initWithValue:(SKProductDiscountTypeMessage)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
@implementation SKProductDiscountPaymentModeMessageBox
- (instancetype)initWithValue:(SKProductDiscountPaymentModeMessage)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
@implementation SKSubscriptionPeriodUnitMessageBox
- (instancetype)initWithValue:(SKSubscriptionPeriodUnitMessage)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
@interface SKPaymentTransactionMessage ()
+ (SKPaymentTransactionMessage *)fromList:(NSArray *)list;
+ (nullable SKPaymentTransactionMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKPaymentMessage ()
+ (SKPaymentMessage *)fromList:(NSArray *)list;
+ (nullable SKPaymentMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKErrorMessage ()
+ (SKErrorMessage *)fromList:(NSArray *)list;
+ (nullable SKErrorMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKPaymentDiscountMessage ()
+ (SKPaymentDiscountMessage *)fromList:(NSArray *)list;
+ (nullable SKPaymentDiscountMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKStorefrontMessage ()
+ (SKStorefrontMessage *)fromList:(NSArray *)list;
+ (nullable SKStorefrontMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKProductsResponseMessage ()
+ (SKProductsResponseMessage *)fromList:(NSArray *)list;
+ (nullable SKProductsResponseMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKProductMessage ()
+ (SKProductMessage *)fromList:(NSArray *)list;
+ (nullable SKProductMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKPriceLocaleMessage ()
+ (SKPriceLocaleMessage *)fromList:(NSArray *)list;
+ (nullable SKPriceLocaleMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKProductDiscountMessage ()
+ (SKProductDiscountMessage *)fromList:(NSArray *)list;
+ (nullable SKProductDiscountMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface SKProductSubscriptionPeriodMessage ()
+ (SKProductSubscriptionPeriodMessage *)fromList:(NSArray *)list;
+ (nullable SKProductSubscriptionPeriodMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@implementation SKPaymentTransactionMessage
+ (instancetype)makeWithPayment:(SKPaymentMessage *)payment
transactionState:(SKPaymentTransactionStateMessage)transactionState
originalTransaction:(nullable SKPaymentTransactionMessage *)originalTransaction
transactionTimeStamp:(nullable NSNumber *)transactionTimeStamp
transactionIdentifier:(nullable NSString *)transactionIdentifier
error:(nullable SKErrorMessage *)error {
SKPaymentTransactionMessage *pigeonResult = [[SKPaymentTransactionMessage alloc] init];
pigeonResult.payment = payment;
pigeonResult.transactionState = transactionState;
pigeonResult.originalTransaction = originalTransaction;
pigeonResult.transactionTimeStamp = transactionTimeStamp;
pigeonResult.transactionIdentifier = transactionIdentifier;
pigeonResult.error = error;
return pigeonResult;
}
+ (SKPaymentTransactionMessage *)fromList:(NSArray *)list {
SKPaymentTransactionMessage *pigeonResult = [[SKPaymentTransactionMessage alloc] init];
pigeonResult.payment = [SKPaymentMessage nullableFromList:(GetNullableObjectAtIndex(list, 0))];
pigeonResult.transactionState = [GetNullableObjectAtIndex(list, 1) integerValue];
pigeonResult.originalTransaction =
[SKPaymentTransactionMessage nullableFromList:(GetNullableObjectAtIndex(list, 2))];
pigeonResult.transactionTimeStamp = GetNullableObjectAtIndex(list, 3);
pigeonResult.transactionIdentifier = GetNullableObjectAtIndex(list, 4);
pigeonResult.error = [SKErrorMessage nullableFromList:(GetNullableObjectAtIndex(list, 5))];
return pigeonResult;
}
+ (nullable SKPaymentTransactionMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKPaymentTransactionMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.payment ? [self.payment toList] : [NSNull null]),
@(self.transactionState),
(self.originalTransaction ? [self.originalTransaction toList] : [NSNull null]),
self.transactionTimeStamp ?: [NSNull null],
self.transactionIdentifier ?: [NSNull null],
(self.error ? [self.error toList] : [NSNull null]),
];
}
@end
@implementation SKPaymentMessage
+ (instancetype)makeWithProductIdentifier:(NSString *)productIdentifier
applicationUsername:(nullable NSString *)applicationUsername
requestData:(nullable NSString *)requestData
quantity:(NSInteger)quantity
simulatesAskToBuyInSandbox:(BOOL)simulatesAskToBuyInSandbox
paymentDiscount:(nullable SKPaymentDiscountMessage *)paymentDiscount {
SKPaymentMessage *pigeonResult = [[SKPaymentMessage alloc] init];
pigeonResult.productIdentifier = productIdentifier;
pigeonResult.applicationUsername = applicationUsername;
pigeonResult.requestData = requestData;
pigeonResult.quantity = quantity;
pigeonResult.simulatesAskToBuyInSandbox = simulatesAskToBuyInSandbox;
pigeonResult.paymentDiscount = paymentDiscount;
return pigeonResult;
}
+ (SKPaymentMessage *)fromList:(NSArray *)list {
SKPaymentMessage *pigeonResult = [[SKPaymentMessage alloc] init];
pigeonResult.productIdentifier = GetNullableObjectAtIndex(list, 0);
pigeonResult.applicationUsername = GetNullableObjectAtIndex(list, 1);
pigeonResult.requestData = GetNullableObjectAtIndex(list, 2);
pigeonResult.quantity = [GetNullableObjectAtIndex(list, 3) integerValue];
pigeonResult.simulatesAskToBuyInSandbox = [GetNullableObjectAtIndex(list, 4) boolValue];
pigeonResult.paymentDiscount =
[SKPaymentDiscountMessage nullableFromList:(GetNullableObjectAtIndex(list, 5))];
return pigeonResult;
}
+ (nullable SKPaymentMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKPaymentMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.productIdentifier ?: [NSNull null],
self.applicationUsername ?: [NSNull null],
self.requestData ?: [NSNull null],
@(self.quantity),
@(self.simulatesAskToBuyInSandbox),
(self.paymentDiscount ? [self.paymentDiscount toList] : [NSNull null]),
];
}
@end
@implementation SKErrorMessage
+ (instancetype)makeWithCode:(NSInteger)code
domain:(NSString *)domain
userInfo:(nullable NSDictionary<NSString *, id> *)userInfo {
SKErrorMessage *pigeonResult = [[SKErrorMessage alloc] init];
pigeonResult.code = code;
pigeonResult.domain = domain;
pigeonResult.userInfo = userInfo;
return pigeonResult;
}
+ (SKErrorMessage *)fromList:(NSArray *)list {
SKErrorMessage *pigeonResult = [[SKErrorMessage alloc] init];
pigeonResult.code = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.domain = GetNullableObjectAtIndex(list, 1);
pigeonResult.userInfo = GetNullableObjectAtIndex(list, 2);
return pigeonResult;
}
+ (nullable SKErrorMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKErrorMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.code),
self.domain ?: [NSNull null],
self.userInfo ?: [NSNull null],
];
}
@end
@implementation SKPaymentDiscountMessage
+ (instancetype)makeWithIdentifier:(NSString *)identifier
keyIdentifier:(NSString *)keyIdentifier
nonce:(NSString *)nonce
signature:(NSString *)signature
timestamp:(NSInteger)timestamp {
SKPaymentDiscountMessage *pigeonResult = [[SKPaymentDiscountMessage alloc] init];
pigeonResult.identifier = identifier;
pigeonResult.keyIdentifier = keyIdentifier;
pigeonResult.nonce = nonce;
pigeonResult.signature = signature;
pigeonResult.timestamp = timestamp;
return pigeonResult;
}
+ (SKPaymentDiscountMessage *)fromList:(NSArray *)list {
SKPaymentDiscountMessage *pigeonResult = [[SKPaymentDiscountMessage alloc] init];
pigeonResult.identifier = GetNullableObjectAtIndex(list, 0);
pigeonResult.keyIdentifier = GetNullableObjectAtIndex(list, 1);
pigeonResult.nonce = GetNullableObjectAtIndex(list, 2);
pigeonResult.signature = GetNullableObjectAtIndex(list, 3);
pigeonResult.timestamp = [GetNullableObjectAtIndex(list, 4) integerValue];
return pigeonResult;
}
+ (nullable SKPaymentDiscountMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKPaymentDiscountMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.identifier ?: [NSNull null],
self.keyIdentifier ?: [NSNull null],
self.nonce ?: [NSNull null],
self.signature ?: [NSNull null],
@(self.timestamp),
];
}
@end
@implementation SKStorefrontMessage
+ (instancetype)makeWithCountryCode:(NSString *)countryCode identifier:(NSString *)identifier {
SKStorefrontMessage *pigeonResult = [[SKStorefrontMessage alloc] init];
pigeonResult.countryCode = countryCode;
pigeonResult.identifier = identifier;
return pigeonResult;
}
+ (SKStorefrontMessage *)fromList:(NSArray *)list {
SKStorefrontMessage *pigeonResult = [[SKStorefrontMessage alloc] init];
pigeonResult.countryCode = GetNullableObjectAtIndex(list, 0);
pigeonResult.identifier = GetNullableObjectAtIndex(list, 1);
return pigeonResult;
}
+ (nullable SKStorefrontMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKStorefrontMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.countryCode ?: [NSNull null],
self.identifier ?: [NSNull null],
];
}
@end
@implementation SKProductsResponseMessage
+ (instancetype)makeWithProducts:(nullable NSArray<SKProductMessage *> *)products
invalidProductIdentifiers:(nullable NSArray<NSString *> *)invalidProductIdentifiers {
SKProductsResponseMessage *pigeonResult = [[SKProductsResponseMessage alloc] init];
pigeonResult.products = products;
pigeonResult.invalidProductIdentifiers = invalidProductIdentifiers;
return pigeonResult;
}
+ (SKProductsResponseMessage *)fromList:(NSArray *)list {
SKProductsResponseMessage *pigeonResult = [[SKProductsResponseMessage alloc] init];
pigeonResult.products = GetNullableObjectAtIndex(list, 0);
pigeonResult.invalidProductIdentifiers = GetNullableObjectAtIndex(list, 1);
return pigeonResult;
}
+ (nullable SKProductsResponseMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKProductsResponseMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.products ?: [NSNull null],
self.invalidProductIdentifiers ?: [NSNull null],
];
}
@end
@implementation SKProductMessage
+ (instancetype)
makeWithProductIdentifier:(NSString *)productIdentifier
localizedTitle:(NSString *)localizedTitle
localizedDescription:(NSString *)localizedDescription
priceLocale:(SKPriceLocaleMessage *)priceLocale
subscriptionGroupIdentifier:(nullable NSString *)subscriptionGroupIdentifier
price:(NSString *)price
subscriptionPeriod:(nullable SKProductSubscriptionPeriodMessage *)subscriptionPeriod
introductoryPrice:(nullable SKProductDiscountMessage *)introductoryPrice
discounts:(nullable NSArray<SKProductDiscountMessage *> *)discounts {
SKProductMessage *pigeonResult = [[SKProductMessage alloc] init];
pigeonResult.productIdentifier = productIdentifier;
pigeonResult.localizedTitle = localizedTitle;
pigeonResult.localizedDescription = localizedDescription;
pigeonResult.priceLocale = priceLocale;
pigeonResult.subscriptionGroupIdentifier = subscriptionGroupIdentifier;
pigeonResult.price = price;
pigeonResult.subscriptionPeriod = subscriptionPeriod;
pigeonResult.introductoryPrice = introductoryPrice;
pigeonResult.discounts = discounts;
return pigeonResult;
}
+ (SKProductMessage *)fromList:(NSArray *)list {
SKProductMessage *pigeonResult = [[SKProductMessage alloc] init];
pigeonResult.productIdentifier = GetNullableObjectAtIndex(list, 0);
pigeonResult.localizedTitle = GetNullableObjectAtIndex(list, 1);
pigeonResult.localizedDescription = GetNullableObjectAtIndex(list, 2);
pigeonResult.priceLocale =
[SKPriceLocaleMessage nullableFromList:(GetNullableObjectAtIndex(list, 3))];
pigeonResult.subscriptionGroupIdentifier = GetNullableObjectAtIndex(list, 4);
pigeonResult.price = GetNullableObjectAtIndex(list, 5);
pigeonResult.subscriptionPeriod =
[SKProductSubscriptionPeriodMessage nullableFromList:(GetNullableObjectAtIndex(list, 6))];
pigeonResult.introductoryPrice =
[SKProductDiscountMessage nullableFromList:(GetNullableObjectAtIndex(list, 7))];
pigeonResult.discounts = GetNullableObjectAtIndex(list, 8);
return pigeonResult;
}
+ (nullable SKProductMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKProductMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.productIdentifier ?: [NSNull null],
self.localizedTitle ?: [NSNull null],
self.localizedDescription ?: [NSNull null],
(self.priceLocale ? [self.priceLocale toList] : [NSNull null]),
self.subscriptionGroupIdentifier ?: [NSNull null],
self.price ?: [NSNull null],
(self.subscriptionPeriod ? [self.subscriptionPeriod toList] : [NSNull null]),
(self.introductoryPrice ? [self.introductoryPrice toList] : [NSNull null]),
self.discounts ?: [NSNull null],
];
}
@end
@implementation SKPriceLocaleMessage
+ (instancetype)makeWithCurrencySymbol:(NSString *)currencySymbol
currencyCode:(NSString *)currencyCode
countryCode:(NSString *)countryCode {
SKPriceLocaleMessage *pigeonResult = [[SKPriceLocaleMessage alloc] init];
pigeonResult.currencySymbol = currencySymbol;
pigeonResult.currencyCode = currencyCode;
pigeonResult.countryCode = countryCode;
return pigeonResult;
}
+ (SKPriceLocaleMessage *)fromList:(NSArray *)list {
SKPriceLocaleMessage *pigeonResult = [[SKPriceLocaleMessage alloc] init];
pigeonResult.currencySymbol = GetNullableObjectAtIndex(list, 0);
pigeonResult.currencyCode = GetNullableObjectAtIndex(list, 1);
pigeonResult.countryCode = GetNullableObjectAtIndex(list, 2);
return pigeonResult;
}
+ (nullable SKPriceLocaleMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKPriceLocaleMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.currencySymbol ?: [NSNull null],
self.currencyCode ?: [NSNull null],
self.countryCode ?: [NSNull null],
];
}
@end
@implementation SKProductDiscountMessage
+ (instancetype)makeWithPrice:(NSString *)price
priceLocale:(SKPriceLocaleMessage *)priceLocale
numberOfPeriods:(NSInteger)numberOfPeriods
paymentMode:(SKProductDiscountPaymentModeMessage)paymentMode
subscriptionPeriod:(SKProductSubscriptionPeriodMessage *)subscriptionPeriod
identifier:(nullable NSString *)identifier
type:(SKProductDiscountTypeMessage)type {
SKProductDiscountMessage *pigeonResult = [[SKProductDiscountMessage alloc] init];
pigeonResult.price = price;
pigeonResult.priceLocale = priceLocale;
pigeonResult.numberOfPeriods = numberOfPeriods;
pigeonResult.paymentMode = paymentMode;
pigeonResult.subscriptionPeriod = subscriptionPeriod;
pigeonResult.identifier = identifier;
pigeonResult.type = type;
return pigeonResult;
}
+ (SKProductDiscountMessage *)fromList:(NSArray *)list {
SKProductDiscountMessage *pigeonResult = [[SKProductDiscountMessage alloc] init];
pigeonResult.price = GetNullableObjectAtIndex(list, 0);
pigeonResult.priceLocale =
[SKPriceLocaleMessage nullableFromList:(GetNullableObjectAtIndex(list, 1))];
pigeonResult.numberOfPeriods = [GetNullableObjectAtIndex(list, 2) integerValue];
pigeonResult.paymentMode = [GetNullableObjectAtIndex(list, 3) integerValue];
pigeonResult.subscriptionPeriod =
[SKProductSubscriptionPeriodMessage nullableFromList:(GetNullableObjectAtIndex(list, 4))];
pigeonResult.identifier = GetNullableObjectAtIndex(list, 5);
pigeonResult.type = [GetNullableObjectAtIndex(list, 6) integerValue];
return pigeonResult;
}
+ (nullable SKProductDiscountMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKProductDiscountMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.price ?: [NSNull null],
(self.priceLocale ? [self.priceLocale toList] : [NSNull null]),
@(self.numberOfPeriods),
@(self.paymentMode),
(self.subscriptionPeriod ? [self.subscriptionPeriod toList] : [NSNull null]),
self.identifier ?: [NSNull null],
@(self.type),
];
}
@end
@implementation SKProductSubscriptionPeriodMessage
+ (instancetype)makeWithNumberOfUnits:(NSInteger)numberOfUnits
unit:(SKSubscriptionPeriodUnitMessage)unit {
SKProductSubscriptionPeriodMessage *pigeonResult =
[[SKProductSubscriptionPeriodMessage alloc] init];
pigeonResult.numberOfUnits = numberOfUnits;
pigeonResult.unit = unit;
return pigeonResult;
}
+ (SKProductSubscriptionPeriodMessage *)fromList:(NSArray *)list {
SKProductSubscriptionPeriodMessage *pigeonResult =
[[SKProductSubscriptionPeriodMessage alloc] init];
pigeonResult.numberOfUnits = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.unit = [GetNullableObjectAtIndex(list, 1) integerValue];
return pigeonResult;
}
+ (nullable SKProductSubscriptionPeriodMessage *)nullableFromList:(NSArray *)list {
return (list) ? [SKProductSubscriptionPeriodMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.numberOfUnits),
@(self.unit),
];
}
@end
@interface InAppPurchaseAPICodecReader : FlutterStandardReader
@end
@implementation InAppPurchaseAPICodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [SKErrorMessage fromList:[self readValue]];
case 129:
return [SKPaymentDiscountMessage fromList:[self readValue]];
case 130:
return [SKPaymentMessage fromList:[self readValue]];
case 131:
return [SKPaymentTransactionMessage fromList:[self readValue]];
case 132:
return [SKPriceLocaleMessage fromList:[self readValue]];
case 133:
return [SKProductDiscountMessage fromList:[self readValue]];
case 134:
return [SKProductMessage fromList:[self readValue]];
case 135:
return [SKProductSubscriptionPeriodMessage fromList:[self readValue]];
case 136:
return [SKProductsResponseMessage fromList:[self readValue]];
case 137:
return [SKStorefrontMessage fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface InAppPurchaseAPICodecWriter : FlutterStandardWriter
@end
@implementation InAppPurchaseAPICodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[SKErrorMessage class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKPaymentDiscountMessage class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKPaymentMessage class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKPaymentTransactionMessage class]]) {
[self writeByte:131];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKPriceLocaleMessage class]]) {
[self writeByte:132];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKProductDiscountMessage class]]) {
[self writeByte:133];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKProductMessage class]]) {
[self writeByte:134];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKProductSubscriptionPeriodMessage class]]) {
[self writeByte:135];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKProductsResponseMessage class]]) {
[self writeByte:136];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[SKStorefrontMessage class]]) {
[self writeByte:137];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface InAppPurchaseAPICodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation InAppPurchaseAPICodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[InAppPurchaseAPICodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[InAppPurchaseAPICodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *InAppPurchaseAPIGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
InAppPurchaseAPICodecReaderWriter *readerWriter =
[[InAppPurchaseAPICodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpInAppPurchaseAPI(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<InAppPurchaseAPI> *api) {
/// Returns if the current device is able to make payments
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.canMakePayments"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(canMakePaymentsWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to @selector(canMakePaymentsWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
NSNumber *output = [api canMakePaymentsWithError:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.transactions"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(transactionsWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to @selector(transactionsWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
NSArray<SKPaymentTransactionMessage *> *output = [api transactionsWithError:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.storefront"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(storefrontWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to @selector(storefrontWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
SKStorefrontMessage *output = [api storefrontWithError:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.addPayment"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(addPaymentPaymentMap:error:)],
@"InAppPurchaseAPI api (%@) doesn't respond to @selector(addPaymentPaymentMap:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSDictionary<NSString *, id> *arg_paymentMap = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api addPaymentPaymentMap:arg_paymentMap error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startProductRequest"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(startProductRequestProductIdentifiers:
completion:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(startProductRequestProductIdentifiers:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSArray<NSString *> *arg_productIdentifiers = GetNullableObjectAtIndex(args, 0);
[api startProductRequestProductIdentifiers:arg_productIdentifiers
completion:^(SKProductsResponseMessage *_Nullable output,
FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.finishTransaction"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(finishTransactionFinishMap:error:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(finishTransactionFinishMap:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSDictionary<NSString *, NSString *> *arg_finishMap = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api finishTransactionFinishMap:arg_finishMap error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.restoreTransactions"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(restoreTransactionsApplicationUserName:error:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(restoreTransactionsApplicationUserName:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSString *arg_applicationUserName = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api restoreTransactionsApplicationUserName:arg_applicationUserName error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI."
@"presentCodeRedemptionSheet"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(presentCodeRedemptionSheetWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(presentCodeRedemptionSheetWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api presentCodeRedemptionSheetWithError:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.retrieveReceiptData"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(retrieveReceiptDataWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to @selector(retrieveReceiptDataWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
NSString *output = [api retrieveReceiptDataWithError:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.refreshReceipt"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(refreshReceiptReceiptProperties:completion:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(refreshReceiptReceiptProperties:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSDictionary<NSString *, id> *arg_receiptProperties = GetNullableObjectAtIndex(args, 0);
[api refreshReceiptReceiptProperties:arg_receiptProperties
completion:^(FlutterError *_Nullable error) {
callback(wrapResult(nil, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI."
@"startObservingPaymentQueue"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(startObservingPaymentQueueWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(startObservingPaymentQueueWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api startObservingPaymentQueueWithError:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI."
@"stopObservingPaymentQueue"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(stopObservingPaymentQueueWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(stopObservingPaymentQueueWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api stopObservingPaymentQueueWithError:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI."
@"registerPaymentQueueDelegate"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(registerPaymentQueueDelegateWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(registerPaymentQueueDelegateWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api registerPaymentQueueDelegateWithError:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI."
@"removePaymentQueueDelegate"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(removePaymentQueueDelegateWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(removePaymentQueueDelegateWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api removePaymentQueueDelegateWithError:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI."
@"showPriceConsentIfNeeded"
binaryMessenger:binaryMessenger
codec:InAppPurchaseAPIGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(showPriceConsentIfNeededWithError:)],
@"InAppPurchaseAPI api (%@) doesn't respond to "
@"@selector(showPriceConsentIfNeededWithError:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api showPriceConsentIfNeededWithError:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
| packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/messages.g.m/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/messages.g.m",
"repo_id": "packages",
"token_count": 13686
} | 998 |
// 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
import Foundation
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#else
#error("Unsupported platform.")
#endif
private func isNullish(_ value: Any?) -> Bool {
return value is NSNull || value == nil
}
private func wrapResult(_ result: Any?) -> [Any?] {
return [result]
}
private func wrapError(_ error: Any) -> [Any?] {
if let flutterError = error as? FlutterError {
return [
flutterError.code,
flutterError.message,
flutterError.details,
]
}
return [
"\(error)",
"\(type(of: error))",
"Stacktrace: \(Thread.callStackSymbols)",
]
}
private func nilOrValue<T>(_ value: Any?) -> T? {
if value is NSNull { return nil }
return value as! T?
}
/// A serialization of a platform image's data.
///
/// Generated class from Pigeon that represents data sent in messages.
struct PlatformImageData {
/// The image data.
var data: FlutterStandardTypedData
/// The image's scale factor.
var scale: Double
static func fromList(_ list: [Any?]) -> PlatformImageData? {
let data = list[0] as! FlutterStandardTypedData
let scale = list[1] as! Double
return PlatformImageData(
data: data,
scale: scale
)
}
func toList() -> [Any?] {
return [
data,
scale,
]
}
}
private class PlatformImagesApiCodecReader: FlutterStandardReader {
override func readValue(ofType type: UInt8) -> Any? {
switch type {
case 128:
return PlatformImageData.fromList(self.readValue() as! [Any?])
default:
return super.readValue(ofType: type)
}
}
}
private class PlatformImagesApiCodecWriter: FlutterStandardWriter {
override func writeValue(_ value: Any) {
if let value = value as? PlatformImageData {
super.writeByte(128)
super.writeValue(value.toList())
} else {
super.writeValue(value)
}
}
}
private class PlatformImagesApiCodecReaderWriter: FlutterStandardReaderWriter {
override func reader(with data: Data) -> FlutterStandardReader {
return PlatformImagesApiCodecReader(data: data)
}
override func writer(with data: NSMutableData) -> FlutterStandardWriter {
return PlatformImagesApiCodecWriter(data: data)
}
}
class PlatformImagesApiCodec: FlutterStandardMessageCodec {
static let shared = PlatformImagesApiCodec(readerWriter: PlatformImagesApiCodecReaderWriter())
}
/// Generated protocol from Pigeon that represents a handler of messages from Flutter.
protocol PlatformImagesApi {
/// Returns the URL for the given resource, or null if no such resource is
/// found.
func resolveUrl(resourceName: String, extension: String?) throws -> String?
/// Returns the data for the image resource with the given name, or null if
/// no such resource is found.
func loadImage(name: String) throws -> PlatformImageData?
}
/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`.
class PlatformImagesApiSetup {
/// The codec used by PlatformImagesApi.
static var codec: FlutterStandardMessageCodec { PlatformImagesApiCodec.shared }
/// Sets up an instance of `PlatformImagesApi` to handle messages through the `binaryMessenger`.
static func setUp(binaryMessenger: FlutterBinaryMessenger, api: PlatformImagesApi?) {
/// Returns the URL for the given resource, or null if no such resource is
/// found.
let resolveUrlChannel = FlutterBasicMessageChannel(
name: "dev.flutter.pigeon.ios_platform_images.PlatformImagesApi.resolveUrl",
binaryMessenger: binaryMessenger, codec: codec)
if let api = api {
resolveUrlChannel.setMessageHandler { message, reply in
let args = message as! [Any?]
let resourceNameArg = args[0] as! String
let extensionArg: String? = nilOrValue(args[1])
do {
let result = try api.resolveUrl(resourceName: resourceNameArg, extension: extensionArg)
reply(wrapResult(result))
} catch {
reply(wrapError(error))
}
}
} else {
resolveUrlChannel.setMessageHandler(nil)
}
/// Returns the data for the image resource with the given name, or null if
/// no such resource is found.
let loadImageChannel = FlutterBasicMessageChannel(
name: "dev.flutter.pigeon.ios_platform_images.PlatformImagesApi.loadImage",
binaryMessenger: binaryMessenger, codec: codec)
if let api = api {
loadImageChannel.setMessageHandler { message, reply in
let args = message as! [Any?]
let nameArg = args[0] as! String
do {
let result = try api.loadImage(name: nameArg)
reply(wrapResult(result))
} catch {
reply(wrapError(error))
}
}
} else {
loadImageChannel.setMessageHandler(nil)
}
}
}
| packages/packages/ios_platform_images/ios/Classes/messages.g.swift/0 | {
"file_path": "packages/packages/ios_platform_images/ios/Classes/messages.g.swift",
"repo_id": "packages",
"token_count": 1730
} | 999 |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Fingerprint colors -->
<color name="black_text">#212121</color>
<color name="grey_text">#757575</color>
</resources>
| packages/packages/local_auth/local_auth_android/android/src/main/res/values/colors.xml/0 | {
"file_path": "packages/packages/local_auth/local_auth_android/android/src/main/res/values/colors.xml",
"repo_id": "packages",
"token_count": 64
} | 1,000 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:local_auth_android/local_auth_android.dart';
import 'package:local_auth_android/src/messages.g.dart';
import 'package:local_auth_platform_interface/local_auth_platform_interface.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'local_auth_test.mocks.dart';
@GenerateMocks(<Type>[LocalAuthApi])
void main() {
late MockLocalAuthApi api;
late LocalAuthAndroid plugin;
setUp(() {
api = MockLocalAuthApi();
plugin = LocalAuthAndroid(api: api);
});
test('registers instance', () {
LocalAuthAndroid.registerWith();
expect(LocalAuthPlatform.instance, isA<LocalAuthAndroid>());
});
group('deviceSupportsBiometrics', () {
test('handles true', () async {
when(api.deviceCanSupportBiometrics()).thenAnswer((_) async => true);
expect(await plugin.deviceSupportsBiometrics(), true);
});
test('handles false', () async {
when(api.deviceCanSupportBiometrics()).thenAnswer((_) async => false);
expect(await plugin.deviceSupportsBiometrics(), false);
});
});
group('isDeviceSupported', () {
test('handles true', () async {
when(api.isDeviceSupported()).thenAnswer((_) async => true);
expect(await plugin.isDeviceSupported(), true);
});
test('handles false', () async {
when(api.isDeviceSupported()).thenAnswer((_) async => false);
expect(await plugin.isDeviceSupported(), false);
});
});
group('stopAuthentication', () {
test('handles true', () async {
when(api.stopAuthentication()).thenAnswer((_) async => true);
expect(await plugin.stopAuthentication(), true);
});
test('handles false', () async {
when(api.stopAuthentication()).thenAnswer((_) async => false);
expect(await plugin.stopAuthentication(), false);
});
});
group('getEnrolledBiometrics', () {
test('translates values', () async {
when(api.getEnrolledBiometrics())
.thenAnswer((_) async => <AuthClassificationWrapper>[
AuthClassificationWrapper(value: AuthClassification.weak),
AuthClassificationWrapper(value: AuthClassification.strong),
]);
final List<BiometricType> result = await plugin.getEnrolledBiometrics();
expect(result, <BiometricType>[
BiometricType.weak,
BiometricType.strong,
]);
});
test('handles empty', () async {
when(api.getEnrolledBiometrics())
.thenAnswer((_) async => <AuthClassificationWrapper>[]);
final List<BiometricType> result = await plugin.getEnrolledBiometrics();
expect(result, <BiometricType>[]);
});
});
group('authenticate', () {
group('strings', () {
test('passes default values when nothing is provided', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.success);
const String reason = 'test reason';
await plugin.authenticate(
localizedReason: reason, authMessages: <AuthMessages>[]);
final VerificationResult result =
verify(api.authenticate(any, captureAny));
final AuthStrings strings = result.captured[0] as AuthStrings;
expect(strings.reason, reason);
// These should all be the default values from
// auth_messages_android.dart
expect(strings.biometricHint, androidBiometricHint);
expect(strings.biometricNotRecognized, androidBiometricNotRecognized);
expect(strings.biometricRequiredTitle, androidBiometricRequiredTitle);
expect(strings.cancelButton, androidCancelButton);
expect(strings.deviceCredentialsRequiredTitle,
androidDeviceCredentialsRequiredTitle);
expect(strings.deviceCredentialsSetupDescription,
androidDeviceCredentialsSetupDescription);
expect(strings.goToSettingsButton, goToSettings);
expect(strings.goToSettingsDescription, androidGoToSettingsDescription);
expect(strings.signInTitle, androidSignInTitle);
});
test('passes default values when only other platform values are provided',
() async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.success);
const String reason = 'test reason';
await plugin.authenticate(
localizedReason: reason,
authMessages: <AuthMessages>[AnotherPlatformAuthMessages()]);
final VerificationResult result =
verify(api.authenticate(any, captureAny));
final AuthStrings strings = result.captured[0] as AuthStrings;
expect(strings.reason, reason);
// These should all be the default values from
// auth_messages_android.dart
expect(strings.biometricHint, androidBiometricHint);
expect(strings.biometricNotRecognized, androidBiometricNotRecognized);
expect(strings.biometricRequiredTitle, androidBiometricRequiredTitle);
expect(strings.cancelButton, androidCancelButton);
expect(strings.deviceCredentialsRequiredTitle,
androidDeviceCredentialsRequiredTitle);
expect(strings.deviceCredentialsSetupDescription,
androidDeviceCredentialsSetupDescription);
expect(strings.goToSettingsButton, goToSettings);
expect(strings.goToSettingsDescription, androidGoToSettingsDescription);
expect(strings.signInTitle, androidSignInTitle);
});
test('passes all non-default values correctly', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.success);
// These are arbitrary values; all that matters is that:
// - they are different from the defaults, and
// - they are different from each other.
const String reason = 'A';
const String hint = 'B';
const String bioNotRecognized = 'C';
const String bioRequired = 'D';
const String cancel = 'E';
const String credentialsRequired = 'F';
const String credentialsSetup = 'G';
const String goButton = 'H';
const String goDescription = 'I';
const String signInTitle = 'J';
await plugin
.authenticate(localizedReason: reason, authMessages: <AuthMessages>[
const AndroidAuthMessages(
biometricHint: hint,
biometricNotRecognized: bioNotRecognized,
biometricRequiredTitle: bioRequired,
cancelButton: cancel,
deviceCredentialsRequiredTitle: credentialsRequired,
deviceCredentialsSetupDescription: credentialsSetup,
goToSettingsButton: goButton,
goToSettingsDescription: goDescription,
signInTitle: signInTitle,
),
AnotherPlatformAuthMessages(),
]);
final VerificationResult result =
verify(api.authenticate(any, captureAny));
final AuthStrings strings = result.captured[0] as AuthStrings;
expect(strings.reason, reason);
expect(strings.biometricHint, hint);
expect(strings.biometricNotRecognized, bioNotRecognized);
expect(strings.biometricRequiredTitle, bioRequired);
expect(strings.cancelButton, cancel);
expect(strings.deviceCredentialsRequiredTitle, credentialsRequired);
expect(strings.deviceCredentialsSetupDescription, credentialsSetup);
expect(strings.goToSettingsButton, goButton);
expect(strings.goToSettingsDescription, goDescription);
expect(strings.signInTitle, signInTitle);
});
test('passes provided messages with default fallbacks', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.success);
// These are arbitrary values; all that matters is that:
// - they are different from the defaults, and
// - they are different from each other.
const String reason = 'A';
const String hint = 'B';
const String bioNotRecognized = 'C';
const String bioRequired = 'D';
const String cancel = 'E';
await plugin
.authenticate(localizedReason: reason, authMessages: <AuthMessages>[
const AndroidAuthMessages(
biometricHint: hint,
biometricNotRecognized: bioNotRecognized,
biometricRequiredTitle: bioRequired,
cancelButton: cancel,
),
]);
final VerificationResult result =
verify(api.authenticate(any, captureAny));
final AuthStrings strings = result.captured[0] as AuthStrings;
expect(strings.reason, reason);
// These should all be the provided values.
expect(strings.biometricHint, hint);
expect(strings.biometricNotRecognized, bioNotRecognized);
expect(strings.biometricRequiredTitle, bioRequired);
expect(strings.cancelButton, cancel);
// These were non set, so should all be the default values from
// auth_messages_android.dart
expect(strings.deviceCredentialsRequiredTitle,
androidDeviceCredentialsRequiredTitle);
expect(strings.deviceCredentialsSetupDescription,
androidDeviceCredentialsSetupDescription);
expect(strings.goToSettingsButton, goToSettings);
expect(strings.goToSettingsDescription, androidGoToSettingsDescription);
expect(strings.signInTitle, androidSignInTitle);
});
});
group('options', () {
test('passes default values', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.success);
await plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]);
final VerificationResult result =
verify(api.authenticate(captureAny, any));
final AuthOptions options = result.captured[0] as AuthOptions;
expect(options.biometricOnly, false);
expect(options.sensitiveTransaction, true);
expect(options.sticky, false);
expect(options.useErrorDialgs, true);
});
test('passes provided non-default values', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.success);
await plugin.authenticate(
localizedReason: 'reason',
authMessages: <AuthMessages>[],
options: const AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: false,
stickyAuth: true,
useErrorDialogs: false,
));
final VerificationResult result =
verify(api.authenticate(captureAny, any));
final AuthOptions options = result.captured[0] as AuthOptions;
expect(options.biometricOnly, true);
expect(options.sensitiveTransaction, false);
expect(options.sticky, true);
expect(options.useErrorDialgs, false);
});
});
group('return values', () {
test('handles success', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.success);
final bool result = await plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]);
expect(result, true);
});
test('handles failure', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.failure);
final bool result = await plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]);
expect(result, false);
});
test('converts errorAlreadyInProgress to legacy PlatformException',
() async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.errorAlreadyInProgress);
expect(
() async => plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]),
throwsA(isA<PlatformException>()
.having(
(PlatformException e) => e.code, 'code', 'auth_in_progress')
.having((PlatformException e) => e.message, 'message',
'Authentication in progress')));
});
test('converts errorNoActivity to legacy PlatformException', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.errorNoActivity);
expect(
() async => plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]),
throwsA(isA<PlatformException>()
.having((PlatformException e) => e.code, 'code', 'no_activity')
.having((PlatformException e) => e.message, 'message',
'local_auth plugin requires a foreground activity')));
});
test('converts errorNotFragmentActivity to legacy PlatformException',
() async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.errorNotFragmentActivity);
expect(
() async => plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]),
throwsA(isA<PlatformException>()
.having((PlatformException e) => e.code, 'code',
'no_fragment_activity')
.having((PlatformException e) => e.message, 'message',
'local_auth plugin requires activity to be a FragmentActivity.')));
});
test('converts errorNotAvailable to legacy PlatformException', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.errorNotAvailable);
expect(
() async => plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]),
throwsA(isA<PlatformException>()
.having((PlatformException e) => e.code, 'code', 'NotAvailable')
.having((PlatformException e) => e.message, 'message',
'Security credentials not available.')));
});
test('converts errorNotEnrolled to legacy PlatformException', () async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.errorNotEnrolled);
expect(
() async => plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]),
throwsA(isA<PlatformException>()
.having((PlatformException e) => e.code, 'code', 'NotEnrolled')
.having((PlatformException e) => e.message, 'message',
'No Biometrics enrolled on this device.')));
});
test('converts errorLockedOutTemporarily to legacy PlatformException',
() async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.errorLockedOutTemporarily);
expect(
() async => plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]),
throwsA(isA<PlatformException>()
.having((PlatformException e) => e.code, 'code', 'LockedOut')
.having(
(PlatformException e) => e.message,
'message',
'The operation was canceled because the API is locked out '
'due to too many attempts. This occurs after 5 failed '
'attempts, and lasts for 30 seconds.')));
});
test('converts errorLockedOutPermanently to legacy PlatformException',
() async {
when(api.authenticate(any, any))
.thenAnswer((_) async => AuthResult.errorLockedOutPermanently);
expect(
() async => plugin.authenticate(
localizedReason: 'reason', authMessages: <AuthMessages>[]),
throwsA(isA<PlatformException>()
.having((PlatformException e) => e.code, 'code',
'PermanentlyLockedOut')
.having(
(PlatformException e) => e.message,
'message',
'The operation was canceled because ERROR_LOCKOUT occurred '
'too many times. Biometric authentication is disabled '
'until the user unlocks with strong '
'authentication (PIN/Pattern/Password)')));
});
});
});
}
class AnotherPlatformAuthMessages extends AuthMessages {
@override
Map<String, String> get args => throw UnimplementedError();
}
| packages/packages/local_auth/local_auth_android/test/local_auth_test.dart/0 | {
"file_path": "packages/packages/local_auth/local_auth_android/test/local_auth_test.dart",
"repo_id": "packages",
"token_count": 6761
} | 1,001 |
// 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:plugin_platform_interface/plugin_platform_interface.dart';
import 'default_method_channel_platform.dart';
import 'types/types.dart';
export 'package:local_auth_platform_interface/types/types.dart';
/// The interface that implementations of local_auth must implement.
///
/// Platform implementations should extend this class rather than implement it as `local_auth`
/// does not consider newly added methods to be breaking changes. Extending this class
/// (using `extends`) ensures that the subclass will get the default implementation, while
/// platform implementations that `implements` this interface will be broken by newly added
/// [LocalAuthPlatform] methods.
abstract class LocalAuthPlatform extends PlatformInterface {
/// Constructs a LocalAuthPlatform.
LocalAuthPlatform() : super(token: _token);
static final Object _token = Object();
static LocalAuthPlatform _instance = DefaultLocalAuthPlatform();
/// The default instance of [LocalAuthPlatform] to use.
///
/// Defaults to [DefaultLocalAuthPlatform].
static LocalAuthPlatform get instance => _instance;
/// Platform-specific implementations should set this with their own
/// platform-specific class that extends [LocalAuthPlatform] when they
/// register themselves.
static set instance(LocalAuthPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
/// Authenticates the user with biometrics available on the device while also
/// allowing the user to use device authentication - pin, pattern, passcode.
///
/// Returns true if the user successfully authenticated, false otherwise.
///
/// [localizedReason] is the message to show to user while prompting them
/// for authentication. This is typically along the lines of: 'Please scan
/// your finger to access MyApp.'. This must not be empty.
///
/// Provide [authMessages] if you want to
/// customize messages in the dialogs.
///
/// Provide [options] for configuring further authentication related options.
///
/// Throws a [PlatformException] if there were technical problems with local
/// authentication (e.g. lack of relevant hardware). This might throw
/// [PlatformException] with error code [otherOperatingSystem] on the iOS
/// simulator.
Future<bool> authenticate({
required String localizedReason,
required Iterable<AuthMessages> authMessages,
AuthenticationOptions options = const AuthenticationOptions(),
}) async {
throw UnimplementedError('authenticate() has not been implemented.');
}
/// Returns true if the device is capable of checking biometrics.
///
/// This will return true even if there are no biometrics currently enrolled.
Future<bool> deviceSupportsBiometrics() async {
throw UnimplementedError('canCheckBiometrics() has not been implemented.');
}
/// Returns a list of enrolled biometrics.
///
/// Possible values include:
/// - BiometricType.face
/// - BiometricType.fingerprint
/// - BiometricType.iris (not yet implemented)
/// - BiometricType.strong
/// - BiometricType.weak
Future<List<BiometricType>> getEnrolledBiometrics() async {
throw UnimplementedError(
'getAvailableBiometrics() has not been implemented.');
}
/// Returns true if device is capable of checking biometrics or is able to
/// fail over to device credentials.
Future<bool> isDeviceSupported() async {
throw UnimplementedError('isDeviceSupported() has not been implemented.');
}
/// Cancels any authentication currently in progress.
///
/// Returns true if auth was cancelled successfully.
/// Returns false if there was no authentication in progress,
/// or an error occurred.
Future<bool> stopAuthentication() async {
throw UnimplementedError('stopAuthentication() has not been implemented.');
}
}
| packages/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart/0 | {
"file_path": "packages/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart",
"repo_id": "packages",
"token_count": 1020
} | 1,002 |
// 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 "include/local_auth_windows/local_auth_plugin.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <windows.h>
#include <functional>
#include <memory>
#include <string>
#include "mocks.h"
namespace local_auth_windows {
namespace test {
using flutter::EncodableList;
using flutter::EncodableMap;
using flutter::EncodableValue;
using ::testing::_;
using ::testing::DoAll;
using ::testing::EndsWith;
using ::testing::Eq;
using ::testing::Pointee;
using ::testing::Return;
TEST(LocalAuthPlugin, IsDeviceSupportedHandlerSuccessIfVerifierAvailable) {
std::unique_ptr<MockUserConsentVerifier> mockConsentVerifier =
std::make_unique<MockUserConsentVerifier>();
EXPECT_CALL(*mockConsentVerifier, CheckAvailabilityAsync)
.Times(1)
.WillOnce([]() -> winrt::Windows::Foundation::IAsyncOperation<
winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability> {
co_return winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability::Available;
});
LocalAuthPlugin plugin(std::move(mockConsentVerifier));
ErrorOr<bool> result(false);
plugin.IsDeviceSupported([&result](ErrorOr<bool> reply) { result = reply; });
EXPECT_FALSE(result.has_error());
EXPECT_TRUE(result.value());
}
TEST(LocalAuthPlugin, IsDeviceSupportedHandlerSuccessIfVerifierNotAvailable) {
std::unique_ptr<MockUserConsentVerifier> mockConsentVerifier =
std::make_unique<MockUserConsentVerifier>();
EXPECT_CALL(*mockConsentVerifier, CheckAvailabilityAsync)
.Times(1)
.WillOnce([]() -> winrt::Windows::Foundation::IAsyncOperation<
winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability> {
co_return winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability::DeviceNotPresent;
});
LocalAuthPlugin plugin(std::move(mockConsentVerifier));
ErrorOr<bool> result(true);
plugin.IsDeviceSupported([&result](ErrorOr<bool> reply) { result = reply; });
EXPECT_FALSE(result.has_error());
EXPECT_FALSE(result.value());
}
TEST(LocalAuthPlugin, AuthenticateHandlerWorksWhenAuthorized) {
std::unique_ptr<MockUserConsentVerifier> mockConsentVerifier =
std::make_unique<MockUserConsentVerifier>();
EXPECT_CALL(*mockConsentVerifier, CheckAvailabilityAsync)
.Times(1)
.WillOnce([]() -> winrt::Windows::Foundation::IAsyncOperation<
winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability> {
co_return winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability::Available;
});
EXPECT_CALL(*mockConsentVerifier, RequestVerificationForWindowAsync)
.Times(1)
.WillOnce([](std::wstring localizedReason)
-> winrt::Windows::Foundation::IAsyncOperation<
winrt::Windows::Security::Credentials::UI::
UserConsentVerificationResult> {
EXPECT_EQ(localizedReason, L"My Reason");
co_return winrt::Windows::Security::Credentials::UI::
UserConsentVerificationResult::Verified;
});
LocalAuthPlugin plugin(std::move(mockConsentVerifier));
ErrorOr<bool> result(false);
plugin.Authenticate("My Reason",
[&result](ErrorOr<bool> reply) { result = reply; });
EXPECT_FALSE(result.has_error());
EXPECT_TRUE(result.value());
}
TEST(LocalAuthPlugin, AuthenticateHandlerWorksWhenNotAuthorized) {
std::unique_ptr<MockUserConsentVerifier> mockConsentVerifier =
std::make_unique<MockUserConsentVerifier>();
EXPECT_CALL(*mockConsentVerifier, CheckAvailabilityAsync)
.Times(1)
.WillOnce([]() -> winrt::Windows::Foundation::IAsyncOperation<
winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability> {
co_return winrt::Windows::Security::Credentials::UI::
UserConsentVerifierAvailability::Available;
});
EXPECT_CALL(*mockConsentVerifier, RequestVerificationForWindowAsync)
.Times(1)
.WillOnce([](std::wstring localizedReason)
-> winrt::Windows::Foundation::IAsyncOperation<
winrt::Windows::Security::Credentials::UI::
UserConsentVerificationResult> {
EXPECT_EQ(localizedReason, L"My Reason");
co_return winrt::Windows::Security::Credentials::UI::
UserConsentVerificationResult::Canceled;
});
LocalAuthPlugin plugin(std::move(mockConsentVerifier));
ErrorOr<bool> result(true);
plugin.Authenticate("My Reason",
[&result](ErrorOr<bool> reply) { result = reply; });
EXPECT_FALSE(result.has_error());
EXPECT_FALSE(result.value());
}
} // namespace test
} // namespace local_auth_windows
| packages/packages/local_auth/local_auth_windows/windows/test/local_auth_plugin_test.cpp/0 | {
"file_path": "packages/packages/local_auth/local_auth_windows/windows/test/local_auth_plugin_test.cpp",
"repo_id": "packages",
"token_count": 2053
} | 1,003 |
// 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:test/test.dart' hide TypeMatcher, isInstanceOf;
import 'package:test/test.dart' as test_package show TypeMatcher;
export 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
// Defines a 'package:test' shim.
// TODO(ianh): Remove this file once https://github.com/dart-lang/matcher/issues/98 is fixed
/// A matcher that compares the type of the actual value to the type argument T.
test_package.TypeMatcher<T> isInstanceOf<T>() => isA<T>();
void tryToDelete(Directory directory) {
// This should not be necessary, but it turns out that
// on Windows it's common for deletions to fail due to
// bogus (we think) "access denied" errors.
try {
directory.deleteSync(recursive: true);
} on FileSystemException catch (error) {
// TODO(goderbauer): We should not be printing from a test util function.
// ignore: avoid_print
print('Failed to delete ${directory.path}: $error');
}
}
| packages/packages/metrics_center/test/common.dart/0 | {
"file_path": "packages/packages/metrics_center/test/common.dart",
"repo_id": "packages",
"token_count": 346
} | 1,004 |
// 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.
// Example script to illustrate how to use the mdns package to discover services
// on the local network.
// ignore_for_file: avoid_print
import 'package:multicast_dns/multicast_dns.dart';
Future<void> main(List<String> args) async {
if (args.isEmpty) {
print('''
Please provide the name of a service as argument.
For example:
dart mdns_sd.dart [--verbose] _workstation._tcp.local''');
return;
}
final bool verbose = args.contains('--verbose') || args.contains('-v');
final String name = args.last;
final MDnsClient client = MDnsClient();
await client.start();
await for (final PtrResourceRecord ptr in client
.lookup<PtrResourceRecord>(ResourceRecordQuery.serverPointer(name))) {
if (verbose) {
print(ptr);
}
await for (final SrvResourceRecord srv in client.lookup<SrvResourceRecord>(
ResourceRecordQuery.service(ptr.domainName))) {
if (verbose) {
print(srv);
}
if (verbose) {
await client
.lookup<TxtResourceRecord>(ResourceRecordQuery.text(ptr.domainName))
.forEach(print);
}
await for (final IPAddressResourceRecord ip
in client.lookup<IPAddressResourceRecord>(
ResourceRecordQuery.addressIPv4(srv.target))) {
if (verbose) {
print(ip);
}
print('Service instance found at '
'${srv.target}:${srv.port} with ${ip.address}.');
}
await for (final IPAddressResourceRecord ip
in client.lookup<IPAddressResourceRecord>(
ResourceRecordQuery.addressIPv6(srv.target))) {
if (verbose) {
print(ip);
}
print('Service instance found at '
'${srv.target}:${srv.port} with ${ip.address}.');
}
}
}
client.stop();
}
| packages/packages/multicast_dns/example/mdns_sd.dart/0 | {
"file_path": "packages/packages/multicast_dns/example/mdns_sd.dart",
"repo_id": "packages",
"token_count": 790
} | 1,005 |
# Palette Generator package
[](https://pub.dartlang.org/packages/palette_generator)
A Flutter package to extract prominent colors from an Image, typically used to
find colors for a user interface.
## Usage
To use this package, add `palette_generator` as a
[dependency in your pubspec.yaml file](https://flutter.io/platform-plugins/).
## Example
Import the library via
```dart
import 'package:palette_generator/palette_generator.dart';
```
Then use the `PaletteGenerator` Dart class in your code. To see how this is done,
check out the [image_colors example app](example/).
| packages/packages/palette_generator/README.md/0 | {
"file_path": "packages/packages/palette_generator/README.md",
"repo_id": "packages",
"token_count": 204
} | 1,006 |
#include "ephemeral/Flutter-Generated.xcconfig"
| packages/packages/palette_generator/example/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "packages/packages/palette_generator/example/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "packages",
"token_count": 19
} | 1,007 |
// 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:typed_data';
// This file contains base64-ecoded versions of the images in assets/, so that
// unit tests can be run on web where loading from files isn't an option and
// loading from assets requires user action.
/// Data version of assets/dominant.png.
final Uint8List kImageDataDominant = base64.decode(
'iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAA'
'AAqElEQVR42u3WoQ0AIAxFwV/C/ivDBmAgIO7ZpuZS0RpZVetx7i3/WItgwYIFCxYswYL1uF7Z'
'/PCMXBYsWLBgwRIsWLD+qZJBwWXBggULFizBggULFixYggULFixYsAQLFixYsGAJFixYsGDBEi'
'xYsGDBgiVYsGDBggVLsGDBggULlmDBggULFizBggULFixYggULFixYsAQLFixYsGAJFixYsGDB'
'EqzzTawXBchMuogIAAAAAElFTkSuQmCC');
/// Data version of assets/tall_blue.png.
final Uint8List kImageDataTallBlue = base64.decode(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAPoCAIAAACQ1AMJAAAACXBIWXMAAAsTAAALEwEAmpwYAA'
'AAH0lEQVRIx+3DQQkAAAgAscP+nTWGnw1W7VSqqqrq3wOa1wjO6jYVpgAAAABJRU5ErkJggg='
'=');
/// Data version of assets/wide_red.png.
final Uint8List kImageDataWideRed = base64.decode(
'iVBORw0KGgoAAAANSUhEUgAAA+gAAAABCAIAAADCYhNkAAAACXBIWXMAA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images.dart/0 | {
"file_path": "packages/packages/palette_generator/test/encoded_images.dart",
"repo_id": "packages",
"token_count": 83397
} | 1,008 |
// 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 Directory;
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
const String kTemporaryPath = 'temporaryPath';
const String kApplicationSupportPath = 'applicationSupportPath';
const String kDownloadsPath = 'downloadsPath';
const String kLibraryPath = 'libraryPath';
const String kApplicationDocumentsPath = 'applicationDocumentsPath';
const String kExternalCachePath = 'externalCachePath';
const String kExternalStoragePath = 'externalStoragePath';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('PathProvider full implementation', () {
setUp(() async {
PathProviderPlatform.instance = FakePathProviderPlatform();
});
test('getTemporaryDirectory', () async {
final Directory result = await getTemporaryDirectory();
expect(result.path, kTemporaryPath);
});
test('getApplicationSupportDirectory', () async {
final Directory result = await getApplicationSupportDirectory();
expect(result.path, kApplicationSupportPath);
});
test('getLibraryDirectory', () async {
final Directory result = await getLibraryDirectory();
expect(result.path, kLibraryPath);
});
test('getApplicationDocumentsDirectory', () async {
final Directory result = await getApplicationDocumentsDirectory();
expect(result.path, kApplicationDocumentsPath);
});
test('getExternalStorageDirectory', () async {
final Directory? result = await getExternalStorageDirectory();
expect(result?.path, kExternalStoragePath);
});
test('getExternalCacheDirectories', () async {
final List<Directory>? result = await getExternalCacheDirectories();
expect(result?.length, 1);
expect(result?.first.path, kExternalCachePath);
});
test('getExternalStorageDirectories', () async {
final List<Directory>? result = await getExternalStorageDirectories();
expect(result?.length, 1);
expect(result?.first.path, kExternalStoragePath);
});
test('getDownloadsDirectory', () async {
final Directory? result = await getDownloadsDirectory();
expect(result?.path, kDownloadsPath);
});
});
group('PathProvider null implementation', () {
setUp(() async {
PathProviderPlatform.instance = AllNullFakePathProviderPlatform();
});
test('getTemporaryDirectory throws on null', () async {
expect(getTemporaryDirectory(),
throwsA(isA<MissingPlatformDirectoryException>()));
});
test('getApplicationSupportDirectory throws on null', () async {
expect(getApplicationSupportDirectory(),
throwsA(isA<MissingPlatformDirectoryException>()));
});
test('getLibraryDirectory throws on null', () async {
expect(getLibraryDirectory(),
throwsA(isA<MissingPlatformDirectoryException>()));
});
test('getApplicationDocumentsDirectory throws on null', () async {
expect(getApplicationDocumentsDirectory(),
throwsA(isA<MissingPlatformDirectoryException>()));
});
test('getExternalStorageDirectory passes null through', () async {
final Directory? result = await getExternalStorageDirectory();
expect(result, isNull);
});
test('getExternalCacheDirectories passes null through', () async {
final List<Directory>? result = await getExternalCacheDirectories();
expect(result, isNull);
});
test('getExternalStorageDirectories passes null through', () async {
final List<Directory>? result = await getExternalStorageDirectories();
expect(result, isNull);
});
test('getDownloadsDirectory passses null through', () async {
final Directory? result = await getDownloadsDirectory();
expect(result, isNull);
});
});
}
class FakePathProviderPlatform extends Fake
with MockPlatformInterfaceMixin
implements PathProviderPlatform {
@override
Future<String?> getTemporaryPath() async {
return kTemporaryPath;
}
@override
Future<String?> getApplicationSupportPath() async {
return kApplicationSupportPath;
}
@override
Future<String?> getLibraryPath() async {
return kLibraryPath;
}
@override
Future<String?> getApplicationDocumentsPath() async {
return kApplicationDocumentsPath;
}
@override
Future<String?> getExternalStoragePath() async {
return kExternalStoragePath;
}
@override
Future<List<String>?> getExternalCachePaths() async {
return <String>[kExternalCachePath];
}
@override
Future<List<String>?> getExternalStoragePaths({
StorageDirectory? type,
}) async {
return <String>[kExternalStoragePath];
}
@override
Future<String?> getDownloadsPath() async {
return kDownloadsPath;
}
}
class AllNullFakePathProviderPlatform extends Fake
with MockPlatformInterfaceMixin
implements PathProviderPlatform {
@override
Future<String?> getTemporaryPath() async {
return null;
}
@override
Future<String?> getApplicationSupportPath() async {
return null;
}
@override
Future<String?> getLibraryPath() async {
return null;
}
@override
Future<String?> getApplicationDocumentsPath() async {
return null;
}
@override
Future<String?> getExternalStoragePath() async {
return null;
}
@override
Future<List<String>?> getExternalCachePaths() async {
return null;
}
@override
Future<List<String>?> getExternalStoragePaths({
StorageDirectory? type,
}) async {
return null;
}
@override
Future<String?> getDownloadsPath() async {
return null;
}
}
| packages/packages/path_provider/path_provider/test/path_provider_test.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider/test/path_provider_test.dart",
"repo_id": "packages",
"token_count": 1850
} | 1,009 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'path_provider_foundation'
s.version = '0.0.1'
s.summary = 'An iOS and macOS implementation of the path_provider plugin.'
s.description = <<-DESC
An iOS and macOS implementation of the Flutter plugin for getting commonly used locations on the filesystem.
DESC
s.homepage = 'https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_foundation'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Dev Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_foundation' }
s.source_files = 'Classes/**/*'
s.ios.dependency 'Flutter'
s.osx.dependency 'FlutterMacOS'
s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14'
s.ios.xcconfig = {
'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift',
'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift',
}
s.swift_version = '5.0'
s.resource_bundles = {'path_provider_foundation_privacy' => ['Resources/PrivacyInfo.xcprivacy']}
end
| packages/packages/path_provider/path_provider_foundation/darwin/path_provider_foundation.podspec/0 | {
"file_path": "packages/packages/path_provider/path_provider_foundation/darwin/path_provider_foundation.podspec",
"repo_id": "packages",
"token_count": 569
} | 1,010 |
# Pigeon
Pigeon is a code generator tool to make communication between Flutter and the
host platform type-safe, easier, and faster.
Pigeon removes the necessity to manage strings across multiple platforms and languages.
It also improves efficiency over common method channel patterns. Most importantly though,
it removes the need to write custom platform channel code, since pigeon generates it for you.
For usage examples, see the [Example README](./example/README.md).
## Features
### Supported Platforms
Currently pigeon supports generating:
* Kotlin and Java code for Android
* Swift and Objective-C code for iOS and macOS
* C++ code for Windows
### Supported Datatypes
Pigeon uses the `StandardMessageCodec` so it supports
[any datatype platform channels support](https://flutter.dev/docs/development/platform-integration/platform-channels#codec).
Custom classes, nested datatypes, and enums are also supported.
Nullable enums in Objective-C generated code will be wrapped in a class to allow for nullability.
### Synchronous and Asynchronous methods
While all calls across platform channel APIs (such as pigeon methods) are asynchronous,
pigeon methods can be written on the native side as synchronous methods,
to make it simpler to always reply exactly once.
If asynchronous methods are needed, the `@async` annotation can be used. This will require
results or errors to be returned via a provided callback. [Example](./example/README.md#HostApi_Example).
### Error Handling
#### Kotlin, Java and Swift
All Host API exceptions are translated into Flutter `PlatformException`.
* For synchronous methods, thrown exceptions will be caught and translated.
* For asynchronous methods, there is no default exception handling; errors
should be returned via the provided callback.
To pass custom details into `PlatformException` for error handling,
use `FlutterError` in your Host API. [Example](./example/README.md#HostApi_Example).
To use `FlutterError` in Swift you must first extend a standard error.
[Example](./example/README.md#AppDelegate.swift).
#### Objective-C and C++
Host API errors can be sent using the provided `FlutterError` class (translated into `PlatformException`).
For synchronous methods:
* Objective-C - Set the `error` argument to a `FlutterError` reference.
* C++ - Return a `FlutterError`.
For async methods:
* Return a `FlutterError` through the provided callback.
### Task Queue
When targeting a Flutter version that supports the
[TaskQueue API](https://docs.flutter.dev/development/platform-integration/platform-channels?tab=type-mappings-kotlin-tab#channels-and-platform-threading)
the threading model for handling HostApi methods can be selected with the
`TaskQueue` annotation.
## Usage
1) Add pigeon as a `dev_dependency`.
1) Make a ".dart" file outside of your "lib" directory for defining the
communication interface.
1) Run pigeon on your ".dart" file to generate the required Dart and
host-language code: `flutter pub get` then `flutter pub run pigeon`
with suitable arguments. [Example](./example/README.md#Invocation).
1) Add the generated Dart code to `./lib` for compilation.
1) Implement the host-language code and add it to your build (see below).
1) Call the generated Dart methods.
### Rules for defining your communication interface
[Example](./example/README.md#HostApi_Example)
1) The file should contain no method or function definitions, only declarations.
1) Custom classes used by APIs are defined as classes with fields of the
supported datatypes (see the supported Datatypes section).
1) APIs should be defined as an `abstract class` with either `@HostApi()` or
`@FlutterApi()` as metadata. `@HostApi()` being for procedures that are defined
on the host platform and the `@FlutterApi()` for procedures that are defined in Dart.
1) Method declarations on the API classes should have arguments and a return
value whose types are defined in the file, are supported datatypes, or are
`void`.
1) Generics are supported, but can currently only be used with nullable types
(example: `List<int?>`).
1) Objc and Swift have special naming conventions that can be utilized with the
`@ObjCSelector` and `@SwiftFunction` respectively.
### Flutter calling into iOS steps
1) Add the generated Objective-C or Swift code to your Xcode project for compilation
(e.g. `ios/Runner.xcworkspace` or `.podspec`).
1) Implement the generated protocol for handling the calls on iOS, set it up
as the handler for the messages.
### Flutter calling into Android Steps
1) Add the generated Java or Kotlin code to your `./android/app/src/main/java` directory
for compilation.
1) Implement the generated Java or Kotlin interface for handling the calls on Android, set
it up as the handler for the messages.
### Flutter calling into Windows Steps
1) Add the generated C++ code to your `./windows` directory for compilation, and
to your `windows/CMakeLists.txt` file.
1) Implement the generated C++ abstract class for handling the calls on Windows,
set it up as the handler for the messages.
### Flutter calling into macOS steps
1) Add the generated Objective-C or Swift code to your Xcode project for compilation
(e.g. `macos/Runner.xcworkspace` or `.podspec`).
1) Implement the generated protocol for handling the calls on macOS, set it up
as the handler for the messages.
### Calling into Flutter from the host platform
Pigeon also supports calling in the opposite direction. The steps are similar
but reversed. For more information look at the annotation `@FlutterApi()` which
denotes APIs that live in Flutter but are invoked from the host platform.
[Example](./example/README.md#FlutterApi_Example).
## Feedback
File an issue in [flutter/flutter](https://github.com/flutter/flutter) with
"[pigeon]" at the start of the title.
| packages/packages/pigeon/README.md/0 | {
"file_path": "packages/packages/pigeon/README.md",
"repo_id": "packages",
"token_count": 1549
} | 1,011 |
// 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
// #docregion swift-class
// This extension of Error is required to do use FlutterError in any Swift code.
extension FlutterError: Error {}
private class PigeonApiImplementation: ExampleHostApi {
func getHostLanguage() throws -> String {
return "Swift"
}
func add(_ a: Int64, to b: Int64) throws -> Int64 {
if a < 0 || b < 0 {
throw FlutterError(code: "code", message: "message", details: "details")
}
return a + b
}
func sendMessage(message: MessageData, completion: @escaping (Result<Bool, Error>) -> Void) {
if message.code == Code.one {
completion(.failure(FlutterError(code: "code", message: "message", details: "details")))
return
}
completion(.success(true))
}
}
// #enddocregion swift-class
// #docregion swift-class-flutter
private class PigeonFlutterApi {
var flutterAPI: MessageFlutterApi
init(binaryMessenger: FlutterBinaryMessenger) {
flutterAPI = MessageFlutterApi(binaryMessenger: binaryMessenger)
}
func callFlutterMethod(
aString aStringArg: String?, completion: @escaping (Result<String, Error>) -> Void
) {
flutterAPI.flutterMethod(aString: aStringArg) {
completion(.success($0))
}
}
}
// #enddocregion swift-class-flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let controller = window?.rootViewController as! FlutterViewController
let api = PigeonApiImplementation()
ExampleHostApiSetup.setUp(binaryMessenger: controller.binaryMessenger, api: api)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
| packages/packages/pigeon/example/app/ios/Runner/AppDelegate.swift/0 | {
"file_path": "packages/packages/pigeon/example/app/ios/Runner/AppDelegate.swift",
"repo_id": "packages",
"token_count": 660
} | 1,012 |
// 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';
/// Documentation comment open symbol.
const String _docCommentPrefix = '///';
/// Documentation comment spec.
const DocumentCommentSpecification _docCommentSpec =
DocumentCommentSpecification(_docCommentPrefix);
/// Options that control how Swift code will be generated.
class SwiftOptions {
/// Creates a [SwiftOptions] object
const SwiftOptions({
this.copyrightHeader,
});
/// A copyright header that will get prepended to generated code.
final Iterable<String>? copyrightHeader;
/// Creates a [SwiftOptions] from a Map representation where:
/// `x = SwiftOptions.fromList(x.toMap())`.
static SwiftOptions fromList(Map<String, Object> map) {
return SwiftOptions(
copyrightHeader: map['copyrightHeader'] as Iterable<String>?,
);
}
/// Converts a [SwiftOptions] to a Map representation where:
/// `x = SwiftOptions.fromList(x.toMap())`.
Map<String, Object> toMap() {
final Map<String, Object> result = <String, Object>{
if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!,
};
return result;
}
/// Overrides any non-null parameters from [options] into this to make a new
/// [SwiftOptions].
SwiftOptions merge(SwiftOptions options) {
return SwiftOptions.fromList(mergeMaps(toMap(), options.toMap()));
}
}
/// Class that manages all Swift code generation.
class SwiftGenerator extends StructuredGenerator<SwiftOptions> {
/// Instantiates a Swift Generator.
const SwiftGenerator();
@override
void writeFilePrologue(
SwiftOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
if (generatorOptions.copyrightHeader != null) {
addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// ');
}
indent.writeln('// ${getGeneratedCodeWarning()}');
indent.writeln('// $seeAlsoWarning');
indent.newln();
}
@override
void writeFileImports(
SwiftOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
indent.writeln('import Foundation');
indent.newln();
indent.format('''
#if os(iOS)
import Flutter
#elseif os(macOS)
import FlutterMacOS
#else
#error("Unsupported platform.")
#endif''');
}
@override
void writeEnum(
SwiftOptions generatorOptions,
Root root,
Indent indent,
Enum anEnum, {
required String dartPackageName,
}) {
indent.newln();
addDocumentationComments(
indent, anEnum.documentationComments, _docCommentSpec);
indent.write('enum ${anEnum.name}: Int ');
indent.addScoped('{', '}', () {
enumerate(anEnum.members, (int index, final EnumMember member) {
addDocumentationComments(
indent, member.documentationComments, _docCommentSpec);
indent.writeln('case ${_camelCase(member.name)} = $index');
});
});
}
@override
void writeDataClass(
SwiftOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
const List<String> generatedComments = <String>[
' Generated class from Pigeon that represents data sent in messages.'
];
indent.newln();
addDocumentationComments(
indent, classDefinition.documentationComments, _docCommentSpec,
generatorComments: generatedComments);
indent.write('struct ${classDefinition.name} ');
indent.addScoped('{', '}', () {
getFieldsInSerializationOrder(classDefinition).forEach((NamedType field) {
_writeClassField(indent, field);
});
indent.newln();
writeClassDecode(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
writeClassEncode(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
});
}
@override
void writeClassEncode(
SwiftOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
indent.write('func toList() -> [Any?] ');
indent.addScoped('{', '}', () {
indent.write('return ');
indent.addScoped('[', ']', () {
// Follow swift-format style, which is to use a trailing comma unless
// there is only one element.
final String separator = classDefinition.fields.length > 1 ? ',' : '';
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
String toWriteValue = '';
final String fieldName = field.name;
final String nullsafe = field.type.isNullable ? '?' : '';
if (field.type.isClass) {
toWriteValue = '$fieldName$nullsafe.toList()';
} else if (field.type.isEnum) {
toWriteValue = '$fieldName$nullsafe.rawValue';
} else {
toWriteValue = field.name;
}
indent.writeln('$toWriteValue$separator');
}
});
});
}
@override
void writeClassDecode(
SwiftOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
final String className = classDefinition.name;
indent.write('static func fromList(_ list: [Any?]) -> $className? ');
indent.addScoped('{', '}', () {
enumerate(getFieldsInSerializationOrder(classDefinition),
(int index, final NamedType field) {
final String listValue = 'list[$index]';
_writeDecodeCasting(
indent: indent,
value: listValue,
variableName: field.name,
type: field.type,
);
});
indent.newln();
indent.write('return ');
indent.addScoped('$className(', ')', () {
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
final String comma =
getFieldsInSerializationOrder(classDefinition).last == field
? ''
: ',';
indent.writeln('${field.name}: ${field.name}$comma');
}
});
});
}
void _writeClassField(Indent indent, NamedType field) {
addDocumentationComments(
indent, field.documentationComments, _docCommentSpec);
indent.write(
'var ${field.name}: ${_nullsafeSwiftTypeForDartType(field.type)}');
final String defaultNil = field.type.isNullable ? ' = nil' : '';
indent.addln(defaultNil);
}
@override
void writeApis(
SwiftOptions 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 let binaryMessenger: FlutterBinaryMessenger
/// init(binaryMessenger: FlutterBinaryMessenger) {...}
/// func add(x: Int32, y: Int32, completion: @escaping (Int32?) -> Void) {...}
/// }
@override
void writeFlutterApi(
SwiftOptions 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> generatedComments = <String>[
' Generated protocol from Pigeon that represents Flutter messages that can be called from Swift.'
];
addDocumentationComments(indent, api.documentationComments, _docCommentSpec,
generatorComments: generatedComments);
indent.addScoped('protocol ${api.name}Protocol {', '}', () {
for (final Method func in api.methods) {
addDocumentationComments(
indent, func.documentationComments, _docCommentSpec);
indent.writeln(_getMethodSignature(
name: func.name,
parameters: func.parameters,
returnType: func.returnType,
errorTypeName: 'FlutterError',
isAsynchronous: true,
swiftFunction: func.swiftFunction,
getParameterName: _getSafeArgumentName,
));
}
});
indent.write('class ${api.name}: ${api.name}Protocol ');
indent.addScoped('{', '}', () {
indent.writeln('private let binaryMessenger: FlutterBinaryMessenger');
indent.write('init(binaryMessenger: FlutterBinaryMessenger) ');
indent.addScoped('{', '}', () {
indent.writeln('self.binaryMessenger = binaryMessenger');
});
final String codecName = _getCodecName(api);
String codecArgumentString = '';
if (getCodecClasses(api, root).isNotEmpty) {
codecArgumentString = ', codec: codec';
indent.write('var codec: FlutterStandardMessageCodec ');
indent.addScoped('{', '}', () {
indent.writeln('return $codecName.shared');
});
}
for (final Method func in api.methods) {
addDocumentationComments(
indent, func.documentationComments, _docCommentSpec);
_writeFlutterMethod(
indent,
name: func.name,
channelName: makeChannelName(api, func, dartPackageName),
parameters: func.parameters,
returnType: func.returnType,
codecArgumentString: codecArgumentString,
swiftFunction: func.swiftFunction,
);
}
});
}
/// Write the swift code that represents a host [Api], [api].
/// Example:
/// protocol Foo {
/// Int32 add(x: Int32, y: Int32)
/// }
@override
void writeHostApi(
SwiftOptions 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> generatedComments = <String>[
' Generated protocol from Pigeon that represents a handler of messages from Flutter.'
];
addDocumentationComments(indent, api.documentationComments, _docCommentSpec,
generatorComments: generatedComments);
indent.write('protocol $apiName ');
indent.addScoped('{', '}', () {
for (final Method method in api.methods) {
addDocumentationComments(
indent, method.documentationComments, _docCommentSpec);
indent.writeln(_getMethodSignature(
name: method.name,
parameters: method.parameters,
returnType: method.returnType,
errorTypeName: 'Error',
isAsynchronous: method.isAsynchronous,
swiftFunction: method.swiftFunction,
));
}
});
indent.newln();
indent.writeln(
'$_docCommentPrefix Generated setup class from Pigeon to handle messages through the `binaryMessenger`.');
indent.write('class ${apiName}Setup ');
indent.addScoped('{', '}', () {
final String codecName = _getCodecName(api);
indent.writeln('$_docCommentPrefix The codec used by $apiName.');
String codecArgumentString = '';
if (getCodecClasses(api, root).isNotEmpty) {
codecArgumentString = ', codec: codec';
indent.writeln(
'static var codec: FlutterStandardMessageCodec { $codecName.shared }');
}
indent.writeln(
'$_docCommentPrefix Sets up an instance of `$apiName` to handle messages through the `binaryMessenger`.');
indent.write(
'static func setUp(binaryMessenger: FlutterBinaryMessenger, api: $apiName?) ');
indent.addScoped('{', '}', () {
for (final Method method in api.methods) {
_writeHostMethodMessageHandler(
indent,
name: method.name,
channelName: makeChannelName(api, method, dartPackageName),
parameters: method.parameters,
returnType: method.returnType,
isAsynchronous: method.isAsynchronous,
codecArgumentString: codecArgumentString,
swiftFunction: method.swiftFunction,
documentationComments: method.documentationComments,
);
}
});
});
}
/// Writes the codec class will be used for encoding messages for the [api].
/// Example:
/// private class FooHostApiCodecReader: FlutterStandardReader {...}
/// private class FooHostApiCodecWriter: FlutterStandardWriter {...}
/// private class FooHostApiCodecReaderWriter: FlutterStandardReaderWriter {...}
void _writeCodec(Indent indent, Api api, Root root) {
assert(getCodecClasses(api, root).isNotEmpty);
final String codecName = _getCodecName(api);
final String readerWriterName = '${codecName}ReaderWriter';
final String readerName = '${codecName}Reader';
final String writerName = '${codecName}Writer';
// Generate Reader
indent.write('private class $readerName: FlutterStandardReader ');
indent.addScoped('{', '}', () {
if (getCodecClasses(api, root).isNotEmpty) {
indent.write('override func readValue(ofType type: UInt8) -> Any? ');
indent.addScoped('{', '}', () {
indent.write('switch type ');
indent.addScoped('{', '}', nestCount: 0, () {
for (final EnumeratedClass customClass
in getCodecClasses(api, root)) {
indent.writeln('case ${customClass.enumeration}:');
indent.nest(1, () {
indent.writeln(
'return ${customClass.name}.fromList(self.readValue() as! [Any?])');
});
}
indent.writeln('default:');
indent.nest(1, () {
indent.writeln('return super.readValue(ofType: type)');
});
});
});
}
});
// Generate Writer
indent.newln();
indent.write('private class $writerName: FlutterStandardWriter ');
indent.addScoped('{', '}', () {
if (getCodecClasses(api, root).isNotEmpty) {
indent.write('override func writeValue(_ value: Any) ');
indent.addScoped('{', '}', () {
indent.write('');
for (final EnumeratedClass customClass
in getCodecClasses(api, root)) {
indent.add('if let value = value as? ${customClass.name} ');
indent.addScoped('{', '} else ', () {
indent.writeln('super.writeByte(${customClass.enumeration})');
indent.writeln('super.writeValue(value.toList())');
}, addTrailingNewline: false);
}
indent.addScoped('{', '}', () {
indent.writeln('super.writeValue(value)');
});
});
}
});
indent.newln();
// Generate ReaderWriter
indent
.write('private class $readerWriterName: FlutterStandardReaderWriter ');
indent.addScoped('{', '}', () {
indent.write(
'override func reader(with data: Data) -> FlutterStandardReader ');
indent.addScoped('{', '}', () {
indent.writeln('return $readerName(data: data)');
});
indent.newln();
indent.write(
'override func writer(with data: NSMutableData) -> FlutterStandardWriter ');
indent.addScoped('{', '}', () {
indent.writeln('return $writerName(data: data)');
});
});
indent.newln();
// Generate Codec
indent.write('class $codecName: FlutterStandardMessageCodec ');
indent.addScoped('{', '}', () {
indent.writeln(
'static let shared = $codecName(readerWriter: $readerWriterName())');
});
indent.newln();
}
String _castForceUnwrap(String value, TypeDeclaration type) {
assert(!type.isVoid);
if (type.isEnum) {
String output =
'${_swiftTypeForDartType(type)}(rawValue: $value as! Int)!';
if (type.isNullable) {
output = 'isNullish($value) ? nil : $output';
}
return output;
} else if (type.baseName == 'Object') {
return value + (type.isNullable ? '' : '!');
} else if (type.baseName == 'int') {
if (type.isNullable) {
// Nullable ints need to check for NSNull, and Int32 before casting can be done safely.
// This nested ternary is a necessary evil to avoid less efficient conversions.
return 'isNullish($value) ? nil : ($value is Int64? ? $value as! Int64? : Int64($value as! Int32))';
} else {
return '$value is Int64 ? $value as! Int64 : Int64($value as! Int32)';
}
} else if (type.isNullable) {
return 'nilOrValue($value)';
} else {
return '$value as! ${_swiftTypeForDartType(type)}';
}
}
void _writeGenericCasting({
required Indent indent,
required String value,
required String variableName,
required String fieldType,
required TypeDeclaration type,
}) {
if (type.isNullable) {
indent.writeln(
'let $variableName: $fieldType? = ${_castForceUnwrap(value, type)}');
} else {
indent.writeln('let $variableName = ${_castForceUnwrap(value, type)}');
}
}
/// Writes decode and casting code for any type.
///
/// Optional parameters should only be used for class decoding.
void _writeDecodeCasting({
required Indent indent,
required String value,
required String variableName,
required TypeDeclaration type,
}) {
final String fieldType = _swiftTypeForDartType(type);
if (type.isNullable) {
if (type.isClass) {
indent.writeln('var $variableName: $fieldType? = nil');
indent
.write('if let ${variableName}List: [Any?] = nilOrValue($value) ');
indent.addScoped('{', '}', () {
indent.writeln(
'$variableName = $fieldType.fromList(${variableName}List)');
});
} else if (type.isEnum) {
indent.writeln('var $variableName: $fieldType? = nil');
indent.writeln(
'let ${variableName}EnumVal: Int? = ${_castForceUnwrap(value, const TypeDeclaration(baseName: 'Int', isNullable: true))}');
indent
.write('if let ${variableName}RawValue = ${variableName}EnumVal ');
indent.addScoped('{', '}', () {
indent.writeln(
'$variableName = $fieldType(rawValue: ${variableName}RawValue)!');
});
} else {
_writeGenericCasting(
indent: indent,
value: value,
variableName: variableName,
fieldType: fieldType,
type: type,
);
}
} else {
if (type.isClass) {
indent.writeln(
'let $variableName = $fieldType.fromList($value as! [Any?])!');
} else {
_writeGenericCasting(
indent: indent,
value: value,
variableName: variableName,
fieldType: fieldType,
type: type,
);
}
}
}
void _writeIsNullish(Indent indent) {
indent.newln();
indent.write('private func isNullish(_ value: Any?) -> Bool ');
indent.addScoped('{', '}', () {
indent.writeln('return value is NSNull || value == nil');
});
}
void _writeWrapResult(Indent indent) {
indent.newln();
indent.write('private func wrapResult(_ result: Any?) -> [Any?] ');
indent.addScoped('{', '}', () {
indent.writeln('return [result]');
});
}
void _writeWrapError(Indent indent) {
indent.newln();
indent.write('private func wrapError(_ error: Any) -> [Any?] ');
indent.addScoped('{', '}', () {
indent.write('if let flutterError = error as? FlutterError ');
indent.addScoped('{', '}', () {
indent.write('return ');
indent.addScoped('[', ']', () {
indent.writeln('flutterError.code,');
indent.writeln('flutterError.message,');
indent.writeln('flutterError.details,');
});
});
indent.write('return ');
indent.addScoped('[', ']', () {
indent.writeln(r'"\(error)",');
indent.writeln(r'"\(type(of: error))",');
indent.writeln(r'"Stacktrace: \(Thread.callStackSymbols)",');
});
});
}
void _writeNilOrValue(Indent indent) {
indent.format('''
private func nilOrValue<T>(_ value: Any?) -> T? {
if value is NSNull { return nil }
return value as! T?
}''');
}
void _writeCreateConnectionError(Indent indent) {
indent.newln();
indent.writeScoped(
'private func createConnectionError(withChannelName channelName: String) -> FlutterError {',
'}', () {
indent.writeln(
'return FlutterError(code: "channel-error", message: "Unable to establish connection on channel: \'\\(channelName)\'.", details: "")');
});
}
@override
void writeGeneralUtilities(
SwiftOptions 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(indent);
}
if (hasFlutterApi) {
_writeCreateConnectionError(indent);
}
_writeIsNullish(indent);
_writeNilOrValue(indent);
}
void _writeFlutterMethod(
Indent indent, {
required String name,
required String channelName,
required List<Parameter> parameters,
required TypeDeclaration returnType,
required String codecArgumentString,
required String? swiftFunction,
}) {
final String methodSignature = _getMethodSignature(
name: name,
parameters: parameters,
returnType: returnType,
errorTypeName: 'FlutterError',
isAsynchronous: true,
swiftFunction: swiftFunction,
getParameterName: _getSafeArgumentName,
);
/// Returns an argument name that can be used in a context where it is possible to collide.
String getEnumSafeArgumentExpression(int count, NamedType argument) {
String enumTag = '';
if (argument.type.isEnum) {
enumTag = argument.type.isNullable ? '?.rawValue' : '.rawValue';
}
return '${_getArgumentName(count, argument)}Arg$enumTag';
}
indent.writeScoped('$methodSignature {', '}', () {
final Iterable<String> enumSafeArgNames = parameters.asMap().entries.map(
(MapEntry<int, NamedType> e) =>
getEnumSafeArgumentExpression(e.key, e.value));
final String sendArgument = parameters.isEmpty
? 'nil'
: '[${enumSafeArgNames.join(', ')}] as [Any?]';
const String channel = 'channel';
indent.writeln('let channelName: String = "$channelName"');
indent.writeln(
'let $channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger$codecArgumentString)');
indent.write('$channel.sendMessage($sendArgument) ');
indent.addScoped('{ response in', '}', () {
indent.writeScoped(
'guard let listResponse = response as? [Any?] else {', '}', () {
indent.writeln(
'completion(.failure(createConnectionError(withChannelName: channelName)))');
indent.writeln('return');
});
indent.writeScoped('if listResponse.count > 1 {', '} ', () {
indent.writeln('let code: String = listResponse[0] as! String');
indent.writeln('let message: String? = nilOrValue(listResponse[1])');
indent.writeln('let details: String? = nilOrValue(listResponse[2])');
indent.writeln(
'completion(.failure(FlutterError(code: code, message: message, details: details)))');
}, addTrailingNewline: false);
if (!returnType.isNullable && !returnType.isVoid) {
indent.addScoped('else if listResponse[0] == nil {', '} ', () {
indent.writeln(
'completion(.failure(FlutterError(code: "null-error", message: "Flutter api returned null value for non-null return value.", details: "")))');
}, addTrailingNewline: false);
}
indent.addScoped('else {', '}', () {
if (returnType.isVoid) {
indent.writeln('completion(.success(Void()))');
} else {
final String fieldType = _swiftTypeForDartType(returnType);
_writeGenericCasting(
indent: indent,
value: 'listResponse[0]',
variableName: 'result',
fieldType: fieldType,
type: returnType,
);
indent.writeln('completion(.success(result))');
}
});
});
});
}
void _writeHostMethodMessageHandler(
Indent indent, {
required String name,
required String channelName,
required Iterable<Parameter> parameters,
required TypeDeclaration returnType,
required bool isAsynchronous,
required String codecArgumentString,
required String? swiftFunction,
List<String> documentationComments = const <String>[],
}) {
final _SwiftFunctionComponents components = _SwiftFunctionComponents(
name: name,
parameters: parameters,
returnType: returnType,
swiftFunction: swiftFunction,
);
final String varChannelName = '${name}Channel';
addDocumentationComments(indent, documentationComments, _docCommentSpec);
indent.writeln(
'let $varChannelName = FlutterBasicMessageChannel(name: "$channelName", binaryMessenger: binaryMessenger$codecArgumentString)');
indent.write('if let api = api ');
indent.addScoped('{', '}', () {
indent.write('$varChannelName.setMessageHandler ');
final String messageVarName = parameters.isNotEmpty ? 'message' : '_';
indent.addScoped('{ $messageVarName, reply in', '}', () {
final List<String> methodArgument = <String>[];
if (components.arguments.isNotEmpty) {
indent.writeln('let args = message as! [Any?]');
enumerate(components.arguments,
(int index, _SwiftFunctionArgument arg) {
final String argName = _getSafeArgumentName(index, arg.namedType);
final String argIndex = 'args[$index]';
final String fieldType = _swiftTypeForDartType(arg.type);
_writeGenericCasting(
indent: indent,
value: argIndex,
variableName: argName,
fieldType: fieldType,
type: arg.type);
if (arg.label == '_') {
methodArgument.add(argName);
} else {
methodArgument.add('${arg.label ?? arg.name}: $argName');
}
});
}
final String tryStatement = isAsynchronous ? '' : 'try ';
// Empty parens are not required when calling a method whose only
// argument is a trailing closure.
final String argumentString = methodArgument.isEmpty && isAsynchronous
? ''
: '(${methodArgument.join(', ')})';
final String call =
'${tryStatement}api.${components.name}$argumentString';
if (isAsynchronous) {
final String resultName = returnType.isVoid ? 'nil' : 'res';
final String successVariableInit =
returnType.isVoid ? '' : '(let res)';
indent.write('$call ');
indent.addScoped('{ result in', '}', () {
indent.write('switch result ');
indent.addScoped('{', '}', nestCount: 0, () {
final String nullsafe = returnType.isNullable ? '?' : '';
final String enumTag =
returnType.isEnum ? '$nullsafe.rawValue' : '';
indent.writeln('case .success$successVariableInit:');
indent.nest(1, () {
indent.writeln('reply(wrapResult($resultName$enumTag))');
});
indent.writeln('case .failure(let error):');
indent.nest(1, () {
indent.writeln('reply(wrapError(error))');
});
});
});
} else {
indent.write('do ');
indent.addScoped('{', '}', () {
if (returnType.isVoid) {
indent.writeln(call);
indent.writeln('reply(wrapResult(nil))');
} else {
String enumTag = '';
if (returnType.isEnum) {
enumTag = '.rawValue';
}
enumTag = returnType.isNullable && returnType.isEnum
? '?$enumTag'
: enumTag;
indent.writeln('let result = $call');
indent.writeln('reply(wrapResult(result$enumTag))');
}
}, addTrailingNewline: false);
indent.addScoped(' catch {', '}', () {
indent.writeln('reply(wrapError(error))');
});
}
});
}, addTrailingNewline: false);
indent.addScoped(' else {', '}', () {
indent.writeln('$varChannelName.setMessageHandler(nil)');
});
}
}
/// Calculates the name of the codec that will be generated for [api].
String _getCodecName(Api api) => '${api.name}Codec';
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.
String _getSafeArgumentName(int count, NamedType argument) =>
'${_getArgumentName(count, argument)}Arg';
String _camelCase(String text) {
final String pascal = text.split('_').map((String part) {
return part.isEmpty ? '' : part[0].toUpperCase() + part.substring(1);
}).join();
return pascal[0].toLowerCase() + pascal.substring(1);
}
/// Converts a [List] of [TypeDeclaration]s to a comma separated [String] to be
/// used in Swift code.
String _flattenTypeArguments(List<TypeDeclaration> args) {
return args.map((TypeDeclaration e) => _swiftTypeForDartType(e)).join(', ');
}
String _swiftTypeForBuiltinGenericDartType(TypeDeclaration type) {
if (type.typeArguments.isEmpty) {
if (type.baseName == 'List') {
return '[Any?]';
} else if (type.baseName == 'Map') {
return '[AnyHashable: Any?]';
} else {
return 'Any';
}
} else {
if (type.baseName == 'List') {
return '[${_nullsafeSwiftTypeForDartType(type.typeArguments.first)}]';
} else if (type.baseName == 'Map') {
return '[${_nullsafeSwiftTypeForDartType(type.typeArguments.first)}: ${_nullsafeSwiftTypeForDartType(type.typeArguments.last)}]';
} else {
return '${type.baseName}<${_flattenTypeArguments(type.typeArguments)}>';
}
}
}
String? _swiftTypeForBuiltinDartType(TypeDeclaration type) {
const Map<String, String> swiftTypeForDartTypeMap = <String, String>{
'void': 'Void',
'bool': 'Bool',
'String': 'String',
'int': 'Int64',
'double': 'Double',
'Uint8List': 'FlutterStandardTypedData',
'Int32List': 'FlutterStandardTypedData',
'Int64List': 'FlutterStandardTypedData',
'Float32List': 'FlutterStandardTypedData',
'Float64List': 'FlutterStandardTypedData',
'Object': 'Any',
};
if (swiftTypeForDartTypeMap.containsKey(type.baseName)) {
return swiftTypeForDartTypeMap[type.baseName];
} else if (type.baseName == 'List' || type.baseName == 'Map') {
return _swiftTypeForBuiltinGenericDartType(type);
} else {
return null;
}
}
String _swiftTypeForDartType(TypeDeclaration type) {
return _swiftTypeForBuiltinDartType(type) ?? type.baseName;
}
String _nullsafeSwiftTypeForDartType(TypeDeclaration type) {
final String nullSafe = type.isNullable ? '?' : '';
return '${_swiftTypeForDartType(type)}$nullSafe';
}
String _getMethodSignature({
required String name,
required Iterable<Parameter> parameters,
required TypeDeclaration returnType,
required String errorTypeName,
bool isAsynchronous = false,
String? swiftFunction,
String Function(int index, NamedType argument) getParameterName =
_getArgumentName,
}) {
final _SwiftFunctionComponents components = _SwiftFunctionComponents(
name: name,
parameters: parameters,
returnType: returnType,
swiftFunction: swiftFunction,
);
final String returnTypeString =
returnType.isVoid ? 'Void' : _nullsafeSwiftTypeForDartType(returnType);
final Iterable<String> types =
parameters.map((NamedType e) => _nullsafeSwiftTypeForDartType(e.type));
final Iterable<String> labels = indexMap(components.arguments,
(int index, _SwiftFunctionArgument argument) {
return argument.label ?? _getArgumentName(index, argument.namedType);
});
final Iterable<String> names = indexMap(parameters, getParameterName);
final String parameterSignature =
map3(types, labels, names, (String type, String label, String name) {
return '${label != name ? '$label ' : ''}$name: $type';
}).join(', ');
if (isAsynchronous) {
if (parameters.isEmpty) {
return 'func ${components.name}(completion: @escaping (Result<$returnTypeString, $errorTypeName>) -> Void)';
} else {
return 'func ${components.name}($parameterSignature, completion: @escaping (Result<$returnTypeString, $errorTypeName>) -> Void)';
}
} else {
if (returnType.isVoid) {
return 'func ${components.name}($parameterSignature) throws';
} else {
return 'func ${components.name}($parameterSignature) throws -> $returnTypeString';
}
}
}
/// A class that represents a Swift function argument.
///
/// The [name] is the name of the argument.
/// The [type] is the type of the argument.
/// The [namedType] is the [NamedType] that this argument is generated from.
/// The [label] is the label of the argument.
class _SwiftFunctionArgument {
_SwiftFunctionArgument({
required this.name,
required this.type,
required this.namedType,
this.label,
});
final String name;
final TypeDeclaration type;
final NamedType namedType;
final String? label;
}
/// A class that represents a Swift function signature.
///
/// The [name] is the name of the function.
/// The [arguments] are the arguments of the function.
/// The [returnType] is the return type of the function.
/// The [method] is the method that this function signature is generated from.
class _SwiftFunctionComponents {
/// Constructor that generates a [_SwiftFunctionComponents] from a [Method].
factory _SwiftFunctionComponents({
required String name,
required Iterable<Parameter> parameters,
required TypeDeclaration returnType,
String? swiftFunction,
}) {
if (swiftFunction == null || swiftFunction.isEmpty) {
return _SwiftFunctionComponents._(
name: name,
returnType: returnType,
arguments: parameters
.map((NamedType field) => _SwiftFunctionArgument(
name: field.name,
type: field.type,
namedType: field,
))
.toList(),
);
}
final String argsExtractor = repeat(r'(\w+):', parameters.length).join();
final RegExp signatureRegex = RegExp(r'(\w+) *\(' + argsExtractor + r'\)');
final RegExpMatch match = signatureRegex.firstMatch(swiftFunction)!;
final Iterable<String> labels = match
.groups(List<int>.generate(parameters.length, (int index) => index + 2))
.whereType();
return _SwiftFunctionComponents._(
name: match.group(1)!,
returnType: returnType,
arguments: map2(
parameters,
labels,
(NamedType field, String label) => _SwiftFunctionArgument(
name: field.name,
label: label == field.name ? null : label,
type: field.type,
namedType: field,
),
).toList(),
);
}
_SwiftFunctionComponents._({
required this.name,
required this.arguments,
required this.returnType,
});
final String name;
final List<_SwiftFunctionArgument> arguments;
final TypeDeclaration returnType;
}
| packages/packages/pigeon/lib/swift_generator.dart/0 | {
"file_path": "packages/packages/pigeon/lib/swift_generator.dart",
"repo_id": "packages",
"token_count": 14646
} | 1,013 |
// 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 static org.mockito.Mockito.*;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class NullableReturnsTest {
@Test
public void nullArgHostApi() {
NullableReturns.NullableArgHostApi mockApi = mock(NullableReturns.NullableArgHostApi.class);
BinaryMessenger binaryMessenger = mock(BinaryMessenger.class);
NullableReturns.NullableArgHostApi.setUp(binaryMessenger, mockApi);
ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> handler =
ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class);
verify(binaryMessenger).setMessageHandler(anyString(), handler.capture());
MessageCodec<Object> codec = NullableReturns.NullableArgHostApi.getCodec();
ByteBuffer message =
codec.encodeMessage(
new ArrayList<Object>() {
{
add(null);
}
});
message.rewind();
handler
.getValue()
.onMessage(
message,
(bytes) -> {
bytes.rewind();
@SuppressWarnings("unchecked")
ArrayList<Object> wrapped = (ArrayList<Object>) codec.decodeMessage(bytes);
assertTrue(wrapped.size() == 1);
});
}
@Test
public void nullArgFlutterApi() {
BinaryMessenger binaryMessenger = mock(BinaryMessenger.class);
doAnswer(
invocation -> {
ByteBuffer message = invocation.getArgument(1);
BinaryMessenger.BinaryReply reply = invocation.getArgument(2);
message.position(0);
@SuppressWarnings("unchecked")
ArrayList<Object> args =
(ArrayList<Object>)
NullableReturns.NullableArgFlutterApi.getCodec().decodeMessage(message);
assertNull(args.get(0));
ByteBuffer replyData =
NullableReturns.NullableArgFlutterApi.getCodec()
.encodeMessage(
new ArrayList<Object>() {
{
add(args.get(0));
}
});
replyData.rewind();
reply.reply(replyData);
return null;
})
.when(binaryMessenger)
.send(anyString(), any(), any());
NullableReturns.NullableArgFlutterApi api =
new NullableReturns.NullableArgFlutterApi(binaryMessenger);
boolean[] didCall = {false};
api.doit(
null,
new NullableReturns.NullableResult<Long>() {
public void success(Long result) {
didCall[0] = true;
assertNull(result);
}
public void error(Throwable error) {
assertEquals(error, null);
}
});
assertTrue(didCall[0]);
}
}
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/NullableReturnsTest.java/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/NullableReturnsTest.java",
"repo_id": "packages",
"token_count": 1497
} | 1,014 |
// 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 AllDatatypesTest : XCTestCase
@end
///////////////////////////////////////////////////////////////////////////////////////////
@implementation AllDatatypesTest
- (void)testAllNull {
FLTAllNullableTypes *everything = [[FLTAllNullableTypes alloc] init];
EchoBinaryMessenger *binaryMessenger =
[[EchoBinaryMessenger alloc] initWithCodec:FLTFlutterIntegrationCoreApiGetCodec()];
FLTFlutterIntegrationCoreApi *api =
[[FLTFlutterIntegrationCoreApi alloc] initWithBinaryMessenger:binaryMessenger];
XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
[api echoAllNullableTypes:everything
completion:^(FLTAllNullableTypes *_Nonnull result, FlutterError *_Nullable error) {
XCTAssertNil(result.aNullableBool);
XCTAssertNil(result.aNullableInt);
XCTAssertNil(result.aNullableDouble);
XCTAssertNil(result.aNullableString);
XCTAssertNil(result.aNullableByteArray);
XCTAssertNil(result.aNullable4ByteArray);
XCTAssertNil(result.aNullable8ByteArray);
XCTAssertNil(result.aNullableFloatArray);
XCTAssertNil(result.aNullableList);
XCTAssertNil(result.aNullableMap);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:1.0];
}
- (void)testAllEquals {
FLTAllNullableTypes *everything = [[FLTAllNullableTypes alloc] init];
everything.aNullableBool = @NO;
everything.aNullableInt = @(1);
everything.aNullableDouble = @(2.0);
everything.aNullableString = @"123";
everything.aNullableByteArray = [FlutterStandardTypedData
typedDataWithBytes:[@"1234" dataUsingEncoding:NSUTF8StringEncoding]];
everything.aNullable4ByteArray = [FlutterStandardTypedData
typedDataWithInt32:[@"1234" dataUsingEncoding:NSUTF8StringEncoding]];
everything.aNullable8ByteArray = [FlutterStandardTypedData
typedDataWithInt64:[@"12345678" dataUsingEncoding:NSUTF8StringEncoding]];
everything.aNullableFloatArray = [FlutterStandardTypedData
typedDataWithFloat64:[@"12345678" dataUsingEncoding:NSUTF8StringEncoding]];
everything.aNullableList = @[ @(1), @(2) ];
everything.aNullableMap = @{@"hello" : @(1234)};
everything.nullableMapWithObject = @{@"hello" : @(1234), @"goodbye" : @"world"};
EchoBinaryMessenger *binaryMessenger =
[[EchoBinaryMessenger alloc] initWithCodec:FLTFlutterIntegrationCoreApiGetCodec()];
FLTFlutterIntegrationCoreApi *api =
[[FLTFlutterIntegrationCoreApi alloc] initWithBinaryMessenger:binaryMessenger];
XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
[api echoAllNullableTypes:everything
completion:^(FLTAllNullableTypes *_Nonnull result, FlutterError *_Nullable error) {
XCTAssertEqual(result.aNullableBool, everything.aNullableBool);
XCTAssertEqual(result.aNullableInt, everything.aNullableInt);
XCTAssertEqual(result.aNullableDouble, everything.aNullableDouble);
XCTAssertEqualObjects(result.aNullableString, everything.aNullableString);
XCTAssertEqualObjects(result.aNullableByteArray.data,
everything.aNullableByteArray.data);
XCTAssertEqualObjects(result.aNullable4ByteArray.data,
everything.aNullable4ByteArray.data);
XCTAssertEqualObjects(result.aNullable8ByteArray.data,
everything.aNullable8ByteArray.data);
XCTAssertEqualObjects(result.aNullableFloatArray.data,
everything.aNullableFloatArray.data);
XCTAssertEqualObjects(result.aNullableList, everything.aNullableList);
XCTAssertEqualObjects(result.aNullableMap, everything.aNullableMap);
XCTAssertEqualObjects(result.nullableMapWithObject,
everything.nullableMapWithObject);
[expectation fulfill];
}];
[self waitForExpectations:@[ expectation ] timeout:1.0];
}
@end
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/AllDatatypesTest.m/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/AllDatatypesTest.m",
"repo_id": "packages",
"token_count": 2003
} | 1,015 |
name: shared_test_plugin_code
description: Common code for test_plugin and alternate_language_test_plugin
version: 0.0.1
publish_to: none
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
build_runner: ^2.1.10
flutter:
sdk: flutter
# These are normal dependencies rather than dev_dependencies because the
# package exports the integration test code to be shared by the integration
# tests for the two plugins.
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: 5.4.4
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml",
"repo_id": "packages",
"token_count": 182
} | 1,016 |
# test_plugin
Tests for default plugin languages.
See [the `platform_tests` README](../README.md) for details.
| packages/packages/pigeon/platform_tests/test_plugin/README.md/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/README.md",
"repo_id": "packages",
"token_count": 35
} | 1,017 |
// 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 junit.framework.TestCase
import org.junit.Test
class PrimitiveTest : TestCase() {
@Test
fun testIntPrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = 1
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.anInt(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertEquals(input.toLong(), wrapped[0]) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.anInt(input.toLong()) }
}
@Test
fun testIntPrimitiveFlutter() {
val binaryMessenger = EchoBinaryMessenger(MultipleArityFlutterApi.codec)
val api = PrimitiveFlutterApi(binaryMessenger)
val input = 1L
var didCall = false
api.anInt(input) {
didCall = true
assertEquals(input, it.getOrNull())
}
assertTrue(didCall)
}
@Test
fun testBoolPrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = true
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBool"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.aBool(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertEquals(input, wrapped[0]) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.aBool(input) }
}
@Test
fun testBoolPrimitiveFlutter() {
val binaryMessenger = EchoBinaryMessenger(MultipleArityFlutterApi.codec)
val api = PrimitiveFlutterApi(binaryMessenger)
val input = true
var didCall = false
api.aBool(input) {
didCall = true
assertEquals(input, it.getOrNull())
}
assertTrue(didCall)
}
@Test
fun testStringPrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = "Hello"
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aString"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.aString(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertEquals(input, wrapped[0]) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.aString(input) }
}
@Test
fun testDoublePrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = 1.0
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aDouble"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.aDouble(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertEquals(input, wrapped[0]) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.aDouble(input) }
}
@Test
fun testDoublePrimitiveFlutter() {
val binaryMessenger = EchoBinaryMessenger(MultipleArityFlutterApi.codec)
val api = PrimitiveFlutterApi(binaryMessenger)
val input = 1.0
var didCall = false
api.aDouble(input) {
didCall = true
assertEquals(input, it.getOrNull())
}
assertTrue(didCall)
}
@Test
fun testMapPrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = mapOf<Any, Any?>("a" to 1, "b" to 2)
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aMap"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.aMap(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertEquals(input, wrapped[0]) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.aMap(input) }
}
@Test
fun testMapPrimitiveFlutter() {
val binaryMessenger = EchoBinaryMessenger(MultipleArityFlutterApi.codec)
val api = PrimitiveFlutterApi(binaryMessenger)
val input = mapOf<Any, Any?>("a" to 1, "b" to 2)
var didCall = false
api.aMap(input) {
didCall = true
assertEquals(input, it.getOrNull())
}
assertTrue(didCall)
}
@Test
fun testListPrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = listOf(1, 2, 3)
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aList"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.aList(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertEquals(input, wrapped[0]) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.aList(input) }
}
@Test
fun testListPrimitiveFlutter() {
val binaryMessenger = EchoBinaryMessenger(MultipleArityFlutterApi.codec)
val api = PrimitiveFlutterApi(binaryMessenger)
val input = listOf(1, 2, 3)
var didCall = false
api.aList(input) {
didCall = true
assertEquals(input, it.getOrNull())
}
assertTrue(didCall)
}
@Test
fun testInt32ListPrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = intArrayOf(1, 2, 3)
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt32List"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.anInt32List(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertTrue(input.contentEquals(wrapped[0] as IntArray)) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.anInt32List(input) }
}
@Test
fun testInt32ListPrimitiveFlutter() {
val binaryMessenger = EchoBinaryMessenger(MultipleArityFlutterApi.codec)
val api = PrimitiveFlutterApi(binaryMessenger)
val input = intArrayOf(1, 2, 3)
var didCall = false
api.anInt32List(input) {
didCall = true
assertTrue(input.contentEquals(it.getOrNull()))
}
assertTrue(didCall)
}
@Test
fun testBoolListPrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = listOf(true, false, true)
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBoolList"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.aBoolList(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertEquals(input, wrapped[0]) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.aBoolList(input) }
}
@Test
fun testBoolListPrimitiveFlutter() {
val binaryMessenger = EchoBinaryMessenger(MultipleArityFlutterApi.codec)
val api = PrimitiveFlutterApi(binaryMessenger)
val input = listOf(true, false, true)
var didCall = false
api.aBoolList(input) {
didCall = true
assertEquals(input, it.getOrNull())
}
assertTrue(didCall)
}
@Test
fun testStringIntMapPrimitiveHost() {
val binaryMessenger = mockk<BinaryMessenger>(relaxed = true)
val api = mockk<PrimitiveHostApi>(relaxed = true)
val input = mapOf<String?, Long?>("a" to 1, "b" to 2)
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aStringIntMap"
val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>()
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.aStringIntMap(any()) } returnsArgument 0
PrimitiveHostApi.setUp(binaryMessenger, api)
val codec = PrimitiveHostApi.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 { assertEquals(input, wrapped[0]) }
}
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
verify { api.aStringIntMap(input) }
}
@Test
fun testStringIntMapPrimitiveFlutter() {
val binaryMessenger = EchoBinaryMessenger(MultipleArityFlutterApi.codec)
val api = PrimitiveFlutterApi(binaryMessenger)
val input = mapOf<String?, Long?>("a" to 1, "b" to 2)
var didCall = false
api.aStringIntMap(input) {
didCall = true
assertEquals(input, it.getOrNull())
}
assertTrue(didCall)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/PrimitiveTest.kt/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/PrimitiveTest.kt",
"repo_id": "packages",
"token_count": 4740
} | 1,018 |
// 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 XCTest
@testable import test_plugin
class MockEnumApi2Host: EnumApi2Host {
func echo(data: DataWithEnum) -> DataWithEnum {
return data
}
}
extension DataWithEnum: Equatable {
public static func == (lhs: DataWithEnum, rhs: DataWithEnum) -> Bool {
lhs.state == rhs.state
}
}
class EnumTests: XCTestCase {
func testEchoHost() throws {
let binaryMessenger = MockBinaryMessenger<DataWithEnum>(codec: EnumApi2HostCodec.shared)
EnumApi2HostSetup.setUp(binaryMessenger: binaryMessenger, api: MockEnumApi2Host())
let channelName = "dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Host.echo"
XCTAssertNotNil(binaryMessenger.handlers[channelName])
let input = DataWithEnum(state: .success)
let inputEncoded = binaryMessenger.codec.encode([input])
let expectation = XCTestExpectation(description: "echo")
binaryMessenger.handlers[channelName]?(inputEncoded) { data in
let outputMap = binaryMessenger.codec.decode(data) as? [Any]
XCTAssertNotNil(outputMap)
let output = outputMap?.first as? DataWithEnum
XCTAssertEqual(output, input)
XCTAssertTrue(outputMap?.count == 1)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1.0)
}
func testEchoFlutter() throws {
let data = DataWithEnum(state: .error)
let binaryMessenger = EchoBinaryMessenger(codec: EnumApi2HostCodec.shared)
let api = EnumApi2Flutter(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
api.echo(data: data) { result in
switch result {
case .success(let res):
XCTAssertEqual(res.state, res.state)
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/EnumTests.swift/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/EnumTests.swift",
"repo_id": "packages",
"token_count": 757
} | 1,019 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <flutter/method_call.h>
#include <flutter/method_result_functions.h>
#include <flutter/standard_method_codec.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
#include <string>
#include "pigeon/message.gen.h"
namespace test_plugin {
namespace test {
namespace {
using flutter::EncodableMap;
using flutter::EncodableValue;
using ::testing::ByMove;
using ::testing::DoAll;
using ::testing::Pointee;
using ::testing::Return;
using ::testing::SetArgPointee;
using namespace message_pigeontest;
class MockMethodResult : public flutter::MethodResult<> {
public:
~MockMethodResult() = default;
MOCK_METHOD(void, SuccessInternal, (const EncodableValue* result),
(override));
MOCK_METHOD(void, ErrorInternal,
(const std::string& error_code, const std::string& error_message,
const EncodableValue* details),
(override));
MOCK_METHOD(void, NotImplementedInternal, (), (override));
};
class MockBinaryMessenger : public flutter::BinaryMessenger {
public:
~MockBinaryMessenger() = default;
MOCK_METHOD(void, Send,
(const std::string& channel, const uint8_t* message,
size_t message_size, flutter::BinaryReply reply),
(override, const));
MOCK_METHOD(void, SetMessageHandler,
(const std::string& channel,
flutter::BinaryMessageHandler handler),
(override));
};
class MockApi : public MessageApi {
public:
~MockApi() = default;
MOCK_METHOD(std::optional<FlutterError>, Initialize, (), (override));
MOCK_METHOD(ErrorOr<MessageSearchReply>, Search,
(const MessageSearchRequest&), (override));
};
class Writer : public flutter::ByteStreamWriter {
public:
void WriteByte(uint8_t byte) override { data_.push_back(byte); }
void WriteBytes(const uint8_t* bytes, size_t length) override {
for (size_t i = 0; i < length; ++i) {
data_.push_back(bytes[i]);
}
}
void WriteAlignment(uint8_t alignment) override {
while (data_.size() % alignment != 0) {
data_.push_back(0);
}
}
std::vector<uint8_t> data_;
};
} // namespace
TEST(PigeonTests, CallInitialize) {
MockBinaryMessenger mock_messenger;
MockApi mock_api;
flutter::BinaryMessageHandler handler;
EXPECT_CALL(
mock_messenger,
SetMessageHandler(
"dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize",
testing::_))
.Times(1)
.WillOnce(testing::SaveArg<1>(&handler));
EXPECT_CALL(
mock_messenger,
SetMessageHandler(
"dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search",
testing::_))
.Times(1);
EXPECT_CALL(mock_api, Initialize());
MessageApi::SetUp(&mock_messenger, &mock_api);
bool did_call_reply = false;
flutter::BinaryReply reply = [&did_call_reply](const uint8_t* data,
size_t size) {
did_call_reply = true;
};
handler(nullptr, 0, reply);
EXPECT_TRUE(did_call_reply);
}
TEST(PigeonTests, CallSearch) {
MockBinaryMessenger mock_messenger;
MockApi mock_api;
flutter::BinaryMessageHandler handler;
EXPECT_CALL(
mock_messenger,
SetMessageHandler(
"dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize",
testing::_))
.Times(1);
EXPECT_CALL(
mock_messenger,
SetMessageHandler(
"dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search",
testing::_))
.Times(1)
.WillOnce(testing::SaveArg<1>(&handler));
EXPECT_CALL(mock_api, Search(testing::_))
.WillOnce(
Return(ByMove(ErrorOr<MessageSearchReply>(MessageSearchReply()))));
MessageApi::SetUp(&mock_messenger, &mock_api);
bool did_call_reply = false;
flutter::BinaryReply reply = [&did_call_reply](const uint8_t* data,
size_t size) {
did_call_reply = true;
};
MessageSearchRequest request;
Writer writer;
flutter::EncodableList args;
args.push_back(flutter::CustomEncodableValue(request));
MessageApiCodecSerializer::GetInstance().WriteValue(args, &writer);
handler(writer.data_.data(), writer.data_.size(), reply);
EXPECT_TRUE(did_call_reply);
}
} // namespace test
} // namespace test_plugin
| packages/packages/pigeon/platform_tests/test_plugin/windows/test/pigeon_test.cpp/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/pigeon_test.cpp",
"repo_id": "packages",
"token_count": 1839
} | 1,020 |
// 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/java_generator.dart';
import 'package:pigeon/pigeon.dart';
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 class', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
name: 'field1'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public class Messages'));
expect(code, contains('public static final class Foobar'));
expect(code, contains('public static final class Builder'));
expect(code, contains('private @Nullable Long field1;'));
expect(code, contains('@CanIgnoreReturnValue'));
});
test('gen one enum', () {
final Enum anEnum = Enum(
name: 'Foobar',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'twoThreeFour'),
EnumMember(name: 'remoteDB'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[],
enums: <Enum>[anEnum],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public enum Foobar'));
expect(code, contains(' ONE(0),'));
expect(code, contains(' TWO_THREE_FOUR(1),'));
expect(code, contains(' REMOTE_DB(2);'));
expect(code, contains('final int index;'));
expect(code, contains('private Foobar(final int index) {'));
expect(code, contains(' this.index = index;'));
});
test('package', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
name: 'field1')
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions =
JavaOptions(className: 'Messages', package: 'com.google.foobar');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('package com.google.foobar;'));
expect(code, contains('ArrayList<Object> toList()'));
});
test('gen one host api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
)
])
], 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 JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public interface Api'));
expect(code, matches('Output.*doSomething.*Input'));
expect(code, contains('channel.setMessageHandler(null)'));
expect(
code,
contains(
'protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer)'));
expect(
code,
contains(
'protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value)'));
expect(
code,
contains(RegExp(
r'@NonNull\s*protected static ArrayList<Object> wrapError\(@NonNull Throwable exception\)')));
expect(code, isNot(contains('ArrayList ')));
expect(code, isNot(contains('ArrayList<>')));
});
test('all the simple datatypes header', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: true,
),
name: 'aBool'),
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
name: 'aInt'),
NamedType(
type: const TypeDeclaration(
baseName: 'double',
isNullable: true,
),
name: 'aDouble'),
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'aString'),
NamedType(
type: const TypeDeclaration(
baseName: 'Uint8List',
isNullable: true,
),
name: 'aUint8List'),
NamedType(
type: const TypeDeclaration(
baseName: 'Int32List',
isNullable: true,
),
name: 'aInt32List'),
NamedType(
type: const TypeDeclaration(
baseName: 'Int64List',
isNullable: true,
),
name: 'aInt64List'),
NamedType(
type: const TypeDeclaration(
baseName: 'Float64List',
isNullable: true,
),
name: 'aFloat64List'),
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('private @Nullable Boolean aBool;'));
expect(code, contains('private @Nullable Long aInt;'));
expect(code, contains('private @Nullable Double aDouble;'));
expect(code, contains('private @Nullable String aString;'));
expect(code, contains('private @Nullable byte[] aUint8List;'));
expect(code, contains('private @Nullable int[] aInt32List;'));
expect(code, contains('private @Nullable long[] aInt64List;'));
expect(code, contains('private @Nullable double[] aFloat64List;'));
});
test('gen one flutter api', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
)
])
], 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 JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public static class Api'));
expect(code, matches('doSomething.*Input.*Output'));
});
test('gen host void api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: const TypeDeclaration.voidDeclaration(),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(matches('=.*doSomething')));
expect(code, contains('doSomething('));
});
test('gen flutter void return api', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: const TypeDeclaration.voidDeclaration(),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'public void doSomething(@NonNull Input arg0Arg, @NonNull VoidResult result)'));
expect(code, contains('result.success();'));
});
test('gen host void argument api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
)
])
], classes: <Class>[
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('Output doSomething()'));
expect(code, contains('api.doSomething()'));
});
test('gen flutter void argument api', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
)
])
], classes: <Class>[
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code,
contains('public void doSomething(@NonNull Result<Output> result)'));
expect(code, contains(RegExp(r'channel.send\(\s*null')));
});
test('gen list', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'List',
isNullable: true,
),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public static final class Foobar'));
expect(code, contains('private @Nullable List<Object> field1;'));
});
test('gen map', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'Map',
isNullable: true,
),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public static final class Foobar'));
expect(code, contains('private @Nullable Map<Object, Object> field1;'));
});
test('gen nested', () {
final Class classDefinition = Class(
name: 'Outer',
fields: <NamedType>[
NamedType(
type: TypeDeclaration(
baseName: 'Nested',
associatedClass: emptyClass,
isNullable: true,
),
name: 'nested')
],
);
final Class nestedClass = Class(
name: 'Nested',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
name: 'data')
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition, nestedClass],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public class Messages'));
expect(code, contains('public static final class Outer'));
expect(code, contains('public static final class Nested'));
expect(code, contains('private @Nullable Nested nested;'));
expect(
code,
contains(
'(nested == null) ? null : Nested.fromList((ArrayList<Object>) nested)'));
expect(code, contains('add((nested == null) ? null : nested.toList());'));
});
test('gen one async Host Api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: 'arg')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
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 JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public interface Api'));
expect(code, contains('public interface Result<T> {'));
expect(code, contains('void error(@NonNull Throwable error);'));
expect(
code,
contains(
'void doSomething(@NonNull Input arg, @NonNull Result<Output> result);'));
expect(code, contains('api.doSomething(argArg, resultCallback);'));
expect(code, contains('channel.setMessageHandler(null)'));
});
test('gen one async Flutter Api', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
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 JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public static class Api'));
expect(code, matches('doSomething.*Input.*Output'));
});
test('gen one enum class', () {
final Enum anEnum = Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'twoThreeFour'),
EnumMember(name: 'remoteDB'),
],
);
final Class classDefinition = Class(
name: 'EnumClass',
fields: <NamedType>[
NamedType(
type: TypeDeclaration(
baseName: 'Enum1',
associatedEnum: emptyEnum,
isNullable: true,
),
name: 'enum1'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[anEnum],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public enum Enum1'));
expect(code, contains(' ONE(0),'));
expect(code, contains(' TWO_THREE_FOUR(1),'));
expect(code, contains(' REMOTE_DB(2);'));
expect(code, contains('final int index;'));
expect(code, contains('private Enum1(final int index) {'));
expect(code, contains(' this.index = index;'));
expect(code,
contains('toListResult.add(enum1 == null ? null : enum1.index);'));
expect(
code,
contains(
'pigeonResult.setEnum1(enum1 == null ? null : Enum1.values()[(int) enum1])'));
});
test('primitive enum host', () {
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: true,
associatedEnum: emptyEnum,
),
)
])
])
], classes: <Class>[], enums: <Enum>[
Enum(name: 'Foo', members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
])
]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public enum Foo'));
expect(
code,
contains(
'Foo fooArg = args.get(0) == null ? null : Foo.values()[(int) args.get(0)];'));
});
Iterable<String> makeIterable(String string) sync* {
yield string;
}
test('header', () {
final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
final JavaOptions javaOptions = JavaOptions(
className: 'Messages',
copyrightHeader: makeIterable('hello world'),
);
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, startsWith('// hello world'));
});
test('generics', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'List',
isNullable: true,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
name: 'field1'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('class Foobar'));
expect(code, contains('List<Long> field1;'));
});
test('generics - maps', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'Map',
isNullable: true,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'String', isNullable: true),
]),
name: 'field1'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('class Foobar'));
expect(code, contains('Map<String, String> field1;'));
});
test('host generics argument', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'List',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
name: 'arg')
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('doit(@NonNull List<Long> arg'));
});
test('flutter generics argument', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'List',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
name: 'arg')
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('doit(@NonNull List<Long> arg'));
});
test('host generics return', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration(
baseName: 'List',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('List<Long> doit('));
expect(code, contains('List<Long> output ='));
});
test('flutter generics return', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType: const TypeDeclaration(
baseName: 'List',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code, contains('public void doit(@NonNull Result<List<Long>> result)'));
expect(code, contains('List<Long> output = (List<Long>) listReply.get(0)'));
});
test('flutter int return', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType:
const TypeDeclaration(baseName: 'int', isNullable: false),
parameters: <Parameter>[],
isAsynchronous: true)
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('public void doit(@NonNull Result<Long> result)'));
expect(
code,
contains(
'Long output = listReply.get(0) == null ? null : ((Number) listReply.get(0)).longValue();'));
});
test('host multiple args', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'add',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
name: 'x',
type:
const TypeDeclaration(isNullable: false, baseName: 'int')),
Parameter(
name: 'y',
type:
const TypeDeclaration(isNullable: false, baseName: 'int')),
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('class Messages'));
expect(code, contains('Long add(@NonNull Long x, @NonNull Long y)'));
expect(code,
contains('ArrayList<Object> args = (ArrayList<Object>) message;'));
expect(code, contains('Number xArg = (Number) args.get(0)'));
expect(code, contains('Number yArg = (Number) args.get(1)'));
expect(
code,
contains(
'Long output = api.add((xArg == null) ? null : xArg.longValue(), (yArg == null) ? null : yArg.longValue())'));
});
test('if host argType is Object not cast', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'objectTest',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
name: 'x',
type: const TypeDeclaration(
isNullable: false, baseName: 'Object')),
],
returnType: const TypeDeclaration.voidDeclaration(),
)
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Api');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('Object xArg = args.get(0)'));
});
test('flutter multiple args', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'add',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
name: 'x',
type:
const TypeDeclaration(isNullable: false, baseName: 'int')),
Parameter(
name: 'y',
type:
const TypeDeclaration(isNullable: false, baseName: 'int')),
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('class Messages'));
expect(code, contains('BasicMessageChannel<Object> channel'));
expect(code, contains('Long output'));
expect(
code,
contains(
'public void add(@NonNull Long xArg, @NonNull Long yArg, @NonNull Result<Long> result)'));
expect(
code,
contains(RegExp(
r'channel.send\(\s*new ArrayList<Object>\(Arrays.asList\(xArg, yArg\)\),\s*channelReply ->')));
});
test('flutter single args', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'send',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
name: 'x',
type:
const TypeDeclaration(isNullable: false, baseName: 'int')),
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(RegExp(
r'channel.send\(\s*new ArrayList<Object>\(Collections.singletonList\(xArg\)\),\s*channelReply ->')));
});
test('return nullable host', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains(RegExp(r'@Nullable\s*Long doit\(\);')));
});
test('return nullable host async', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
isAsynchronous: true,
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
// Java doesn't accept nullability annotations in type arguments.
expect(code, contains('Result<Long>'));
});
test('nullable argument host', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'foo',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
)),
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains(' void doit(@Nullable Long foo);'));
});
test('nullable argument flutter', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'foo',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
)),
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'public void doit(@Nullable Long fooArg, @NonNull VoidResult result) {'));
});
test('background platform channel', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'foo',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
)),
],
taskQueueType: TaskQueueType.serialBackgroundThread)
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();'));
expect(
code,
contains(RegExp(
r'new BasicMessageChannel<>\(\s*binaryMessenger, "dev.flutter.pigeon.test_package.Api.doit", getCodec\(\), taskQueue\)')));
});
test('generated annotation', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions =
JavaOptions(className: 'Messages', useGeneratedAnnotation: true);
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@javax.annotation.Generated("dev.flutter.pigeon")'));
});
test('no generated annotation', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code,
isNot(contains('@javax.annotation.Generated("dev.flutter.pigeon")')));
});
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 JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
for (final String comment in comments) {
// This regex finds the comment only between the open and close comment block
expect(
RegExp(r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', dotAll: true)
.hasMatch(code),
true);
}
expect(code, isNot(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 JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains(' extends StandardMessageCodec')));
expect(code, contains('StandardMessageCodec'));
});
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',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
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 JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains(' extends StandardMessageCodec'));
});
test('creates api error class for custom errors', () {
final Api api = AstHostApi(name: 'Api', methods: <Method>[]);
final Root root = Root(
apis: <Api>[api],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('class FlutterError'));
});
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 JavaGenerator generator = JavaGenerator();
const JavaOptions javaOptions = JavaOptions(className: 'Messages');
generator.generate(
javaOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('createConnectionError(channelName)'));
expect(
code,
contains(
'return new FlutterError("channel-error", "Unable to establish connection on channel: " + channelName + ".", "");'));
});
}
| packages/packages/pigeon/test/java_generator_test.dart/0 | {
"file_path": "packages/packages/pigeon/test/java_generator_test.dart",
"repo_id": "packages",
"token_count": 24211
} | 1,021 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// TODO(louisehsu): given the difficulty of making the same integration tests
// work for both web and ios implementations, please find tests in their respective
// platform implementation packages.
testWidgets('placeholder test', (WidgetTester tester) async {});
}
| packages/packages/pointer_interceptor/pointer_interceptor/example/integration_test/widget_test.dart/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor/example/integration_test/widget_test.dart",
"repo_id": "packages",
"token_count": 181
} | 1,022 |
// 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 class PointerInterceptorIosPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
registrar.register(
PointerInterceptorFactory(), withId: "plugins.flutter.dev/pointer_interceptor_ios")
}
}
| packages/packages/pointer_interceptor/pointer_interceptor_ios/ios/Classes/PointerInterceptorIosPlugin.swift/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/ios/Classes/PointerInterceptorIosPlugin.swift",
"repo_id": "packages",
"token_count": 131
} | 1,023 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test(
'Default implementation of PointerInterceptorPlatform should throw unimplemented error',
() {
final PointerInterceptorPlatform unimplementedPointerInterceptorPlatform =
UnimplementedPointerInterceptorPlatform();
final Container testChild = Container();
expect(
() => unimplementedPointerInterceptorPlatform.buildWidget(
child: testChild),
throwsUnimplementedError);
});
}
class UnimplementedPointerInterceptorPlatform
extends PointerInterceptorPlatform {}
| packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart",
"repo_id": "packages",
"token_count": 292
} | 1,024 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import 'package:process/process.dart';
import 'package:process/src/interface/common.dart';
import 'package:test/test.dart';
void main() {
group('getExecutablePath', () {
late FileSystem fs;
late Directory workingDir, dir1, dir2, dir3;
void initialize(FileSystemStyle style) {
setUp(() {
fs = MemoryFileSystem(style: style);
workingDir = fs.systemTempDirectory.createTempSync('work_dir_');
dir1 = fs.systemTempDirectory.createTempSync('dir1_');
dir2 = fs.systemTempDirectory.createTempSync('dir2_');
dir3 = fs.systemTempDirectory.createTempSync('dir3_');
});
}
tearDown(() {
for (final Directory directory in <Directory>[
workingDir,
dir1,
dir2,
dir3
]) {
directory.deleteSync(recursive: true);
}
});
group('on windows', () {
late Platform platform;
initialize(FileSystemStyle.windows);
setUp(() {
platform = FakePlatform(
operatingSystem: 'windows',
environment: <String, String>{
'PATH': '${dir1.path};${dir2.path}',
'PATHEXT': '.exe;.bat'
},
);
});
test('absolute', () {
String command = fs.path.join(dir3.path, 'bla.exe');
final String expectedPath = command;
fs.file(command).createSync();
String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
command = fs.path.withoutExtension(command);
executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
});
test('in path', () {
String command = 'bla.exe';
final String expectedPath = fs.path.join(dir2.path, command);
fs.file(expectedPath).createSync();
String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
command = fs.path.withoutExtension(command);
executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
});
test('in path multiple times', () {
String command = 'bla.exe';
final String expectedPath = fs.path.join(dir1.path, command);
final String wrongPath = fs.path.join(dir2.path, command);
fs.file(expectedPath).createSync();
fs.file(wrongPath).createSync();
String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
command = fs.path.withoutExtension(command);
executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
});
test('in subdir of work dir', () {
String command = fs.path.join('.', 'foo', 'bla.exe');
final String expectedPath = fs.path.join(workingDir.path, command);
fs.file(expectedPath).createSync(recursive: true);
String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
command = fs.path.withoutExtension(command);
executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
});
test('in work dir', () {
String command = fs.path.join('.', 'bla.exe');
final String expectedPath = fs.path.join(workingDir.path, command);
final String wrongPath = fs.path.join(dir2.path, command);
fs.file(expectedPath).createSync();
fs.file(wrongPath).createSync();
String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
command = fs.path.withoutExtension(command);
executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
});
test('with multiple extensions', () {
const String command = 'foo';
final String expectedPath = fs.path.join(dir1.path, '$command.exe');
final String wrongPath1 = fs.path.join(dir1.path, '$command.bat');
final String wrongPath2 = fs.path.join(dir2.path, '$command.exe');
fs.file(expectedPath).createSync();
fs.file(wrongPath1).createSync();
fs.file(wrongPath2).createSync();
final String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
});
test('not found', () {
const String command = 'foo.exe';
final String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
expect(executablePath, isNull);
});
test('not found with throwOnFailure throws exception with match state',
() {
const String command = 'foo.exe';
expect(
() => getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
throwOnFailure: true,
),
throwsA(isA<ProcessPackageExecutableNotFoundException>()
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.candidates,
'candidates',
isEmpty)
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.workingDirectory,
'workingDirectory',
equals(workingDir.path))
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.toString(),
'toString',
contains(
' Working Directory: C:\\.tmp_rand0\\work_dir_rand0\n'
' Search Path:\n'
' C:\\.tmp_rand0\\dir1_rand0\n'
' C:\\.tmp_rand0\\dir2_rand0\n'))));
});
test('when path has spaces', () {
expect(
sanitizeExecutablePath(r'Program Files\bla.exe',
platform: platform),
r'"Program Files\bla.exe"');
expect(
sanitizeExecutablePath(r'ProgramFiles\bla.exe', platform: platform),
r'ProgramFiles\bla.exe');
expect(
sanitizeExecutablePath(r'"Program Files\bla.exe"',
platform: platform),
r'"Program Files\bla.exe"');
expect(
sanitizeExecutablePath(r'"Program Files\bla.exe"',
platform: platform),
r'"Program Files\bla.exe"');
expect(
sanitizeExecutablePath(r'C:\"Program Files"\bla.exe',
platform: platform),
r'C:\"Program Files"\bla.exe');
});
test('with absolute path when currentDirectory getter throws', () {
final FileSystem fsNoCwd = MemoryFileSystemNoCwd(fs);
final String command = fs.path.join(dir3.path, 'bla.exe');
final String expectedPath = command;
fs.file(command).createSync();
final String? executablePath = getExecutablePath(
command,
null,
platform: platform,
fs: fsNoCwd,
);
_expectSamePath(executablePath, expectedPath);
});
test('with relative path when currentDirectory getter throws', () {
final FileSystem fsNoCwd = MemoryFileSystemNoCwd(fs);
final String command = fs.path.join('.', 'bla.exe');
final String? executablePath = getExecutablePath(
command,
null,
platform: platform,
fs: fsNoCwd,
);
expect(executablePath, isNull);
});
});
group('on Linux', () {
late Platform platform;
initialize(FileSystemStyle.posix);
setUp(() {
platform = FakePlatform(
operatingSystem: 'linux',
environment: <String, String>{'PATH': '${dir1.path}:${dir2.path}'});
});
test('absolute', () {
final String command = fs.path.join(dir3.path, 'bla');
final String expectedPath = command;
final String wrongPath = fs.path.join(dir3.path, 'bla.bat');
fs.file(command).createSync();
fs.file(wrongPath).createSync();
final String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
});
test('in path multiple times', () {
const String command = 'xxx';
final String expectedPath = fs.path.join(dir1.path, command);
final String wrongPath = fs.path.join(dir2.path, command);
fs.file(expectedPath).createSync();
fs.file(wrongPath).createSync();
final String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
_expectSamePath(executablePath, expectedPath);
});
test('not found', () {
const String command = 'foo';
final String? executablePath = getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
);
expect(executablePath, isNull);
});
test('not found with throwOnFailure throws exception with match state',
() {
const String command = 'foo';
expect(
() => getExecutablePath(
command,
workingDir.path,
platform: platform,
fs: fs,
throwOnFailure: true,
),
throwsA(isA<ProcessPackageExecutableNotFoundException>()
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.candidates,
'candidates',
isEmpty)
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.workingDirectory,
'workingDirectory',
equals(workingDir.path))
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.toString(),
'toString',
contains(' Working Directory: /.tmp_rand0/work_dir_rand0\n'
' Search Path:\n'
' /.tmp_rand0/dir1_rand0\n'
' /.tmp_rand0/dir2_rand0\n'))));
});
test('when path has spaces', () {
expect(
sanitizeExecutablePath('/usr/local/bin/foo bar',
platform: platform),
'/usr/local/bin/foo bar');
});
});
});
group('Real Filesystem', () {
// These tests don't use the memory filesystem because Dart can't modify file
// executable permissions, so we have to create them with actual commands.
late Platform platform;
late Directory tmpDir;
late Directory pathDir1;
late Directory pathDir2;
late Directory pathDir3;
late Directory pathDir4;
late Directory pathDir5;
late File command1;
late File command2;
late File command3;
late File command4;
late File command5;
const Platform localPlatform = LocalPlatform();
late FileSystem fs;
setUp(() {
fs = const LocalFileSystem();
tmpDir = fs.systemTempDirectory.createTempSync();
pathDir1 = tmpDir.childDirectory('path1')..createSync();
pathDir2 = tmpDir.childDirectory('path2')..createSync();
pathDir3 = tmpDir.childDirectory('path3')..createSync();
pathDir4 = tmpDir.childDirectory('path4')..createSync();
pathDir5 = tmpDir.childDirectory('path5')..createSync();
command1 = pathDir1.childFile('command')..createSync();
command2 = pathDir2.childFile('command')..createSync();
command3 = pathDir3.childFile('command')..createSync();
command4 = pathDir4.childFile('command')..createSync();
command5 = pathDir5.childFile('command')..createSync();
platform = FakePlatform(
operatingSystem: localPlatform.operatingSystem,
environment: <String, String>{
'PATH': <Directory>[
pathDir1,
pathDir2,
pathDir3,
pathDir4,
pathDir5,
].map<String>((Directory dir) => dir.absolute.path).join(':'),
},
);
});
tearDown(() {
tmpDir.deleteSync(recursive: true);
});
test('Only returns executables in PATH', () {
if (localPlatform.isWindows) {
// Windows doesn't check for executable-ness, and we can't run 'chmod'
// on Windows anyhow.
return;
}
// Make the second command in the path executable, but not the first.
// No executable permissions
io.Process.runSync('chmod', <String>['0644', '--', command1.path]);
// Only group executable permissions
io.Process.runSync('chmod', <String>['0645', '--', command2.path]);
// Only other executable permissions
io.Process.runSync('chmod', <String>['0654', '--', command3.path]);
// All executable permissions, but not readable
io.Process.runSync('chmod', <String>['0311', '--', command4.path]);
// All executable permissions
io.Process.runSync('chmod', <String>['0755', '--', command5.path]);
final String? executablePath = getExecutablePath(
'command',
tmpDir.path,
platform: platform,
fs: fs,
);
// Make sure that the path returned is for the last command, since that
// one comes last in the PATH, but is the only one executable by the
// user.
_expectSamePath(executablePath, command5.absolute.path);
});
test(
'Test that finding non-executable paths throws with proper information',
() {
if (localPlatform.isWindows) {
// Windows doesn't check for executable-ness, and we can't run 'chmod'
// on Windows anyhow.
return;
}
// Make the second command in the path executable, but not the first.
// No executable permissions
io.Process.runSync('chmod', <String>['0644', '--', command1.path]);
// Only group executable permissions
io.Process.runSync('chmod', <String>['0645', '--', command2.path]);
// Only other executable permissions
io.Process.runSync('chmod', <String>['0654', '--', command3.path]);
// All executable permissions, but not readable
io.Process.runSync('chmod', <String>['0311', '--', command4.path]);
expect(
() => getExecutablePath(
'command',
tmpDir.path,
platform: platform,
fs: fs,
throwOnFailure: true,
),
throwsA(isA<ProcessPackageExecutableNotFoundException>()
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.candidates,
'candidates',
equals(<String>[
'${tmpDir.path}/path1/command',
'${tmpDir.path}/path2/command',
'${tmpDir.path}/path3/command',
'${tmpDir.path}/path4/command',
'${tmpDir.path}/path5/command',
]))
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.toString(),
'toString',
contains(
'ProcessPackageExecutableNotFoundException: Found candidates, but lacked sufficient permissions to execute "command".\n'
' Command: command\n'
' Working Directory: ${tmpDir.path}\n'
' Candidates:\n'
' ${tmpDir.path}/path1/command\n'
' ${tmpDir.path}/path2/command\n'
' ${tmpDir.path}/path3/command\n'
' ${tmpDir.path}/path4/command\n'
' ${tmpDir.path}/path5/command\n'
' Search Path:\n'
' ${tmpDir.path}/path1\n'
' ${tmpDir.path}/path2\n'
' ${tmpDir.path}/path3\n'
' ${tmpDir.path}/path4\n'
' ${tmpDir.path}/path5\n'))));
});
test('Test that finding no executable paths throws with proper information',
() {
if (localPlatform.isWindows) {
// Windows doesn't check for executable-ness, and we can't run 'chmod'
// on Windows anyhow.
return;
}
expect(
() => getExecutablePath(
'non-existent-command',
tmpDir.path,
platform: platform,
fs: fs,
throwOnFailure: true,
),
throwsA(isA<ProcessPackageExecutableNotFoundException>()
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.candidates,
'candidates',
isEmpty)
.having(
(ProcessPackageExecutableNotFoundException
notFoundException) =>
notFoundException.toString(),
'toString',
contains(
'ProcessPackageExecutableNotFoundException: Failed to find "non-existent-command" in the search path.\n'
' Command: non-existent-command\n'
' Working Directory: ${tmpDir.path}\n'
' Search Path:\n'
' ${tmpDir.path}/path1\n'
' ${tmpDir.path}/path2\n'
' ${tmpDir.path}/path3\n'
' ${tmpDir.path}/path4\n'
' ${tmpDir.path}/path5\n'))));
});
});
}
void _expectSamePath(String? actual, String? expected) {
expect(actual, isNotNull);
expect(actual!.toLowerCase(), expected!.toLowerCase());
}
class MemoryFileSystemNoCwd extends ForwardingFileSystem {
MemoryFileSystemNoCwd(super.delegate);
@override
Directory get currentDirectory {
throw const FileSystemException('Access denied');
}
}
| packages/packages/process/test/src/interface/common_test.dart/0 | {
"file_path": "packages/packages/process/test/src/interface/common_test.dart",
"repo_id": "packages",
"token_count": 9747
} | 1,025 |
// 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 (v12.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, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import
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';
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];
}
/// Home screen quick-action shortcut item.
class ShortcutItemMessage {
ShortcutItemMessage({
required this.type,
required 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;
Object encode() {
return <Object?>[
type,
localizedTitle,
icon,
];
}
static ShortcutItemMessage decode(Object result) {
result as List<Object?>;
return ShortcutItemMessage(
type: result[0]! as String,
localizedTitle: result[1]! as String,
icon: result[2] as String?,
);
}
}
class _IOSQuickActionsApiCodec extends StandardMessageCodec {
const _IOSQuickActionsApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is ShortcutItemMessage) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return ShortcutItemMessage.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class IOSQuickActionsApi {
/// Constructor for [IOSQuickActionsApi]. 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.
IOSQuickActionsApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _IOSQuickActionsApiCodec();
/// Sets the dynamic shortcuts for the app.
Future<void> setShortcutItems(
List<ShortcutItemMessage?> arg_itemsList) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsApi.setShortcutItems',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_itemsList]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
/// Removes all dynamic shortcuts.
Future<void> clearShortcutItems() async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsApi.clearShortcutItems',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(null) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
abstract class IOSQuickActionsFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Sends a string representing a shortcut from the native platform to the app.
void launchAction(String action);
static void setup(IOSQuickActionsFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction was null.');
final List<Object?> args = (message as List<Object?>?)!;
final String? arg_action = (args[0] as String?);
assert(arg_action != null,
'Argument for dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction was null, expected non-null String.');
try {
api.launchAction(arg_action!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
| packages/packages/quick_actions/quick_actions_ios/lib/messages.g.dart/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_ios/lib/messages.g.dart",
"repo_id": "packages",
"token_count": 2231
} | 1,026 |
name: quick_actions_platform_interface
description: A common platform interface for the quick_actions plugin.
repository: https://github.com/flutter/packages/tree/main/packages/quick_actions/quick_actions_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+quick_actions%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: 1.0.6
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
mockito: 5.4.4
topics:
- quick-actions
- os-integration
| packages/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml",
"repo_id": "packages",
"token_count": 270
} | 1,027 |
name: local
description: Example of new custom local widgets for RFW
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ^3.2.0
flutter: ">=3.16.0"
dependencies:
flutter:
sdk: flutter
rfw:
path: ../../
| packages/packages/rfw/example/local/pubspec.yaml/0 | {
"file_path": "packages/packages/rfw/example/local/pubspec.yaml",
"repo_id": "packages",
"token_count": 110
} | 1,028 |
// 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 'package:flutter/widgets.dart';
import '../dart/model.dart';
import 'content.dart';
import 'runtime.dart';
export '../dart/model.dart' show DynamicMap, LibraryName;
/// Injection point for a remote widget.
///
/// This widget combines an RFW [Runtime] and [DynamicData], inserting a
/// specified [widget] into the tree.
class RemoteWidget extends StatefulWidget {
/// Inserts the specified [widget] into the tree.
///
/// The [onEvent] argument is optional. When omitted, events are discarded.
const RemoteWidget({ super.key, required this.runtime, required this.widget, required this.data, this.onEvent });
/// The [Runtime] to use to render the widget specified by [widget].
///
/// This should update rarely (doing so is relatively expensive), but it is
/// fine to update it. For example, a client could update this on the fly when
/// the server deploys a new version of the widget library.
///
/// Frequent updates (e.g. animations) should be done by updating [data] instead.
final Runtime runtime;
/// The name of the widget to display, and the library from which to obtain
/// it.
///
/// The widget must be declared either in the specified library, or one of its
/// dependencies.
///
/// The data to show in the widget is specified using [data].
final FullyQualifiedWidgetName widget;
/// The data to which the widget specified by [name] will be bound.
///
/// This includes data that comes from the application, e.g. a description of
/// the user's device, the current time, or an animation controller's value,
/// and data that comes from the server, e.g. the contents of the user's
/// shopping cart.
///
/// This can be updated frequently (once per frame) using
/// [DynamicContent.update].
final DynamicContent data;
/// Called when there's an event triggered by a remote widget.
///
/// If this is null, events are discarded.
final RemoteEventHandler? onEvent;
@override
State<RemoteWidget> createState() => _RemoteWidgetState();
}
class _RemoteWidgetState extends State<RemoteWidget> {
@override
void initState() {
super.initState();
widget.runtime.addListener(_runtimeChanged);
}
@override
void didUpdateWidget(RemoteWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.runtime != widget.runtime) {
oldWidget.runtime.removeListener(_runtimeChanged);
widget.runtime.addListener(_runtimeChanged);
}
}
@override
void dispose() {
widget.runtime.removeListener(_runtimeChanged);
super.dispose();
}
void _runtimeChanged() {
setState(() { /* widget probably changed */ });
}
void _eventHandler(String eventName, DynamicMap eventArguments) {
if (widget.onEvent != null) {
widget.onEvent!(eventName, eventArguments);
}
}
@override
Widget build(BuildContext context) {
return widget.runtime.build(context, widget.widget, widget.data, _eventHandler);
}
}
| packages/packages/rfw/lib/src/flutter/remote_widget.dart/0 | {
"file_path": "packages/packages/rfw/lib/src/flutter/remote_widget.dart",
"repo_id": "packages",
"token_count": 905
} | 1,029 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'dart:io';
import 'package:lcov_parser/lcov_parser.dart' as lcov;
import 'package:meta/meta.dart';
// After you run `flutter test --coverage`, `.../rfw/coverage/lcov.info` will
// represent the latest coverage information for the package. Load that file
// into your IDE's coverage mode to see what lines need coverage.
// In Emacs, that's `M-x coverlay-load-file`, for example.
// (If you're using Emacs, you may need to set the variable `coverlay:base-path`
// first (make sure it has a trailing slash), then load the overlay file, and
// once it is loaded you can call `M-x coverlay-display-stats` to get a summary
// of the files to look at.)
// If Dart coverage increases the number of lines that could be covered, it is
// possible that this package will no longer report 100% coverage even though
// nothing has changed about the package itself. In the event that that happens,
// set this constant to the number of lines currently being covered and file a
// bug, cc'ing the current package owner (Hixie) so that they can add more tests.
const int? targetLines = null;
@immutable
final class LcovLine {
const LcovLine(this.filename, this.line);
final String filename;
final int line;
@override
int get hashCode => Object.hash(filename, line);
@override
bool operator ==(Object other) {
return other is LcovLine &&
other.line == line &&
other.filename == filename;
}
@override
String toString() {
return '$filename:$line';
}
}
Future<void> main(List<String> arguments) async {
// This script is mentioned in the CONTRIBUTING.md file.
final Directory coverageDirectory = Directory('coverage');
if (coverageDirectory.existsSync()) {
coverageDirectory.deleteSync(recursive: true);
}
final ProcessResult result = Process.runSync(
'flutter',
<String>[
'test',
'--coverage',
if (arguments.isNotEmpty) ...arguments,
],
);
if (result.exitCode != 0) {
print(result.stdout);
print(result.stderr);
print('Tests failed.');
// leave coverage directory around to aid debugging
exit(1);
}
if (Platform.environment.containsKey('CHANNEL') &&
Platform.environment['CHANNEL'] != 'master' &&
Platform.environment['CHANNEL'] != 'main') {
print(
'Tests passed. (Coverage verification skipped; currently on ${Platform.environment['CHANNEL']} channel.)',
);
coverageDirectory.deleteSync(recursive: true);
exit(0);
}
final List<File> libFiles = Directory('lib')
.listSync(recursive: true)
.whereType<File>()
.where((File file) => file.path.endsWith('.dart'))
.toList();
final Set<LcovLine> flakyLines = <LcovLine>{};
final Set<LcovLine> deadLines = <LcovLine>{};
for (final File file in libFiles) {
int lineNumber = 0;
for (final String line in file.readAsLinesSync()) {
lineNumber += 1;
if (line.endsWith('// dead code on VM target')) {
deadLines.add(LcovLine(file.path, lineNumber));
}
if (line.endsWith('// https://github.com/dart-lang/sdk/issues/53349')) {
flakyLines.add(LcovLine(file.path, lineNumber));
}
}
}
final List<lcov.Record> records = await lcov.Parser.parse(
'coverage/lcov.info',
);
int totalLines = 0;
int coveredLines = 0;
bool deadLinesError = false;
for (final lcov.Record record in records) {
if (record.lines != null) {
totalLines += record.lines!.found ?? 0;
coveredLines += record.lines!.hit ?? 0;
if (record.file != null && record.lines!.details != null) {
for (int index = 0; index < record.lines!.details!.length; index += 1) {
if (record.lines!.details![index].hit != null &&
record.lines!.details![index].line != null) {
final LcovLine line = LcovLine(
record.file!,
record.lines!.details![index].line!,
);
if (flakyLines.contains(line)) {
totalLines -= 1;
if (record.lines!.details![index].hit! > 0) {
coveredLines -= 1;
}
}
if (deadLines.contains(line)) {
deadLines.remove(line);
totalLines -= 1;
if (record.lines!.details![index].hit! > 0) {
print(
'$line: Line is marked as being dead code but was nonetheless covered.',
);
deadLinesError = true;
}
}
}
}
}
}
}
if (deadLines.isNotEmpty || deadLinesError) {
for (final LcovLine line in deadLines) {
print(
'$line: Line is marked as being undetectably dead code but was not considered reachable.',
);
}
print(
'Consider removing the "dead code on VM target" comment from affected lines.',
);
exit(1);
}
if (totalLines <= 0 || totalLines < coveredLines) {
print('Failed to compute coverage correctly.');
exit(1);
}
final String coveredPercent =
(100.0 * coveredLines / totalLines).toStringAsFixed(1);
if (targetLines != null) {
if (targetLines! < totalLines) {
print(
'Warning: test_coverage has an override set to reduce the expected number of covered lines from $totalLines to $targetLines.\n'
'New tests should be written to cover all lines in the package.',
);
totalLines = targetLines!;
} else if (targetLines == totalLines) {
print(
'Warning: test_coverage has a redundant targetLines; it is equal to the actual number of coverable lines ($totalLines).\n'
'Update test_coverage.dart to set the targetLines constant to null.',
);
} else {
print(
'Warning: test_coverage has an outdated targetLines ($targetLines) that is above the total number of lines in the package ($totalLines).\n'
'Update test_coverage.dart to set the targetLines constant to null.',
);
}
}
if (coveredLines < totalLines) {
print('');
print(' ╭──────────────────────────────╮');
print(' │ COVERAGE REGRESSION DETECTED │');
print(' ╰──────────────────────────────╯');
print('');
print(
'Coverage has reduced to only $coveredLines lines ($coveredPercent%), out\n'
'of $totalLines total lines; ${totalLines - coveredLines} lines are not covered by tests.\n'
'Please add sufficient tests to get coverage back to 100%.',
);
print('');
print(
'When in doubt, ask @Hixie for advice. Thanks!',
);
exit(1);
}
coverageDirectory.deleteSync(recursive: true);
}
| packages/packages/rfw/test_coverage/bin/test_coverage.dart/0 | {
"file_path": "packages/packages/rfw/test_coverage/bin/test_coverage.dart",
"repo_id": "packages",
"token_count": 2664
} | 1,030 |
rootProject.name = 'shared_preferences_android'
| packages/packages/shared_preferences/shared_preferences_android/android/settings.gradle/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_android/android/settings.gradle",
"repo_id": "packages",
"token_count": 15
} | 1,031 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'shared_preferences_foundation'
s.version = '0.0.1'
s.summary = 'iOS and macOS implementation of the shared_preferences plugin.'
s.description = <<-DESC
Wraps NSUserDefaults, providing a persistent store for simple key-value pairs.
DESC
s.homepage = 'https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_foundation'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Flutter Team' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_foundation' }
s.source_files = 'Classes/**/*'
s.ios.dependency 'Flutter'
s.osx.dependency 'FlutterMacOS'
s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.xcconfig = {
'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift',
'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift',
}
s.swift_version = '5.0'
s.resource_bundles = {'shared_preferences_foundation_privacy' => ['Resources/PrivacyInfo.xcprivacy']}
end
| packages/packages/shared_preferences/shared_preferences_foundation/darwin/shared_preferences_foundation.podspec/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_foundation/darwin/shared_preferences_foundation.podspec",
"repo_id": "packages",
"token_count": 600
} | 1,032 |
name: shared_preferences_windows
description: Windows implementation of shared_preferences
repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_windows
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22
version: 2.3.2
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: shared_preferences
platforms:
windows:
dartPluginClass: SharedPreferencesWindows
dependencies:
file: ">=6.0.0 <8.0.0"
flutter:
sdk: flutter
path: ^1.8.0
path_provider_platform_interface: ^2.0.0
path_provider_windows: ^2.0.0
shared_preferences_platform_interface: ^2.3.0
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- persistence
- shared-preferences
- storage
| packages/packages/shared_preferences/shared_preferences_windows/pubspec.yaml/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_windows/pubspec.yaml",
"repo_id": "packages",
"token_count": 337
} | 1,033 |
// 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' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'table.dart';
/// Defines the leading and trailing padding values of a [TableSpan].
class TableSpanPadding {
/// Creates a padding configuration for a [TableSpan].
const TableSpanPadding({
this.leading = 0.0,
this.trailing = 0.0,
});
/// Creates padding where both the [leading] and [trailing] are `value`.
const TableSpanPadding.all(double value)
: leading = value,
trailing = value;
/// The leading amount of pixels to pad a [TableSpan] by.
///
/// If the [TableSpan] is a row and the vertical [Axis] is not reversed, this
/// offset will be applied above the row. If the vertical [Axis] is reversed,
/// this will be applied below the row.
///
/// If the [TableSpan] is a column and the horizontal [Axis] is not reversed,
/// this offset will be applied to the left the column. If the horizontal
/// [Axis] is reversed, this will be applied to the right of the column.
final double leading;
/// The trailing amount of pixels to pad a [TableSpan] by.
///
/// If the [TableSpan] is a row and the vertical [Axis] is not reversed, this
/// offset will be applied below the row. If the vertical [Axis] is reversed,
/// this will be applied above the row.
///
/// If the [TableSpan] is a column and the horizontal [Axis] is not reversed,
/// this offset will be applied to the right the column. If the horizontal
/// [Axis] is reversed, this will be applied to the left of the column.
final double trailing;
}
/// Defines the extent, visual appearance, and gesture handling of a row or
/// column in a [TableView].
///
/// A span refers to either a column or a row in a table.
class TableSpan {
/// Creates a [TableSpan].
///
/// The [extent] argument must be provided.
const TableSpan({
required this.extent,
TableSpanPadding? padding,
this.recognizerFactories = const <Type, GestureRecognizerFactory>{},
this.onEnter,
this.onExit,
this.cursor = MouseCursor.defer,
this.backgroundDecoration,
this.foregroundDecoration,
}) : padding = padding ?? const TableSpanPadding();
/// Defines the extent of the span.
///
/// If the span represents a row, this is the height of the row. If it
/// represents a column, this is the width of the column.
final TableSpanExtent extent;
/// Defines the leading and or trailing extent to pad the row or column by.
///
/// Defaults to no padding.
final TableSpanPadding padding;
/// Factory for creating [GestureRecognizer]s that want to compete for
/// gestures within the [extent] of the span.
///
/// If this span represents a row, a factory for a [TapGestureRecognizer]
/// could for example be provided here to recognize taps within the bounds
/// of the row.
///
/// The content of a cell takes precedence in handling pointer events. Next,
/// the recognizers defined for the [TableView.mainAxis], followed by the
/// other [Axis].
final Map<Type, GestureRecognizerFactory> recognizerFactories;
/// Triggers when a mouse pointer, with or without buttons pressed, has
/// entered the region encompassing the row or column described by this span.
///
/// This callback is triggered when the pointer has started to be contained by
/// the region, either due to a pointer event, or due to the movement or
/// appearance of the region. This method is always matched by a later
/// [onExit] call.
final PointerEnterEventListener? onEnter;
/// Triggered when a mouse pointer, with or without buttons pressed, has
/// exited the region encompassing the row or column described by this span.
///
/// This callback is triggered when the pointer has stopped being contained
/// by the region, either due to a pointer event, or due to the movement or
/// disappearance of the region. This method always matches an earlier
/// [onEnter] call.
final PointerExitEventListener? onExit;
/// Mouse cursor to show when the mouse hovers over this span.
///
/// Defaults to [MouseCursor.defer].
final MouseCursor cursor;
/// The [TableSpanDecoration] to paint behind the content of this span.
///
/// The [backgroundDecoration]s of the [TableView.mainAxis] are painted after
/// the [backgroundDecoration]s of the other [Axis]. On top of that,
/// the content of the individual cells in this span are painted, followed by
/// any specified [foregroundDecoration].
///
/// The decorations of pinned rows and columns are painted separately from
/// the decorations of unpinned rows and columns, with the unpinned rows and
/// columns being painted first to account for overlap from pinned rows or
/// columns.
final TableSpanDecoration? backgroundDecoration;
/// The [TableSpanDecoration] to paint in front of the content of this span.
///
/// After painting any [backgroundDecoration]s, and the content of the
/// individual cells, the [foregroundDecoration] of the [TableView.mainAxis]
/// are painted after the [foregroundDecoration]s of the other [Axis]
///
/// The decorations of pinned rows and columns are painted separately from
/// the decorations of unpinned rows and columns, with the unpinned rows and
/// columns being painted first to account for overlap from pinned rows or
/// columns.
final TableSpanDecoration? foregroundDecoration;
}
/// Delegate passed to [TableSpanExtent.calculateExtent] from the
/// [RenderTableViewport] during layout.
///
/// Provides access to metrics from the [TableView] that a [TableSpanExtent] may
/// need to calculate its extent.
///
/// Extents will not be computed for every frame unless the delegate has been
/// updated. Otherwise, after the extents are computed during the first layout
/// passed, they are cached and reused in subsequent frames.
class TableSpanExtentDelegate {
/// Creates a [TableSpanExtentDelegate].
///
/// Usually, only [TableView]s need to create instances of this class.
const TableSpanExtentDelegate({
required this.viewportExtent,
required this.precedingExtent,
});
/// The size of the viewport in the axis-direction of the span.
///
/// If the [TableSpanExtent] calculates the extent of a row, this is the
/// height of the viewport. If it calculates the extent of a column, this
/// is the width of the viewport.
final double viewportExtent;
/// The scroll extent that has already been used up by previous spans.
///
/// If the [TableSpanExtent] calculates the extent of a row, this is the
/// sum of all row extents prior to this row. If it calculates the extent
/// of a column, this is the sum of all previous columns.
final double precedingExtent;
}
/// Defines the extent of a [TableSpan].
///
/// If the span is a row, its extent is the height of the row. If the span is
/// a column, it's the width of that column.
abstract class TableSpanExtent {
/// Creates a [TableSpanExtent].
const TableSpanExtent();
/// Calculates the actual extent of the span in pixels.
///
/// To assist with the calculation, table metrics obtained from the provided
/// [TableSpanExtentDelegate] may be used.
double calculateExtent(TableSpanExtentDelegate delegate);
}
/// A span extent with a fixed [pixels] value.
class FixedTableSpanExtent extends TableSpanExtent {
/// Creates a [FixedTableSpanExtent].
///
/// The provided [pixels] value must be equal to or greater then zero.
const FixedTableSpanExtent(this.pixels) : assert(pixels >= 0.0);
/// The extent of the span in pixels.
final double pixels;
@override
double calculateExtent(TableSpanExtentDelegate delegate) => pixels;
}
/// Specified the span extent as a fraction of the viewport extent.
///
/// For example, a column with a 1.0 as [fraction] will be as wide as the
/// viewport.
class FractionalTableSpanExtent extends TableSpanExtent {
/// Creates a [FractionalTableSpanExtent].
///
/// The provided [fraction] value must be equal to or greater than zero.
const FractionalTableSpanExtent(
this.fraction,
) : assert(fraction >= 0.0);
/// The fraction of the [TableSpanExtentDelegate.viewportExtent] that the
/// span should occupy.
///
/// The provided [fraction] value must be equal to or greater than zero.
final double fraction;
@override
double calculateExtent(TableSpanExtentDelegate delegate) =>
delegate.viewportExtent * fraction;
}
/// Specifies that the span should occupy the remaining space in the viewport.
///
/// If the previous [TableSpan]s can already fill out the viewport, this will
/// evaluate the span's extent to zero. If the previous spans cannot fill out the
/// viewport, this span's extent will be whatever space is left to fill out the
/// viewport.
///
/// To avoid that the span's extent evaluates to zero, consider combining this
/// extent with another extent. The following example will make sure that the
/// span's extent is at least 200 pixels, but if there's more than that available
/// in the viewport, it will fill all that space:
///
/// ```dart
/// const MaxTableSpanExtent(FixedTableSpanExtent(200.0), RemainingTableSpanExtent());
/// ```
class RemainingTableSpanExtent extends TableSpanExtent {
/// Creates a [RemainingTableSpanExtent].
const RemainingTableSpanExtent();
@override
double calculateExtent(TableSpanExtentDelegate delegate) {
return math.max(0.0, delegate.viewportExtent - delegate.precedingExtent);
}
}
/// Signature for a function that combines the result of two
/// [TableSpanExtent.calculateExtent] invocations.
///
/// Used by [CombiningTableSpanExtent];
typedef TableSpanExtentCombiner = double Function(double, double);
/// Runs the result of two [TableSpanExtent]s through a `combiner` function
/// to determine the ultimate pixel extent of a span.
class CombiningTableSpanExtent extends TableSpanExtent {
/// Creates a [CombiningTableSpanExtent];
const CombiningTableSpanExtent(this._extent1, this._extent2, this._combiner);
final TableSpanExtent _extent1;
final TableSpanExtent _extent2;
final TableSpanExtentCombiner _combiner;
@override
double calculateExtent(TableSpanExtentDelegate delegate) {
return _combiner(
_extent1.calculateExtent(delegate),
_extent2.calculateExtent(delegate),
);
}
}
/// Returns the larger pixel extent of the two provided [TableSpanExtent].
class MaxTableSpanExtent extends CombiningTableSpanExtent {
/// Creates a [MaxTableSpanExtent].
const MaxTableSpanExtent(
TableSpanExtent extent1,
TableSpanExtent extent2,
) : super(extent1, extent2, math.max);
}
/// Returns the smaller pixel extent of the two provided [TableSpanExtent].
class MinTableSpanExtent extends CombiningTableSpanExtent {
/// Creates a [MinTableSpanExtent].
const MinTableSpanExtent(
TableSpanExtent extent1,
TableSpanExtent extent2,
) : super(extent1, extent2, math.min);
}
/// A decoration for a [TableSpan].
///
/// When decorating merged cells in the [TableView], a merged cell will take its
/// decoration from the leading cell of the merged span.
class TableSpanDecoration {
/// Creates a [TableSpanDecoration].
const TableSpanDecoration({
this.border,
this.color,
this.borderRadius,
this.consumeSpanPadding = true,
});
/// The border drawn around the span.
final TableSpanBorder? border;
/// The radius by which the leading and trailing ends of a row or
/// column will be rounded.
///
/// Applies to the [border] and [color] of the given [TableSpan].
final BorderRadius? borderRadius;
/// The color to fill the bounds of the span with.
final Color? color;
/// Whether or not the decoration should extend to fill the space created by
/// the [TableSpanPadding].
///
/// Defaults to true, meaning if a [TableSpan] is a row, the decoration will
/// apply to the full [TableSpanExtent], including the
/// [TableSpanPadding.leading] and [TableSpanPadding.trailing] for the row.
/// This same row decoration will consume any padding from the column spans so
/// as to decorate the row as one continuous span.
///
/// {@tool snippet}
/// This example illustrates how [consumeSpanPadding] affects
/// [TableSpanDecoration.color]. By default, the color of the decoration
/// consumes the padding, coloring the row fully by including the padding
/// around the row. When [consumeSpanPadding] is false, the padded area of
/// the row is not decorated.
///
/// ```dart
/// TableView.builder(
/// rowCount: 4,
/// columnCount: 4,
/// columnBuilder: (int index) => TableSpan(
/// extent: const FixedTableSpanExtent(150.0),
/// padding: const TableSpanPadding(trailing: 10),
/// ),
/// rowBuilder: (int index) => TableSpan(
/// extent: const FixedTableSpanExtent(150.0),
/// padding: TableSpanPadding(leading: 10, trailing: 10),
/// backgroundDecoration: TableSpanDecoration(
/// color: index.isOdd ? Colors.blue : Colors.green,
/// // The background color will not be applied to the padded area.
/// consumeSpanPadding: false,
/// ),
/// ),
/// cellBuilder: (_, TableVicinity vicinity) {
/// return Container(
/// height: 150,
/// width: 150,
/// child: const Center(child: FlutterLogo()),
/// );
/// },
/// );
/// ```
/// {@end-tool}
final bool consumeSpanPadding;
/// Called to draw the decoration around a span.
///
/// The provided [TableSpanDecorationPaintDetails] describes the bounds and
/// orientation of the span that are currently visible inside the viewport of
/// the table. The extent of the actual span may be larger.
///
/// If a span contains pinned parts, [paint] is invoked separately for the
/// pinned and unpinned parts. For example: If a row contains a pinned column,
/// paint is called with the [TableSpanDecorationPaintDetails.rect] for the
/// cell representing the pinned column and separately with another
/// [TableSpanDecorationPaintDetails.rect] containing all the other unpinned
/// cells.
void paint(TableSpanDecorationPaintDetails details) {
if (color != null) {
final Paint paint = Paint()
..color = color!
..isAntiAlias = borderRadius != null;
if (borderRadius == null || borderRadius == BorderRadius.zero) {
details.canvas.drawRect(details.rect, paint);
} else {
details.canvas.drawRRect(
borderRadius!.toRRect(details.rect),
paint,
);
}
}
if (border != null) {
border!.paint(details, borderRadius);
}
}
}
/// Describes the border for a [TableSpan].
class TableSpanBorder {
/// Creates a [TableSpanBorder].
const TableSpanBorder({
this.trailing = BorderSide.none,
this.leading = BorderSide.none,
});
/// The border to draw on the trailing side of the span, based on the
/// [AxisDirection].
///
/// The trailing side of a row is the bottom when [Axis.vertical] is
/// [AxisDirection.down], the trailing side of a column
/// is its right side when the [Axis.horizontal] is [AxisDirection.right].
final BorderSide trailing;
/// The border to draw on the leading side of the span.
///
/// The leading side of a row is the top when [Axis.vertical] is
/// [AxisDirection.down], the leading side of a column
/// is its left side when the [Axis.horizontal] is [AxisDirection.right].
final BorderSide leading;
/// Called to draw the border around a span.
///
/// If the span represents a row, `axisDirection` will be [AxisDirection.left]
/// or [AxisDirection.right]. For columns, the `axisDirection` will be
/// [AxisDirection.down] or [AxisDirection.up].
///
/// The provided [TableSpanDecorationPaintDetails] describes the bounds and
/// orientation of the span that are currently visible inside the viewport of
/// the table. The extent of the actual span may be larger.
///
/// If a span contains pinned parts, [paint] is invoked separately for the
/// pinned and unpinned parts. For example: If a row contains a pinned column,
/// paint is called with the [TableSpanDecorationPaintDetails.rect] for the
/// cell representing the pinned column and separately with another
/// [TableSpanDecorationPaintDetails.rect] containing all the other unpinned
/// cells.
void paint(
TableSpanDecorationPaintDetails details,
BorderRadius? borderRadius,
) {
final AxisDirection axisDirection = details.axisDirection;
switch (axisDirectionToAxis(axisDirection)) {
case Axis.horizontal:
final Border border = Border(
top: axisDirection == AxisDirection.right ? leading : trailing,
bottom: axisDirection == AxisDirection.right ? trailing : leading,
);
border.paint(
details.canvas,
details.rect,
borderRadius: borderRadius,
);
case Axis.vertical:
final Border border = Border(
left: axisDirection == AxisDirection.down ? leading : trailing,
right: axisDirection == AxisDirection.down ? trailing : leading,
);
border.paint(
details.canvas,
details.rect,
borderRadius: borderRadius,
);
}
}
}
/// Provides the details of a given [TableSpanDecoration] for painting.
///
/// Created during paint by the [RenderTableViewport] for the
/// [TableSpan.foregroundDecoration] and [TableSpan.backgroundDecoration].
class TableSpanDecorationPaintDetails {
/// Creates the details needed to paint a [TableSpanDecoration].
///
/// The [canvas], [rect], and [axisDirection] must be provided.
TableSpanDecorationPaintDetails({
required this.canvas,
required this.rect,
required this.axisDirection,
});
/// The [Canvas] that the [TableSpanDecoration] will be painted to.
final Canvas canvas;
/// A [Rect] representing the visible area of a row or column in the
/// [TableView], as represented by a [TableSpan].
///
/// This Rect contains all of the visible children in a given row or column,
/// which is the area the [TableSpanDecoration] will be applied to.
final Rect rect;
/// The [AxisDirection] of the [Axis] of the [TableSpan].
///
/// When [AxisDirection.down] or [AxisDirection.up], which would be
/// [Axis.vertical], a column is being painted. When [AxisDirection.left] or
/// [AxisDirection.right], which would be [Axis.horizontal], a row is being
/// painted.
final AxisDirection axisDirection;
}
| packages/packages/two_dimensional_scrollables/lib/src/table_view/table_span.dart/0 | {
"file_path": "packages/packages/two_dimensional_scrollables/lib/src/table_view/table_span.dart",
"repo_id": "packages",
"token_count": 5727
} | 1,034 |
name: url_launcher
description: Flutter plugin for launching a URL. Supports
web, phone, SMS, and email schemes.
repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
version: 6.2.5
environment:
sdk: ">=3.2.0 <4.0.0"
flutter: ">=3.16.0"
flutter:
plugin:
platforms:
android:
default_package: url_launcher_android
ios:
default_package: url_launcher_ios
linux:
default_package: url_launcher_linux
macos:
default_package: url_launcher_macos
web:
default_package: url_launcher_web
windows:
default_package: url_launcher_windows
dependencies:
flutter:
sdk: flutter
url_launcher_android: ^6.2.0
url_launcher_ios: ^6.2.0
# Allow either the pure-native or Dart/native hybrid versions of the desktop
# implementations, as both are compatible.
url_launcher_linux: ^3.1.0
url_launcher_macos: ^3.1.0
url_launcher_platform_interface: ^2.2.0
url_launcher_web: ^2.2.0
url_launcher_windows: ^3.1.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: 5.4.4
plugin_platform_interface: ^2.1.7
test: ^1.16.3
topics:
- links
- os-integration
- url-launcher
- urls
| packages/packages/url_launcher/url_launcher/pubspec.yaml/0 | {
"file_path": "packages/packages/url_launcher/url_launcher/pubspec.yaml",
"repo_id": "packages",
"token_count": 573
} | 1,035 |
// 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.urllauncher;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Browser;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import androidx.core.content.ContextCompat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/* Launches WebView activity */
public class WebViewActivity extends Activity {
/*
* Use this to trigger a BroadcastReceiver inside WebViewActivity
* that will request the current instance to finish.
* */
public static final String ACTION_CLOSE = "close action";
private final BroadcastReceiver broadcastReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_CLOSE.equals(action)) {
finish();
}
}
};
private final WebViewClient webViewClient =
new WebViewClient() {
/*
* This method is deprecated in API 24. Still overridden to support
* earlier Android versions.
*/
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
view.loadUrl(url);
return false;
}
return super.shouldOverrideUrlLoading(view, url);
}
@RequiresApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.loadUrl(request.getUrl().toString());
}
return false;
}
};
// Uses default (package-private) access since it's used by inner class implementations.
WebView webview;
private final IntentFilter closeIntentFilter = new IntentFilter(ACTION_CLOSE);
// Verifies that a url opened by `Window.open` has a secure url.
class FlutterWebChromeClient extends WebChromeClient {
@Override
public boolean onCreateWindow(
final WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
final WebViewClient webViewClient =
new WebViewClient() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean shouldOverrideUrlLoading(
@NonNull WebView view, @NonNull WebResourceRequest request) {
webview.loadUrl(request.getUrl().toString());
return true;
}
/*
* This method is deprecated in API 24. Still overridden to support
* earlier Android versions.
*/
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webview.loadUrl(url);
return true;
}
};
final WebView newWebView = new WebView(webview.getContext());
newWebView.setWebViewClient(webViewClient);
final WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
// Get the Intent that started this activity and extract the string
final Intent intent = getIntent();
final String url = intent.getStringExtra(URL_EXTRA);
final boolean enableJavaScript = intent.getBooleanExtra(ENABLE_JS_EXTRA, false);
final boolean enableDomStorage = intent.getBooleanExtra(ENABLE_DOM_EXTRA, false);
final Bundle headersBundle = intent.getBundleExtra(Browser.EXTRA_HEADERS);
final Map<String, String> headersMap = extractHeaders(headersBundle);
webview.loadUrl(url, headersMap);
webview.getSettings().setJavaScriptEnabled(enableJavaScript);
webview.getSettings().setDomStorageEnabled(enableDomStorage);
// Open new urls inside the webview itself.
webview.setWebViewClient(webViewClient);
// Multi windows is set with FlutterWebChromeClient by default to handle internal bug: b/159892679.
webview.getSettings().setSupportMultipleWindows(true);
webview.setWebChromeClient(new FlutterWebChromeClient());
// Register receiver that may finish this Activity.
ContextCompat.registerReceiver(
this, broadcastReceiver, closeIntentFilter, ContextCompat.RECEIVER_EXPORTED);
}
@VisibleForTesting
public static @NonNull Map<String, String> extractHeaders(@Nullable Bundle headersBundle) {
if (headersBundle == null) {
return Collections.emptyMap();
}
final Map<String, String> headersMap = new HashMap<>();
for (String key : headersBundle.keySet()) {
final String value = headersBundle.getString(key);
headersMap.put(key, value);
}
return headersMap;
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
@Override
public boolean onKeyDown(int keyCode, @Nullable KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@VisibleForTesting static final String URL_EXTRA = "url";
@VisibleForTesting static final String ENABLE_JS_EXTRA = "enableJavaScript";
@VisibleForTesting static final String ENABLE_DOM_EXTRA = "enableDomStorage";
/* Hides the constants used to forward data to the Activity instance. */
public static @NonNull Intent createIntent(
@NonNull Context context,
@NonNull String url,
boolean enableJavaScript,
boolean enableDomStorage,
@NonNull Bundle headersBundle) {
return new Intent(context, WebViewActivity.class)
.putExtra(URL_EXTRA, url)
.putExtra(ENABLE_JS_EXTRA, enableJavaScript)
.putExtra(ENABLE_DOM_EXTRA, enableDomStorage)
.putExtra(Browser.EXTRA_HEADERS, headersBundle);
}
}
| packages/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/WebViewActivity.java/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/WebViewActivity.java",
"repo_id": "packages",
"token_count": 2479
} | 1,036 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=false
| packages/packages/url_launcher/url_launcher_android/example/android/gradle.properties/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_android/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 30
} | 1,037 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:flutter/services.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'src/messages.g.dart';
/// An implementation of [UrlLauncherPlatform] for iOS.
class UrlLauncherIOS extends UrlLauncherPlatform {
/// Creates a new plugin implementation instance.
UrlLauncherIOS({
@visibleForTesting UrlLauncherApi? api,
}) : _hostApi = api ?? UrlLauncherApi();
final UrlLauncherApi _hostApi;
/// Registers this class as the default instance of [UrlLauncherPlatform].
static void registerWith() {
UrlLauncherPlatform.instance = UrlLauncherIOS();
}
@override
final LinkDelegate? linkDelegate = null;
@override
Future<bool> canLaunch(String url) async {
final LaunchResult result = await _hostApi.canLaunchUrl(url);
return _mapLaunchResult(result);
}
@override
Future<void> closeWebView() {
return _hostApi.closeSafariViewController();
}
@override
Future<bool> launch(
String url, {
required bool useSafariVC,
required bool useWebView,
required bool enableJavaScript,
required bool enableDomStorage,
required bool universalLinksOnly,
required Map<String, String> headers,
String? webOnlyWindowName,
}) async {
final PreferredLaunchMode mode;
if (useSafariVC) {
mode = PreferredLaunchMode.inAppBrowserView;
} else if (universalLinksOnly) {
mode = PreferredLaunchMode.externalNonBrowserApplication;
} else {
mode = PreferredLaunchMode.externalApplication;
}
return launchUrl(
url,
LaunchOptions(
mode: mode,
webViewConfiguration: InAppWebViewConfiguration(
enableDomStorage: enableDomStorage,
enableJavaScript: enableJavaScript,
headers: headers)));
}
@override
Future<bool> launchUrl(String url, LaunchOptions options) async {
final bool inApp;
switch (options.mode) {
case PreferredLaunchMode.inAppWebView:
case PreferredLaunchMode.inAppBrowserView:
// The iOS implementation doesn't distinguish between these two modes;
// both are treated as inAppBrowserView.
inApp = true;
case PreferredLaunchMode.externalApplication:
case PreferredLaunchMode.externalNonBrowserApplication:
inApp = false;
case PreferredLaunchMode.platformDefault:
// Intentionally treat any new values as platformDefault; support for any
// new mode requires intentional opt-in, otherwise falling back is the
// documented behavior.
// ignore: no_default_cases
default:
// By default, open web URLs in the application.
inApp = url.startsWith('http:') || url.startsWith('https:');
break;
}
if (inApp) {
return _mapInAppLoadResult(
await _hostApi.openUrlInSafariViewController(url),
url: url);
} else {
return _mapLaunchResult(await _hostApi.launchUrl(url,
options.mode == PreferredLaunchMode.externalNonBrowserApplication));
}
}
@override
Future<bool> supportsMode(PreferredLaunchMode mode) async {
switch (mode) {
case PreferredLaunchMode.platformDefault:
case PreferredLaunchMode.inAppWebView:
case PreferredLaunchMode.inAppBrowserView:
case PreferredLaunchMode.externalApplication:
case PreferredLaunchMode.externalNonBrowserApplication:
return true;
// Default is a desired behavior here since support for new modes is
// always opt-in, and the enum lives in a different package, so silently
// adding "false" for new values is the correct behavior.
// ignore: no_default_cases
default:
return false;
}
}
@override
Future<bool> supportsCloseForMode(PreferredLaunchMode mode) async {
return mode == PreferredLaunchMode.inAppWebView ||
mode == PreferredLaunchMode.inAppBrowserView;
}
bool _mapLaunchResult(LaunchResult result) {
switch (result) {
case LaunchResult.success:
return true;
case LaunchResult.failure:
return false;
case LaunchResult.invalidUrl:
throw _invalidUrlException();
}
}
bool _mapInAppLoadResult(InAppLoadResult result, {required String url}) {
switch (result) {
case InAppLoadResult.success:
return true;
case InAppLoadResult.failedToLoad:
throw _failedSafariViewControllerLoadException(url);
case InAppLoadResult.invalidUrl:
throw _invalidUrlException();
}
}
// TODO(stuartmorgan): Remove this as part of standardizing error handling.
// See https://github.com/flutter/flutter/issues/127665
//
// This PlatformException (including the exact string details, since those
// are a defacto part of the API) is for compatibility with the previous
// native implementation.
PlatformException _invalidUrlException() {
throw PlatformException(
code: 'argument_error',
message: 'Unable to parse URL',
);
}
// TODO(stuartmorgan): Remove this as part of standardizing error handling.
// See https://github.com/flutter/flutter/issues/127665
//
// This PlatformException (including the exact string details, since those
// are a defacto part of the API) is for compatibility with the previous
// native implementation.
PlatformException _failedSafariViewControllerLoadException(String url) {
throw PlatformException(
code: 'Error',
message: 'Error while launching $url',
);
}
}
| packages/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart",
"repo_id": "packages",
"token_count": 1978
} | 1,038 |
name: url_launcher_linux
description: Linux implementation of the url_launcher plugin.
repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher_linux
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22
version: 3.1.1
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
implements: url_launcher
platforms:
linux:
pluginClass: UrlLauncherPlugin
dartPluginClass: UrlLauncherLinux
dependencies:
flutter:
sdk: flutter
url_launcher_platform_interface: ^2.2.0
dev_dependencies:
flutter_test:
sdk: flutter
test: ^1.16.3
topics:
- links
- os-integration
- url-launcher
- urls
| packages/packages/url_launcher/url_launcher_linux/pubspec.yaml/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_linux/pubspec.yaml",
"repo_id": "packages",
"token_count": 306
} | 1,039 |
// 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',
cppOptions: CppOptions(namespace: 'url_launcher_windows'),
cppHeaderOut: 'windows/messages.g.h',
cppSourceOut: 'windows/messages.g.cpp',
copyrightHeader: 'pigeons/copyright.txt',
))
@HostApi(dartHostTestHandler: 'TestUrlLauncherApi')
abstract class UrlLauncherApi {
bool canLaunchUrl(String url);
bool launchUrl(String url);
}
| packages/packages/url_launcher/url_launcher_windows/pigeons/messages.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_windows/pigeons/messages.dart",
"repo_id": "packages",
"token_count": 214
} | 1,040 |
// 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 (v9.2.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, 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:video_player_android/src/messages.g.dart';
class _TestHostVideoPlayerApiCodec extends StandardMessageCodec {
const _TestHostVideoPlayerApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is CreateMessage) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is LoopingMessage) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is MixWithOthersMessage) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else if (value is PlaybackSpeedMessage) {
buffer.putUint8(131);
writeValue(buffer, value.encode());
} else if (value is PositionMessage) {
buffer.putUint8(132);
writeValue(buffer, value.encode());
} else if (value is TextureMessage) {
buffer.putUint8(133);
writeValue(buffer, value.encode());
} else if (value is VolumeMessage) {
buffer.putUint8(134);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return CreateMessage.decode(readValue(buffer)!);
case 129:
return LoopingMessage.decode(readValue(buffer)!);
case 130:
return MixWithOthersMessage.decode(readValue(buffer)!);
case 131:
return PlaybackSpeedMessage.decode(readValue(buffer)!);
case 132:
return PositionMessage.decode(readValue(buffer)!);
case 133:
return TextureMessage.decode(readValue(buffer)!);
case 134:
return VolumeMessage.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
abstract class TestHostVideoPlayerApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = _TestHostVideoPlayerApiCodec();
void initialize();
TextureMessage create(CreateMessage msg);
void dispose(TextureMessage msg);
void setLooping(LoopingMessage msg);
void setVolume(VolumeMessage msg);
void setPlaybackSpeed(PlaybackSpeedMessage msg);
void play(TextureMessage msg);
PositionMessage position(TextureMessage msg);
void seekTo(PositionMessage msg);
void pause(TextureMessage msg);
void setMixWithOthers(MixWithOthersMessage msg);
static void setup(TestHostVideoPlayerApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.initialize', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
// ignore message
api.initialize();
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.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.AndroidVideoPlayerApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final CreateMessage? arg_msg = (args[0] as CreateMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.create was null, expected non-null CreateMessage.');
final TextureMessage output = api.create(arg_msg!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.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.AndroidVideoPlayerApi.dispose was null.');
final List<Object?> args = (message as List<Object?>?)!;
final TextureMessage? arg_msg = (args[0] as TextureMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.dispose was null, expected non-null TextureMessage.');
api.dispose(arg_msg!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.setLooping', 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.AndroidVideoPlayerApi.setLooping was null.');
final List<Object?> args = (message as List<Object?>?)!;
final LoopingMessage? arg_msg = (args[0] as LoopingMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setLooping was null, expected non-null LoopingMessage.');
api.setLooping(arg_msg!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.setVolume', 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.AndroidVideoPlayerApi.setVolume was null.');
final List<Object?> args = (message as List<Object?>?)!;
final VolumeMessage? arg_msg = (args[0] as VolumeMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setVolume was null, expected non-null VolumeMessage.');
api.setVolume(arg_msg!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.setPlaybackSpeed', 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.AndroidVideoPlayerApi.setPlaybackSpeed was null.');
final List<Object?> args = (message as List<Object?>?)!;
final PlaybackSpeedMessage? arg_msg =
(args[0] as PlaybackSpeedMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setPlaybackSpeed was null, expected non-null PlaybackSpeedMessage.');
api.setPlaybackSpeed(arg_msg!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.play', 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.AndroidVideoPlayerApi.play was null.');
final List<Object?> args = (message as List<Object?>?)!;
final TextureMessage? arg_msg = (args[0] as TextureMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.play was null, expected non-null TextureMessage.');
api.play(arg_msg!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.position', 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.AndroidVideoPlayerApi.position was null.');
final List<Object?> args = (message as List<Object?>?)!;
final TextureMessage? arg_msg = (args[0] as TextureMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.position was null, expected non-null TextureMessage.');
final PositionMessage output = api.position(arg_msg!);
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.seekTo', 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.AndroidVideoPlayerApi.seekTo was null.');
final List<Object?> args = (message as List<Object?>?)!;
final PositionMessage? arg_msg = (args[0] as PositionMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.seekTo was null, expected non-null PositionMessage.');
api.seekTo(arg_msg!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.pause', 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.AndroidVideoPlayerApi.pause was null.');
final List<Object?> args = (message as List<Object?>?)!;
final TextureMessage? arg_msg = (args[0] as TextureMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.pause was null, expected non-null TextureMessage.');
api.pause(arg_msg!);
return <Object?>[];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.AndroidVideoPlayerApi.setMixWithOthers', 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.AndroidVideoPlayerApi.setMixWithOthers was null.');
final List<Object?> args = (message as List<Object?>?)!;
final MixWithOthersMessage? arg_msg =
(args[0] as MixWithOthersMessage?);
assert(arg_msg != null,
'Argument for dev.flutter.pigeon.AndroidVideoPlayerApi.setMixWithOthers was null, expected non-null MixWithOthersMessage.');
api.setMixWithOthers(arg_msg!);
return <Object?>[];
});
}
}
}
}
| packages/packages/video_player/video_player_android/test/test_api.g.dart/0 | {
"file_path": "packages/packages/video_player/video_player_android/test/test_api.g.dart",
"repo_id": "packages",
"token_count": 6029
} | 1,041 |
// 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 (v13.0.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import "messages.g.h"
#if TARGET_OS_OSX
#import <FlutterMacOS/FlutterMacOS.h>
#else
#import <Flutter/Flutter.h>
#endif
#if !__has_feature(objc_arc)
#error File requires ARC to be enabled.
#endif
static NSArray *wrapResult(id result, FlutterError *error) {
if (error) {
return @[
error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null]
];
}
return @[ result ?: [NSNull null] ];
}
static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) {
id result = array[key];
return (result == [NSNull null]) ? nil : result;
}
@interface FVPTextureMessage ()
+ (FVPTextureMessage *)fromList:(NSArray *)list;
+ (nullable FVPTextureMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FVPLoopingMessage ()
+ (FVPLoopingMessage *)fromList:(NSArray *)list;
+ (nullable FVPLoopingMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FVPVolumeMessage ()
+ (FVPVolumeMessage *)fromList:(NSArray *)list;
+ (nullable FVPVolumeMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FVPPlaybackSpeedMessage ()
+ (FVPPlaybackSpeedMessage *)fromList:(NSArray *)list;
+ (nullable FVPPlaybackSpeedMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FVPPositionMessage ()
+ (FVPPositionMessage *)fromList:(NSArray *)list;
+ (nullable FVPPositionMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FVPCreateMessage ()
+ (FVPCreateMessage *)fromList:(NSArray *)list;
+ (nullable FVPCreateMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FVPMixWithOthersMessage ()
+ (FVPMixWithOthersMessage *)fromList:(NSArray *)list;
+ (nullable FVPMixWithOthersMessage *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@implementation FVPTextureMessage
+ (instancetype)makeWithTextureId:(NSInteger)textureId {
FVPTextureMessage *pigeonResult = [[FVPTextureMessage alloc] init];
pigeonResult.textureId = textureId;
return pigeonResult;
}
+ (FVPTextureMessage *)fromList:(NSArray *)list {
FVPTextureMessage *pigeonResult = [[FVPTextureMessage alloc] init];
pigeonResult.textureId = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FVPTextureMessage *)nullableFromList:(NSArray *)list {
return (list) ? [FVPTextureMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.textureId),
];
}
@end
@implementation FVPLoopingMessage
+ (instancetype)makeWithTextureId:(NSInteger)textureId isLooping:(BOOL)isLooping {
FVPLoopingMessage *pigeonResult = [[FVPLoopingMessage alloc] init];
pigeonResult.textureId = textureId;
pigeonResult.isLooping = isLooping;
return pigeonResult;
}
+ (FVPLoopingMessage *)fromList:(NSArray *)list {
FVPLoopingMessage *pigeonResult = [[FVPLoopingMessage alloc] init];
pigeonResult.textureId = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.isLooping = [GetNullableObjectAtIndex(list, 1) boolValue];
return pigeonResult;
}
+ (nullable FVPLoopingMessage *)nullableFromList:(NSArray *)list {
return (list) ? [FVPLoopingMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.textureId),
@(self.isLooping),
];
}
@end
@implementation FVPVolumeMessage
+ (instancetype)makeWithTextureId:(NSInteger)textureId volume:(double)volume {
FVPVolumeMessage *pigeonResult = [[FVPVolumeMessage alloc] init];
pigeonResult.textureId = textureId;
pigeonResult.volume = volume;
return pigeonResult;
}
+ (FVPVolumeMessage *)fromList:(NSArray *)list {
FVPVolumeMessage *pigeonResult = [[FVPVolumeMessage alloc] init];
pigeonResult.textureId = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.volume = [GetNullableObjectAtIndex(list, 1) doubleValue];
return pigeonResult;
}
+ (nullable FVPVolumeMessage *)nullableFromList:(NSArray *)list {
return (list) ? [FVPVolumeMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.textureId),
@(self.volume),
];
}
@end
@implementation FVPPlaybackSpeedMessage
+ (instancetype)makeWithTextureId:(NSInteger)textureId speed:(double)speed {
FVPPlaybackSpeedMessage *pigeonResult = [[FVPPlaybackSpeedMessage alloc] init];
pigeonResult.textureId = textureId;
pigeonResult.speed = speed;
return pigeonResult;
}
+ (FVPPlaybackSpeedMessage *)fromList:(NSArray *)list {
FVPPlaybackSpeedMessage *pigeonResult = [[FVPPlaybackSpeedMessage alloc] init];
pigeonResult.textureId = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.speed = [GetNullableObjectAtIndex(list, 1) doubleValue];
return pigeonResult;
}
+ (nullable FVPPlaybackSpeedMessage *)nullableFromList:(NSArray *)list {
return (list) ? [FVPPlaybackSpeedMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.textureId),
@(self.speed),
];
}
@end
@implementation FVPPositionMessage
+ (instancetype)makeWithTextureId:(NSInteger)textureId position:(NSInteger)position {
FVPPositionMessage *pigeonResult = [[FVPPositionMessage alloc] init];
pigeonResult.textureId = textureId;
pigeonResult.position = position;
return pigeonResult;
}
+ (FVPPositionMessage *)fromList:(NSArray *)list {
FVPPositionMessage *pigeonResult = [[FVPPositionMessage alloc] init];
pigeonResult.textureId = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.position = [GetNullableObjectAtIndex(list, 1) integerValue];
return pigeonResult;
}
+ (nullable FVPPositionMessage *)nullableFromList:(NSArray *)list {
return (list) ? [FVPPositionMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.textureId),
@(self.position),
];
}
@end
@implementation FVPCreateMessage
+ (instancetype)makeWithAsset:(nullable NSString *)asset
uri:(nullable NSString *)uri
packageName:(nullable NSString *)packageName
formatHint:(nullable NSString *)formatHint
httpHeaders:(NSDictionary<NSString *, NSString *> *)httpHeaders {
FVPCreateMessage *pigeonResult = [[FVPCreateMessage alloc] init];
pigeonResult.asset = asset;
pigeonResult.uri = uri;
pigeonResult.packageName = packageName;
pigeonResult.formatHint = formatHint;
pigeonResult.httpHeaders = httpHeaders;
return pigeonResult;
}
+ (FVPCreateMessage *)fromList:(NSArray *)list {
FVPCreateMessage *pigeonResult = [[FVPCreateMessage alloc] init];
pigeonResult.asset = GetNullableObjectAtIndex(list, 0);
pigeonResult.uri = GetNullableObjectAtIndex(list, 1);
pigeonResult.packageName = GetNullableObjectAtIndex(list, 2);
pigeonResult.formatHint = GetNullableObjectAtIndex(list, 3);
pigeonResult.httpHeaders = GetNullableObjectAtIndex(list, 4);
return pigeonResult;
}
+ (nullable FVPCreateMessage *)nullableFromList:(NSArray *)list {
return (list) ? [FVPCreateMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.asset ?: [NSNull null],
self.uri ?: [NSNull null],
self.packageName ?: [NSNull null],
self.formatHint ?: [NSNull null],
self.httpHeaders ?: [NSNull null],
];
}
@end
@implementation FVPMixWithOthersMessage
+ (instancetype)makeWithMixWithOthers:(BOOL)mixWithOthers {
FVPMixWithOthersMessage *pigeonResult = [[FVPMixWithOthersMessage alloc] init];
pigeonResult.mixWithOthers = mixWithOthers;
return pigeonResult;
}
+ (FVPMixWithOthersMessage *)fromList:(NSArray *)list {
FVPMixWithOthersMessage *pigeonResult = [[FVPMixWithOthersMessage alloc] init];
pigeonResult.mixWithOthers = [GetNullableObjectAtIndex(list, 0) boolValue];
return pigeonResult;
}
+ (nullable FVPMixWithOthersMessage *)nullableFromList:(NSArray *)list {
return (list) ? [FVPMixWithOthersMessage fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.mixWithOthers),
];
}
@end
@interface FVPAVFoundationVideoPlayerApiCodecReader : FlutterStandardReader
@end
@implementation FVPAVFoundationVideoPlayerApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FVPCreateMessage fromList:[self readValue]];
case 129:
return [FVPLoopingMessage fromList:[self readValue]];
case 130:
return [FVPMixWithOthersMessage fromList:[self readValue]];
case 131:
return [FVPPlaybackSpeedMessage fromList:[self readValue]];
case 132:
return [FVPPositionMessage fromList:[self readValue]];
case 133:
return [FVPTextureMessage fromList:[self readValue]];
case 134:
return [FVPVolumeMessage fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FVPAVFoundationVideoPlayerApiCodecWriter : FlutterStandardWriter
@end
@implementation FVPAVFoundationVideoPlayerApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FVPCreateMessage class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FVPLoopingMessage class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FVPMixWithOthersMessage class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FVPPlaybackSpeedMessage class]]) {
[self writeByte:131];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FVPPositionMessage class]]) {
[self writeByte:132];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FVPTextureMessage class]]) {
[self writeByte:133];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FVPVolumeMessage class]]) {
[self writeByte:134];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FVPAVFoundationVideoPlayerApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FVPAVFoundationVideoPlayerApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FVPAVFoundationVideoPlayerApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FVPAVFoundationVideoPlayerApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FVPAVFoundationVideoPlayerApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FVPAVFoundationVideoPlayerApiCodecReaderWriter *readerWriter =
[[FVPAVFoundationVideoPlayerApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpFVPAVFoundationVideoPlayerApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FVPAVFoundationVideoPlayerApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.initialize"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(initialize:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(initialize:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api initialize:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.create"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(create:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(create:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPCreateMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
FVPTextureMessage *output = [api create:arg_msg error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.dispose"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(dispose:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(dispose:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPTextureMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api dispose:arg_msg error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setLooping"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(setLooping:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(setLooping:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPLoopingMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api setLooping:arg_msg error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.setVolume"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(setVolume:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(setVolume:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPVolumeMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api setVolume:arg_msg error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi."
@"setPlaybackSpeed"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setPlaybackSpeed:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to "
@"@selector(setPlaybackSpeed:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPPlaybackSpeedMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api setPlaybackSpeed:arg_msg error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.play"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(play:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(play:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPTextureMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api play:arg_msg error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.position"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(position:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(position:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPTextureMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
FVPPositionMessage *output = [api position:arg_msg error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.seekTo"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(seekTo:completion:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to "
@"@selector(seekTo:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPPositionMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
[api seekTo:arg_msg
completion:^(FlutterError *_Nullable error) {
callback(wrapResult(nil, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi.pause"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(pause:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to @selector(pause:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPTextureMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api pause:arg_msg error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.video_player_avfoundation.AVFoundationVideoPlayerApi."
@"setMixWithOthers"
binaryMessenger:binaryMessenger
codec:FVPAVFoundationVideoPlayerApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setMixWithOthers:error:)],
@"FVPAVFoundationVideoPlayerApi api (%@) doesn't respond to "
@"@selector(setMixWithOthers:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
FVPMixWithOthersMessage *arg_msg = GetNullableObjectAtIndex(args, 0);
FlutterError *error;
[api setMixWithOthers:arg_msg error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
| packages/packages/video_player/video_player_avfoundation/darwin/Classes/messages.g.m/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/messages.g.m",
"repo_id": "packages",
"token_count": 8255
} | 1,042 |
// 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:js_interop';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
import 'package:web/helpers.dart';
import 'package:web/web.dart' as web;
import 'duration_utils.dart';
import 'pkg_web_tweaks.dart';
// An error code value to error name Map.
// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/code
const Map<int, String> _kErrorValueToErrorName = <int, String>{
1: 'MEDIA_ERR_ABORTED',
2: 'MEDIA_ERR_NETWORK',
3: 'MEDIA_ERR_DECODE',
4: 'MEDIA_ERR_SRC_NOT_SUPPORTED',
};
// An error code value to description Map.
// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/code
const Map<int, String> _kErrorValueToErrorDescription = <int, String>{
1: 'The user canceled the fetching of the video.',
2: 'A network error occurred while fetching the video, despite having previously been available.',
3: 'An error occurred while trying to decode the video, despite having previously been determined to be usable.',
4: 'The video has been found to be unsuitable (missing or in a format not supported by your browser).',
};
// The default error message, when the error is an empty string
// See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/message
const String _kDefaultErrorMessage =
'No further diagnostic information can be determined or provided.';
/// Wraps a [web.HTMLVideoElement] so its API complies with what is expected by the plugin.
class VideoPlayer {
/// Create a [VideoPlayer] from a [web.HTMLVideoElement] instance.
VideoPlayer({
required web.HTMLVideoElement videoElement,
@visibleForTesting StreamController<VideoEvent>? eventController,
}) : _videoElement = videoElement,
_eventController = eventController ?? StreamController<VideoEvent>();
final StreamController<VideoEvent> _eventController;
final web.HTMLVideoElement _videoElement;
web.EventHandler? _onContextMenu;
bool _isInitialized = false;
bool _isBuffering = false;
/// Returns the [Stream] of [VideoEvent]s from the inner [web.HTMLVideoElement].
Stream<VideoEvent> get events => _eventController.stream;
/// Initializes the wrapped [web.HTMLVideoElement].
///
/// This method sets the required DOM attributes so videos can [play] programmatically,
/// and attaches listeners to the internal events from the [web.HTMLVideoElement]
/// to react to them / expose them through the [VideoPlayer.events] stream.
///
/// The [src] parameter is the URL of the video. It is passed in from the plugin
/// `create` method so it can be set in the VideoElement *last*. This way, all
/// the event listeners needed to integrate the videoElement with the plugin
/// are attached before any events start firing (events start to fire when the
/// `src` attribute is set).
///
/// The `src` parameter is nullable for testing purposes.
void initialize({
String? src,
}) {
_videoElement
..autoplay = false
..controls = false
..playsInline = true;
_videoElement.onCanPlay.listen(_onVideoElementInitialization);
// Needed for Safari iOS 17, which may not send `canplay`.
_videoElement.onLoadedMetadata.listen(_onVideoElementInitialization);
_videoElement.onCanPlayThrough.listen((dynamic _) {
setBuffering(false);
});
_videoElement.onPlaying.listen((dynamic _) {
setBuffering(false);
});
_videoElement.onWaiting.listen((dynamic _) {
setBuffering(true);
_sendBufferingRangesUpdate();
});
// The error event fires when some form of error occurs while attempting to load or perform the media.
_videoElement.onError.listen((web.Event _) {
setBuffering(false);
// The Event itself (_) doesn't contain info about the actual error.
// We need to look at the HTMLMediaElement.error.
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error
final web.MediaError error = _videoElement.error!;
_eventController.addError(PlatformException(
code: _kErrorValueToErrorName[error.code]!,
message: error.message != '' ? error.message : _kDefaultErrorMessage,
details: _kErrorValueToErrorDescription[error.code],
));
});
_videoElement.onPlay.listen((dynamic _) {
_eventController.add(VideoEvent(
eventType: VideoEventType.isPlayingStateUpdate,
isPlaying: true,
));
});
_videoElement.onPause.listen((dynamic _) {
_eventController.add(VideoEvent(
eventType: VideoEventType.isPlayingStateUpdate,
isPlaying: false,
));
});
_videoElement.onEnded.listen((dynamic _) {
setBuffering(false);
_eventController.add(VideoEvent(eventType: VideoEventType.completed));
});
// The `src` of the _videoElement is the last property that is set, so all
// the listeners for the events that the plugin cares about are attached.
if (src != null) {
_videoElement.src = src;
}
}
/// Attempts to play the video.
///
/// If this method is called programmatically (without user interaction), it
/// might fail unless the video is completely muted (or it has no Audio tracks).
///
/// When called from some user interaction (a tap on a button), the above
/// limitation should disappear.
Future<void> play() {
return _videoElement.play().toDart.catchError((Object e) {
// play() attempts to begin playback of the media. It returns
// a Promise which can get rejected in case of failure to begin
// playback for any reason, such as permission issues.
// The rejection handler is called with a DOMException.
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play
final web.DOMException exception = e as web.DOMException;
_eventController.addError(PlatformException(
code: exception.name,
message: exception.message,
));
return null;
}, test: (Object e) => e is web.DOMException);
}
/// Pauses the video in the current position.
void pause() {
_videoElement.pause();
}
/// Controls whether the video should start again after it finishes.
// ignore: use_setters_to_change_properties
void setLooping(bool value) {
_videoElement.loop = value;
}
/// Sets the volume at which the media will be played.
///
/// Values must fall between 0 and 1, where 0 is muted and 1 is the loudest.
///
/// When volume is set to 0, the `muted` property is also applied to the
/// [web.HTMLVideoElement]. This is required for auto-play on the web.
void setVolume(double volume) {
assert(volume >= 0 && volume <= 1);
// TODO(ditman): Do we need to expose a "muted" API?
// https://github.com/flutter/flutter/issues/60721
_videoElement.muted = !(volume > 0.0);
_videoElement.volume = volume;
}
/// Sets the playback `speed`.
///
/// A `speed` of 1.0 is "normal speed," values lower than 1.0 make the media
/// play slower than normal, higher values make it play faster.
///
/// `speed` cannot be negative.
///
/// The audio is muted when the fast forward or slow motion is outside a useful
/// range (for example, Gecko mutes the sound outside the range 0.25 to 4.0).
///
/// The pitch of the audio is corrected by default.
void setPlaybackSpeed(double speed) {
assert(speed > 0);
_videoElement.playbackRate = speed;
}
/// Moves the playback head to a new `position`.
///
/// `position` cannot be negative.
void seekTo(Duration position) {
assert(!position.isNegative);
// Don't seek if video is already at target position.
//
// This is needed because the core plugin will pause and seek to the end of
// the video when it finishes, and that causes an infinite loop of `ended`
// events on the web.
//
// See: https://github.com/flutter/flutter/issues/77674
if (position == _videoElementCurrentTime) {
return;
}
_videoElement.currentTime = position.inMilliseconds.toDouble() / 1000;
}
/// Returns the current playback head position as a [Duration].
Duration getPosition() {
_sendBufferingRangesUpdate();
return _videoElementCurrentTime;
}
/// Returns the currentTime of the underlying video element.
Duration get _videoElementCurrentTime {
return Duration(milliseconds: (_videoElement.currentTime * 1000).round());
}
/// Sets options
Future<void> setOptions(VideoPlayerWebOptions options) async {
// In case this method is called multiple times, reset options.
_resetOptions();
if (options.controls.enabled) {
_videoElement.controls = true;
final String controlsList = options.controls.controlsList;
if (controlsList.isNotEmpty) {
_videoElement.controlsList = controlsList.toJS;
}
if (!options.controls.allowPictureInPicture) {
_videoElement.disablePictureInPicture = true.toJS;
}
}
if (!options.allowContextMenu) {
_onContextMenu = ((web.Event event) => event.preventDefault()).toJS;
_videoElement.addEventListener('contextmenu', _onContextMenu);
}
if (!options.allowRemotePlayback) {
_videoElement.disableRemotePlayback = true.toJS;
}
}
void _resetOptions() {
_videoElement.controls = false;
_videoElement.removeAttribute('controlsList');
_videoElement.removeAttribute('disablePictureInPicture');
if (_onContextMenu != null) {
_videoElement.removeEventListener('contextmenu', _onContextMenu);
_onContextMenu = null;
}
_videoElement.removeAttribute('disableRemotePlayback');
}
/// Disposes of the current [web.HTMLVideoElement].
void dispose() {
_videoElement.removeAttribute('src');
if (_onContextMenu != null) {
_videoElement.removeEventListener('contextmenu', _onContextMenu);
_onContextMenu = null;
}
_videoElement.load();
}
// Handler to mark (and broadcast) when this player [_isInitialized].
//
// (Used as a JS event handler for "canplay" and "loadedmetadata")
//
// This function can be called multiple times by different JS Events, but it'll
// only broadcast an "initialized" event the first time it's called, and ignore
// the rest of the calls.
void _onVideoElementInitialization(Object? _) {
if (!_isInitialized) {
_isInitialized = true;
_sendInitialized();
}
}
// Sends an [VideoEventType.initialized] [VideoEvent] with info about the wrapped video.
void _sendInitialized() {
final Duration? duration =
convertNumVideoDurationToPluginDuration(_videoElement.duration);
final Size? size = _videoElement.videoHeight.isFinite
? Size(
_videoElement.videoWidth.toDouble(),
_videoElement.videoHeight.toDouble(),
)
: null;
_eventController.add(
VideoEvent(
eventType: VideoEventType.initialized,
duration: duration,
size: size,
),
);
}
/// Caches the current "buffering" state of the video.
///
/// If the current buffering state is different from the previous one
/// ([_isBuffering]), this dispatches a [VideoEvent].
@visibleForTesting
void setBuffering(bool buffering) {
if (_isBuffering != buffering) {
_isBuffering = buffering;
_eventController.add(VideoEvent(
eventType: _isBuffering
? VideoEventType.bufferingStart
: VideoEventType.bufferingEnd,
));
}
}
// Broadcasts the [web.HTMLVideoElement.buffered] status through the [events] stream.
void _sendBufferingRangesUpdate() {
_eventController.add(VideoEvent(
buffered: _toDurationRange(_videoElement.buffered),
eventType: VideoEventType.bufferingUpdate,
));
}
// Converts from [html.TimeRanges] to our own List<DurationRange>.
List<DurationRange> _toDurationRange(web.TimeRanges buffered) {
final List<DurationRange> durationRange = <DurationRange>[];
for (int i = 0; i < buffered.length; i++) {
durationRange.add(DurationRange(
Duration(milliseconds: (buffered.start(i) * 1000).round()),
Duration(milliseconds: (buffered.end(i) * 1000).round()),
));
}
return durationRange;
}
}
| packages/packages/video_player/video_player_web/lib/src/video_player.dart/0 | {
"file_path": "packages/packages/video_player/video_player_web/lib/src/video_player.dart",
"repo_id": "packages",
"token_count": 4120
} | 1,043 |
// 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.
/// Compilation options for bulding a Flutter web app.
///
/// This object holds metadata that is used to determine how the benchmark app
/// should be built.
class CompilationOptions {
/// Creates a [CompilationOptions] object.
const CompilationOptions({
this.renderer = WebRenderer.canvaskit,
this.useWasm = false,
});
/// The renderer to use for the build.
final WebRenderer renderer;
/// Whether to build the app with dart2wasm.
final bool useWasm;
@override
String toString() {
return '(renderer: ${renderer.name}, compiler: ${useWasm ? 'dart2wasm' : 'dart2js'})';
}
}
/// The possible types of web renderers Flutter can build for.
enum WebRenderer {
/// The HTML web renderer.
html,
/// The CanvasKit web renderer.
canvaskit,
/// The SKIA Wasm web renderer.
skwasm,
}
| packages/packages/web_benchmarks/lib/src/compilation_options.dart/0 | {
"file_path": "packages/packages/web_benchmarks/lib/src/compilation_options.dart",
"repo_id": "packages",
"token_count": 312
} | 1,044 |
// 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:web_benchmarks/client.dart';
import 'runner.dart';
class SimpleRecorder extends AppRecorder {
SimpleRecorder() : super(benchmarkName: 'simple');
@override
Future<void> automate() async {
// Do nothing.
}
}
Future<void> main() async {
await runBenchmarks(<String, RecorderFactory>{
'simple': () => SimpleRecorder(),
});
}
| packages/packages/web_benchmarks/testing/test_app/lib/benchmarks/runner_simple.dart/0 | {
"file_path": "packages/packages/web_benchmarks/testing/test_app/lib/benchmarks/runner_simple.dart",
"repo_id": "packages",
"token_count": 182
} | 1,045 |
// 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.os.Handler;
import android.os.Looper;
import android.webkit.JavascriptInterface;
import androidx.annotation.NonNull;
/**
* Added as a JavaScript interface to the WebView for any JavaScript channel that the Dart code sets
* up.
*
* <p>Exposes a single method named `postMessage` to JavaScript, which sends a message to the Dart
* code.
*/
public class JavaScriptChannel {
private final Handler platformThreadHandler;
final String javaScriptChannelName;
private final JavaScriptChannelFlutterApiImpl flutterApi;
/**
* Creates a {@link JavaScriptChannel} that passes arguments of callback methods to Dart.
*
* @param flutterApi the Flutter Api to which JS messages are sent
* @param channelName JavaScript channel the message was sent through
* @param platformThreadHandler handles making callbacks on the desired thread
*/
public JavaScriptChannel(
@NonNull JavaScriptChannelFlutterApiImpl flutterApi,
@NonNull String channelName,
@NonNull Handler platformThreadHandler) {
this.flutterApi = flutterApi;
this.javaScriptChannelName = channelName;
this.platformThreadHandler = platformThreadHandler;
}
// Suppressing unused warning as this is invoked from JavaScript.
@SuppressWarnings("unused")
@JavascriptInterface
public void postMessage(@NonNull final String message) {
final Runnable postMessageRunnable =
() -> flutterApi.postMessage(JavaScriptChannel.this, message, reply -> {});
if (platformThreadHandler.getLooper() == Looper.myLooper()) {
postMessageRunnable.run();
} else {
platformThreadHandler.post(postMessageRunnable);
}
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/JavaScriptChannel.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/JavaScriptChannel.java",
"repo_id": "packages",
"token_count": 546
} | 1,046 |
// 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 android.util;
import java.util.HashMap;
// Creates an implementation of LongSparseArray that can be used with unittests and the JVM.
// Typically android.util.LongSparseArray does nothing when not used with an Android environment.
public class LongSparseArray<E> {
private final HashMap<Long, E> mHashMap;
public LongSparseArray() {
mHashMap = new HashMap<>();
}
public void append(long key, E value) {
mHashMap.put(key, value);
}
public E get(long key) {
return mHashMap.get(key);
}
public void remove(long key) {
mHashMap.remove(key);
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/android/util/LongSparseArray.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/android/util/LongSparseArray.java",
"repo_id": "packages",
"token_count": 239
} | 1,047 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_android/src/android_webview.dart'
as android_webview;
import 'package:webview_flutter_android/src/android_webview_api_impls.dart';
import 'package:webview_flutter_android/src/instance_manager.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'android_webview_cookie_manager_test.mocks.dart';
import 'test_android_webview.g.dart';
@GenerateMocks(<Type>[
android_webview.CookieManager,
AndroidWebViewController,
TestInstanceManagerHostApi,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the call to clear the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
test('clearCookies should call android_webview.clearCookies', () async {
final android_webview.CookieManager mockCookieManager = MockCookieManager();
when(mockCookieManager.removeAllCookies())
.thenAnswer((_) => Future<bool>.value(true));
final AndroidWebViewCookieManagerCreationParams params =
AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
const PlatformWebViewCookieManagerCreationParams());
final bool hasClearedCookies = await AndroidWebViewCookieManager(params,
cookieManager: mockCookieManager)
.clearCookies();
expect(hasClearedCookies, true);
verify(mockCookieManager.removeAllCookies());
});
test('setCookie should throw ArgumentError for cookie with invalid path', () {
final AndroidWebViewCookieManagerCreationParams params =
AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
const PlatformWebViewCookieManagerCreationParams());
final AndroidWebViewCookieManager androidCookieManager =
AndroidWebViewCookieManager(params, cookieManager: MockCookieManager());
expect(
() => androidCookieManager.setCookie(const WebViewCookie(
name: 'foo',
value: 'bar',
domain: 'flutter.dev',
path: 'invalid;path',
)),
throwsA(const TypeMatcher<ArgumentError>()),
);
});
test(
'setCookie should call android_webview.setCookie with properly formatted cookie value',
() {
final android_webview.CookieManager mockCookieManager = MockCookieManager();
final AndroidWebViewCookieManagerCreationParams params =
AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
const PlatformWebViewCookieManagerCreationParams());
AndroidWebViewCookieManager(params, cookieManager: mockCookieManager)
.setCookie(const WebViewCookie(
name: 'foo&',
value: 'bar@',
domain: 'flutter.dev',
));
verify(mockCookieManager.setCookie(
'flutter.dev',
'foo%26=bar%40; path=/',
));
});
test('setAcceptThirdPartyCookies', () async {
final MockAndroidWebViewController mockController =
MockAndroidWebViewController();
final InstanceManager instanceManager =
InstanceManager(onWeakReferenceRemoved: (_) {});
android_webview.WebView.api = WebViewHostApiImpl(
instanceManager: instanceManager,
);
final android_webview.WebView webView = android_webview.WebView.detached(
instanceManager: instanceManager,
);
const int webViewIdentifier = 4;
instanceManager.addHostCreatedInstance(webView, webViewIdentifier);
when(mockController.webViewIdentifier).thenReturn(webViewIdentifier);
final AndroidWebViewCookieManagerCreationParams params =
AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
const PlatformWebViewCookieManagerCreationParams());
final android_webview.CookieManager mockCookieManager = MockCookieManager();
await AndroidWebViewCookieManager(
params,
cookieManager: mockCookieManager,
).setAcceptThirdPartyCookies(mockController, false);
verify(mockCookieManager.setAcceptThirdPartyCookies(webView, false));
android_webview.WebView.api = WebViewHostApiImpl();
});
}
| packages/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.dart",
"repo_id": "packages",
"token_count": 1598
} | 1,048 |
// 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 "FWFDataConverters.h"
#import <Flutter/Flutter.h>
NSURLRequest *_Nullable FWFNativeNSURLRequestFromRequestData(FWFNSUrlRequestData *data) {
NSURL *url = [NSURL URLWithString:data.url];
if (!url) {
return nil;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if (!request) {
return nil;
}
if (data.httpMethod) {
[request setHTTPMethod:data.httpMethod];
}
if (data.httpBody) {
[request setHTTPBody:data.httpBody.data];
}
[request setAllHTTPHeaderFields:data.allHttpHeaderFields];
return request;
}
extern NSHTTPCookie *_Nullable FWFNativeNSHTTPCookieFromCookieData(FWFNSHttpCookieData *data) {
NSMutableDictionary<NSHTTPCookiePropertyKey, id> *properties = [NSMutableDictionary dictionary];
for (int i = 0; i < data.propertyKeys.count; i++) {
NSHTTPCookiePropertyKey cookieKey =
FWFNativeNSHTTPCookiePropertyKeyFromEnumData(data.propertyKeys[i]);
if (!cookieKey) {
// Some keys aren't supported on all versions, so this ignores keys
// that require a higher version or are unsupported.
continue;
}
[properties setObject:data.propertyValues[i] forKey:cookieKey];
}
return [NSHTTPCookie cookieWithProperties:properties];
}
NSKeyValueObservingOptions FWFNativeNSKeyValueObservingOptionsFromEnumData(
FWFNSKeyValueObservingOptionsEnumData *data) {
switch (data.value) {
case FWFNSKeyValueObservingOptionsEnumNewValue:
return NSKeyValueObservingOptionNew;
case FWFNSKeyValueObservingOptionsEnumOldValue:
return NSKeyValueObservingOptionOld;
case FWFNSKeyValueObservingOptionsEnumInitialValue:
return NSKeyValueObservingOptionInitial;
case FWFNSKeyValueObservingOptionsEnumPriorNotification:
return NSKeyValueObservingOptionPrior;
}
return -1;
}
NSHTTPCookiePropertyKey _Nullable FWFNativeNSHTTPCookiePropertyKeyFromEnumData(
FWFNSHttpCookiePropertyKeyEnumData *data) {
switch (data.value) {
case FWFNSHttpCookiePropertyKeyEnumComment:
return NSHTTPCookieComment;
case FWFNSHttpCookiePropertyKeyEnumCommentUrl:
return NSHTTPCookieCommentURL;
case FWFNSHttpCookiePropertyKeyEnumDiscard:
return NSHTTPCookieDiscard;
case FWFNSHttpCookiePropertyKeyEnumDomain:
return NSHTTPCookieDomain;
case FWFNSHttpCookiePropertyKeyEnumExpires:
return NSHTTPCookieExpires;
case FWFNSHttpCookiePropertyKeyEnumMaximumAge:
return NSHTTPCookieMaximumAge;
case FWFNSHttpCookiePropertyKeyEnumName:
return NSHTTPCookieName;
case FWFNSHttpCookiePropertyKeyEnumOriginUrl:
return NSHTTPCookieOriginURL;
case FWFNSHttpCookiePropertyKeyEnumPath:
return NSHTTPCookiePath;
case FWFNSHttpCookiePropertyKeyEnumPort:
return NSHTTPCookiePort;
case FWFNSHttpCookiePropertyKeyEnumSameSitePolicy:
if (@available(iOS 13.0, *)) {
return NSHTTPCookieSameSitePolicy;
} else {
return nil;
}
case FWFNSHttpCookiePropertyKeyEnumSecure:
return NSHTTPCookieSecure;
case FWFNSHttpCookiePropertyKeyEnumValue:
return NSHTTPCookieValue;
case FWFNSHttpCookiePropertyKeyEnumVersion:
return NSHTTPCookieVersion;
}
return nil;
}
extern WKUserScript *FWFNativeWKUserScriptFromScriptData(FWFWKUserScriptData *data) {
return [[WKUserScript alloc]
initWithSource:data.source
injectionTime:FWFNativeWKUserScriptInjectionTimeFromEnumData(data.injectionTime)
forMainFrameOnly:data.isMainFrameOnly];
}
WKUserScriptInjectionTime FWFNativeWKUserScriptInjectionTimeFromEnumData(
FWFWKUserScriptInjectionTimeEnumData *data) {
switch (data.value) {
case FWFWKUserScriptInjectionTimeEnumAtDocumentStart:
return WKUserScriptInjectionTimeAtDocumentStart;
case FWFWKUserScriptInjectionTimeEnumAtDocumentEnd:
return WKUserScriptInjectionTimeAtDocumentEnd;
}
return -1;
}
WKAudiovisualMediaTypes FWFNativeWKAudiovisualMediaTypeFromEnumData(
FWFWKAudiovisualMediaTypeEnumData *data) {
switch (data.value) {
case FWFWKAudiovisualMediaTypeEnumNone:
return WKAudiovisualMediaTypeNone;
case FWFWKAudiovisualMediaTypeEnumAudio:
return WKAudiovisualMediaTypeAudio;
case FWFWKAudiovisualMediaTypeEnumVideo:
return WKAudiovisualMediaTypeVideo;
case FWFWKAudiovisualMediaTypeEnumAll:
return WKAudiovisualMediaTypeAll;
}
return -1;
}
NSString *_Nullable FWFNativeWKWebsiteDataTypeFromEnumData(FWFWKWebsiteDataTypeEnumData *data) {
switch (data.value) {
case FWFWKWebsiteDataTypeEnumCookies:
return WKWebsiteDataTypeCookies;
case FWFWKWebsiteDataTypeEnumMemoryCache:
return WKWebsiteDataTypeMemoryCache;
case FWFWKWebsiteDataTypeEnumDiskCache:
return WKWebsiteDataTypeDiskCache;
case FWFWKWebsiteDataTypeEnumOfflineWebApplicationCache:
return WKWebsiteDataTypeOfflineWebApplicationCache;
case FWFWKWebsiteDataTypeEnumLocalStorage:
return WKWebsiteDataTypeLocalStorage;
case FWFWKWebsiteDataTypeEnumSessionStorage:
return WKWebsiteDataTypeSessionStorage;
case FWFWKWebsiteDataTypeEnumWebSQLDatabases:
return WKWebsiteDataTypeWebSQLDatabases;
case FWFWKWebsiteDataTypeEnumIndexedDBDatabases:
return WKWebsiteDataTypeIndexedDBDatabases;
}
return nil;
}
FWFWKNavigationActionData *FWFWKNavigationActionDataFromNativeWKNavigationAction(
WKNavigationAction *action) {
return [FWFWKNavigationActionData
makeWithRequest:FWFNSUrlRequestDataFromNativeNSURLRequest(action.request)
targetFrame:FWFWKFrameInfoDataFromNativeWKFrameInfo(action.targetFrame)
navigationType:FWFWKNavigationTypeFromNativeWKNavigationType(action.navigationType)];
}
FWFNSUrlRequestData *FWFNSUrlRequestDataFromNativeNSURLRequest(NSURLRequest *request) {
return [FWFNSUrlRequestData
makeWithUrl:request.URL.absoluteString == nil ? @"" : request.URL.absoluteString
httpMethod:request.HTTPMethod
httpBody:request.HTTPBody
? [FlutterStandardTypedData typedDataWithBytes:request.HTTPBody]
: nil
allHttpHeaderFields:request.allHTTPHeaderFields ? request.allHTTPHeaderFields : @{}];
}
FWFWKFrameInfoData *FWFWKFrameInfoDataFromNativeWKFrameInfo(WKFrameInfo *info) {
return [FWFWKFrameInfoData
makeWithIsMainFrame:info.isMainFrame
request:FWFNSUrlRequestDataFromNativeNSURLRequest(info.request)];
}
FWFWKNavigationResponseData *FWFWKNavigationResponseDataFromNativeNavigationResponse(
WKNavigationResponse *response) {
return [FWFWKNavigationResponseData
makeWithResponse:FWFNSHttpUrlResponseDataFromNativeNSURLResponse(response.response)
forMainFrame:response.forMainFrame];
}
/// Cast the NSURLResponse object to NSHTTPURLResponse.
///
/// NSURLResponse doesn't contain the status code so it must be cast to NSHTTPURLResponse.
/// This cast will always succeed because the NSURLResponse object actually is an instance of
/// NSHTTPURLResponse. See:
/// https://developer.apple.com/documentation/foundation/nsurlresponse#overview
FWFNSHttpUrlResponseData *FWFNSHttpUrlResponseDataFromNativeNSURLResponse(NSURLResponse *response) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
return [FWFNSHttpUrlResponseData makeWithStatusCode:httpResponse.statusCode];
}
WKNavigationActionPolicy FWFNativeWKNavigationActionPolicyFromEnumData(
FWFWKNavigationActionPolicyEnumData *data) {
switch (data.value) {
case FWFWKNavigationActionPolicyEnumAllow:
return WKNavigationActionPolicyAllow;
case FWFWKNavigationActionPolicyEnumCancel:
return WKNavigationActionPolicyCancel;
}
return -1;
}
FWFNSErrorData *FWFNSErrorDataFromNativeNSError(NSError *error) {
NSMutableDictionary *userInfo;
if (error.userInfo) {
userInfo = [NSMutableDictionary dictionary];
for (NSErrorUserInfoKey key in error.userInfo.allKeys) {
NSObject *value = error.userInfo[key];
if ([value isKindOfClass:[NSString class]]) {
userInfo[key] = value;
} else {
userInfo[key] = [NSString stringWithFormat:@"Unsupported Type: %@", value.description];
}
}
}
return [FWFNSErrorData makeWithCode:error.code domain:error.domain userInfo:userInfo];
}
WKNavigationResponsePolicy FWFNativeWKNavigationResponsePolicyFromEnum(
FWFWKNavigationResponsePolicyEnum policy) {
switch (policy) {
case FWFWKNavigationResponsePolicyEnumAllow:
return WKNavigationResponsePolicyAllow;
case FWFWKNavigationResponsePolicyEnumCancel:
return WKNavigationResponsePolicyCancel;
}
return -1;
}
FWFNSKeyValueChangeKeyEnumData *FWFNSKeyValueChangeKeyEnumDataFromNativeNSKeyValueChangeKey(
NSKeyValueChangeKey key) {
if ([key isEqualToString:NSKeyValueChangeIndexesKey]) {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumIndexes];
} else if ([key isEqualToString:NSKeyValueChangeKindKey]) {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumKind];
} else if ([key isEqualToString:NSKeyValueChangeNewKey]) {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumNewValue];
} else if ([key isEqualToString:NSKeyValueChangeNotificationIsPriorKey]) {
return [FWFNSKeyValueChangeKeyEnumData
makeWithValue:FWFNSKeyValueChangeKeyEnumNotificationIsPrior];
} else if ([key isEqualToString:NSKeyValueChangeOldKey]) {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumOldValue];
} else {
return [FWFNSKeyValueChangeKeyEnumData makeWithValue:FWFNSKeyValueChangeKeyEnumUnknown];
}
return nil;
}
FWFWKScriptMessageData *FWFWKScriptMessageDataFromNativeWKScriptMessage(WKScriptMessage *message) {
return [FWFWKScriptMessageData makeWithName:message.name body:message.body];
}
FWFWKNavigationType FWFWKNavigationTypeFromNativeWKNavigationType(WKNavigationType type) {
switch (type) {
case WKNavigationTypeLinkActivated:
return FWFWKNavigationTypeLinkActivated;
case WKNavigationTypeFormSubmitted:
return FWFWKNavigationTypeFormResubmitted;
case WKNavigationTypeBackForward:
return FWFWKNavigationTypeBackForward;
case WKNavigationTypeReload:
return FWFWKNavigationTypeReload;
case WKNavigationTypeFormResubmitted:
return FWFWKNavigationTypeFormResubmitted;
case WKNavigationTypeOther:
return FWFWKNavigationTypeOther;
}
return FWFWKNavigationTypeUnknown;
}
FWFWKSecurityOriginData *FWFWKSecurityOriginDataFromNativeWKSecurityOrigin(
WKSecurityOrigin *origin) {
return [FWFWKSecurityOriginData makeWithHost:origin.host
port:origin.port
protocol:origin.protocol];
}
WKPermissionDecision FWFNativeWKPermissionDecisionFromData(FWFWKPermissionDecisionData *data) {
switch (data.value) {
case FWFWKPermissionDecisionDeny:
return WKPermissionDecisionDeny;
case FWFWKPermissionDecisionGrant:
return WKPermissionDecisionGrant;
case FWFWKPermissionDecisionPrompt:
return WKPermissionDecisionPrompt;
}
return -1;
}
FWFWKMediaCaptureTypeData *FWFWKMediaCaptureTypeDataFromNativeWKMediaCaptureType(
WKMediaCaptureType type) {
switch (type) {
case WKMediaCaptureTypeCamera:
return [FWFWKMediaCaptureTypeData makeWithValue:FWFWKMediaCaptureTypeCamera];
case WKMediaCaptureTypeMicrophone:
return [FWFWKMediaCaptureTypeData makeWithValue:FWFWKMediaCaptureTypeMicrophone];
case WKMediaCaptureTypeCameraAndMicrophone:
return [FWFWKMediaCaptureTypeData makeWithValue:FWFWKMediaCaptureTypeCameraAndMicrophone];
default:
return [FWFWKMediaCaptureTypeData makeWithValue:FWFWKMediaCaptureTypeUnknown];
}
return nil;
}
NSURLSessionAuthChallengeDisposition
FWFNativeNSURLSessionAuthChallengeDispositionFromFWFNSUrlSessionAuthChallengeDisposition(
FWFNSUrlSessionAuthChallengeDisposition value) {
switch (value) {
case FWFNSUrlSessionAuthChallengeDispositionUseCredential:
return NSURLSessionAuthChallengeUseCredential;
case FWFNSUrlSessionAuthChallengeDispositionPerformDefaultHandling:
return NSURLSessionAuthChallengePerformDefaultHandling;
case FWFNSUrlSessionAuthChallengeDispositionCancelAuthenticationChallenge:
return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
case FWFNSUrlSessionAuthChallengeDispositionRejectProtectionSpace:
return NSURLSessionAuthChallengeRejectProtectionSpace;
}
return -1;
}
NSURLCredentialPersistence FWFNativeNSURLCredentialPersistenceFromFWFNSUrlCredentialPersistence(
FWFNSUrlCredentialPersistence value) {
switch (value) {
case FWFNSUrlCredentialPersistenceNone:
return NSURLCredentialPersistenceNone;
case FWFNSUrlCredentialPersistenceSession:
return NSURLCredentialPersistenceForSession;
case FWFNSUrlCredentialPersistencePermanent:
return NSURLCredentialPersistencePermanent;
case FWFNSUrlCredentialPersistenceSynchronizable:
return NSURLCredentialPersistenceSynchronizable;
}
return -1;
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFDataConverters.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFDataConverters.m",
"repo_id": "packages",
"token_count": 4801
} | 1,049 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
#import <WebKit/WebKit.h>
#import "FWFObjectHostApi.h"
#import "FWFGeneratedWebKitApis.h"
#import "FWFInstanceManager.h"
NS_ASSUME_NONNULL_BEGIN
/// Flutter api implementation for UIScrollViewDelegate.
///
/// Handles making callbacks to Dart for a UIScrollViewDelegate.
@interface FWFScrollViewDelegateFlutterApiImpl : FWFUIScrollViewDelegateFlutterApi
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
/// Implementation of WKUIScrollViewDelegate for FWFUIScrollViewDelegateHostApiImpl.
@interface FWFScrollViewDelegate : FWFObject <UIScrollViewDelegate>
@property(readonly, nonnull, nonatomic) FWFScrollViewDelegateFlutterApiImpl *scrollViewDelegateAPI;
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
/// Host api implementation for UIScrollViewDelegate.
///
/// Handles creating UIScrollView that intercommunicate with a paired Dart object.
@interface FWFScrollViewDelegateHostApiImpl : NSObject <FWFUIScrollViewDelegateHostApi>
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
NS_ASSUME_NONNULL_END
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScrollViewDelegateHostApi.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFScrollViewDelegateHostApi.h",
"repo_id": "packages",
"token_count": 540
} | 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 <Flutter/Flutter.h>
#import <WebKit/WebKit.h>
#import "FWFGeneratedWebKitApis.h"
#import "FWFInstanceManager.h"
NS_ASSUME_NONNULL_BEGIN
/// Host api implementation for WKUserContentController.
///
/// Handles creating WKUserContentController that intercommunicate with a paired Dart object.
@interface FWFUserContentControllerHostApiImpl : NSObject <FWFWKUserContentControllerHostApi>
- (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager;
@end
NS_ASSUME_NONNULL_END
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUserContentControllerHostApi.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFUserContentControllerHostApi.h",
"repo_id": "packages",
"token_count": 203
} | 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.
// Autogenerated from Pigeon (v13.0.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
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];
}
/// Mirror of NSKeyValueObservingOptions.
///
/// See https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions?language=objc.
enum NSKeyValueObservingOptionsEnum {
newValue,
oldValue,
initialValue,
priorNotification,
}
/// Mirror of NSKeyValueChange.
///
/// See https://developer.apple.com/documentation/foundation/nskeyvaluechange?language=objc.
enum NSKeyValueChangeEnum {
setting,
insertion,
removal,
replacement,
}
/// Mirror of NSKeyValueChangeKey.
///
/// See https://developer.apple.com/documentation/foundation/nskeyvaluechangekey?language=objc.
enum NSKeyValueChangeKeyEnum {
indexes,
kind,
newValue,
notificationIsPrior,
oldValue,
unknown,
}
/// Mirror of WKUserScriptInjectionTime.
///
/// See https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime?language=objc.
enum WKUserScriptInjectionTimeEnum {
atDocumentStart,
atDocumentEnd,
}
/// Mirror of WKAudiovisualMediaTypes.
///
/// See [WKAudiovisualMediaTypes](https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes?language=objc).
enum WKAudiovisualMediaTypeEnum {
none,
audio,
video,
all,
}
/// Mirror of WKWebsiteDataTypes.
///
/// See https://developer.apple.com/documentation/webkit/wkwebsitedatarecord/data_store_record_types?language=objc.
enum WKWebsiteDataTypeEnum {
cookies,
memoryCache,
diskCache,
offlineWebApplicationCache,
localStorage,
sessionStorage,
webSQLDatabases,
indexedDBDatabases,
}
/// Mirror of WKNavigationActionPolicy.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc.
enum WKNavigationActionPolicyEnum {
allow,
cancel,
}
/// Mirror of WKNavigationResponsePolicy.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc.
enum WKNavigationResponsePolicyEnum {
allow,
cancel,
}
/// Mirror of NSHTTPCookiePropertyKey.
///
/// See https://developer.apple.com/documentation/foundation/nshttpcookiepropertykey.
enum NSHttpCookiePropertyKeyEnum {
comment,
commentUrl,
discard,
domain,
expires,
maximumAge,
name,
originUrl,
path,
port,
sameSitePolicy,
secure,
value,
version,
}
/// An object that contains information about an action that causes navigation
/// to occur.
///
/// Wraps [WKNavigationType](https://developer.apple.com/documentation/webkit/wknavigationaction?language=objc).
enum WKNavigationType {
/// A link activation.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypelinkactivated?language=objc.
linkActivated,
/// A request to submit a form.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeformsubmitted?language=objc.
submitted,
/// A request for the frame’s next or previous item.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypebackforward?language=objc.
backForward,
/// A request to reload the webpage.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypereload?language=objc.
reload,
/// A request to resubmit a form.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeformresubmitted?language=objc.
formResubmitted,
/// A navigation request that originates for some other reason.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationtype/wknavigationtypeother?language=objc.
other,
/// An unknown navigation type.
///
/// This does not represent an actual value provided by the platform and only
/// indicates a value was provided that isn't currently supported.
unknown,
}
/// Possible permission decisions for device resource access.
///
/// See https://developer.apple.com/documentation/webkit/wkpermissiondecision?language=objc.
enum WKPermissionDecision {
/// Deny permission for the requested resource.
///
/// See https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisiondeny?language=objc.
deny,
/// Deny permission for the requested resource.
///
/// See https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisiongrant?language=objc.
grant,
/// Prompt the user for permission for the requested resource.
///
/// See https://developer.apple.com/documentation/webkit/wkpermissiondecision/wkpermissiondecisionprompt?language=objc.
prompt,
}
/// List of the types of media devices that can capture audio, video, or both.
///
/// See https://developer.apple.com/documentation/webkit/wkmediacapturetype?language=objc.
enum WKMediaCaptureType {
/// A media device that can capture video.
///
/// See https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypecamera?language=objc.
camera,
/// A media device or devices that can capture audio and video.
///
/// See https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypecameraandmicrophone?language=objc.
cameraAndMicrophone,
/// A media device that can capture audio.
///
/// See https://developer.apple.com/documentation/webkit/wkmediacapturetype/wkmediacapturetypemicrophone?language=objc.
microphone,
/// An unknown media device.
///
/// This does not represent an actual value provided by the platform and only
/// indicates a value was provided that isn't currently supported.
unknown,
}
/// Responses to an authentication challenge.
///
/// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition?language=objc.
enum NSUrlSessionAuthChallengeDisposition {
/// Use the specified credential, which may be nil.
///
/// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengeusecredential?language=objc.
useCredential,
/// Use the default handling for the challenge as though this delegate method
/// were not implemented.
///
/// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengeperformdefaulthandling?language=objc.
performDefaultHandling,
/// Cancel the entire request.
///
/// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengecancelauthenticationchallenge?language=objc.
cancelAuthenticationChallenge,
/// Reject this challenge, and call the authentication delegate method again
/// with the next authentication protection space.
///
/// See https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition/nsurlsessionauthchallengerejectprotectionspace?language=objc.
rejectProtectionSpace,
}
/// Specifies how long a credential will be kept.
enum NSUrlCredentialPersistence {
/// The credential should not be stored.
///
/// See https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencenone?language=objc.
none,
/// The credential should be stored only for this session.
///
/// See https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistenceforsession?language=objc.
session,
/// The credential should be stored in the keychain.
///
/// See https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencepermanent?language=objc.
permanent,
/// The credential should be stored permanently in the keychain, and in
/// addition should be distributed to other devices based on the owning Apple
/// ID.
///
/// See https://developer.apple.com/documentation/foundation/nsurlcredentialpersistence/nsurlcredentialpersistencesynchronizable?language=objc.
synchronizable,
}
class NSKeyValueObservingOptionsEnumData {
NSKeyValueObservingOptionsEnumData({
required this.value,
});
NSKeyValueObservingOptionsEnum value;
Object encode() {
return <Object?>[
value.index,
];
}
static NSKeyValueObservingOptionsEnumData decode(Object result) {
result as List<Object?>;
return NSKeyValueObservingOptionsEnumData(
value: NSKeyValueObservingOptionsEnum.values[result[0]! as int],
);
}
}
class NSKeyValueChangeKeyEnumData {
NSKeyValueChangeKeyEnumData({
required this.value,
});
NSKeyValueChangeKeyEnum value;
Object encode() {
return <Object?>[
value.index,
];
}
static NSKeyValueChangeKeyEnumData decode(Object result) {
result as List<Object?>;
return NSKeyValueChangeKeyEnumData(
value: NSKeyValueChangeKeyEnum.values[result[0]! as int],
);
}
}
class WKUserScriptInjectionTimeEnumData {
WKUserScriptInjectionTimeEnumData({
required this.value,
});
WKUserScriptInjectionTimeEnum value;
Object encode() {
return <Object?>[
value.index,
];
}
static WKUserScriptInjectionTimeEnumData decode(Object result) {
result as List<Object?>;
return WKUserScriptInjectionTimeEnumData(
value: WKUserScriptInjectionTimeEnum.values[result[0]! as int],
);
}
}
class WKAudiovisualMediaTypeEnumData {
WKAudiovisualMediaTypeEnumData({
required this.value,
});
WKAudiovisualMediaTypeEnum value;
Object encode() {
return <Object?>[
value.index,
];
}
static WKAudiovisualMediaTypeEnumData decode(Object result) {
result as List<Object?>;
return WKAudiovisualMediaTypeEnumData(
value: WKAudiovisualMediaTypeEnum.values[result[0]! as int],
);
}
}
class WKWebsiteDataTypeEnumData {
WKWebsiteDataTypeEnumData({
required this.value,
});
WKWebsiteDataTypeEnum value;
Object encode() {
return <Object?>[
value.index,
];
}
static WKWebsiteDataTypeEnumData decode(Object result) {
result as List<Object?>;
return WKWebsiteDataTypeEnumData(
value: WKWebsiteDataTypeEnum.values[result[0]! as int],
);
}
}
class WKNavigationActionPolicyEnumData {
WKNavigationActionPolicyEnumData({
required this.value,
});
WKNavigationActionPolicyEnum value;
Object encode() {
return <Object?>[
value.index,
];
}
static WKNavigationActionPolicyEnumData decode(Object result) {
result as List<Object?>;
return WKNavigationActionPolicyEnumData(
value: WKNavigationActionPolicyEnum.values[result[0]! as int],
);
}
}
class NSHttpCookiePropertyKeyEnumData {
NSHttpCookiePropertyKeyEnumData({
required this.value,
});
NSHttpCookiePropertyKeyEnum value;
Object encode() {
return <Object?>[
value.index,
];
}
static NSHttpCookiePropertyKeyEnumData decode(Object result) {
result as List<Object?>;
return NSHttpCookiePropertyKeyEnumData(
value: NSHttpCookiePropertyKeyEnum.values[result[0]! as int],
);
}
}
class WKPermissionDecisionData {
WKPermissionDecisionData({
required this.value,
});
WKPermissionDecision value;
Object encode() {
return <Object?>[
value.index,
];
}
static WKPermissionDecisionData decode(Object result) {
result as List<Object?>;
return WKPermissionDecisionData(
value: WKPermissionDecision.values[result[0]! as int],
);
}
}
class WKMediaCaptureTypeData {
WKMediaCaptureTypeData({
required this.value,
});
WKMediaCaptureType value;
Object encode() {
return <Object?>[
value.index,
];
}
static WKMediaCaptureTypeData decode(Object result) {
result as List<Object?>;
return WKMediaCaptureTypeData(
value: WKMediaCaptureType.values[result[0]! as int],
);
}
}
/// Mirror of NSURLRequest.
///
/// See https://developer.apple.com/documentation/foundation/nsurlrequest?language=objc.
class NSUrlRequestData {
NSUrlRequestData({
required this.url,
this.httpMethod,
this.httpBody,
required this.allHttpHeaderFields,
});
String url;
String? httpMethod;
Uint8List? httpBody;
Map<String?, String?> allHttpHeaderFields;
Object encode() {
return <Object?>[
url,
httpMethod,
httpBody,
allHttpHeaderFields,
];
}
static NSUrlRequestData decode(Object result) {
result as List<Object?>;
return NSUrlRequestData(
url: result[0]! as String,
httpMethod: result[1] as String?,
httpBody: result[2] as Uint8List?,
allHttpHeaderFields:
(result[3] as Map<Object?, Object?>?)!.cast<String?, String?>(),
);
}
}
/// Mirror of NSURLResponse.
///
/// See https://developer.apple.com/documentation/foundation/nshttpurlresponse?language=objc.
class NSHttpUrlResponseData {
NSHttpUrlResponseData({
required this.statusCode,
});
int statusCode;
Object encode() {
return <Object?>[
statusCode,
];
}
static NSHttpUrlResponseData decode(Object result) {
result as List<Object?>;
return NSHttpUrlResponseData(
statusCode: result[0]! as int,
);
}
}
/// Mirror of WKUserScript.
///
/// See https://developer.apple.com/documentation/webkit/wkuserscript?language=objc.
class WKUserScriptData {
WKUserScriptData({
required this.source,
this.injectionTime,
required this.isMainFrameOnly,
});
String source;
WKUserScriptInjectionTimeEnumData? injectionTime;
bool isMainFrameOnly;
Object encode() {
return <Object?>[
source,
injectionTime?.encode(),
isMainFrameOnly,
];
}
static WKUserScriptData decode(Object result) {
result as List<Object?>;
return WKUserScriptData(
source: result[0]! as String,
injectionTime: result[1] != null
? WKUserScriptInjectionTimeEnumData.decode(
result[1]! as List<Object?>)
: null,
isMainFrameOnly: result[2]! as bool,
);
}
}
/// Mirror of WKNavigationAction.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationaction.
class WKNavigationActionData {
WKNavigationActionData({
required this.request,
required this.targetFrame,
required this.navigationType,
});
NSUrlRequestData request;
WKFrameInfoData targetFrame;
WKNavigationType navigationType;
Object encode() {
return <Object?>[
request.encode(),
targetFrame.encode(),
navigationType.index,
];
}
static WKNavigationActionData decode(Object result) {
result as List<Object?>;
return WKNavigationActionData(
request: NSUrlRequestData.decode(result[0]! as List<Object?>),
targetFrame: WKFrameInfoData.decode(result[1]! as List<Object?>),
navigationType: WKNavigationType.values[result[2]! as int],
);
}
}
/// Mirror of WKNavigationResponse.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationresponse.
class WKNavigationResponseData {
WKNavigationResponseData({
required this.response,
required this.forMainFrame,
});
NSHttpUrlResponseData response;
bool forMainFrame;
Object encode() {
return <Object?>[
response.encode(),
forMainFrame,
];
}
static WKNavigationResponseData decode(Object result) {
result as List<Object?>;
return WKNavigationResponseData(
response: NSHttpUrlResponseData.decode(result[0]! as List<Object?>),
forMainFrame: result[1]! as bool,
);
}
}
/// Mirror of WKFrameInfo.
///
/// See https://developer.apple.com/documentation/webkit/wkframeinfo?language=objc.
class WKFrameInfoData {
WKFrameInfoData({
required this.isMainFrame,
required this.request,
});
bool isMainFrame;
NSUrlRequestData request;
Object encode() {
return <Object?>[
isMainFrame,
request.encode(),
];
}
static WKFrameInfoData decode(Object result) {
result as List<Object?>;
return WKFrameInfoData(
isMainFrame: result[0]! as bool,
request: NSUrlRequestData.decode(result[1]! as List<Object?>),
);
}
}
/// Mirror of NSError.
///
/// See https://developer.apple.com/documentation/foundation/nserror?language=objc.
class NSErrorData {
NSErrorData({
required this.code,
required this.domain,
this.userInfo,
});
int code;
String domain;
Map<String?, Object?>? userInfo;
Object encode() {
return <Object?>[
code,
domain,
userInfo,
];
}
static NSErrorData decode(Object result) {
result as List<Object?>;
return NSErrorData(
code: result[0]! as int,
domain: result[1]! as String,
userInfo: (result[2] as Map<Object?, Object?>?)?.cast<String?, Object?>(),
);
}
}
/// Mirror of WKScriptMessage.
///
/// See https://developer.apple.com/documentation/webkit/wkscriptmessage?language=objc.
class WKScriptMessageData {
WKScriptMessageData({
required this.name,
this.body,
});
String name;
Object? body;
Object encode() {
return <Object?>[
name,
body,
];
}
static WKScriptMessageData decode(Object result) {
result as List<Object?>;
return WKScriptMessageData(
name: result[0]! as String,
body: result[1],
);
}
}
/// Mirror of WKSecurityOrigin.
///
/// See https://developer.apple.com/documentation/webkit/wksecurityorigin?language=objc.
class WKSecurityOriginData {
WKSecurityOriginData({
required this.host,
required this.port,
required this.protocol,
});
String host;
int port;
String protocol;
Object encode() {
return <Object?>[
host,
port,
protocol,
];
}
static WKSecurityOriginData decode(Object result) {
result as List<Object?>;
return WKSecurityOriginData(
host: result[0]! as String,
port: result[1]! as int,
protocol: result[2]! as String,
);
}
}
/// Mirror of NSHttpCookieData.
///
/// See https://developer.apple.com/documentation/foundation/nshttpcookie?language=objc.
class NSHttpCookieData {
NSHttpCookieData({
required this.propertyKeys,
required this.propertyValues,
});
List<NSHttpCookiePropertyKeyEnumData?> propertyKeys;
List<Object?> propertyValues;
Object encode() {
return <Object?>[
propertyKeys,
propertyValues,
];
}
static NSHttpCookieData decode(Object result) {
result as List<Object?>;
return NSHttpCookieData(
propertyKeys: (result[0] as List<Object?>?)!
.cast<NSHttpCookiePropertyKeyEnumData?>(),
propertyValues: (result[1] as List<Object?>?)!.cast<Object?>(),
);
}
}
/// An object that can represent either a value supported by
/// `StandardMessageCodec`, a data class in this pigeon file, or an identifier
/// of an object stored in an `InstanceManager`.
class ObjectOrIdentifier {
ObjectOrIdentifier({
this.value,
required this.isIdentifier,
});
Object? value;
/// Whether value is an int that is used to retrieve an instance stored in an
/// `InstanceManager`.
bool isIdentifier;
Object encode() {
return <Object?>[
value,
isIdentifier,
];
}
static ObjectOrIdentifier decode(Object result) {
result as List<Object?>;
return ObjectOrIdentifier(
value: result[0],
isIdentifier: result[1]! as bool,
);
}
}
class AuthenticationChallengeResponse {
AuthenticationChallengeResponse({
required this.disposition,
this.credentialIdentifier,
});
NSUrlSessionAuthChallengeDisposition disposition;
int? credentialIdentifier;
Object encode() {
return <Object?>[
disposition.index,
credentialIdentifier,
];
}
static AuthenticationChallengeResponse decode(Object result) {
result as List<Object?>;
return AuthenticationChallengeResponse(
disposition:
NSUrlSessionAuthChallengeDisposition.values[result[0]! as int],
credentialIdentifier: result[1] as int?,
);
}
}
class _WKWebsiteDataStoreHostApiCodec extends StandardMessageCodec {
const _WKWebsiteDataStoreHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is WKWebsiteDataTypeEnumData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return WKWebsiteDataTypeEnumData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Mirror of WKWebsiteDataStore.
///
/// See https://developer.apple.com/documentation/webkit/wkwebsitedatastore?language=objc.
class WKWebsiteDataStoreHostApi {
/// Constructor for [WKWebsiteDataStoreHostApi]. 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.
WKWebsiteDataStoreHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _WKWebsiteDataStoreHostApiCodec();
Future<void> createFromWebViewConfiguration(
int arg_identifier, int arg_configurationIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createFromWebViewConfiguration',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_configurationIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> createDefaultDataStore(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.createDefaultDataStore',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<bool> removeDataOfTypes(
int arg_identifier,
List<WKWebsiteDataTypeEnumData?> arg_dataTypes,
double arg_modificationTimeInSecondsSinceEpoch) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi.removeDataOfTypes',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(<Object?>[
arg_identifier,
arg_dataTypes,
arg_modificationTimeInSecondsSinceEpoch
]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as bool?)!;
}
}
}
/// Mirror of UIView.
///
/// See https://developer.apple.com/documentation/uikit/uiview?language=objc.
class UIViewHostApi {
/// Constructor for [UIViewHostApi]. 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.
UIViewHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> setBackgroundColor(int arg_identifier, int? arg_value) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setBackgroundColor',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_value]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setOpaque(int arg_identifier, bool arg_opaque) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setOpaque',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_opaque]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
/// Mirror of UIScrollView.
///
/// See https://developer.apple.com/documentation/uikit/uiscrollview?language=objc.
class UIScrollViewHostApi {
/// Constructor for [UIScrollViewHostApi]. 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.
UIScrollViewHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> createFromWebView(
int arg_identifier, int arg_webViewIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.createFromWebView',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier, arg_webViewIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<List<double?>> getContentOffset(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.getContentOffset',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as List<Object?>?)!.cast<double?>();
}
}
Future<void> scrollBy(int arg_identifier, double arg_x, double arg_y) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.scrollBy',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_x, arg_y]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setContentOffset(
int arg_identifier, double arg_x, double arg_y) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setContentOffset',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_x, arg_y]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setDelegate(
int arg_identifier, int? arg_uiScrollViewDelegateIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setDelegate',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_uiScrollViewDelegateIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class _WKWebViewConfigurationHostApiCodec extends StandardMessageCodec {
const _WKWebViewConfigurationHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is WKAudiovisualMediaTypeEnumData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return WKAudiovisualMediaTypeEnumData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Mirror of WKWebViewConfiguration.
///
/// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc.
class WKWebViewConfigurationHostApi {
/// Constructor for [WKWebViewConfigurationHostApi]. 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.
WKWebViewConfigurationHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec =
_WKWebViewConfigurationHostApiCodec();
Future<void> create(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.create',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> createFromWebView(
int arg_identifier, int arg_webViewIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.createFromWebView',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier, arg_webViewIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setAllowsInlineMediaPlayback(
int arg_identifier, bool arg_allow) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_allow]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setLimitsNavigationsToAppBoundDomains(
int arg_identifier, bool arg_limit) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setLimitsNavigationsToAppBoundDomains',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_limit]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setMediaTypesRequiringUserActionForPlayback(int arg_identifier,
List<WKAudiovisualMediaTypeEnumData?> arg_types) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_types]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
/// Handles callbacks from a WKWebViewConfiguration instance.
///
/// See https://developer.apple.com/documentation/webkit/wkwebviewconfiguration?language=objc.
abstract class WKWebViewConfigurationFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
void create(int identifier);
static void setup(WKWebViewConfigurationFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationFlutterApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationFlutterApi.create was null, expected non-null int.');
try {
api.create(arg_identifier!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
class _WKUserContentControllerHostApiCodec extends StandardMessageCodec {
const _WKUserContentControllerHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is WKUserScriptData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is WKUserScriptInjectionTimeEnumData) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return WKUserScriptData.decode(readValue(buffer)!);
case 129:
return WKUserScriptInjectionTimeEnumData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Mirror of WKUserContentController.
///
/// See https://developer.apple.com/documentation/webkit/wkusercontentcontroller?language=objc.
class WKUserContentControllerHostApi {
/// Constructor for [WKUserContentControllerHostApi]. 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.
WKUserContentControllerHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec =
_WKUserContentControllerHostApiCodec();
Future<void> createFromWebViewConfiguration(
int arg_identifier, int arg_configurationIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.createFromWebViewConfiguration',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_configurationIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> addScriptMessageHandler(
int arg_identifier, int arg_handlerIdentifier, String arg_name) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addScriptMessageHandler',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_handlerIdentifier, arg_name])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> removeScriptMessageHandler(
int arg_identifier, String arg_name) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeScriptMessageHandler',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_name]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> removeAllScriptMessageHandlers(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeAllScriptMessageHandlers',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> addUserScript(
int arg_identifier, WKUserScriptData arg_userScript) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.addUserScript',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_userScript]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> removeAllUserScripts(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUserContentControllerHostApi.removeAllUserScripts',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
/// Mirror of WKUserPreferences.
///
/// See https://developer.apple.com/documentation/webkit/wkpreferences?language=objc.
class WKPreferencesHostApi {
/// Constructor for [WKPreferencesHostApi]. 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.
WKPreferencesHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> createFromWebViewConfiguration(
int arg_identifier, int arg_configurationIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.createFromWebViewConfiguration',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_configurationIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setJavaScriptEnabled(
int arg_identifier, bool arg_enabled) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi.setJavaScriptEnabled',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_enabled]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
/// Mirror of WKScriptMessageHandler.
///
/// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc.
class WKScriptMessageHandlerHostApi {
/// Constructor for [WKScriptMessageHandlerHostApi]. 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.
WKScriptMessageHandlerHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerHostApi.create',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class _WKScriptMessageHandlerFlutterApiCodec extends StandardMessageCodec {
const _WKScriptMessageHandlerFlutterApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is WKScriptMessageData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return WKScriptMessageData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Handles callbacks from a WKScriptMessageHandler instance.
///
/// See https://developer.apple.com/documentation/webkit/wkscriptmessagehandler?language=objc.
abstract class WKScriptMessageHandlerFlutterApi {
static const MessageCodec<Object?> codec =
_WKScriptMessageHandlerFlutterApiCodec();
void didReceiveScriptMessage(int identifier,
int userContentControllerIdentifier, WKScriptMessageData message);
static void setup(WKScriptMessageHandlerFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerFlutterApi.didReceiveScriptMessage',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerFlutterApi.didReceiveScriptMessage 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_wkwebview.WKScriptMessageHandlerFlutterApi.didReceiveScriptMessage was null, expected non-null int.');
final int? arg_userContentControllerIdentifier = (args[1] as int?);
assert(arg_userContentControllerIdentifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerFlutterApi.didReceiveScriptMessage was null, expected non-null int.');
final WKScriptMessageData? arg_message =
(args[2] as WKScriptMessageData?);
assert(arg_message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerFlutterApi.didReceiveScriptMessage was null, expected non-null WKScriptMessageData.');
try {
api.didReceiveScriptMessage(arg_identifier!,
arg_userContentControllerIdentifier!, arg_message!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
/// Mirror of WKNavigationDelegate.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc.
class WKNavigationDelegateHostApi {
/// Constructor for [WKNavigationDelegateHostApi]. 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.
WKNavigationDelegateHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateHostApi.create',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class _WKNavigationDelegateFlutterApiCodec extends StandardMessageCodec {
const _WKNavigationDelegateFlutterApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is AuthenticationChallengeResponse) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is NSErrorData) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is NSHttpUrlResponseData) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else if (value is NSUrlRequestData) {
buffer.putUint8(131);
writeValue(buffer, value.encode());
} else if (value is WKFrameInfoData) {
buffer.putUint8(132);
writeValue(buffer, value.encode());
} else if (value is WKNavigationActionData) {
buffer.putUint8(133);
writeValue(buffer, value.encode());
} else if (value is WKNavigationActionPolicyEnumData) {
buffer.putUint8(134);
writeValue(buffer, value.encode());
} else if (value is WKNavigationResponseData) {
buffer.putUint8(135);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return AuthenticationChallengeResponse.decode(readValue(buffer)!);
case 129:
return NSErrorData.decode(readValue(buffer)!);
case 130:
return NSHttpUrlResponseData.decode(readValue(buffer)!);
case 131:
return NSUrlRequestData.decode(readValue(buffer)!);
case 132:
return WKFrameInfoData.decode(readValue(buffer)!);
case 133:
return WKNavigationActionData.decode(readValue(buffer)!);
case 134:
return WKNavigationActionPolicyEnumData.decode(readValue(buffer)!);
case 135:
return WKNavigationResponseData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Handles callbacks from a WKNavigationDelegate instance.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationdelegate?language=objc.
abstract class WKNavigationDelegateFlutterApi {
static const MessageCodec<Object?> codec =
_WKNavigationDelegateFlutterApiCodec();
void didFinishNavigation(int identifier, int webViewIdentifier, String? url);
void didStartProvisionalNavigation(
int identifier, int webViewIdentifier, String? url);
Future<WKNavigationActionPolicyEnumData> decidePolicyForNavigationAction(
int identifier,
int webViewIdentifier,
WKNavigationActionData navigationAction);
Future<WKNavigationResponsePolicyEnum> decidePolicyForNavigationResponse(
int identifier,
int webViewIdentifier,
WKNavigationResponseData navigationResponse);
void didFailNavigation(
int identifier, int webViewIdentifier, NSErrorData error);
void didFailProvisionalNavigation(
int identifier, int webViewIdentifier, NSErrorData error);
void webViewWebContentProcessDidTerminate(
int identifier, int webViewIdentifier);
Future<AuthenticationChallengeResponse> didReceiveAuthenticationChallenge(
int identifier, int webViewIdentifier, int challengeIdentifier);
static void setup(WKNavigationDelegateFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didFinishNavigation',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didFinishNavigation 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_wkwebview.WKNavigationDelegateFlutterApi.didFinishNavigation 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_wkwebview.WKNavigationDelegateFlutterApi.didFinishNavigation was null, expected non-null int.');
final String? arg_url = (args[2] as String?);
try {
api.didFinishNavigation(
arg_identifier!, arg_webViewIdentifier!, arg_url);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didStartProvisionalNavigation',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didStartProvisionalNavigation 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_wkwebview.WKNavigationDelegateFlutterApi.didStartProvisionalNavigation 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_wkwebview.WKNavigationDelegateFlutterApi.didStartProvisionalNavigation was null, expected non-null int.');
final String? arg_url = (args[2] as String?);
try {
api.didStartProvisionalNavigation(
arg_identifier!, arg_webViewIdentifier!, arg_url);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationAction',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationAction 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_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationAction 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_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationAction was null, expected non-null int.');
final WKNavigationActionData? arg_navigationAction =
(args[2] as WKNavigationActionData?);
assert(arg_navigationAction != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationAction was null, expected non-null WKNavigationActionData.');
try {
final WKNavigationActionPolicyEnumData output =
await api.decidePolicyForNavigationAction(arg_identifier!,
arg_webViewIdentifier!, arg_navigationAction!);
return wrapResponse(result: output);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationResponse',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationResponse 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_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationResponse 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_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationResponse was null, expected non-null int.');
final WKNavigationResponseData? arg_navigationResponse =
(args[2] as WKNavigationResponseData?);
assert(arg_navigationResponse != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.decidePolicyForNavigationResponse was null, expected non-null WKNavigationResponseData.');
try {
final WKNavigationResponsePolicyEnum output =
await api.decidePolicyForNavigationResponse(arg_identifier!,
arg_webViewIdentifier!, arg_navigationResponse!);
return wrapResponse(result: output.index);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didFailNavigation',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didFailNavigation 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_wkwebview.WKNavigationDelegateFlutterApi.didFailNavigation 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_wkwebview.WKNavigationDelegateFlutterApi.didFailNavigation was null, expected non-null int.');
final NSErrorData? arg_error = (args[2] as NSErrorData?);
assert(arg_error != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didFailNavigation was null, expected non-null NSErrorData.');
try {
api.didFailNavigation(
arg_identifier!, arg_webViewIdentifier!, arg_error!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didFailProvisionalNavigation',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didFailProvisionalNavigation 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_wkwebview.WKNavigationDelegateFlutterApi.didFailProvisionalNavigation 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_wkwebview.WKNavigationDelegateFlutterApi.didFailProvisionalNavigation was null, expected non-null int.');
final NSErrorData? arg_error = (args[2] as NSErrorData?);
assert(arg_error != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didFailProvisionalNavigation was null, expected non-null NSErrorData.');
try {
api.didFailProvisionalNavigation(
arg_identifier!, arg_webViewIdentifier!, arg_error!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.webViewWebContentProcessDidTerminate',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.webViewWebContentProcessDidTerminate 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_wkwebview.WKNavigationDelegateFlutterApi.webViewWebContentProcessDidTerminate 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_wkwebview.WKNavigationDelegateFlutterApi.webViewWebContentProcessDidTerminate was null, expected non-null int.');
try {
api.webViewWebContentProcessDidTerminate(
arg_identifier!, arg_webViewIdentifier!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didReceiveAuthenticationChallenge',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didReceiveAuthenticationChallenge 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_wkwebview.WKNavigationDelegateFlutterApi.didReceiveAuthenticationChallenge 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_wkwebview.WKNavigationDelegateFlutterApi.didReceiveAuthenticationChallenge was null, expected non-null int.');
final int? arg_challengeIdentifier = (args[2] as int?);
assert(arg_challengeIdentifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateFlutterApi.didReceiveAuthenticationChallenge was null, expected non-null int.');
try {
final AuthenticationChallengeResponse output =
await api.didReceiveAuthenticationChallenge(arg_identifier!,
arg_webViewIdentifier!, arg_challengeIdentifier!);
return wrapResponse(result: output);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
class _NSObjectHostApiCodec extends StandardMessageCodec {
const _NSObjectHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is NSKeyValueObservingOptionsEnumData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return NSKeyValueObservingOptionsEnumData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Mirror of NSObject.
///
/// See https://developer.apple.com/documentation/objectivec/nsobject.
class NSObjectHostApi {
/// Constructor for [NSObjectHostApi]. 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.
NSObjectHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _NSObjectHostApiCodec();
Future<void> dispose(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.dispose',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> addObserver(
int arg_identifier,
int arg_observerIdentifier,
String arg_keyPath,
List<NSKeyValueObservingOptionsEnumData?> arg_options) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.addObserver',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(<Object?>[
arg_identifier,
arg_observerIdentifier,
arg_keyPath,
arg_options
]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> removeObserver(int arg_identifier, int arg_observerIdentifier,
String arg_keyPath) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.removeObserver',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(
<Object?>[arg_identifier, arg_observerIdentifier, arg_keyPath])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class _NSObjectFlutterApiCodec extends StandardMessageCodec {
const _NSObjectFlutterApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is NSKeyValueChangeKeyEnumData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is ObjectOrIdentifier) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return NSKeyValueChangeKeyEnumData.decode(readValue(buffer)!);
case 129:
return ObjectOrIdentifier.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Handles callbacks from an NSObject instance.
///
/// See https://developer.apple.com/documentation/objectivec/nsobject.
abstract class NSObjectFlutterApi {
static const MessageCodec<Object?> codec = _NSObjectFlutterApiCodec();
void observeValue(
int identifier,
String keyPath,
int objectIdentifier,
List<NSKeyValueChangeKeyEnumData?> changeKeys,
List<ObjectOrIdentifier?> changeValues);
void dispose(int identifier);
static void setup(NSObjectFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.observeValue',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.observeValue 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_wkwebview.NSObjectFlutterApi.observeValue was null, expected non-null int.');
final String? arg_keyPath = (args[1] as String?);
assert(arg_keyPath != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.observeValue was null, expected non-null String.');
final int? arg_objectIdentifier = (args[2] as int?);
assert(arg_objectIdentifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.observeValue was null, expected non-null int.');
final List<NSKeyValueChangeKeyEnumData?>? arg_changeKeys =
(args[3] as List<Object?>?)?.cast<NSKeyValueChangeKeyEnumData?>();
assert(arg_changeKeys != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.observeValue was null, expected non-null List<NSKeyValueChangeKeyEnumData?>.');
final List<ObjectOrIdentifier?>? arg_changeValues =
(args[4] as List<Object?>?)?.cast<ObjectOrIdentifier?>();
assert(arg_changeValues != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.observeValue was null, expected non-null List<ObjectOrIdentifier?>.');
try {
api.observeValue(arg_identifier!, arg_keyPath!,
arg_objectIdentifier!, arg_changeKeys!, arg_changeValues!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.dispose',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.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_wkwebview.NSObjectFlutterApi.dispose was null, expected non-null int.');
try {
api.dispose(arg_identifier!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
class _WKWebViewHostApiCodec extends StandardMessageCodec {
const _WKWebViewHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is AuthenticationChallengeResponse) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is NSErrorData) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is NSHttpCookieData) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else if (value is NSHttpCookiePropertyKeyEnumData) {
buffer.putUint8(131);
writeValue(buffer, value.encode());
} else if (value is NSHttpUrlResponseData) {
buffer.putUint8(132);
writeValue(buffer, value.encode());
} else if (value is NSKeyValueChangeKeyEnumData) {
buffer.putUint8(133);
writeValue(buffer, value.encode());
} else if (value is NSKeyValueObservingOptionsEnumData) {
buffer.putUint8(134);
writeValue(buffer, value.encode());
} else if (value is NSUrlRequestData) {
buffer.putUint8(135);
writeValue(buffer, value.encode());
} else if (value is ObjectOrIdentifier) {
buffer.putUint8(136);
writeValue(buffer, value.encode());
} else if (value is WKAudiovisualMediaTypeEnumData) {
buffer.putUint8(137);
writeValue(buffer, value.encode());
} else if (value is WKFrameInfoData) {
buffer.putUint8(138);
writeValue(buffer, value.encode());
} else if (value is WKMediaCaptureTypeData) {
buffer.putUint8(139);
writeValue(buffer, value.encode());
} else if (value is WKNavigationActionData) {
buffer.putUint8(140);
writeValue(buffer, value.encode());
} else if (value is WKNavigationActionPolicyEnumData) {
buffer.putUint8(141);
writeValue(buffer, value.encode());
} else if (value is WKNavigationResponseData) {
buffer.putUint8(142);
writeValue(buffer, value.encode());
} else if (value is WKPermissionDecisionData) {
buffer.putUint8(143);
writeValue(buffer, value.encode());
} else if (value is WKScriptMessageData) {
buffer.putUint8(144);
writeValue(buffer, value.encode());
} else if (value is WKSecurityOriginData) {
buffer.putUint8(145);
writeValue(buffer, value.encode());
} else if (value is WKUserScriptData) {
buffer.putUint8(146);
writeValue(buffer, value.encode());
} else if (value is WKUserScriptInjectionTimeEnumData) {
buffer.putUint8(147);
writeValue(buffer, value.encode());
} else if (value is WKWebsiteDataTypeEnumData) {
buffer.putUint8(148);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return AuthenticationChallengeResponse.decode(readValue(buffer)!);
case 129:
return NSErrorData.decode(readValue(buffer)!);
case 130:
return NSHttpCookieData.decode(readValue(buffer)!);
case 131:
return NSHttpCookiePropertyKeyEnumData.decode(readValue(buffer)!);
case 132:
return NSHttpUrlResponseData.decode(readValue(buffer)!);
case 133:
return NSKeyValueChangeKeyEnumData.decode(readValue(buffer)!);
case 134:
return NSKeyValueObservingOptionsEnumData.decode(readValue(buffer)!);
case 135:
return NSUrlRequestData.decode(readValue(buffer)!);
case 136:
return ObjectOrIdentifier.decode(readValue(buffer)!);
case 137:
return WKAudiovisualMediaTypeEnumData.decode(readValue(buffer)!);
case 138:
return WKFrameInfoData.decode(readValue(buffer)!);
case 139:
return WKMediaCaptureTypeData.decode(readValue(buffer)!);
case 140:
return WKNavigationActionData.decode(readValue(buffer)!);
case 141:
return WKNavigationActionPolicyEnumData.decode(readValue(buffer)!);
case 142:
return WKNavigationResponseData.decode(readValue(buffer)!);
case 143:
return WKPermissionDecisionData.decode(readValue(buffer)!);
case 144:
return WKScriptMessageData.decode(readValue(buffer)!);
case 145:
return WKSecurityOriginData.decode(readValue(buffer)!);
case 146:
return WKUserScriptData.decode(readValue(buffer)!);
case 147:
return WKUserScriptInjectionTimeEnumData.decode(readValue(buffer)!);
case 148:
return WKWebsiteDataTypeEnumData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Mirror of WKWebView.
///
/// See https://developer.apple.com/documentation/webkit/wkwebview?language=objc.
class WKWebViewHostApi {
/// Constructor for [WKWebViewHostApi]. 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.
WKWebViewHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _WKWebViewHostApiCodec();
Future<void> create(
int arg_identifier, int arg_configurationIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.create',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_configurationIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setUIDelegate(
int arg_identifier, int? arg_uiDelegateIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setUIDelegate',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier, arg_uiDelegateIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setNavigationDelegate(
int arg_identifier, int? arg_navigationDelegateIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setNavigationDelegate',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_navigationDelegateIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<String?> getUrl(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getUrl',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
Future<double> getEstimatedProgress(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getEstimatedProgress',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as double?)!;
}
}
Future<void> loadRequest(
int arg_identifier, NSUrlRequestData arg_request) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadRequest',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_request]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> loadHtmlString(
int arg_identifier, String arg_string, String? arg_baseUrl) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadHtmlString',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier, arg_string, arg_baseUrl])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> loadFileUrl(
int arg_identifier, String arg_url, String arg_readAccessUrl) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFileUrl',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_url, arg_readAccessUrl])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> loadFlutterAsset(int arg_identifier, String arg_key) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFlutterAsset',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_key]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<bool> canGoBack(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoBack',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as bool?)!;
}
}
Future<bool> canGoForward(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoForward',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else if (replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (replyList[0] as bool?)!;
}
}
Future<void> goBack(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goBack',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> goForward(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goForward',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> reload(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.reload',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<String?> getTitle(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getTitle',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
Future<void> setAllowsBackForwardNavigationGestures(
int arg_identifier, bool arg_allow) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setAllowsBackForwardNavigationGestures',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_allow]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setCustomUserAgent(
int arg_identifier, String? arg_userAgent) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setCustomUserAgent',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_userAgent]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<Object?> evaluateJavaScript(
int arg_identifier, String arg_javaScriptString) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.evaluateJavaScript',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier, arg_javaScriptString])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return replyList[0];
}
}
Future<void> setInspectable(int arg_identifier, bool arg_inspectable) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setInspectable',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_inspectable]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<String?> getCustomUserAgent(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getCustomUserAgent',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
}
/// Mirror of WKUIDelegate.
///
/// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc.
class WKUIDelegateHostApi {
/// Constructor for [WKUIDelegateHostApi]. 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.
WKUIDelegateHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateHostApi.create',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
class _WKUIDelegateFlutterApiCodec extends StandardMessageCodec {
const _WKUIDelegateFlutterApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is NSUrlRequestData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is WKFrameInfoData) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else if (value is WKMediaCaptureTypeData) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else if (value is WKNavigationActionData) {
buffer.putUint8(131);
writeValue(buffer, value.encode());
} else if (value is WKPermissionDecisionData) {
buffer.putUint8(132);
writeValue(buffer, value.encode());
} else if (value is WKSecurityOriginData) {
buffer.putUint8(133);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return NSUrlRequestData.decode(readValue(buffer)!);
case 129:
return WKFrameInfoData.decode(readValue(buffer)!);
case 130:
return WKMediaCaptureTypeData.decode(readValue(buffer)!);
case 131:
return WKNavigationActionData.decode(readValue(buffer)!);
case 132:
return WKPermissionDecisionData.decode(readValue(buffer)!);
case 133:
return WKSecurityOriginData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Handles callbacks from a WKUIDelegate instance.
///
/// See https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc.
abstract class WKUIDelegateFlutterApi {
static const MessageCodec<Object?> codec = _WKUIDelegateFlutterApiCodec();
void onCreateWebView(int identifier, int webViewIdentifier,
int configurationIdentifier, WKNavigationActionData navigationAction);
/// Callback to Dart function `WKUIDelegate.requestMediaCapturePermission`.
Future<WKPermissionDecisionData> requestMediaCapturePermission(
int identifier,
int webViewIdentifier,
WKSecurityOriginData origin,
WKFrameInfoData frame,
WKMediaCaptureTypeData type);
/// Callback to Dart function `WKUIDelegate.runJavaScriptAlertPanel`.
Future<void> runJavaScriptAlertPanel(
int identifier, String message, WKFrameInfoData frame);
/// Callback to Dart function `WKUIDelegate.runJavaScriptConfirmPanel`.
Future<bool> runJavaScriptConfirmPanel(
int identifier, String message, WKFrameInfoData frame);
/// Callback to Dart function `WKUIDelegate.runJavaScriptTextInputPanel`.
Future<String> runJavaScriptTextInputPanel(
int identifier, String prompt, String defaultText, WKFrameInfoData frame);
static void setup(WKUIDelegateFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.onCreateWebView',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.onCreateWebView 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_wkwebview.WKUIDelegateFlutterApi.onCreateWebView 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_wkwebview.WKUIDelegateFlutterApi.onCreateWebView was null, expected non-null int.');
final int? arg_configurationIdentifier = (args[2] as int?);
assert(arg_configurationIdentifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.onCreateWebView was null, expected non-null int.');
final WKNavigationActionData? arg_navigationAction =
(args[3] as WKNavigationActionData?);
assert(arg_navigationAction != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.onCreateWebView was null, expected non-null WKNavigationActionData.');
try {
api.onCreateWebView(arg_identifier!, arg_webViewIdentifier!,
arg_configurationIdentifier!, arg_navigationAction!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.requestMediaCapturePermission',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.requestMediaCapturePermission 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_wkwebview.WKUIDelegateFlutterApi.requestMediaCapturePermission 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_wkwebview.WKUIDelegateFlutterApi.requestMediaCapturePermission was null, expected non-null int.');
final WKSecurityOriginData? arg_origin =
(args[2] as WKSecurityOriginData?);
assert(arg_origin != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.requestMediaCapturePermission was null, expected non-null WKSecurityOriginData.');
final WKFrameInfoData? arg_frame = (args[3] as WKFrameInfoData?);
assert(arg_frame != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.requestMediaCapturePermission was null, expected non-null WKFrameInfoData.');
final WKMediaCaptureTypeData? arg_type =
(args[4] as WKMediaCaptureTypeData?);
assert(arg_type != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.requestMediaCapturePermission was null, expected non-null WKMediaCaptureTypeData.');
try {
final WKPermissionDecisionData output =
await api.requestMediaCapturePermission(arg_identifier!,
arg_webViewIdentifier!, arg_origin!, arg_frame!, arg_type!);
return wrapResponse(result: output);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptAlertPanel',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptAlertPanel 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_wkwebview.WKUIDelegateFlutterApi.runJavaScriptAlertPanel was null, expected non-null int.');
final String? arg_message = (args[1] as String?);
assert(arg_message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptAlertPanel was null, expected non-null String.');
final WKFrameInfoData? arg_frame = (args[2] as WKFrameInfoData?);
assert(arg_frame != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptAlertPanel was null, expected non-null WKFrameInfoData.');
try {
await api.runJavaScriptAlertPanel(
arg_identifier!, arg_message!, arg_frame!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptConfirmPanel',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptConfirmPanel 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_wkwebview.WKUIDelegateFlutterApi.runJavaScriptConfirmPanel was null, expected non-null int.');
final String? arg_message = (args[1] as String?);
assert(arg_message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptConfirmPanel was null, expected non-null String.');
final WKFrameInfoData? arg_frame = (args[2] as WKFrameInfoData?);
assert(arg_frame != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptConfirmPanel was null, expected non-null WKFrameInfoData.');
try {
final bool output = await api.runJavaScriptConfirmPanel(
arg_identifier!, arg_message!, arg_frame!);
return wrapResponse(result: output);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptTextInputPanel',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptTextInputPanel 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_wkwebview.WKUIDelegateFlutterApi.runJavaScriptTextInputPanel was null, expected non-null int.');
final String? arg_prompt = (args[1] as String?);
assert(arg_prompt != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptTextInputPanel was null, expected non-null String.');
final String? arg_defaultText = (args[2] as String?);
assert(arg_defaultText != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptTextInputPanel was null, expected non-null String.');
final WKFrameInfoData? arg_frame = (args[3] as WKFrameInfoData?);
assert(arg_frame != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.runJavaScriptTextInputPanel was null, expected non-null WKFrameInfoData.');
try {
final String output = await api.runJavaScriptTextInputPanel(
arg_identifier!, arg_prompt!, arg_defaultText!, arg_frame!);
return wrapResponse(result: output);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
class _WKHttpCookieStoreHostApiCodec extends StandardMessageCodec {
const _WKHttpCookieStoreHostApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is NSHttpCookieData) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is NSHttpCookiePropertyKeyEnumData) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return NSHttpCookieData.decode(readValue(buffer)!);
case 129:
return NSHttpCookiePropertyKeyEnumData.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
/// Mirror of WKHttpCookieStore.
///
/// See https://developer.apple.com/documentation/webkit/wkhttpcookiestore?language=objc.
class WKHttpCookieStoreHostApi {
/// Constructor for [WKHttpCookieStoreHostApi]. 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.
WKHttpCookieStoreHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = _WKHttpCookieStoreHostApiCodec();
Future<void> createFromWebsiteDataStore(
int arg_identifier, int arg_websiteDataStoreIdentifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.createFromWebsiteDataStore',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_websiteDataStoreIdentifier])
as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
Future<void> setCookie(
int arg_identifier, NSHttpCookieData arg_cookie) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.setCookie',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel
.send(<Object?>[arg_identifier, arg_cookie]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
/// Host API for `NSUrl`.
///
/// This class may handle instantiating and adding native object instances that
/// are attached to a Dart instance or method calls on the associated native
/// class or an instance of the class.
///
/// See https://developer.apple.com/documentation/foundation/nsurl?language=objc.
class NSUrlHostApi {
/// Constructor for [NSUrlHostApi]. 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.
NSUrlHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<String?> getAbsoluteString(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlHostApi.getAbsoluteString',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return (replyList[0] as String?);
}
}
}
/// Flutter API for `NSUrl`.
///
/// This class may handle instantiating and adding Dart instances that are
/// attached to a native instance or receiving callback methods from an
/// overridden native class.
///
/// See https://developer.apple.com/documentation/foundation/nsurl?language=objc.
abstract class NSUrlFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
void create(int identifier);
static void setup(NSUrlFlutterApi? api, {BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlFlutterApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlFlutterApi.create was null, expected non-null int.');
try {
api.create(arg_identifier!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
/// Host API for `UIScrollViewDelegate`.
///
/// This class may handle instantiating and adding native object instances that
/// are attached to a Dart instance or method calls on the associated native
/// class or an instance of the class.
///
/// See https://developer.apple.com/documentation/uikit/uiscrollviewdelegate?language=objc.
class UIScrollViewDelegateHostApi {
/// Constructor for [UIScrollViewDelegateHostApi]. 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.
UIScrollViewDelegateHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
Future<void> create(int arg_identifier) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateHostApi.create',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList =
await channel.send(<Object?>[arg_identifier]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
/// Flutter API for `UIScrollViewDelegate`.
///
/// See https://developer.apple.com/documentation/uikit/uiscrollviewdelegate?language=objc.
abstract class UIScrollViewDelegateFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
void scrollViewDidScroll(
int identifier, int uiScrollViewIdentifier, double x, double y);
static void setup(UIScrollViewDelegateFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateFlutterApi.scrollViewDidScroll',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateFlutterApi.scrollViewDidScroll 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_wkwebview.UIScrollViewDelegateFlutterApi.scrollViewDidScroll was null, expected non-null int.');
final int? arg_uiScrollViewIdentifier = (args[1] as int?);
assert(arg_uiScrollViewIdentifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateFlutterApi.scrollViewDidScroll was null, expected non-null int.');
final double? arg_x = (args[2] as double?);
assert(arg_x != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateFlutterApi.scrollViewDidScroll was null, expected non-null double.');
final double? arg_y = (args[3] as double?);
assert(arg_y != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateFlutterApi.scrollViewDidScroll was null, expected non-null double.');
try {
api.scrollViewDidScroll(
arg_identifier!, arg_uiScrollViewIdentifier!, arg_x!, arg_y!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
/// Host API for `NSUrlCredential`.
///
/// 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.apple.com/documentation/foundation/nsurlcredential?language=objc.
class NSUrlCredentialHostApi {
/// Constructor for [NSUrlCredentialHostApi]. 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.
NSUrlCredentialHostApi({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Create a new native instance and add it to the `InstanceManager`.
Future<void> createWithUser(int arg_identifier, String arg_user,
String arg_password, NSUrlCredentialPersistence arg_persistence) async {
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlCredentialHostApi.createWithUser',
codec,
binaryMessenger: _binaryMessenger);
final List<Object?>? replyList = await channel.send(<Object?>[
arg_identifier,
arg_user,
arg_password,
arg_persistence.index
]) as List<Object?>?;
if (replyList == null) {
throw PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel.',
);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}
/// Flutter API for `NSUrlProtectionSpace`.
///
/// This class may handle instantiating and adding Dart instances that are
/// attached to a native instance or receiving callback methods from an
/// overridden native class.
///
/// See https://developer.apple.com/documentation/foundation/nsurlprotectionspace?language=objc.
abstract class NSUrlProtectionSpaceFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Create a new Dart instance and add it to the `InstanceManager`.
void create(int identifier, String? host, String? realm,
String? authenticationMethod);
static void setup(NSUrlProtectionSpaceFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlProtectionSpaceFlutterApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlProtectionSpaceFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlProtectionSpaceFlutterApi.create was null, expected non-null int.');
final String? arg_host = (args[1] as String?);
final String? arg_realm = (args[2] as String?);
final String? arg_authenticationMethod = (args[3] as String?);
try {
api.create(
arg_identifier!, arg_host, arg_realm, arg_authenticationMethod);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
/// Flutter API for `NSUrlAuthenticationChallenge`.
///
/// This class may handle instantiating and adding Dart instances that are
/// attached to a native instance or receiving callback methods from an
/// overridden native class.
///
/// See https://developer.apple.com/documentation/foundation/nsurlauthenticationchallenge?language=objc.
abstract class NSUrlAuthenticationChallengeFlutterApi {
static const MessageCodec<Object?> codec = StandardMessageCodec();
/// Create a new Dart instance and add it to the `InstanceManager`.
void create(int identifier, int protectionSpaceIdentifier);
static void setup(NSUrlAuthenticationChallengeFlutterApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlAuthenticationChallengeFlutterApi.create',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
channel.setMessageHandler(null);
} else {
channel.setMessageHandler((Object? message) async {
assert(message != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlAuthenticationChallengeFlutterApi.create was null.');
final List<Object?> args = (message as List<Object?>?)!;
final int? arg_identifier = (args[0] as int?);
assert(arg_identifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlAuthenticationChallengeFlutterApi.create was null, expected non-null int.');
final int? arg_protectionSpaceIdentifier = (args[1] as int?);
assert(arg_protectionSpaceIdentifier != null,
'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlAuthenticationChallengeFlutterApi.create was null, expected non-null int.');
try {
api.create(arg_identifier!, arg_protectionSpaceIdentifier!);
return wrapResponse(empty: true);
} on PlatformException catch (e) {
return wrapResponse(error: e);
} catch (e) {
return wrapResponse(
error: PlatformException(code: 'error', message: e.toString()));
}
});
}
}
}
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/common/web_kit.g.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/common/web_kit.g.dart",
"repo_id": "packages",
"token_count": 53312
} | 1,052 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart';
import 'package:webview_flutter_wkwebview/src/foundation/foundation.dart';
import 'package:webview_flutter_wkwebview/src/ui_kit/ui_kit.dart';
import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart';
import 'package:webview_flutter_wkwebview/src/webkit_proxy.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
import 'webkit_webview_controller_test.mocks.dart';
@GenerateMocks(<Type>[
NSUrl,
UIScrollView,
UIScrollViewDelegate,
WKPreferences,
WKUserContentController,
WKWebsiteDataStore,
WKWebView,
WKWebViewConfiguration,
WKScriptMessageHandler,
])
void main() {
WidgetsFlutterBinding.ensureInitialized();
group('WebKitWebViewController', () {
WebKitWebViewController createControllerWithMocks({
MockUIScrollView? mockScrollView,
UIScrollViewDelegate? scrollViewDelegate,
MockWKPreferences? mockPreferences,
WKUIDelegate? uiDelegate,
MockWKUserContentController? mockUserContentController,
MockWKWebsiteDataStore? mockWebsiteDataStore,
MockWKWebView Function(
WKWebViewConfiguration configuration, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)? observeValue,
})? createMockWebView,
MockWKWebViewConfiguration? mockWebViewConfiguration,
InstanceManager? instanceManager,
}) {
final MockWKWebViewConfiguration nonNullMockWebViewConfiguration =
mockWebViewConfiguration ?? MockWKWebViewConfiguration();
late final MockWKWebView nonNullMockWebView;
final PlatformWebViewControllerCreationParams controllerCreationParams =
WebKitWebViewControllerCreationParams(
webKitProxy: WebKitProxy(
createWebViewConfiguration: ({InstanceManager? instanceManager}) {
return nonNullMockWebViewConfiguration;
},
createWebView: (
_, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)? observeValue,
InstanceManager? instanceManager,
}) {
nonNullMockWebView = createMockWebView == null
? MockWKWebView()
: createMockWebView(
nonNullMockWebViewConfiguration,
observeValue: observeValue,
);
return nonNullMockWebView;
},
createUIDelegate: ({
void Function(
WKWebView webView,
WKWebViewConfiguration configuration,
WKNavigationAction navigationAction,
)? onCreateWebView,
Future<WKPermissionDecision> Function(
WKUIDelegate instance,
WKWebView webView,
WKSecurityOrigin origin,
WKFrameInfo frame,
WKMediaCaptureType type,
)? requestMediaCapturePermission,
Future<void> Function(
String message,
WKFrameInfo frame,
)? runJavaScriptAlertDialog,
Future<bool> Function(
String message,
WKFrameInfo frame,
)? runJavaScriptConfirmDialog,
Future<String> Function(
String prompt,
String defaultText,
WKFrameInfo frame,
)? runJavaScriptTextInputDialog,
InstanceManager? instanceManager,
}) {
return uiDelegate ??
CapturingUIDelegate(
onCreateWebView: onCreateWebView,
requestMediaCapturePermission:
requestMediaCapturePermission,
runJavaScriptAlertDialog: runJavaScriptAlertDialog,
runJavaScriptConfirmDialog: runJavaScriptConfirmDialog,
runJavaScriptTextInputDialog: runJavaScriptTextInputDialog);
},
createScriptMessageHandler: WKScriptMessageHandler.detached,
createUIScrollViewDelegate: ({
void Function(UIScrollView, double, double)? scrollViewDidScroll,
}) {
return scrollViewDelegate ??
CapturingUIScrollViewDelegate(
scrollViewDidScroll: scrollViewDidScroll,
);
},
),
instanceManager: instanceManager,
);
final WebKitWebViewController controller = WebKitWebViewController(
controllerCreationParams,
);
when(nonNullMockWebView.scrollView)
.thenReturn(mockScrollView ?? MockUIScrollView());
when(nonNullMockWebView.configuration)
.thenReturn(nonNullMockWebViewConfiguration);
when(nonNullMockWebViewConfiguration.preferences)
.thenReturn(mockPreferences ?? MockWKPreferences());
when(nonNullMockWebViewConfiguration.userContentController).thenReturn(
mockUserContentController ?? MockWKUserContentController());
when(nonNullMockWebViewConfiguration.websiteDataStore)
.thenReturn(mockWebsiteDataStore ?? MockWKWebsiteDataStore());
return controller;
}
group('WebKitWebViewControllerCreationParams', () {
test('allowsInlineMediaPlayback', () {
final MockWKWebViewConfiguration mockConfiguration =
MockWKWebViewConfiguration();
WebKitWebViewControllerCreationParams(
webKitProxy: WebKitProxy(
createWebViewConfiguration: ({InstanceManager? instanceManager}) {
return mockConfiguration;
},
),
allowsInlineMediaPlayback: true,
);
verify(
mockConfiguration.setAllowsInlineMediaPlayback(true),
);
});
test('limitsNavigationsToAppBoundDomains', () {
final MockWKWebViewConfiguration mockConfiguration =
MockWKWebViewConfiguration();
WebKitWebViewControllerCreationParams(
webKitProxy: WebKitProxy(
createWebViewConfiguration: ({InstanceManager? instanceManager}) {
return mockConfiguration;
},
),
limitsNavigationsToAppBoundDomains: true,
);
verify(
mockConfiguration.setLimitsNavigationsToAppBoundDomains(true),
);
});
test(
'limitsNavigationsToAppBoundDomains is not called if it uses default value (false)',
() {
final MockWKWebViewConfiguration mockConfiguration =
MockWKWebViewConfiguration();
WebKitWebViewControllerCreationParams(
webKitProxy: WebKitProxy(
createWebViewConfiguration: ({InstanceManager? instanceManager}) {
return mockConfiguration;
},
),
);
verifyNever(
mockConfiguration.setLimitsNavigationsToAppBoundDomains(any),
);
});
test('mediaTypesRequiringUserAction', () {
final MockWKWebViewConfiguration mockConfiguration =
MockWKWebViewConfiguration();
WebKitWebViewControllerCreationParams(
webKitProxy: WebKitProxy(
createWebViewConfiguration: ({InstanceManager? instanceManager}) {
return mockConfiguration;
},
),
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{
PlaybackMediaTypes.video,
},
);
verify(
mockConfiguration.setMediaTypesRequiringUserActionForPlayback(
<WKAudiovisualMediaType>{
WKAudiovisualMediaType.video,
},
),
);
});
test('mediaTypesRequiringUserAction defaults to include audio and video',
() {
final MockWKWebViewConfiguration mockConfiguration =
MockWKWebViewConfiguration();
WebKitWebViewControllerCreationParams(
webKitProxy: WebKitProxy(
createWebViewConfiguration: ({InstanceManager? instanceManager}) {
return mockConfiguration;
},
),
);
verify(
mockConfiguration.setMediaTypesRequiringUserActionForPlayback(
<WKAudiovisualMediaType>{
WKAudiovisualMediaType.audio,
WKAudiovisualMediaType.video,
},
),
);
});
test('mediaTypesRequiringUserAction sets value to none if set is empty',
() {
final MockWKWebViewConfiguration mockConfiguration =
MockWKWebViewConfiguration();
WebKitWebViewControllerCreationParams(
webKitProxy: WebKitProxy(
createWebViewConfiguration: ({InstanceManager? instanceManager}) {
return mockConfiguration;
},
),
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
);
verify(
mockConfiguration.setMediaTypesRequiringUserActionForPlayback(
<WKAudiovisualMediaType>{WKAudiovisualMediaType.none},
),
);
});
});
test('loadFile', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.loadFile('/path/to/file.html');
verify(mockWebView.loadFileUrl(
'/path/to/file.html',
readAccessUrl: '/path/to',
));
});
test('loadFlutterAsset', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.loadFlutterAsset('test_assets/index.html');
verify(mockWebView.loadFlutterAsset('test_assets/index.html'));
});
test('loadHtmlString', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
const String htmlString = '<html><body>Test data.</body></html>';
await controller.loadHtmlString(htmlString, baseUrl: 'baseUrl');
verify(mockWebView.loadHtmlString(
'<html><body>Test data.</body></html>',
baseUrl: 'baseUrl',
));
});
group('loadRequest', () {
test('Throws ArgumentError for empty scheme', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
expect(
() async => controller.loadRequest(
LoadRequestParams(uri: Uri.parse('www.google.com')),
),
throwsA(isA<ArgumentError>()),
);
});
test('GET without headers', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.loadRequest(
LoadRequestParams(uri: Uri.parse('https://www.google.com')),
);
final NSUrlRequest request = verify(mockWebView.loadRequest(captureAny))
.captured
.single as NSUrlRequest;
expect(request.url, 'https://www.google.com');
expect(request.allHttpHeaderFields, <String, String>{});
expect(request.httpMethod, 'get');
});
test('GET with headers', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.loadRequest(
LoadRequestParams(
uri: Uri.parse('https://www.google.com'),
headers: const <String, String>{'a': 'header'},
),
);
final NSUrlRequest request = verify(mockWebView.loadRequest(captureAny))
.captured
.single as NSUrlRequest;
expect(request.url, 'https://www.google.com');
expect(request.allHttpHeaderFields, <String, String>{'a': 'header'});
expect(request.httpMethod, 'get');
});
test('POST without body', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.loadRequest(LoadRequestParams(
uri: Uri.parse('https://www.google.com'),
method: LoadRequestMethod.post,
));
final NSUrlRequest request = verify(mockWebView.loadRequest(captureAny))
.captured
.single as NSUrlRequest;
expect(request.url, 'https://www.google.com');
expect(request.httpMethod, 'post');
});
test('POST with body', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.loadRequest(LoadRequestParams(
uri: Uri.parse('https://www.google.com'),
method: LoadRequestMethod.post,
body: Uint8List.fromList('Test Body'.codeUnits),
));
final NSUrlRequest request = verify(mockWebView.loadRequest(captureAny))
.captured
.single as NSUrlRequest;
expect(request.url, 'https://www.google.com');
expect(request.httpMethod, 'post');
expect(
request.httpBody,
Uint8List.fromList('Test Body'.codeUnits),
);
});
});
test('canGoBack', () {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
when(mockWebView.canGoBack()).thenAnswer(
(_) => Future<bool>.value(false),
);
expect(controller.canGoBack(), completion(false));
});
test('canGoForward', () {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
when(mockWebView.canGoForward()).thenAnswer(
(_) => Future<bool>.value(true),
);
expect(controller.canGoForward(), completion(true));
});
test('goBack', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.goBack();
verify(mockWebView.goBack());
});
test('goForward', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.goForward();
verify(mockWebView.goForward());
});
test('reload', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.reload();
verify(mockWebView.reload());
});
test('setAllowsBackForwardNavigationGestures', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.setAllowsBackForwardNavigationGestures(true);
verify(mockWebView.setAllowsBackForwardNavigationGestures(true));
});
test('runJavaScriptReturningResult', () {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
final Object result = Object();
when(mockWebView.evaluateJavaScript('runJavaScript')).thenAnswer(
(_) => Future<Object>.value(result),
);
expect(
controller.runJavaScriptReturningResult('runJavaScript'),
completion(result),
);
});
test('runJavaScriptReturningResult throws error on null return value', () {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
when(mockWebView.evaluateJavaScript('runJavaScript')).thenAnswer(
(_) => Future<String?>.value(),
);
expect(
() => controller.runJavaScriptReturningResult('runJavaScript'),
throwsArgumentError,
);
});
test('runJavaScript', () {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
when(mockWebView.evaluateJavaScript('runJavaScript')).thenAnswer(
(_) => Future<String>.value('returnString'),
);
expect(
controller.runJavaScript('runJavaScript'),
completes,
);
});
test('runJavaScript ignores exception with unsupported javaScript type',
() {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
when(mockWebView.evaluateJavaScript('runJavaScript'))
.thenThrow(PlatformException(
code: '',
details: const NSError(
code: WKErrorCode.javaScriptResultTypeIsUnsupported,
domain: '',
),
));
expect(
controller.runJavaScript('runJavaScript'),
completes,
);
});
test('getTitle', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
when(mockWebView.getTitle())
.thenAnswer((_) => Future<String>.value('Web Title'));
expect(controller.getTitle(), completion('Web Title'));
});
test('currentUrl', () {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
when(mockWebView.getUrl())
.thenAnswer((_) => Future<String>.value('myUrl.com'));
expect(controller.currentUrl(), completion('myUrl.com'));
});
test('scrollTo', () async {
final MockUIScrollView mockScrollView = MockUIScrollView();
final WebKitWebViewController controller = createControllerWithMocks(
mockScrollView: mockScrollView,
);
await controller.scrollTo(2, 4);
verify(mockScrollView.setContentOffset(const Point<double>(2.0, 4.0)));
});
test('scrollBy', () async {
final MockUIScrollView mockScrollView = MockUIScrollView();
final WebKitWebViewController controller = createControllerWithMocks(
mockScrollView: mockScrollView,
);
await controller.scrollBy(2, 4);
verify(mockScrollView.scrollBy(const Point<double>(2.0, 4.0)));
});
test('getScrollPosition', () {
final MockUIScrollView mockScrollView = MockUIScrollView();
final WebKitWebViewController controller = createControllerWithMocks(
mockScrollView: mockScrollView,
);
when(mockScrollView.getContentOffset()).thenAnswer(
(_) => Future<Point<double>>.value(const Point<double>(8.0, 16.0)),
);
expect(
controller.getScrollPosition(),
completion(const Offset(8.0, 16.0)),
);
});
test('disable zoom', () async {
final MockWKUserContentController mockUserContentController =
MockWKUserContentController();
final WebKitWebViewController controller = createControllerWithMocks(
mockUserContentController: mockUserContentController,
);
await controller.enableZoom(false);
final WKUserScript zoomScript =
verify(mockUserContentController.addUserScript(captureAny))
.captured
.first as WKUserScript;
expect(zoomScript.isMainFrameOnly, isTrue);
expect(zoomScript.injectionTime, WKUserScriptInjectionTime.atDocumentEnd);
expect(
zoomScript.source,
"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);",
);
});
test('setBackgroundColor', () async {
final MockWKWebView mockWebView = MockWKWebView();
final MockUIScrollView mockScrollView = MockUIScrollView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
mockScrollView: mockScrollView,
);
await controller.setBackgroundColor(Colors.red);
// UIScrollView.setBackgroundColor must be called last.
verifyInOrder(<Object>[
mockWebView.setOpaque(false),
mockWebView.setBackgroundColor(Colors.transparent),
mockScrollView.setBackgroundColor(Colors.red),
]);
});
test('userAgent', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.setUserAgent('MyUserAgent');
verify(mockWebView.setCustomUserAgent('MyUserAgent'));
});
test('enable JavaScript', () async {
final MockWKPreferences mockPreferences = MockWKPreferences();
final WebKitWebViewController controller = createControllerWithMocks(
mockPreferences: mockPreferences,
);
await controller.setJavaScriptMode(JavaScriptMode.unrestricted);
verify(mockPreferences.setJavaScriptEnabled(true));
});
test('disable JavaScript', () async {
final MockWKPreferences mockPreferences = MockWKPreferences();
final WebKitWebViewController controller = createControllerWithMocks(
mockPreferences: mockPreferences,
);
await controller.setJavaScriptMode(JavaScriptMode.disabled);
verify(mockPreferences.setJavaScriptEnabled(false));
});
test('clearCache', () {
final MockWKWebsiteDataStore mockWebsiteDataStore =
MockWKWebsiteDataStore();
final WebKitWebViewController controller = createControllerWithMocks(
mockWebsiteDataStore: mockWebsiteDataStore,
);
when(
mockWebsiteDataStore.removeDataOfTypes(
<WKWebsiteDataType>{
WKWebsiteDataType.memoryCache,
WKWebsiteDataType.diskCache,
WKWebsiteDataType.offlineWebApplicationCache,
},
DateTime.fromMillisecondsSinceEpoch(0),
),
).thenAnswer((_) => Future<bool>.value(false));
expect(controller.clearCache(), completes);
});
test('clearLocalStorage', () {
final MockWKWebsiteDataStore mockWebsiteDataStore =
MockWKWebsiteDataStore();
final WebKitWebViewController controller = createControllerWithMocks(
mockWebsiteDataStore: mockWebsiteDataStore,
);
when(
mockWebsiteDataStore.removeDataOfTypes(
<WKWebsiteDataType>{WKWebsiteDataType.localStorage},
DateTime.fromMillisecondsSinceEpoch(0),
),
).thenAnswer((_) => Future<bool>.value(false));
expect(controller.clearLocalStorage(), completes);
});
test('addJavaScriptChannel', () async {
final WebKitProxy webKitProxy = WebKitProxy(
createScriptMessageHandler: ({
required void Function(
WKUserContentController userContentController,
WKScriptMessage message,
) didReceiveScriptMessage,
}) {
return WKScriptMessageHandler.detached(
didReceiveScriptMessage: didReceiveScriptMessage,
);
},
);
final WebKitJavaScriptChannelParams javaScriptChannelParams =
WebKitJavaScriptChannelParams(
name: 'name',
onMessageReceived: (JavaScriptMessage message) {},
webKitProxy: webKitProxy,
);
final MockWKUserContentController mockUserContentController =
MockWKUserContentController();
final WebKitWebViewController controller = createControllerWithMocks(
mockUserContentController: mockUserContentController,
);
await controller.addJavaScriptChannel(javaScriptChannelParams);
verify(mockUserContentController.addScriptMessageHandler(
argThat(isA<WKScriptMessageHandler>()),
'name',
));
final WKUserScript userScript =
verify(mockUserContentController.addUserScript(captureAny))
.captured
.single as WKUserScript;
expect(userScript.source, 'window.name = webkit.messageHandlers.name;');
expect(
userScript.injectionTime,
WKUserScriptInjectionTime.atDocumentStart,
);
});
test('addJavaScriptChannel requires channel with a unique name', () async {
final WebKitProxy webKitProxy = WebKitProxy(
createScriptMessageHandler: ({
required void Function(
WKUserContentController userContentController,
WKScriptMessage message,
) didReceiveScriptMessage,
}) {
return WKScriptMessageHandler.detached(
didReceiveScriptMessage: didReceiveScriptMessage,
);
},
);
final MockWKUserContentController mockUserContentController =
MockWKUserContentController();
final WebKitWebViewController controller = createControllerWithMocks(
mockUserContentController: mockUserContentController,
);
const String nonUniqueName = 'name';
final WebKitJavaScriptChannelParams javaScriptChannelParams =
WebKitJavaScriptChannelParams(
name: nonUniqueName,
onMessageReceived: (JavaScriptMessage message) {},
webKitProxy: webKitProxy,
);
await controller.addJavaScriptChannel(javaScriptChannelParams);
expect(
() => controller.addJavaScriptChannel(
JavaScriptChannelParams(
name: nonUniqueName,
onMessageReceived: (_) {},
),
),
throwsArgumentError,
);
});
test('removeJavaScriptChannel', () async {
final WebKitProxy webKitProxy = WebKitProxy(
createScriptMessageHandler: ({
required void Function(
WKUserContentController userContentController,
WKScriptMessage message,
) didReceiveScriptMessage,
}) {
return WKScriptMessageHandler.detached(
didReceiveScriptMessage: didReceiveScriptMessage,
);
},
);
final WebKitJavaScriptChannelParams javaScriptChannelParams =
WebKitJavaScriptChannelParams(
name: 'name',
onMessageReceived: (JavaScriptMessage message) {},
webKitProxy: webKitProxy,
);
final MockWKUserContentController mockUserContentController =
MockWKUserContentController();
final WebKitWebViewController controller = createControllerWithMocks(
mockUserContentController: mockUserContentController,
);
await controller.addJavaScriptChannel(javaScriptChannelParams);
reset(mockUserContentController);
await controller.removeJavaScriptChannel('name');
verify(mockUserContentController.removeAllUserScripts());
verify(mockUserContentController.removeScriptMessageHandler('name'));
verifyNoMoreInteractions(mockUserContentController);
});
test('removeJavaScriptChannel with zoom disabled', () async {
final WebKitProxy webKitProxy = WebKitProxy(
createScriptMessageHandler: ({
required void Function(
WKUserContentController userContentController,
WKScriptMessage message,
) didReceiveScriptMessage,
}) {
return WKScriptMessageHandler.detached(
didReceiveScriptMessage: didReceiveScriptMessage,
);
},
);
final WebKitJavaScriptChannelParams javaScriptChannelParams =
WebKitJavaScriptChannelParams(
name: 'name',
onMessageReceived: (JavaScriptMessage message) {},
webKitProxy: webKitProxy,
);
final MockWKUserContentController mockUserContentController =
MockWKUserContentController();
final WebKitWebViewController controller = createControllerWithMocks(
mockUserContentController: mockUserContentController,
);
await controller.enableZoom(false);
await controller.addJavaScriptChannel(javaScriptChannelParams);
clearInteractions(mockUserContentController);
await controller.removeJavaScriptChannel('name');
final WKUserScript zoomScript =
verify(mockUserContentController.addUserScript(captureAny))
.captured
.first as WKUserScript;
expect(zoomScript.isMainFrameOnly, isTrue);
expect(zoomScript.injectionTime, WKUserScriptInjectionTime.atDocumentEnd);
expect(
zoomScript.source,
"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);",
);
});
test('getUserAgent', () {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
const String userAgent = 'str';
when(mockWebView.getCustomUserAgent()).thenAnswer(
(_) => Future<String?>.value(userAgent),
);
expect(controller.getUserAgent(), completion(userAgent));
});
test('setPlatformNavigationDelegate', () {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
final WebKitNavigationDelegate navigationDelegate =
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: CapturingUIDelegate.new,
),
),
);
controller.setPlatformNavigationDelegate(navigationDelegate);
verify(
mockWebView.setNavigationDelegate(
CapturingNavigationDelegate.lastCreatedDelegate,
),
);
});
test('setPlatformNavigationDelegate onProgress', () async {
final MockWKWebView mockWebView = MockWKWebView();
late final void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) webViewObserveValue;
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (
_, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)? observeValue,
}) {
webViewObserveValue = observeValue!;
return mockWebView;
},
);
verify(
mockWebView.addObserver(
mockWebView,
keyPath: 'estimatedProgress',
options: <NSKeyValueObservingOptions>{
NSKeyValueObservingOptions.newValue,
},
),
);
final WebKitNavigationDelegate navigationDelegate =
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: WKUIDelegate.detached,
),
),
);
late final int callbackProgress;
await navigationDelegate.setOnProgress(
(int progress) => callbackProgress = progress,
);
await controller.setPlatformNavigationDelegate(navigationDelegate);
webViewObserveValue(
'estimatedProgress',
mockWebView,
<NSKeyValueChangeKey, Object?>{NSKeyValueChangeKey.newValue: 0.0},
);
expect(callbackProgress, 0);
});
test('Requests to open a new window loads request in same window', () {
// Reset last created delegate.
CapturingUIDelegate.lastCreatedDelegate = CapturingUIDelegate();
// Create a new WebKitWebViewController that sets
// CapturingUIDelegate.lastCreatedDelegate.
createControllerWithMocks();
final MockWKWebView mockWebView = MockWKWebView();
const NSUrlRequest request = NSUrlRequest(url: 'https://www.google.com');
CapturingUIDelegate.lastCreatedDelegate.onCreateWebView!(
mockWebView,
WKWebViewConfiguration.detached(),
const WKNavigationAction(
request: request,
targetFrame: WKFrameInfo(
isMainFrame: false,
request: NSUrlRequest(url: 'https://google.com')),
navigationType: WKNavigationType.linkActivated,
),
);
verify(mockWebView.loadRequest(request));
});
test(
'setPlatformNavigationDelegate onProgress can be changed by the WebKitNavigationDelegate',
() async {
final MockWKWebView mockWebView = MockWKWebView();
late final void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) webViewObserveValue;
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (
_, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)? observeValue,
}) {
webViewObserveValue = observeValue!;
return mockWebView;
},
);
final WebKitNavigationDelegate navigationDelegate =
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: WKUIDelegate.detached,
),
),
);
// First value of onProgress does nothing.
await navigationDelegate.setOnProgress((_) {});
await controller.setPlatformNavigationDelegate(navigationDelegate);
// Second value of onProgress sets `callbackProgress`.
late final int callbackProgress;
await navigationDelegate.setOnProgress(
(int progress) => callbackProgress = progress,
);
webViewObserveValue(
'estimatedProgress',
mockWebView,
<NSKeyValueChangeKey, Object?>{NSKeyValueChangeKey.newValue: 0.0},
);
expect(callbackProgress, 0);
});
test('setPlatformNavigationDelegate onUrlChange', () async {
final MockWKWebView mockWebView = MockWKWebView();
late final void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) webViewObserveValue;
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (
_, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)? observeValue,
}) {
webViewObserveValue = observeValue!;
return mockWebView;
},
);
verify(
mockWebView.addObserver(
mockWebView,
keyPath: 'URL',
options: <NSKeyValueObservingOptions>{
NSKeyValueObservingOptions.newValue,
},
),
);
final WebKitNavigationDelegate navigationDelegate =
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: WKUIDelegate.detached,
),
),
);
final Completer<UrlChange> urlChangeCompleter = Completer<UrlChange>();
await navigationDelegate.setOnUrlChange(
(UrlChange change) => urlChangeCompleter.complete(change),
);
await controller.setPlatformNavigationDelegate(navigationDelegate);
final MockNSUrl mockNSUrl = MockNSUrl();
when(mockNSUrl.getAbsoluteString()).thenAnswer((_) {
return Future<String>.value('https://www.google.com');
});
webViewObserveValue(
'URL',
mockWebView,
<NSKeyValueChangeKey, Object?>{NSKeyValueChangeKey.newValue: mockNSUrl},
);
final UrlChange urlChange = await urlChangeCompleter.future;
expect(urlChange.url, 'https://www.google.com');
});
test('setPlatformNavigationDelegate onUrlChange to null NSUrl', () async {
final MockWKWebView mockWebView = MockWKWebView();
late final void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
) webViewObserveValue;
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (
_, {
void Function(
String keyPath,
NSObject object,
Map<NSKeyValueChangeKey, Object?> change,
)? observeValue,
}) {
webViewObserveValue = observeValue!;
return mockWebView;
},
);
final WebKitNavigationDelegate navigationDelegate =
WebKitNavigationDelegate(
const WebKitNavigationDelegateCreationParams(
webKitProxy: WebKitProxy(
createNavigationDelegate: CapturingNavigationDelegate.new,
createUIDelegate: WKUIDelegate.detached,
),
),
);
final Completer<UrlChange> urlChangeCompleter = Completer<UrlChange>();
await navigationDelegate.setOnUrlChange(
(UrlChange change) => urlChangeCompleter.complete(change),
);
await controller.setPlatformNavigationDelegate(navigationDelegate);
webViewObserveValue(
'URL',
mockWebView,
<NSKeyValueChangeKey, Object?>{NSKeyValueChangeKey.newValue: null},
);
final UrlChange urlChange = await urlChangeCompleter.future;
expect(urlChange.url, isNull);
});
test('webViewIdentifier', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final MockWKWebView mockWebView = MockWKWebView();
when(mockWebView.copy()).thenReturn(MockWKWebView());
instanceManager.addHostCreatedInstance(mockWebView, 0);
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
instanceManager: instanceManager,
);
expect(
controller.webViewIdentifier,
instanceManager.getIdentifier(mockWebView),
);
});
test('setOnPermissionRequest', () async {
final WebKitWebViewController controller = createControllerWithMocks();
late final PlatformWebViewPermissionRequest permissionRequest;
await controller.setOnPlatformPermissionRequest(
(PlatformWebViewPermissionRequest request) async {
permissionRequest = request;
await request.grant();
},
);
final Future<WKPermissionDecision> Function(
WKUIDelegate instance,
WKWebView webView,
WKSecurityOrigin origin,
WKFrameInfo frame,
WKMediaCaptureType type,
) onPermissionRequestCallback = CapturingUIDelegate
.lastCreatedDelegate.requestMediaCapturePermission!;
final WKPermissionDecision decision = await onPermissionRequestCallback(
CapturingUIDelegate.lastCreatedDelegate,
WKWebView.detached(),
const WKSecurityOrigin(host: '', port: 0, protocol: ''),
const WKFrameInfo(
isMainFrame: false,
request: NSUrlRequest(url: 'https://google.com')),
WKMediaCaptureType.microphone,
);
expect(permissionRequest.types, <WebViewPermissionResourceType>[
WebViewPermissionResourceType.microphone,
]);
expect(decision, WKPermissionDecision.grant);
});
group('JavaScript Dialog', () {
test('setOnJavaScriptAlertDialog', () async {
final WebKitWebViewController controller = createControllerWithMocks();
late final String message;
await controller.setOnJavaScriptAlertDialog(
(JavaScriptAlertDialogRequest request) async {
message = request.message;
return;
});
const String callbackMessage = 'Message';
final Future<void> Function(String message, WKFrameInfo frame)
onJavaScriptAlertDialog =
CapturingUIDelegate.lastCreatedDelegate.runJavaScriptAlertDialog!;
await onJavaScriptAlertDialog(
callbackMessage,
const WKFrameInfo(
isMainFrame: false,
request: NSUrlRequest(url: 'https://google.com')));
expect(message, callbackMessage);
});
test('setOnJavaScriptConfirmDialog', () async {
final WebKitWebViewController controller = createControllerWithMocks();
late final String message;
const bool callbackReturnValue = true;
await controller.setOnJavaScriptConfirmDialog(
(JavaScriptConfirmDialogRequest request) async {
message = request.message;
return callbackReturnValue;
});
const String callbackMessage = 'Message';
final Future<bool> Function(String message, WKFrameInfo frame)
onJavaScriptConfirmDialog =
CapturingUIDelegate.lastCreatedDelegate.runJavaScriptConfirmDialog!;
final bool returnValue = await onJavaScriptConfirmDialog(
callbackMessage,
const WKFrameInfo(
isMainFrame: false,
request: NSUrlRequest(url: 'https://google.com')));
expect(message, callbackMessage);
expect(returnValue, callbackReturnValue);
});
test('setOnJavaScriptTextInputDialog', () async {
final WebKitWebViewController controller = createControllerWithMocks();
late final String message;
late final String? defaultText;
const String callbackReturnValue = 'Return Value';
await controller.setOnJavaScriptTextInputDialog(
(JavaScriptTextInputDialogRequest request) async {
message = request.message;
defaultText = request.defaultText;
return callbackReturnValue;
});
const String callbackMessage = 'Message';
const String callbackDefaultText = 'Default Text';
final Future<String> Function(
String prompt, String defaultText, WKFrameInfo frame)
onJavaScriptTextInputDialog = CapturingUIDelegate
.lastCreatedDelegate.runJavaScriptTextInputDialog!;
final String returnValue = await onJavaScriptTextInputDialog(
callbackMessage,
callbackDefaultText,
const WKFrameInfo(
isMainFrame: false,
request: NSUrlRequest(url: 'https://google.com')));
expect(message, callbackMessage);
expect(defaultText, callbackDefaultText);
expect(returnValue, callbackReturnValue);
});
});
test('inspectable', () async {
final MockWKWebView mockWebView = MockWKWebView();
final WebKitWebViewController controller = createControllerWithMocks(
createMockWebView: (_, {dynamic observeValue}) => mockWebView,
);
await controller.setInspectable(true);
verify(mockWebView.setInspectable(true));
});
group('Console logging', () {
test('setConsoleLogCallback should inject the correct JavaScript',
() async {
final MockWKUserContentController mockUserContentController =
MockWKUserContentController();
final WebKitWebViewController controller = createControllerWithMocks(
mockUserContentController: mockUserContentController,
);
await controller
.setOnConsoleMessage((JavaScriptConsoleMessage message) {});
final List<dynamic> capturedScripts =
verify(mockUserContentController.addUserScript(captureAny))
.captured
.toList();
final WKUserScript messageHandlerScript =
capturedScripts[0] as WKUserScript;
final WKUserScript overrideConsoleScript =
capturedScripts[1] as WKUserScript;
expect(messageHandlerScript.isMainFrameOnly, isFalse);
expect(messageHandlerScript.injectionTime,
WKUserScriptInjectionTime.atDocumentStart);
expect(messageHandlerScript.source,
'window.fltConsoleMessage = webkit.messageHandlers.fltConsoleMessage;');
expect(overrideConsoleScript.isMainFrameOnly, isTrue);
expect(overrideConsoleScript.injectionTime,
WKUserScriptInjectionTime.atDocumentStart);
expect(overrideConsoleScript.source, '''
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);
});
''');
});
test('setConsoleLogCallback should parse levels correctly', () async {
final MockWKUserContentController mockUserContentController =
MockWKUserContentController();
final WebKitWebViewController controller = createControllerWithMocks(
mockUserContentController: mockUserContentController,
);
final Map<JavaScriptLogLevel, String> logs =
<JavaScriptLogLevel, String>{};
await controller.setOnConsoleMessage(
(JavaScriptConsoleMessage message) =>
logs[message.level] = message.message);
final List<dynamic> capturedParameters = verify(
mockUserContentController.addScriptMessageHandler(
captureAny, any))
.captured
.toList();
final WKScriptMessageHandler scriptMessageHandler =
capturedParameters[0] as WKScriptMessageHandler;
scriptMessageHandler.didReceiveScriptMessage(
mockUserContentController,
const WKScriptMessage(
name: 'test',
body: '{"level": "debug", "message": "Debug message"}'));
scriptMessageHandler.didReceiveScriptMessage(
mockUserContentController,
const WKScriptMessage(
name: 'test',
body: '{"level": "error", "message": "Error message"}'));
scriptMessageHandler.didReceiveScriptMessage(
mockUserContentController,
const WKScriptMessage(
name: 'test',
body: '{"level": "info", "message": "Info message"}'));
scriptMessageHandler.didReceiveScriptMessage(
mockUserContentController,
const WKScriptMessage(
name: 'test',
body: '{"level": "log", "message": "Log message"}'));
scriptMessageHandler.didReceiveScriptMessage(
mockUserContentController,
const WKScriptMessage(
name: 'test',
body: '{"level": "warning", "message": "Warning message"}'));
expect(logs.length, 5);
expect(logs[JavaScriptLogLevel.debug], 'Debug message');
expect(logs[JavaScriptLogLevel.error], 'Error message');
expect(logs[JavaScriptLogLevel.info], 'Info message');
expect(logs[JavaScriptLogLevel.log], 'Log message');
expect(logs[JavaScriptLogLevel.warning], 'Warning message');
});
});
test('setOnScrollPositionChange', () async {
final WebKitWebViewController controller = createControllerWithMocks();
final Completer<ScrollPositionChange> changeCompleter =
Completer<ScrollPositionChange>();
await controller.setOnScrollPositionChange(
(ScrollPositionChange change) {
changeCompleter.complete(change);
},
);
final void Function(
UIScrollView scrollView,
double,
double,
) onScrollViewDidScroll = CapturingUIScrollViewDelegate
.lastCreatedDelegate.scrollViewDidScroll!;
final MockUIScrollView mockUIScrollView = MockUIScrollView();
onScrollViewDidScroll(mockUIScrollView, 1.0, 2.0);
final ScrollPositionChange change = await changeCompleter.future;
expect(change.x, 1.0);
expect(change.y, 2.0);
});
});
group('WebKitJavaScriptChannelParams', () {
test('onMessageReceived', () async {
late final WKScriptMessageHandler messageHandler;
final WebKitProxy webKitProxy = WebKitProxy(
createScriptMessageHandler: ({
required void Function(
WKUserContentController userContentController,
WKScriptMessage message,
) didReceiveScriptMessage,
}) {
messageHandler = WKScriptMessageHandler.detached(
didReceiveScriptMessage: didReceiveScriptMessage,
);
return messageHandler;
},
);
late final String callbackMessage;
WebKitJavaScriptChannelParams(
name: 'name',
onMessageReceived: (JavaScriptMessage message) {
callbackMessage = message.message;
},
webKitProxy: webKitProxy,
);
messageHandler.didReceiveScriptMessage(
MockWKUserContentController(),
const WKScriptMessage(name: 'name', body: 'myMessage'),
);
expect(callbackMessage, 'myMessage');
});
});
}
// Records the last created instance of itself.
class CapturingNavigationDelegate extends WKNavigationDelegate {
CapturingNavigationDelegate({
super.didFinishNavigation,
super.didStartProvisionalNavigation,
super.didFailNavigation,
super.didFailProvisionalNavigation,
super.decidePolicyForNavigationAction,
super.decidePolicyForNavigationResponse,
super.webViewWebContentProcessDidTerminate,
super.didReceiveAuthenticationChallenge,
}) : super.detached() {
lastCreatedDelegate = this;
}
static CapturingNavigationDelegate lastCreatedDelegate =
CapturingNavigationDelegate();
}
// Records the last created instance of itself.
class CapturingUIDelegate extends WKUIDelegate {
CapturingUIDelegate({
super.onCreateWebView,
super.requestMediaCapturePermission,
super.runJavaScriptAlertDialog,
super.runJavaScriptConfirmDialog,
super.runJavaScriptTextInputDialog,
super.instanceManager,
}) : super.detached() {
lastCreatedDelegate = this;
}
static CapturingUIDelegate lastCreatedDelegate = CapturingUIDelegate();
}
class CapturingUIScrollViewDelegate extends UIScrollViewDelegate {
CapturingUIScrollViewDelegate({
super.scrollViewDidScroll,
super.instanceManager,
}) : super.detached() {
lastCreatedDelegate = this;
}
static CapturingUIScrollViewDelegate lastCreatedDelegate =
CapturingUIScrollViewDelegate();
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_controller_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/test/webkit_webview_controller_test.dart",
"repo_id": "packages",
"token_count": 21846
} | 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.
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:xdg_directories/xdg_directories.dart';
import 'package:xdg_directories_example/main.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('xdg_directories_demo', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
expect(find.textContaining(dataHome.path), findsWidgets);
expect(find.textContaining(configHome.path), findsWidgets);
expect(
find.textContaining(
dataDirs.map((Directory directory) => directory.path).join('\n')),
findsWidgets);
expect(
find.textContaining(
configDirs.map((Directory directory) => directory.path).join('\n')),
findsWidgets);
expect(
find.textContaining(cacheHome.path, skipOffstage: false),
findsWidgets,
);
expect(find.textContaining(runtimeDir?.path ?? '', skipOffstage: false),
findsWidgets);
});
}
| packages/packages/xdg_directories/example/integration_test/xdg_directories_test.dart/0 | {
"file_path": "packages/packages/xdg_directories/example/integration_test/xdg_directories_test.dart",
"repo_id": "packages",
"token_count": 463
} | 1,054 |
# The list of external dependencies that are allowed as unpinned dependencies.
# See https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#Dependencies
#
# All entries here should have an explanation for why they are here, either
# via being part of one of the default-allowed groups, or a specific reason.
## Explicit allowances
# Owned by individual Flutter Team members.
# Ideally we would not do this, since there's no clear plan for what
# would happen if the individuals left the Flutter Team, and the
# repositories may or may not meet Flutter's security standards. Be
# cautious about adding to this list.
- build_verify
- google_maps
- win32
## Allowed by default
# Dart-team-owned packages
- analyzer
- args
- async
- build
- build_config
- build_runner
- build_test
- code_builder
- collection
- convert
- crypto
- dart_style
- fake_async
- ffi
- gcloud
- html
- http
- intl
- io
- js
- json_serializable
- lints
- logging
- markdown
- meta
- mime
- path
- shelf
- shelf_static
- source_gen
- stream_transform
- test
- test_api
- vm_service
- wasm
- web
- yaml
# Google-owned packages
- _discoveryapis_commons
- adaptive_navigation
- file
- googleapis
- googleapis_auth
- json_annotation
- quiver
- sanitize_html
- source_helper
- vector_math
- webkit_inspection_protocol
| packages/script/configs/allowed_unpinned_deps.yaml/0 | {
"file_path": "packages/script/configs/allowed_unpinned_deps.yaml",
"repo_id": "packages",
"token_count": 411
} | 1,055 |
# Flutter Plugin Tools
This is a set of utilities used in this repository, both for CI and for
local development.
## Getting Started
Set up:
```sh
cd script/tool && dart pub get && cd ../../
```
Run:
```sh
dart run script/tool/bin/flutter_plugin_tools.dart <args>
```
Many commands require the Flutter-bundled version of Dart to be the first `dart` in the path.
## Commands
Run with `--help` for a full list of commands and arguments, but the
following shows a number of common commands being run for a specific package.
Most commands take a `--packages` argument to control which package(s) the
command is targetting. An package name can be any of:
- The name of a package (e.g., `path_provider_android`).
- The name of a federated plugin (e.g., `path_provider`), in which case all
packages that make up that plugin will be targetted.
- A combination federated_plugin_name/package_name (e.g.,
`path_provider/path_provider` for the app-facing package).
The examples below assume they are being run from the repository root, but
the script works from anywhere. If you develop in flutter/packages frequently,
it may be useful to make an alias for
`dart run /absolute/path/to/script/tool/bin/flutter_plugin_tools.dart` so that
you can easily run commands from within packages. For that use case there is
also a `--current-package` flag as an alternative to `--packages`, to target the
current working directory's package (or enclosing package; it can be used from
anywhere within a package).
### Format Code
```sh
dart run script/tool/bin/flutter_plugin_tools.dart format --packages package_name
```
### Run the Dart Static Analyzer
```sh
dart run script/tool/bin/flutter_plugin_tools.dart analyze --packages package_name
```
### Run Dart Unit Tests
```sh
dart run script/tool/bin/flutter_plugin_tools.dart test --packages package_name
```
### Run Dart Integration Tests
```sh
dart run script/tool/bin/flutter_plugin_tools.dart build-examples --apk --packages package_name
dart run script/tool/bin/flutter_plugin_tools.dart drive-examples --android --packages package_name
```
Replace `--apk`/`--android` with the platform you want to test against
(omit it to get a list of valid options).
### Run Native Tests
`native-test` takes one or more platform flags to run tests for. By default it
runs both unit tests and (on platforms that support it) integration tests, but
`--no-unit` or `--no-integration` can be used to run just one type.
Examples:
```sh
# Run just unit tests for iOS and Android:
dart run script/tool/bin/flutter_plugin_tools.dart native-test --ios --android --no-integration --packages package_name
# Run all tests for macOS:
dart run script/tool/bin/flutter_plugin_tools.dart native-test --macos --packages package_name
# Run all tests for Windows:
dart run script/tool/bin/flutter_plugin_tools.dart native-test --windows --packages package_name
```
### Update README.md from Example Sources
```sh
# Update all .md files for all packages:
dart run script/tool/bin/flutter_plugin_tools.dart update-excerpts
# Update the .md files only for one package:
dart run script/tool/bin/flutter_plugin_tools.dart update-excerpts --packages package_name
```
_See also: https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#readme-code_
### Update CHANGELOG and Version
`update-release-info` will automatically update the version and `CHANGELOG.md`
following standard repository style and practice. It can be used for
single-package updates to handle the details of getting the `CHANGELOG.md`
format correct, but is especially useful for bulk updates across multiple packages.
For instance, if you add a new analysis option that requires production
code changes across many packages:
```sh
dart run script/tool/bin/flutter_plugin_tools.dart update-release-info \
--version=minimal \
--base-branch=upstream/main \
--changelog="Fixes violations of new analysis option some_new_option."
```
The `minimal` option for `--version` will skip unchanged packages, and treat
each changed package as either `bugfix` or `next` depending on the files that
have changed in that package, so it is often the best choice for a bulk change.
For cases where you know the change type, `minor` or `bugfix` will make the
corresponding version bump, or `next` will update only `CHANGELOG.md` without
changing the version.
If you have a standard repository setup, `--base-branch=upstream/main` will
usually give the behavior you want, finding all packages changed relative to
the branch point from `upstream/main`. For more complex use cases where you want
a different diff point, you can pass a different `--base-branch`, or use
`--base-sha` to pick the exact diff point.
### Update a dependency
`update-dependency` will update a pub dependency to a new version.
For instance, to updated to version 3.0.0 of `some_package` in every package
that depends on it:
```sh
dart run script/tool/bin/flutter_plugin_tools.dart update-dependency \
--pub-package=some_package \
--version=3.0.0 \
```
If a `--version` is not provided, the latest version from pub will be used.
Currently this only updates the dependency itself in pubspec.yaml, but in the
future this will also update any generated code for packages that use code
generation (e.g., regenerating mocks when updating `mockito`).
### Publish a Release
**Releases are automated for `flutter/packages`.**
The manual procedure described here is _deprecated_, and should only be used when
the automated process fails. Please, read
[Releasing a Plugin or Package](https://github.com/flutter/flutter/wiki/Releasing-a-Plugin-or-Package)
on the Flutter Wiki first.
```sh
cd <path_to_repo>
git checkout <commit_hash_to_publish>
dart run script/tool/bin/flutter_plugin_tools.dart publish --packages <package>
```
By default the tool tries to push tags to the `upstream` remote, but some
additional settings can be configured. Run `dart run script/tool/bin/flutter_plugin_tools.dart
publish --help` for more usage information.
The tool wraps `pub publish` for pushing the package to pub, and then will
automatically use git to try to create and push tags. It has some additional
safety checking around `pub publish` too. By default `pub publish` publishes
_everything_, including untracked or uncommitted files in version control.
`publish` will first check the status of the local
directory and refuse to publish if there are any mismatched files with version
control present.
| packages/script/tool/README.md/0 | {
"file_path": "packages/script/tool/README.md",
"repo_id": "packages",
"token_count": 1859
} | 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.
import 'package:file/file.dart';
import 'package:path/path.dart' as p;
import 'common/core.dart';
import 'common/output_utils.dart';
import 'common/package_command.dart';
const Set<String> _codeFileExtensions = <String>{
'.c',
'.cc',
'.cpp',
'.dart',
'.h',
'.html',
'.java',
'.kt',
'.m',
'.mm',
'.swift',
'.sh',
};
// Basenames without extensions of files to ignore.
const Set<String> _ignoreBasenameList = <String>{
'flutter_export_environment',
'GeneratedPluginRegistrant',
'generated_plugin_registrant',
};
// File suffixes that otherwise match _codeFileExtensions to ignore.
const Set<String> _ignoreSuffixList = <String>{
'.g.dart', // Generated API code.
'.mocks.dart', // Generated by Mockito.
};
// Full basenames of files to ignore.
const Set<String> _ignoredFullBasenameList = <String>{
'resource.h', // Generated by VS.
};
// Copyright and license regexes for third-party code.
//
// These are intentionally very simple, since there is very little third-party
// code in this repository. Complexity can be added as-needed on a case-by-case
// basis.
//
// When adding license regexes here, include the copyright info to ensure that
// any new additions are flagged for added scrutiny in review.
final List<RegExp> _thirdPartyLicenseBlockRegexes = <RegExp>[
// Third-party code used in url_launcher_web.
RegExp(
r'^// Copyright 2017 Workiva Inc\..*'
r'^// Licensed under the Apache License, Version 2\.0',
multiLine: true,
dotAll: true,
),
// Third-party code used in google_maps_flutter_web.
RegExp(
r'^// The MIT License [^C]+ Copyright \(c\) 2008 Krasimir Tsonev',
multiLine: true,
),
// bsdiff in flutter/packages.
RegExp(
r'// Copyright 2003-2005 Colin Percival\. All rights reserved\.\n'
r'// Use of this source code is governed by a BSD-style license that can be\n'
r'// found in the LICENSE file\.\n',
),
];
// The exact format of the BSD license that our license files should contain.
// Slight variants are not accepted because they may prevent consolidation in
// tools that assemble all licenses used in distributed applications.
// standardized.
const String _fullBsdLicenseText = '''
Copyright 2013 The Flutter Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
''';
/// Validates that code files have copyright and license blocks.
class LicenseCheckCommand extends PackageCommand {
/// Creates a new license check command for [packagesDir].
LicenseCheckCommand(super.packagesDir, {super.platform, super.gitDir});
@override
final String name = 'license-check';
@override
List<String> get aliases => <String>['check-license'];
@override
final String description =
'Ensures that all code files have copyright/license blocks.';
@override
Future<void> run() async {
// Create a set of absolute paths to submodule directories, with trailing
// separator, to do prefix matching with to test directory inclusion.
final Iterable<String> submodulePaths = (await _getSubmoduleDirectories())
.map(
(Directory dir) => '${dir.absolute.path}${platform.pathSeparator}');
final Iterable<File> allFiles = (await _getAllFiles()).where(
(File file) => !submodulePaths.any(file.absolute.path.startsWith));
final Iterable<File> codeFiles = allFiles.where((File file) =>
_codeFileExtensions.contains(p.extension(file.path)) &&
!_shouldIgnoreFile(file));
final Iterable<File> firstPartyLicenseFiles = allFiles.where((File file) =>
path.basename(file.basename) == 'LICENSE' && !_isThirdParty(file));
final List<File> licenseFileFailures =
await _checkLicenseFiles(firstPartyLicenseFiles);
final Map<_LicenseFailureType, List<File>> codeFileFailures =
await _checkCodeLicenses(codeFiles);
bool passed = true;
print('\n=======================================\n');
if (licenseFileFailures.isNotEmpty) {
passed = false;
printError(
'The following LICENSE files do not follow the expected format:');
for (final File file in licenseFileFailures) {
printError(' ${file.path}');
}
printError('Please ensure that they use the exact format used in this '
'repository".\n');
}
if (codeFileFailures[_LicenseFailureType.incorrectFirstParty]!.isNotEmpty) {
passed = false;
printError('The license block for these files is missing or incorrect:');
for (final File file
in codeFileFailures[_LicenseFailureType.incorrectFirstParty]!) {
printError(' ${file.path}');
}
printError(
'If this third-party code, move it to a "third_party/" directory, '
'otherwise ensure that you are using the exact copyright and license '
'text used by all first-party files in this repository.\n');
}
if (codeFileFailures[_LicenseFailureType.unknownThirdParty]!.isNotEmpty) {
passed = false;
printError(
'No recognized license was found for the following third-party files:');
for (final File file
in codeFileFailures[_LicenseFailureType.unknownThirdParty]!) {
printError(' ${file.path}');
}
print('Please check that they have a license at the top of the file. '
'If they do, the license check needs to be updated to recognize '
'the new third-party license block.\n');
}
if (!passed) {
throw ToolExit(1);
}
printSuccess('All files passed validation!');
}
// Creates the expected copyright+license block for first-party code.
String _generateLicenseBlock(
String comment, {
String prefix = '',
String suffix = '',
}) {
return '$prefix${comment}Copyright 2013 The Flutter Authors. All rights reserved.\n'
'${comment}Use of this source code is governed by a BSD-style license that can be\n'
'${comment}found in the LICENSE file.$suffix\n';
}
/// Checks all license blocks for [codeFiles], returning any that fail
/// validation.
Future<Map<_LicenseFailureType, List<File>>> _checkCodeLicenses(
Iterable<File> codeFiles) async {
final List<File> incorrectFirstPartyFiles = <File>[];
final List<File> unrecognizedThirdPartyFiles = <File>[];
// Most code file types in the repository use '//' comments.
final String defaultFirstParyLicenseBlock = _generateLicenseBlock('// ');
// A few file types have a different comment structure.
final Map<String, String> firstPartyLicenseBlockByExtension =
<String, String>{
'.sh': _generateLicenseBlock('# '),
'.html': _generateLicenseBlock('', prefix: '<!-- ', suffix: ' -->'),
};
for (final File file in codeFiles) {
print('Checking ${file.path}');
// On Windows, git may auto-convert line endings on checkout; this should
// still pass since they will be converted back on commit.
final String content =
(await file.readAsString()).replaceAll('\r\n', '\n');
final String firstParyLicense =
firstPartyLicenseBlockByExtension[p.extension(file.path)] ??
defaultFirstParyLicenseBlock;
if (_isThirdParty(file)) {
// Third-party directories allow either known third-party licenses, our
// the first-party license, as there may be local additions.
if (!_thirdPartyLicenseBlockRegexes
.any((RegExp regex) => regex.hasMatch(content)) &&
!content.contains(firstParyLicense)) {
unrecognizedThirdPartyFiles.add(file);
}
} else {
if (!content.contains(firstParyLicense)) {
incorrectFirstPartyFiles.add(file);
}
}
}
// Sort by path for more usable output.
int pathCompare(File a, File b) => a.path.compareTo(b.path);
incorrectFirstPartyFiles.sort(pathCompare);
unrecognizedThirdPartyFiles.sort(pathCompare);
return <_LicenseFailureType, List<File>>{
_LicenseFailureType.incorrectFirstParty: incorrectFirstPartyFiles,
_LicenseFailureType.unknownThirdParty: unrecognizedThirdPartyFiles,
};
}
/// Checks all provided LICENSE [files], returning any that fail validation.
Future<List<File>> _checkLicenseFiles(Iterable<File> files) async {
final List<File> incorrectLicenseFiles = <File>[];
for (final File file in files) {
print('Checking ${file.path}');
// On Windows, git may auto-convert line endings on checkout; this should
// still pass since they will be converted back on commit.
final String contents = file.readAsStringSync().replaceAll('\r\n', '\n');
if (!contents.contains(_fullBsdLicenseText)) {
incorrectLicenseFiles.add(file);
}
}
return incorrectLicenseFiles;
}
bool _shouldIgnoreFile(File file) {
final String path = file.path;
return _ignoreBasenameList.contains(p.basenameWithoutExtension(path)) ||
_ignoreSuffixList.any((String suffix) =>
path.endsWith(suffix) ||
_ignoredFullBasenameList.contains(p.basename(path)));
}
bool _isThirdParty(File file) {
return path.split(file.path).contains('third_party');
}
Future<List<File>> _getAllFiles() => packagesDir.parent
.list(recursive: true, followLinks: false)
.where((FileSystemEntity entity) => entity is File)
.map((FileSystemEntity file) => file as File)
.toList();
// Returns the directories containing mapped submodules, if any.
Future<Iterable<Directory>> _getSubmoduleDirectories() async {
final List<Directory> submodulePaths = <Directory>[];
final Directory repoRoot =
packagesDir.fileSystem.directory((await gitDir).path);
final File submoduleSpec = repoRoot.childFile('.gitmodules');
if (submoduleSpec.existsSync()) {
final RegExp pathLine = RegExp(r'path\s*=\s*(.*)');
for (final String line in submoduleSpec.readAsLinesSync()) {
final RegExpMatch? match = pathLine.firstMatch(line);
if (match != null) {
submodulePaths.add(repoRoot.childDirectory(match.group(1)!.trim()));
}
}
}
return submodulePaths;
}
}
enum _LicenseFailureType { incorrectFirstParty, unknownThirdParty }
| packages/script/tool/lib/src/license_check_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/license_check_command.dart",
"repo_id": "packages",
"token_count": 3986
} | 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.
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:yaml_edit/yaml_edit.dart';
import 'common/git_version_finder.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/package_state_utils.dart';
import 'common/repository_package.dart';
/// Supported version change types, from smallest to largest component.
enum _VersionIncrementType { build, bugfix, minor }
/// Possible results of attempting to update a CHANGELOG.md file.
enum _ChangelogUpdateOutcome { addedSection, updatedSection, failed }
/// A state machine for the process of updating a CHANGELOG.md.
enum _ChangelogUpdateState {
/// Looking for the first version section.
findingFirstSection,
/// Looking for the first list entry in an existing section.
findingFirstListItem,
/// Finished with updates.
finishedUpdating,
}
/// A command to update the changelog, and optionally version, of packages.
class UpdateReleaseInfoCommand extends PackageLoopingCommand {
/// Creates a publish metadata updater command instance.
UpdateReleaseInfoCommand(
super.packagesDir, {
super.gitDir,
}) {
argParser.addOption(_changelogFlag,
mandatory: true,
help: 'The changelog entry to add. '
'Each line will be a separate list entry.');
argParser.addOption(_versionTypeFlag,
mandatory: true,
help: 'The version change level',
allowed: <String>[
_versionNext,
_versionMinimal,
_versionBugfix,
_versionMinor,
],
allowedHelp: <String, String>{
_versionNext:
'No version change; just adds a NEXT entry to the changelog.',
_versionBugfix: 'Increments the bugfix version.',
_versionMinor: 'Increments the minor version.',
_versionMinimal: 'Depending on the changes to each package: '
'increments the bugfix version (for publishable changes), '
"uses NEXT (for changes that don't need to be published), "
'or skips (if no changes).',
});
}
static const String _changelogFlag = 'changelog';
static const String _versionTypeFlag = 'version';
static const String _versionNext = 'next';
static const String _versionBugfix = 'bugfix';
static const String _versionMinor = 'minor';
static const String _versionMinimal = 'minimal';
// The version change type, if there is a set type for all platforms.
//
// If null, either there is no version change, or it is dynamic (`minimal`).
_VersionIncrementType? _versionChange;
// The cache of changed files, for dynamic version change determination.
//
// Only set for `minimal` version change.
late final List<String> _changedFiles;
@override
final String name = 'update-release-info';
@override
final String description = 'Updates CHANGELOG.md files, and optionally the '
'version in pubspec.yaml, in a way that is consistent with version-check '
'enforcement.';
@override
bool get hasLongOutput => false;
@override
Future<void> initializeRun() async {
if (getStringArg(_changelogFlag).trim().isEmpty) {
throw UsageException('Changelog message must not be empty.', usage);
}
switch (getStringArg(_versionTypeFlag)) {
case _versionMinor:
_versionChange = _VersionIncrementType.minor;
case _versionBugfix:
_versionChange = _VersionIncrementType.bugfix;
case _versionMinimal:
final GitVersionFinder gitVersionFinder = await retrieveVersionFinder();
// If the line below fails with "Not a valid object name FETCH_HEAD"
// run "git fetch", FETCH_HEAD is a temporary reference that only exists
// after a fetch. This can happen when a branch is made locally and
// pushed but never fetched.
_changedFiles = await gitVersionFinder.getChangedFiles();
// Anothing other than a fixed change is null.
_versionChange = null;
case _versionNext:
_versionChange = null;
default:
throw UnimplementedError('Unimplemented version change type');
}
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
String nextVersionString;
_VersionIncrementType? versionChange = _versionChange;
// If the change type is `minimal` determine what changes, if any, are
// needed.
if (versionChange == null &&
getStringArg(_versionTypeFlag) == _versionMinimal) {
final Directory gitRoot =
packagesDir.fileSystem.directory((await gitDir).path);
final String relativePackagePath =
getRelativePosixPath(package.directory, from: gitRoot);
final PackageChangeState state = await checkPackageChangeState(package,
changedPaths: _changedFiles,
relativePackagePath: relativePackagePath);
if (!state.hasChanges) {
return PackageResult.skip('No changes to package');
}
if (!state.needsVersionChange && !state.needsChangelogChange) {
return PackageResult.skip('No non-exempt changes to package');
}
if (state.needsVersionChange) {
versionChange = _VersionIncrementType.bugfix;
}
}
if (versionChange != null) {
final Version? updatedVersion =
_updatePubspecVersion(package, versionChange);
if (updatedVersion == null) {
return PackageResult.fail(
<String>['Could not determine current version.']);
}
nextVersionString = updatedVersion.toString();
print('${indentation}Incremented version to $nextVersionString.');
} else {
nextVersionString = 'NEXT';
}
final _ChangelogUpdateOutcome updateOutcome =
_updateChangelog(package, nextVersionString);
switch (updateOutcome) {
case _ChangelogUpdateOutcome.addedSection:
print('${indentation}Added a $nextVersionString section.');
case _ChangelogUpdateOutcome.updatedSection:
print('${indentation}Updated NEXT section.');
case _ChangelogUpdateOutcome.failed:
return PackageResult.fail(<String>['Could not update CHANGELOG.md.']);
}
return PackageResult.success();
}
_ChangelogUpdateOutcome _updateChangelog(
RepositoryPackage package, String version) {
if (!package.changelogFile.existsSync()) {
printError('${indentation}Missing CHANGELOG.md.');
return _ChangelogUpdateOutcome.failed;
}
final String newHeader = '## $version';
final RegExp listItemPattern = RegExp(r'^(\s*[-*])');
final StringBuffer newChangelog = StringBuffer();
_ChangelogUpdateState state = _ChangelogUpdateState.findingFirstSection;
bool updatedExistingSection = false;
for (final String line in package.changelogFile.readAsLinesSync()) {
switch (state) {
case _ChangelogUpdateState.findingFirstSection:
final String trimmedLine = line.trim();
if (trimmedLine.isEmpty) {
// Discard any whitespace at the top of the file.
} else if (trimmedLine == '## NEXT') {
// Replace the header with the new version (which may also be NEXT).
newChangelog.writeln(newHeader);
// Find the existing list to add to.
state = _ChangelogUpdateState.findingFirstListItem;
} else {
// The first content in the file isn't a NEXT section, so just add
// the new section.
<String>[
newHeader,
'',
..._changelogAdditionsAsList(),
'',
line, // Don't drop the current line.
].forEach(newChangelog.writeln);
state = _ChangelogUpdateState.finishedUpdating;
}
case _ChangelogUpdateState.findingFirstListItem:
final RegExpMatch? match = listItemPattern.firstMatch(line);
if (match != null) {
final String listMarker = match[1]!;
// Add the new items on top. If the new change is changing the
// version, then the new item should be more relevant to package
// clients than anything that was already there. If it's still
// NEXT, the order doesn't matter.
<String>[
..._changelogAdditionsAsList(listMarker: listMarker),
line, // Don't drop the current line.
].forEach(newChangelog.writeln);
state = _ChangelogUpdateState.finishedUpdating;
updatedExistingSection = true;
} else if (line.trim().isEmpty) {
// Scan past empty lines, but keep them.
newChangelog.writeln(line);
} else {
printError(' Existing NEXT section has unrecognized format.');
return _ChangelogUpdateOutcome.failed;
}
case _ChangelogUpdateState.finishedUpdating:
// Once changes are done, add the rest of the lines as-is.
newChangelog.writeln(line);
}
}
package.changelogFile.writeAsStringSync(newChangelog.toString());
return updatedExistingSection
? _ChangelogUpdateOutcome.updatedSection
: _ChangelogUpdateOutcome.addedSection;
}
/// Returns the changelog to add as a Markdown list, using the given list
/// bullet style (default to the repository standard of '*'), and adding
/// any missing periods.
///
/// E.g., 'A line\nAnother line.' will become:
/// ```
/// [ '* A line.', '* Another line.' ]
/// ```
Iterable<String> _changelogAdditionsAsList({String listMarker = '*'}) {
return getStringArg(_changelogFlag).split('\n').map((String entry) {
String standardizedEntry = entry.trim();
if (!standardizedEntry.endsWith('.')) {
standardizedEntry = '$standardizedEntry.';
}
return '$listMarker $standardizedEntry';
});
}
/// Updates the version in [package]'s pubspec according to [type], returning
/// the new version, or null if there was an error updating the version.
Version? _updatePubspecVersion(
RepositoryPackage package, _VersionIncrementType type) {
final Pubspec pubspec = package.parsePubspec();
final Version? currentVersion = pubspec.version;
if (currentVersion == null) {
printError('${indentation}No version in pubspec.yaml');
return null;
}
// For versions less than 1.0, shift the change down one component per
// Dart versioning conventions.
final _VersionIncrementType adjustedType = currentVersion.major > 0
? type
: _VersionIncrementType.values[type.index - 1];
final Version newVersion = _nextVersion(currentVersion, adjustedType);
// Write the new version to the pubspec.
final YamlEditor editablePubspec =
YamlEditor(package.pubspecFile.readAsStringSync());
editablePubspec.update(<String>['version'], newVersion.toString());
package.pubspecFile.writeAsStringSync(editablePubspec.toString());
return newVersion;
}
Version _nextVersion(Version version, _VersionIncrementType type) {
switch (type) {
case _VersionIncrementType.minor:
return version.nextMinor;
case _VersionIncrementType.bugfix:
return version.nextPatch;
case _VersionIncrementType.build:
final int buildNumber =
version.build.isEmpty ? 0 : version.build.first as int;
return Version(version.major, version.minor, version.patch,
build: '${buildNumber + 1}');
}
}
}
| packages/script/tool/lib/src/update_release_info_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/update_release_info_command.dart",
"repo_id": "packages",
"token_count": 4271
} | 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 'dart:convert';
import 'package:flutter_plugin_tools/src/common/pub_version_finder.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:test/test.dart';
void main() {
test('Package does not exist.', () async {
final MockClient mockClient = MockClient((http.Request request) async {
return http.Response('', 404);
});
final PubVersionFinder finder = PubVersionFinder(httpClient: mockClient);
final PubVersionFinderResponse response =
await finder.getPackageVersion(packageName: 'some_package');
expect(response.versions, isEmpty);
expect(response.result, PubVersionFinderResult.noPackageFound);
expect(response.httpResponse.statusCode, 404);
expect(response.httpResponse.body, '');
});
test('HTTP error when getting versions from pub', () async {
final MockClient mockClient = MockClient((http.Request request) async {
return http.Response('', 400);
});
final PubVersionFinder finder = PubVersionFinder(httpClient: mockClient);
final PubVersionFinderResponse response =
await finder.getPackageVersion(packageName: 'some_package');
expect(response.versions, isEmpty);
expect(response.result, PubVersionFinderResult.fail);
expect(response.httpResponse.statusCode, 400);
expect(response.httpResponse.body, '');
});
test('Get a correct list of versions when http response is OK.', () async {
const Map<String, dynamic> httpResponse = <String, dynamic>{
'name': 'some_package',
'versions': <String>[
'0.0.1',
'0.0.2',
'0.0.2+2',
'0.1.1',
'0.0.1+1',
'0.1.0',
'0.2.0',
'0.1.0+1',
'0.0.2+1',
'2.0.0',
'1.2.0',
'1.0.0',
],
};
final MockClient mockClient = MockClient((http.Request request) async {
return http.Response(json.encode(httpResponse), 200);
});
final PubVersionFinder finder = PubVersionFinder(httpClient: mockClient);
final PubVersionFinderResponse response =
await finder.getPackageVersion(packageName: 'some_package');
expect(response.versions, <Version>[
Version.parse('2.0.0'),
Version.parse('1.2.0'),
Version.parse('1.0.0'),
Version.parse('0.2.0'),
Version.parse('0.1.1'),
Version.parse('0.1.0+1'),
Version.parse('0.1.0'),
Version.parse('0.0.2+2'),
Version.parse('0.0.2+1'),
Version.parse('0.0.2'),
Version.parse('0.0.1+1'),
Version.parse('0.0.1'),
]);
expect(response.result, PubVersionFinderResult.success);
expect(response.httpResponse.statusCode, 200);
expect(response.httpResponse.body, json.encode(httpResponse));
});
}
| packages/script/tool/test/common/pub_version_finder_test.dart/0 | {
"file_path": "packages/script/tool/test/common/pub_version_finder_test.dart",
"repo_id": "packages",
"token_count": 1146
} | 1,059 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/command_runner.dart';
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_plugin_tools/src/list_command.dart';
import 'package:test/test.dart';
import 'mocks.dart';
import 'util.dart';
void main() {
group('ListCommand', () {
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
late CommandRunner<void> runner;
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
final ListCommand command =
ListCommand(packagesDir, platform: mockPlatform);
runner = CommandRunner<void>('list_test', 'Test for $ListCommand');
runner.addCommand(command);
});
test('lists top-level packages', () async {
createFakePackage('package1', packagesDir);
createFakePlugin('plugin2', packagesDir);
final List<String> plugins =
await runCapturingPrint(runner, <String>['list', '--type=package']);
expect(
plugins,
orderedEquals(<String>[
'/packages/package1',
'/packages/plugin2',
]),
);
});
test('lists examples', () async {
createFakePlugin('plugin1', packagesDir);
createFakePlugin('plugin2', packagesDir,
examples: <String>['example1', 'example2']);
createFakePlugin('plugin3', packagesDir, examples: <String>[]);
final List<String> examples =
await runCapturingPrint(runner, <String>['list', '--type=example']);
expect(
examples,
orderedEquals(<String>[
'/packages/plugin1/example',
'/packages/plugin2/example/example1',
'/packages/plugin2/example/example2',
]),
);
});
test('lists packages and subpackages', () async {
createFakePackage('package1', packagesDir);
createFakePlugin('plugin2', packagesDir,
examples: <String>['example1', 'example2']);
createFakePlugin('plugin3', packagesDir, examples: <String>[]);
final List<String> packages = await runCapturingPrint(
runner, <String>['list', '--type=package-or-subpackage']);
expect(
packages,
unorderedEquals(<String>[
'/packages/package1',
'/packages/package1/example',
'/packages/plugin2',
'/packages/plugin2/example/example1',
'/packages/plugin2/example/example2',
'/packages/plugin3',
]),
);
});
test('lists files', () async {
createFakePlugin('plugin1', packagesDir);
createFakePlugin('plugin2', packagesDir,
examples: <String>['example1', 'example2']);
createFakePlugin('plugin3', packagesDir, examples: <String>[]);
final List<String> examples =
await runCapturingPrint(runner, <String>['list', '--type=file']);
expect(
examples,
unorderedEquals(<String>[
'/packages/plugin1/pubspec.yaml',
'/packages/plugin1/AUTHORS',
'/packages/plugin1/CHANGELOG.md',
'/packages/plugin1/README.md',
'/packages/plugin1/example/pubspec.yaml',
'/packages/plugin2/pubspec.yaml',
'/packages/plugin2/AUTHORS',
'/packages/plugin2/CHANGELOG.md',
'/packages/plugin2/README.md',
'/packages/plugin2/example/example1/pubspec.yaml',
'/packages/plugin2/example/example2/pubspec.yaml',
'/packages/plugin3/pubspec.yaml',
'/packages/plugin3/AUTHORS',
'/packages/plugin3/CHANGELOG.md',
'/packages/plugin3/README.md',
]),
);
});
test('lists plugins using federated plugin layout', () async {
createFakePlugin('plugin1', packagesDir);
// Create a federated plugin by creating a directory under the packages
// directory with several packages underneath.
final Directory federatedPluginDir =
packagesDir.childDirectory('my_plugin')..createSync();
createFakePlugin('my_plugin', federatedPluginDir);
createFakePlugin('my_plugin_web', federatedPluginDir);
createFakePlugin('my_plugin_macos', federatedPluginDir);
// Test without specifying `--type`.
final List<String> plugins =
await runCapturingPrint(runner, <String>['list']);
expect(
plugins,
unorderedEquals(<String>[
'/packages/plugin1',
'/packages/my_plugin/my_plugin',
'/packages/my_plugin/my_plugin_web',
'/packages/my_plugin/my_plugin_macos',
]),
);
});
test('can filter plugins with the --packages argument', () async {
createFakePlugin('plugin1', packagesDir);
// Create a federated plugin by creating a directory under the packages
// directory with several packages underneath.
final Directory federatedPluginDir =
packagesDir.childDirectory('my_plugin')..createSync();
createFakePlugin('my_plugin', federatedPluginDir);
createFakePlugin('my_plugin_web', federatedPluginDir);
createFakePlugin('my_plugin_macos', federatedPluginDir);
List<String> plugins = await runCapturingPrint(
runner, <String>['list', '--packages=plugin1']);
expect(
plugins,
unorderedEquals(<String>[
'/packages/plugin1',
]),
);
plugins = await runCapturingPrint(
runner, <String>['list', '--packages=my_plugin']);
expect(
plugins,
unorderedEquals(<String>[
'/packages/my_plugin/my_plugin',
'/packages/my_plugin/my_plugin_web',
'/packages/my_plugin/my_plugin_macos',
]),
);
plugins = await runCapturingPrint(
runner, <String>['list', '--packages=my_plugin/my_plugin_web']);
expect(
plugins,
unorderedEquals(<String>[
'/packages/my_plugin/my_plugin_web',
]),
);
plugins = await runCapturingPrint(runner,
<String>['list', '--packages=my_plugin/my_plugin_web,plugin1']);
expect(
plugins,
unorderedEquals(<String>[
'/packages/plugin1',
'/packages/my_plugin/my_plugin_web',
]),
);
});
});
}
| packages/script/tool/test/list_command_test.dart/0 | {
"file_path": "packages/script/tool/test/list_command_test.dart",
"repo_id": "packages",
"token_count": 2641
} | 1,060 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '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/version_check_command.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:mockito/mockito.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:test/test.dart';
import 'common/package_command_test.mocks.dart';
import 'mocks.dart';
import 'util.dart';
void testAllowedVersion(
String mainVersion,
String headVersion, {
bool allowed = true,
NextVersionType? nextVersionType,
}) {
final Version main = Version.parse(mainVersion);
final Version head = Version.parse(headVersion);
final Map<Version, NextVersionType> allowedVersions =
getAllowedNextVersions(main, newVersion: head);
if (allowed) {
expect(allowedVersions, contains(head));
if (nextVersionType != null) {
expect(allowedVersions[head], equals(nextVersionType));
}
} else {
expect(allowedVersions, isNot(contains(head)));
}
}
void main() {
const String indentation = ' ';
group('VersionCheckCommand', () {
late FileSystem fileSystem;
late MockPlatform mockPlatform;
late Directory packagesDir;
late CommandRunner<void> runner;
late RecordingProcessRunner processRunner;
late MockGitDir gitDir;
// Ignored if mockHttpResponse is set.
int mockHttpStatus;
Map<String, dynamic>? mockHttpResponse;
setUp(() {
fileSystem = MemoryFileSystem();
mockPlatform = MockPlatform();
packagesDir = createPackagesDirectory(fileSystem: fileSystem);
gitDir = MockGitDir();
when(gitDir.path).thenReturn(packagesDir.parent.path);
when(gitDir.runCommand(any, throwOnError: anyNamed('throwOnError')))
.thenAnswer((Invocation invocation) {
final List<String> arguments =
invocation.positionalArguments[0]! as List<String>;
// Route git calls through the process runner, to make mock output
// consistent with other processes. Attach the first argument to the
// command to make targeting the mock results easier.
final String gitCommand = arguments.removeAt(0);
return processRunner.run('git-$gitCommand', arguments);
});
// Default to simulating the plugin never having been published.
mockHttpStatus = 404;
mockHttpResponse = null;
final MockClient mockClient = MockClient((http.Request request) async {
return http.Response(json.encode(mockHttpResponse),
mockHttpResponse == null ? mockHttpStatus : 200);
});
processRunner = RecordingProcessRunner();
final VersionCheckCommand command = VersionCheckCommand(packagesDir,
processRunner: processRunner,
platform: mockPlatform,
gitDir: gitDir,
httpClient: mockClient);
runner = CommandRunner<void>(
'version_check_command', 'Test for $VersionCheckCommand');
runner.addCommand(command);
});
test('allows valid version', () async {
createFakePlugin('plugin', packagesDir, version: '2.0.0');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('1.0.0 -> 2.0.0'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall(
'git-show', <String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('denies invalid version', () async {
createFakePlugin('plugin', packagesDir, version: '0.2.0');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 0.0.1')),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Incorrectly updated version.'),
]));
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall(
'git-show', <String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('uses merge-base without explicit base-sha', () async {
createFakePlugin('plugin', packagesDir, version: '2.0.0');
processRunner.mockProcessesForExecutable['git-merge-base'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'abc123')),
FakeProcessInfo(MockProcess(stdout: 'abc123')),
];
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
final List<String> output =
await runCapturingPrint(runner, <String>['version-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('1.0.0 -> 2.0.0'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall('git-merge-base',
<String>['--fork-point', 'FETCH_HEAD', 'HEAD'], null),
ProcessCall('git-show',
<String>['abc123:packages/plugin/pubspec.yaml'], null),
]));
});
test('allows valid version for new package.', () async {
createFakePlugin('plugin', packagesDir, version: '1.0.0');
final List<String> output =
await runCapturingPrint(runner, <String>['version-check']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('Unable to find previous version at git base.'),
]),
);
});
test('allows likely reverts.', () async {
createFakePlugin('plugin', packagesDir, version: '0.6.1');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 0.6.2')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('New version is lower than previous version. '
'This is assumed to be a revert.'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall(
'git-show', <String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('denies lower version that could not be a simple revert', () async {
createFakePlugin('plugin', packagesDir, version: '0.5.1');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 0.6.2')),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Incorrectly updated version.'),
]));
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall(
'git-show', <String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('allows minor changes to platform interfaces', () async {
createFakePlugin('plugin_platform_interface', packagesDir,
version: '1.1.0');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('1.0.0 -> 1.1.0'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall(
'git-show',
<String>[
'main:packages/plugin_platform_interface/pubspec.yaml'
],
null)
]));
});
test('disallows breaking changes to platform interfaces by default',
() async {
createFakePlugin('plugin_platform_interface', packagesDir,
version: '2.0.0');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
' Breaking changes to platform interfaces are not allowed '
'without explicit justification.\n'
' See https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages '
'for more information.'),
]));
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall(
'git-show',
<String>[
'main:packages/plugin_platform_interface/pubspec.yaml'
],
null)
]));
});
test('allows breaking changes to platform interfaces with override label',
() async {
createFakePlugin('plugin_platform_interface', packagesDir,
version: '2.0.0');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'version-check',
'--base-sha=main',
'--pr-labels=some label,override: allow breaking change,another-label'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Allowing breaking change to plugin_platform_interface '
'due to the "override: allow breaking change" label.'),
contains('Ran for 1 package(s) (1 with warnings)'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall(
'git-show',
<String>[
'main:packages/plugin_platform_interface/pubspec.yaml'
],
null)
]));
});
test('allows breaking changes to platform interfaces with bypass flag',
() async {
createFakePlugin('plugin_platform_interface', packagesDir,
version: '2.0.0');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
final List<String> output = await runCapturingPrint(runner, <String>[
'version-check',
'--base-sha=main',
'--ignore-platform-interface-breaks'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Allowing breaking change to plugin_platform_interface due '
'to --ignore-platform-interface-breaks'),
contains('Ran for 1 package(s) (1 with warnings)'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall(
'git-show',
<String>[
'main:packages/plugin_platform_interface/pubspec.yaml'
],
null)
]));
});
test('Allow empty lines in front of the first version in CHANGELOG',
() async {
const String version = '1.0.1';
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: version);
const String changelog = '''
## $version
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test('Throws if versions in changelog and pubspec do not match', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.1');
const String changelog = '''
## 1.0.2
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main', '--against-pub'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Versions in CHANGELOG.md and pubspec.yaml do not match.'),
]),
);
});
test('Success if CHANGELOG and pubspec versions match', () async {
const String version = '1.0.1';
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: version);
const String changelog = '''
## $version
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test(
'Fail if pubspec version only matches an older version listed in CHANGELOG',
() async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.1
* Some changes.
## 1.0.0
* Some other changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
bool hasError = false;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main', '--against-pub'],
errorHandler: (Error e) {
expect(e, isA<ToolExit>());
hasError = true;
});
expect(hasError, isTrue);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Versions in CHANGELOG.md and pubspec.yaml do not match.'),
]),
);
});
test('Allow NEXT as a placeholder for gathering CHANGELOG entries',
() async {
const String version = '1.0.0';
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: version);
const String changelog = '''
## NEXT
* Some changes that won't be published until the next time there's a release.
## $version
* Some other changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('Found NEXT; validating next version in the CHANGELOG.'),
]),
);
});
test('Fail if NEXT appears after a version', () async {
const String version = '1.0.1';
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: version);
const String changelog = '''
## $version
* Some changes.
## NEXT
* Some changes that should have been folded in 1.0.1.
## 1.0.0
* Some other changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
bool hasError = false;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main', '--against-pub'],
errorHandler: (Error e) {
expect(e, isA<ToolExit>());
hasError = true;
});
expect(hasError, isTrue);
expect(
output,
containsAllInOrder(<Matcher>[
contains('When bumping the version for release, the NEXT section '
"should be incorporated into the new version's release notes.")
]),
);
});
test('Fail if NEXT is left in the CHANGELOG when adding a version bump',
() async {
const String version = '1.0.1';
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: version);
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
const String changelog = '''
## NEXT
* Some changes that should have been folded in 1.0.1.
## $version
* Some changes.
## 1.0.0
* Some other changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
bool hasError = false;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main'],
errorHandler: (Error e) {
expect(e, isA<ToolExit>());
hasError = true;
});
expect(hasError, isTrue);
expect(
output,
containsAllInOrder(<Matcher>[
contains('When bumping the version for release, the NEXT section '
"should be incorporated into the new version's release notes."),
contains('plugin:\n'
' CHANGELOG.md failed validation.'),
]),
);
});
test('fails if the version increases without replacing NEXT', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.1');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
const String changelog = '''
## NEXT
* Some changes that should be listed as part of 1.0.1.
## 1.0.0
* Some other changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
bool hasError = false;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main'],
errorHandler: (Error e) {
expect(e, isA<ToolExit>());
hasError = true;
});
expect(hasError, isTrue);
expect(
output,
containsAllInOrder(<Matcher>[
contains('When bumping the version for release, the NEXT section '
"should be incorporated into the new version's release notes.")
]),
);
});
test('allows NEXT for a revert', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## NEXT
* Some changes that should be listed as part of 1.0.1.
## 1.0.0
* Some other changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.1')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('New version is lower than previous version. '
'This is assumed to be a revert.'),
]),
);
});
// This handles imports of a package with a NEXT section.
test('allows NEXT for a new package', () async {
final RepositoryPackage plugin =
createFakePackage('a_package', packagesDir, version: '1.0.0');
const String changelog = '''
## NEXT
* Some changes that should be listed in the next release.
## 1.0.0
* Some other changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Unable to find previous version at git base'),
contains('Found NEXT; validating next version in the CHANGELOG'),
]),
);
});
test(
'fails gracefully if the version headers are not found due to using the wrong style',
() async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## NEXT
* Some changes for a later release.
# 1.0.0
* Some other changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'version-check',
'--base-sha=main',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Unable to find a version in CHANGELOG.md'),
contains('The current version should be on a line starting with '
'"## ", either on the first non-empty line or after a "## NEXT" '
'section.'),
]),
);
});
test('fails gracefully if the version is unparseable', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## Alpha
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
Error? commandError;
final List<String> output = await runCapturingPrint(runner, <String>[
'version-check',
'--base-sha=main',
], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('"Alpha" could not be parsed as a version.'),
]),
);
});
group('missing change detection', () {
Future<List<String>> runWithMissingChangeDetection(List<String> extraArgs,
{void Function(Error error)? errorHandler}) async {
return runCapturingPrint(
runner,
<String>[
'version-check',
'--base-sha=main',
'--check-for-missing-changes',
...extraArgs,
],
errorHandler: errorHandler);
}
test('passes for unchanged packages', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test(
'fails if a version change is missing from a change that does not '
'pass the exemption check', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/lib/plugin.dart
''')),
];
Error? commandError;
final List<String> output = await runWithMissingChangeDetection(
<String>[], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('No version change found'),
contains('plugin:\n'
' Missing version change'),
]),
);
});
test('passes version change requirement when version changes', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.1');
const String changelog = '''
## 1.0.1
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/lib/plugin.dart
packages/plugin/CHANGELOG.md
packages/plugin/pubspec.yaml
''')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test('version change check ignores files outside the package', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin_a/lib/plugin.dart
tool/plugin/lib/plugin.dart
''')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test('allows missing version change for exempt changes', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/example/android/.pluginToolsConfig.yaml
packages/plugin/example/android/lint-baseline.xml
packages/plugin/example/android/src/androidTest/foo/bar/FooTest.java
packages/plugin/example/ios/RunnerTests/Foo.m
packages/plugin/example/ios/RunnerUITests/info.plist
packages/plugin/analysis_options.yaml
packages/plugin/CHANGELOG.md
''')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test('allows missing version change with override label', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/lib/plugin.dart
packages/plugin/CHANGELOG.md
packages/plugin/pubspec.yaml
''')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[
'--pr-labels=some label,override: no versioning needed,another-label'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Ignoring lack of version change due to the '
'"override: no versioning needed" label.'),
]),
);
});
test('fails if a CHANGELOG change is missing', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/example/lib/foo.dart
''')),
];
Error? commandError;
final List<String> output = await runWithMissingChangeDetection(
<String>[], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('No CHANGELOG change found.\nIf'),
contains('plugin:\n'
' Missing CHANGELOG change'),
]),
);
});
test('passes CHANGELOG check when the CHANGELOG is changed', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/example/lib/foo.dart
packages/plugin/CHANGELOG.md
''')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test('fails CHANGELOG check if only another package CHANGELOG chages',
() async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/example/lib/foo.dart
packages/another_plugin/CHANGELOG.md
''')),
];
Error? commandError;
final List<String> output = await runWithMissingChangeDetection(
<String>[], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('No CHANGELOG change found'),
]),
);
});
test('allows missing CHANGELOG change with justification', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/example/lib/foo.dart
''')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[
'--pr-labels=some label,override: no changelog needed,another-label'
]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Ignoring lack of CHANGELOG update due to the '
'"override: no changelog needed" label.'),
]),
);
});
// This test ensures that Dependabot Gradle changes to test-only files
// aren't flagged by the version check.
test(
'allows missing CHANGELOG and version change for test-only Gradle changes',
() async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
// File list.
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/android/build.gradle
''')),
// build.gradle diff
FakeProcessInfo(MockProcess(stdout: '''
- androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
- testImplementation 'junit:junit:4.10.0'
+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
+ testImplementation 'junit:junit:4.13.2'
''')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test(
'allows missing CHANGELOG and version change for dev-only-file changes',
() async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
// File list.
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/tool/run_tests.dart
packages/plugin/run_tests.sh
''')),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test(
'allows missing CHANGELOG and version change for dev-only line-level '
'changes in production files', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
// File list.
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/lib/plugin.dart
''')),
// Dart file diff.
FakeProcessInfo(MockProcess(stdout: '''
+ // TODO(someone): Fix this.
+ // ignore: some_lint
'''), <String>['main', 'HEAD', '--', 'packages/plugin/lib/plugin.dart']),
];
final List<String> output =
await runWithMissingChangeDetection(<String>[]);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
]),
);
});
test('documentation comments are not exempt', () async {
final RepositoryPackage plugin =
createFakePlugin('plugin', packagesDir, version: '1.0.0');
const String changelog = '''
## 1.0.0
* Some changes.
''';
plugin.changelogFile.writeAsStringSync(changelog);
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
processRunner.mockProcessesForExecutable['git-diff'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '''
packages/plugin/lib/plugin.dart
''')),
// Dart file diff.
FakeProcessInfo(MockProcess(stdout: '''
+ /// Important new information for API clients!
'''), <String>['main', 'HEAD', '--', 'packages/plugin/lib/plugin.dart']),
];
Error? commandError;
final List<String> output = await runWithMissingChangeDetection(
<String>[], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains(
'No version change found, but the change to this package could '
'not be verified to be exempt\n',
),
contains('plugin:\n'
' Missing version change'),
]),
);
});
});
test('allows valid against pub', () async {
mockHttpResponse = <String, dynamic>{
'name': 'some_package',
'versions': <String>[
'0.0.1',
'0.0.2',
'1.0.0',
],
};
createFakePlugin('plugin', packagesDir, version: '2.0.0');
final List<String> output = await runCapturingPrint(runner,
<String>['version-check', '--base-sha=main', '--against-pub']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('plugin: Current largest version on pub: 1.0.0'),
]),
);
});
test('denies invalid against pub', () async {
mockHttpResponse = <String, dynamic>{
'name': 'some_package',
'versions': <String>[
'0.0.1',
'0.0.2',
],
};
createFakePlugin('plugin', packagesDir, version: '2.0.0');
bool hasError = false;
final List<String> result = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main', '--against-pub'],
errorHandler: (Error e) {
expect(e, isA<ToolExit>());
hasError = true;
});
expect(hasError, isTrue);
expect(
result,
containsAllInOrder(<Matcher>[
contains('''
${indentation}Incorrectly updated version.
${indentation}HEAD: 2.0.0, pub: 0.0.2.
${indentation}Allowed versions: {1.0.0: NextVersionType.BREAKING_MAJOR, 0.1.0: NextVersionType.MINOR, 0.0.3: NextVersionType.PATCH}''')
]),
);
});
test(
'throw and print error message if http request failed when checking against pub',
() async {
mockHttpStatus = 400;
createFakePlugin('plugin', packagesDir, version: '2.0.0');
bool hasError = false;
final List<String> result = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main', '--against-pub'],
errorHandler: (Error e) {
expect(e, isA<ToolExit>());
hasError = true;
});
expect(hasError, isTrue);
expect(
result,
containsAllInOrder(<Matcher>[
contains('''
${indentation}Error fetching version on pub for plugin.
${indentation}HTTP Status 400
${indentation}HTTP response: null
''')
]),
);
});
test('when checking against pub, allow any version if http status is 404.',
() async {
mockHttpStatus = 404;
createFakePlugin('plugin', packagesDir, version: '2.0.0');
processRunner.mockProcessesForExecutable['git-show'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
final List<String> result = await runCapturingPrint(runner,
<String>['version-check', '--base-sha=main', '--against-pub']);
expect(
result,
containsAllInOrder(<Matcher>[
contains('Unable to find previous version on pub server.'),
]),
);
});
group('prelease versions', () {
test(
'allow an otherwise-valid transition that also adds a pre-release component',
() async {
createFakePlugin('plugin', packagesDir, version: '2.0.0-dev');
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.0.0')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('1.0.0 -> 2.0.0-dev'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall('git-show',
<String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('allow releasing a pre-release', () async {
createFakePlugin('plugin', packagesDir, version: '1.2.0');
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.2.0-dev')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('1.2.0-dev -> 1.2.0'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall('git-show',
<String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
// Allow abandoning a pre-release version in favor of a different version
// change type.
test(
'allow an otherwise-valid transition that also removes a pre-release component',
() async {
createFakePlugin('plugin', packagesDir, version: '2.0.0');
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.2.0-dev')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('1.2.0-dev -> 2.0.0'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall('git-show',
<String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('allow changing only the pre-release version', () async {
createFakePlugin('plugin', packagesDir, version: '1.2.0-dev.2');
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 1.2.0-dev.1')),
];
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main']);
expect(
output,
containsAllInOrder(<Matcher>[
contains('Running for plugin'),
contains('1.2.0-dev.1 -> 1.2.0-dev.2'),
]),
);
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall('git-show',
<String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('denies invalid version change that also adds a pre-release',
() async {
createFakePlugin('plugin', packagesDir, version: '0.2.0-dev');
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 0.0.1')),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Incorrectly updated version.'),
]));
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall('git-show',
<String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('denies invalid version change that also removes a pre-release',
() async {
createFakePlugin('plugin', packagesDir, version: '0.2.0');
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 0.0.1-dev')),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Incorrectly updated version.'),
]));
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall('git-show',
<String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
test('denies invalid version change between pre-releases', () async {
createFakePlugin('plugin', packagesDir, version: '0.2.0-dev');
processRunner.mockProcessesForExecutable['git-show'] =
<FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: 'version: 0.0.1-dev')),
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['version-check', '--base-sha=main'],
errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Incorrectly updated version.'),
]));
expect(
processRunner.recordedCalls,
containsAllInOrder(const <ProcessCall>[
ProcessCall('git-show',
<String>['main:packages/plugin/pubspec.yaml'], null)
]));
});
});
});
group('Pre 1.0', () {
test('nextVersion allows patch version', () {
testAllowedVersion('0.12.0', '0.12.0+1',
nextVersionType: NextVersionType.PATCH);
testAllowedVersion('0.12.0+4', '0.12.0+5',
nextVersionType: NextVersionType.PATCH);
});
test('nextVersion does not allow jumping patch', () {
testAllowedVersion('0.12.0', '0.12.0+2', allowed: false);
testAllowedVersion('0.12.0+2', '0.12.0+4', allowed: false);
});
test('nextVersion does not allow going back', () {
testAllowedVersion('0.12.0', '0.11.0', allowed: false);
testAllowedVersion('0.12.0+2', '0.12.0+1', allowed: false);
testAllowedVersion('0.12.0+1', '0.12.0', allowed: false);
});
test('nextVersion allows minor version', () {
testAllowedVersion('0.12.0', '0.12.1',
nextVersionType: NextVersionType.MINOR);
testAllowedVersion('0.12.0+4', '0.12.1',
nextVersionType: NextVersionType.MINOR);
});
test('nextVersion does not allow jumping minor', () {
testAllowedVersion('0.12.0', '0.12.2', allowed: false);
testAllowedVersion('0.12.0+2', '0.12.3', allowed: false);
});
});
group('Releasing 1.0', () {
test('nextVersion allows releasing 1.0', () {
testAllowedVersion('0.12.0', '1.0.0',
nextVersionType: NextVersionType.BREAKING_MAJOR);
testAllowedVersion('0.12.0+4', '1.0.0',
nextVersionType: NextVersionType.BREAKING_MAJOR);
});
test('nextVersion does not allow jumping major', () {
testAllowedVersion('0.12.0', '2.0.0', allowed: false);
testAllowedVersion('0.12.0+4', '2.0.0', allowed: false);
});
test('nextVersion does not allow un-releasing', () {
testAllowedVersion('1.0.0', '0.12.0+4', allowed: false);
testAllowedVersion('1.0.0', '0.12.0', allowed: false);
});
});
group('Post 1.0', () {
test('nextVersion allows patch jumps', () {
testAllowedVersion('1.0.1', '1.0.2',
nextVersionType: NextVersionType.PATCH);
testAllowedVersion('1.0.0', '1.0.1',
nextVersionType: NextVersionType.PATCH);
});
test('nextVersion does not allow build jumps', () {
testAllowedVersion('1.0.1', '1.0.1+1', allowed: false);
testAllowedVersion('1.0.0+5', '1.0.0+6', allowed: false);
});
test('nextVersion does not allow skipping patches', () {
testAllowedVersion('1.0.1', '1.0.3', allowed: false);
testAllowedVersion('1.0.0', '1.0.6', allowed: false);
});
test('nextVersion allows minor version jumps', () {
testAllowedVersion('1.0.1', '1.1.0',
nextVersionType: NextVersionType.MINOR);
testAllowedVersion('1.0.0', '1.1.0',
nextVersionType: NextVersionType.MINOR);
});
test('nextVersion does not allow skipping minor versions', () {
testAllowedVersion('1.0.1', '1.2.0', allowed: false);
testAllowedVersion('1.1.0', '1.3.0', allowed: false);
});
test('nextVersion allows breaking changes', () {
testAllowedVersion('1.0.1', '2.0.0',
nextVersionType: NextVersionType.BREAKING_MAJOR);
testAllowedVersion('1.0.0', '2.0.0',
nextVersionType: NextVersionType.BREAKING_MAJOR);
});
test('nextVersion does not allow skipping major versions', () {
testAllowedVersion('1.0.1', '3.0.0', allowed: false);
testAllowedVersion('1.1.0', '2.3.0', allowed: false);
});
});
}
| packages/script/tool/test/version_check_command_test.dart/0 | {
"file_path": "packages/script/tool/test/version_check_command_test.dart",
"repo_id": "packages",
"token_count": 23242
} | 1,061 |
export const ENV = process.env.NODE_ENV;
export const UPLOAD_PATH = 'uploads';
export const SHARE_PATH = 'share';
export const ALLOWED_HOSTS = [
'localhost:5001',
'io-photobooth-dev.web.app',
'io-photo-booth.web.app',
'us-central1-io-photobooth-dev.cloudfunctions.net',
'us-central1-io-photo-booth.cloudfunctions.net',
'photobooth.flutter.dev',
];
| photobooth/functions/src/config.ts/0 | {
"file_path": "photobooth/functions/src/config.ts",
"repo_id": "photobooth",
"token_count": 145
} | 1,062 |
{
"@@locale": "zh_Hant",
"landingPageHeading": "歡迎來到 I\u2215O 照相館",
"landingPageSubheading": "向社群分享您拍的照片!",
"landingPageTakePhotoButtonText": "開拍",
"footerMadeWithText": "產品構建基於 ",
"footerMadeWithFlutterLinkText": "Flutter",
"footerMadeWithFirebaseLinkText": "Firebase",
"footerGoogleIOLinkText": "Google I\u2215O",
"footerCodelabLinkText": "Codelab",
"footerHowItsMadeLinkText": "本應用程式如何構建",
"footerTermsOfServiceLinkText": "服務條款",
"footerPrivacyPolicyLinkText": "私隱權政策",
"sharePageHeading": "向社群分享您拍的照片!",
"sharePageSubheading": "向社群分享您拍的照片!",
"sharePageSuccessHeading": "拍照已分享!",
"sharePageSuccessSubheading": "感謝使用由 Flutter 構建的 Web 應用程式,您拍的照片已經發佈在這個唯一的網址上了",
"sharePageSuccessCaption1": "您拍的照片將在這個網址上保留 30 天然後被自動刪除。若要請求提前刪除,請聯絡 ",
"sharePageSuccessCaption2": "[email protected]",
"sharePageSuccessCaption3": " 並確保帶上照片的唯一網址。",
"sharePageRetakeButtonText": "重新拍一張",
"sharePageShareButtonText": "分享",
"sharePageDownloadButtonText": "下載",
"socialMediaShareLinkText": "剛通過 #IO照相館 拍了一張自拍,大家 #GoogleIO 大會見!#IOPhotoBooth ",
"previewPageCameraNotAllowedText": "您拒絕授予使用設備相機的權限,為了使用這個應用程式,請予以授權。",
"sharePageSocialMediaShareClarification1": "如果您選擇在社交平台上分享您拍的照片,應用程式將會生成一個唯一的、30 天有效期網址的網址(過期自動刪除),照片亦不會被分享或者存儲。如果您希望提早刪除這些照片,請聯絡 ",
"sharePageSocialMediaShareClarification2": "[email protected]",
"sharePageSocialMediaShareClarification3": " 並且帶上照片的唯一網址。",
"sharePageCopyLinkButton": "複製",
"sharePageLinkedCopiedButton": "已複製",
"sharePageErrorHeading": "處理照片時遇到了一些問題",
"sharePageErrorSubheading": "請確保您的設備和瀏覽器都更新到了最新版本,如果問題依舊存在,請通過這個郵件與我們聯絡 [email protected] 。",
"shareDialogHeading": "分享您拍的照片!",
"shareDialogSubheading": "與其他人分享您拍的照片,也可以替換為頭像,讓大家知道您在參加 Google I/O 大會!",
"shareErrorDialogHeading": "喔唷!",
"shareErrorDialogTryAgainButton": "退回",
"shareErrorDialogSubheading": "出了點問題,我們沒法加載您拍的照片了。",
"sharePageProgressOverlayHeading": "正在通過 Flutter 「精修」 您拍的照片!",
"sharePageProgressOverlaySubheading": "請不要關閉本頁面。",
"shareDialogTwitterButtonText": "Twitter",
"shareDialogFacebookButtonText": "Facebook",
"photoBoothCameraAccessDeniedHeadline": "相機權限獲取失敗",
"photoBoothCameraAccessDeniedSubheadline": "為了拍照成功,您需要允許瀏覽器獲取您的相機權限",
"photoBoothCameraNotFoundHeadline": "無法找到相機",
"photoBoothCameraNotFoundSubheadline1": "您的設備似乎並沒有相機或者相機工作不正常",
"photoBoothCameraNotFoundSubheadline2": "如果您希望使用這個應用程式進行拍照,請通過相機功能正常的設備訪問 I\u2215O 照相館頁面。",
"photoBoothCameraErrorHeadline": "糟糕,出錯了",
"photoBoothCameraErrorSubheadline1": "請刷新您的瀏覽器然後重試。",
"photoBoothCameraErrorSubheadline2": "如果問題仍一直出現,請通過郵件聯絡我們 [email protected]",
"photoBoothCameraNotSupportedHeadline": "糟糕,出錯了",
"photoBoothCameraNotSupportedSubheadline": "請確保您的設備和瀏覽器都已更新至最新版本。",
"stickersDrawerTitle": "添加貼圖",
"openStickersTooltip": "添加貼圖",
"retakeButtonTooltip": "重拍",
"clearStickersButtonTooltip": "清除貼圖",
"charactersCaptionText": "來幾個好朋友",
"sharePageLearnMoreAboutTextPart1": "您可以瞭解更多關於 ",
"sharePageLearnMoreAboutTextPart2": " 和 ",
"sharePageLearnMoreAboutTextPart3": ",或者更深入的瞭解和查看 ",
"sharePageLearnMoreAboutTextPart4": "開原始碼。",
"goToGoogleIOButtonText": "查看 Google I\u2215O 內容",
"clearStickersDialogHeading": "要清除所有貼圖嗎?",
"clearStickersDialogSubheading": "您是要清空屏幕上所有添加的貼圖嗎?",
"clearStickersDialogCancelButtonText": "不是,請返回上一頁",
"clearStickersDialogConfirmButtonText": "是的,清除所有貼圖",
"propsReminderText": "添加一些貼圖",
"stickersNextConfirmationHeading": "準備好查看您拍的照片了嘛?",
"stickersNextConfirmationSubheading": "一旦您離開這個頁面,照片就不能再進行任何修改了喔。",
"stickersNextConfirmationCancelButtonText": "不要,我還需要再改改",
"stickersNextConfirmationConfirmButtonText": "可以,展示我拍的照片",
"stickersRetakeConfirmationHeading": "您確定嗎?",
"stickersRetakeConfirmationSubheading": "選擇重拍會讓您添加的所有貼圖和朋友都被移除",
"stickersRetakeConfirmationCancelButtonText": "不要,請留在當前頁面",
"stickersRetakeConfirmationConfirmButtonText": "是的,重新拍照",
"shareRetakeConfirmationHeading": "準備好拍一張新照片了嗎?",
"shareRetakeConfirmationSubheading": "記得把剛拍的那張下載保存或者分享出去",
"shareRetakeConfirmationCancelButtonText": "沒有,請留在當前頁面",
"shareRetakeConfirmationConfirmButtonText": "是的,重新拍照",
"shutterButtonLabelText": "拍照",
"stickersNextButtonLabelText": "創建最終版的照片",
"dashButtonLabelText": "添加朋友 dash",
"sparkyButtonLabelText": "添加朋友 sparky",
"dinoButtonLabelText": "添加朋友 dino",
"androidButtonLabelText": "添加朋友 android jetpack",
"addStickersButtonLabelText": "添加貼圖",
"retakePhotoButtonLabelText": "重拍",
"clearAllStickersButtonLabelText": "清除所有貼圖"
} | photobooth/lib/l10n/arb/app_zh_Hant.arb/0 | {
"file_path": "photobooth/lib/l10n/arb/app_zh_Hant.arb",
"repo_id": "photobooth",
"token_count": 3466
} | 1,063 |
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class AnimatedAndroid extends AnimatedSprite {
const AnimatedAndroid({super.key})
: super(
loadingIndicatorColor: PhotoboothColors.green,
sprites: const Sprites(
asset: 'android_spritesheet.png',
size: Size(450, 658),
frames: 25,
stepTime: 2 / 25,
),
);
}
| photobooth/lib/photobooth/widgets/animated_characters/animated_android.dart/0 | {
"file_path": "photobooth/lib/photobooth/widgets/animated_characters/animated_android.dart",
"repo_id": "photobooth",
"token_count": 202
} | 1,064 |
part of 'share_bloc.dart';
abstract class ShareEvent extends Equatable {
const ShareEvent();
@override
List<Object> get props => [];
}
class ShareViewLoaded extends ShareEvent {
const ShareViewLoaded();
}
abstract class ShareTapped extends ShareEvent {
const ShareTapped();
}
class ShareOnTwitterTapped extends ShareTapped {
const ShareOnTwitterTapped();
}
class ShareOnFacebookTapped extends ShareTapped {
const ShareOnFacebookTapped();
}
class _ShareCompositeSucceeded extends ShareEvent {
const _ShareCompositeSucceeded({required this.bytes});
final Uint8List bytes;
}
class _ShareCompositeFailed extends ShareEvent {
const _ShareCompositeFailed();
}
| photobooth/lib/share/bloc/share_event.dart/0 | {
"file_path": "photobooth/lib/share/bloc/share_event.dart",
"repo_id": "photobooth",
"token_count": 208
} | 1,065 |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
const _backgroundColor = Color(0xFFF1F3F4);
const _textColor = Color(0xFF80858A);
class ShareCopyableLink extends StatefulWidget {
const ShareCopyableLink({
required this.link,
this.suspendDuration = const Duration(seconds: 5),
super.key,
});
/// The link that will be stored in the [Clipboard]
/// when [_CopyButton] is tapped.
final String link;
/// The duration for which the [_CopiedButton] is visible
/// after tapping on the [_CopyButton]. Defaults to 5 seconds.
final Duration suspendDuration;
@override
ShareCopyableLinkState createState() => ShareCopyableLinkState();
}
@visibleForTesting
class ShareCopyableLinkState extends State<ShareCopyableLink> {
@visibleForTesting
Timer? timer;
@visibleForTesting
bool copied = false;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return DecoratedBox(
decoration: BoxDecoration(
color: _backgroundColor,
borderRadius: BorderRadius.circular(10),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: 24),
const Icon(Icons.link, color: _textColor),
const SizedBox(width: 16),
Flexible(
child: SelectableText(
widget.link,
style: theme.textTheme.labelLarge?.copyWith(
color: _textColor,
overflow: TextOverflow.ellipsis,
),
maxLines: 1,
),
),
const SizedBox(width: 16),
Padding(
padding: const EdgeInsets.all(6),
child: copied
? _CopiedButton(
key: const Key('shareCopyableLink_copiedButton'),
onPressed: _resetCopied,
)
: _CopyButton(
key: const Key('shareCopyableLink_copyButton'),
onPressed: _copy,
),
),
],
),
);
}
void _copy() {
Clipboard.setData(ClipboardData(text: widget.link));
setState(() {
copied = true;
});
timer?.cancel();
timer = Timer(
const Duration(seconds: 5),
_resetCopied,
);
}
void _resetCopied() {
if (mounted) {
setState(() => copied = false);
}
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
}
final _copyButtonsMinimumSize = MaterialStateProperty.all(const Size(120, 40));
final _copyButtonsShape = MaterialStateProperty.all(
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
);
class _CopyButton extends StatelessWidget {
const _CopyButton({
required this.onPressed,
super.key,
});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return ElevatedButton(
style: ButtonStyle(
minimumSize: _copyButtonsMinimumSize,
backgroundColor: MaterialStateProperty.all(PhotoboothColors.blue),
shape: _copyButtonsShape,
),
onPressed: onPressed,
child: Text(l10n.sharePageCopyLinkButton),
);
}
}
class _CopiedButton extends StatelessWidget {
const _CopiedButton({
required this.onPressed,
super.key,
});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return ElevatedButton(
style: ButtonStyle(
minimumSize: _copyButtonsMinimumSize,
backgroundColor: MaterialStateProperty.all(PhotoboothColors.green),
shape: _copyButtonsShape,
),
onPressed: onPressed,
child: Text(l10n.sharePageLinkedCopiedButton),
);
}
}
| photobooth/lib/share/widgets/share_copyable_link.dart/0 | {
"file_path": "photobooth/lib/share/widgets/share_copyable_link.dart",
"repo_id": "photobooth",
"token_count": 1681
} | 1,066 |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:io_photobooth/l10n/l10n.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class ClearStickersButtonLayer extends StatelessWidget {
const ClearStickersButtonLayer({super.key});
@override
Widget build(BuildContext context) {
final isHidden = context.select(
(PhotoboothBloc bloc) => bloc.state.stickers.isEmpty,
);
if (isHidden) return const SizedBox();
return ClearStickersButton(
onPressed: () async {
final photoboothBloc = context.read<PhotoboothBloc>();
final confirmed = await showAppDialog<bool>(
context: context,
child: const ClearStickersDialog(),
);
if (confirmed ?? false) {
photoboothBloc.add(const PhotoClearStickersTapped());
}
},
);
}
}
class ClearStickersButton extends StatelessWidget {
const ClearStickersButton({
required this.onPressed,
super.key,
});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Semantics(
focusable: true,
button: true,
label: l10n.clearAllStickersButtonLabelText,
child: AppTooltipButton(
onPressed: onPressed,
message: l10n.clearStickersButtonTooltip,
verticalOffset: 50,
child: Image.asset('assets/icons/delete_icon.png', height: 100),
),
);
}
}
| photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_button_layer.dart/0 | {
"file_path": "photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_button_layer.dart",
"repo_id": "photobooth",
"token_count": 631
} | 1,067 |
import 'package:analytics/src/analytics_io.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('trackEvent', () {
test('returns normally', () {
expect(
() => trackEvent(
category: 'category',
action: 'action',
label: 'label',
),
returnsNormally,
);
});
});
}
| photobooth/packages/analytics/test/analytics_io_test.dart/0 | {
"file_path": "photobooth/packages/analytics/test/analytics_io_test.dart",
"repo_id": "photobooth",
"token_count": 166
} | 1,068 |
class MediaDeviceInfo {
const MediaDeviceInfo({
this.deviceId,
this.label,
});
final String? deviceId;
final String? label;
}
| photobooth/packages/camera/camera_platform_interface/lib/src/types/media_device_info.dart/0 | {
"file_path": "photobooth/packages/camera/camera_platform_interface/lib/src/types/media_device_info.dart",
"repo_id": "photobooth",
"token_count": 50
} | 1,069 |
name: image_compositor
description: A Flutter package which adds image compositing support via web workers
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.3.0
test: ^1.21.7
very_good_analysis: ^4.0.0+1
| photobooth/packages/image_compositor/pubspec.yaml/0 | {
"file_path": "photobooth/packages/image_compositor/pubspec.yaml",
"repo_id": "photobooth",
"token_count": 127
} | 1,070 |
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher_string.dart';
/// Opens the given [url] in a new tab of the host browser
Future<void> openLink(String url, {VoidCallback? onError}) async {
if (await canLaunchUrlString(url)) {
await launchUrlString(url);
} else if (onError != null) {
onError();
}
}
| photobooth/packages/photobooth_ui/lib/src/helpers/links_helper.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/helpers/links_helper.dart",
"repo_id": "photobooth",
"token_count": 122
} | 1,071 |
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
/// Default duration for a single pulse animation.
const defaultPulseDuration = Duration(milliseconds: 1600);
/// Default duration for the time between pulse animations.
const defaultTimeBetweenPulses = Duration(milliseconds: 800);
/// {@template animated_pulse}
/// Widget that applies a pulse animation to its child.
/// {@endtemplate}
class AnimatedPulse extends StatefulWidget {
/// {@macro animated_pulse}
const AnimatedPulse({
required this.child,
super.key,
this.pulseDuration = defaultPulseDuration,
this.timeBetweenPulses = defaultTimeBetweenPulses,
});
/// [Widget] that will have the pulse animation
final Widget child;
/// The duration of a single pulse animation.
final Duration pulseDuration;
/// The duration of the time between pulse animations.
final Duration timeBetweenPulses;
@override
State<AnimatedPulse> createState() => _AnimatedPulseState();
}
class _AnimatedPulseState extends State<AnimatedPulse>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
Timer? _timer;
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: widget.pulseDuration)
..addStatusListener(_onAnimationStatusChanged)
..forward();
}
void _onAnimationStatusChanged(AnimationStatus status) {
if (!mounted) return;
if (status == AnimationStatus.completed) {
_timer = Timer(widget.timeBetweenPulses, () {
if (mounted) _controller.forward(from: 0);
});
}
}
@override
void dispose() {
_timer?.cancel();
_controller
..removeStatusListener(_onAnimationStatusChanged)
..dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: PulsePainter(_controller),
child: widget.child,
);
}
}
/// {@template pulse_painter}
/// Painter for the pulse animation
/// {@endtemplate}
class PulsePainter extends CustomPainter {
/// {@macro pulse_painter}
const PulsePainter(this._animation) : super(repaint: _animation);
final Animation<double> _animation;
@override
void paint(Canvas canvas, Size size) {
final rect = Rect.fromLTRB(0, 0, size.width, size.height);
const color = PhotoboothColors.blue;
final circleSize = rect.width / 2;
final area = circleSize * circleSize;
final radius = sqrt(area * _animation.value * 3);
final opacity = 1.0 - _animation.value.clamp(0.0, 1.0);
final paint = Paint()..color = color.withOpacity(opacity);
canvas.drawCircle(rect.center, radius, paint);
}
@override
bool shouldRepaint(PulsePainter oldDelegate) => true;
}
| photobooth/packages/photobooth_ui/lib/src/widgets/animated_pulse.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/animated_pulse.dart",
"repo_id": "photobooth",
"token_count": 945
} | 1,072 |
export 'constants.dart';
| photobooth/packages/photobooth_ui/test/helpers/helpers.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/helpers/helpers.dart",
"repo_id": "photobooth",
"token_count": 9
} | 1,073 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
void main() {
group('AppTooltipButton', () {
testWidgets('renders AppTooltip', (tester) async {
const target = Key('__key__');
await tester.pumpWidget(
MaterialApp(
home: Material(
child: AppTooltipButton(
message: 'message',
onPressed: () {},
child: const SizedBox(key: target),
),
),
),
);
expect(find.byType(AppTooltip), findsOneWidget);
expect(find.byKey(target), findsOneWidget);
expect(find.text('message'), findsNothing);
});
testWidgets('calls onPressed when child is tapped', (tester) async {
var onPressedCallCount = 0;
const target = Key('__key__');
await tester.pumpWidget(
MaterialApp(
home: Material(
child: AppTooltipButton(
message: 'message',
onPressed: () => onPressedCallCount++,
child: const SizedBox(key: target),
),
),
),
);
await tester.tap(find.byKey(target), warnIfMissed: false);
expect(onPressedCallCount, equals(1));
});
testWidgets('renders tooltip when mode is visibleUntilInteraction',
(tester) async {
const target = Key('__key__');
await tester.pumpWidget(
MaterialApp(
home: Material(
child: AppTooltipButton(
message: 'message',
onPressed: () {},
mode: TooltipMode.visibleUntilInteraction,
child: const SizedBox(key: target),
),
),
),
);
expect(find.text('message'), findsOneWidget);
tester.widget<InkWell>(find.byType(InkWell)).onTap!.call();
await tester.pumpAndSettle();
expect(find.text('message'), findsNothing);
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/app_tooltip_button_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/widgets/app_tooltip_button_test.dart",
"repo_id": "photobooth",
"token_count": 930
} | 1,074 |
# platform_helper
A new Flutter package project.
## Getting Started
This project is a starting point for a Dart
[package](https://flutter.dev/developing-packages/),
a library module containing code that can be shared easily across
multiple Flutter or Dart projects.
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/platform_helper/README.md/0 | {
"file_path": "photobooth/packages/platform_helper/README.md",
"repo_id": "photobooth",
"token_count": 115
} | 1,075 |
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/external_links/external_links.dart';
import 'package:mocktail/mocktail.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
class MockUrlLauncher extends Mock
with MockPlatformInterfaceMixin
implements UrlLauncherPlatform {}
void main() {
setUpAll(() {
registerFallbackValue(const LaunchOptions());
});
group('External links', () {
late UrlLauncherPlatform originalUrlLauncher;
setUp(() {
originalUrlLauncher = UrlLauncherPlatform.instance;
});
tearDown(() {
UrlLauncherPlatform.instance = originalUrlLauncher;
});
group('launchGoogleIOLink', () {
test('launches correct link', () async {
final mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await launchGoogleIOLink();
verify(() => mock.launchUrl(googleIOExternalLink, any())).called(1);
});
});
group('launchFlutterDevLink', () {
test('launches correct link', () async {
final mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await launchFlutterDevLink();
verify(() => mock.launchUrl(flutterDevExternalLink, any())).called(1);
});
});
group('launchFirebaseLink', () {
test('launches correct link', () async {
final mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await launchFirebaseLink();
verify(() => mock.launchUrl(firebaseExternalLink, any())).called(1);
});
});
group('launchPhotoboothEmail', () {
test('launches correct link', () async {
final mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await launchPhotoboothEmail();
verify(() => mock.launchUrl(photoboothEmail, any())).called(1);
});
});
group('launchOpenSourceLink', () {
test('launches correct link', () async {
final mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
when(() => mock.canLaunch(any())).thenAnswer((_) async => true);
when(() => mock.launchUrl(any(), any())).thenAnswer((_) async => true);
await launchOpenSourceLink();
verify(() => mock.launchUrl(openSourceLink, any())).called(1);
});
});
});
}
| photobooth/test/external_links/external_links_test.dart/0 | {
"file_path": "photobooth/test/external_links/external_links_test.dart",
"repo_id": "photobooth",
"token_count": 1153
} | 1,076 |
// ignore_for_file: prefer_const_constructors
import 'dart:convert';
import 'dart:typed_data';
import 'package:bloc_test/bloc_test.dart';
import 'package:camera/camera.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:photos_repository/photos_repository.dart';
import '../../helpers/helpers.dart';
class MockPhotosRepository extends Mock implements PhotosRepository {}
class MockPhotoAsset extends Mock implements PhotoAsset {}
class MockAsset extends Mock implements Asset {}
void main() {
final data = 'data:image/png,${base64.encode(transparentImage)}';
final image = CameraImage(width: 0, height: 0, data: data);
final imageData = Uint8List.fromList(transparentImage);
const aspectRatio = PhotoboothAspectRatio.portrait;
const imageId = 'image-name';
const shareText = 'share-text';
const explicitShareUrl = 'explicit-share-url';
const twitterShareUrl = 'twitter-share-url';
const facebookShareUrl = 'facebook-share-url';
group('ShareBloc', () {
late PhotosRepository photosRepository;
late Asset asset;
late PhotoAsset photoAsset;
late ShareBloc shareBloc;
setUpAll(() {
registerFallbackValue(Uint8List(0));
});
setUp(() {
photosRepository = MockPhotosRepository();
asset = MockAsset();
when(() => asset.path).thenReturn('assets/path/asset.png');
photoAsset = MockPhotoAsset();
when(() => photoAsset.asset).thenReturn(asset);
when(() => photoAsset.angle).thenReturn(0);
when(() => photoAsset.constraint).thenReturn(PhotoConstraint());
when(() => photoAsset.position).thenReturn(
PhotoAssetPosition(dx: 1, dy: 1),
);
when(() => photoAsset.size).thenReturn(PhotoAssetSize());
shareBloc = ShareBloc(
photosRepository: photosRepository,
imageId: imageId,
image: image,
assets: [photoAsset],
shareText: shareText,
aspectRatio: aspectRatio,
isSharingEnabled: true,
);
});
test('initial state is ShareState', () {
expect(shareBloc.state, equals(ShareState()));
});
group('ShareViewLoaded', () {
blocTest<ShareBloc, ShareState>(
'emits [loading, failure] when compositing fails',
build: () {
when(
() => photosRepository.composite(
width: any(named: 'width'),
height: any(named: 'height'),
data: any(named: 'data'),
layers: any(named: 'layers'),
aspectRatio: any(named: 'aspectRatio'),
),
).thenThrow(Exception());
return shareBloc;
},
act: (bloc) => bloc.add(ShareViewLoaded()),
expect: () => [
ShareState(compositeStatus: ShareStatus.loading),
ShareState(
compositeStatus: ShareStatus.failure,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, success] when compositing succeeds',
build: () {
when(
() => photosRepository.composite(
width: any(named: 'width'),
height: any(named: 'height'),
data: any(named: 'data'),
layers: any(named: 'layers'),
aspectRatio: any(named: 'aspectRatio'),
),
).thenAnswer((_) async => imageData);
return shareBloc;
},
act: (bloc) => bloc.add(ShareViewLoaded()),
expect: () => [
ShareState(compositeStatus: ShareStatus.loading),
isA<ShareState>().having(
(s) => s.compositeStatus,
'compositeStatus',
ShareStatus.success,
),
],
);
});
group('ShareOnTwitterTapped', () {
blocTest<ShareBloc, ShareState>(
'does nothing when sharing is disabled',
build: () => ShareBloc(
photosRepository: photosRepository,
imageId: imageId,
image: image,
assets: [photoAsset],
shareText: shareText,
aspectRatio: aspectRatio,
),
act: (bloc) => bloc.add(ShareOnTwitterTapped()),
expect: () => <ShareState>[],
);
blocTest<ShareBloc, ShareState>(
'sets isUploadRequested to true with correct shareUrl',
build: () => shareBloc,
seed: () => ShareState(compositeStatus: ShareStatus.loading),
act: (bloc) => bloc.add(ShareOnTwitterTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, failure] '
'when composite status is success and upload fails',
build: () {
when(
() => photosRepository.sharePhoto(
fileName: any(named: 'fileName'),
data: any(named: 'data'),
shareText: any(named: 'shareText'),
),
).thenThrow(Exception());
return shareBloc;
},
seed: () => ShareState(compositeStatus: ShareStatus.success),
act: (bloc) => bloc.add(ShareOnTwitterTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.success,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.failure,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, success] '
'when composite status is success and upload succeeds',
build: () {
when(
() => photosRepository.sharePhoto(
fileName: any(named: 'fileName'),
data: any(named: 'data'),
shareText: any(named: 'shareText'),
),
).thenAnswer(
(_) async => ShareUrls(
explicitShareUrl: explicitShareUrl,
facebookShareUrl: facebookShareUrl,
twitterShareUrl: twitterShareUrl,
),
);
return shareBloc;
},
seed: () => ShareState(
compositeStatus: ShareStatus.success,
bytes: imageData,
),
act: (bloc) => bloc.add(ShareOnTwitterTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.success,
bytes: imageData,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.loading,
bytes: imageData,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.success,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, failure] '
'when composite status is failure and compositing fails',
build: () {
when(
() => photosRepository.composite(
width: any(named: 'width'),
height: any(named: 'height'),
data: any(named: 'data'),
layers: any(named: 'layers'),
aspectRatio: any(named: 'aspectRatio'),
),
).thenThrow(Exception());
return shareBloc;
},
seed: () => ShareState(compositeStatus: ShareStatus.failure),
act: (bloc) => bloc.add(ShareOnTwitterTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.failure,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
ShareState(
compositeStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
ShareState(
compositeStatus: ShareStatus.failure,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, failure] '
'when composite status is failure and compositing succeeds '
'but upload fails.',
build: () {
when(
() => photosRepository.composite(
width: any(named: 'width'),
height: any(named: 'height'),
data: any(named: 'data'),
layers: any(named: 'layers'),
aspectRatio: any(named: 'aspectRatio'),
),
).thenAnswer((_) async => imageData);
when(
() => photosRepository.sharePhoto(
fileName: any(named: 'fileName'),
data: any(named: 'data'),
shareText: any(named: 'shareText'),
),
).thenThrow(Exception());
return shareBloc;
},
seed: () => ShareState(compositeStatus: ShareStatus.failure),
act: (bloc) => bloc.add(ShareOnTwitterTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.failure,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
ShareState(
compositeStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
isA<ShareState>().having(
(s) => s.compositeStatus,
'compositeStatus',
ShareStatus.success,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.loading,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.failure,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, success] '
'when composite status is failure and compositing succeeds '
'and upload succeeds.',
build: () {
when(
() => photosRepository.composite(
width: any(named: 'width'),
height: any(named: 'height'),
data: any(named: 'data'),
layers: any(named: 'layers'),
aspectRatio: any(named: 'aspectRatio'),
),
).thenAnswer((_) async => imageData);
when(
() => photosRepository.sharePhoto(
fileName: any(named: 'fileName'),
data: any(named: 'data'),
shareText: any(named: 'shareText'),
),
).thenAnswer(
(_) async => ShareUrls(
explicitShareUrl: explicitShareUrl,
facebookShareUrl: facebookShareUrl,
twitterShareUrl: twitterShareUrl,
),
);
return shareBloc;
},
seed: () => ShareState(compositeStatus: ShareStatus.failure),
act: (bloc) => bloc.add(ShareOnTwitterTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.failure,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
ShareState(
compositeStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.twitter,
),
isA<ShareState>().having(
(s) => s.compositeStatus,
'compositeStatus',
ShareStatus.success,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.loading,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.success,
),
],
);
});
group('ShareOnFacebookTapped', () {
blocTest<ShareBloc, ShareState>(
'does nothing when sharing is disabled',
build: () => ShareBloc(
photosRepository: photosRepository,
imageId: imageId,
image: image,
assets: [photoAsset],
shareText: shareText,
aspectRatio: aspectRatio,
),
act: (bloc) => bloc.add(ShareOnFacebookTapped()),
expect: () => <ShareState>[],
);
blocTest<ShareBloc, ShareState>(
'sets isUploadRequested to true with correct shareUrl',
build: () => shareBloc,
seed: () => ShareState(compositeStatus: ShareStatus.loading),
act: (bloc) => bloc.add(ShareOnFacebookTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, failure] '
'when composite status is success and upload fails',
build: () {
when(
() => photosRepository.sharePhoto(
fileName: any(named: 'fileName'),
data: any(named: 'data'),
shareText: any(named: 'shareText'),
),
).thenThrow(Exception());
return shareBloc;
},
seed: () => ShareState(compositeStatus: ShareStatus.success),
act: (bloc) => bloc.add(ShareOnFacebookTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.success,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.failure,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, success] '
'when composite status is success and upload succeeds',
build: () {
when(
() => photosRepository.sharePhoto(
fileName: any(named: 'fileName'),
data: any(named: 'data'),
shareText: any(named: 'shareText'),
),
).thenAnswer(
(_) async => ShareUrls(
explicitShareUrl: explicitShareUrl,
facebookShareUrl: facebookShareUrl,
twitterShareUrl: twitterShareUrl,
),
);
return shareBloc;
},
seed: () => ShareState(
compositeStatus: ShareStatus.success,
bytes: imageData,
),
act: (bloc) => bloc.add(ShareOnFacebookTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.success,
bytes: imageData,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
ShareState(
compositeStatus: ShareStatus.success,
uploadStatus: ShareStatus.loading,
bytes: imageData,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.success,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, failure] '
'when composite status is failure and compositing fails',
build: () {
when(
() => photosRepository.composite(
width: any(named: 'width'),
height: any(named: 'height'),
data: any(named: 'data'),
layers: any(named: 'layers'),
aspectRatio: any(named: 'aspectRatio'),
),
).thenThrow(Exception());
return shareBloc;
},
seed: () => ShareState(compositeStatus: ShareStatus.failure),
act: (bloc) => bloc.add(ShareOnFacebookTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.failure,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
ShareState(
compositeStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
ShareState(
compositeStatus: ShareStatus.failure,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, failure] '
'when composite status is failure and compositing succeeds '
'but upload fails.',
build: () {
when(
() => photosRepository.composite(
width: any(named: 'width'),
height: any(named: 'height'),
data: any(named: 'data'),
layers: any(named: 'layers'),
aspectRatio: any(named: 'aspectRatio'),
),
).thenAnswer((_) async => imageData);
when(
() => photosRepository.sharePhoto(
fileName: any(named: 'fileName'),
data: any(named: 'data'),
shareText: any(named: 'shareText'),
),
).thenThrow(Exception());
return shareBloc;
},
seed: () => ShareState(compositeStatus: ShareStatus.failure),
act: (bloc) => bloc.add(ShareOnFacebookTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.failure,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
ShareState(
compositeStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
isA<ShareState>().having(
(s) => s.compositeStatus,
'compositeStatus',
ShareStatus.success,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.loading,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.failure,
),
],
);
blocTest<ShareBloc, ShareState>(
'emits [loading, success] '
'when composite status is failure and compositing succeeds '
'and upload succeeds.',
build: () {
when(
() => photosRepository.composite(
width: any(named: 'width'),
height: any(named: 'height'),
data: any(named: 'data'),
layers: any(named: 'layers'),
aspectRatio: any(named: 'aspectRatio'),
),
).thenAnswer((_) async => imageData);
when(
() => photosRepository.sharePhoto(
fileName: any(named: 'fileName'),
data: any(named: 'data'),
shareText: any(named: 'shareText'),
),
).thenAnswer(
(_) async => ShareUrls(
explicitShareUrl: explicitShareUrl,
facebookShareUrl: facebookShareUrl,
twitterShareUrl: twitterShareUrl,
),
);
return shareBloc;
},
seed: () => ShareState(compositeStatus: ShareStatus.failure),
act: (bloc) => bloc.add(ShareOnFacebookTapped()),
expect: () => [
ShareState(
compositeStatus: ShareStatus.failure,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
ShareState(
compositeStatus: ShareStatus.loading,
isUploadRequested: true,
shareUrl: ShareUrl.facebook,
),
isA<ShareState>().having(
(s) => s.compositeStatus,
'compositeStatus',
ShareStatus.success,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.loading,
),
isA<ShareState>().having(
(s) => s.uploadStatus,
'uploadStatus',
ShareStatus.success,
),
],
);
});
});
}
| photobooth/test/share/bloc/share_bloc_test.dart/0 | {
"file_path": "photobooth/test/share/bloc/share_bloc_test.dart",
"repo_id": "photobooth",
"token_count": 10333
} | 1,077 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class MockAsset extends Mock implements Asset {}
void main() {
group('StickersBloc', () {
test('initial state is StickersState()', () {
expect(StickersBloc().state, equals(StickersState()));
});
group('StickersDrawerTabTapped', () {
blocTest<StickersBloc, StickersState>(
'emits state with updated tab index',
build: StickersBloc.new,
seed: () => StickersState(
isDrawerActive: true,
shouldDisplayPropsReminder: false,
),
act: (bloc) => bloc.add(StickersDrawerTabTapped(index: 1)),
expect: () => [
StickersState(
isDrawerActive: true,
shouldDisplayPropsReminder: false,
tabIndex: 1,
),
],
);
});
group('StickersDrawerToggled', () {
blocTest<StickersBloc, StickersState>(
'emits isDrawerActive: true when isDrawerActive: false',
build: StickersBloc.new,
seed: () => StickersState(
shouldDisplayPropsReminder: false,
),
act: (bloc) => bloc.add(StickersDrawerToggled()),
expect: () => [
StickersState(
isDrawerActive: true,
shouldDisplayPropsReminder: false,
),
],
);
blocTest<StickersBloc, StickersState>(
'emits isDrawerActive: false when isDrawerActive: true',
build: StickersBloc.new,
seed: () => StickersState(
isDrawerActive: true,
shouldDisplayPropsReminder: false,
),
act: (bloc) => bloc.add(StickersDrawerToggled()),
expect: () => [
StickersState(
shouldDisplayPropsReminder: false,
),
],
);
blocTest<StickersBloc, StickersState>(
'emits shouldDisplayPropsReminder:false when StickersDrawerToggled',
build: StickersBloc.new,
seed: StickersState.new,
act: (bloc) => bloc.add(StickersDrawerToggled()),
expect: () => [
StickersState(
isDrawerActive: true,
shouldDisplayPropsReminder: false,
),
],
);
});
});
}
| photobooth/test/stickers/bloc/stickers_bloc_test.dart/0 | {
"file_path": "photobooth/test/stickers/bloc/stickers_bloc_test.dart",
"repo_id": "photobooth",
"token_count": 1130
} | 1,078 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.