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:pigeon/pigeon.dart';
@HostApi()
abstract class BackgroundApi2Host {
@TaskQueue(type: TaskQueueType.serialBackgroundThread)
int add(int x, int y);
}
| packages/packages/pigeon/pigeons/background_platform_channels.dart/0 | {
"file_path": "packages/packages/pigeon/pigeons/background_platform_channels.dart",
"repo_id": "packages",
"token_count": 104
} | 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.
package com.example.alternate_language_test_plugin;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import com.example.alternate_language_test_plugin.Primitive.PrimitiveFlutterApi;
import com.example.alternate_language_test_plugin.Primitive.PrimitiveHostApi;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class PrimitiveTest {
private static BinaryMessenger makeMockBinaryMessenger() {
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>) PrimitiveFlutterApi.getCodec().decodeMessage(message);
Object arg = args.get(0);
if (arg instanceof Long) {
Long longArg = (Long) arg;
if (longArg.intValue() == longArg.longValue()) {
// Value fits in the Integer so gets sent as such
// https://docs.flutter.dev/development/platform-integration/platform-channels?tab=type-mappings-java-tab#codec
arg = Integer.valueOf(longArg.intValue());
}
}
ArrayList<Object> wrapped = new ArrayList<Object>();
wrapped.add(0, arg);
ByteBuffer replyData = PrimitiveFlutterApi.getCodec().encodeMessage(wrapped);
replyData.position(0);
reply.reply(replyData);
return null;
})
.when(binaryMessenger)
.send(anyString(), any(), any());
return binaryMessenger;
}
@Test
public void primitiveInt() {
BinaryMessenger binaryMessenger = makeMockBinaryMessenger();
PrimitiveFlutterApi api = new PrimitiveFlutterApi(binaryMessenger);
boolean[] didCall = {false};
api.anInt(
1L,
new Primitive.Result<Long>() {
public void success(Long result) {
didCall[0] = true;
assertEquals(result, (Long) 1L);
}
public void error(Throwable error) {
assertEquals(error, null);
}
});
assertTrue(didCall[0]);
}
@Test
public void primitiveLongInt() {
BinaryMessenger binaryMessenger = makeMockBinaryMessenger();
PrimitiveFlutterApi api = new PrimitiveFlutterApi(binaryMessenger);
boolean[] didCall = {false};
api.anInt(
1L << 50,
new Primitive.Result<Long>() {
public void success(Long result) {
didCall[0] = true;
assertEquals(result.longValue(), 1L << 50);
}
public void error(Throwable error) {
assertEquals(error, null);
}
});
assertTrue(didCall[0]);
}
@Test
public void primitiveIntHostApi() {
PrimitiveHostApi mockApi = mock(PrimitiveHostApi.class);
when(mockApi.anInt(1L)).thenReturn(1L);
BinaryMessenger binaryMessenger = mock(BinaryMessenger.class);
PrimitiveHostApi.setUp(binaryMessenger, mockApi);
ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> handler =
ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class);
verify(binaryMessenger)
.setMessageHandler(
eq("dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt"),
handler.capture());
MessageCodec<Object> codec = PrimitiveHostApi.getCodec();
@SuppressWarnings("unchecked")
ByteBuffer message = codec.encodeMessage(new ArrayList<Object>(Arrays.asList((Integer) 1)));
message.rewind();
handler
.getValue()
.onMessage(
message,
(bytes) -> {
bytes.rewind();
@SuppressWarnings("unchecked")
ArrayList<Object> wrapped = (ArrayList<Object>) codec.decodeMessage(bytes);
assertTrue(wrapped.size() > 0);
assertEquals(1L, ((Long) wrapped.get(0)).longValue());
});
}
@Test
public void primitiveBool() {
BinaryMessenger binaryMessenger = makeMockBinaryMessenger();
PrimitiveFlutterApi api = new PrimitiveFlutterApi(binaryMessenger);
boolean[] didCall = {false};
api.aBool(
true,
new Primitive.Result<Boolean>() {
public void success(Boolean result) {
didCall[0] = true;
assertEquals(result, (Boolean) true);
}
public void error(Throwable error) {
assertEquals(error, null);
}
});
assertTrue(didCall[0]);
}
@Test
public void primitiveString() {
BinaryMessenger binaryMessenger = makeMockBinaryMessenger();
PrimitiveFlutterApi api = new PrimitiveFlutterApi(binaryMessenger);
boolean[] didCall = {false};
api.aString(
"hello",
new Primitive.Result<String>() {
public void success(String result) {
didCall[0] = true;
assertEquals(result, "hello");
}
public void error(Throwable error) {
assertEquals(error, null);
}
});
assertTrue(didCall[0]);
}
@Test
public void primitiveDouble() {
BinaryMessenger binaryMessenger = makeMockBinaryMessenger();
PrimitiveFlutterApi api = new PrimitiveFlutterApi(binaryMessenger);
boolean[] didCall = {false};
api.aDouble(
1.5,
new Primitive.Result<Double>() {
public void success(Double result) {
didCall[0] = true;
assertEquals(result, 1.5, 0.01);
}
public void error(Throwable error) {
assertEquals(error, null);
}
});
assertTrue(didCall[0]);
}
@Test
public void primitiveMap() {
BinaryMessenger binaryMessenger = makeMockBinaryMessenger();
PrimitiveFlutterApi api = new PrimitiveFlutterApi(binaryMessenger);
boolean[] didCall = {false};
api.aMap(
Collections.singletonMap("hello", 1),
new Primitive.Result<Map<Object, Object>>() {
public void success(Map<Object, Object> result) {
didCall[0] = true;
assertEquals(result, Collections.singletonMap("hello", 1));
}
public void error(Throwable error) {
assertEquals(error, null);
}
});
assertTrue(didCall[0]);
}
@Test
public void primitiveList() {
BinaryMessenger binaryMessenger = makeMockBinaryMessenger();
PrimitiveFlutterApi api = new PrimitiveFlutterApi(binaryMessenger);
boolean[] didCall = {false};
api.aList(
Collections.singletonList("hello"),
new Primitive.Result<List<Object>>() {
public void success(List<Object> result) {
didCall[0] = true;
assertEquals(result, Collections.singletonList("hello"));
}
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/PrimitiveTest.java/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/PrimitiveTest.java",
"repo_id": "packages",
"token_count": 3245
} | 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.
@import Flutter;
@import Foundation;
NS_ASSUME_NONNULL_BEGIN
/// A FlutterBinaryMessenger who replies with the first argument sent to it.
@interface EchoBinaryMessenger : NSObject <FlutterBinaryMessenger>
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithCodec:(NSObject<FlutterMessageCodec> *)codec;
@end
NS_ASSUME_NONNULL_END
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/EchoMessenger.h/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/EchoMessenger.h",
"repo_id": "packages",
"token_count": 163
} | 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 "AlternateLanguageTestPlugin.h"
#import "CoreTests.gen.h"
@interface AlternateLanguageTestPlugin ()
@property(nonatomic) FLTFlutterIntegrationCoreApi *flutterAPI;
@end
/// This plugin handles the native side of the integration tests in example/integration_test/.
@implementation AlternateLanguageTestPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
AlternateLanguageTestPlugin *plugin = [[AlternateLanguageTestPlugin alloc] init];
SetUpFLTHostIntegrationCoreApi([registrar messenger], plugin);
plugin.flutterAPI =
[[FLTFlutterIntegrationCoreApi alloc] initWithBinaryMessenger:[registrar messenger]];
}
#pragma mark HostIntegrationCoreApi implementation
- (void)noopWithError:(FlutterError *_Nullable *_Nonnull)error {
}
- (nullable FLTAllTypes *)echoAllTypes:(FLTAllTypes *)everything
error:(FlutterError *_Nullable *_Nonnull)error {
return everything;
}
- (nullable FLTAllNullableTypes *)echoAllNullableTypes:(nullable FLTAllNullableTypes *)everything
error:(FlutterError *_Nullable *_Nonnull)error {
return everything;
}
- (nullable id)throwErrorWithError:(FlutterError *_Nullable *_Nonnull)error {
*error = [FlutterError errorWithCode:@"An error" message:nil details:nil];
return nil;
}
- (void)throwErrorFromVoidWithError:(FlutterError *_Nullable *_Nonnull)error {
*error = [FlutterError errorWithCode:@"An error" message:nil details:nil];
}
- (nullable id)throwFlutterErrorWithError:(FlutterError *_Nullable *_Nonnull)error {
*error = [FlutterError errorWithCode:@"code" message:@"message" details:@"details"];
return nil;
}
- (nullable NSNumber *)echoInt:(NSInteger)anInt error:(FlutterError *_Nullable *_Nonnull)error {
return @(anInt);
}
- (nullable NSNumber *)echoDouble:(double)aDouble error:(FlutterError *_Nullable *_Nonnull)error {
return @(aDouble);
}
- (nullable NSNumber *)echoBool:(BOOL)aBool error:(FlutterError *_Nullable *_Nonnull)error {
return @(aBool);
}
- (nullable NSString *)echoString:(NSString *)aString
error:(FlutterError *_Nullable *_Nonnull)error {
return aString;
}
- (nullable FlutterStandardTypedData *)echoUint8List:(FlutterStandardTypedData *)aUint8List
error:(FlutterError *_Nullable *_Nonnull)error {
return aUint8List;
}
- (nullable id)echoObject:(id)anObject error:(FlutterError *_Nullable *_Nonnull)error {
return anObject;
}
- (nullable NSArray<id> *)echoList:(NSArray<id> *)aList
error:(FlutterError *_Nullable *_Nonnull)error {
return aList;
}
- (nullable NSDictionary<NSString *, id> *)echoMap:(NSDictionary<NSString *, id> *)aMap
error:(FlutterError *_Nullable *_Nonnull)error {
return aMap;
}
- (nullable FLTAllClassesWrapper *)echoClassWrapper:(FLTAllClassesWrapper *)wrapper
error:(FlutterError *_Nullable *_Nonnull)error {
return wrapper;
}
- (FLTAnEnumBox *_Nullable)echoEnum:(FLTAnEnum)anEnum
error:(FlutterError *_Nullable *_Nonnull)error {
return [[FLTAnEnumBox alloc] initWithValue:anEnum];
}
- (nullable NSString *)echoNamedDefaultString:(NSString *)aString
error:(FlutterError *_Nullable *_Nonnull)error {
return aString;
}
- (nullable NSNumber *)echoOptionalDefaultDouble:(double)aDouble
error:(FlutterError *_Nullable *_Nonnull)error {
return @(aDouble);
}
- (nullable NSNumber *)echoRequiredInt:(NSInteger)anInt
error:(FlutterError *_Nullable *_Nonnull)error {
return @(anInt);
}
- (nullable NSString *)extractNestedNullableStringFrom:(FLTAllClassesWrapper *)wrapper
error:(FlutterError *_Nullable *_Nonnull)error {
return wrapper.allNullableTypes.aNullableString;
}
- (nullable FLTAllClassesWrapper *)
createNestedObjectWithNullableString:(nullable NSString *)nullableString
error:(FlutterError *_Nullable *_Nonnull)error {
FLTAllNullableTypes *innerObject = [[FLTAllNullableTypes alloc] init];
innerObject.aNullableString = nullableString;
return [FLTAllClassesWrapper makeWithAllNullableTypes:innerObject allTypes:nil];
}
- (nullable FLTAllNullableTypes *)
sendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool
anInt:(nullable NSNumber *)aNullableInt
aString:(nullable NSString *)aNullableString
error:(FlutterError *_Nullable *_Nonnull)error {
FLTAllNullableTypes *someTypes = [[FLTAllNullableTypes alloc] init];
someTypes.aNullableBool = aNullableBool;
someTypes.aNullableInt = aNullableInt;
someTypes.aNullableString = aNullableString;
return someTypes;
}
- (nullable NSNumber *)echoNullableInt:(nullable NSNumber *)aNullableInt
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableInt;
}
- (nullable NSNumber *)echoNullableDouble:(nullable NSNumber *)aNullableDouble
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableDouble;
}
- (nullable NSNumber *)echoNullableBool:(nullable NSNumber *)aNullableBool
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableBool;
}
- (nullable NSString *)echoNullableString:(nullable NSString *)aNullableString
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableString;
}
- (nullable FlutterStandardTypedData *)
echoNullableUint8List:(nullable FlutterStandardTypedData *)aNullableUint8List
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableUint8List;
}
- (nullable id)echoNullableObject:(nullable id)aNullableObject
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableObject;
}
- (nullable NSArray<id> *)echoNullableList:(nullable NSArray<id> *)aNullableList
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableList;
}
- (nullable NSDictionary<NSString *, id> *)
echoNullableMap:(nullable NSDictionary<NSString *, id> *)aNullableMap
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableMap;
}
- (FLTAnEnumBox *_Nullable)echoNullableEnum:(nullable FLTAnEnumBox *)AnEnumBoxed
error:(FlutterError *_Nullable *_Nonnull)error {
return AnEnumBoxed;
}
- (nullable NSNumber *)echoOptionalNullableInt:(nullable NSNumber *)aNullableInt
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableInt;
}
- (nullable NSString *)echoNamedNullableString:(nullable NSString *)aNullableString
error:(FlutterError *_Nullable *_Nonnull)error {
return aNullableString;
}
- (void)noopAsyncWithCompletion:(void (^)(FlutterError *_Nullable))completion {
completion(nil);
}
- (void)throwAsyncErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion {
completion(nil, [FlutterError errorWithCode:@"An error" message:nil details:nil]);
}
- (void)throwAsyncErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion {
completion([FlutterError errorWithCode:@"An error" message:nil details:nil]);
}
- (void)throwAsyncFlutterErrorWithCompletion:(void (^)(id _Nullable,
FlutterError *_Nullable))completion {
completion(nil, [FlutterError errorWithCode:@"code" message:@"message" details:@"details"]);
}
- (void)echoAsyncAllTypes:(FLTAllTypes *)everything
completion:(void (^)(FLTAllTypes *_Nullable, FlutterError *_Nullable))completion {
completion(everything, nil);
}
- (void)echoAsyncNullableAllNullableTypes:(nullable FLTAllNullableTypes *)everything
completion:(void (^)(FLTAllNullableTypes *_Nullable,
FlutterError *_Nullable))completion {
completion(everything, nil);
}
- (void)echoAsyncInt:(NSInteger)anInt
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
completion(@(anInt), nil);
}
- (void)echoAsyncDouble:(double)aDouble
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
completion(@(aDouble), nil);
}
- (void)echoAsyncBool:(BOOL)aBool
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
completion(@(aBool), nil);
}
- (void)echoAsyncString:(NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion {
completion(aString, nil);
}
- (void)echoAsyncUint8List:(FlutterStandardTypedData *)aUint8List
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion {
completion(aUint8List, nil);
}
- (void)echoAsyncObject:(id)anObject
completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion {
completion(anObject, nil);
}
- (void)echoAsyncList:(NSArray<id> *)aList
completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion {
completion(aList, nil);
}
- (void)echoAsyncMap:(NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion {
completion(aMap, nil);
}
- (void)echoAsyncEnum:(FLTAnEnum)anEnum
completion:(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion {
completion([[FLTAnEnumBox alloc] initWithValue:anEnum], nil);
}
- (void)echoAsyncNullableInt:(nullable NSNumber *)anInt
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
completion(anInt, nil);
}
- (void)echoAsyncNullableDouble:(nullable NSNumber *)aDouble
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
completion(aDouble, nil);
}
- (void)echoAsyncNullableBool:(nullable NSNumber *)aBool
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
completion(aBool, nil);
}
- (void)echoAsyncNullableString:(nullable NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion {
completion(aString, nil);
}
- (void)echoAsyncNullableUint8List:(nullable FlutterStandardTypedData *)aUint8List
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion {
completion(aUint8List, nil);
}
- (void)echoAsyncNullableObject:(nullable id)anObject
completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion {
completion(anObject, nil);
}
- (void)echoAsyncNullableList:(nullable NSArray<id> *)aList
completion:
(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion {
completion(aList, nil);
}
- (void)echoAsyncNullableMap:(nullable NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion {
completion(aMap, nil);
}
- (void)echoAsyncNullableEnum:(nullable FLTAnEnumBox *)AnEnumBoxed
completion:
(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion {
completion(AnEnumBoxed, nil);
}
- (void)callFlutterNoopWithCompletion:(void (^)(FlutterError *_Nullable))completion {
[self.flutterAPI noopWithCompletion:^(FlutterError *error) {
completion(error);
}];
}
- (void)callFlutterThrowErrorWithCompletion:(void (^)(id _Nullable,
FlutterError *_Nullable))completion {
[self.flutterAPI throwErrorWithCompletion:^(id value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterThrowErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion {
[self.flutterAPI throwErrorFromVoidWithCompletion:^(FlutterError *error) {
completion(error);
}];
}
- (void)callFlutterEchoAllTypes:(FLTAllTypes *)everything
completion:
(void (^)(FLTAllTypes *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoAllTypes:everything
completion:^(FLTAllTypes *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterSendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool
anInt:(nullable NSNumber *)aNullableInt
aString:(nullable NSString *)aNullableString
completion:(void (^)(FLTAllNullableTypes *_Nullable,
FlutterError *_Nullable))completion {
[self.flutterAPI
sendMultipleNullableTypesABool:aNullableBool
anInt:aNullableInt
aString:aNullableString
completion:^(FLTAllNullableTypes *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoBool:(BOOL)aBool
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoBool:aBool
completion:^(NSNumber *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoInt:(NSInteger)anInt
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoInt:anInt
completion:^(NSNumber *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoDouble:(double)aDouble
completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoDouble:aDouble
completion:^(NSNumber *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoString:(NSString *)aString
completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoString:aString
completion:^(NSString *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoUint8List:(FlutterStandardTypedData *)aList
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion {
[self.flutterAPI echoUint8List:aList
completion:^(FlutterStandardTypedData *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoList:(NSArray<id> *)aList
completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoList:aList
completion:^(NSArray<id> *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoMap:(NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion {
[self.flutterAPI echoMap:aMap
completion:^(NSDictionary<NSString *, id> *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoEnum:(FLTAnEnum)anEnum
completion:(void (^)(FLTAnEnumBox *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoEnum:anEnum
completion:^(FLTAnEnumBox *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoAllNullableTypes:(nullable FLTAllNullableTypes *)everything
completion:(void (^)(FLTAllNullableTypes *_Nullable,
FlutterError *_Nullable))completion {
[self.flutterAPI echoAllNullableTypes:everything
completion:^(FLTAllNullableTypes *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoNullableBool:(nullable NSNumber *)aBool
completion:
(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoNullableBool:aBool
completion:^(NSNumber *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoNullableInt:(nullable NSNumber *)anInt
completion:
(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoNullableInt:anInt
completion:^(NSNumber *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoNullableDouble:(nullable NSNumber *)aDouble
completion:
(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoNullableDouble:aDouble
completion:^(NSNumber *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoNullableString:(nullable NSString *)aString
completion:
(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoNullableString:aString
completion:^(NSString *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoNullableUint8List:(nullable FlutterStandardTypedData *)aList
completion:(void (^)(FlutterStandardTypedData *_Nullable,
FlutterError *_Nullable))completion {
[self.flutterAPI echoNullableUint8List:aList
completion:^(FlutterStandardTypedData *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoNullableList:(nullable NSArray<id> *)aList
completion:
(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion {
[self.flutterAPI echoNullableList:aList
completion:^(NSArray<id> *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoNullableMap:(nullable NSDictionary<NSString *, id> *)aMap
completion:(void (^)(NSDictionary<NSString *, id> *_Nullable,
FlutterError *_Nullable))completion {
[self.flutterAPI echoNullableMap:aMap
completion:^(NSDictionary<NSString *, id> *value, FlutterError *error) {
completion(value, error);
}];
}
- (void)callFlutterEchoNullableEnum:(nullable FLTAnEnumBox *)AnEnumBoxed
completion:(void (^)(FLTAnEnumBox *_Nullable,
FlutterError *_Nullable))completion {
[self.flutterAPI echoNullableEnum:AnEnumBoxed
completion:^(FLTAnEnumBox *value, FlutterError *error) {
completion(value, error);
}];
}
@end
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/ios/Classes/AlternateLanguageTestPlugin.m/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/ios/Classes/AlternateLanguageTestPlugin.m",
"repo_id": "packages",
"token_count": 9601
} | 1,015 |
// 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 'generated.dart';
void main() {
runApp(const ExampleApp());
}
/// A trivial example that validates that Pigeon is able to successfully call
/// into native code.
///
/// Actual testing is all done in the integration tests, which run in the
/// context of the example app but don't actually rely on this class.
class ExampleApp extends StatefulWidget {
/// Creates a new example app.
const ExampleApp({super.key});
@override
State<ExampleApp> createState() => _ExampleAppState();
}
class _ExampleAppState extends State<ExampleApp> {
late final HostIntegrationCoreApi api;
String status = 'Calling...';
@override
void initState() {
super.initState();
initPlatformState();
}
Future<void> initPlatformState() async {
api = HostIntegrationCoreApi();
try {
// Make a single trivial call just to validate that everything is wired
// up.
await api.noop();
} catch (e) {
setState(() {
status = 'Failed: $e';
});
return;
}
setState(() {
status = 'Success!';
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Pigeon integration tests'),
),
body: Center(
child: Text(status),
),
),
);
}
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/example_app.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/example_app.dart",
"repo_id": "packages",
"token_count": 550
} | 1,016 |
// 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 specifically tests the test code generated by dartTestOut.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_test_plugin_code/src/generated/message.gen.dart';
import 'test_message.gen.dart';
class Mock implements TestHostApi {
List<String> log = <String>[];
@override
void initialize() {
log.add('initialize');
}
@override
MessageSearchReply search(MessageSearchRequest arg) {
log.add('search');
return MessageSearchReply()..result = arg.query;
}
}
class MockNested implements TestNestedApi {
bool didCall = false;
@override
MessageSearchReply search(MessageNested arg) {
didCall = true;
if (arg.request == null) {
return MessageSearchReply();
} else {
return MessageSearchReply()..result = arg.request?.query;
}
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('simple', () async {
final MessageNestedApi api = MessageNestedApi();
final MockNested mock = MockNested();
TestNestedApi.setup(mock);
final MessageSearchReply reply =
await api.search(MessageNested()..request = null);
expect(mock.didCall, true);
expect(reply.result, null);
});
test('nested', () async {
final MessageApi api = MessageApi();
final Mock mock = Mock();
TestHostApi.setup(mock);
final MessageSearchReply reply =
await api.search(MessageSearchRequest()..query = 'foo');
expect(mock.log, <String>['search']);
expect(reply.result, 'foo');
});
test('no-arg calls', () async {
final MessageApi api = MessageApi();
final Mock mock = Mock();
TestHostApi.setup(mock);
await api.initialize();
expect(mock.log, <String>['initialize']);
});
test(
'calling methods with null',
() async {
final Mock mock = Mock();
TestHostApi.setup(mock);
expect(
await const BasicMessageChannel<Object?>(
'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize',
StandardMessageCodec(),
).send(<Object?>[null]),
isEmpty,
);
try {
await const BasicMessageChannel<Object?>(
'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search',
StandardMessageCodec(),
).send(<Object?>[null]) as List<Object?>?;
expect(true, isFalse); // should not reach here
} catch (error) {
expect(error, isAssertionError);
expect(
error.toString(),
contains(
'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null, expected non-null MessageSearchRequest.',
),
);
}
expect(mock.log, <String>['initialize']);
},
);
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/genered_dart_test_code_test.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/genered_dart_test_code_test.dart",
"repo_id": "packages",
"token_count": 1123
} | 1,017 |
group 'com.example.test_plugin'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.9.22'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.0.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'com.example.test_plugin'
}
compileSdk 34
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
allWarningsAsErrors = true
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
minSdkVersion 16
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
dependencies {
testImplementation 'junit:junit:4.+'
testImplementation "io.mockk:mockk:1.13.7"
}
}
| packages/packages/pigeon/platform_tests/test_plugin/android/build.gradle/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/build.gradle",
"repo_id": "packages",
"token_count": 759
} | 1,018 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/pigeon/platform_tests/test_plugin/example/android/gradle.properties/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 31
} | 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.
import XCTest
@testable import test_plugin
class ListTests: XCTestCase {
func testListInList() throws {
let inside = TestMessage(testList: [1, 2, 3])
let top = TestMessage(testList: [inside])
let binaryMessenger = EchoBinaryMessenger(codec: FlutterSmallApiCodec.shared)
let api = FlutterSmallApi(binaryMessenger: binaryMessenger)
let expectation = XCTestExpectation(description: "callback")
api.echo(top) { result in
switch result {
case .success(let res):
XCTAssertEqual(1, res.testList?.count)
XCTAssertTrue(res.testList?[0] is TestMessage)
XCTAssert(equalsList(inside.testList, (res.testList?[0] as! TestMessage).testList))
expectation.fulfill()
case .failure(_):
return
}
}
wait(for: [expectation], timeout: 1.0)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ListTests.swift/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ListTests.swift",
"repo_id": "packages",
"token_count": 378
} | 1,020 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/pigeon/platform_tests/test_plugin/example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 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.
#include "echo_messenger.h"
#include <flutter/encodable_value.h>
#include <flutter/message_codec.h>
namespace testing {
EchoMessenger::EchoMessenger(
const flutter::MessageCodec<flutter::EncodableValue>* codec)
: codec_(codec) {}
EchoMessenger::~EchoMessenger() {}
// flutter::BinaryMessenger:
void EchoMessenger::Send(const std::string& channel, const uint8_t* message,
size_t message_size,
flutter::BinaryReply reply) const {
std::unique_ptr<flutter::EncodableValue> arg_value =
codec_->DecodeMessage(message, message_size);
const auto& args = std::get<flutter::EncodableList>(*arg_value);
std::unique_ptr<std::vector<uint8_t>> reply_data =
codec_->EncodeMessage(args[0]);
reply(reply_data->data(), reply_data->size());
}
void EchoMessenger::SetMessageHandler(const std::string& channel,
flutter::BinaryMessageHandler handler) {}
} // namespace testing
| packages/packages/pigeon/platform_tests/test_plugin/windows/test/utils/echo_messenger.cpp/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/utils/echo_messenger.cpp",
"repo_id": "packages",
"token_count": 441
} | 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 'package:pigeon/ast.dart';
import 'package:pigeon/generator_tools.dart';
import 'package:pigeon/objc_generator.dart';
import 'package:pigeon/pigeon_lib.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 header', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface Foobar'));
expect(code, matches('@property.*NSString.*field1'));
});
test('gen one class source', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('#import "foo.h"'));
expect(code, contains('@implementation Foobar'));
});
test('gen one enum header', () {
final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[
Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
)
]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('typedef NS_ENUM(NSUInteger, Enum1) {'));
expect(code, contains(' Enum1One = 0,'));
expect(code, contains(' Enum1Two = 1,'));
});
test('gen one enum header with prefix', () {
final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[
Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
)
]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(prefix: 'PREFIX'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('typedef NS_ENUM(NSUInteger, PREFIXEnum1) {'));
expect(code, contains(' PREFIXEnum1One = 0,'));
expect(code, contains(' PREFIXEnum1Two = 1,'));
});
test('gen one class source with enum', () {
final Root root = Root(
apis: <Api>[],
classes: <Class>[
Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type:
const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'field1'),
NamedType(
type: TypeDeclaration(
baseName: 'Enum1',
associatedEnum: emptyEnum,
isNullable: true,
),
name: 'enum1'),
],
),
],
enums: <Enum>[
Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
)
],
);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('#import "foo.h"'));
expect(code, contains('@implementation Foobar'));
expect(
code,
contains(
'Enum1Box *enum1 = enum1AsNumber == nil ? nil : [[Enum1Box alloc] initWithValue:[enum1AsNumber integerValue]];'));
});
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',
associatedEnum: emptyEnum,
isNullable: false,
))
])
])
], classes: <Class>[], enums: <Enum>[
Enum(name: 'Foo', members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
])
]);
final StringBuffer sink = StringBuffer();
const ObjcOptions options =
ObjcOptions(headerIncludePath: 'foo.h', prefix: 'AC');
{
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: options,
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('typedef NS_ENUM(NSUInteger, ACFoo)'));
expect(code, contains(':(ACFoo)foo error:'));
}
{
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: options,
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'ACFoo arg_foo = [GetNullableObjectAtIndex(args, 0) integerValue];'));
}
});
test('validate nullable primitive enum', () {
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',
associatedEnum: emptyEnum,
isNullable: true,
))
])
])
], classes: <Class>[], enums: <Enum>[
Enum(name: 'Foo', members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
])
]);
const ObjcOptions options = ObjcOptions(headerIncludePath: 'foo.h');
final List<Error> errors = validateObjc(options, root);
expect(errors.length, 1);
expect(errors[0].message, contains('Nullable enum'));
});
test('gen one class header with enum', () {
final Root root = Root(
apis: <Api>[],
classes: <Class>[
Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type:
const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'field1'),
NamedType(
type: TypeDeclaration(
baseName: 'Enum1',
associatedEnum: emptyEnum,
isNullable: true,
),
name: 'enum1'),
],
),
],
enums: <Enum>[
Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
)
],
);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code,
contains('@property(nonatomic, strong, nullable) Enum1Box * enum1;'));
});
test('gen one api header', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface Input'));
expect(code, contains('@interface Output'));
expect(code, contains('@protocol Api'));
expect(code, contains('/// @return `nil` only when `error != nil`.'));
expect(code, matches('nullable Output.*doSomething.*Input.*FlutterError'));
expect(code, matches('SetUpApi.*<Api>.*_Nullable'));
expect(code, contains('ApiGetCodec(void)'));
});
test('gen one api source', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('#import "foo.h"'));
expect(code, contains('@implementation Input'));
expect(code, contains('@implementation Output'));
expect(code, contains('SetUpApi('));
expect(
code,
contains(
'NSCAssert([api respondsToSelector:@selector(doSomething:error:)'));
expect(code, contains('ApiGetCodec(void) {'));
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface Foobar'));
expect(code, contains('@class FlutterStandardTypedData;'));
expect(code, matches('@property.*strong.*NSNumber.*aBool'));
expect(code, matches('@property.*strong.*NSNumber.*aInt'));
expect(code, matches('@property.*strong.*NSNumber.*aDouble'));
expect(code, matches('@property.*copy.*NSString.*aString'));
expect(code,
matches('@property.*strong.*FlutterStandardTypedData.*aUint8List'));
expect(code,
matches('@property.*strong.*FlutterStandardTypedData.*aInt32List'));
expect(code,
matches('@property.*strong.*FlutterStandardTypedData.*Int64List'));
expect(code,
matches('@property.*strong.*FlutterStandardTypedData.*Float64List'));
});
test('bool source', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'bool', isNullable: true),
name: 'aBool'),
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@implementation Foobar'));
expect(code,
contains('pigeonResult.aBool = GetNullableObjectAtIndex(list, 0);'));
});
test('nested class header', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'input')
]),
Class(name: 'Nested', fields: <NamedType>[
NamedType(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: true,
),
name: 'nested')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code,
contains('@property(nonatomic, strong, nullable) Input * nested;'));
});
test('nested class source', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'input')
]),
Class(name: 'Nested', fields: <NamedType>[
NamedType(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: true,
),
name: 'nested')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'pigeonResult.nested = [Input nullableFromList:(GetNullableObjectAtIndex(list, 0))];'));
expect(
code, contains('self.nested ? [self.nested toList] : [NSNull null]'));
});
test('prefix class header', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface ABCFoobar'));
});
test('prefix class source', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@implementation ABCFoobar'));
});
test('prefix nested class header', () {
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: 'Nested',
associatedClass: emptyClass,
isNullable: false,
))
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'input')
]),
Class(name: 'Nested', fields: <NamedType>[
NamedType(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: true,
),
name: 'nested')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches('property.*ABCInput'));
expect(code, matches('ABCNested.*doSomething.*ABCInput'));
expect(code, contains('@protocol ABCApi'));
});
test('prefix nested class source', () {
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: 'Nested',
associatedClass: emptyClass,
isNullable: false,
))
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'input')
]),
Class(name: 'Nested', fields: <NamedType>[
NamedType(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: true,
),
name: 'nested')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('ABCInput fromList'));
expect(code, matches(r'ABCInput.*=.*args.*0.*\;'));
expect(code, contains('void SetUpABCApi('));
});
test('gen flutter api header', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface Api : NSObject'));
expect(
code,
contains(
'initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;'));
expect(code, matches('void.*doSomething.*Input.*Output'));
expect(code, contains('ApiGetCodec(void)'));
});
test('gen flutter api source', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(headerIncludePath: 'foo.h'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@implementation Api'));
expect(code, matches('void.*doSomething.*Input.*Output.*{'));
expect(code, contains('ApiGetCodec(void) {'));
});
test('gen host void header', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('(void)doSomething:'));
});
test('gen host void source', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(matches('=.*doSomething')));
expect(code, matches('[.*doSomething:.*]'));
expect(code, contains('callback(wrapResult(nil, error))'));
});
test('gen flutter void return header', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('completion:(void (^)(FlutterError *_Nullable))'));
});
test('gen flutter void return source', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('completion:(void (^)(FlutterError *_Nullable))'));
expect(code, contains('completion(nil)'));
});
test('gen host void arg header', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches('ABCOutput.*doSomethingWithError:[(]FlutterError'));
});
test('gen host void arg source', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches('output.*=.*api doSomethingWithError:&error'));
});
test('gen flutter void arg header', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion'));
});
test('gen flutter void arg source', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion'));
expect(code, contains('channel sendMessage:nil'));
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface Foobar'));
expect(code, matches('@property.*NSArray.*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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface Foobar'));
expect(code, matches('@property.*NSDictionary.*field1'));
});
test('gen map field with object', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'Map',
isNullable: true,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'Object', isNullable: true),
]),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface Foobar'));
expect(
code,
contains(
'@property(nonatomic, copy, nullable) NSDictionary<NSString *, id> *'));
});
test('gen map argument with object', () {
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: 'Map',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'Object', isNullable: true),
]))
]),
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('(NSDictionary<NSString *, id> *)foo'));
});
test('async void (input) HostApi header', () {
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: 'input')
],
returnType: const TypeDeclaration.voidDeclaration(),
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'(void)doSomethingInput:(ABCInput *)input completion:(void (^)(FlutterError *_Nullable))completion'));
});
test('async output(input) HostApi header', () {
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: 'input')
],
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'(void)doSomethingInput:(ABCInput *)input completion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion'));
});
test('async output(void) HostApi header', () {
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,
),
isAsynchronous: true)
])
], classes: <Class>[
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'output')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'(void)doSomethingWithCompletion:(void (^)(ABCOutput *_Nullable, FlutterError *_Nullable))completion'));
});
test('async void (void) HostApi header', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration.voidDeclaration(),
isAsynchronous: true)
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'(void)doSomethingWithCompletion:(void (^)(FlutterError *_Nullable))completion'));
});
test('async output(input) HostApi source', () {
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,
),
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'[api doSomething:arg0 completion:^(ABCOutput *_Nullable output, FlutterError *_Nullable error) {'));
});
test('async void (input) HostApi source', () {
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: 'foo')
],
returnType: const TypeDeclaration.voidDeclaration(),
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'[api doSomethingFoo:arg_foo completion:^(FlutterError *_Nullable error) {'));
});
test('async void (void) HostApi source', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: const TypeDeclaration.voidDeclaration(),
isAsynchronous: true)
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'[api doSomethingWithCompletion:^(FlutterError *_Nullable error) {'));
});
test('async output(void) HostApi source', () {
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,
),
isAsynchronous: true)
])
], classes: <Class>[
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: true),
name: 'output')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'[api doSomethingWithCompletion:^(ABCOutput *_Nullable output, FlutterError *_Nullable error) {'));
});
Iterable<String> makeIterable(String string) sync* {
yield string;
}
test('source copyright', () {
final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: ObjcOptions(
headerIncludePath: 'foo.h',
prefix: 'ABC',
copyrightHeader: makeIterable('hello world')),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, startsWith('// hello world'));
});
test('header copyright', () {
final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: ObjcOptions(
headerIncludePath: 'foo.h',
prefix: 'ABC',
copyrightHeader: makeIterable('hello world')),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, startsWith('// hello world'));
});
test('field 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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('NSArray<NSNumber *> * 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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('doitArg:(NSArray<NSNumber *> *)arg'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'NSArray<NSNumber *> *arg_arg = GetNullableObjectAtIndex(args, 0)'));
}
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('doitArg:(NSArray<NSNumber *> *)arg'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('doitArg:(NSArray<NSNumber *> *)arg'));
}
});
test('host nested generic 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: 'List',
isNullable: true,
typeArguments: <TypeDeclaration>[
TypeDeclaration(
baseName: 'bool', isNullable: true)
]),
]),
name: 'arg')
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('doitArg:(NSArray<NSArray<NSNumber *> *> *)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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code, contains('- (nullable NSArray<NSNumber *> *)doitWithError:'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('NSArray<NSNumber *> *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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code, contains('doitWithCompletion:(void (^)(NSArray<NSNumber *> *'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code, contains('doitWithCompletion:(void (^)(NSArray<NSNumber *> *'));
}
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'- (nullable NSNumber *)addX:(NSInteger)x y:(NSInteger)y error:(FlutterError *_Nullable *_Nonnull)error;'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('NSArray *args = message;'));
expect(
code,
contains(
'NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];'));
expect(
code,
contains(
'NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];'));
expect(code,
contains('NSNumber *output = [api addX:arg_x y:arg_y error:&error]'));
}
});
test('host multiple args async', () {
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),
isAsynchronous: true,
)
])
], classes: <Class>[], enums: <Enum>[]);
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'- (void)addX:(NSInteger)x y:(NSInteger)y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('NSArray *args = message;'));
expect(
code,
contains(
'NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];'));
expect(
code,
contains(
'NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];'));
expect(code, contains('[api addX:arg_x y:arg_y completion:'));
}
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'- (void)addX:(NSInteger)x y:(NSInteger)y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'- (void)addX:(NSInteger)arg_x y:(NSInteger)arg_y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {'));
expect(
code, contains('[channel sendMessage:@[@(arg_x), @(arg_y)] reply:'));
}
});
Root getDivideRoot(ApiLocation location) => Root(
apis: <Api>[
switch (location) {
ApiLocation.host => AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'divide',
location: location,
objcSelector: 'divideValue:by:',
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'int', isNullable: false),
name: 'x',
),
Parameter(
type: const TypeDeclaration(
baseName: 'int', isNullable: false),
name: 'y',
),
],
returnType: const TypeDeclaration(
baseName: 'double', isNullable: false))
]),
ApiLocation.flutter => AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'divide',
location: location,
objcSelector: 'divideValue:by:',
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'int', isNullable: false),
name: 'x',
),
Parameter(
type: const TypeDeclaration(
baseName: 'int', isNullable: false),
name: 'y',
),
],
returnType: const TypeDeclaration(
baseName: 'double', isNullable: false))
]),
}
],
classes: <Class>[],
enums: <Enum>[],
);
test('host custom objc selector', () {
final Root divideRoot = getDivideRoot(ApiLocation.host);
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
divideRoot,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches('divideValue:.*by:.*error.*;'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
divideRoot,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches('divideValue:.*by:.*error.*;'));
}
});
test('flutter custom objc selector', () {
final Root divideRoot = getDivideRoot(ApiLocation.flutter);
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
divideRoot,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches('divideValue:.*by:.*completion.*;'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions:
const ObjcOptions(headerIncludePath: 'foo.h', prefix: 'ABC'),
);
generator.generate(
generatorOptions,
divideRoot,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches('divideValue:.*by:.*completion.*{'));
}
});
test('test non null field', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(baseName: 'String', isNullable: false),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('@interface Foobar'));
expect(code, contains('@property(nonatomic, copy) NSString * field1'));
});
test('return nullable flutter header', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
matches(
r'doitWithCompletion.*void.*NSNumber \*_Nullable.*FlutterError.*completion;'));
});
test('return nullable flutter source', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches(r'doitWithCompletion.*NSNumber \*_Nullable'));
});
test('return nullable host header', () {
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, matches(r'nullable NSNumber.*doitWithError'));
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('doitFoo:(nullable NSNumber *)foo'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code,
contains('NSNumber *arg_foo = GetNullableObjectAtIndex(args, 0);'));
}
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('doitFoo:(nullable NSNumber *)foo'));
}
{
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('- (void)doitFoo:(nullable NSNumber *)arg_foo'));
}
});
test('background platform channel', () {
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>[],
taskQueueType: TaskQueueType.serialBackgroundThread)
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'NSObject<FlutterTaskQueue> *taskQueue = [binaryMessenger makeBackgroundTaskQueue];'));
expect(code, contains('taskQueue:taskQueue'));
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
for (final String comment in comments) {
expect(code, contains('///$comment'));
}
expect(code, contains('/// ///'));
});
test("doesn't create codecs if no custom datatypes", () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(
name: 'Api',
methods: <Method>[
Method(
name: 'method',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'field',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
],
)
],
)
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains(' : FlutterStandardReader')));
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains(' : FlutterStandardReader'));
});
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 ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'return [FlutterError errorWithCode:@"channel-error" message:[NSString stringWithFormat:@"%@/%@/%@", @"Unable to establish connection on channel: \'", channelName, @"\'."] details:@""]'));
expect(code, contains('completion(createConnectionError(channelName))'));
});
test('header of FlutterApi uses correct enum name with prefix', () {
final Enum enum1 = Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
);
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
isAsynchronous: true,
parameters: <Parameter>[],
returnType: TypeDeclaration(
baseName: 'Enum1',
isNullable: false,
associatedEnum: enum1,
),
)
]),
], classes: <Class>[], enums: <Enum>[
enum1,
]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(prefix: 'FLT'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains('FLTFLT')));
expect(code, contains('FLTEnum1Box'));
});
test('source of FlutterApi uses correct enum name with prefix', () {
final Enum enum1 = Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
);
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
isAsynchronous: true,
parameters: <Parameter>[],
returnType: TypeDeclaration(
baseName: 'Enum1',
isNullable: false,
associatedEnum: enum1,
),
)
]),
], classes: <Class>[], enums: <Enum>[
enum1,
]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(prefix: 'FLT'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains('FLTFLT')));
expect(code, contains('FLTEnum1Box'));
});
test('header of HostApi uses correct enum name with prefix', () {
final Enum enum1 = Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
);
final TypeDeclaration enumType = TypeDeclaration(
baseName: 'Enum1',
isNullable: false,
associatedEnum: enum1,
);
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
isAsynchronous: true,
parameters: <Parameter>[Parameter(name: 'value', type: enumType)],
returnType: enumType,
)
]),
], classes: <Class>[], enums: <Enum>[
enum1,
]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.header,
languageOptions: const ObjcOptions(prefix: 'FLT'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains('FLTFLT')));
expect(code, contains('FLTEnum1Box'));
});
test('source of HostApi uses correct enum name with prefix', () {
final Enum enum1 = Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
);
final TypeDeclaration enumType = TypeDeclaration(
baseName: 'Enum1',
isNullable: false,
associatedEnum: enum1,
);
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
isAsynchronous: true,
parameters: <Parameter>[Parameter(name: 'value', type: enumType)],
returnType: enumType,
)
]),
], classes: <Class>[], enums: <Enum>[
enum1,
]);
final StringBuffer sink = StringBuffer();
const ObjcGenerator generator = ObjcGenerator();
final OutputFileOptions<ObjcOptions> generatorOptions =
OutputFileOptions<ObjcOptions>(
fileType: FileType.source,
languageOptions: const ObjcOptions(prefix: 'FLT'),
);
generator.generate(
generatorOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains('FLTFLT')));
expect(code, contains('FLTEnum1Box'));
});
}
| packages/packages/pigeon/test/objc_generator_test.dart/0 | {
"file_path": "packages/packages/pigeon/test/objc_generator_test.dart",
"repo_id": "packages",
"token_count": 46472
} | 1,023 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 3.1.4
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Fixes new lint warnings.
## 3.1.3
* Adds example app.
## 3.1.2
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 3.1.1
* Transfers the package source from https://github.com/google/platform.dart to
https://github.com/flutter/packages.
## 3.1.0
* Removed `Platform.packageRoot`, which was already marked deprecated, and which
didn't work in Dart 2.
## 3.0.2
* Added `FakePlatform.copyWith` function.
## 3.0.1
* Added string constants for each of the supported platforms for use in switch
statements.
## 3.0.0
* First stable null safe release.
## 3.0.0-nullsafety.4
* Update supported SDK range.
## 3.0.0-nullsafety.3
* Update supported SDK range.
## 3.0.0-nullsafety.2
* Update supported SDK range.
## 3.0.0-nullsafety.1
* Migrate package to null-safe dart.
## 2.2.1
* Add `operatingSystemVersion`
## 2.2.0
* Declare compatibility with Dart 2 stable
* Update dependency on `package:test` to 1.0
## 2.1.2
* Relax sdk upper bound constraint to '<2.0.0' to allow 'edge' dart sdk use.
## 2.1.1
* Bumped maximum Dart SDK version to 2.0.0-dev.infinity
## 2.1.0
* Added `localeName`
* Bumped minimum Dart SDK version to 1.24.0-dev.0.0
## 2.0.0
* Added `stdinSupportsAnsi` and `stdinSupportsAnsi`
* Removed `ansiSupported`
## 1.1.1
* Updated `LocalPlatform` to use new `dart.io` API for ansi color support queries
* Bumped minimum Dart SDK version to 1.23.0-dev.10.0
## 1.1.0
* Added `ansiSupported`
* Bumped minimum Dart SDK version to 1.23.0-dev.9.0
## 1.0.2
* Minor doc updates
## 1.0.1
* Added const constructors for `Platform` and `LocalPlatform`
## 1.0.0
* Initial version
| packages/packages/platform/CHANGELOG.md/0 | {
"file_path": "packages/packages/platform/CHANGELOG.md",
"repo_id": "packages",
"token_count": 676
} | 1,024 |
## 0.10.2
* Updates web code to package `web: ^0.5.0`.
* Updates SDK version to Dart `^3.3.0`. Flutter `^3.19.0`.
## 0.10.1+2
* Fixes "width and height missing" warning on web.
## 0.10.1+1
* Updates minimum required plugin_platform_interface version to 2.1.7.
## 0.10.1
* Uses `HtmlElementView.fromTagName` instead of custom factories.
* Migrates package and tests to `platform:web`.
* Updates minimum supported SDK version to Flutter 3.16.0/Dart 3.2.0.
## 0.10.0
* Moves web implementation to its own package.
| packages/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md",
"repo_id": "packages",
"token_count": 187
} | 1,025 |
name: pointer_interceptor_web
description: Web implementation of the pointer_interceptor plugin.
repository: https://github.com/flutter/packages/tree/main/packages/pointer_interceptor/pointer_interceptor_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Apointer_interceptor
version: 0.10.2
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
flutter:
plugin:
implements: pointer_interceptor
platforms:
web:
pluginClass: PointerInterceptorWeb
fileName: pointer_interceptor_web.dart
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
plugin_platform_interface: ^2.1.7
pointer_interceptor_platform_interface: ^0.10.0
web: ^0.5.0
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- pointer-interceptor
- web | packages/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml",
"repo_id": "packages",
"token_count": 319
} | 1,026 |
// 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';
/// Decodes a UTF8-encoded byte array into a list of Strings, where each list
/// entry represents a line of text.
List<String> decode(List<int> data) =>
const LineSplitter().convert(utf8.decode(data));
/// Consumes and returns an entire stream of bytes.
Future<List<int>> consume(Stream<List<int>> stream) =>
stream.expand((List<int> data) => data).toList();
| packages/packages/process/test/utils.dart/0 | {
"file_path": "packages/packages/process/test/utils.dart",
"repo_id": "packages",
"token_count": 169
} | 1,027 |
name: quick_actions
description: Flutter plugin for creating shortcuts on home screen, also known as
Quick Actions on iOS and App Shortcuts on Android.
repository: https://github.com/flutter/packages/tree/main/packages/quick_actions/quick_actions
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+quick_actions%22
version: 1.0.7
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
flutter:
plugin:
platforms:
android:
default_package: quick_actions_android
ios:
default_package: quick_actions_ios
dependencies:
flutter:
sdk: flutter
quick_actions_android: ^1.0.0
quick_actions_ios: ^1.0.0
quick_actions_platform_interface: ^1.0.0
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
mockito: 5.4.4
plugin_platform_interface: ^2.1.7
topics:
- quick-actions
- os-integration
| packages/packages/quick_actions/quick_actions/pubspec.yaml/0 | {
"file_path": "packages/packages/quick_actions/quick_actions/pubspec.yaml",
"repo_id": "packages",
"token_count": 360
} | 1,028 |
#include "ephemeral/Flutter-Generated.xcconfig"
| packages/packages/rfw/example/hello/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "packages/packages/rfw/example/hello/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "packages",
"token_count": 19
} | 1,029 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/rfw/example/remote/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "packages/packages/rfw/example/remote/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,030 |
name: rfw
description: "Remote Flutter widgets: a library for rendering declarative widget description files at runtime."
repository: https://github.com/flutter/packages/tree/main/packages/rfw
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+rfw%22
version: 1.0.26
environment:
sdk: ^3.2.0
flutter: ">=3.16.0"
dependencies:
flutter:
sdk: flutter
meta: ^1.7.0
dev_dependencies:
flutter_test:
sdk: flutter
lcov_parser: 0.1.2
topics:
- ui
- widgets
| packages/packages/rfw/pubspec.yaml/0 | {
"file_path": "packages/packages/rfw/pubspec.yaml",
"repo_id": "packages",
"token_count": 216
} | 1,031 |
// 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
package io.flutter.plugins.sharedpreferences;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StandardMessageCodec;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** Generated class from Pigeon. */
@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"})
public class Messages {
/** Error class for passing custom error details to Flutter via a thrown PlatformException. */
public static class FlutterError extends RuntimeException {
/** The error code. */
public final String code;
/** The error details. Must be a datatype supported by the api codec. */
public final Object details;
public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) {
super(message);
this.code = code;
this.details = details;
}
}
@NonNull
protected static ArrayList<Object> wrapError(@NonNull Throwable exception) {
ArrayList<Object> errorList = new ArrayList<Object>(3);
if (exception instanceof FlutterError) {
FlutterError error = (FlutterError) exception;
errorList.add(error.code);
errorList.add(error.getMessage());
errorList.add(error.details);
} else {
errorList.add(exception.toString());
errorList.add(exception.getClass().getSimpleName());
errorList.add(
"Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception));
}
return errorList;
}
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */
public interface SharedPreferencesApi {
/** Removes property from shared preferences data set. */
@NonNull
Boolean remove(@NonNull String key);
/** Adds property to shared preferences data set of type bool. */
@NonNull
Boolean setBool(@NonNull String key, @NonNull Boolean value);
/** Adds property to shared preferences data set of type String. */
@NonNull
Boolean setString(@NonNull String key, @NonNull String value);
/** Adds property to shared preferences data set of type int. */
@NonNull
Boolean setInt(@NonNull String key, @NonNull Long value);
/** Adds property to shared preferences data set of type double. */
@NonNull
Boolean setDouble(@NonNull String key, @NonNull Double value);
/** Adds property to shared preferences data set of type List<String>. */
@NonNull
Boolean setStringList(@NonNull String key, @NonNull List<String> value);
/** Removes all properties from shared preferences data set with matching prefix. */
@NonNull
Boolean clear(@NonNull String prefix, @Nullable List<String> allowList);
/** Gets all properties from shared preferences data set with matching prefix. */
@NonNull
Map<String, Object> getAll(@NonNull String prefix, @Nullable List<String> allowList);
/** The codec used by SharedPreferencesApi. */
static @NonNull MessageCodec<Object> getCodec() {
return new StandardMessageCodec();
}
/**
* Sets up an instance of `SharedPreferencesApi` to handle messages through the
* `binaryMessenger`.
*/
static void setup(
@NonNull BinaryMessenger binaryMessenger, @Nullable SharedPreferencesApi api) {
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.SharedPreferencesApi.remove",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String keyArg = (String) args.get(0);
try {
Boolean output = api.remove(keyArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.SharedPreferencesApi.setBool",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String keyArg = (String) args.get(0);
Boolean valueArg = (Boolean) args.get(1);
try {
Boolean output = api.setBool(keyArg, valueArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.SharedPreferencesApi.setString",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String keyArg = (String) args.get(0);
String valueArg = (String) args.get(1);
try {
Boolean output = api.setString(keyArg, valueArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.SharedPreferencesApi.setInt",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String keyArg = (String) args.get(0);
Number valueArg = (Number) args.get(1);
try {
Boolean output =
api.setInt(keyArg, (valueArg == null) ? null : valueArg.longValue());
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.SharedPreferencesApi.setDouble",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String keyArg = (String) args.get(0);
Double valueArg = (Double) args.get(1);
try {
Boolean output = api.setDouble(keyArg, valueArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.SharedPreferencesApi.setStringList",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String keyArg = (String) args.get(0);
List<String> valueArg = (List<String>) args.get(1);
try {
Boolean output = api.setStringList(keyArg, valueArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.SharedPreferencesApi.clear",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String prefixArg = (String) args.get(0);
List<String> allowListArg = (List<String>) args.get(1);
try {
Boolean output = api.clear(prefixArg, allowListArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger,
"dev.flutter.pigeon.SharedPreferencesApi.getAll",
getCodec(),
taskQueue);
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
ArrayList<Object> args = (ArrayList<Object>) message;
String prefixArg = (String) args.get(0);
List<String> allowListArg = (List<String>) args.get(1);
try {
Map<String, Object> output = api.getAll(prefixArg, allowListArg);
wrapped.add(0, output);
} catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
}
| packages/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/Messages.java/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_android/android/src/main/java/io/flutter/plugins/sharedpreferences/Messages.java",
"repo_id": "packages",
"token_count": 5923
} | 1,032 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:shared_preferences_platform_interface/types.dart';
import 'src/messages.g.dart';
/// The Android implementation of [SharedPreferencesStorePlatform].
///
/// This class implements the `package:shared_preferences` functionality for Android.
class SharedPreferencesAndroid extends SharedPreferencesStorePlatform {
/// Creates a new plugin implementation instance.
SharedPreferencesAndroid({
@visibleForTesting SharedPreferencesApi? api,
}) : _api = api ?? SharedPreferencesApi();
final SharedPreferencesApi _api;
/// Registers this class as the default instance of [SharedPreferencesStorePlatform].
static void registerWith() {
SharedPreferencesStorePlatform.instance = SharedPreferencesAndroid();
}
static const String _defaultPrefix = 'flutter.';
@override
Future<bool> remove(String key) async {
return _api.remove(key);
}
@override
Future<bool> setValue(String valueType, String key, Object value) async {
switch (valueType) {
case 'String':
return _api.setString(key, value as String);
case 'Bool':
return _api.setBool(key, value as bool);
case 'Int':
return _api.setInt(key, value as int);
case 'Double':
return _api.setDouble(key, value as double);
case 'StringList':
return _api.setStringList(key, value as List<String>);
}
// TODO(tarrinneal): change to ArgumentError across all platforms.
throw PlatformException(
code: 'InvalidOperation',
message: '"$valueType" is not a supported type.');
}
@override
Future<bool> clear() async {
return clearWithParameters(
ClearParameters(
filter: PreferencesFilter(prefix: _defaultPrefix),
),
);
}
@override
Future<bool> clearWithPrefix(String prefix) async {
return clearWithParameters(
ClearParameters(filter: PreferencesFilter(prefix: prefix)));
}
@override
Future<bool> clearWithParameters(ClearParameters parameters) async {
final PreferencesFilter filter = parameters.filter;
return _api.clear(
filter.prefix,
filter.allowList?.toList(),
);
}
@override
Future<Map<String, Object>> getAll() async {
return getAllWithParameters(
GetAllParameters(
filter: PreferencesFilter(prefix: _defaultPrefix),
),
);
}
@override
Future<Map<String, Object>> getAllWithPrefix(String prefix) async {
return getAllWithParameters(
GetAllParameters(filter: PreferencesFilter(prefix: prefix)));
}
@override
Future<Map<String, Object>> getAllWithParameters(
GetAllParameters parameters) async {
final PreferencesFilter filter = parameters.filter;
final Map<String?, Object?> data =
await _api.getAll(filter.prefix, filter.allowList?.toList());
return data.cast<String, Object>();
}
}
| packages/packages/shared_preferences/shared_preferences_android/lib/shared_preferences_android.dart/0 | {
"file_path": "packages/packages/shared_preferences/shared_preferences_android/lib/shared_preferences_android.dart",
"repo_id": "packages",
"token_count": 1050
} | 1,033 |
name: two_dimensional_scrollables
description: Widgets that scroll using the two dimensional scrolling foundation.
version: 0.1.2
repository: https://github.com/flutter/packages/tree/main/packages/two_dimensional_scrollables
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+two_dimensional_scrollables%22+
environment:
sdk: '>=3.2.0 <4.0.0'
flutter: ">=3.16.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_lints: ^2.0.0
flutter_test:
sdk: flutter
topics:
- scrollable
- widgets
| packages/packages/two_dimensional_scrollables/pubspec.yaml/0 | {
"file_path": "packages/packages/two_dimensional_scrollables/pubspec.yaml",
"repo_id": "packages",
"token_count": 221
} | 1,034 |
// 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
@testable import url_launcher_ios
// Tests whether NSURL parsing is strict. When linking against the iOS 17 SDK or later,
// NSURL uses a more lenient parser which will not return nil.
private func urlParsingIsStrict() -> Bool {
return URL(string: "b a d U R L") == nil
}
final class URLLauncherTests: XCTestCase {
private func createPlugin() -> URLLauncherPlugin {
let launcher = FakeLauncher()
return URLLauncherPlugin(launcher: launcher)
}
private func createPlugin(launcher: FakeLauncher) -> URLLauncherPlugin {
return URLLauncherPlugin(launcher: launcher)
}
func testCanLaunchSuccess() {
let result = createPlugin().canLaunchUrl(url: "good://url")
XCTAssertEqual(result, .success)
}
func testCanLaunchFailure() {
let result = createPlugin().canLaunchUrl(url: "bad://url")
XCTAssertEqual(result, .failure)
}
func testCanLaunchFailureWithInvalidURL() {
let result = createPlugin().canLaunchUrl(url: "urls can't have spaces")
if urlParsingIsStrict() {
XCTAssertEqual(result, .invalidUrl)
} else {
XCTAssertEqual(result, .failure)
}
}
func testLaunchSuccess() {
let expectation = XCTestExpectation(description: "completion called")
createPlugin().launchUrl(url: "good://url", universalLinksOnly: false) { result in
switch result {
case .success(let details):
XCTAssertEqual(details, .success)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
func testLaunchFailure() {
let expectation = XCTestExpectation(description: "completion called")
createPlugin().launchUrl(url: "bad://url", universalLinksOnly: false) { result in
switch result {
case .success(let details):
XCTAssertEqual(details, .failure)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
func testLaunchFailureWithInvalidURL() {
let expectation = XCTestExpectation(description: "completion called")
createPlugin().launchUrl(url: "urls can't have spaces", universalLinksOnly: false) { result in
switch result {
case .success(let details):
if urlParsingIsStrict() {
XCTAssertEqual(details, .invalidUrl)
} else {
XCTAssertEqual(details, .failure)
}
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
}
func testLaunchWithoutUniversalLinks() {
let launcher = FakeLauncher()
let plugin = createPlugin(launcher: launcher)
let expectation = XCTestExpectation(description: "completion called")
plugin.launchUrl(url: "good://url", universalLinksOnly: false) { result in
switch result {
case .success(let details):
XCTAssertEqual(details, .success)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
XCTAssertEqual(launcher.passedOptions?[.universalLinksOnly] as? Bool, false)
}
func testLaunchWithUniversalLinks() {
let launcher = FakeLauncher()
let plugin = createPlugin(launcher: launcher)
let expectation = XCTestExpectation(description: "completion called")
plugin.launchUrl(url: "good://url", universalLinksOnly: true) { result in
switch result {
case .success(let details):
XCTAssertEqual(details, .success)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
XCTAssertEqual(launcher.passedOptions?[.universalLinksOnly] as? Bool, true)
}
}
final private class FakeLauncher: NSObject, Launcher {
var passedOptions: [UIApplication.OpenExternalURLOptionsKey: Any]?
func canOpenURL(_ url: URL) -> Bool {
url.scheme == "good"
}
func open(
_ url: URL,
options: [UIApplication.OpenExternalURLOptionsKey: Any],
completionHandler completion: ((Bool) -> Void)?
) {
self.passedOptions = options
completion?(url.scheme == "good")
}
}
| packages/packages/url_launcher/url_launcher_ios/example/ios/RunnerTests/URLLauncherTests.swift/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_ios/example/ios/RunnerTests/URLLauncherTests.swift",
"repo_id": "packages",
"token_count": 1647
} | 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.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
swiftOut: 'ios/Classes/messages.g.swift',
copyrightHeader: 'pigeons/copyright.txt',
))
/// Possible outcomes of launching a URL.
enum LaunchResult {
/// The URL was successfully launched (or could be, for `canLaunchUrl`).
success,
/// There was no handler available for the URL.
failure,
/// The URL could not be launched because it is invalid.
invalidUrl,
}
/// Possible outcomes of handling a URL within the application.
enum InAppLoadResult {
/// The URL was successfully loaded.
success,
/// The URL did not load successfully.
failedToLoad,
/// The URL could not be launched because it is invalid.
invalidUrl,
}
@HostApi()
abstract class UrlLauncherApi {
/// Checks whether a URL can be loaded.
@ObjCSelector('canLaunchURL:')
LaunchResult canLaunchUrl(String url);
/// Opens the URL externally, returning the status of launching it.
@async
@ObjCSelector('launchURL:universalLinksOnly:')
LaunchResult launchUrl(String url, bool universalLinksOnly);
/// Opens the URL in an in-app SFSafariViewController, returning the results
/// of loading it.
@async
@ObjCSelector('openSafariViewControllerWithURL:')
InAppLoadResult openUrlInSafariViewController(String url);
/// Closes the view controller opened by [openUrlInSafariViewController].
void closeSafariViewController();
}
| packages/packages/url_launcher/url_launcher_ios/pigeons/messages.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_ios/pigeons/messages.dart",
"repo_id": "packages",
"token_count": 479
} | 1,036 |
// 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:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import 'package:url_launcher_windows/src/messages.g.dart';
import 'package:url_launcher_windows/url_launcher_windows.dart';
void main() {
late _FakeUrlLauncherApi api;
late UrlLauncherWindows plugin;
setUp(() {
api = _FakeUrlLauncherApi();
plugin = UrlLauncherWindows(api: api);
});
test('registers instance', () {
UrlLauncherWindows.registerWith();
expect(UrlLauncherPlatform.instance, isA<UrlLauncherWindows>());
});
group('canLaunch', () {
test('handles true', () async {
api.canLaunch = true;
final bool result = await plugin.canLaunch('http://example.com/');
expect(result, isTrue);
expect(api.argument, 'http://example.com/');
});
test('handles false', () async {
api.canLaunch = false;
final bool result = await plugin.canLaunch('http://example.com/');
expect(result, isFalse);
expect(api.argument, 'http://example.com/');
});
});
group('launch', () {
test('handles success', () async {
api.canLaunch = true;
expect(
await plugin.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
),
true);
expect(api.argument, 'http://example.com/');
});
test('handles failure', () async {
api.canLaunch = false;
expect(
await plugin.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
),
false);
expect(api.argument, 'http://example.com/');
});
test('handles errors', () async {
api.throwError = true;
await expectLater(
plugin.launch(
'http://example.com/',
useSafariVC: true,
useWebView: false,
enableJavaScript: false,
enableDomStorage: false,
universalLinksOnly: false,
headers: const <String, String>{},
),
throwsA(isA<PlatformException>()));
expect(api.argument, 'http://example.com/');
});
});
group('supportsMode', () {
test('returns true for platformDefault', () async {
final UrlLauncherWindows launcher = UrlLauncherWindows(api: api);
expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault),
true);
});
test('returns true for external application', () async {
final UrlLauncherWindows launcher = UrlLauncherWindows(api: api);
expect(
await launcher.supportsMode(PreferredLaunchMode.externalApplication),
true);
});
test('returns false for other modes', () async {
final UrlLauncherWindows launcher = UrlLauncherWindows(api: api);
expect(
await launcher
.supportsMode(PreferredLaunchMode.externalNonBrowserApplication),
false);
expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView),
false);
expect(
await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false);
});
});
test('supportsCloseForMode returns false', () async {
final UrlLauncherWindows launcher = UrlLauncherWindows(api: api);
expect(
await launcher
.supportsCloseForMode(PreferredLaunchMode.platformDefault),
false);
expect(
await launcher
.supportsCloseForMode(PreferredLaunchMode.externalApplication),
false);
});
}
class _FakeUrlLauncherApi implements UrlLauncherApi {
/// The argument that was passed to an API call.
String? argument;
/// Controls the behavior of the fake canLaunch implementations.
///
/// - [canLaunchUrl] returns this value.
/// - [launchUrl] returns this value if [throwError] is false.
bool canLaunch = false;
/// Whether to throw a platform exception.
bool throwError = false;
@override
Future<bool> canLaunchUrl(String url) async {
argument = url;
return canLaunch;
}
@override
Future<bool> launchUrl(String url) async {
argument = url;
if (throwError) {
throw PlatformException(code: 'Failed');
}
return canLaunch;
}
}
| packages/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart/0 | {
"file_path": "packages/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart",
"repo_id": "packages",
"token_count": 1893
} | 1,037 |
group 'io.flutter.plugins.videoplayer'
version '1.0-SNAPSHOT'
def args = ["-Xlint:deprecation","-Xlint:unchecked","-Werror"]
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.2.1'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
project.getTasks().withType(JavaCompile){
options.compilerArgs.addAll(args)
}
apply plugin: 'com.android.library'
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'io.flutter.plugins.videoplayer'
}
compileSdk 34
defaultConfig {
minSdkVersion 16
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dependencies {
def exoplayer_version = "2.18.7"
implementation "com.google.android.exoplayer:exoplayer-core:${exoplayer_version}"
implementation "com.google.android.exoplayer:exoplayer-hls:${exoplayer_version}"
implementation "com.google.android.exoplayer:exoplayer-dash:${exoplayer_version}"
implementation "com.google.android.exoplayer:exoplayer-smoothstreaming:${exoplayer_version}"
testImplementation 'junit:junit:4.13.2'
testImplementation 'androidx.test:core:1.3.0'
testImplementation 'org.mockito:mockito-inline:5.0.0'
testImplementation 'org.robolectric:robolectric:4.10.3'
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
}
| packages/packages/video_player/video_player_android/android/build.gradle/0 | {
"file_path": "packages/packages/video_player/video_player_android/android/build.gradle",
"repo_id": "packages",
"token_count": 918
} | 1,038 |
## NEXT
* Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6.
## 2.5.6
* Adds privacy manifest.
## 2.5.5
* Fixes display of initial frame when paused.
## 2.5.4
* Fixes new lint warnings.
## 2.5.3
* Publishes an instance of the plugin to the registrar on macOS, as on iOS.
## 2.5.2
* Fixes flickering and seek-while-paused on macOS.
## 2.5.1
* Updates to Pigeon 13.
## 2.5.0
* Adds support for macOS.
## 2.4.11
* Updates Pigeon.
* Changes Objective-C class prefixes to avoid future collisions.
## 2.4.10
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 2.4.9
* Fixes the iOS crash when using multiple players on the same screen.
See: https://github.com/flutter/flutter/issues/124937
## 2.4.8
* Fixes missing `isPlaybackLikelyToKeepUp` check for iOS video player `bufferingEnd` event and `bufferingStart` event.
## 2.4.7
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
* Adds iOS exception on incorrect asset path
## 2.4.6
* Fixes hang when seeking to end of video.
## 2.4.5
* Updates functions without a prototype to avoid deprecation warning.
## 2.4.4
* Updates pigeon to fix warnings with clang 15.
## 2.4.3
* Synchronizes `VideoPlayerValue.isPlaying` with `AVPlayer`.
## 2.4.2
* Makes seekTo async and only complete when AVPlayer.seekTo completes.
## 2.4.1
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
## 2.4.0
* Updates minimum Flutter version to 3.3 and iOS 11.
## 2.3.9
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 2.3.8
* Adds compatibilty with version 6.0 of the platform interface.
* Fixes file URI construction in example.
* Updates code for new analysis options.
* Adds an integration test for a bug where the aspect ratios of some HLS videos are incorrectly inverted.
* Removes an unnecessary override in example code.
## 2.3.7
* Fixes a bug where the aspect ratio of some HLS videos are incorrectly inverted.
* Updates code for `no_leading_underscores_for_local_identifiers` lint.
## 2.3.6
* Fixes a bug in iOS 16 where videos from protected live streams are not shown.
* Updates minimum Flutter version to 2.10.
* Fixes violations of new analysis option use_named_constants.
* Fixes avoid_redundant_argument_values lint warnings and minor typos.
* Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316).
## 2.3.5
* Updates references to the obsolete master branch.
## 2.3.4
* Removes unnecessary imports.
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 2.3.3
* Fix XCUITest based on the new voice over announcement for tooltips.
See: https://github.com/flutter/flutter/pull/87684
## 2.3.2
* Applies the standardized transform for videos with different orientations.
## 2.3.1
* Renames internal method channels to avoid potential confusion with the
default implementation's method channel.
* Updates Pigeon to 2.0.1.
## 2.3.0
* Updates Pigeon to ^1.0.16.
## 2.2.18
* Wait to initialize m3u8 videos until size is set, fixing aspect ratio.
* Adjusts test timeouts for network-dependent native tests to avoid flake.
## 2.2.17
* Splits from `video_player` as a federated implementation.
| packages/packages/video_player/video_player_avfoundation/CHANGELOG.md/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1086
} | 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 AVFoundation;
@import video_player_avfoundation;
@import XCTest;
#import <OCMock/OCMock.h>
#import <video_player_avfoundation/AVAssetTrackUtils.h>
#import <video_player_avfoundation/FVPVideoPlayerPlugin_Test.h>
// TODO(stuartmorgan): Convert to using mock registrars instead.
NSObject<FlutterPluginRegistry> *GetPluginRegistry(void) {
#if TARGET_OS_IOS
return (NSObject<FlutterPluginRegistry> *)[[UIApplication sharedApplication] delegate];
#else
return (FlutterViewController *)NSApplication.sharedApplication.windows[0].contentViewController;
#endif
}
#if TARGET_OS_IOS
@interface FakeAVAssetTrack : AVAssetTrack
@property(readonly, nonatomic) CGAffineTransform preferredTransform;
@property(readonly, nonatomic) CGSize naturalSize;
@property(readonly, nonatomic) UIImageOrientation orientation;
- (instancetype)initWithOrientation:(UIImageOrientation)orientation;
@end
@implementation FakeAVAssetTrack
- (instancetype)initWithOrientation:(UIImageOrientation)orientation {
_orientation = orientation;
_naturalSize = CGSizeMake(800, 600);
return self;
}
- (CGAffineTransform)preferredTransform {
switch (_orientation) {
case UIImageOrientationUp:
return CGAffineTransformMake(1, 0, 0, 1, 0, 0);
case UIImageOrientationDown:
return CGAffineTransformMake(-1, 0, 0, -1, 0, 0);
case UIImageOrientationLeft:
return CGAffineTransformMake(0, -1, 1, 0, 0, 0);
case UIImageOrientationRight:
return CGAffineTransformMake(0, 1, -1, 0, 0, 0);
case UIImageOrientationUpMirrored:
return CGAffineTransformMake(-1, 0, 0, 1, 0, 0);
case UIImageOrientationDownMirrored:
return CGAffineTransformMake(1, 0, 0, -1, 0, 0);
case UIImageOrientationLeftMirrored:
return CGAffineTransformMake(0, -1, -1, 0, 0, 0);
case UIImageOrientationRightMirrored:
return CGAffineTransformMake(0, 1, 1, 0, 0, 0);
}
}
@end
#endif
@interface VideoPlayerTests : XCTestCase
@end
@interface StubAVPlayer : AVPlayer
@property(readonly, nonatomic) NSNumber *beforeTolerance;
@property(readonly, nonatomic) NSNumber *afterTolerance;
@property(readonly, assign) CMTime lastSeekTime;
@end
@implementation StubAVPlayer
- (void)seekToTime:(CMTime)time
toleranceBefore:(CMTime)toleranceBefore
toleranceAfter:(CMTime)toleranceAfter
completionHandler:(void (^)(BOOL finished))completionHandler {
_beforeTolerance = [NSNumber numberWithLong:toleranceBefore.value];
_afterTolerance = [NSNumber numberWithLong:toleranceAfter.value];
_lastSeekTime = time;
[super seekToTime:time
toleranceBefore:toleranceBefore
toleranceAfter:toleranceAfter
completionHandler:completionHandler];
}
@end
@interface StubFVPAVFactory : NSObject <FVPAVFactory>
@property(nonatomic, strong) StubAVPlayer *stubAVPlayer;
@property(nonatomic, strong) AVPlayerItemVideoOutput *output;
- (instancetype)initWithPlayer:(StubAVPlayer *)stubAVPlayer
output:(AVPlayerItemVideoOutput *)output;
@end
@implementation StubFVPAVFactory
// Creates a factory that returns the given items. Any items that are nil will instead return
// a real object just as the non-test implementation would.
- (instancetype)initWithPlayer:(StubAVPlayer *)stubAVPlayer
output:(AVPlayerItemVideoOutput *)output {
self = [super init];
_stubAVPlayer = stubAVPlayer;
_output = output;
return self;
}
- (AVPlayer *)playerWithPlayerItem:(AVPlayerItem *)playerItem {
return _stubAVPlayer ?: [AVPlayer playerWithPlayerItem:playerItem];
}
- (AVPlayerItemVideoOutput *)videoOutputWithPixelBufferAttributes:
(NSDictionary<NSString *, id> *)attributes {
return _output ?: [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:attributes];
}
@end
#pragma mark -
/** Test implementation of FVPDisplayLinkFactory that returns a provided display link nstance. */
@interface StubFVPDisplayLinkFactory : NSObject <FVPDisplayLinkFactory>
/** This display link to return. */
@property(nonatomic, strong) FVPDisplayLink *displayLink;
- (instancetype)initWithDisplayLink:(FVPDisplayLink *)displayLink;
@end
@implementation StubFVPDisplayLinkFactory
- (instancetype)initWithDisplayLink:(FVPDisplayLink *)displayLink {
self = [super init];
_displayLink = displayLink;
return self;
}
- (FVPDisplayLink *)displayLinkWithRegistrar:(id<FlutterPluginRegistrar>)registrar
callback:(void (^)(void))callback {
return self.displayLink;
}
@end
/** Non-test implementation of the diplay link factory. */
@interface FVPDefaultDisplayLinkFactory : NSObject <FVPDisplayLinkFactory>
@end
@implementation FVPDefaultDisplayLinkFactory
- (FVPDisplayLink *)displayLinkWithRegistrar:(id<FlutterPluginRegistrar>)registrar
callback:(void (^)(void))callback {
return [[FVPDisplayLink alloc] initWithRegistrar:registrar callback:callback];
}
@end
#pragma mark -
@implementation VideoPlayerTests
- (void)testBlankVideoBugWithEncryptedVideoStreamAndInvertedAspectRatioBugForSomeVideoStream {
// This is to fix 2 bugs: 1. blank video for encrypted video streams on iOS 16
// (https://github.com/flutter/flutter/issues/111457) and 2. swapped width and height for some
// video streams (not just iOS 16). (https://github.com/flutter/flutter/issues/109116). An
// invisible AVPlayerLayer is used to overwrite the protection of pixel buffers in those streams
// for issue #1, and restore the correct width and height for issue #2.
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"testPlayerLayerWorkaround"];
FVPVideoPlayerPlugin *videoPlayerPlugin =
[[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
FlutterError *error;
[videoPlayerPlugin initialize:&error];
XCTAssertNil(error);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error];
XCTAssertNil(error);
XCTAssertNotNil(textureMessage);
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureMessage.textureId)];
XCTAssertNotNil(player);
XCTAssertNotNil(player.playerLayer, @"AVPlayerLayer should be present.");
XCTAssertNotNil(player.playerLayer.superlayer, @"AVPlayerLayer should be added on screen.");
}
- (void)testSeekToWhilePausedStartsDisplayLinkTemporarily {
NSObject<FlutterTextureRegistry> *mockTextureRegistry =
OCMProtocolMock(@protocol(FlutterTextureRegistry));
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"SeekToWhilePausedStartsDisplayLinkTemporarily"];
NSObject<FlutterPluginRegistrar> *partialRegistrar = OCMPartialMock(registrar);
OCMStub([partialRegistrar textures]).andReturn(mockTextureRegistry);
FVPDisplayLink *mockDisplayLink =
OCMPartialMock([[FVPDisplayLink alloc] initWithRegistrar:registrar
callback:^(){
}]);
StubFVPDisplayLinkFactory *stubDisplayLinkFactory =
[[StubFVPDisplayLinkFactory alloc] initWithDisplayLink:mockDisplayLink];
AVPlayerItemVideoOutput *mockVideoOutput = OCMPartialMock([[AVPlayerItemVideoOutput alloc] init]);
FVPVideoPlayerPlugin *videoPlayerPlugin = [[FVPVideoPlayerPlugin alloc]
initWithAVFactory:[[StubFVPAVFactory alloc] initWithPlayer:nil output:mockVideoOutput]
displayLinkFactory:stubDisplayLinkFactory
registrar:partialRegistrar];
FlutterError *initalizationError;
[videoPlayerPlugin initialize:&initalizationError];
XCTAssertNil(initalizationError);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FlutterError *createError;
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&createError];
NSInteger textureId = textureMessage.textureId;
// Ensure that the video playback is paused before seeking.
FlutterError *pauseError;
[videoPlayerPlugin pause:textureMessage error:&pauseError];
XCTestExpectation *initializedExpectation = [self expectationWithDescription:@"seekTo completes"];
FVPPositionMessage *message = [FVPPositionMessage makeWithTextureId:textureId position:1234];
[videoPlayerPlugin seekTo:message
completion:^(FlutterError *_Nullable error) {
[initializedExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:30.0 handler:nil];
// Seeking to a new position should start the display link temporarily.
OCMVerify([mockDisplayLink setRunning:YES]);
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureId)];
XCTAssertEqual([player position], 1234);
// Simulate a buffer being available.
OCMStub([mockVideoOutput hasNewPixelBufferForItemTime:kCMTimeZero])
.ignoringNonObjectArgs()
.andReturn(YES);
// Any non-zero value is fine here since it won't actually be used, just NULL-checked.
CVPixelBufferRef fakeBufferRef = (CVPixelBufferRef)1;
OCMStub([mockVideoOutput copyPixelBufferForItemTime:kCMTimeZero itemTimeForDisplay:NULL])
.ignoringNonObjectArgs()
.andReturn(fakeBufferRef);
// Simulate a callback from the engine to request a new frame.
[player copyPixelBuffer];
// Since a frame was found, and the video is paused, the display link should be paused again.
OCMVerify([mockDisplayLink setRunning:NO]);
}
- (void)testInitStartsDisplayLinkTemporarily {
NSObject<FlutterTextureRegistry> *mockTextureRegistry =
OCMProtocolMock(@protocol(FlutterTextureRegistry));
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"InitStartsDisplayLinkTemporarily"];
NSObject<FlutterPluginRegistrar> *partialRegistrar = OCMPartialMock(registrar);
OCMStub([partialRegistrar textures]).andReturn(mockTextureRegistry);
FVPDisplayLink *mockDisplayLink =
OCMPartialMock([[FVPDisplayLink alloc] initWithRegistrar:registrar
callback:^(){
}]);
StubFVPDisplayLinkFactory *stubDisplayLinkFactory =
[[StubFVPDisplayLinkFactory alloc] initWithDisplayLink:mockDisplayLink];
AVPlayerItemVideoOutput *mockVideoOutput = OCMPartialMock([[AVPlayerItemVideoOutput alloc] init]);
StubAVPlayer *stubAVPlayer = [[StubAVPlayer alloc] init];
FVPVideoPlayerPlugin *videoPlayerPlugin = [[FVPVideoPlayerPlugin alloc]
initWithAVFactory:[[StubFVPAVFactory alloc] initWithPlayer:stubAVPlayer
output:mockVideoOutput]
displayLinkFactory:stubDisplayLinkFactory
registrar:partialRegistrar];
FlutterError *initalizationError;
[videoPlayerPlugin initialize:&initalizationError];
XCTAssertNil(initalizationError);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FlutterError *createError;
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&createError];
NSInteger textureId = textureMessage.textureId;
// Init should start the display link temporarily.
OCMVerify([mockDisplayLink setRunning:YES]);
// Simulate a buffer being available.
OCMStub([mockVideoOutput hasNewPixelBufferForItemTime:kCMTimeZero])
.ignoringNonObjectArgs()
.andReturn(YES);
// Any non-zero value is fine here since it won't actually be used, just NULL-checked.
CVPixelBufferRef fakeBufferRef = (CVPixelBufferRef)1;
OCMStub([mockVideoOutput copyPixelBufferForItemTime:kCMTimeZero itemTimeForDisplay:NULL])
.ignoringNonObjectArgs()
.andReturn(fakeBufferRef);
// Simulate a callback from the engine to request a new frame.
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureId)];
[player copyPixelBuffer];
// Since a frame was found, and the video is paused, the display link should be paused again.
OCMVerify([mockDisplayLink setRunning:NO]);
}
- (void)testSeekToWhilePlayingDoesNotStopDisplayLink {
NSObject<FlutterTextureRegistry> *mockTextureRegistry =
OCMProtocolMock(@protocol(FlutterTextureRegistry));
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"SeekToWhilePlayingDoesNotStopDisplayLink"];
NSObject<FlutterPluginRegistrar> *partialRegistrar = OCMPartialMock(registrar);
OCMStub([partialRegistrar textures]).andReturn(mockTextureRegistry);
FVPDisplayLink *mockDisplayLink =
OCMPartialMock([[FVPDisplayLink alloc] initWithRegistrar:registrar
callback:^(){
}]);
StubFVPDisplayLinkFactory *stubDisplayLinkFactory =
[[StubFVPDisplayLinkFactory alloc] initWithDisplayLink:mockDisplayLink];
AVPlayerItemVideoOutput *mockVideoOutput = OCMPartialMock([[AVPlayerItemVideoOutput alloc] init]);
FVPVideoPlayerPlugin *videoPlayerPlugin = [[FVPVideoPlayerPlugin alloc]
initWithAVFactory:[[StubFVPAVFactory alloc] initWithPlayer:nil output:mockVideoOutput]
displayLinkFactory:stubDisplayLinkFactory
registrar:partialRegistrar];
FlutterError *initalizationError;
[videoPlayerPlugin initialize:&initalizationError];
XCTAssertNil(initalizationError);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FlutterError *createError;
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&createError];
NSInteger textureId = textureMessage.textureId;
// Ensure that the video is playing before seeking.
FlutterError *playError;
[videoPlayerPlugin play:textureMessage error:&playError];
XCTestExpectation *initializedExpectation = [self expectationWithDescription:@"seekTo completes"];
FVPPositionMessage *message = [FVPPositionMessage makeWithTextureId:textureId position:1234];
[videoPlayerPlugin seekTo:message
completion:^(FlutterError *_Nullable error) {
[initializedExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:30.0 handler:nil];
OCMVerify([mockDisplayLink setRunning:YES]);
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureId)];
XCTAssertEqual([player position], 1234);
// Simulate a buffer being available.
OCMStub([mockVideoOutput hasNewPixelBufferForItemTime:kCMTimeZero])
.ignoringNonObjectArgs()
.andReturn(YES);
// Any non-zero value is fine here since it won't actually be used, just NULL-checked.
CVPixelBufferRef fakeBufferRef = (CVPixelBufferRef)1;
OCMStub([mockVideoOutput copyPixelBufferForItemTime:kCMTimeZero itemTimeForDisplay:NULL])
.ignoringNonObjectArgs()
.andReturn(fakeBufferRef);
// Simulate a callback from the engine to request a new frame.
[player copyPixelBuffer];
// Since the video was playing, the display link should not be paused after getting a buffer.
OCMVerify(never(), [mockDisplayLink setRunning:NO]);
}
- (void)testPauseWhileWaitingForFrameDoesNotStopDisplayLink {
NSObject<FlutterTextureRegistry> *mockTextureRegistry =
OCMProtocolMock(@protocol(FlutterTextureRegistry));
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"PauseWhileWaitingForFrameDoesNotStopDisplayLink"];
NSObject<FlutterPluginRegistrar> *partialRegistrar = OCMPartialMock(registrar);
OCMStub([partialRegistrar textures]).andReturn(mockTextureRegistry);
FVPDisplayLink *mockDisplayLink =
OCMPartialMock([[FVPDisplayLink alloc] initWithRegistrar:registrar
callback:^(){
}]);
StubFVPDisplayLinkFactory *stubDisplayLinkFactory =
[[StubFVPDisplayLinkFactory alloc] initWithDisplayLink:mockDisplayLink];
AVPlayerItemVideoOutput *mockVideoOutput = OCMPartialMock([[AVPlayerItemVideoOutput alloc] init]);
FVPVideoPlayerPlugin *videoPlayerPlugin = [[FVPVideoPlayerPlugin alloc]
initWithAVFactory:[[StubFVPAVFactory alloc] initWithPlayer:nil output:mockVideoOutput]
displayLinkFactory:stubDisplayLinkFactory
registrar:partialRegistrar];
FlutterError *initalizationError;
[videoPlayerPlugin initialize:&initalizationError];
XCTAssertNil(initalizationError);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FlutterError *createError;
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&createError];
// Run a play/pause cycle to force the pause codepath to run completely.
FlutterError *playPauseError;
[videoPlayerPlugin play:textureMessage error:&playPauseError];
[videoPlayerPlugin pause:textureMessage error:&playPauseError];
// Since a buffer hasn't been available yet, the pause should not have stopped the display link.
OCMVerify(never(), [mockDisplayLink setRunning:NO]);
}
- (void)testDeregistersFromPlayer {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"testDeregistersFromPlayer"];
FVPVideoPlayerPlugin *videoPlayerPlugin =
(FVPVideoPlayerPlugin *)[[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
FlutterError *error;
[videoPlayerPlugin initialize:&error];
XCTAssertNil(error);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error];
XCTAssertNil(error);
XCTAssertNotNil(textureMessage);
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureMessage.textureId)];
XCTAssertNotNil(player);
AVPlayer *avPlayer = player.player;
[videoPlayerPlugin dispose:textureMessage error:&error];
XCTAssertEqual(videoPlayerPlugin.playersByTextureId.count, 0);
XCTAssertNil(error);
[self keyValueObservingExpectationForObject:avPlayer keyPath:@"currentItem" expectedValue:nil];
[self waitForExpectationsWithTimeout:30.0 handler:nil];
}
- (void)testBufferingStateFromPlayer {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"testLiveStreamBufferEndFromPlayer"];
FVPVideoPlayerPlugin *videoPlayerPlugin =
(FVPVideoPlayerPlugin *)[[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
FlutterError *error;
[videoPlayerPlugin initialize:&error];
XCTAssertNil(error);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error];
XCTAssertNil(error);
XCTAssertNotNil(textureMessage);
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureMessage.textureId)];
XCTAssertNotNil(player);
AVPlayer *avPlayer = player.player;
[avPlayer play];
[player onListenWithArguments:nil
eventSink:^(NSDictionary<NSString *, id> *event) {
if ([event[@"event"] isEqualToString:@"bufferingEnd"]) {
XCTAssertTrue(avPlayer.currentItem.isPlaybackLikelyToKeepUp);
}
if ([event[@"event"] isEqualToString:@"bufferingStart"]) {
XCTAssertFalse(avPlayer.currentItem.isPlaybackLikelyToKeepUp);
}
}];
XCTestExpectation *bufferingStateExpectation =
[self expectationWithDescription:@"bufferingState"];
NSTimeInterval timeout = 10;
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC);
dispatch_after(delay, dispatch_get_main_queue(), ^{
[bufferingStateExpectation fulfill];
});
[self waitForExpectationsWithTimeout:timeout + 1 handler:nil];
}
- (void)testVideoControls {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"TestVideoControls"];
FVPVideoPlayerPlugin *videoPlayerPlugin =
(FVPVideoPlayerPlugin *)[[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
NSDictionary<NSString *, id> *videoInitialization =
[self testPlugin:videoPlayerPlugin
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"];
XCTAssertEqualObjects(videoInitialization[@"height"], @720);
XCTAssertEqualObjects(videoInitialization[@"width"], @1280);
XCTAssertEqualWithAccuracy([videoInitialization[@"duration"] intValue], 4000, 200);
}
- (void)testAudioControls {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"TestAudioControls"];
FVPVideoPlayerPlugin *videoPlayerPlugin =
(FVPVideoPlayerPlugin *)[[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
NSDictionary<NSString *, id> *audioInitialization =
[self testPlugin:videoPlayerPlugin
uri:@"https://flutter.github.io/assets-for-api-docs/assets/audio/rooster.mp3"];
XCTAssertEqualObjects(audioInitialization[@"height"], @0);
XCTAssertEqualObjects(audioInitialization[@"width"], @0);
// Perfect precision not guaranteed.
XCTAssertEqualWithAccuracy([audioInitialization[@"duration"] intValue], 5400, 200);
}
- (void)testHLSControls {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"TestHLSControls"];
FVPVideoPlayerPlugin *videoPlayerPlugin =
(FVPVideoPlayerPlugin *)[[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
NSDictionary<NSString *, id> *videoInitialization =
[self testPlugin:videoPlayerPlugin
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8"];
XCTAssertEqualObjects(videoInitialization[@"height"], @720);
XCTAssertEqualObjects(videoInitialization[@"width"], @1280);
XCTAssertEqualWithAccuracy([videoInitialization[@"duration"] intValue], 4000, 200);
}
#if TARGET_OS_IOS
- (void)testTransformFix {
[self validateTransformFixForOrientation:UIImageOrientationUp];
[self validateTransformFixForOrientation:UIImageOrientationDown];
[self validateTransformFixForOrientation:UIImageOrientationLeft];
[self validateTransformFixForOrientation:UIImageOrientationRight];
[self validateTransformFixForOrientation:UIImageOrientationUpMirrored];
[self validateTransformFixForOrientation:UIImageOrientationDownMirrored];
[self validateTransformFixForOrientation:UIImageOrientationLeftMirrored];
[self validateTransformFixForOrientation:UIImageOrientationRightMirrored];
}
#endif
- (void)testSeekToleranceWhenNotSeekingToEnd {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"TestSeekTolerance"];
StubAVPlayer *stubAVPlayer = [[StubAVPlayer alloc] init];
StubFVPAVFactory *stubAVFactory = [[StubFVPAVFactory alloc] initWithPlayer:stubAVPlayer
output:nil];
FVPVideoPlayerPlugin *pluginWithMockAVPlayer =
[[FVPVideoPlayerPlugin alloc] initWithAVFactory:stubAVFactory
displayLinkFactory:nil
registrar:registrar];
FlutterError *initializationError;
[pluginWithMockAVPlayer initialize:&initializationError];
XCTAssertNil(initializationError);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FlutterError *createError;
FVPTextureMessage *textureMessage = [pluginWithMockAVPlayer create:create error:&createError];
NSInteger textureId = textureMessage.textureId;
XCTestExpectation *initializedExpectation =
[self expectationWithDescription:@"seekTo has zero tolerance when seeking not to end"];
FVPPositionMessage *message = [FVPPositionMessage makeWithTextureId:textureId position:1234];
[pluginWithMockAVPlayer seekTo:message
completion:^(FlutterError *_Nullable error) {
[initializedExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:30.0 handler:nil];
XCTAssertEqual([stubAVPlayer.beforeTolerance intValue], 0);
XCTAssertEqual([stubAVPlayer.afterTolerance intValue], 0);
}
- (void)testSeekToleranceWhenSeekingToEnd {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"TestSeekToEndTolerance"];
StubAVPlayer *stubAVPlayer = [[StubAVPlayer alloc] init];
StubFVPAVFactory *stubAVFactory = [[StubFVPAVFactory alloc] initWithPlayer:stubAVPlayer
output:nil];
FVPVideoPlayerPlugin *pluginWithMockAVPlayer =
[[FVPVideoPlayerPlugin alloc] initWithAVFactory:stubAVFactory
displayLinkFactory:nil
registrar:registrar];
FlutterError *initializationError;
[pluginWithMockAVPlayer initialize:&initializationError];
XCTAssertNil(initializationError);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FlutterError *createError;
FVPTextureMessage *textureMessage = [pluginWithMockAVPlayer create:create error:&createError];
NSInteger textureId = textureMessage.textureId;
XCTestExpectation *initializedExpectation =
[self expectationWithDescription:@"seekTo has non-zero tolerance when seeking to end"];
// The duration of this video is "0" due to the non standard initiliatazion process.
FVPPositionMessage *message = [FVPPositionMessage makeWithTextureId:textureId position:0];
[pluginWithMockAVPlayer seekTo:message
completion:^(FlutterError *_Nullable error) {
[initializedExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:30.0 handler:nil];
XCTAssertGreaterThan([stubAVPlayer.beforeTolerance intValue], 0);
XCTAssertGreaterThan([stubAVPlayer.afterTolerance intValue], 0);
}
- (NSDictionary<NSString *, id> *)testPlugin:(FVPVideoPlayerPlugin *)videoPlayerPlugin
uri:(NSString *)uri {
FlutterError *error;
[videoPlayerPlugin initialize:&error];
XCTAssertNil(error);
FVPCreateMessage *create = [FVPCreateMessage makeWithAsset:nil
uri:uri
packageName:nil
formatHint:nil
httpHeaders:@{}];
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error];
NSInteger textureId = textureMessage.textureId;
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureId)];
XCTAssertNotNil(player);
XCTestExpectation *initializedExpectation = [self expectationWithDescription:@"initialized"];
__block NSDictionary<NSString *, id> *initializationEvent;
[player onListenWithArguments:nil
eventSink:^(NSDictionary<NSString *, id> *event) {
if ([event[@"event"] isEqualToString:@"initialized"]) {
initializationEvent = event;
XCTAssertEqual(event.count, 4);
[initializedExpectation fulfill];
}
}];
[self waitForExpectationsWithTimeout:30.0 handler:nil];
// Starts paused.
AVPlayer *avPlayer = player.player;
XCTAssertEqual(avPlayer.rate, 0);
XCTAssertEqual(avPlayer.volume, 1);
XCTAssertEqual(avPlayer.timeControlStatus, AVPlayerTimeControlStatusPaused);
// Change playback speed.
FVPPlaybackSpeedMessage *playback = [FVPPlaybackSpeedMessage makeWithTextureId:textureId speed:2];
[videoPlayerPlugin setPlaybackSpeed:playback error:&error];
XCTAssertNil(error);
XCTAssertEqual(avPlayer.rate, 2);
XCTAssertEqual(avPlayer.timeControlStatus, AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate);
// Volume
FVPVolumeMessage *volume = [FVPVolumeMessage makeWithTextureId:textureId volume:0.1];
[videoPlayerPlugin setVolume:volume error:&error];
XCTAssertNil(error);
XCTAssertEqual(avPlayer.volume, 0.1f);
[player onCancelWithArguments:nil];
return initializationEvent;
}
// Checks whether [AVPlayer rate] KVO observations are correctly detached.
// - https://github.com/flutter/flutter/issues/124937
//
// Failing to de-register results in a crash in [AVPlayer willChangeValueForKey:].
- (void)testDoesNotCrashOnRateObservationAfterDisposal {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"testDoesNotCrashOnRateObservationAfterDisposal"];
AVPlayer *avPlayer = nil;
__weak FVPVideoPlayer *weakPlayer = nil;
// Autoreleasepool is needed to simulate conditions of FVPVideoPlayer deallocation.
@autoreleasepool {
FVPVideoPlayerPlugin *videoPlayerPlugin =
(FVPVideoPlayerPlugin *)[[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
FlutterError *error;
[videoPlayerPlugin initialize:&error];
XCTAssertNil(error);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error];
XCTAssertNil(error);
XCTAssertNotNil(textureMessage);
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureMessage.textureId)];
XCTAssertNotNil(player);
weakPlayer = player;
avPlayer = player.player;
[videoPlayerPlugin dispose:textureMessage error:&error];
XCTAssertNil(error);
}
// [FVPVideoPlayerPlugin dispose:error:] selector is dispatching the [FVPVideoPlayer dispose] call
// with a 1-second delay keeping a strong reference to the player. The polling ensures the player
// was truly deallocated.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak"
[self expectationForPredicate:[NSPredicate predicateWithFormat:@"self != nil"]
evaluatedWithObject:weakPlayer
handler:nil];
#pragma clang diagnostic pop
[self waitForExpectationsWithTimeout:10.0 handler:nil];
[avPlayer willChangeValueForKey:@"rate"]; // No assertions needed. Lack of crash is a success.
}
// During the hot reload:
// 1. `[FVPVideoPlayer onTextureUnregistered:]` gets called.
// 2. `[FVPVideoPlayerPlugin initialize:]` gets called.
//
// Both of these methods dispatch [FVPVideoPlayer dispose] on the main thread
// leading to a possible crash when de-registering observers twice.
- (void)testHotReloadDoesNotCrash {
NSObject<FlutterPluginRegistrar> *registrar =
[GetPluginRegistry() registrarForPlugin:@"testHotReloadDoesNotCrash"];
__weak FVPVideoPlayer *weakPlayer = nil;
// Autoreleasepool is needed to simulate conditions of FVPVideoPlayer deallocation.
@autoreleasepool {
FVPVideoPlayerPlugin *videoPlayerPlugin =
(FVPVideoPlayerPlugin *)[[FVPVideoPlayerPlugin alloc] initWithRegistrar:registrar];
FlutterError *error;
[videoPlayerPlugin initialize:&error];
XCTAssertNil(error);
FVPCreateMessage *create = [FVPCreateMessage
makeWithAsset:nil
uri:@"https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4"
packageName:nil
formatHint:nil
httpHeaders:@{}];
FVPTextureMessage *textureMessage = [videoPlayerPlugin create:create error:&error];
XCTAssertNil(error);
XCTAssertNotNil(textureMessage);
FVPVideoPlayer *player = videoPlayerPlugin.playersByTextureId[@(textureMessage.textureId)];
XCTAssertNotNil(player);
weakPlayer = player;
[player onTextureUnregistered:nil];
XCTAssertNil(error);
[videoPlayerPlugin initialize:&error];
XCTAssertNil(error);
}
// [FVPVideoPlayerPlugin dispose:error:] selector is dispatching the [FVPVideoPlayer dispose] call
// with a 1-second delay keeping a strong reference to the player. The polling ensures the player
// was truly deallocated.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak"
[self expectationForPredicate:[NSPredicate predicateWithFormat:@"self != nil"]
evaluatedWithObject:weakPlayer
handler:nil];
#pragma clang diagnostic pop
[self waitForExpectationsWithTimeout:10.0
handler:nil]; // No assertions needed. Lack of crash is a success.
}
- (void)testPublishesInRegistration {
NSString *pluginKey = @"TestRegistration";
NSObject<FlutterPluginRegistry> *registry = GetPluginRegistry();
NSObject<FlutterPluginRegistrar> *registrar = [registry registrarForPlugin:pluginKey];
[FVPVideoPlayerPlugin registerWithRegistrar:registrar];
id publishedValue = [registry valuePublishedByPlugin:pluginKey];
XCTAssertNotNil(publishedValue);
XCTAssertTrue([publishedValue isKindOfClass:[FVPVideoPlayerPlugin class]]);
}
#if TARGET_OS_IOS
- (void)validateTransformFixForOrientation:(UIImageOrientation)orientation {
AVAssetTrack *track = [[FakeAVAssetTrack alloc] initWithOrientation:orientation];
CGAffineTransform t = FVPGetStandardizedTransformForTrack(track);
CGSize size = track.naturalSize;
CGFloat expectX, expectY;
switch (orientation) {
case UIImageOrientationUp:
expectX = 0;
expectY = 0;
break;
case UIImageOrientationDown:
expectX = size.width;
expectY = size.height;
break;
case UIImageOrientationLeft:
expectX = 0;
expectY = size.width;
break;
case UIImageOrientationRight:
expectX = size.height;
expectY = 0;
break;
case UIImageOrientationUpMirrored:
expectX = size.width;
expectY = 0;
break;
case UIImageOrientationDownMirrored:
expectX = 0;
expectY = size.height;
break;
case UIImageOrientationLeftMirrored:
expectX = size.height;
expectY = size.width;
break;
case UIImageOrientationRightMirrored:
expectX = 0;
expectY = 0;
break;
}
XCTAssertEqual(t.tx, expectX);
XCTAssertEqual(t.ty, expectY);
}
#endif
@end
| packages/packages/video_player/video_player_avfoundation/darwin/RunnerTests/VideoPlayerTests.m/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/darwin/RunnerTests/VideoPlayerTests.m",
"repo_id": "packages",
"token_count": 13469
} | 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.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartTestOut: 'test/test_api.g.dart',
objcHeaderOut: 'darwin/Classes/messages.g.h',
objcSourceOut: 'darwin/Classes/messages.g.m',
objcOptions: ObjcOptions(
prefix: 'FVP',
),
copyrightHeader: 'pigeons/copyright.txt',
))
class TextureMessage {
TextureMessage(this.textureId);
int textureId;
}
class LoopingMessage {
LoopingMessage(this.textureId, this.isLooping);
int textureId;
bool isLooping;
}
class VolumeMessage {
VolumeMessage(this.textureId, this.volume);
int textureId;
double volume;
}
class PlaybackSpeedMessage {
PlaybackSpeedMessage(this.textureId, this.speed);
int textureId;
double speed;
}
class PositionMessage {
PositionMessage(this.textureId, this.position);
int textureId;
int position;
}
class CreateMessage {
CreateMessage({required this.httpHeaders});
String? asset;
String? uri;
String? packageName;
String? formatHint;
Map<String?, String?> httpHeaders;
}
class MixWithOthersMessage {
MixWithOthersMessage(this.mixWithOthers);
bool mixWithOthers;
}
@HostApi(dartHostTestHandler: 'TestHostVideoPlayerApi')
abstract class AVFoundationVideoPlayerApi {
@ObjCSelector('initialize')
void initialize();
@ObjCSelector('create:')
TextureMessage create(CreateMessage msg);
@ObjCSelector('dispose:')
void dispose(TextureMessage msg);
@ObjCSelector('setLooping:')
void setLooping(LoopingMessage msg);
@ObjCSelector('setVolume:')
void setVolume(VolumeMessage msg);
@ObjCSelector('setPlaybackSpeed:')
void setPlaybackSpeed(PlaybackSpeedMessage msg);
@ObjCSelector('play:')
void play(TextureMessage msg);
@ObjCSelector('position:')
PositionMessage position(TextureMessage msg);
@async
@ObjCSelector('seekTo:')
void seekTo(PositionMessage msg);
@ObjCSelector('pause:')
void pause(TextureMessage msg);
@ObjCSelector('setMixWithOthers:')
void setMixWithOthers(MixWithOthersMessage msg);
}
| packages/packages/video_player/video_player_avfoundation/pigeons/messages.dart/0 | {
"file_path": "packages/packages/video_player/video_player_avfoundation/pigeons/messages.dart",
"repo_id": "packages",
"token_count": 730
} | 1,041 |
name: video_player_web
description: Web platform implementation of video_player.
repository: https://github.com/flutter/packages/tree/main/packages/video_player/video_player_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22
version: 2.3.0
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
flutter:
plugin:
implements: video_player
platforms:
web:
pluginClass: VideoPlayerPlugin
fileName: video_player_web.dart
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
video_player_platform_interface: ^6.2.0
web: ^0.5.1
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- video
- video-player
| packages/packages/video_player/video_player_web/pubspec.yaml/0 | {
"file_path": "packages/packages/video_player/video_player_web/pubspec.yaml",
"repo_id": "packages",
"token_count": 303
} | 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.
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:convert' show json;
import 'dart:io' as io;
import 'package:logging/logging.dart';
import 'package:path/path.dart' as path;
import 'package:process/process.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_static/shelf_static.dart';
import 'benchmark_result.dart';
import 'browser.dart';
import 'common.dart';
import 'compilation_options.dart';
/// The default port number used by the local benchmark server.
const int defaultBenchmarkServerPort = 9999;
/// The default port number used for Chrome DevTool Protocol.
const int defaultChromeDebugPort = 10000;
/// Builds and serves a Flutter Web app, collects raw benchmark data and
/// summarizes the result as a [BenchmarkResult].
class BenchmarkServer {
/// Creates a benchmark server.
///
/// [benchmarkAppDirectory] is the directory containing the app that's being
/// benchmarked. The app is expected to use `package:web_benchmarks/client.dart`
/// and call the `runBenchmarks` function to run the benchmarks.
///
/// [entryPoint] is the path to the main app file that runs the benchmark. It
/// can be different (and typically is) from the production entry point of the
/// app.
///
/// If [useCanvasKit] is true, builds the app in CanvasKit mode.
///
/// [benchmarkServerPort] is the port this benchmark server serves the app on.
///
/// [chromeDebugPort] is the port Chrome uses for DevTool Protocol used to
/// extract tracing data.
///
/// If [headless] is true, runs Chrome without UI. In particular, this is
/// useful in environments (e.g. CI) that doesn't have a display.
BenchmarkServer({
required this.benchmarkAppDirectory,
required this.entryPoint,
required this.benchmarkServerPort,
required this.chromeDebugPort,
required this.headless,
required this.treeShakeIcons,
this.compilationOptions = const CompilationOptions(),
this.initialPage = defaultInitialPage,
});
final ProcessManager _processManager = const LocalProcessManager();
/// The directory containing the app that's being benchmarked.
///
/// The app is expected to use `package:web_benchmarks/client.dart`
/// and call the `runBenchmarks` function to run the benchmarks.
final io.Directory benchmarkAppDirectory;
/// The path to the main app file that runs the benchmark.
///
/// It can be different (and typically is) from the production entry point of
/// the app.
final String entryPoint;
/// The compilation options to use for building the benchmark web app.
final CompilationOptions compilationOptions;
/// The port this benchmark server serves the app on.
final int benchmarkServerPort;
/// The port Chrome uses for DevTool Protocol used to extract tracing data.
final int chromeDebugPort;
/// Whether to run Chrome without UI.
///
/// This is useful in environments (e.g. CI) that doesn't have a display.
final bool headless;
/// Whether to tree shake icons during the build.
///
/// When false, '--no-tree-shake-icons' will be passed as a build argument.
final bool treeShakeIcons;
/// The initial page to load upon opening the benchmark app in Chrome.
///
/// The default value is [defaultInitialPage].
final String initialPage;
String get _benchmarkAppUrl =>
'http://localhost:$benchmarkServerPort/$initialPage';
/// Builds and serves the benchmark app, and collects benchmark results.
Future<BenchmarkResults> run() async {
// Reduce logging level. Otherwise, package:webkit_inspection_protocol is way too spammy.
Logger.root.level = Level.INFO;
if (!_processManager.canRun('flutter')) {
throw Exception(
"flutter executable is not runnable. Make sure it's in the PATH.");
}
final DateTime startTime = DateTime.now();
print('Building Flutter web app $compilationOptions...');
final io.ProcessResult buildResult = await _processManager.run(
<String>[
'flutter',
'build',
'web',
if (compilationOptions.useWasm) ...<String>[
'--wasm',
'--wasm-opt=debug',
'--omit-type-checks',
],
'--web-renderer=${compilationOptions.renderer.name}',
'--dart-define=FLUTTER_WEB_ENABLE_PROFILING=true',
if (!treeShakeIcons) '--no-tree-shake-icons',
'--profile',
'-t',
entryPoint,
],
workingDirectory: benchmarkAppDirectory.path,
);
final int buildTime = Duration(
milliseconds: DateTime.now().millisecondsSinceEpoch -
startTime.millisecondsSinceEpoch,
).inSeconds;
print('Build took ${buildTime}s to complete.');
if (buildResult.exitCode != 0) {
io.stderr.writeln(buildResult.stdout);
io.stderr.writeln(buildResult.stderr);
throw Exception('Failed to build the benchmark.');
}
final Completer<List<Map<String, dynamic>>> profileData =
Completer<List<Map<String, dynamic>>>();
final List<Map<String, dynamic>> collectedProfiles =
<Map<String, dynamic>>[];
List<String>? benchmarks;
late Iterator<String> benchmarkIterator;
// This future fixes a race condition between the web-page loading and
// asking to run a benchmark, and us connecting to Chrome's DevTools port.
// Sometime one wins. Other times, the other wins.
Future<Chrome>? whenChromeIsReady;
Chrome? chrome;
late io.HttpServer server;
List<Map<String, dynamic>>? latestPerformanceTrace;
Cascade cascade = Cascade();
// Serves the static files built for the app (html, js, images, fonts, etc)
cascade = cascade.add(createStaticHandler(
path.join(benchmarkAppDirectory.path, 'build', 'web'),
defaultDocument: 'index.html',
));
// Serves the benchmark server API used by the benchmark app to coordinate
// the running of benchmarks.
cascade = cascade.add((Request request) async {
try {
chrome ??= await whenChromeIsReady;
if (request.requestedUri.path.endsWith('/profile-data')) {
final Map<String, dynamic> profile =
json.decode(await request.readAsString()) as Map<String, dynamic>;
final String? benchmarkName = profile['name'] as String?;
if (benchmarkName != benchmarkIterator.current) {
profileData.completeError(Exception(
'Browser returned benchmark results from a wrong benchmark.\n'
'Requested to run benchmark ${benchmarkIterator.current}, but '
'got results for $benchmarkName.',
));
unawaited(server.close());
}
// Trace data is null when the benchmark is not frame-based, such as RawRecorder.
if (latestPerformanceTrace != null) {
final BlinkTraceSummary? traceSummary =
BlinkTraceSummary.fromJson(latestPerformanceTrace!);
profile['totalUiFrame.average'] =
traceSummary?.averageTotalUIFrameTime.inMicroseconds;
profile['scoreKeys'] ??=
<dynamic>[]; // using dynamic for consistency with JSON
(profile['scoreKeys'] as List<dynamic>).add('totalUiFrame.average');
latestPerformanceTrace = null;
}
collectedProfiles.add(profile);
return Response.ok('Profile received');
} else if (request.requestedUri.path
.endsWith('/start-performance-tracing')) {
latestPerformanceTrace = null;
await chrome!.beginRecordingPerformance(
request.requestedUri.queryParameters['label']);
return Response.ok('Started performance tracing');
} else if (request.requestedUri.path
.endsWith('/stop-performance-tracing')) {
latestPerformanceTrace = await chrome!.endRecordingPerformance();
return Response.ok('Stopped performance tracing');
} else if (request.requestedUri.path.endsWith('/on-error')) {
final Map<String, dynamic> errorDetails =
json.decode(await request.readAsString()) as Map<String, dynamic>;
unawaited(server.close());
// Keep the stack trace as a string. It's thrown in the browser, not this Dart VM.
final String errorMessage =
'Caught browser-side error: ${errorDetails['error']}\n${errorDetails['stackTrace']}';
if (!profileData.isCompleted) {
profileData.completeError(errorMessage);
} else {
io.stderr.writeln(errorMessage);
}
return Response.ok('');
} else if (request.requestedUri.path.endsWith('/next-benchmark')) {
if (benchmarks == null) {
benchmarks =
(json.decode(await request.readAsString()) as List<dynamic>)
.cast<String>();
benchmarkIterator = benchmarks!.iterator;
}
if (benchmarkIterator.moveNext()) {
final String nextBenchmark = benchmarkIterator.current;
print('Launching benchmark "$nextBenchmark"');
return Response.ok(nextBenchmark);
} else {
profileData.complete(collectedProfiles);
return Response.ok(kEndOfBenchmarks);
}
} else if (request.requestedUri.path.endsWith('/print-to-console')) {
// A passthrough used by
// `dev/benchmarks/macrobenchmarks/lib/web_benchmarks.dart`
// to print information.
final String message = await request.readAsString();
print('[APP] $message');
return Response.ok('Reported.');
} else {
return Response.notFound(
'This request is not handled by the profile-data handler.');
}
} catch (error, stackTrace) {
if (!profileData.isCompleted) {
profileData.completeError(error, stackTrace);
} else {
io.stderr.writeln('Caught error: $error');
io.stderr.writeln('$stackTrace');
}
return Response.internalServerError(body: '$error');
}
});
// If all previous handlers returned HTTP 404, this is the last handler
// that simply warns about the unrecognized path.
cascade = cascade.add((Request request) {
io.stderr.writeln('Unrecognized URL path: ${request.requestedUri.path}');
return Response.notFound('Not found: ${request.requestedUri.path}');
});
server = await io.HttpServer.bind('localhost', benchmarkServerPort);
try {
shelf_io.serveRequests(server, cascade.handler);
final String dartToolDirectory =
path.join(benchmarkAppDirectory.path, '.dart_tool');
final String userDataDir = io.Directory(dartToolDirectory)
.createTempSync('chrome_user_data_')
.path;
final ChromeOptions options = ChromeOptions(
url: _benchmarkAppUrl,
userDataDirectory: userDataDir,
headless: headless,
debugPort: chromeDebugPort,
);
print('Launching Chrome.');
whenChromeIsReady = Chrome.launch(
options,
onError: (String error) {
if (!profileData.isCompleted) {
profileData.completeError(Exception(error));
} else {
io.stderr.writeln('Chrome error: $error');
}
},
workingDirectory: benchmarkAppDirectory.path,
);
print('Waiting for the benchmark to report benchmark profile.');
final List<Map<String, dynamic>> profiles = await profileData.future;
print('Received profile data');
final Map<String, List<BenchmarkScore>> results =
<String, List<BenchmarkScore>>{};
for (final Map<String, dynamic> profile in profiles) {
final String benchmarkName = profile['name'] as String;
if (benchmarkName.isEmpty) {
throw StateError('Benchmark name is empty');
}
final List<String> scoreKeys =
List<String>.from(profile['scoreKeys'] as Iterable<dynamic>);
if (scoreKeys.isEmpty) {
throw StateError('No score keys in benchmark "$benchmarkName"');
}
for (final String scoreKey in scoreKeys) {
if (scoreKey.isEmpty) {
throw StateError(
'Score key is empty in benchmark "$benchmarkName". '
'Received [${scoreKeys.join(', ')}]');
}
}
final List<BenchmarkScore> scores = <BenchmarkScore>[];
for (final String key in profile.keys) {
if (key == 'name' || key == 'scoreKeys') {
continue;
}
scores.add(BenchmarkScore(
metric: key,
value: profile[key] as num,
));
}
results[benchmarkName] = scores;
}
return BenchmarkResults(results);
} finally {
if (headless) {
chrome?.stop();
} else {
// In non-headless mode wait for the developer to close Chrome
// manually. Otherwise, they won't get a chance to debug anything.
print(
'Benchmark finished. Chrome running in windowed mode. Close '
'Chrome manually to continue.',
);
await chrome?.whenExits;
}
unawaited(server.close());
}
}
}
| packages/packages/web_benchmarks/lib/src/runner.dart/0 | {
"file_path": "packages/packages/web_benchmarks/lib/src/runner.dart",
"repo_id": "packages",
"token_count": 5087
} | 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.
import 'package:flutter/material.dart';
class IconGeneratorPage extends StatefulWidget {
const IconGeneratorPage({super.key});
static int defaultIconCodePoint = int.parse('0xf03f');
@override
State<IconGeneratorPage> createState() => _IconGeneratorPageState();
}
class _IconGeneratorPageState extends State<IconGeneratorPage> {
int iconCodePoint = IconGeneratorPage.defaultIconCodePoint;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextField(
onSubmitted: (String value) {
final int codePointAsInt =
int.tryParse(value) ?? IconGeneratorPage.defaultIconCodePoint;
setState(() {
iconCodePoint = codePointAsInt;
});
},
),
const SizedBox(height: 24.0),
Icon(generateIcon(iconCodePoint)),
],
);
}
// Unless '--no-tree-shake-icons' is passed to the flutter build command,
// the presence of this method will trigger an exception due to the use of
// non-constant invocations of [IconData].
IconData generateIcon(int materialIconCodePoint) => IconData(
materialIconCodePoint,
fontFamily: 'MaterialIcons',
);
}
| packages/packages/web_benchmarks/testing/test_app/lib/icon_page.dart/0 | {
"file_path": "packages/packages/web_benchmarks/testing/test_app/lib/icon_page.dart",
"repo_id": "packages",
"token_count": 511
} | 1,044 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/webview_flutter/webview_flutter/example/android/gradle.properties/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 30
} | 1,045 |
// Mocks generated by Mockito 5.4.4 from annotations
// in webview_flutter/test/webview_controller_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i5;
import 'dart:ui' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_platform_interface/src/platform_navigation_delegate.dart'
as _i6;
import 'package:webview_flutter_platform_interface/src/platform_webview_controller.dart'
as _i4;
import 'package:webview_flutter_platform_interface/src/types/types.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakePlatformWebViewControllerCreationParams_0 extends _i1.SmartFake
implements _i2.PlatformWebViewControllerCreationParams {
_FakePlatformWebViewControllerCreationParams_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeObject_1 extends _i1.SmartFake implements Object {
_FakeObject_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeOffset_2 extends _i1.SmartFake implements _i3.Offset {
_FakeOffset_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePlatformNavigationDelegateCreationParams_3 extends _i1.SmartFake
implements _i2.PlatformNavigationDelegateCreationParams {
_FakePlatformNavigationDelegateCreationParams_3(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [PlatformWebViewController].
///
/// See the documentation for Mockito's code generation for more information.
class MockPlatformWebViewController extends _i1.Mock
implements _i4.PlatformWebViewController {
MockPlatformWebViewController() {
_i1.throwOnMissingStub(this);
}
@override
_i2.PlatformWebViewControllerCreationParams get params => (super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformWebViewControllerCreationParams_0(
this,
Invocation.getter(#params),
),
) as _i2.PlatformWebViewControllerCreationParams);
@override
_i5.Future<void> loadFile(String? absoluteFilePath) => (super.noSuchMethod(
Invocation.method(
#loadFile,
[absoluteFilePath],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> loadFlutterAsset(String? key) => (super.noSuchMethod(
Invocation.method(
#loadFlutterAsset,
[key],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> loadHtmlString(
String? html, {
String? baseUrl,
}) =>
(super.noSuchMethod(
Invocation.method(
#loadHtmlString,
[html],
{#baseUrl: baseUrl},
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> loadRequest(_i2.LoadRequestParams? params) =>
(super.noSuchMethod(
Invocation.method(
#loadRequest,
[params],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<String?> currentUrl() => (super.noSuchMethod(
Invocation.method(
#currentUrl,
[],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
_i5.Future<bool> canGoBack() => (super.noSuchMethod(
Invocation.method(
#canGoBack,
[],
),
returnValue: _i5.Future<bool>.value(false),
) as _i5.Future<bool>);
@override
_i5.Future<bool> canGoForward() => (super.noSuchMethod(
Invocation.method(
#canGoForward,
[],
),
returnValue: _i5.Future<bool>.value(false),
) as _i5.Future<bool>);
@override
_i5.Future<void> goBack() => (super.noSuchMethod(
Invocation.method(
#goBack,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> goForward() => (super.noSuchMethod(
Invocation.method(
#goForward,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> reload() => (super.noSuchMethod(
Invocation.method(
#reload,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> clearCache() => (super.noSuchMethod(
Invocation.method(
#clearCache,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> clearLocalStorage() => (super.noSuchMethod(
Invocation.method(
#clearLocalStorage,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setPlatformNavigationDelegate(
_i6.PlatformNavigationDelegate? handler) =>
(super.noSuchMethod(
Invocation.method(
#setPlatformNavigationDelegate,
[handler],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> runJavaScript(String? javaScript) => (super.noSuchMethod(
Invocation.method(
#runJavaScript,
[javaScript],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<Object> runJavaScriptReturningResult(String? javaScript) =>
(super.noSuchMethod(
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
returnValue: _i5.Future<Object>.value(_FakeObject_1(
this,
Invocation.method(
#runJavaScriptReturningResult,
[javaScript],
),
)),
) as _i5.Future<Object>);
@override
_i5.Future<void> addJavaScriptChannel(
_i4.JavaScriptChannelParams? javaScriptChannelParams) =>
(super.noSuchMethod(
Invocation.method(
#addJavaScriptChannel,
[javaScriptChannelParams],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> removeJavaScriptChannel(String? javaScriptChannelName) =>
(super.noSuchMethod(
Invocation.method(
#removeJavaScriptChannel,
[javaScriptChannelName],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<String?> getTitle() => (super.noSuchMethod(
Invocation.method(
#getTitle,
[],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
_i5.Future<void> scrollTo(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollTo,
[
x,
y,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> scrollBy(
int? x,
int? y,
) =>
(super.noSuchMethod(
Invocation.method(
#scrollBy,
[
x,
y,
],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<_i3.Offset> getScrollPosition() => (super.noSuchMethod(
Invocation.method(
#getScrollPosition,
[],
),
returnValue: _i5.Future<_i3.Offset>.value(_FakeOffset_2(
this,
Invocation.method(
#getScrollPosition,
[],
),
)),
) as _i5.Future<_i3.Offset>);
@override
_i5.Future<void> enableZoom(bool? enabled) => (super.noSuchMethod(
Invocation.method(
#enableZoom,
[enabled],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setBackgroundColor(_i3.Color? color) => (super.noSuchMethod(
Invocation.method(
#setBackgroundColor,
[color],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setJavaScriptMode(_i2.JavaScriptMode? javaScriptMode) =>
(super.noSuchMethod(
Invocation.method(
#setJavaScriptMode,
[javaScriptMode],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setUserAgent(String? userAgent) => (super.noSuchMethod(
Invocation.method(
#setUserAgent,
[userAgent],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnPlatformPermissionRequest(
void Function(_i2.PlatformWebViewPermissionRequest)?
onPermissionRequest) =>
(super.noSuchMethod(
Invocation.method(
#setOnPlatformPermissionRequest,
[onPermissionRequest],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<String?> getUserAgent() => (super.noSuchMethod(
Invocation.method(
#getUserAgent,
[],
),
returnValue: _i5.Future<String?>.value(),
) as _i5.Future<String?>);
@override
_i5.Future<void> setOnConsoleMessage(
void Function(_i2.JavaScriptConsoleMessage)? onConsoleMessage) =>
(super.noSuchMethod(
Invocation.method(
#setOnConsoleMessage,
[onConsoleMessage],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnScrollPositionChange(
void Function(_i2.ScrollPositionChange)? onScrollPositionChange) =>
(super.noSuchMethod(
Invocation.method(
#setOnScrollPositionChange,
[onScrollPositionChange],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnJavaScriptAlertDialog(
_i5.Future<void> Function(_i2.JavaScriptAlertDialogRequest)?
onJavaScriptAlertDialog) =>
(super.noSuchMethod(
Invocation.method(
#setOnJavaScriptAlertDialog,
[onJavaScriptAlertDialog],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnJavaScriptConfirmDialog(
_i5.Future<bool> Function(_i2.JavaScriptConfirmDialogRequest)?
onJavaScriptConfirmDialog) =>
(super.noSuchMethod(
Invocation.method(
#setOnJavaScriptConfirmDialog,
[onJavaScriptConfirmDialog],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnJavaScriptTextInputDialog(
_i5.Future<String> Function(_i2.JavaScriptTextInputDialogRequest)?
onJavaScriptTextInputDialog) =>
(super.noSuchMethod(
Invocation.method(
#setOnJavaScriptTextInputDialog,
[onJavaScriptTextInputDialog],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
}
/// A class which mocks [PlatformNavigationDelegate].
///
/// See the documentation for Mockito's code generation for more information.
class MockPlatformNavigationDelegate extends _i1.Mock
implements _i6.PlatformNavigationDelegate {
MockPlatformNavigationDelegate() {
_i1.throwOnMissingStub(this);
}
@override
_i2.PlatformNavigationDelegateCreationParams get params =>
(super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformNavigationDelegateCreationParams_3(
this,
Invocation.getter(#params),
),
) as _i2.PlatformNavigationDelegateCreationParams);
@override
_i5.Future<void> setOnNavigationRequest(
_i6.NavigationRequestCallback? onNavigationRequest) =>
(super.noSuchMethod(
Invocation.method(
#setOnNavigationRequest,
[onNavigationRequest],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnPageStarted(_i6.PageEventCallback? onPageStarted) =>
(super.noSuchMethod(
Invocation.method(
#setOnPageStarted,
[onPageStarted],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnPageFinished(_i6.PageEventCallback? onPageFinished) =>
(super.noSuchMethod(
Invocation.method(
#setOnPageFinished,
[onPageFinished],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnHttpError(_i6.HttpResponseErrorCallback? onHttpError) =>
(super.noSuchMethod(
Invocation.method(
#setOnHttpError,
[onHttpError],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnProgress(_i6.ProgressCallback? onProgress) =>
(super.noSuchMethod(
Invocation.method(
#setOnProgress,
[onProgress],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnWebResourceError(
_i6.WebResourceErrorCallback? onWebResourceError) =>
(super.noSuchMethod(
Invocation.method(
#setOnWebResourceError,
[onWebResourceError],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnUrlChange(_i6.UrlChangeCallback? onUrlChange) =>
(super.noSuchMethod(
Invocation.method(
#setOnUrlChange,
[onUrlChange],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<void> setOnHttpAuthRequest(
_i6.HttpAuthRequestCallback? onHttpAuthRequest) =>
(super.noSuchMethod(
Invocation.method(
#setOnHttpAuthRequest,
[onHttpAuthRequest],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
}
| packages/packages/webview_flutter/webview_flutter/test/webview_controller_test.mocks.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter/test/webview_controller_test.mocks.dart",
"repo_id": "packages",
"token_count": 7760
} | 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 io.flutter.plugins.webviewflutter;
import android.os.Handler;
import androidx.annotation.NonNull;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.JavaScriptChannelHostApi;
/**
* Host api implementation for {@link JavaScriptChannel}.
*
* <p>Handles creating {@link JavaScriptChannel}s that intercommunicate with a paired Dart object.
*/
public class JavaScriptChannelHostApiImpl implements JavaScriptChannelHostApi {
private final InstanceManager instanceManager;
private final JavaScriptChannelCreator javaScriptChannelCreator;
private final JavaScriptChannelFlutterApiImpl flutterApi;
private Handler platformThreadHandler;
/** Handles creating {@link JavaScriptChannel}s for a {@link JavaScriptChannelHostApiImpl}. */
public static class JavaScriptChannelCreator {
/**
* Creates a {@link JavaScriptChannel}.
*
* @param flutterApi handles sending messages to Dart
* @param channelName JavaScript channel the message should be sent through
* @param platformThreadHandler handles making callbacks on the desired thread
* @return the created {@link JavaScriptChannel}
*/
@NonNull
public JavaScriptChannel createJavaScriptChannel(
@NonNull JavaScriptChannelFlutterApiImpl flutterApi,
@NonNull String channelName,
@NonNull Handler platformThreadHandler) {
return new JavaScriptChannel(flutterApi, channelName, platformThreadHandler);
}
}
/**
* Creates a host API that handles creating {@link JavaScriptChannel}s.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param javaScriptChannelCreator handles creating {@link JavaScriptChannel}s
* @param flutterApi handles sending messages to Dart
* @param platformThreadHandler handles making callbacks on the desired thread
*/
public JavaScriptChannelHostApiImpl(
@NonNull InstanceManager instanceManager,
@NonNull JavaScriptChannelCreator javaScriptChannelCreator,
@NonNull JavaScriptChannelFlutterApiImpl flutterApi,
@NonNull Handler platformThreadHandler) {
this.instanceManager = instanceManager;
this.javaScriptChannelCreator = javaScriptChannelCreator;
this.flutterApi = flutterApi;
this.platformThreadHandler = platformThreadHandler;
}
/**
* Sets the platformThreadHandler to make callbacks
*
* @param platformThreadHandler the new thread handler
*/
public void setPlatformThreadHandler(@NonNull Handler platformThreadHandler) {
this.platformThreadHandler = platformThreadHandler;
}
@Override
public void create(@NonNull Long instanceId, @NonNull String channelName) {
final JavaScriptChannel javaScriptChannel =
javaScriptChannelCreator.createJavaScriptChannel(
flutterApi, channelName, platformThreadHandler);
instanceManager.addDartCreatedInstance(javaScriptChannel, instanceId);
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/JavaScriptChannelHostApiImpl.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/JavaScriptChannelHostApiImpl.java",
"repo_id": "packages",
"token_count": 872
} | 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.
package io.flutter.plugins.webviewflutter;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import android.webkit.WebChromeClient.CustomViewCallback;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.CustomViewCallbackFlutterApi;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class CustomViewCallbackTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public CustomViewCallback mockCustomViewCallback;
@Mock public BinaryMessenger mockBinaryMessenger;
@Mock public CustomViewCallbackFlutterApi mockFlutterApi;
InstanceManager instanceManager;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Test
public void onCustomViewHidden() {
final long instanceIdentifier = 0;
instanceManager.addDartCreatedInstance(mockCustomViewCallback, instanceIdentifier);
final CustomViewCallbackHostApiImpl hostApi =
new CustomViewCallbackHostApiImpl(mockBinaryMessenger, instanceManager);
hostApi.onCustomViewHidden(instanceIdentifier);
verify(mockCustomViewCallback).onCustomViewHidden();
}
@Test
public void flutterApiCreate() {
final CustomViewCallbackFlutterApiImpl flutterApi =
new CustomViewCallbackFlutterApiImpl(mockBinaryMessenger, instanceManager);
flutterApi.setApi(mockFlutterApi);
flutterApi.create(mockCustomViewCallback, reply -> {});
final long instanceIdentifier =
Objects.requireNonNull(
instanceManager.getIdentifierForStrongReference(mockCustomViewCallback));
verify(mockFlutterApi).create(eq(instanceIdentifier), any());
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/CustomViewCallbackTest.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/CustomViewCallbackTest.java",
"repo_id": "packages",
"token_count": 709
} | 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.
package io.flutter.plugins.webviewflutter;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.net.Uri;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import io.flutter.plugins.webviewflutter.WebViewClientHostApiImpl.WebViewClientCompatImpl;
import io.flutter.plugins.webviewflutter.WebViewClientHostApiImpl.WebViewClientCreator;
import java.util.HashMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class WebViewClientTest {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock public WebViewClientFlutterApiImpl mockFlutterApi;
@Mock public WebView mockWebView;
@Mock public WebViewClientCompatImpl mockWebViewClient;
InstanceManager instanceManager;
WebViewClientHostApiImpl hostApiImpl;
WebViewClientCompatImpl webViewClient;
@Before
public void setUp() {
instanceManager = InstanceManager.create(identifier -> {});
final WebViewClientCreator webViewClientCreator =
new WebViewClientCreator() {
@Override
@NonNull
public WebViewClient createWebViewClient(
@NonNull WebViewClientFlutterApiImpl flutterApi) {
webViewClient = (WebViewClientCompatImpl) super.createWebViewClient(flutterApi);
return webViewClient;
}
};
hostApiImpl =
new WebViewClientHostApiImpl(instanceManager, webViewClientCreator, mockFlutterApi);
hostApiImpl.create(1L);
}
@After
public void tearDown() {
instanceManager.stopFinalizationListener();
}
@Test
public void onPageStarted() {
webViewClient.onPageStarted(mockWebView, "https://www.google.com", null);
verify(mockFlutterApi)
.onPageStarted(eq(webViewClient), eq(mockWebView), eq("https://www.google.com"), any());
}
@Test
public void onReceivedError() {
webViewClient.onReceivedError(mockWebView, 32, "description", "https://www.google.com");
verify(mockFlutterApi)
.onReceivedError(
eq(webViewClient),
eq(mockWebView),
eq(32L),
eq("description"),
eq("https://www.google.com"),
any());
}
@Test
public void urlLoading() {
webViewClient.shouldOverrideUrlLoading(mockWebView, "https://www.google.com");
verify(mockFlutterApi)
.urlLoading(eq(webViewClient), eq(mockWebView), eq("https://www.google.com"), any());
}
@Test
public void convertWebResourceRequestWithNullHeaders() {
final Uri mockUri = mock(Uri.class);
when(mockUri.toString()).thenReturn("");
final WebResourceRequest mockRequest = mock(WebResourceRequest.class);
when(mockRequest.getMethod()).thenReturn("method");
when(mockRequest.getUrl()).thenReturn(mockUri);
when(mockRequest.isForMainFrame()).thenReturn(true);
when(mockRequest.getRequestHeaders()).thenReturn(null);
final GeneratedAndroidWebView.WebResourceRequestData data =
WebViewClientFlutterApiImpl.createWebResourceRequestData(mockRequest);
assertEquals(data.getRequestHeaders(), new HashMap<String, String>());
}
@Test
public void setReturnValueForShouldOverrideUrlLoading() {
final WebViewClientHostApiImpl webViewClientHostApi =
new WebViewClientHostApiImpl(
instanceManager,
new WebViewClientCreator() {
@NonNull
@Override
public WebViewClient createWebViewClient(
@NonNull WebViewClientFlutterApiImpl flutterApi) {
return mockWebViewClient;
}
},
mockFlutterApi);
instanceManager.addDartCreatedInstance(mockWebViewClient, 2);
webViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading(2L, false);
verify(mockWebViewClient).setReturnValueForShouldOverrideUrlLoading(false);
}
@Test
public void doUpdateVisitedHistory() {
webViewClient.doUpdateVisitedHistory(mockWebView, "https://www.google.com", true);
verify(mockFlutterApi)
.doUpdateVisitedHistory(
eq(webViewClient), eq(mockWebView), eq("https://www.google.com"), eq(true), any());
}
@Test
public void onReceivedHttpError() {
final Uri mockUri = mock(Uri.class);
when(mockUri.toString()).thenReturn("");
final WebResourceRequest mockRequest = mock(WebResourceRequest.class);
when(mockRequest.getMethod()).thenReturn("method");
when(mockRequest.getUrl()).thenReturn(mockUri);
when(mockRequest.isForMainFrame()).thenReturn(true);
when(mockRequest.getRequestHeaders()).thenReturn(null);
final WebResourceResponse mockResponse = mock(WebResourceResponse.class);
when(mockResponse.getStatusCode()).thenReturn(404);
webViewClient.onReceivedHttpError(mockWebView, mockRequest, mockResponse);
verify(mockFlutterApi)
.onReceivedHttpError(
eq(webViewClient),
eq(mockWebView),
any(WebResourceRequest.class),
any(WebResourceResponse.class),
any());
}
}
| packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientTest.java/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientTest.java",
"repo_id": "packages",
"token_count": 2138
} | 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 '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';
import 'package:webview_flutter_android/src/android_webview.g.dart';
import 'package:webview_flutter_android/src/android_webview_api_impls.dart';
import 'package:webview_flutter_android/src/instance_manager.dart';
import 'android_webview_test.mocks.dart';
import 'test_android_webview.g.dart';
@GenerateMocks(<Type>[
CookieManagerHostApi,
DownloadListener,
JavaScriptChannel,
TestCookieManagerHostApi,
TestCustomViewCallbackHostApi,
TestDownloadListenerHostApi,
TestGeolocationPermissionsCallbackHostApi,
TestInstanceManagerHostApi,
TestJavaObjectHostApi,
TestJavaScriptChannelHostApi,
TestWebChromeClientHostApi,
TestWebSettingsHostApi,
TestWebStorageHostApi,
TestWebViewClientHostApi,
TestWebViewHostApi,
TestAssetManagerHostApi,
TestPermissionRequestHostApi,
WebChromeClient,
WebView,
WebViewClient,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Mocks the calls to the native InstanceManager.
TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi());
TestJavaObjectHostApi.setup(MockTestJavaObjectHostApi());
group('Android WebView', () {
group('JavaObject', () {
late MockTestJavaObjectHostApi mockPlatformHostApi;
setUp(() {
mockPlatformHostApi = MockTestJavaObjectHostApi();
TestJavaObjectHostApi.setup(mockPlatformHostApi);
});
test('JavaObject.dispose', () async {
int? callbackIdentifier;
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (int identifier) {
callbackIdentifier = identifier;
},
);
final JavaObject object = JavaObject.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(object, 0);
JavaObject.dispose(object);
expect(callbackIdentifier, 0);
});
test('JavaObjectFlutterApi.dispose', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final JavaObject object = JavaObject.detached(
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(object, 0);
instanceManager.removeWeakReference(object);
expect(instanceManager.containsIdentifier(0), isTrue);
final JavaObjectFlutterApiImpl flutterApi = JavaObjectFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.dispose(0);
expect(instanceManager.containsIdentifier(0), isFalse);
});
});
group('WebView', () {
late MockTestWebViewHostApi mockPlatformHostApi;
late InstanceManager instanceManager;
late WebView webView;
late int webViewInstanceId;
setUp(() {
mockPlatformHostApi = MockTestWebViewHostApi();
TestWebViewHostApi.setup(mockPlatformHostApi);
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
WebView.api = WebViewHostApiImpl(instanceManager: instanceManager);
webView = WebView();
webViewInstanceId = instanceManager.getIdentifier(webView)!;
});
test('create', () {
verify(mockPlatformHostApi.create(webViewInstanceId));
});
test('setWebContentsDebuggingEnabled true', () {
WebView.setWebContentsDebuggingEnabled(true);
verify(mockPlatformHostApi.setWebContentsDebuggingEnabled(true));
});
test('setWebContentsDebuggingEnabled false', () {
WebView.setWebContentsDebuggingEnabled(false);
verify(mockPlatformHostApi.setWebContentsDebuggingEnabled(false));
});
test('loadData', () {
webView.loadData(
data: 'hello',
mimeType: 'text/plain',
encoding: 'base64',
);
verify(mockPlatformHostApi.loadData(
webViewInstanceId,
'hello',
'text/plain',
'base64',
));
});
test('loadData with null values', () {
webView.loadData(data: 'hello');
verify(mockPlatformHostApi.loadData(
webViewInstanceId,
'hello',
null,
null,
));
});
test('loadDataWithBaseUrl', () {
webView.loadDataWithBaseUrl(
baseUrl: 'https://base.url',
data: 'hello',
mimeType: 'text/plain',
encoding: 'base64',
historyUrl: 'https://history.url',
);
verify(mockPlatformHostApi.loadDataWithBaseUrl(
webViewInstanceId,
'https://base.url',
'hello',
'text/plain',
'base64',
'https://history.url',
));
});
test('loadDataWithBaseUrl with null values', () {
webView.loadDataWithBaseUrl(data: 'hello');
verify(mockPlatformHostApi.loadDataWithBaseUrl(
webViewInstanceId,
null,
'hello',
null,
null,
null,
));
});
test('loadUrl', () {
webView.loadUrl('hello', <String, String>{'a': 'header'});
verify(mockPlatformHostApi.loadUrl(
webViewInstanceId,
'hello',
<String, String>{'a': 'header'},
));
});
test('canGoBack', () {
when(mockPlatformHostApi.canGoBack(webViewInstanceId))
.thenReturn(false);
expect(webView.canGoBack(), completion(false));
});
test('canGoForward', () {
when(mockPlatformHostApi.canGoForward(webViewInstanceId))
.thenReturn(true);
expect(webView.canGoForward(), completion(true));
});
test('goBack', () {
webView.goBack();
verify(mockPlatformHostApi.goBack(webViewInstanceId));
});
test('goForward', () {
webView.goForward();
verify(mockPlatformHostApi.goForward(webViewInstanceId));
});
test('reload', () {
webView.reload();
verify(mockPlatformHostApi.reload(webViewInstanceId));
});
test('clearCache', () {
webView.clearCache(false);
verify(mockPlatformHostApi.clearCache(webViewInstanceId, false));
});
test('evaluateJavascript', () {
when(
mockPlatformHostApi.evaluateJavascript(
webViewInstanceId, 'runJavaScript'),
).thenAnswer((_) => Future<String>.value('returnValue'));
expect(
webView.evaluateJavascript('runJavaScript'),
completion('returnValue'),
);
});
test('getTitle', () {
when(mockPlatformHostApi.getTitle(webViewInstanceId))
.thenReturn('aTitle');
expect(webView.getTitle(), completion('aTitle'));
});
test('scrollTo', () {
webView.scrollTo(12, 13);
verify(mockPlatformHostApi.scrollTo(webViewInstanceId, 12, 13));
});
test('scrollBy', () {
webView.scrollBy(12, 14);
verify(mockPlatformHostApi.scrollBy(webViewInstanceId, 12, 14));
});
test('getScrollX', () {
when(mockPlatformHostApi.getScrollX(webViewInstanceId)).thenReturn(67);
expect(webView.getScrollX(), completion(67));
});
test('getScrollY', () {
when(mockPlatformHostApi.getScrollY(webViewInstanceId)).thenReturn(56);
expect(webView.getScrollY(), completion(56));
});
test('getScrollPosition', () async {
when(mockPlatformHostApi.getScrollPosition(webViewInstanceId))
.thenReturn(WebViewPoint(x: 2, y: 16));
await expectLater(
webView.getScrollPosition(),
completion(const Offset(2.0, 16.0)),
);
});
test('setWebViewClient', () {
TestWebViewClientHostApi.setup(MockTestWebViewClientHostApi());
WebViewClient.api = WebViewClientHostApiImpl(
instanceManager: instanceManager,
);
final WebViewClient mockWebViewClient = MockWebViewClient();
when(mockWebViewClient.copy()).thenReturn(MockWebViewClient());
instanceManager.addDartCreatedInstance(mockWebViewClient);
webView.setWebViewClient(mockWebViewClient);
final int webViewClientInstanceId =
instanceManager.getIdentifier(mockWebViewClient)!;
verify(mockPlatformHostApi.setWebViewClient(
webViewInstanceId,
webViewClientInstanceId,
));
});
test('addJavaScriptChannel', () {
TestJavaScriptChannelHostApi.setup(MockTestJavaScriptChannelHostApi());
JavaScriptChannel.api = JavaScriptChannelHostApiImpl(
instanceManager: instanceManager,
);
final JavaScriptChannel mockJavaScriptChannel = MockJavaScriptChannel();
when(mockJavaScriptChannel.copy()).thenReturn(MockJavaScriptChannel());
when(mockJavaScriptChannel.channelName).thenReturn('aChannel');
webView.addJavaScriptChannel(mockJavaScriptChannel);
final int javaScriptChannelInstanceId =
instanceManager.getIdentifier(mockJavaScriptChannel)!;
verify(mockPlatformHostApi.addJavaScriptChannel(
webViewInstanceId,
javaScriptChannelInstanceId,
));
});
test('removeJavaScriptChannel', () {
TestJavaScriptChannelHostApi.setup(MockTestJavaScriptChannelHostApi());
JavaScriptChannel.api = JavaScriptChannelHostApiImpl(
instanceManager: instanceManager,
);
final JavaScriptChannel mockJavaScriptChannel = MockJavaScriptChannel();
when(mockJavaScriptChannel.copy()).thenReturn(MockJavaScriptChannel());
when(mockJavaScriptChannel.channelName).thenReturn('aChannel');
expect(
webView.removeJavaScriptChannel(mockJavaScriptChannel),
completes,
);
webView.addJavaScriptChannel(mockJavaScriptChannel);
webView.removeJavaScriptChannel(mockJavaScriptChannel);
final int javaScriptChannelInstanceId =
instanceManager.getIdentifier(mockJavaScriptChannel)!;
verify(mockPlatformHostApi.removeJavaScriptChannel(
webViewInstanceId,
javaScriptChannelInstanceId,
));
});
test('setDownloadListener', () {
TestDownloadListenerHostApi.setup(MockTestDownloadListenerHostApi());
DownloadListener.api = DownloadListenerHostApiImpl(
instanceManager: instanceManager,
);
final DownloadListener mockDownloadListener = MockDownloadListener();
when(mockDownloadListener.copy()).thenReturn(MockDownloadListener());
instanceManager.addDartCreatedInstance(mockDownloadListener);
webView.setDownloadListener(mockDownloadListener);
final int downloadListenerInstanceId =
instanceManager.getIdentifier(mockDownloadListener)!;
verify(mockPlatformHostApi.setDownloadListener(
webViewInstanceId,
downloadListenerInstanceId,
));
});
test('setWebChromeClient', () {
TestWebChromeClientHostApi.setup(MockTestWebChromeClientHostApi());
WebChromeClient.api = WebChromeClientHostApiImpl(
instanceManager: instanceManager,
);
final WebChromeClient mockWebChromeClient = MockWebChromeClient();
when(mockWebChromeClient.copy()).thenReturn(MockWebChromeClient());
instanceManager.addDartCreatedInstance(mockWebChromeClient);
webView.setWebChromeClient(mockWebChromeClient);
final int webChromeClientInstanceId =
instanceManager.getIdentifier(mockWebChromeClient)!;
verify(mockPlatformHostApi.setWebChromeClient(
webViewInstanceId,
webChromeClientInstanceId,
));
});
test('FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final WebViewFlutterApiImpl api = WebViewFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
api.create(instanceIdentifier);
expect(
instanceManager.getInstanceWithWeakReference(instanceIdentifier),
isA<WebView>(),
);
});
test('copy', () {
expect(webView.copy(), isA<WebView>());
});
});
group('WebSettings', () {
late MockTestWebSettingsHostApi mockPlatformHostApi;
late InstanceManager instanceManager;
late WebSettings webSettings;
late int webSettingsInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
TestWebViewHostApi.setup(MockTestWebViewHostApi());
WebView.api = WebViewHostApiImpl(instanceManager: instanceManager);
mockPlatformHostApi = MockTestWebSettingsHostApi();
TestWebSettingsHostApi.setup(mockPlatformHostApi);
WebSettings.api = WebSettingsHostApiImpl(
instanceManager: instanceManager,
);
webSettings = WebSettings(WebView());
webSettingsInstanceId = instanceManager.getIdentifier(webSettings)!;
});
test('create', () {
verify(mockPlatformHostApi.create(webSettingsInstanceId, any));
});
test('setDomStorageEnabled', () {
webSettings.setDomStorageEnabled(false);
verify(mockPlatformHostApi.setDomStorageEnabled(
webSettingsInstanceId,
false,
));
});
test('setJavaScriptCanOpenWindowsAutomatically', () {
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
verify(mockPlatformHostApi.setJavaScriptCanOpenWindowsAutomatically(
webSettingsInstanceId,
true,
));
});
test('setSupportMultipleWindows', () {
webSettings.setSupportMultipleWindows(false);
verify(mockPlatformHostApi.setSupportMultipleWindows(
webSettingsInstanceId,
false,
));
});
test('setJavaScriptEnabled', () {
webSettings.setJavaScriptEnabled(true);
verify(mockPlatformHostApi.setJavaScriptEnabled(
webSettingsInstanceId,
true,
));
});
test('setUserAgentString', () {
webSettings.setUserAgentString('hola');
verify(mockPlatformHostApi.setUserAgentString(
webSettingsInstanceId,
'hola',
));
});
test('setMediaPlaybackRequiresUserGesture', () {
webSettings.setMediaPlaybackRequiresUserGesture(false);
verify(mockPlatformHostApi.setMediaPlaybackRequiresUserGesture(
webSettingsInstanceId,
false,
));
});
test('setSupportZoom', () {
webSettings.setSupportZoom(true);
verify(mockPlatformHostApi.setSupportZoom(
webSettingsInstanceId,
true,
));
});
test('setLoadWithOverviewMode', () {
webSettings.setLoadWithOverviewMode(false);
verify(mockPlatformHostApi.setLoadWithOverviewMode(
webSettingsInstanceId,
false,
));
});
test('setUseWideViewPort', () {
webSettings.setUseWideViewPort(true);
verify(mockPlatformHostApi.setUseWideViewPort(
webSettingsInstanceId,
true,
));
});
test('setDisplayZoomControls', () {
webSettings.setDisplayZoomControls(false);
verify(mockPlatformHostApi.setDisplayZoomControls(
webSettingsInstanceId,
false,
));
});
test('setBuiltInZoomControls', () {
webSettings.setBuiltInZoomControls(true);
verify(mockPlatformHostApi.setBuiltInZoomControls(
webSettingsInstanceId,
true,
));
});
test('setAllowFileAccess', () {
webSettings.setAllowFileAccess(true);
verify(mockPlatformHostApi.setAllowFileAccess(
webSettingsInstanceId,
true,
));
});
test('copy', () {
expect(webSettings.copy(), isA<WebSettings>());
});
test('setTextZoom', () {
webSettings.setTextZoom(100);
verify(mockPlatformHostApi.setTextZoom(
webSettingsInstanceId,
100,
));
});
test('getUserAgentString', () async {
const String userAgent = 'str';
when(mockPlatformHostApi.getUserAgentString(webSettingsInstanceId))
.thenReturn(userAgent);
expect(await webSettings.getUserAgentString(), userAgent);
});
});
group('JavaScriptChannel', () {
late JavaScriptChannelFlutterApiImpl flutterApi;
late InstanceManager instanceManager;
late MockJavaScriptChannel mockJavaScriptChannel;
late int mockJavaScriptChannelInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
flutterApi = JavaScriptChannelFlutterApiImpl(
instanceManager: instanceManager,
);
mockJavaScriptChannel = MockJavaScriptChannel();
when(mockJavaScriptChannel.copy()).thenReturn(MockJavaScriptChannel());
mockJavaScriptChannelInstanceId =
instanceManager.addDartCreatedInstance(mockJavaScriptChannel);
});
test('postMessage', () {
late final String result;
when(mockJavaScriptChannel.postMessage).thenReturn((String message) {
result = message;
});
flutterApi.postMessage(
mockJavaScriptChannelInstanceId,
'Hello, World!',
);
expect(result, 'Hello, World!');
});
test('copy', () {
expect(
JavaScriptChannel.detached('channel', postMessage: (_) {}).copy(),
isA<JavaScriptChannel>(),
);
});
});
group('WebViewClient', () {
late WebViewClientFlutterApiImpl flutterApi;
late InstanceManager instanceManager;
late MockWebViewClient mockWebViewClient;
late int mockWebViewClientInstanceId;
late MockWebView mockWebView;
late int mockWebViewInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
flutterApi = WebViewClientFlutterApiImpl(
instanceManager: instanceManager,
);
mockWebViewClient = MockWebViewClient();
when(mockWebViewClient.copy()).thenReturn(MockWebViewClient());
mockWebViewClientInstanceId =
instanceManager.addDartCreatedInstance(mockWebViewClient);
mockWebView = MockWebView();
when(mockWebView.copy()).thenReturn(MockWebView());
mockWebViewInstanceId =
instanceManager.addDartCreatedInstance(mockWebView);
});
test('onPageStarted', () {
late final List<Object> result;
when(mockWebViewClient.onPageStarted).thenReturn(
(WebView webView, String url) {
result = <Object>[webView, url];
},
);
flutterApi.onPageStarted(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
'https://www.google.com',
);
expect(result, <Object>[mockWebView, 'https://www.google.com']);
});
test('onPageFinished', () {
late final List<Object> result;
when(mockWebViewClient.onPageFinished).thenReturn(
(WebView webView, String url) {
result = <Object>[webView, url];
},
);
flutterApi.onPageFinished(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
'https://www.google.com',
);
expect(result, <Object>[mockWebView, 'https://www.google.com']);
});
test('onReceivedHttpError', () {
late final List<Object> result;
when(mockWebViewClient.onReceivedHttpError).thenReturn(
(
WebView webView,
WebResourceRequest request,
WebResourceResponse response,
) {
result = <Object>[webView, request, response];
},
);
flutterApi.onReceivedHttpError(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
WebResourceRequestData(
url: 'https://www.google.com',
isForMainFrame: true,
hasGesture: true,
method: 'GET',
isRedirect: false,
requestHeaders: <String?, String?>{},
),
WebResourceResponseData(
statusCode: 401,
),
);
expect(result, <Object>[mockWebView, isNotNull, isNotNull]);
});
test('onReceivedRequestError', () {
late final List<Object> result;
when(mockWebViewClient.onReceivedRequestError).thenReturn(
(
WebView webView,
WebResourceRequest request,
WebResourceError error,
) {
result = <Object>[webView, request, error];
},
);
flutterApi.onReceivedRequestError(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
WebResourceRequestData(
url: 'https://www.google.com',
isForMainFrame: true,
hasGesture: true,
method: 'POST',
isRedirect: false,
requestHeaders: <String?, String?>{},
),
WebResourceErrorData(errorCode: 34, description: 'error description'),
);
expect(
result,
containsAllInOrder(<Object?>[mockWebView, isNotNull, isNotNull]),
);
});
test('onReceivedError', () {
late final List<Object> result;
when(mockWebViewClient.onReceivedError).thenReturn(
(
WebView webView,
int errorCode,
String description,
String failingUrl,
) {
result = <Object>[webView, errorCode, description, failingUrl];
},
);
flutterApi.onReceivedError(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
14,
'desc',
'https://www.google.com',
);
expect(
result,
containsAllInOrder(
<Object?>[mockWebView, 14, 'desc', 'https://www.google.com'],
),
);
});
test('requestLoading', () {
late final List<Object> result;
when(mockWebViewClient.requestLoading).thenReturn(
(WebView webView, WebResourceRequest request) {
result = <Object>[webView, request];
},
);
flutterApi.requestLoading(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
WebResourceRequestData(
url: 'https://www.google.com',
isForMainFrame: true,
hasGesture: true,
method: 'POST',
isRedirect: true,
requestHeaders: <String?, String?>{},
),
);
expect(
result,
containsAllInOrder(<Object?>[mockWebView, isNotNull]),
);
});
test('urlLoading', () {
late final List<Object> result;
when(mockWebViewClient.urlLoading).thenReturn(
(WebView webView, String url) {
result = <Object>[webView, url];
},
);
flutterApi.urlLoading(mockWebViewClientInstanceId,
mockWebViewInstanceId, 'https://www.google.com');
expect(
result,
containsAllInOrder(<Object?>[mockWebView, 'https://www.google.com']),
);
});
test('doUpdateVisitedHistory', () {
late final List<Object> result;
when(mockWebViewClient.doUpdateVisitedHistory).thenReturn(
(
WebView webView,
String url,
bool isReload,
) {
result = <Object>[webView, url, isReload];
},
);
flutterApi.doUpdateVisitedHistory(
mockWebViewClientInstanceId,
mockWebViewInstanceId,
'https://www.google.com',
false,
);
expect(
result,
containsAllInOrder(
<Object?>[mockWebView, 'https://www.google.com', false],
),
);
});
test('copy', () {
expect(WebViewClient.detached().copy(), isA<WebViewClient>());
});
});
group('DownloadListener', () {
late DownloadListenerFlutterApiImpl flutterApi;
late InstanceManager instanceManager;
late MockDownloadListener mockDownloadListener;
late int mockDownloadListenerInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
flutterApi = DownloadListenerFlutterApiImpl(
instanceManager: instanceManager,
);
mockDownloadListener = MockDownloadListener();
when(mockDownloadListener.copy()).thenReturn(MockDownloadListener());
mockDownloadListenerInstanceId =
instanceManager.addDartCreatedInstance(mockDownloadListener);
});
test('onDownloadStart', () {
late final List<Object> result;
when(mockDownloadListener.onDownloadStart).thenReturn(
(
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
) {
result = <Object>[
url,
userAgent,
contentDisposition,
mimetype,
contentLength,
];
},
);
flutterApi.onDownloadStart(
mockDownloadListenerInstanceId,
'url',
'userAgent',
'contentDescription',
'mimetype',
45,
);
expect(
result,
containsAllInOrder(<Object?>[
'url',
'userAgent',
'contentDescription',
'mimetype',
45,
]),
);
});
test('copy', () {
expect(
DownloadListener.detached(
onDownloadStart: (_, __, ____, _____, ______) {},
).copy(),
isA<DownloadListener>(),
);
});
});
group('WebChromeClient', () {
late WebChromeClientFlutterApiImpl flutterApi;
late InstanceManager instanceManager;
late MockWebChromeClient mockWebChromeClient;
late int mockWebChromeClientInstanceId;
late MockWebView mockWebView;
late int mockWebViewInstanceId;
setUp(() {
instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {});
flutterApi = WebChromeClientFlutterApiImpl(
instanceManager: instanceManager,
);
mockWebChromeClient = MockWebChromeClient();
when(mockWebChromeClient.copy()).thenReturn(MockWebChromeClient());
mockWebChromeClientInstanceId =
instanceManager.addDartCreatedInstance(mockWebChromeClient);
mockWebView = MockWebView();
when(mockWebView.copy()).thenReturn(MockWebView());
mockWebViewInstanceId =
instanceManager.addDartCreatedInstance(mockWebView);
});
test('onProgressChanged', () {
late final List<Object> result;
when(mockWebChromeClient.onProgressChanged).thenReturn(
(WebView webView, int progress) {
result = <Object>[webView, progress];
},
);
flutterApi.onProgressChanged(
mockWebChromeClientInstanceId,
mockWebViewInstanceId,
76,
);
expect(result, containsAllInOrder(<Object?>[mockWebView, 76]));
});
test('onGeolocationPermissionsShowPrompt', () async {
const String origin = 'https://www.example.com';
final GeolocationPermissionsCallback callback =
GeolocationPermissionsCallback.detached();
final int paramsId = instanceManager.addDartCreatedInstance(callback);
late final GeolocationPermissionsCallback outerCallback;
when(mockWebChromeClient.onGeolocationPermissionsShowPrompt).thenReturn(
(String origin, GeolocationPermissionsCallback callback) async {
outerCallback = callback;
},
);
flutterApi.onGeolocationPermissionsShowPrompt(
mockWebChromeClientInstanceId,
paramsId,
origin,
);
await expectLater(
outerCallback,
callback,
);
});
test('onShowFileChooser', () async {
late final List<Object> result;
when(mockWebChromeClient.onShowFileChooser).thenReturn(
(WebView webView, FileChooserParams params) {
result = <Object>[webView, params];
return Future<List<String>>.value(<String>['fileOne', 'fileTwo']);
},
);
final FileChooserParams params = FileChooserParams.detached(
isCaptureEnabled: false,
acceptTypes: <String>[],
filenameHint: 'filenameHint',
mode: FileChooserMode.open,
);
instanceManager.addHostCreatedInstance(params, 3);
await expectLater(
flutterApi.onShowFileChooser(
mockWebChromeClientInstanceId,
mockWebViewInstanceId,
3,
),
completion(<String>['fileOne', 'fileTwo']),
);
expect(result[0], mockWebView);
expect(result[1], params);
});
test('setSynchronousReturnValueForOnShowFileChooser', () {
final MockTestWebChromeClientHostApi mockHostApi =
MockTestWebChromeClientHostApi();
TestWebChromeClientHostApi.setup(mockHostApi);
WebChromeClient.api =
WebChromeClientHostApiImpl(instanceManager: instanceManager);
final WebChromeClient webChromeClient = WebChromeClient.detached();
instanceManager.addHostCreatedInstance(webChromeClient, 2);
webChromeClient.setSynchronousReturnValueForOnShowFileChooser(false);
verify(
mockHostApi.setSynchronousReturnValueForOnShowFileChooser(2, false),
);
});
test(
'setSynchronousReturnValueForOnShowFileChooser throws StateError when onShowFileChooser is null',
() {
final MockTestWebChromeClientHostApi mockHostApi =
MockTestWebChromeClientHostApi();
TestWebChromeClientHostApi.setup(mockHostApi);
WebChromeClient.api =
WebChromeClientHostApiImpl(instanceManager: instanceManager);
final WebChromeClient clientWithNullCallback =
WebChromeClient.detached();
instanceManager.addHostCreatedInstance(clientWithNullCallback, 2);
expect(
() => clientWithNullCallback
.setSynchronousReturnValueForOnShowFileChooser(true),
throwsStateError,
);
final WebChromeClient clientWithNonnullCallback =
WebChromeClient.detached(
onShowFileChooser: (_, __) async => <String>[],
);
instanceManager.addHostCreatedInstance(clientWithNonnullCallback, 3);
clientWithNonnullCallback
.setSynchronousReturnValueForOnShowFileChooser(true);
verify(
mockHostApi.setSynchronousReturnValueForOnShowFileChooser(3, true),
);
});
test('onPermissionRequest', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int instanceIdentifier = 0;
late final List<Object?> callbackParameters;
final WebChromeClient instance = WebChromeClient.detached(
onPermissionRequest: (
WebChromeClient instance,
PermissionRequest request,
) {
callbackParameters = <Object?>[
instance,
request,
];
},
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
final WebChromeClientFlutterApiImpl flutterApi =
WebChromeClientFlutterApiImpl(
instanceManager: instanceManager,
);
final PermissionRequest request = PermissionRequest.detached(
resources: <String>[],
binaryMessenger: null,
instanceManager: instanceManager,
);
const int requestIdentifier = 32;
instanceManager.addHostCreatedInstance(
request,
requestIdentifier,
);
flutterApi.onPermissionRequest(
instanceIdentifier,
requestIdentifier,
);
expect(callbackParameters, <Object?>[instance, request]);
});
test('onShowCustomView', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int instanceIdentifier = 0;
late final List<Object?> callbackParameters;
final WebChromeClient instance = WebChromeClient.detached(
onShowCustomView: (
WebChromeClient instance,
View view,
CustomViewCallback callback,
) {
callbackParameters = <Object?>[
instance,
view,
callback,
];
},
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
final WebChromeClientFlutterApiImpl flutterApi =
WebChromeClientFlutterApiImpl(
instanceManager: instanceManager,
);
final View view = View.detached(
instanceManager: instanceManager,
);
const int viewIdentifier = 50;
instanceManager.addHostCreatedInstance(view, viewIdentifier);
final CustomViewCallback callback = CustomViewCallback.detached(
instanceManager: instanceManager,
);
const int callbackIdentifier = 51;
instanceManager.addHostCreatedInstance(callback, callbackIdentifier);
flutterApi.onShowCustomView(
instanceIdentifier,
viewIdentifier,
callbackIdentifier,
);
expect(callbackParameters, <Object?>[
instance,
view,
callback,
]);
});
test('onHideCustomView', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int instanceIdentifier = 0;
late final List<Object?> callbackParameters;
final WebChromeClient instance = WebChromeClient.detached(
onHideCustomView: (
WebChromeClient instance,
) {
callbackParameters = <Object?>[
instance,
];
},
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
final WebChromeClientFlutterApiImpl flutterApi =
WebChromeClientFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.onHideCustomView(instanceIdentifier);
expect(callbackParameters, <Object?>[instance]);
});
test('onConsoleMessage', () async {
late final List<Object> result;
when(mockWebChromeClient.onConsoleMessage).thenReturn(
(WebChromeClient instance, ConsoleMessage message) {
result = <Object>[instance, message];
},
);
final ConsoleMessage message = ConsoleMessage(
lineNumber: 0,
message: 'message',
level: ConsoleMessageLevel.error,
sourceId: 'sourceId',
);
flutterApi.onConsoleMessage(
mockWebChromeClientInstanceId,
message,
);
expect(result[0], mockWebChromeClient);
expect(result[1], message);
});
test('setSynchronousReturnValueForOnConsoleMessage', () {
final MockTestWebChromeClientHostApi mockHostApi =
MockTestWebChromeClientHostApi();
TestWebChromeClientHostApi.setup(mockHostApi);
WebChromeClient.api =
WebChromeClientHostApiImpl(instanceManager: instanceManager);
final WebChromeClient webChromeClient = WebChromeClient.detached();
instanceManager.addHostCreatedInstance(webChromeClient, 2);
webChromeClient.setSynchronousReturnValueForOnConsoleMessage(false);
verify(
mockHostApi.setSynchronousReturnValueForOnConsoleMessage(2, false),
);
});
test(
'setSynchronousReturnValueForOnConsoleMessage throws StateError when onConsoleMessage is null',
() {
final MockTestWebChromeClientHostApi mockHostApi =
MockTestWebChromeClientHostApi();
TestWebChromeClientHostApi.setup(mockHostApi);
WebChromeClient.api =
WebChromeClientHostApiImpl(instanceManager: instanceManager);
final WebChromeClient clientWithNullCallback =
WebChromeClient.detached();
instanceManager.addHostCreatedInstance(clientWithNullCallback, 2);
expect(
() => clientWithNullCallback
.setSynchronousReturnValueForOnConsoleMessage(true),
throwsStateError,
);
final WebChromeClient clientWithNonnullCallback =
WebChromeClient.detached(
onConsoleMessage: (_, __) async {},
);
instanceManager.addHostCreatedInstance(clientWithNonnullCallback, 3);
clientWithNonnullCallback
.setSynchronousReturnValueForOnConsoleMessage(true);
verify(
mockHostApi.setSynchronousReturnValueForOnConsoleMessage(3, true),
);
});
test('copy', () {
expect(WebChromeClient.detached().copy(), isA<WebChromeClient>());
});
});
test('onGeolocationPermissionsHidePrompt', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
const int instanceIdentifier = 0;
late final List<Object?> callbackParameters;
final WebChromeClient instance = WebChromeClient.detached(
onGeolocationPermissionsHidePrompt: (WebChromeClient instance) {
callbackParameters = <Object?>[instance];
},
instanceManager: instanceManager,
);
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
final WebChromeClientFlutterApiImpl flutterApi =
WebChromeClientFlutterApiImpl(instanceManager: instanceManager);
flutterApi.onGeolocationPermissionsHidePrompt(instanceIdentifier);
expect(callbackParameters, <Object?>[instance]);
});
test('copy', () {
expect(WebChromeClient.detached().copy(), isA<WebChromeClient>());
});
});
group('FileChooserParams', () {
test('FlutterApi create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final FileChooserParamsFlutterApiImpl flutterApi =
FileChooserParamsFlutterApiImpl(
instanceManager: instanceManager,
);
flutterApi.create(
0,
false,
const <String>['my', 'list'],
FileChooserMode.openMultiple,
'filenameHint',
);
final FileChooserParams instance =
instanceManager.getInstanceWithWeakReference(0)! as FileChooserParams;
expect(instance.isCaptureEnabled, false);
expect(instance.acceptTypes, const <String>['my', 'list']);
expect(instance.mode, FileChooserMode.openMultiple);
expect(instance.filenameHint, 'filenameHint');
});
group('CustomViewCallback', () {
tearDown(() {
TestCustomViewCallbackHostApi.setup(null);
});
test('onCustomViewHidden', () async {
final MockTestCustomViewCallbackHostApi mockApi =
MockTestCustomViewCallbackHostApi();
TestCustomViewCallbackHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CustomViewCallback instance = CustomViewCallback.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
await instance.onCustomViewHidden();
verify(mockApi.onCustomViewHidden(instanceIdentifier));
});
test('FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CustomViewCallbackFlutterApiImpl api =
CustomViewCallbackFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
api.create(instanceIdentifier);
expect(
instanceManager.getInstanceWithWeakReference(instanceIdentifier),
isA<CustomViewCallback>(),
);
});
});
group('View', () {
test('FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final ViewFlutterApiImpl api = ViewFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
api.create(instanceIdentifier);
expect(
instanceManager.getInstanceWithWeakReference(instanceIdentifier),
isA<View>(),
);
});
});
});
group('CookieManager', () {
tearDown(() {
TestCookieManagerHostApi.setup(null);
});
test('instance', () {
final MockTestCookieManagerHostApi mockApi =
MockTestCookieManagerHostApi();
TestCookieManagerHostApi.setup(mockApi);
final CookieManager instance = CookieManager.instance;
verify(mockApi.attachInstance(
JavaObject.globalInstanceManager.getIdentifier(instance),
));
});
test('setCookie', () async {
final MockTestCookieManagerHostApi mockApi =
MockTestCookieManagerHostApi();
TestCookieManagerHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CookieManager instance = CookieManager.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
const String url = 'testString';
const String value = 'testString2';
await instance.setCookie(url, value);
verify(mockApi.setCookie(instanceIdentifier, url, value));
});
test('clearCookies', () async {
final MockTestCookieManagerHostApi mockApi =
MockTestCookieManagerHostApi();
TestCookieManagerHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CookieManager instance = CookieManager.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
const bool result = true;
when(mockApi.removeAllCookies(
instanceIdentifier,
)).thenAnswer((_) => Future<bool>.value(result));
expect(await instance.removeAllCookies(), result);
verify(mockApi.removeAllCookies(instanceIdentifier));
});
test('setAcceptThirdPartyCookies', () async {
final MockTestCookieManagerHostApi mockApi =
MockTestCookieManagerHostApi();
TestCookieManagerHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final CookieManager instance = CookieManager.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
final WebView webView = WebView.detached(
instanceManager: instanceManager,
);
const int webViewIdentifier = 4;
instanceManager.addHostCreatedInstance(webView, webViewIdentifier);
const bool accept = true;
await instance.setAcceptThirdPartyCookies(
webView,
accept,
);
verify(mockApi.setAcceptThirdPartyCookies(
instanceIdentifier,
webViewIdentifier,
accept,
));
});
});
group('WebStorage', () {
late MockTestWebStorageHostApi mockPlatformHostApi;
late WebStorage webStorage;
late int webStorageInstanceId;
setUp(() {
mockPlatformHostApi = MockTestWebStorageHostApi();
TestWebStorageHostApi.setup(mockPlatformHostApi);
webStorage = WebStorage();
webStorageInstanceId =
WebStorage.api.instanceManager.getIdentifier(webStorage)!;
});
test('create', () {
verify(mockPlatformHostApi.create(webStorageInstanceId));
});
test('deleteAllData', () {
webStorage.deleteAllData();
verify(mockPlatformHostApi.deleteAllData(webStorageInstanceId));
});
test('copy', () {
expect(WebStorage.detached().copy(), isA<WebStorage>());
});
});
group('PermissionRequest', () {
setUp(() {});
tearDown(() {
TestPermissionRequestHostApi.setup(null);
});
test('grant', () async {
final MockTestPermissionRequestHostApi mockApi =
MockTestPermissionRequestHostApi();
TestPermissionRequestHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final PermissionRequest instance = PermissionRequest.detached(
resources: <String>[],
binaryMessenger: null,
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
const List<String> resources = <String>[PermissionRequest.audioCapture];
await instance.grant(resources);
verify(mockApi.grant(
instanceIdentifier,
resources,
));
});
test('deny', () async {
final MockTestPermissionRequestHostApi mockApi =
MockTestPermissionRequestHostApi();
TestPermissionRequestHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final PermissionRequest instance = PermissionRequest.detached(
resources: <String>[],
binaryMessenger: null,
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
await instance.deny();
verify(mockApi.deny(instanceIdentifier));
});
});
group('GeolocationPermissionsCallback', () {
tearDown(() {
TestGeolocationPermissionsCallbackHostApi.setup(null);
});
test('invoke', () async {
final MockTestGeolocationPermissionsCallbackHostApi mockApi =
MockTestGeolocationPermissionsCallbackHostApi();
TestGeolocationPermissionsCallbackHostApi.setup(mockApi);
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final GeolocationPermissionsCallback instance =
GeolocationPermissionsCallback.detached(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
instanceManager.addHostCreatedInstance(instance, instanceIdentifier);
const String origin = 'testString';
const bool allow = true;
const bool retain = true;
await instance.invoke(
origin,
allow,
retain,
);
verify(mockApi.invoke(instanceIdentifier, origin, allow, retain));
});
test('Geolocation FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final GeolocationPermissionsCallbackFlutterApiImpl api =
GeolocationPermissionsCallbackFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
api.create(instanceIdentifier);
expect(
instanceManager.getInstanceWithWeakReference(instanceIdentifier),
isA<GeolocationPermissionsCallback>(),
);
});
test('FlutterAPI create', () {
final InstanceManager instanceManager = InstanceManager(
onWeakReferenceRemoved: (_) {},
);
final PermissionRequestFlutterApiImpl api =
PermissionRequestFlutterApiImpl(
instanceManager: instanceManager,
);
const int instanceIdentifier = 0;
api.create(instanceIdentifier, <String?>[]);
expect(
instanceManager.getInstanceWithWeakReference(instanceIdentifier),
isA<PermissionRequest>(),
);
});
});
}
| packages/packages/webview_flutter/webview_flutter_android/test/android_webview_test.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_android/test/android_webview_test.dart",
"repo_id": "packages",
"token_count": 20862
} | 1,050 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
/// Types of resources that can require permissions.
///
/// Platform specific implementations can create their own resource types.
///
/// This example demonstrates how to extend the [WebViewPermissionResourceType]
/// to create additional platform-specific types:
///
/// ```dart
/// class AndroidWebViewPermissionResourceType
/// extends WebViewPermissionResourceType {
/// const AndroidWebViewPermissionResourceType._(super.name);
///
/// static const AndroidWebViewPermissionResourceType midiSysex =
/// AndroidWebViewPermissionResourceType._('midiSysex');
///
/// static const AndroidWebViewPermissionResourceType protectedMediaId =
/// AndroidWebViewPermissionResourceType._('protectedMediaId');
/// }
///```
///
@immutable
class WebViewPermissionResourceType {
/// Constructs a [WebViewPermissionResourceType].
///
/// This should only be used by this class and subclasses in platform
/// implementations.
@protected
const WebViewPermissionResourceType(this.name);
/// Unique name of the resource type.
///
/// For platform implementations, this should match the name of variable.
final String name;
/// A media device that can capture video.
static const WebViewPermissionResourceType camera =
WebViewPermissionResourceType('camera');
/// A media device that can capture audio.
static const WebViewPermissionResourceType microphone =
WebViewPermissionResourceType('microphone');
}
/// Permissions request when web content requests access to protected resources.
///
/// A response MUST be provided by calling a provided method.
///
/// Platform specific implementations can add additional methods when extending
/// this class.
///
/// This example demonstrates how to extend the
/// [PlatformWebViewPermissionRequest] to provide additional platform-specific
/// features:
///
/// ```dart
/// class WebKitWebViewPermissionRequest extends PlatformWebViewPermissionRequest {
/// const WebKitWebViewPermissionRequest._({
/// required super.types,
/// required void Function(WKPermissionDecision decision) onDecision,
/// }) : _onDecision = onDecision;
///
/// final void Function(WKPermissionDecision) _onDecision;
///
/// @override
/// Future<void> grant() async {
/// _onDecision(WKPermissionDecision.grant);
/// }
///
/// @override
/// Future<void> deny() async {
/// _onDecision(WKPermissionDecision.deny);
/// }
///
/// Future<void> prompt() async {
/// _onDecision(WKPermissionDecision.prompt);
/// }
/// }
/// ```
@immutable
abstract class PlatformWebViewPermissionRequest {
/// Creates a [PlatformWebViewPermissionRequest].
const PlatformWebViewPermissionRequest({required this.types});
/// All resources access has been requested for.
final Set<WebViewPermissionResourceType> types;
/// Grant permission for the requested resource(s).
Future<void> grant();
/// Deny permission for the requested resource(s).
Future<void> deny();
}
| packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/platform_webview_permission_request.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/platform_webview_permission_request.dart",
"repo_id": "packages",
"token_count": 876
} | 1,051 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:html' as html;
import 'dart:ui_web' as ui_web;
import 'package:flutter/cupertino.dart';
import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
import 'content_type.dart';
import 'http_request_factory.dart';
/// An implementation of [PlatformWebViewControllerCreationParams] using Flutter
/// for Web API.
@immutable
class WebWebViewControllerCreationParams
extends PlatformWebViewControllerCreationParams {
/// Creates a new [AndroidWebViewControllerCreationParams] instance.
WebWebViewControllerCreationParams({
@visibleForTesting this.httpRequestFactory = const HttpRequestFactory(),
}) : super();
/// Creates a [WebWebViewControllerCreationParams] instance based on [PlatformWebViewControllerCreationParams].
WebWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebViewControllerCreationParams params, {
@visibleForTesting
HttpRequestFactory httpRequestFactory = const HttpRequestFactory(),
}) : this(httpRequestFactory: httpRequestFactory);
static int _nextIFrameId = 0;
/// Handles creating and sending URL requests.
final HttpRequestFactory httpRequestFactory;
/// The underlying element used as the WebView.
@visibleForTesting
final html.IFrameElement iFrame = html.IFrameElement()
..id = 'webView${_nextIFrameId++}'
..style.width = '100%'
..style.height = '100%'
..style.border = 'none';
}
/// An implementation of [PlatformWebViewController] using Flutter for Web API.
class WebWebViewController extends PlatformWebViewController {
/// Constructs a [WebWebViewController].
WebWebViewController(PlatformWebViewControllerCreationParams params)
: super.implementation(params is WebWebViewControllerCreationParams
? params
: WebWebViewControllerCreationParams
.fromPlatformWebViewControllerCreationParams(params));
WebWebViewControllerCreationParams get _webWebViewParams =>
params as WebWebViewControllerCreationParams;
@override
Future<void> loadHtmlString(String html, {String? baseUrl}) async {
// ignore: unsafe_html
_webWebViewParams.iFrame.src = Uri.dataFromString(
html,
mimeType: 'text/html',
encoding: utf8,
).toString();
}
@override
Future<void> loadRequest(LoadRequestParams params) async {
if (!params.uri.hasScheme) {
throw ArgumentError(
'LoadRequestParams#uri is required to have a scheme.');
}
if (params.headers.isEmpty &&
(params.body == null || params.body!.isEmpty) &&
params.method == LoadRequestMethod.get) {
// ignore: unsafe_html
_webWebViewParams.iFrame.src = params.uri.toString();
} else {
await _updateIFrameFromXhr(params);
}
}
/// Performs an AJAX request defined by [params].
Future<void> _updateIFrameFromXhr(LoadRequestParams params) async {
final html.HttpRequest httpReq =
await _webWebViewParams.httpRequestFactory.request(
params.uri.toString(),
method: params.method.serialize(),
requestHeaders: params.headers,
sendData: params.body,
);
final String header =
httpReq.getResponseHeader('content-type') ?? 'text/html';
final ContentType contentType = ContentType.parse(header);
final Encoding encoding = Encoding.getByName(contentType.charset) ?? utf8;
// ignore: unsafe_html
_webWebViewParams.iFrame.src = Uri.dataFromString(
httpReq.responseText ?? '',
mimeType: contentType.mimeType,
encoding: encoding,
).toString();
}
}
/// An implementation of [PlatformWebViewWidget] using Flutter the for Web API.
class WebWebViewWidget extends PlatformWebViewWidget {
/// Constructs a [WebWebViewWidget].
WebWebViewWidget(PlatformWebViewWidgetCreationParams params)
: super.implementation(params) {
final WebWebViewController controller =
params.controller as WebWebViewController;
ui_web.platformViewRegistry.registerViewFactory(
controller._webWebViewParams.iFrame.id,
(int viewId) => controller._webWebViewParams.iFrame,
);
}
@override
Widget build(BuildContext context) {
return HtmlElementView(
key: params.key,
viewType: (params.controller as WebWebViewController)
._webWebViewParams
.iFrame
.id,
);
}
}
| packages/packages/webview_flutter/webview_flutter_web/lib/src/web_webview_controller.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_web/lib/src/web_webview_controller.dart",
"repo_id": "packages",
"token_count": 1585
} | 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.
// Autogenerated from Pigeon (v13.0.0), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import "FWFGeneratedWebKitApis.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
/// Mirror of NSKeyValueObservingOptions.
///
/// See
/// https://developer.apple.com/documentation/foundation/nskeyvalueobservingoptions?language=objc.
@implementation FWFNSKeyValueObservingOptionsEnumBox
- (instancetype)initWithValue:(FWFNSKeyValueObservingOptionsEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Mirror of NSKeyValueChange.
///
/// See https://developer.apple.com/documentation/foundation/nskeyvaluechange?language=objc.
@implementation FWFNSKeyValueChangeEnumBox
- (instancetype)initWithValue:(FWFNSKeyValueChangeEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Mirror of NSKeyValueChangeKey.
///
/// See https://developer.apple.com/documentation/foundation/nskeyvaluechangekey?language=objc.
@implementation FWFNSKeyValueChangeKeyEnumBox
- (instancetype)initWithValue:(FWFNSKeyValueChangeKeyEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Mirror of WKUserScriptInjectionTime.
///
/// See https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime?language=objc.
@implementation FWFWKUserScriptInjectionTimeEnumBox
- (instancetype)initWithValue:(FWFWKUserScriptInjectionTimeEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Mirror of WKAudiovisualMediaTypes.
///
/// See
/// [WKAudiovisualMediaTypes](https://developer.apple.com/documentation/webkit/wkaudiovisualmediatypes?language=objc).
@implementation FWFWKAudiovisualMediaTypeEnumBox
- (instancetype)initWithValue:(FWFWKAudiovisualMediaTypeEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Mirror of WKWebsiteDataTypes.
///
/// See
/// https://developer.apple.com/documentation/webkit/wkwebsitedatarecord/data_store_record_types?language=objc.
@implementation FWFWKWebsiteDataTypeEnumBox
- (instancetype)initWithValue:(FWFWKWebsiteDataTypeEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Mirror of WKNavigationActionPolicy.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc.
@implementation FWFWKNavigationActionPolicyEnumBox
- (instancetype)initWithValue:(FWFWKNavigationActionPolicyEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Mirror of WKNavigationResponsePolicy.
///
/// See https://developer.apple.com/documentation/webkit/wknavigationactionpolicy?language=objc.
@implementation FWFWKNavigationResponsePolicyEnumBox
- (instancetype)initWithValue:(FWFWKNavigationResponsePolicyEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Mirror of NSHTTPCookiePropertyKey.
///
/// See https://developer.apple.com/documentation/foundation/nshttpcookiepropertykey.
@implementation FWFNSHttpCookiePropertyKeyEnumBox
- (instancetype)initWithValue:(FWFNSHttpCookiePropertyKeyEnum)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// An object that contains information about an action that causes navigation
/// to occur.
///
/// Wraps
/// [WKNavigationType](https://developer.apple.com/documentation/webkit/wknavigationaction?language=objc).
@implementation FWFWKNavigationTypeBox
- (instancetype)initWithValue:(FWFWKNavigationType)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Possible permission decisions for device resource access.
///
/// See https://developer.apple.com/documentation/webkit/wkpermissiondecision?language=objc.
@implementation FWFWKPermissionDecisionBox
- (instancetype)initWithValue:(FWFWKPermissionDecision)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// List of the types of media devices that can capture audio, video, or both.
///
/// See https://developer.apple.com/documentation/webkit/wkmediacapturetype?language=objc.
@implementation FWFWKMediaCaptureTypeBox
- (instancetype)initWithValue:(FWFWKMediaCaptureType)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Responses to an authentication challenge.
///
/// See
/// https://developer.apple.com/documentation/foundation/nsurlsessionauthchallengedisposition?language=objc.
@implementation FWFNSUrlSessionAuthChallengeDispositionBox
- (instancetype)initWithValue:(FWFNSUrlSessionAuthChallengeDisposition)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
/// Specifies how long a credential will be kept.
@implementation FWFNSUrlCredentialPersistenceBox
- (instancetype)initWithValue:(FWFNSUrlCredentialPersistence)value {
self = [super init];
if (self) {
_value = value;
}
return self;
}
@end
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 FWFNSKeyValueObservingOptionsEnumData ()
+ (FWFNSKeyValueObservingOptionsEnumData *)fromList:(NSArray *)list;
+ (nullable FWFNSKeyValueObservingOptionsEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSKeyValueChangeKeyEnumData ()
+ (FWFNSKeyValueChangeKeyEnumData *)fromList:(NSArray *)list;
+ (nullable FWFNSKeyValueChangeKeyEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKUserScriptInjectionTimeEnumData ()
+ (FWFWKUserScriptInjectionTimeEnumData *)fromList:(NSArray *)list;
+ (nullable FWFWKUserScriptInjectionTimeEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKAudiovisualMediaTypeEnumData ()
+ (FWFWKAudiovisualMediaTypeEnumData *)fromList:(NSArray *)list;
+ (nullable FWFWKAudiovisualMediaTypeEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKWebsiteDataTypeEnumData ()
+ (FWFWKWebsiteDataTypeEnumData *)fromList:(NSArray *)list;
+ (nullable FWFWKWebsiteDataTypeEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKNavigationActionPolicyEnumData ()
+ (FWFWKNavigationActionPolicyEnumData *)fromList:(NSArray *)list;
+ (nullable FWFWKNavigationActionPolicyEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSHttpCookiePropertyKeyEnumData ()
+ (FWFNSHttpCookiePropertyKeyEnumData *)fromList:(NSArray *)list;
+ (nullable FWFNSHttpCookiePropertyKeyEnumData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKPermissionDecisionData ()
+ (FWFWKPermissionDecisionData *)fromList:(NSArray *)list;
+ (nullable FWFWKPermissionDecisionData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKMediaCaptureTypeData ()
+ (FWFWKMediaCaptureTypeData *)fromList:(NSArray *)list;
+ (nullable FWFWKMediaCaptureTypeData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSUrlRequestData ()
+ (FWFNSUrlRequestData *)fromList:(NSArray *)list;
+ (nullable FWFNSUrlRequestData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSHttpUrlResponseData ()
+ (FWFNSHttpUrlResponseData *)fromList:(NSArray *)list;
+ (nullable FWFNSHttpUrlResponseData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKUserScriptData ()
+ (FWFWKUserScriptData *)fromList:(NSArray *)list;
+ (nullable FWFWKUserScriptData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKNavigationActionData ()
+ (FWFWKNavigationActionData *)fromList:(NSArray *)list;
+ (nullable FWFWKNavigationActionData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKNavigationResponseData ()
+ (FWFWKNavigationResponseData *)fromList:(NSArray *)list;
+ (nullable FWFWKNavigationResponseData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKFrameInfoData ()
+ (FWFWKFrameInfoData *)fromList:(NSArray *)list;
+ (nullable FWFWKFrameInfoData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSErrorData ()
+ (FWFNSErrorData *)fromList:(NSArray *)list;
+ (nullable FWFNSErrorData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKScriptMessageData ()
+ (FWFWKScriptMessageData *)fromList:(NSArray *)list;
+ (nullable FWFWKScriptMessageData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFWKSecurityOriginData ()
+ (FWFWKSecurityOriginData *)fromList:(NSArray *)list;
+ (nullable FWFWKSecurityOriginData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFNSHttpCookieData ()
+ (FWFNSHttpCookieData *)fromList:(NSArray *)list;
+ (nullable FWFNSHttpCookieData *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFObjectOrIdentifier ()
+ (FWFObjectOrIdentifier *)fromList:(NSArray *)list;
+ (nullable FWFObjectOrIdentifier *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@interface FWFAuthenticationChallengeResponse ()
+ (FWFAuthenticationChallengeResponse *)fromList:(NSArray *)list;
+ (nullable FWFAuthenticationChallengeResponse *)nullableFromList:(NSArray *)list;
- (NSArray *)toList;
@end
@implementation FWFNSKeyValueObservingOptionsEnumData
+ (instancetype)makeWithValue:(FWFNSKeyValueObservingOptionsEnum)value {
FWFNSKeyValueObservingOptionsEnumData *pigeonResult =
[[FWFNSKeyValueObservingOptionsEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFNSKeyValueObservingOptionsEnumData *)fromList:(NSArray *)list {
FWFNSKeyValueObservingOptionsEnumData *pigeonResult =
[[FWFNSKeyValueObservingOptionsEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFNSKeyValueObservingOptionsEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSKeyValueObservingOptionsEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFNSKeyValueChangeKeyEnumData
+ (instancetype)makeWithValue:(FWFNSKeyValueChangeKeyEnum)value {
FWFNSKeyValueChangeKeyEnumData *pigeonResult = [[FWFNSKeyValueChangeKeyEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFNSKeyValueChangeKeyEnumData *)fromList:(NSArray *)list {
FWFNSKeyValueChangeKeyEnumData *pigeonResult = [[FWFNSKeyValueChangeKeyEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFNSKeyValueChangeKeyEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSKeyValueChangeKeyEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKUserScriptInjectionTimeEnumData
+ (instancetype)makeWithValue:(FWFWKUserScriptInjectionTimeEnum)value {
FWFWKUserScriptInjectionTimeEnumData *pigeonResult =
[[FWFWKUserScriptInjectionTimeEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKUserScriptInjectionTimeEnumData *)fromList:(NSArray *)list {
FWFWKUserScriptInjectionTimeEnumData *pigeonResult =
[[FWFWKUserScriptInjectionTimeEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKUserScriptInjectionTimeEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKUserScriptInjectionTimeEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKAudiovisualMediaTypeEnumData
+ (instancetype)makeWithValue:(FWFWKAudiovisualMediaTypeEnum)value {
FWFWKAudiovisualMediaTypeEnumData *pigeonResult =
[[FWFWKAudiovisualMediaTypeEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKAudiovisualMediaTypeEnumData *)fromList:(NSArray *)list {
FWFWKAudiovisualMediaTypeEnumData *pigeonResult =
[[FWFWKAudiovisualMediaTypeEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKAudiovisualMediaTypeEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKAudiovisualMediaTypeEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKWebsiteDataTypeEnumData
+ (instancetype)makeWithValue:(FWFWKWebsiteDataTypeEnum)value {
FWFWKWebsiteDataTypeEnumData *pigeonResult = [[FWFWKWebsiteDataTypeEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKWebsiteDataTypeEnumData *)fromList:(NSArray *)list {
FWFWKWebsiteDataTypeEnumData *pigeonResult = [[FWFWKWebsiteDataTypeEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKWebsiteDataTypeEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKWebsiteDataTypeEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKNavigationActionPolicyEnumData
+ (instancetype)makeWithValue:(FWFWKNavigationActionPolicyEnum)value {
FWFWKNavigationActionPolicyEnumData *pigeonResult =
[[FWFWKNavigationActionPolicyEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKNavigationActionPolicyEnumData *)fromList:(NSArray *)list {
FWFWKNavigationActionPolicyEnumData *pigeonResult =
[[FWFWKNavigationActionPolicyEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKNavigationActionPolicyEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKNavigationActionPolicyEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFNSHttpCookiePropertyKeyEnumData
+ (instancetype)makeWithValue:(FWFNSHttpCookiePropertyKeyEnum)value {
FWFNSHttpCookiePropertyKeyEnumData *pigeonResult =
[[FWFNSHttpCookiePropertyKeyEnumData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFNSHttpCookiePropertyKeyEnumData *)fromList:(NSArray *)list {
FWFNSHttpCookiePropertyKeyEnumData *pigeonResult =
[[FWFNSHttpCookiePropertyKeyEnumData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFNSHttpCookiePropertyKeyEnumData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSHttpCookiePropertyKeyEnumData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKPermissionDecisionData
+ (instancetype)makeWithValue:(FWFWKPermissionDecision)value {
FWFWKPermissionDecisionData *pigeonResult = [[FWFWKPermissionDecisionData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKPermissionDecisionData *)fromList:(NSArray *)list {
FWFWKPermissionDecisionData *pigeonResult = [[FWFWKPermissionDecisionData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKPermissionDecisionData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKPermissionDecisionData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFWKMediaCaptureTypeData
+ (instancetype)makeWithValue:(FWFWKMediaCaptureType)value {
FWFWKMediaCaptureTypeData *pigeonResult = [[FWFWKMediaCaptureTypeData alloc] init];
pigeonResult.value = value;
return pigeonResult;
}
+ (FWFWKMediaCaptureTypeData *)fromList:(NSArray *)list {
FWFWKMediaCaptureTypeData *pigeonResult = [[FWFWKMediaCaptureTypeData alloc] init];
pigeonResult.value = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFWKMediaCaptureTypeData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKMediaCaptureTypeData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.value),
];
}
@end
@implementation FWFNSUrlRequestData
+ (instancetype)makeWithUrl:(NSString *)url
httpMethod:(nullable NSString *)httpMethod
httpBody:(nullable FlutterStandardTypedData *)httpBody
allHttpHeaderFields:(NSDictionary<NSString *, NSString *> *)allHttpHeaderFields {
FWFNSUrlRequestData *pigeonResult = [[FWFNSUrlRequestData alloc] init];
pigeonResult.url = url;
pigeonResult.httpMethod = httpMethod;
pigeonResult.httpBody = httpBody;
pigeonResult.allHttpHeaderFields = allHttpHeaderFields;
return pigeonResult;
}
+ (FWFNSUrlRequestData *)fromList:(NSArray *)list {
FWFNSUrlRequestData *pigeonResult = [[FWFNSUrlRequestData alloc] init];
pigeonResult.url = GetNullableObjectAtIndex(list, 0);
pigeonResult.httpMethod = GetNullableObjectAtIndex(list, 1);
pigeonResult.httpBody = GetNullableObjectAtIndex(list, 2);
pigeonResult.allHttpHeaderFields = GetNullableObjectAtIndex(list, 3);
return pigeonResult;
}
+ (nullable FWFNSUrlRequestData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSUrlRequestData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.url ?: [NSNull null],
self.httpMethod ?: [NSNull null],
self.httpBody ?: [NSNull null],
self.allHttpHeaderFields ?: [NSNull null],
];
}
@end
@implementation FWFNSHttpUrlResponseData
+ (instancetype)makeWithStatusCode:(NSInteger)statusCode {
FWFNSHttpUrlResponseData *pigeonResult = [[FWFNSHttpUrlResponseData alloc] init];
pigeonResult.statusCode = statusCode;
return pigeonResult;
}
+ (FWFNSHttpUrlResponseData *)fromList:(NSArray *)list {
FWFNSHttpUrlResponseData *pigeonResult = [[FWFNSHttpUrlResponseData alloc] init];
pigeonResult.statusCode = [GetNullableObjectAtIndex(list, 0) integerValue];
return pigeonResult;
}
+ (nullable FWFNSHttpUrlResponseData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSHttpUrlResponseData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.statusCode),
];
}
@end
@implementation FWFWKUserScriptData
+ (instancetype)makeWithSource:(NSString *)source
injectionTime:(nullable FWFWKUserScriptInjectionTimeEnumData *)injectionTime
isMainFrameOnly:(BOOL)isMainFrameOnly {
FWFWKUserScriptData *pigeonResult = [[FWFWKUserScriptData alloc] init];
pigeonResult.source = source;
pigeonResult.injectionTime = injectionTime;
pigeonResult.isMainFrameOnly = isMainFrameOnly;
return pigeonResult;
}
+ (FWFWKUserScriptData *)fromList:(NSArray *)list {
FWFWKUserScriptData *pigeonResult = [[FWFWKUserScriptData alloc] init];
pigeonResult.source = GetNullableObjectAtIndex(list, 0);
pigeonResult.injectionTime =
[FWFWKUserScriptInjectionTimeEnumData nullableFromList:(GetNullableObjectAtIndex(list, 1))];
pigeonResult.isMainFrameOnly = [GetNullableObjectAtIndex(list, 2) boolValue];
return pigeonResult;
}
+ (nullable FWFWKUserScriptData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKUserScriptData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.source ?: [NSNull null],
(self.injectionTime ? [self.injectionTime toList] : [NSNull null]),
@(self.isMainFrameOnly),
];
}
@end
@implementation FWFWKNavigationActionData
+ (instancetype)makeWithRequest:(FWFNSUrlRequestData *)request
targetFrame:(FWFWKFrameInfoData *)targetFrame
navigationType:(FWFWKNavigationType)navigationType {
FWFWKNavigationActionData *pigeonResult = [[FWFWKNavigationActionData alloc] init];
pigeonResult.request = request;
pigeonResult.targetFrame = targetFrame;
pigeonResult.navigationType = navigationType;
return pigeonResult;
}
+ (FWFWKNavigationActionData *)fromList:(NSArray *)list {
FWFWKNavigationActionData *pigeonResult = [[FWFWKNavigationActionData alloc] init];
pigeonResult.request = [FWFNSUrlRequestData nullableFromList:(GetNullableObjectAtIndex(list, 0))];
pigeonResult.targetFrame =
[FWFWKFrameInfoData nullableFromList:(GetNullableObjectAtIndex(list, 1))];
pigeonResult.navigationType = [GetNullableObjectAtIndex(list, 2) integerValue];
return pigeonResult;
}
+ (nullable FWFWKNavigationActionData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKNavigationActionData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.request ? [self.request toList] : [NSNull null]),
(self.targetFrame ? [self.targetFrame toList] : [NSNull null]),
@(self.navigationType),
];
}
@end
@implementation FWFWKNavigationResponseData
+ (instancetype)makeWithResponse:(FWFNSHttpUrlResponseData *)response
forMainFrame:(BOOL)forMainFrame {
FWFWKNavigationResponseData *pigeonResult = [[FWFWKNavigationResponseData alloc] init];
pigeonResult.response = response;
pigeonResult.forMainFrame = forMainFrame;
return pigeonResult;
}
+ (FWFWKNavigationResponseData *)fromList:(NSArray *)list {
FWFWKNavigationResponseData *pigeonResult = [[FWFWKNavigationResponseData alloc] init];
pigeonResult.response =
[FWFNSHttpUrlResponseData nullableFromList:(GetNullableObjectAtIndex(list, 0))];
pigeonResult.forMainFrame = [GetNullableObjectAtIndex(list, 1) boolValue];
return pigeonResult;
}
+ (nullable FWFWKNavigationResponseData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKNavigationResponseData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
(self.response ? [self.response toList] : [NSNull null]),
@(self.forMainFrame),
];
}
@end
@implementation FWFWKFrameInfoData
+ (instancetype)makeWithIsMainFrame:(BOOL)isMainFrame request:(FWFNSUrlRequestData *)request {
FWFWKFrameInfoData *pigeonResult = [[FWFWKFrameInfoData alloc] init];
pigeonResult.isMainFrame = isMainFrame;
pigeonResult.request = request;
return pigeonResult;
}
+ (FWFWKFrameInfoData *)fromList:(NSArray *)list {
FWFWKFrameInfoData *pigeonResult = [[FWFWKFrameInfoData alloc] init];
pigeonResult.isMainFrame = [GetNullableObjectAtIndex(list, 0) boolValue];
pigeonResult.request = [FWFNSUrlRequestData nullableFromList:(GetNullableObjectAtIndex(list, 1))];
return pigeonResult;
}
+ (nullable FWFWKFrameInfoData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKFrameInfoData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.isMainFrame),
(self.request ? [self.request toList] : [NSNull null]),
];
}
@end
@implementation FWFNSErrorData
+ (instancetype)makeWithCode:(NSInteger)code
domain:(NSString *)domain
userInfo:(nullable NSDictionary<NSString *, id> *)userInfo {
FWFNSErrorData *pigeonResult = [[FWFNSErrorData alloc] init];
pigeonResult.code = code;
pigeonResult.domain = domain;
pigeonResult.userInfo = userInfo;
return pigeonResult;
}
+ (FWFNSErrorData *)fromList:(NSArray *)list {
FWFNSErrorData *pigeonResult = [[FWFNSErrorData alloc] init];
pigeonResult.code = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.domain = GetNullableObjectAtIndex(list, 1);
pigeonResult.userInfo = GetNullableObjectAtIndex(list, 2);
return pigeonResult;
}
+ (nullable FWFNSErrorData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSErrorData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.code),
self.domain ?: [NSNull null],
self.userInfo ?: [NSNull null],
];
}
@end
@implementation FWFWKScriptMessageData
+ (instancetype)makeWithName:(NSString *)name body:(nullable id)body {
FWFWKScriptMessageData *pigeonResult = [[FWFWKScriptMessageData alloc] init];
pigeonResult.name = name;
pigeonResult.body = body;
return pigeonResult;
}
+ (FWFWKScriptMessageData *)fromList:(NSArray *)list {
FWFWKScriptMessageData *pigeonResult = [[FWFWKScriptMessageData alloc] init];
pigeonResult.name = GetNullableObjectAtIndex(list, 0);
pigeonResult.body = GetNullableObjectAtIndex(list, 1);
return pigeonResult;
}
+ (nullable FWFWKScriptMessageData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKScriptMessageData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.name ?: [NSNull null],
self.body ?: [NSNull null],
];
}
@end
@implementation FWFWKSecurityOriginData
+ (instancetype)makeWithHost:(NSString *)host port:(NSInteger)port protocol:(NSString *)protocol {
FWFWKSecurityOriginData *pigeonResult = [[FWFWKSecurityOriginData alloc] init];
pigeonResult.host = host;
pigeonResult.port = port;
pigeonResult.protocol = protocol;
return pigeonResult;
}
+ (FWFWKSecurityOriginData *)fromList:(NSArray *)list {
FWFWKSecurityOriginData *pigeonResult = [[FWFWKSecurityOriginData alloc] init];
pigeonResult.host = GetNullableObjectAtIndex(list, 0);
pigeonResult.port = [GetNullableObjectAtIndex(list, 1) integerValue];
pigeonResult.protocol = GetNullableObjectAtIndex(list, 2);
return pigeonResult;
}
+ (nullable FWFWKSecurityOriginData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFWKSecurityOriginData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.host ?: [NSNull null],
@(self.port),
self.protocol ?: [NSNull null],
];
}
@end
@implementation FWFNSHttpCookieData
+ (instancetype)makeWithPropertyKeys:(NSArray<FWFNSHttpCookiePropertyKeyEnumData *> *)propertyKeys
propertyValues:(NSArray<id> *)propertyValues {
FWFNSHttpCookieData *pigeonResult = [[FWFNSHttpCookieData alloc] init];
pigeonResult.propertyKeys = propertyKeys;
pigeonResult.propertyValues = propertyValues;
return pigeonResult;
}
+ (FWFNSHttpCookieData *)fromList:(NSArray *)list {
FWFNSHttpCookieData *pigeonResult = [[FWFNSHttpCookieData alloc] init];
pigeonResult.propertyKeys = GetNullableObjectAtIndex(list, 0);
pigeonResult.propertyValues = GetNullableObjectAtIndex(list, 1);
return pigeonResult;
}
+ (nullable FWFNSHttpCookieData *)nullableFromList:(NSArray *)list {
return (list) ? [FWFNSHttpCookieData fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.propertyKeys ?: [NSNull null],
self.propertyValues ?: [NSNull null],
];
}
@end
@implementation FWFObjectOrIdentifier
+ (instancetype)makeWithValue:(nullable id)value isIdentifier:(BOOL)isIdentifier {
FWFObjectOrIdentifier *pigeonResult = [[FWFObjectOrIdentifier alloc] init];
pigeonResult.value = value;
pigeonResult.isIdentifier = isIdentifier;
return pigeonResult;
}
+ (FWFObjectOrIdentifier *)fromList:(NSArray *)list {
FWFObjectOrIdentifier *pigeonResult = [[FWFObjectOrIdentifier alloc] init];
pigeonResult.value = GetNullableObjectAtIndex(list, 0);
pigeonResult.isIdentifier = [GetNullableObjectAtIndex(list, 1) boolValue];
return pigeonResult;
}
+ (nullable FWFObjectOrIdentifier *)nullableFromList:(NSArray *)list {
return (list) ? [FWFObjectOrIdentifier fromList:list] : nil;
}
- (NSArray *)toList {
return @[
self.value ?: [NSNull null],
@(self.isIdentifier),
];
}
@end
@implementation FWFAuthenticationChallengeResponse
+ (instancetype)makeWithDisposition:(FWFNSUrlSessionAuthChallengeDisposition)disposition
credentialIdentifier:(nullable NSNumber *)credentialIdentifier {
FWFAuthenticationChallengeResponse *pigeonResult =
[[FWFAuthenticationChallengeResponse alloc] init];
pigeonResult.disposition = disposition;
pigeonResult.credentialIdentifier = credentialIdentifier;
return pigeonResult;
}
+ (FWFAuthenticationChallengeResponse *)fromList:(NSArray *)list {
FWFAuthenticationChallengeResponse *pigeonResult =
[[FWFAuthenticationChallengeResponse alloc] init];
pigeonResult.disposition = [GetNullableObjectAtIndex(list, 0) integerValue];
pigeonResult.credentialIdentifier = GetNullableObjectAtIndex(list, 1);
return pigeonResult;
}
+ (nullable FWFAuthenticationChallengeResponse *)nullableFromList:(NSArray *)list {
return (list) ? [FWFAuthenticationChallengeResponse fromList:list] : nil;
}
- (NSArray *)toList {
return @[
@(self.disposition),
self.credentialIdentifier ?: [NSNull null],
];
}
@end
@interface FWFWKWebsiteDataStoreHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKWebsiteDataStoreHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFWKWebsiteDataTypeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKWebsiteDataStoreHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKWebsiteDataStoreHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFWKWebsiteDataTypeEnumData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKWebsiteDataStoreHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKWebsiteDataStoreHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKWebsiteDataStoreHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKWebsiteDataStoreHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKWebsiteDataStoreHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKWebsiteDataStoreHostApiCodecReaderWriter *readerWriter =
[[FWFWKWebsiteDataStoreHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpFWFWKWebsiteDataStoreHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKWebsiteDataStoreHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi."
@"createFromWebViewConfiguration"
binaryMessenger:binaryMessenger
codec:FWFWKWebsiteDataStoreHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(createFromWebViewConfigurationWithIdentifier:
configurationIdentifier:error:)],
@"FWFWKWebsiteDataStoreHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewConfigurationWithIdentifier:configurationIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_configurationIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
FlutterError *error;
[api createFromWebViewConfigurationWithIdentifier:arg_identifier
configurationIdentifier:arg_configurationIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi."
@"createDefaultDataStore"
binaryMessenger:binaryMessenger
codec:FWFWKWebsiteDataStoreHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createDefaultDataStoreWithIdentifier:error:)],
@"FWFWKWebsiteDataStoreHostApi api (%@) doesn't respond to "
@"@selector(createDefaultDataStoreWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api createDefaultDataStoreWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebsiteDataStoreHostApi."
@"removeDataOfTypes"
binaryMessenger:binaryMessenger
codec:FWFWKWebsiteDataStoreHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector
(removeDataFromDataStoreWithIdentifier:ofTypes:modifiedSince:completion:)],
@"FWFWKWebsiteDataStoreHostApi api (%@) doesn't respond to "
@"@selector(removeDataFromDataStoreWithIdentifier:ofTypes:modifiedSince:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSArray<FWFWKWebsiteDataTypeEnumData *> *arg_dataTypes = GetNullableObjectAtIndex(args, 1);
double arg_modificationTimeInSecondsSinceEpoch =
[GetNullableObjectAtIndex(args, 2) doubleValue];
[api removeDataFromDataStoreWithIdentifier:arg_identifier
ofTypes:arg_dataTypes
modifiedSince:arg_modificationTimeInSecondsSinceEpoch
completion:^(NSNumber *_Nullable output,
FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFUIViewHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFUIViewHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFUIViewHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setBackgroundColor"
binaryMessenger:binaryMessenger
codec:FWFUIViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setBackgroundColorForViewWithIdentifier:
toValue:error:)],
@"FWFUIViewHostApi api (%@) doesn't respond to "
@"@selector(setBackgroundColorForViewWithIdentifier:toValue:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSNumber *arg_value = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setBackgroundColorForViewWithIdentifier:arg_identifier toValue:arg_value error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.UIViewHostApi.setOpaque"
binaryMessenger:binaryMessenger
codec:FWFUIViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setOpaqueForViewWithIdentifier:isOpaque:error:)],
@"FWFUIViewHostApi api (%@) doesn't respond to "
@"@selector(setOpaqueForViewWithIdentifier:isOpaque:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
BOOL arg_opaque = [GetNullableObjectAtIndex(args, 1) boolValue];
FlutterError *error;
[api setOpaqueForViewWithIdentifier:arg_identifier isOpaque:arg_opaque error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFUIScrollViewHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFUIScrollViewHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFUIScrollViewHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.createFromWebView"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createFromWebViewWithIdentifier:
webViewIdentifier:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewWithIdentifier:webViewIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_webViewIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
FlutterError *error;
[api createFromWebViewWithIdentifier:arg_identifier
webViewIdentifier:arg_webViewIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.getContentOffset"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(contentOffsetForScrollViewWithIdentifier:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(contentOffsetForScrollViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
NSArray<NSNumber *> *output = [api contentOffsetForScrollViewWithIdentifier:arg_identifier
error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.scrollBy"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(scrollByForScrollViewWithIdentifier:x:y:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(scrollByForScrollViewWithIdentifier:x:y:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
double arg_x = [GetNullableObjectAtIndex(args, 1) doubleValue];
double arg_y = [GetNullableObjectAtIndex(args, 2) doubleValue];
FlutterError *error;
[api scrollByForScrollViewWithIdentifier:arg_identifier x:arg_x y:arg_y error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setContentOffset"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setContentOffsetForScrollViewWithIdentifier:toX:y:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(setContentOffsetForScrollViewWithIdentifier:toX:y:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
double arg_x = [GetNullableObjectAtIndex(args, 1) doubleValue];
double arg_y = [GetNullableObjectAtIndex(args, 2) doubleValue];
FlutterError *error;
[api setContentOffsetForScrollViewWithIdentifier:arg_identifier
toX:arg_x
y:arg_y
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewHostApi.setDelegate"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setDelegateForScrollViewWithIdentifier:
uiScrollViewDelegateIdentifier:error:)],
@"FWFUIScrollViewHostApi api (%@) doesn't respond to "
@"@selector(setDelegateForScrollViewWithIdentifier:uiScrollViewDelegateIdentifier:"
@"error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSNumber *arg_uiScrollViewDelegateIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setDelegateForScrollViewWithIdentifier:arg_identifier
uiScrollViewDelegateIdentifier:arg_uiScrollViewDelegateIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFWKWebViewConfigurationHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKWebViewConfigurationHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFWKAudiovisualMediaTypeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKWebViewConfigurationHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKWebViewConfigurationHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFWKAudiovisualMediaTypeEnumData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKWebViewConfigurationHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKWebViewConfigurationHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKWebViewConfigurationHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKWebViewConfigurationHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKWebViewConfigurationHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKWebViewConfigurationHostApiCodecReaderWriter *readerWriter =
[[FWFWKWebViewConfigurationHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpFWFWKWebViewConfigurationHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKWebViewConfigurationHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKWebViewConfigurationHostApi.createFromWebView"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createFromWebViewWithIdentifier:
webViewIdentifier:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewWithIdentifier:webViewIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_webViewIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
FlutterError *error;
[api createFromWebViewWithIdentifier:arg_identifier
webViewIdentifier:arg_webViewIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKWebViewConfigurationHostApi.setAllowsInlineMediaPlayback"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector
(setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:isAllowed:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:isAllowed:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
BOOL arg_allow = [GetNullableObjectAtIndex(args, 1) boolValue];
FlutterError *error;
[api setAllowsInlineMediaPlaybackForConfigurationWithIdentifier:arg_identifier
isAllowed:arg_allow
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKWebViewConfigurationHostApi.setLimitsNavigationsToAppBoundDomains"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setLimitsNavigationsToAppBoundDomainsForConfigurationWithIdentifier:
isLimited:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(setLimitsNavigationsToAppBoundDomainsForConfigurationWithIdentifier:"
@"isLimited:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
BOOL arg_limit = [GetNullableObjectAtIndex(args, 1) boolValue];
FlutterError *error;
[api setLimitsNavigationsToAppBoundDomainsForConfigurationWithIdentifier:arg_identifier
isLimited:arg_limit
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKWebViewConfigurationHostApi.setMediaTypesRequiringUserActionForPlayback"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewConfigurationHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setMediaTypesRequiresUserActionForConfigurationWithIdentifier:
forTypes:error:)],
@"FWFWKWebViewConfigurationHostApi api (%@) doesn't respond to "
@"@selector(setMediaTypesRequiresUserActionForConfigurationWithIdentifier:forTypes:"
@"error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSArray<FWFWKAudiovisualMediaTypeEnumData *> *arg_types = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setMediaTypesRequiresUserActionForConfigurationWithIdentifier:arg_identifier
forTypes:arg_types
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFWKWebViewConfigurationFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
@interface FWFWKWebViewConfigurationFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFWKWebViewConfigurationFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)createWithIdentifier:(NSInteger)arg_identifier
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewConfigurationFlutterApi.create"
binaryMessenger:self.binaryMessenger
codec:FWFWKWebViewConfigurationFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier) ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
@interface FWFWKUserContentControllerHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKUserContentControllerHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFWKUserScriptData fromList:[self readValue]];
case 129:
return [FWFWKUserScriptInjectionTimeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKUserContentControllerHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKUserContentControllerHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFWKUserScriptData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKUserScriptInjectionTimeEnumData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKUserContentControllerHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKUserContentControllerHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKUserContentControllerHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKUserContentControllerHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKUserContentControllerHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKUserContentControllerHostApiCodecReaderWriter *readerWriter =
[[FWFWKUserContentControllerHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpFWFWKUserContentControllerHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKUserContentControllerHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKUserContentControllerHostApi.createFromWebViewConfiguration"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(createFromWebViewConfigurationWithIdentifier:
configurationIdentifier:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewConfigurationWithIdentifier:configurationIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_configurationIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
FlutterError *error;
[api createFromWebViewConfigurationWithIdentifier:arg_identifier
configurationIdentifier:arg_configurationIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKUserContentControllerHostApi.addScriptMessageHandler"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(addScriptMessageHandlerForControllerWithIdentifier:
handlerIdentifier:ofName:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(addScriptMessageHandlerForControllerWithIdentifier:handlerIdentifier:"
@"ofName:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_handlerIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
NSString *arg_name = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api addScriptMessageHandlerForControllerWithIdentifier:arg_identifier
handlerIdentifier:arg_handlerIdentifier
ofName:arg_name
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKUserContentControllerHostApi.removeScriptMessageHandler"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(removeScriptMessageHandlerForControllerWithIdentifier:name:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(removeScriptMessageHandlerForControllerWithIdentifier:name:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSString *arg_name = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api removeScriptMessageHandlerForControllerWithIdentifier:arg_identifier
name:arg_name
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKUserContentControllerHostApi.removeAllScriptMessageHandlers"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(removeAllScriptMessageHandlersForControllerWithIdentifier:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(removeAllScriptMessageHandlersForControllerWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api removeAllScriptMessageHandlersForControllerWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKUserContentControllerHostApi.addUserScript"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(addUserScriptForControllerWithIdentifier:
userScript:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(addUserScriptForControllerWithIdentifier:userScript:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FWFWKUserScriptData *arg_userScript = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api addUserScriptForControllerWithIdentifier:arg_identifier
userScript:arg_userScript
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKUserContentControllerHostApi.removeAllUserScripts"
binaryMessenger:binaryMessenger
codec:FWFWKUserContentControllerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(removeAllUserScriptsForControllerWithIdentifier:error:)],
@"FWFWKUserContentControllerHostApi api (%@) doesn't respond to "
@"@selector(removeAllUserScriptsForControllerWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api removeAllUserScriptsForControllerWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFWKPreferencesHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFWKPreferencesHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKPreferencesHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi."
@"createFromWebViewConfiguration"
binaryMessenger:binaryMessenger
codec:FWFWKPreferencesHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(createFromWebViewConfigurationWithIdentifier:
configurationIdentifier:error:)],
@"FWFWKPreferencesHostApi api (%@) doesn't respond to "
@"@selector(createFromWebViewConfigurationWithIdentifier:configurationIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_configurationIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
FlutterError *error;
[api createFromWebViewConfigurationWithIdentifier:arg_identifier
configurationIdentifier:arg_configurationIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKPreferencesHostApi."
@"setJavaScriptEnabled"
binaryMessenger:binaryMessenger
codec:FWFWKPreferencesHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setJavaScriptEnabledForPreferencesWithIdentifier:isEnabled:error:)],
@"FWFWKPreferencesHostApi api (%@) doesn't respond to "
@"@selector(setJavaScriptEnabledForPreferencesWithIdentifier:isEnabled:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
BOOL arg_enabled = [GetNullableObjectAtIndex(args, 1) boolValue];
FlutterError *error;
[api setJavaScriptEnabledForPreferencesWithIdentifier:arg_identifier
isEnabled:arg_enabled
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFWKScriptMessageHandlerHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFWKScriptMessageHandlerHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKScriptMessageHandlerHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKScriptMessageHandlerHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKScriptMessageHandlerHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFWKScriptMessageHandlerHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFWKScriptMessageHandlerFlutterApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKScriptMessageHandlerFlutterApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFWKScriptMessageData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKScriptMessageHandlerFlutterApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKScriptMessageHandlerFlutterApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFWKScriptMessageData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKScriptMessageHandlerFlutterApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKScriptMessageHandlerFlutterApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKScriptMessageHandlerFlutterApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKScriptMessageHandlerFlutterApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKScriptMessageHandlerFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKScriptMessageHandlerFlutterApiCodecReaderWriter *readerWriter =
[[FWFWKScriptMessageHandlerFlutterApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
@interface FWFWKScriptMessageHandlerFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFWKScriptMessageHandlerFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)
didReceiveScriptMessageForHandlerWithIdentifier:(NSInteger)arg_identifier
userContentControllerIdentifier:(NSInteger)arg_userContentControllerIdentifier
message:(FWFWKScriptMessageData *)arg_message
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKScriptMessageHandlerFlutterApi.didReceiveScriptMessage"
binaryMessenger:self.binaryMessenger
codec:FWFWKScriptMessageHandlerFlutterApiGetCodec()];
[channel
sendMessage:@[
@(arg_identifier), @(arg_userContentControllerIdentifier), arg_message ?: [NSNull null]
]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
NSObject<FlutterMessageCodec> *FWFWKNavigationDelegateHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFWKNavigationDelegateHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKNavigationDelegateHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKNavigationDelegateHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKNavigationDelegateHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFWKNavigationDelegateHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFWKNavigationDelegateFlutterApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKNavigationDelegateFlutterApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFAuthenticationChallengeResponse fromList:[self readValue]];
case 129:
return [FWFNSErrorData fromList:[self readValue]];
case 130:
return [FWFNSHttpUrlResponseData fromList:[self readValue]];
case 131:
return [FWFNSUrlRequestData fromList:[self readValue]];
case 132:
return [FWFWKFrameInfoData fromList:[self readValue]];
case 133:
return [FWFWKNavigationActionData fromList:[self readValue]];
case 134:
return [FWFWKNavigationActionPolicyEnumData fromList:[self readValue]];
case 135:
return [FWFWKNavigationResponseData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKNavigationDelegateFlutterApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKNavigationDelegateFlutterApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFAuthenticationChallengeResponse class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSErrorData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpUrlResponseData class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSUrlRequestData class]]) {
[self writeByte:131];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKFrameInfoData class]]) {
[self writeByte:132];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionData class]]) {
[self writeByte:133];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionPolicyEnumData class]]) {
[self writeByte:134];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationResponseData class]]) {
[self writeByte:135];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKNavigationDelegateFlutterApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKNavigationDelegateFlutterApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKNavigationDelegateFlutterApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKNavigationDelegateFlutterApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKNavigationDelegateFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKNavigationDelegateFlutterApiCodecReaderWriter *readerWriter =
[[FWFWKNavigationDelegateFlutterApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
@interface FWFWKNavigationDelegateFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFWKNavigationDelegateFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)didFinishNavigationForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
URL:(nullable NSString *)arg_url
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKNavigationDelegateFlutterApi.didFinishNavigation"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), @(arg_webViewIdentifier), arg_url ?: [NSNull null] ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)didStartProvisionalNavigationForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
URL:(nullable NSString *)arg_url
completion:(void (^)(FlutterError *_Nullable))
completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKNavigationDelegateFlutterApi.didStartProvisionalNavigation"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), @(arg_webViewIdentifier), arg_url ?: [NSNull null] ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)decidePolicyForNavigationActionForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
navigationAction:(FWFWKNavigationActionData *)
arg_navigationAction
completion:
(void (^)(
FWFWKNavigationActionPolicyEnumData
*_Nullable,
FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKNavigationDelegateFlutterApi.decidePolicyForNavigationAction"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
@(arg_identifier), @(arg_webViewIdentifier), arg_navigationAction ?: [NSNull null]
]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion(nil, [FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
FWFWKNavigationActionPolicyEnumData *output =
reply[0] == [NSNull null] ? nil : reply[0];
completion(output, nil);
}
} else {
completion(nil, [FlutterError
errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)decidePolicyForNavigationResponseForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
navigationResponse:(FWFWKNavigationResponseData *)
arg_navigationResponse
completion:
(void (^)(
FWFWKNavigationResponsePolicyEnumBox
*_Nullable,
FlutterError *_Nullable))
completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKNavigationDelegateFlutterApi.decidePolicyForNavigationResponse"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
@(arg_identifier), @(arg_webViewIdentifier), arg_navigationResponse ?: [NSNull null]
]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion(nil, [FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
NSNumber *outputAsNumber = reply[0] == [NSNull null] ? nil : reply[0];
FWFWKNavigationResponsePolicyEnumBox *output =
outputAsNumber == nil ? nil
: [[FWFWKNavigationResponsePolicyEnumBox alloc]
initWithValue:[outputAsNumber integerValue]];
completion(output, nil);
}
} else {
completion(nil, [FlutterError
errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)didFailNavigationForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
error:(FWFNSErrorData *)arg_error
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKNavigationDelegateFlutterApi.didFailNavigation"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), @(arg_webViewIdentifier), arg_error ?: [NSNull null] ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)didFailProvisionalNavigationForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
error:(FWFNSErrorData *)arg_error
completion:(void (^)(FlutterError *_Nullable))
completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKNavigationDelegateFlutterApi.didFailProvisionalNavigation"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), @(arg_webViewIdentifier), arg_error ?: [NSNull null] ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)webViewWebContentProcessDidTerminateForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:
(NSInteger)arg_webViewIdentifier
completion:
(void (^)(FlutterError *_Nullable))
completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKNavigationDelegateFlutterApi.webViewWebContentProcessDidTerminate"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), @(arg_webViewIdentifier) ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)
didReceiveAuthenticationChallengeForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
challengeIdentifier:(NSInteger)arg_challengeIdentifier
completion:
(void (^)(FWFAuthenticationChallengeResponse
*_Nullable,
FlutterError *_Nullable))
completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"WKNavigationDelegateFlutterApi.didReceiveAuthenticationChallenge"
binaryMessenger:self.binaryMessenger
codec:FWFWKNavigationDelegateFlutterApiGetCodec()];
[channel sendMessage:@[ @(arg_identifier), @(arg_webViewIdentifier), @(arg_challengeIdentifier) ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion(nil, [FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
FWFAuthenticationChallengeResponse *output =
reply[0] == [NSNull null] ? nil : reply[0];
completion(output, nil);
}
} else {
completion(nil, [FlutterError
errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
@interface FWFNSObjectHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFNSObjectHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSKeyValueObservingOptionsEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFNSObjectHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFNSObjectHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSKeyValueObservingOptionsEnumData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFNSObjectHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFNSObjectHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFNSObjectHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFNSObjectHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFNSObjectHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFNSObjectHostApiCodecReaderWriter *readerWriter =
[[FWFNSObjectHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpFWFNSObjectHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFNSObjectHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.dispose"
binaryMessenger:binaryMessenger
codec:FWFNSObjectHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(disposeObjectWithIdentifier:error:)],
@"FWFNSObjectHostApi api (%@) doesn't respond to "
@"@selector(disposeObjectWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api disposeObjectWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.addObserver"
binaryMessenger:binaryMessenger
codec:FWFNSObjectHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(addObserverForObjectWithIdentifier:
observerIdentifier:keyPath:options:error:)],
@"FWFNSObjectHostApi api (%@) doesn't respond to "
@"@selector(addObserverForObjectWithIdentifier:observerIdentifier:keyPath:options:"
@"error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_observerIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
NSString *arg_keyPath = GetNullableObjectAtIndex(args, 2);
NSArray<FWFNSKeyValueObservingOptionsEnumData *> *arg_options =
GetNullableObjectAtIndex(args, 3);
FlutterError *error;
[api addObserverForObjectWithIdentifier:arg_identifier
observerIdentifier:arg_observerIdentifier
keyPath:arg_keyPath
options:arg_options
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectHostApi.removeObserver"
binaryMessenger:binaryMessenger
codec:FWFNSObjectHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(removeObserverForObjectWithIdentifier:
observerIdentifier:keyPath:error:)],
@"FWFNSObjectHostApi api (%@) doesn't respond to "
@"@selector(removeObserverForObjectWithIdentifier:observerIdentifier:keyPath:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_observerIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
NSString *arg_keyPath = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api removeObserverForObjectWithIdentifier:arg_identifier
observerIdentifier:arg_observerIdentifier
keyPath:arg_keyPath
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFNSObjectFlutterApiCodecReader : FlutterStandardReader
@end
@implementation FWFNSObjectFlutterApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSKeyValueChangeKeyEnumData fromList:[self readValue]];
case 129:
return [FWFObjectOrIdentifier fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFNSObjectFlutterApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFNSObjectFlutterApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSKeyValueChangeKeyEnumData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFObjectOrIdentifier class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFNSObjectFlutterApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFNSObjectFlutterApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFNSObjectFlutterApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFNSObjectFlutterApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFNSObjectFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFNSObjectFlutterApiCodecReaderWriter *readerWriter =
[[FWFNSObjectFlutterApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
@interface FWFNSObjectFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFNSObjectFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)observeValueForObjectWithIdentifier:(NSInteger)arg_identifier
keyPath:(NSString *)arg_keyPath
objectIdentifier:(NSInteger)arg_objectIdentifier
changeKeys:
(NSArray<FWFNSKeyValueChangeKeyEnumData *> *)arg_changeKeys
changeValues:(NSArray<FWFObjectOrIdentifier *> *)arg_changeValues
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.observeValue"
binaryMessenger:self.binaryMessenger
codec:FWFNSObjectFlutterApiGetCodec()];
[channel
sendMessage:@[
@(arg_identifier), arg_keyPath ?: [NSNull null], @(arg_objectIdentifier),
arg_changeKeys ?: [NSNull null], arg_changeValues ?: [NSNull null]
]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)disposeObjectWithIdentifier:(NSInteger)arg_identifier
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.NSObjectFlutterApi.dispose"
binaryMessenger:self.binaryMessenger
codec:FWFNSObjectFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier) ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
@interface FWFWKWebViewHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKWebViewHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFAuthenticationChallengeResponse fromList:[self readValue]];
case 129:
return [FWFNSErrorData fromList:[self readValue]];
case 130:
return [FWFNSHttpCookieData fromList:[self readValue]];
case 131:
return [FWFNSHttpCookiePropertyKeyEnumData fromList:[self readValue]];
case 132:
return [FWFNSHttpUrlResponseData fromList:[self readValue]];
case 133:
return [FWFNSKeyValueChangeKeyEnumData fromList:[self readValue]];
case 134:
return [FWFNSKeyValueObservingOptionsEnumData fromList:[self readValue]];
case 135:
return [FWFNSUrlRequestData fromList:[self readValue]];
case 136:
return [FWFObjectOrIdentifier fromList:[self readValue]];
case 137:
return [FWFWKAudiovisualMediaTypeEnumData fromList:[self readValue]];
case 138:
return [FWFWKFrameInfoData fromList:[self readValue]];
case 139:
return [FWFWKMediaCaptureTypeData fromList:[self readValue]];
case 140:
return [FWFWKNavigationActionData fromList:[self readValue]];
case 141:
return [FWFWKNavigationActionPolicyEnumData fromList:[self readValue]];
case 142:
return [FWFWKNavigationResponseData fromList:[self readValue]];
case 143:
return [FWFWKPermissionDecisionData fromList:[self readValue]];
case 144:
return [FWFWKScriptMessageData fromList:[self readValue]];
case 145:
return [FWFWKSecurityOriginData fromList:[self readValue]];
case 146:
return [FWFWKUserScriptData fromList:[self readValue]];
case 147:
return [FWFWKUserScriptInjectionTimeEnumData fromList:[self readValue]];
case 148:
return [FWFWKWebsiteDataTypeEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKWebViewHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKWebViewHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFAuthenticationChallengeResponse class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSErrorData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpCookieData class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpCookiePropertyKeyEnumData class]]) {
[self writeByte:131];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpUrlResponseData class]]) {
[self writeByte:132];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSKeyValueChangeKeyEnumData class]]) {
[self writeByte:133];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSKeyValueObservingOptionsEnumData class]]) {
[self writeByte:134];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSUrlRequestData class]]) {
[self writeByte:135];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFObjectOrIdentifier class]]) {
[self writeByte:136];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKAudiovisualMediaTypeEnumData class]]) {
[self writeByte:137];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKFrameInfoData class]]) {
[self writeByte:138];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKMediaCaptureTypeData class]]) {
[self writeByte:139];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionData class]]) {
[self writeByte:140];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionPolicyEnumData class]]) {
[self writeByte:141];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationResponseData class]]) {
[self writeByte:142];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKPermissionDecisionData class]]) {
[self writeByte:143];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKScriptMessageData class]]) {
[self writeByte:144];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKSecurityOriginData class]]) {
[self writeByte:145];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKUserScriptData class]]) {
[self writeByte:146];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKUserScriptInjectionTimeEnumData class]]) {
[self writeByte:147];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKWebsiteDataTypeEnumData class]]) {
[self writeByte:148];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKWebViewHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKWebViewHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKWebViewHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKWebViewHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKWebViewHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKWebViewHostApiCodecReaderWriter *readerWriter =
[[FWFWKWebViewHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpFWFWKWebViewHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKWebViewHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:
configurationIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:configurationIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_configurationIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
FlutterError *error;
[api createWithIdentifier:arg_identifier
configurationIdentifier:arg_configurationIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setUIDelegate"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setUIDelegateForWebViewWithIdentifier:
delegateIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setUIDelegateForWebViewWithIdentifier:delegateIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSNumber *arg_uiDelegateIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setUIDelegateForWebViewWithIdentifier:arg_identifier
delegateIdentifier:arg_uiDelegateIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi."
@"setNavigationDelegate"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector(setNavigationDelegateForWebViewWithIdentifier:
delegateIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setNavigationDelegateForWebViewWithIdentifier:delegateIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSNumber *arg_navigationDelegateIdentifier = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setNavigationDelegateForWebViewWithIdentifier:arg_identifier
delegateIdentifier:arg_navigationDelegateIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getUrl"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(URLForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(URLForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
NSString *output = [api URLForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getEstimatedProgress"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(estimatedProgressForWebViewWithIdentifier:
error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(estimatedProgressForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
NSNumber *output = [api estimatedProgressForWebViewWithIdentifier:arg_identifier
error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadRequest"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(loadRequestForWebViewWithIdentifier:
request:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(loadRequestForWebViewWithIdentifier:request:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FWFNSUrlRequestData *arg_request = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api loadRequestForWebViewWithIdentifier:arg_identifier request:arg_request error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadHtmlString"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(loadHTMLForWebViewWithIdentifier:
HTMLString:baseURL:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(loadHTMLForWebViewWithIdentifier:HTMLString:baseURL:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSString *arg_string = GetNullableObjectAtIndex(args, 1);
NSString *arg_baseUrl = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api loadHTMLForWebViewWithIdentifier:arg_identifier
HTMLString:arg_string
baseURL:arg_baseUrl
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFileUrl"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(loadFileForWebViewWithIdentifier:fileURL:readAccessURL:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(loadFileForWebViewWithIdentifier:fileURL:readAccessURL:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSString *arg_url = GetNullableObjectAtIndex(args, 1);
NSString *arg_readAccessUrl = GetNullableObjectAtIndex(args, 2);
FlutterError *error;
[api loadFileForWebViewWithIdentifier:arg_identifier
fileURL:arg_url
readAccessURL:arg_readAccessUrl
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.loadFlutterAsset"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(loadAssetForWebViewWithIdentifier:
assetKey:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(loadAssetForWebViewWithIdentifier:assetKey:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSString *arg_key = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api loadAssetForWebViewWithIdentifier:arg_identifier assetKey:arg_key error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoBack"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(canGoBackForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(canGoBackForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
NSNumber *output = [api canGoBackForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.canGoForward"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(canGoForwardForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(canGoForwardForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
NSNumber *output = [api canGoForwardForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goBack"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(goBackForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(goBackForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api goBackForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.goForward"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(goForwardForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(goForwardForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api goForwardForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.reload"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(reloadWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(reloadWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api reloadWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getTitle"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(titleForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(titleForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
NSString *output = [api titleForWebViewWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi."
@"setAllowsBackForwardNavigationGestures"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setAllowsBackForwardForWebViewWithIdentifier:isAllowed:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setAllowsBackForwardForWebViewWithIdentifier:isAllowed:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
BOOL arg_allow = [GetNullableObjectAtIndex(args, 1) boolValue];
FlutterError *error;
[api setAllowsBackForwardForWebViewWithIdentifier:arg_identifier
isAllowed:arg_allow
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setCustomUserAgent"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(setCustomUserAgentForWebViewWithIdentifier:userAgent:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setCustomUserAgentForWebViewWithIdentifier:userAgent:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSString *arg_userAgent = GetNullableObjectAtIndex(args, 1);
FlutterError *error;
[api setCustomUserAgentForWebViewWithIdentifier:arg_identifier
userAgent:arg_userAgent
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.evaluateJavaScript"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert(
[api respondsToSelector:@selector
(evaluateJavaScriptForWebViewWithIdentifier:javaScriptString:completion:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(evaluateJavaScriptForWebViewWithIdentifier:javaScriptString:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSString *arg_javaScriptString = GetNullableObjectAtIndex(args, 1);
[api evaluateJavaScriptForWebViewWithIdentifier:arg_identifier
javaScriptString:arg_javaScriptString
completion:^(id _Nullable output,
FlutterError *_Nullable error) {
callback(wrapResult(output, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.setInspectable"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setInspectableForWebViewWithIdentifier:
inspectable:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(setInspectableForWebViewWithIdentifier:inspectable:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
BOOL arg_inspectable = [GetNullableObjectAtIndex(args, 1) boolValue];
FlutterError *error;
[api setInspectableForWebViewWithIdentifier:arg_identifier
inspectable:arg_inspectable
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKWebViewHostApi.getCustomUserAgent"
binaryMessenger:binaryMessenger
codec:FWFWKWebViewHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(customUserAgentForWebViewWithIdentifier:error:)],
@"FWFWKWebViewHostApi api (%@) doesn't respond to "
@"@selector(customUserAgentForWebViewWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
NSString *output = [api customUserAgentForWebViewWithIdentifier:arg_identifier
error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFWKUIDelegateHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFWKUIDelegateHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKUIDelegateHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFWKUIDelegateHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFWKUIDelegateHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
@interface FWFWKUIDelegateFlutterApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKUIDelegateFlutterApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSUrlRequestData fromList:[self readValue]];
case 129:
return [FWFWKFrameInfoData fromList:[self readValue]];
case 130:
return [FWFWKMediaCaptureTypeData fromList:[self readValue]];
case 131:
return [FWFWKNavigationActionData fromList:[self readValue]];
case 132:
return [FWFWKPermissionDecisionData fromList:[self readValue]];
case 133:
return [FWFWKSecurityOriginData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKUIDelegateFlutterApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKUIDelegateFlutterApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSUrlRequestData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKFrameInfoData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKMediaCaptureTypeData class]]) {
[self writeByte:130];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKNavigationActionData class]]) {
[self writeByte:131];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKPermissionDecisionData class]]) {
[self writeByte:132];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFWKSecurityOriginData class]]) {
[self writeByte:133];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKUIDelegateFlutterApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKUIDelegateFlutterApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKUIDelegateFlutterApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKUIDelegateFlutterApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKUIDelegateFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKUIDelegateFlutterApiCodecReaderWriter *readerWriter =
[[FWFWKUIDelegateFlutterApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
@interface FWFWKUIDelegateFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFWKUIDelegateFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)onCreateWebViewForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
configurationIdentifier:(NSInteger)arg_configurationIdentifier
navigationAction:(FWFWKNavigationActionData *)arg_navigationAction
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi.onCreateWebView"
binaryMessenger:self.binaryMessenger
codec:FWFWKUIDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[
@(arg_identifier), @(arg_webViewIdentifier), @(arg_configurationIdentifier),
arg_navigationAction ?: [NSNull null]
]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)requestMediaCapturePermissionForDelegateWithIdentifier:(NSInteger)arg_identifier
webViewIdentifier:(NSInteger)arg_webViewIdentifier
origin:(FWFWKSecurityOriginData *)arg_origin
frame:(FWFWKFrameInfoData *)arg_frame
type:(FWFWKMediaCaptureTypeData *)arg_type
completion:
(void (^)(
FWFWKPermissionDecisionData *_Nullable,
FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi."
@"requestMediaCapturePermission"
binaryMessenger:self.binaryMessenger
codec:FWFWKUIDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[
@(arg_identifier), @(arg_webViewIdentifier), arg_origin ?: [NSNull null],
arg_frame ?: [NSNull null], arg_type ?: [NSNull null]
]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion(nil, [FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
FWFWKPermissionDecisionData *output = reply[0] == [NSNull null] ? nil : reply[0];
completion(output, nil);
}
} else {
completion(nil,
[FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)runJavaScriptAlertPanelForDelegateWithIdentifier:(NSInteger)arg_identifier
message:(NSString *)arg_message
frame:(FWFWKFrameInfoData *)arg_frame
completion:
(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi."
@"runJavaScriptAlertPanel"
binaryMessenger:self.binaryMessenger
codec:FWFWKUIDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), arg_message ?: [NSNull null], arg_frame ?: [NSNull null] ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)runJavaScriptConfirmPanelForDelegateWithIdentifier:(NSInteger)arg_identifier
message:(NSString *)arg_message
frame:(FWFWKFrameInfoData *)arg_frame
completion:
(void (^)(NSNumber *_Nullable,
FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi."
@"runJavaScriptConfirmPanel"
binaryMessenger:self.binaryMessenger
codec:FWFWKUIDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), arg_message ?: [NSNull null], arg_frame ?: [NSNull null] ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion(nil, [FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
NSNumber *output = reply[0] == [NSNull null] ? nil : reply[0];
completion(output, nil);
}
} else {
completion(nil,
[FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
- (void)runJavaScriptTextInputPanelForDelegateWithIdentifier:(NSInteger)arg_identifier
prompt:(NSString *)arg_prompt
defaultText:(NSString *)arg_defaultText
frame:(FWFWKFrameInfoData *)arg_frame
completion:(void (^)(NSString *_Nullable,
FlutterError *_Nullable))
completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKUIDelegateFlutterApi."
@"runJavaScriptTextInputPanel"
binaryMessenger:self.binaryMessenger
codec:FWFWKUIDelegateFlutterApiGetCodec()];
[channel sendMessage:@[
@(arg_identifier), arg_prompt ?: [NSNull null], arg_defaultText ?: [NSNull null],
arg_frame ?: [NSNull null]
]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion(nil, [FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
NSString *output = reply[0] == [NSNull null] ? nil : reply[0];
completion(output, nil);
}
} else {
completion(nil, [FlutterError
errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
@interface FWFWKHttpCookieStoreHostApiCodecReader : FlutterStandardReader
@end
@implementation FWFWKHttpCookieStoreHostApiCodecReader
- (nullable id)readValueOfType:(UInt8)type {
switch (type) {
case 128:
return [FWFNSHttpCookieData fromList:[self readValue]];
case 129:
return [FWFNSHttpCookiePropertyKeyEnumData fromList:[self readValue]];
default:
return [super readValueOfType:type];
}
}
@end
@interface FWFWKHttpCookieStoreHostApiCodecWriter : FlutterStandardWriter
@end
@implementation FWFWKHttpCookieStoreHostApiCodecWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[FWFNSHttpCookieData class]]) {
[self writeByte:128];
[self writeValue:[value toList]];
} else if ([value isKindOfClass:[FWFNSHttpCookiePropertyKeyEnumData class]]) {
[self writeByte:129];
[self writeValue:[value toList]];
} else {
[super writeValue:value];
}
}
@end
@interface FWFWKHttpCookieStoreHostApiCodecReaderWriter : FlutterStandardReaderWriter
@end
@implementation FWFWKHttpCookieStoreHostApiCodecReaderWriter
- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data {
return [[FWFWKHttpCookieStoreHostApiCodecWriter alloc] initWithData:data];
}
- (FlutterStandardReader *)readerWithData:(NSData *)data {
return [[FWFWKHttpCookieStoreHostApiCodecReader alloc] initWithData:data];
}
@end
NSObject<FlutterMessageCodec> *FWFWKHttpCookieStoreHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
static dispatch_once_t sPred = 0;
dispatch_once(&sPred, ^{
FWFWKHttpCookieStoreHostApiCodecReaderWriter *readerWriter =
[[FWFWKHttpCookieStoreHostApiCodecReaderWriter alloc] init];
sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter];
});
return sSharedObject;
}
void SetUpFWFWKHttpCookieStoreHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFWKHttpCookieStoreHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi."
@"createFromWebsiteDataStore"
binaryMessenger:binaryMessenger
codec:FWFWKHttpCookieStoreHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createFromWebsiteDataStoreWithIdentifier:
dataStoreIdentifier:error:)],
@"FWFWKHttpCookieStoreHostApi api (%@) doesn't respond to "
@"@selector(createFromWebsiteDataStoreWithIdentifier:dataStoreIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSInteger arg_websiteDataStoreIdentifier = [GetNullableObjectAtIndex(args, 1) integerValue];
FlutterError *error;
[api createFromWebsiteDataStoreWithIdentifier:arg_identifier
dataStoreIdentifier:arg_websiteDataStoreIdentifier
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.WKHttpCookieStoreHostApi.setCookie"
binaryMessenger:binaryMessenger
codec:FWFWKHttpCookieStoreHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(setCookieForStoreWithIdentifier:
cookie:completion:)],
@"FWFWKHttpCookieStoreHostApi api (%@) doesn't respond to "
@"@selector(setCookieForStoreWithIdentifier:cookie:completion:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FWFNSHttpCookieData *arg_cookie = GetNullableObjectAtIndex(args, 1);
[api setCookieForStoreWithIdentifier:arg_identifier
cookie:arg_cookie
completion:^(FlutterError *_Nullable error) {
callback(wrapResult(nil, error));
}];
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFNSUrlHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFNSUrlHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFNSUrlHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlHostApi.getAbsoluteString"
binaryMessenger:binaryMessenger
codec:FWFNSUrlHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(absoluteStringForNSURLWithIdentifier:error:)],
@"FWFNSUrlHostApi api (%@) doesn't respond to "
@"@selector(absoluteStringForNSURLWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
NSString *output = [api absoluteStringForNSURLWithIdentifier:arg_identifier error:&error];
callback(wrapResult(output, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFNSUrlFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
@interface FWFNSUrlFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFNSUrlFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)createWithIdentifier:(NSInteger)arg_identifier
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlFlutterApi.create"
binaryMessenger:self.binaryMessenger
codec:FWFNSUrlFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier) ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
NSObject<FlutterMessageCodec> *FWFUIScrollViewDelegateHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFUIScrollViewDelegateHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFUIScrollViewDelegateHostApi> *api) {
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.UIScrollViewDelegateHostApi.create"
binaryMessenger:binaryMessenger
codec:FWFUIScrollViewDelegateHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(createWithIdentifier:error:)],
@"FWFUIScrollViewDelegateHostApi api (%@) doesn't respond to "
@"@selector(createWithIdentifier:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
FlutterError *error;
[api createWithIdentifier:arg_identifier error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFUIScrollViewDelegateFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
@interface FWFUIScrollViewDelegateFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFUIScrollViewDelegateFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)scrollViewDidScrollWithIdentifier:(NSInteger)arg_identifier
UIScrollViewIdentifier:(NSInteger)arg_uiScrollViewIdentifier
x:(double)arg_x
y:(double)arg_y
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"UIScrollViewDelegateFlutterApi.scrollViewDidScroll"
binaryMessenger:self.binaryMessenger
codec:FWFUIScrollViewDelegateFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), @(arg_uiScrollViewIdentifier), @(arg_x), @(arg_y) ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
NSObject<FlutterMessageCodec> *FWFNSUrlCredentialHostApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
void SetUpFWFNSUrlCredentialHostApi(id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FWFNSUrlCredentialHostApi> *api) {
/// Create a new native instance and add it to the `InstanceManager`.
{
FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc]
initWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlCredentialHostApi.createWithUser"
binaryMessenger:binaryMessenger
codec:FWFNSUrlCredentialHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector
(createWithUserWithIdentifier:user:password:persistence:error:)],
@"FWFNSUrlCredentialHostApi api (%@) doesn't respond to "
@"@selector(createWithUserWithIdentifier:user:password:persistence:error:)",
api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
NSArray *args = message;
NSInteger arg_identifier = [GetNullableObjectAtIndex(args, 0) integerValue];
NSString *arg_user = GetNullableObjectAtIndex(args, 1);
NSString *arg_password = GetNullableObjectAtIndex(args, 2);
FWFNSUrlCredentialPersistence arg_persistence =
[GetNullableObjectAtIndex(args, 3) integerValue];
FlutterError *error;
[api createWithUserWithIdentifier:arg_identifier
user:arg_user
password:arg_password
persistence:arg_persistence
error:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
}
NSObject<FlutterMessageCodec> *FWFNSUrlProtectionSpaceFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
@interface FWFNSUrlProtectionSpaceFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFNSUrlProtectionSpaceFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)createWithIdentifier:(NSInteger)arg_identifier
host:(nullable NSString *)arg_host
realm:(nullable NSString *)arg_realm
authenticationMethod:(nullable NSString *)arg_authenticationMethod
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:
@"dev.flutter.pigeon.webview_flutter_wkwebview.NSUrlProtectionSpaceFlutterApi.create"
binaryMessenger:self.binaryMessenger
codec:FWFNSUrlProtectionSpaceFlutterApiGetCodec()];
[channel
sendMessage:@[
@(arg_identifier), arg_host ?: [NSNull null], arg_realm ?: [NSNull null],
arg_authenticationMethod ?: [NSNull null]
]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
NSObject<FlutterMessageCodec> *FWFNSUrlAuthenticationChallengeFlutterApiGetCodec(void) {
static FlutterStandardMessageCodec *sSharedObject = nil;
sSharedObject = [FlutterStandardMessageCodec sharedInstance];
return sSharedObject;
}
@interface FWFNSUrlAuthenticationChallengeFlutterApi ()
@property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger;
@end
@implementation FWFNSUrlAuthenticationChallengeFlutterApi
- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger {
self = [super init];
if (self) {
_binaryMessenger = binaryMessenger;
}
return self;
}
- (void)createWithIdentifier:(NSInteger)arg_identifier
protectionSpaceIdentifier:(NSInteger)arg_protectionSpaceIdentifier
completion:(void (^)(FlutterError *_Nullable))completion {
FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel
messageChannelWithName:@"dev.flutter.pigeon.webview_flutter_wkwebview."
@"NSUrlAuthenticationChallengeFlutterApi.create"
binaryMessenger:self.binaryMessenger
codec:FWFNSUrlAuthenticationChallengeFlutterApiGetCodec()];
[channel
sendMessage:@[ @(arg_identifier), @(arg_protectionSpaceIdentifier) ]
reply:^(NSArray<id> *reply) {
if (reply != nil) {
if (reply.count > 1) {
completion([FlutterError errorWithCode:reply[0]
message:reply[1]
details:reply[2]]);
} else {
completion(nil);
}
} else {
completion([FlutterError errorWithCode:@"channel-error"
message:@"Unable to establish connection on channel."
details:@""]);
}
}];
}
@end
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFGeneratedWebKitApis.m/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFGeneratedWebKitApis.m",
"repo_id": "packages",
"token_count": 73247
} | 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 <Flutter/Flutter.h>
#import <WebKit/WebKit.h>
#import "FWFGeneratedWebKitApis.h"
#import "FWFInstanceManager.h"
#import "FWFObjectHostApi.h"
NS_ASSUME_NONNULL_BEGIN
/// Flutter api implementation for WKWebViewConfiguration.
///
/// Handles making callbacks to Dart for a WKWebViewConfiguration.
@interface FWFWebViewConfigurationFlutterApiImpl : FWFWKWebViewConfigurationFlutterApi
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
- (void)createWithConfiguration:(WKWebViewConfiguration *)configuration
completion:(void (^)(FlutterError *_Nullable))completion;
@end
/// Implementation of WKWebViewConfiguration for FWFWebViewConfigurationHostApiImpl.
@interface FWFWebViewConfiguration : WKWebViewConfiguration
@property(readonly, nonnull, nonatomic) FWFObjectFlutterApiImpl *objectApi;
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
/// Host api implementation for WKWebViewConfiguration.
///
/// Handles creating WKWebViewConfiguration that intercommunicate with a paired Dart object.
@interface FWFWebViewConfigurationHostApiImpl : NSObject <FWFWKWebViewConfigurationHostApi>
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager;
@end
NS_ASSUME_NONNULL_END
| packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewConfigurationHostApi.h/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebViewConfigurationHostApi.h",
"repo_id": "packages",
"token_count": 562
} | 1,054 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../common/instance_manager.dart';
import '../common/web_kit.g.dart';
import 'foundation.dart';
export '../common/web_kit.g.dart'
show NSUrlCredentialPersistence, NSUrlSessionAuthChallengeDisposition;
Iterable<NSKeyValueObservingOptionsEnumData>
_toNSKeyValueObservingOptionsEnumData(
Iterable<NSKeyValueObservingOptions> options,
) {
return options.map<NSKeyValueObservingOptionsEnumData>((
NSKeyValueObservingOptions option,
) {
late final NSKeyValueObservingOptionsEnum? value;
switch (option) {
case NSKeyValueObservingOptions.newValue:
value = NSKeyValueObservingOptionsEnum.newValue;
case NSKeyValueObservingOptions.oldValue:
value = NSKeyValueObservingOptionsEnum.oldValue;
case NSKeyValueObservingOptions.initialValue:
value = NSKeyValueObservingOptionsEnum.initialValue;
case NSKeyValueObservingOptions.priorNotification:
value = NSKeyValueObservingOptionsEnum.priorNotification;
}
return NSKeyValueObservingOptionsEnumData(value: value);
});
}
extension _NSKeyValueChangeKeyEnumDataConverter on NSKeyValueChangeKeyEnumData {
NSKeyValueChangeKey toNSKeyValueChangeKey() {
return NSKeyValueChangeKey.values.firstWhere(
(NSKeyValueChangeKey element) => element.name == value.name,
);
}
}
/// Handles initialization of Flutter APIs for the Foundation library.
class FoundationFlutterApis {
/// Constructs a [FoundationFlutterApis].
@visibleForTesting
FoundationFlutterApis({
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) : _binaryMessenger = binaryMessenger,
object = NSObjectFlutterApiImpl(instanceManager: instanceManager),
url = NSUrlFlutterApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
urlProtectionSpace = NSUrlProtectionSpaceFlutterApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
urlAuthenticationChallenge = NSUrlAuthenticationChallengeFlutterApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
static FoundationFlutterApis _instance = FoundationFlutterApis();
/// Sets the global instance containing the Flutter Apis for the Foundation library.
@visibleForTesting
static set instance(FoundationFlutterApis instance) {
_instance = instance;
}
/// Global instance containing the Flutter Apis for the Foundation library.
static FoundationFlutterApis get instance {
return _instance;
}
final BinaryMessenger? _binaryMessenger;
bool _hasBeenSetUp = false;
/// Flutter Api for [NSObject].
@visibleForTesting
final NSObjectFlutterApiImpl object;
/// Flutter Api for [NSUrl].
@visibleForTesting
final NSUrlFlutterApiImpl url;
/// Flutter Api for [NSUrlProtectionSpace].
@visibleForTesting
final NSUrlProtectionSpaceFlutterApiImpl urlProtectionSpace;
/// Flutter Api for [NSUrlAuthenticationChallenge].
@visibleForTesting
final NSUrlAuthenticationChallengeFlutterApiImpl urlAuthenticationChallenge;
/// Ensures all the Flutter APIs have been set up to receive calls from native code.
void ensureSetUp() {
if (!_hasBeenSetUp) {
NSObjectFlutterApi.setup(
object,
binaryMessenger: _binaryMessenger,
);
NSUrlFlutterApi.setup(url, binaryMessenger: _binaryMessenger);
NSUrlProtectionSpaceFlutterApi.setup(
urlProtectionSpace,
binaryMessenger: _binaryMessenger,
);
NSUrlAuthenticationChallengeFlutterApi.setup(
urlAuthenticationChallenge,
binaryMessenger: _binaryMessenger,
);
_hasBeenSetUp = true;
}
}
}
/// Host api implementation for [NSObject].
class NSObjectHostApiImpl extends NSObjectHostApi {
/// Constructs an [NSObjectHostApiImpl].
NSObjectHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Sends binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with Objective-C objects.
final InstanceManager instanceManager;
/// Calls [addObserver] with the ids of the provided object instances.
Future<void> addObserverForInstances(
NSObject instance,
NSObject observer,
String keyPath,
Set<NSKeyValueObservingOptions> options,
) {
return addObserver(
instanceManager.getIdentifier(instance)!,
instanceManager.getIdentifier(observer)!,
keyPath,
_toNSKeyValueObservingOptionsEnumData(options).toList(),
);
}
/// Calls [removeObserver] with the ids of the provided object instances.
Future<void> removeObserverForInstances(
NSObject instance,
NSObject observer,
String keyPath,
) {
return removeObserver(
instanceManager.getIdentifier(instance)!,
instanceManager.getIdentifier(observer)!,
keyPath,
);
}
}
/// Flutter api implementation for [NSObject].
class NSObjectFlutterApiImpl extends NSObjectFlutterApi {
/// Constructs a [NSObjectFlutterApiImpl].
NSObjectFlutterApiImpl({InstanceManager? instanceManager})
: instanceManager = instanceManager ?? NSObject.globalInstanceManager;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
NSObject _getObject(int identifier) {
return instanceManager.getInstanceWithWeakReference(identifier)!;
}
@override
void observeValue(
int identifier,
String keyPath,
int objectIdentifier,
List<NSKeyValueChangeKeyEnumData?> changeKeys,
List<ObjectOrIdentifier?> changeValues,
) {
final void Function(String, NSObject, Map<NSKeyValueChangeKey, Object?>)?
function = _getObject(identifier).observeValue;
function?.call(
keyPath,
instanceManager.getInstanceWithWeakReference(objectIdentifier)!
as NSObject,
Map<NSKeyValueChangeKey, Object?>.fromIterables(
changeKeys.map<NSKeyValueChangeKey>(
(NSKeyValueChangeKeyEnumData? data) {
return data!.toNSKeyValueChangeKey();
},
),
changeValues.map<Object?>((ObjectOrIdentifier? value) {
if (value != null && value.isIdentifier) {
return instanceManager.getInstanceWithWeakReference(
value.value! as int,
);
}
return value?.value;
}),
),
);
}
@override
void dispose(int identifier) {
instanceManager.remove(identifier);
}
}
/// Host api implementation for [NSUrl].
class NSUrlHostApiImpl extends NSUrlHostApi {
/// Constructs an [NSUrlHostApiImpl].
NSUrlHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Sends binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with Objective-C objects.
final InstanceManager instanceManager;
/// Calls [getAbsoluteString] with the ids of the provided object instances.
Future<String?> getAbsoluteStringFromInstances(NSUrl instance) {
return getAbsoluteString(instanceManager.getIdentifier(instance)!);
}
}
/// Flutter API implementation 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.
class NSUrlFlutterApiImpl implements NSUrlFlutterApi {
/// Constructs a [NSUrlFlutterApiImpl].
NSUrlFlutterApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void create(int identifier) {
instanceManager.addHostCreatedInstance(
NSUrl.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
identifier,
);
}
}
/// Host api implementation for [NSUrlCredential].
class NSUrlCredentialHostApiImpl extends NSUrlCredentialHostApi {
/// Constructs an [NSUrlCredentialHostApiImpl].
NSUrlCredentialHostApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager,
super(binaryMessenger: binaryMessenger);
/// Sends binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with Objective-C objects.
final InstanceManager instanceManager;
/// Calls [createWithUser] with the ids of the provided object instances.
Future<void> createWithUserFromInstances(
NSUrlCredential instance,
String user,
String password,
NSUrlCredentialPersistence persistence,
) {
return createWithUser(
instanceManager.addDartCreatedInstance(instance),
user,
password,
persistence,
);
}
}
/// Flutter API implementation 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.
@protected
class NSUrlProtectionSpaceFlutterApiImpl
implements NSUrlProtectionSpaceFlutterApi {
/// Constructs a [NSUrlProtectionSpaceFlutterApiImpl].
NSUrlProtectionSpaceFlutterApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void create(
int identifier,
String? host,
String? realm,
String? authenticationMethod,
) {
instanceManager.addHostCreatedInstance(
NSUrlProtectionSpace.detached(
host: host,
realm: realm,
authenticationMethod: authenticationMethod,
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
identifier,
);
}
}
/// Flutter API implementation 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.
@protected
class NSUrlAuthenticationChallengeFlutterApiImpl
implements NSUrlAuthenticationChallengeFlutterApi {
/// Constructs a [NSUrlAuthenticationChallengeFlutterApiImpl].
NSUrlAuthenticationChallengeFlutterApiImpl({
this.binaryMessenger,
InstanceManager? instanceManager,
}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager;
/// Receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used which routes to
/// the host platform.
final BinaryMessenger? binaryMessenger;
/// Maintains instances stored to communicate with native language objects.
final InstanceManager instanceManager;
@override
void create(
int identifier,
int protectionSpaceIdentifier,
) {
instanceManager.addHostCreatedInstance(
NSUrlAuthenticationChallenge.detached(
protectionSpace: instanceManager.getInstanceWithWeakReference(
protectionSpaceIdentifier,
)!,
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
identifier,
);
}
}
| packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/foundation/foundation_api_impls.dart/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/foundation/foundation_api_impls.dart",
"repo_id": "packages",
"token_count": 4097
} | 1,055 |
name: webview_flutter_wkwebview
description: A Flutter plugin that provides a WebView widget based on Apple's WKWebView control.
repository: https://github.com/flutter/packages/tree/main/packages/webview_flutter/webview_flutter_wkwebview
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22
version: 3.13.0
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
implements: webview_flutter
platforms:
ios:
pluginClass: FLTWebViewFlutterPlugin
dartPluginClass: WebKitWebViewPlatform
dependencies:
flutter:
sdk: flutter
path: ^1.8.0
webview_flutter_platform_interface: ^2.10.0
dev_dependencies:
build_runner: ^2.1.5
flutter_test:
sdk: flutter
mockito: 5.4.4
pigeon: ^13.0.0
topics:
- html
- webview
- webview-flutter
| packages/packages/webview_flutter/webview_flutter_wkwebview/pubspec.yaml/0 | {
"file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/pubspec.yaml",
"repo_id": "packages",
"token_count": 352
} | 1,056 |
# Packages that are excluded from dart unit tests
#
# We exclude flutter_image because its tests need a test server,
# so are run via custom_package_tests.
- flutter_image
| packages/script/configs/dart_unit_tests_exceptions.yaml/0 | {
"file_path": "packages/script/configs/dart_unit_tests_exceptions.yaml",
"repo_id": "packages",
"token_count": 48
} | 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 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:pub_semver/pub_semver.dart';
/// Finding version of [package] that is published on pub.
class PubVersionFinder {
/// Constructor.
///
/// Note: you should manually close the [httpClient] when done using the finder.
PubVersionFinder({this.pubHost = defaultPubHost, required this.httpClient});
/// The default pub host to use.
static const String defaultPubHost = 'https://pub.dev';
/// The pub host url, defaults to `https://pub.dev`.
final String pubHost;
/// The http client.
///
/// You should manually close this client when done using this finder.
final http.Client httpClient;
/// Get the package version on pub.
Future<PubVersionFinderResponse> getPackageVersion(
{required String packageName}) async {
assert(packageName.isNotEmpty);
final Uri pubHostUri = Uri.parse(pubHost);
final Uri url = pubHostUri.replace(path: '/packages/$packageName.json');
final http.Response response = await httpClient.get(url);
if (response.statusCode == 404) {
return PubVersionFinderResponse(
versions: <Version>[],
result: PubVersionFinderResult.noPackageFound,
httpResponse: response);
} else if (response.statusCode != 200) {
return PubVersionFinderResponse(
versions: <Version>[],
result: PubVersionFinderResult.fail,
httpResponse: response);
}
final Map<Object?, Object?> responseBody =
json.decode(response.body) as Map<Object?, Object?>;
final List<Version> versions = (responseBody['versions']! as List<Object?>)
.cast<String>()
.map<Version>(
(final String versionString) => Version.parse(versionString))
.toList();
return PubVersionFinderResponse(
versions: versions,
result: PubVersionFinderResult.success,
httpResponse: response);
}
}
/// Represents a response for [PubVersionFinder].
class PubVersionFinderResponse {
/// Constructor.
PubVersionFinderResponse(
{required this.versions,
required this.result,
required this.httpResponse}) {
if (versions.isNotEmpty) {
versions.sort((Version a, Version b) {
// TODO(cyanglaz): Think about how to handle pre-release version with [Version.prioritize].
// https://github.com/flutter/flutter/issues/82222
return b.compareTo(a);
});
}
}
/// The versions found in [PubVersionFinder].
///
/// This is sorted by largest to smallest, so the first element in the list is the largest version.
/// Might be `null` if the [result] is not [PubVersionFinderResult.success].
final List<Version> versions;
/// The result of the version finder.
final PubVersionFinderResult result;
/// The response object of the http request.
final http.Response httpResponse;
}
/// An enum representing the result of [PubVersionFinder].
enum PubVersionFinderResult {
/// The version finder successfully found a version.
success,
/// The version finder failed to find a valid version.
///
/// This might due to http connection errors or user errors.
fail,
/// The version finder failed to locate the package.
///
/// This indicates the package is new.
noPackageFound,
}
| packages/script/tool/lib/src/common/pub_version_finder.dart/0 | {
"file_path": "packages/script/tool/lib/src/common/pub_version_finder.dart",
"repo_id": "packages",
"token_count": 1128
} | 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 'package:file/file.dart';
import 'common/package_command.dart';
import 'common/repository_package.dart';
/// A command to list different types of repository content.
class ListCommand extends PackageCommand {
/// Creates an instance of the list command, whose behavior depends on the
/// 'type' argument it provides.
ListCommand(
super.packagesDir, {
super.platform,
}) {
argParser.addOption(
_type,
defaultsTo: _package,
allowed: <String>[_package, _example, _allPackage, _file],
help: 'What type of file system content to list.',
);
}
static const String _type = 'type';
static const String _allPackage = 'package-or-subpackage';
static const String _example = 'example';
static const String _package = 'package';
static const String _file = 'file';
@override
final String name = 'list';
@override
final String description = 'Lists packages or files';
@override
Future<void> run() async {
switch (getStringArg(_type)) {
case _package:
await for (final PackageEnumerationEntry entry in getTargetPackages()) {
print(entry.package.path);
}
case _example:
final Stream<RepositoryPackage> examples = getTargetPackages()
.expand<RepositoryPackage>(
(PackageEnumerationEntry entry) => entry.package.getExamples());
await for (final RepositoryPackage package in examples) {
print(package.path);
}
case _allPackage:
await for (final PackageEnumerationEntry entry
in getTargetPackagesAndSubpackages()) {
print(entry.package.path);
}
case _file:
await for (final File file in getFiles()) {
print(file.path);
}
}
}
}
| packages/script/tool/lib/src/list_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/list_command.dart",
"repo_id": "packages",
"token_count": 692
} | 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 'common/core.dart';
import 'common/output_utils.dart';
import 'common/package_looping_command.dart';
import 'common/plugin_utils.dart';
import 'common/repository_package.dart';
import 'common/xcode.dart';
/// The command to run Xcode's static analyzer on plugins.
class XcodeAnalyzeCommand extends PackageLoopingCommand {
/// Creates an instance of the test command.
XcodeAnalyzeCommand(
super.packagesDir, {
super.processRunner,
super.platform,
}) : _xcode = Xcode(processRunner: processRunner, log: true) {
argParser.addFlag(platformIOS, help: 'Analyze iOS');
argParser.addFlag(platformMacOS, help: 'Analyze macOS');
argParser.addOption(_minIOSVersionArg,
help: 'Sets the minimum iOS deployment version to use when compiling, '
'overriding the default minimum version. This can be used to find '
'deprecation warnings that will affect the plugin in the future.');
argParser.addOption(_minMacOSVersionArg,
help:
'Sets the minimum macOS deployment version to use when compiling, '
'overriding the default minimum version. This can be used to find '
'deprecation warnings that will affect the plugin in the future.');
}
static const String _minIOSVersionArg = 'ios-min-version';
static const String _minMacOSVersionArg = 'macos-min-version';
final Xcode _xcode;
@override
final String name = 'xcode-analyze';
@override
List<String> get aliases => <String>['analyze-xcode'];
@override
final String description =
'Runs Xcode analysis on the iOS and/or macOS example apps.';
@override
Future<void> initializeRun() async {
if (!(getBoolArg(platformIOS) || getBoolArg(platformMacOS))) {
printError('At least one platform flag must be provided.');
throw ToolExit(exitInvalidArguments);
}
}
@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
final bool testIOS = getBoolArg(platformIOS) &&
pluginSupportsPlatform(platformIOS, package,
requiredMode: PlatformSupport.inline);
final bool testMacOS = getBoolArg(platformMacOS) &&
pluginSupportsPlatform(platformMacOS, package,
requiredMode: PlatformSupport.inline);
final bool multiplePlatformsRequested =
getBoolArg(platformIOS) && getBoolArg(platformMacOS);
if (!(testIOS || testMacOS)) {
return PackageResult.skip('Not implemented for target platform(s).');
}
final String minIOSVersion = getStringArg(_minIOSVersionArg);
final String minMacOSVersion = getStringArg(_minMacOSVersionArg);
final List<String> failures = <String>[];
if (testIOS &&
!await _analyzePlugin(package, 'iOS', extraFlags: <String>[
'-destination',
'generic/platform=iOS Simulator',
if (minIOSVersion.isNotEmpty)
'IPHONEOS_DEPLOYMENT_TARGET=$minIOSVersion',
])) {
failures.add('iOS');
}
if (testMacOS &&
!await _analyzePlugin(package, 'macOS', extraFlags: <String>[
if (minMacOSVersion.isNotEmpty)
'MACOSX_DEPLOYMENT_TARGET=$minMacOSVersion',
])) {
failures.add('macOS');
}
// Only provide the failing platform in the failure details if testing
// multiple platforms, otherwise it's just noise.
return failures.isEmpty
? PackageResult.success()
: PackageResult.fail(
multiplePlatformsRequested ? failures : <String>[]);
}
/// Analyzes [plugin] for [platform], returning true if it passed analysis.
Future<bool> _analyzePlugin(
RepositoryPackage plugin,
String platform, {
List<String> extraFlags = const <String>[],
}) async {
bool passing = true;
for (final RepositoryPackage example in plugin.getExamples()) {
// Running tests and static analyzer.
final String examplePath = getRelativePosixPath(example.directory,
from: plugin.directory.parent);
print('Running $platform tests and analyzer for $examplePath...');
final int exitCode = await _xcode.runXcodeBuild(
example.directory,
actions: <String>['analyze'],
workspace: '${platform.toLowerCase()}/Runner.xcworkspace',
scheme: 'Runner',
configuration: 'Debug',
extraFlags: <String>[
...extraFlags,
'GCC_TREAT_WARNINGS_AS_ERRORS=YES',
],
);
if (exitCode == 0) {
printSuccess('$examplePath ($platform) passed analysis.');
} else {
printError('$examplePath ($platform) failed analysis.');
passing = false;
}
}
return passing;
}
}
| packages/script/tool/lib/src/xcode_analyze_command.dart/0 | {
"file_path": "packages/script/tool/lib/src/xcode_analyze_command.dart",
"repo_id": "packages",
"token_count": 1759
} | 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:file/file.dart';
import 'package:file/local.dart';
import 'package:flutter_plugin_tools/src/common/xcode.dart';
import 'package:test/test.dart';
import '../mocks.dart';
import '../util.dart';
void main() {
late RecordingProcessRunner processRunner;
late Xcode xcode;
setUp(() {
processRunner = RecordingProcessRunner();
xcode = Xcode(processRunner: processRunner);
});
group('findBestAvailableIphoneSimulator', () {
test('finds the newest device', () async {
const String expectedDeviceId = '1E76A0FD-38AC-4537-A989-EA639D7D012A';
// Note: This uses `dynamic` deliberately, and should not be updated to
// Object, in order to ensure that the code correctly handles this return
// type from JSON decoding.
final Map<String, dynamic> devices = <String, dynamic>{
'runtimes': <Map<String, dynamic>>[
<String, dynamic>{
'bundlePath':
'/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 13.0.simruntime',
'buildversion': '17A577',
'runtimeRoot':
'/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 13.0.simruntime/Contents/Resources/RuntimeRoot',
'identifier': 'com.apple.CoreSimulator.SimRuntime.iOS-13-0',
'version': '13.0',
'isAvailable': true,
'name': 'iOS 13.0'
},
<String, dynamic>{
'bundlePath':
'/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 13.4.simruntime',
'buildversion': '17L255',
'runtimeRoot':
'/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 13.4.simruntime/Contents/Resources/RuntimeRoot',
'identifier': 'com.apple.CoreSimulator.SimRuntime.iOS-13-4',
'version': '13.4',
'isAvailable': true,
'name': 'iOS 13.4'
},
<String, dynamic>{
'bundlePath':
'/Applications/Xcode_11_7.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime',
'buildversion': '17T531',
'runtimeRoot':
'/Applications/Xcode_11_7.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot',
'identifier': 'com.apple.CoreSimulator.SimRuntime.watchOS-6-2',
'version': '6.2.1',
'isAvailable': true,
'name': 'watchOS 6.2'
}
],
'devices': <String, dynamic>{
'com.apple.CoreSimulator.SimRuntime.iOS-13-4': <Map<String, dynamic>>[
<String, dynamic>{
'dataPath':
'/Users/xxx/Library/Developer/CoreSimulator/Devices/2706BBEB-1E01-403E-A8E9-70E8E5A24774/data',
'logPath':
'/Users/xxx/Library/Logs/CoreSimulator/2706BBEB-1E01-403E-A8E9-70E8E5A24774',
'udid': '2706BBEB-1E01-403E-A8E9-70E8E5A24774',
'isAvailable': true,
'deviceTypeIdentifier':
'com.apple.CoreSimulator.SimDeviceType.iPhone-8',
'state': 'Shutdown',
'name': 'iPhone 8'
},
<String, dynamic>{
'dataPath':
'/Users/xxx/Library/Developer/CoreSimulator/Devices/1E76A0FD-38AC-4537-A989-EA639D7D012A/data',
'logPath':
'/Users/xxx/Library/Logs/CoreSimulator/1E76A0FD-38AC-4537-A989-EA639D7D012A',
'udid': expectedDeviceId,
'isAvailable': true,
'deviceTypeIdentifier':
'com.apple.CoreSimulator.SimDeviceType.iPhone-8-Plus',
'state': 'Shutdown',
'name': 'iPhone 8 Plus'
}
]
}
};
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: jsonEncode(devices)),
<String>['simctl', 'list']),
];
expect(await xcode.findBestAvailableIphoneSimulator(), expectedDeviceId);
});
test('ignores non-iOS runtimes', () async {
// Note: This uses `dynamic` deliberately, and should not be updated to
// Object, in order to ensure that the code correctly handles this return
// type from JSON decoding.
final Map<String, dynamic> devices = <String, dynamic>{
'runtimes': <Map<String, dynamic>>[
<String, dynamic>{
'bundlePath':
'/Applications/Xcode_11_7.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime',
'buildversion': '17T531',
'runtimeRoot':
'/Applications/Xcode_11_7.app/Contents/Developer/Platforms/WatchOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS.simruntime/Contents/Resources/RuntimeRoot',
'identifier': 'com.apple.CoreSimulator.SimRuntime.watchOS-6-2',
'version': '6.2.1',
'isAvailable': true,
'name': 'watchOS 6.2'
}
],
'devices': <String, dynamic>{
'com.apple.CoreSimulator.SimRuntime.watchOS-6-2':
<Map<String, dynamic>>[
<String, dynamic>{
'dataPath':
'/Users/xxx/Library/Developer/CoreSimulator/Devices/1E76A0FD-38AC-4537-A989-EA639D7D012A/data',
'logPath':
'/Users/xxx/Library/Logs/CoreSimulator/1E76A0FD-38AC-4537-A989-EA639D7D012A',
'udid': '1E76A0FD-38AC-4537-A989-EA639D7D012A',
'isAvailable': true,
'deviceTypeIdentifier':
'com.apple.CoreSimulator.SimDeviceType.Apple-Watch-38mm',
'state': 'Shutdown',
'name': 'Apple Watch'
}
]
}
};
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: jsonEncode(devices)),
<String>['simctl', 'list']),
];
expect(await xcode.findBestAvailableIphoneSimulator(), null);
});
test('returns null if simctl fails', () async {
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['simctl', 'list']),
];
expect(await xcode.findBestAvailableIphoneSimulator(), null);
});
});
group('runXcodeBuild', () {
test('handles minimal arguments', () async {
final Directory directory = const LocalFileSystem().currentDirectory;
final int exitCode = await xcode.runXcodeBuild(
directory,
workspace: 'A.xcworkspace',
scheme: 'AScheme',
);
expect(exitCode, 0);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'xcrun',
const <String>[
'xcodebuild',
'build',
'-workspace',
'A.xcworkspace',
'-scheme',
'AScheme',
],
directory.path),
]));
});
test('handles all arguments', () async {
final Directory directory = const LocalFileSystem().currentDirectory;
final int exitCode = await xcode.runXcodeBuild(directory,
actions: <String>['action1', 'action2'],
workspace: 'A.xcworkspace',
scheme: 'AScheme',
configuration: 'Debug',
extraFlags: <String>['-a', '-b', 'c=d']);
expect(exitCode, 0);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'xcrun',
const <String>[
'xcodebuild',
'action1',
'action2',
'-workspace',
'A.xcworkspace',
'-scheme',
'AScheme',
'-configuration',
'Debug',
'-a',
'-b',
'c=d',
],
directory.path),
]));
});
test('returns error codes', () async {
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(exitCode: 1), <String>['xcodebuild']),
];
final Directory directory = const LocalFileSystem().currentDirectory;
final int exitCode = await xcode.runXcodeBuild(
directory,
workspace: 'A.xcworkspace',
scheme: 'AScheme',
);
expect(exitCode, 1);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'xcrun',
const <String>[
'xcodebuild',
'build',
'-workspace',
'A.xcworkspace',
'-scheme',
'AScheme',
],
directory.path),
]));
});
});
group('projectHasTarget', () {
test('returns true when present', () async {
const String stdout = '''
{
"project" : {
"configurations" : [
"Debug",
"Release"
],
"name" : "Runner",
"schemes" : [
"Runner"
],
"targets" : [
"Runner",
"RunnerTests",
"RunnerUITests"
]
}
}''';
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: stdout), <String>['xcodebuild']),
];
final Directory project =
const LocalFileSystem().directory('/foo.xcodeproj');
expect(await xcode.projectHasTarget(project, 'RunnerTests'), true);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'xcrun',
<String>[
'xcodebuild',
'-list',
'-json',
'-project',
project.path,
],
null),
]));
});
test('returns false when not present', () async {
const String stdout = '''
{
"project" : {
"configurations" : [
"Debug",
"Release"
],
"name" : "Runner",
"schemes" : [
"Runner"
],
"targets" : [
"Runner",
"RunnerUITests"
]
}
}''';
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: stdout), <String>['xcodebuild']),
];
final Directory project =
const LocalFileSystem().directory('/foo.xcodeproj');
expect(await xcode.projectHasTarget(project, 'RunnerTests'), false);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'xcrun',
<String>[
'xcodebuild',
'-list',
'-json',
'-project',
project.path,
],
null),
]));
});
test('returns null for unexpected output', () async {
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: '{}'), <String>['xcodebuild']),
];
final Directory project =
const LocalFileSystem().directory('/foo.xcodeproj');
expect(await xcode.projectHasTarget(project, 'RunnerTests'), null);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'xcrun',
<String>[
'xcodebuild',
'-list',
'-json',
'-project',
project.path,
],
null),
]));
});
test('returns null for invalid output', () async {
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(MockProcess(stdout: ':)'), <String>['xcodebuild']),
];
final Directory project =
const LocalFileSystem().directory('/foo.xcodeproj');
expect(await xcode.projectHasTarget(project, 'RunnerTests'), null);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'xcrun',
<String>[
'xcodebuild',
'-list',
'-json',
'-project',
project.path,
],
null),
]));
});
test('returns null for failure', () async {
processRunner.mockProcessesForExecutable['xcrun'] = <FakeProcessInfo>[
FakeProcessInfo(
MockProcess(exitCode: 1), <String>['xcodebuild', '-list'])
];
final Directory project =
const LocalFileSystem().directory('/foo.xcodeproj');
expect(await xcode.projectHasTarget(project, 'RunnerTests'), null);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
ProcessCall(
'xcrun',
<String>[
'xcodebuild',
'-list',
'-json',
'-project',
project.path,
],
null),
]));
});
});
}
| packages/script/tool/test/common/xcode_test.dart/0 | {
"file_path": "packages/script/tool/test/common/xcode_test.dart",
"repo_id": "packages",
"token_count": 6961
} | 1,061 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io' as io;
import 'package:file/file.dart';
import 'package:mockito/mockito.dart';
import 'package:platform/platform.dart';
class MockPlatform extends Mock implements Platform {
MockPlatform({
this.isLinux = false,
this.isMacOS = false,
this.isWindows = false,
});
@override
bool isLinux;
@override
bool isMacOS;
@override
bool isWindows;
@override
Uri get script => isWindows
? Uri.file(r'C:\foo\bar', windows: true)
: Uri.file('/foo/bar', windows: false);
@override
Map<String, String> environment = <String, String>{};
}
class MockProcess extends Mock implements io.Process {
/// Creates a mock process with the given results.
///
/// The default encodings match the ProcessRunner defaults; mocks for
/// processes run with a different encoding will need to be created with
/// the matching encoding.
MockProcess({
int exitCode = 0,
String? stdout,
String? stderr,
Encoding stdoutEncoding = io.systemEncoding,
Encoding stderrEncoding = io.systemEncoding,
}) : _exitCode = exitCode {
if (stdout != null) {
_stdoutController.add(stdoutEncoding.encoder.convert(stdout));
}
if (stderr != null) {
_stderrController.add(stderrEncoding.encoder.convert(stderr));
}
_stdoutController.close();
_stderrController.close();
}
final int _exitCode;
final StreamController<List<int>> _stdoutController =
StreamController<List<int>>();
final StreamController<List<int>> _stderrController =
StreamController<List<int>>();
final MockIOSink stdinMock = MockIOSink();
@override
int get pid => 99;
@override
Future<int> get exitCode async => _exitCode;
@override
Stream<List<int>> get stdout => _stdoutController.stream;
@override
Stream<List<int>> get stderr => _stderrController.stream;
@override
IOSink get stdin => stdinMock;
@override
bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) => true;
}
class MockIOSink extends Mock implements IOSink {
List<String> lines = <String>[];
@override
void writeln([Object? obj = '']) => lines.add(obj.toString());
}
| packages/script/tool/test/mocks.dart/0 | {
"file_path": "packages/script/tool/test/mocks.dart",
"repo_id": "packages",
"token_count": 816
} | 1,062 |
/* eslint-disable @typescript-eslint/no-unused-vars */
import * as functions from 'firebase-functions';
import { getShareResponse } from './';
jest.mock('firebase-admin', () => {
return {
storage: jest.fn(() => ({
bucket: jest.fn(() => ({
name: 'test-bucket',
file: jest.fn(() => ({
exists: jest.fn(async () => {
return [ true ];
}),
})),
})),
})),
};
});
describe('Share API', () => {
const baseReq = {
path: '',
protocol: 'http',
get(_: string) {
return 'localhost:5001';
},
} as functions.https.Request;
test('Invalid path returns 404 and html', async () => {
const req = Object.assign({}, baseReq);
const res = await getShareResponse(req);
expect(res.status).toEqual(404);
expect(typeof res.send).toEqual('string');
expect(res.send).toContain('DOCTYPE html');
});
test('Invalid file extension returns 404 and html', async () => {
const req = Object.assign({}, baseReq, {
path: 'wrong.gif',
});
const res = await getShareResponse(req);
expect(res.status).toEqual(404);
expect(typeof res.send).toEqual('string');
expect(res.send).toContain('DOCTYPE html');
});
test('Valid file name returns 200 and html', async () => {
const req = Object.assign({}, baseReq, {
path: 'test.png',
});
const res = await getShareResponse(req);
expect(res.status).toEqual(200);
expect(typeof res.send).toEqual('string');
expect(res.send).toContain('DOCTYPE html');
});
});
| photobooth/functions/src/share/index.spec.ts/0 | {
"file_path": "photobooth/functions/src/share/index.spec.ts",
"repo_id": "photobooth",
"token_count": 637
} | 1,063 |
import 'package:flutter/material.dart';
import 'package:io_photobooth/footer/footer.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class WhiteFooter extends StatelessWidget {
const WhiteFooter({super.key});
@override
Widget build(BuildContext context) {
return const Footer(textColor: PhotoboothColors.white);
}
}
class BlackFooter extends StatelessWidget {
const BlackFooter({super.key});
@override
Widget build(BuildContext context) {
return const Footer(textColor: PhotoboothColors.black);
}
}
class Footer extends StatelessWidget {
const Footer({required this.textColor, super.key});
final Color textColor;
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.bodySmall!.copyWith(color: textColor),
child: Padding(
padding: const EdgeInsets.fromLTRB(50, 0, 50, 32),
child: ResponsiveLayoutBuilder(
small: (_, __) => const _ColumnFooter(key: Key('footer_column')),
large: (_, __) => const _RowFooter(key: Key('footer_row')),
),
),
);
}
}
class _ColumnFooter extends StatelessWidget {
const _ColumnFooter({super.key});
@override
Widget build(BuildContext context) {
const gap = SizedBox(height: 16);
return const Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
FooterMadeWithLink(),
SizedBox(height: 32),
Wrap(
alignment: WrapAlignment.center,
runSpacing: 16,
children: [
FooterGoogleIOLink(),
SizedBox(width: 30),
FooterCodelabLink(),
SizedBox(width: 30),
FooterHowItsMadeLink(),
],
),
gap,
Wrap(
alignment: WrapAlignment.center,
runSpacing: 16,
children: [
FooterTermsOfServiceLink(),
SizedBox(width: 30),
FooterPrivacyPolicyLink(),
],
),
],
);
}
}
class _RowFooter extends StatelessWidget {
const _RowFooter({super.key});
@override
Widget build(BuildContext context) {
const gap = SizedBox(width: 32);
return const Row(
children: [
FooterMadeWithLink(),
Spacer(),
FooterGoogleIOLink(),
gap,
FooterCodelabLink(),
gap,
FooterHowItsMadeLink(),
gap,
FooterTermsOfServiceLink(),
gap,
FooterPrivacyPolicyLink(),
],
);
}
}
| photobooth/lib/footer/widgets/footer.dart/0 | {
"file_path": "photobooth/lib/footer/widgets/footer.dart",
"repo_id": "photobooth",
"token_count": 1116
} | 1,064 |
export 'view/landing_page.dart';
export 'widgets/widgets.dart';
| photobooth/lib/landing/landing.dart/0 | {
"file_path": "photobooth/lib/landing/landing.dart",
"repo_id": "photobooth",
"token_count": 25
} | 1,065 |
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class AnimatedDash extends AnimatedSprite {
const AnimatedDash({super.key})
: super(
loadingIndicatorColor: PhotoboothColors.blue,
sprites: const Sprites(
asset: 'dash_spritesheet.png',
size: Size(650, 587),
frames: 25,
stepTime: 2 / 25,
),
);
}
| photobooth/lib/photobooth/widgets/animated_characters/animated_dash.dart/0 | {
"file_path": "photobooth/lib/photobooth/widgets/animated_characters/animated_dash.dart",
"repo_id": "photobooth",
"token_count": 202
} | 1,066 |
export 'bloc/share_bloc.dart';
export 'view/view.dart';
export 'widgets/widgets.dart';
| photobooth/lib/share/share.dart/0 | {
"file_path": "photobooth/lib/share/share.dart",
"repo_id": "photobooth",
"token_count": 36
} | 1,067 |
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
class SharePreviewPhoto extends StatelessWidget {
const SharePreviewPhoto({required this.image, super.key});
final Uint8List image;
@override
Widget build(BuildContext context) {
return Transform.rotate(
angle: -5 * (math.pi / 180),
child: Container(
constraints: const BoxConstraints(maxWidth: 600, maxHeight: 400),
decoration: const BoxDecoration(
boxShadow: [
BoxShadow(
color: PhotoboothColors.black54,
blurRadius: 7,
offset: Offset(-3, 9),
spreadRadius: 1,
),
],
),
child: Image.memory(
image,
isAntiAlias: true,
filterQuality: FilterQuality.high,
),
),
);
}
}
| photobooth/lib/share/widgets/share_preview_photo.dart/0 | {
"file_path": "photobooth/lib/share/widgets/share_preview_photo.dart",
"repo_id": "photobooth",
"token_count": 423
} | 1,068 |
import 'package:flutter/material.dart';
import 'package:io_photobooth/l10n/l10n.dart';
class ClearStickersConfirmButton extends StatelessWidget {
const ClearStickersConfirmButton({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text(l10n.clearStickersDialogConfirmButtonText),
);
}
}
| photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_confirm_button.dart/0 | {
"file_path": "photobooth/lib/stickers/widgets/clear_stickers/clear_stickers_confirm_button.dart",
"repo_id": "photobooth",
"token_count": 159
} | 1,069 |
# authentication_repository
Repository which manages user authentication using Firebase Authentication.
| photobooth/packages/authentication_repository/README.md/0 | {
"file_path": "photobooth/packages/authentication_repository/README.md",
"repo_id": "photobooth",
"token_count": 20
} | 1,070 |
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
Fore more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
-->
<base href="/" />
<meta charset="UTF-8" />
<meta content="IE=Edge" http-equiv="X-UA-Compatible" />
<meta name="description" content="A new Flutter project." />
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="apple-mobile-web-app-title" content="example />
<link rel="apple-touch-icon" href="icons/Icon-192.png" />
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png" />
<title>I/O Photo Booth</title>
<link rel="manifest" href="manifest.json" />
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("flutter-first-frame", function () {
navigator.serviceWorker.register("flutter_service_worker.js");
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
| photobooth/packages/camera/camera/example/web/index.html/0 | {
"file_path": "photobooth/packages/camera/camera/example/web/index.html",
"repo_id": "photobooth",
"token_count": 578
} | 1,071 |
name: camera_platform_interface
description: A common platform interface for the camera plugin.
version: 0.0.1
environment:
sdk: ">=2.19.0 <3.0.0"
flutter: ">=2.0.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.3
dev_dependencies:
very_good_analysis: ^4.0.0+1
| photobooth/packages/camera/camera_platform_interface/pubspec.yaml/0 | {
"file_path": "photobooth/packages/camera/camera_platform_interface/pubspec.yaml",
"repo_id": "photobooth",
"token_count": 122
} | 1,072 |
export 'constants.dart';
| photobooth/packages/image_compositor/test/helpers/helpers.dart/0 | {
"file_path": "photobooth/packages/image_compositor/test/helpers/helpers.dart",
"repo_id": "photobooth",
"token_count": 9
} | 1,073 |
/// Namespace for Default Photobooth Aspect Ratios
abstract class PhotoboothAspectRatio {
/// Aspect ratio used for landscape.
static const landscape = 4 / 3;
/// Aspect ratio used for portrait.
static const portrait = 3 / 4;
}
| photobooth/packages/photobooth_ui/lib/src/layout/aspect_ratio.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/layout/aspect_ratio.dart",
"repo_id": "photobooth",
"token_count": 67
} | 1,074 |
import 'package:flutter/material.dart';
/// {@template app_animated_cross_fade}
/// Abstraction of AnimatedCrossFade to override the layout centering
/// the widgets inside
/// {@endtemplate}
class AppAnimatedCrossFade extends StatelessWidget {
/// {@macro app_animated_cross_fade}
const AppAnimatedCrossFade({
required this.firstChild,
required this.secondChild,
required this.crossFadeState,
super.key,
});
/// First [Widget] to display
final Widget firstChild;
/// Second [Widget] to display
final Widget secondChild;
/// Specifies when to display [firstChild] or [secondChild]
final CrossFadeState crossFadeState;
@override
Widget build(BuildContext context) {
return AnimatedCrossFade(
firstChild: firstChild,
secondChild: secondChild,
crossFadeState: crossFadeState,
duration: const Duration(seconds: 1),
layoutBuilder: (
Widget topChild,
Key topChildKey,
Widget bottomChild,
Key bottomChildKey,
) {
return Stack(
clipBehavior: Clip.none,
alignment: Alignment.center,
children: [
Align(
key: bottomChildKey,
child: bottomChild,
),
Align(
key: topChildKey,
child: topChild,
),
],
);
},
);
}
}
| photobooth/packages/photobooth_ui/lib/src/widgets/app_animated_cross_fade.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/app_animated_cross_fade.dart",
"repo_id": "photobooth",
"token_count": 584
} | 1,075 |
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.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() {
late UrlLauncherPlatform mock;
late UrlLauncherPlatform original;
setUpAll(() {
registerFallbackValue(const LaunchOptions());
});
setUp(() {
original = UrlLauncherPlatform.instance;
mock = MockUrlLauncher();
UrlLauncherPlatform.instance = mock;
});
tearDown(() {
UrlLauncherPlatform.instance = original;
});
group('openLink', () {
test('launches the link', () async {
when(() => mock.canLaunch('url')).thenAnswer((_) async => true);
when(() => mock.launchUrl('url', any())).thenAnswer((_) async => true);
await openLink('url');
verify(() => mock.launchUrl('url', any())).called(1);
});
test('executes the onError callback when it cannot launch', () async {
var wasCalled = false;
when(() => mock.canLaunch('url')).thenAnswer((_) async => false);
when(() => mock.launchUrl('url', any())).thenAnswer((_) async => true);
await openLink(
'url',
onError: () {
wasCalled = true;
},
);
await expectLater(wasCalled, isTrue);
});
});
}
| photobooth/packages/photobooth_ui/test/src/helpers/links_helper_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/helpers/links_helper_test.dart",
"repo_id": "photobooth",
"token_count": 555
} | 1,076 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
void main() {
group('Clickable', () {
testWidgets('makes the given child tappable/clickable', (tester) async {
var wasClicked = false;
await tester.pumpWidget(
MaterialApp(
home: Clickable(
onPressed: () {
wasClicked = true;
},
child: const Text('Click me'),
),
),
);
expect(find.text('Click me'), findsOneWidget);
expect(wasClicked, isFalse);
await tester.tap(find.text('Click me'));
await tester.pumpAndSettle();
expect(wasClicked, isTrue);
});
});
}
| photobooth/packages/photobooth_ui/test/src/widgets/clickable_test.dart/0 | {
"file_path": "photobooth/packages/photobooth_ui/test/src/widgets/clickable_test.dart",
"repo_id": "photobooth",
"token_count": 338
} | 1,077 |
export 'src/unsupported.dart'
if (dart.library.html) 'src/web.dart'
if (dart.library.io) 'src/mobile.dart';
| photobooth/packages/platform_helper/lib/platform_helper.dart/0 | {
"file_path": "photobooth/packages/platform_helper/lib/platform_helper.dart",
"repo_id": "photobooth",
"token_count": 53
} | 1,078 |
export 'constants.dart';
export 'pump_app.dart';
export 'set_display_size.dart';
| photobooth/test/helpers/helpers.dart/0 | {
"file_path": "photobooth/test/helpers/helpers.dart",
"repo_id": "photobooth",
"token_count": 32
} | 1,079 |
// ignore_for_file: prefer_const_constructors
import 'dart:typed_data';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/share/share.dart';
import 'package:mocktail/mocktail.dart';
import '../../helpers/helpers.dart';
class FakePhotoboothEvent extends Fake implements PhotoboothEvent {}
class FakePhotoboothState extends Fake implements PhotoboothState {}
void main() {
const width = 1;
const height = 1;
const data = '';
const image = CameraImage(width: width, height: height, data: data);
final bytes = Uint8List.fromList(transparentImage);
late PhotoboothBloc photoboothBloc;
setUpAll(() {
registerFallbackValue(FakePhotoboothEvent());
registerFallbackValue(FakePhotoboothState());
});
setUp(() {
photoboothBloc = MockPhotoboothBloc();
when(() => photoboothBloc.state).thenReturn(PhotoboothState(image: image));
});
group('ShareBottomSheet', () {
testWidgets('displays heading', (tester) async {
await tester.pumpApp(
Scaffold(body: ShareBottomSheet(image: bytes)),
photoboothBloc: photoboothBloc,
);
expect(find.byKey(Key('shareBottomSheet_heading')), findsOneWidget);
});
testWidgets('displays subheading', (tester) async {
await tester.pumpApp(
Scaffold(body: ShareBottomSheet(image: bytes)),
photoboothBloc: photoboothBloc,
);
expect(find.byKey(Key('shareBottomSheet_subheading')), findsOneWidget);
});
testWidgets('displays a TwitterButton', (tester) async {
await tester.pumpApp(
Scaffold(body: ShareBottomSheet(image: bytes)),
photoboothBloc: photoboothBloc,
);
expect(find.byType(TwitterButton), findsOneWidget);
});
testWidgets('displays a FacebookButton', (tester) async {
await tester.pumpApp(
Scaffold(body: ShareBottomSheet(image: bytes)),
photoboothBloc: photoboothBloc,
);
expect(find.byType(FacebookButton), findsOneWidget);
});
testWidgets('taps on close will dismiss the popup', (tester) async {
await tester.pumpApp(
Scaffold(body: ShareBottomSheet(image: bytes)),
photoboothBloc: photoboothBloc,
);
await tester.tap(find.byIcon(Icons.clear));
await tester.pumpAndSettle();
expect(find.byType(ShareBottomSheet), findsNothing);
});
});
}
| photobooth/test/share/view/share_bottom_sheet_test.dart/0 | {
"file_path": "photobooth/test/share/view/share_bottom_sheet_test.dart",
"repo_id": "photobooth",
"token_count": 966
} | 1,080 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import '../../../helpers/helpers.dart';
void main() {
group('ClearStickersDialog', () {
testWidgets('renders heading', (tester) async {
await tester.pumpApp(ClearStickersDialog());
expect(find.byKey(Key('clearStickersDialog_heading')), findsOneWidget);
});
testWidgets('renders subheading', (tester) async {
await tester.pumpApp(ClearStickersDialog());
expect(find.byKey(Key('clearStickersDialog_subheading')), findsOneWidget);
});
testWidgets('tapping on ClearStickersCancelButton will dismiss the dialog',
(tester) async {
await tester.pumpApp(ClearStickersDialog());
await tester.ensureVisible(find.byType(ClearStickersCancelButton));
await tester.tap(find.byType(ClearStickersCancelButton));
await tester.pumpAndSettle();
expect(find.byType(ClearStickersDialog), findsNothing);
});
testWidgets('tapping on ClearStickersConfirmButton will dismiss the dialog',
(tester) async {
await tester.pumpApp(ClearStickersDialog());
await tester.ensureVisible(find.byType(ClearStickersConfirmButton));
await tester.tap(find.byType(ClearStickersConfirmButton));
await tester.pumpAndSettle();
expect(find.byType(ClearStickersDialog), findsNothing);
});
});
}
| photobooth/test/stickers/widgets/clear_stickers/clear_stickers_dialog_test.dart/0 | {
"file_path": "photobooth/test/stickers/widgets/clear_stickers/clear_stickers_dialog_test.dart",
"repo_id": "photobooth",
"token_count": 543
} | 1,081 |
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^10.0.2",
"firebase-functions": "^3.18.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
| pinball/functions/package.json/0 | {
"file_path": "pinball/functions/package.json",
"repo_id": "pinball",
"token_count": 227
} | 1,082 |
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
/// {@template focus_data}
/// Defines a [Camera] focus point.
/// {@endtemplate}
class _FocusData {
/// {@macro focus_data}
const _FocusData({
required this.zoom,
required this.position,
});
/// The amount of zoom.
final double zoom;
/// The position of the camera.
final Vector2 position;
}
/// Changes the game focus when the [GameBloc] status changes.
class CameraFocusingBehavior extends Component
with FlameBlocListenable<GameBloc, GameState>, HasGameRef {
final Map<GameStatus, _FocusData> _foci = {};
GameStatus? _activeFocus;
final _previousSize = Vector2.zero();
@override
bool listenWhen(GameState? previousState, GameState newState) {
return previousState?.status != newState.status;
}
@override
void onNewState(GameState state) => _zoomTo(state.status);
@override
void onGameResize(Vector2 size) {
super.onGameResize(size);
if (size == _previousSize) return;
_previousSize.setFrom(size);
_foci.addAll(
{
GameStatus.waiting: _FocusData(
zoom: size.y / 175,
position: _foci[GameStatus.waiting]?.position ?? Vector2(0, -112),
),
GameStatus.playing: _FocusData(
zoom: size.y / 160,
position: _foci[GameStatus.playing]?.position ?? Vector2(0, -7.8),
),
GameStatus.gameOver: _FocusData(
zoom: size.y / 100,
position: _foci[GameStatus.gameOver]?.position ?? Vector2(0, -111),
),
},
);
if (_activeFocus != null) {
_snap(_activeFocus!);
}
}
@override
Future<void> onLoad() async {
await super.onLoad();
_snap(GameStatus.waiting);
}
void _snap(GameStatus focusKey) {
final focusData = _foci[_activeFocus = focusKey]!;
gameRef.camera
..speed = 100
..followVector2(focusData.position)
..zoom = focusData.zoom;
}
void _zoomTo(GameStatus focusKey) {
final focusData = _foci[_activeFocus = focusKey]!;
final zoom = CameraZoom(value: focusData.zoom);
zoom.completed.then((_) {
gameRef.camera.moveTo(focusData.position);
});
add(zoom);
}
}
| pinball/lib/game/behaviors/camera_focusing_behavior.dart/0 | {
"file_path": "pinball/lib/game/behaviors/camera_focusing_behavior.dart",
"repo_id": "pinball",
"token_count": 932
} | 1,083 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/game/behaviors/behaviors.dart';
import 'package:pinball_components/pinball_components.dart';
/// {@template ramp_shot_behavior}
/// Increases the score when a [Ball] is shot into the [SpaceshipRamp].
/// {@endtemplate}
class RampShotBehavior extends Component
with FlameBlocListenable<SpaceshipRampCubit, SpaceshipRampState> {
/// {@macro ramp_shot_behavior}
RampShotBehavior({
required Points points,
}) : _points = points,
super();
final Points _points;
@override
bool listenWhen(
SpaceshipRampState previousState,
SpaceshipRampState newState,
) {
return previousState.hits < newState.hits;
}
@override
void onNewState(SpaceshipRampState state) {
parent!.add(
ScoringBehavior(
points: _points,
position: Vector2(0, -45),
),
);
}
}
| pinball/lib/game/components/android_acres/behaviors/ramp_shot_behavior.dart/0 | {
"file_path": "pinball/lib/game/components/android_acres/behaviors/ramp_shot_behavior.dart",
"repo_id": "pinball",
"token_count": 348
} | 1,084 |
export 'chrome_dino_bonus_behavior.dart';
| pinball/lib/game/components/dino_desert/behaviors/behaviors.dart/0 | {
"file_path": "pinball/lib/game/components/dino_desert/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 16
} | 1,085 |
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:pinball/game/components/multiballs/behaviors/behaviors.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template multiballs_component}
/// A [SpriteGroupComponent] for the multiball over the board.
/// {@endtemplate}
class Multiballs extends Component with ZIndex {
/// {@macro multiballs_component}
Multiballs()
: super(
children: [
Multiball.a(),
Multiball.b(),
Multiball.c(),
Multiball.d(),
MultiballsBehavior(),
],
) {
zIndex = ZIndexes.decal;
}
/// Creates a [Multiballs] without any children.
///
/// This can be used for testing [Multiballs]'s behaviors in isolation.
@visibleForTesting
Multiballs.test();
}
| pinball/lib/game/components/multiballs/multiballs.dart/0 | {
"file_path": "pinball/lib/game/components/multiballs/multiballs.dart",
"repo_id": "pinball",
"token_count": 362
} | 1,086 |
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/start_game/start_game.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// {@template play_button_overlay}
/// [Widget] that renders the button responsible to starting the game
/// {@endtemplate}
class PlayButtonOverlay extends StatelessWidget {
/// {@macro play_button_overlay}
const PlayButtonOverlay({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return PinballButton(
text: l10n.play,
onTap: () {
context.read<StartGameBloc>().add(const PlayTapped());
},
);
}
}
| pinball/lib/game/view/widgets/play_button_overlay.dart/0 | {
"file_path": "pinball/lib/game/view/widgets/play_button_overlay.dart",
"repo_id": "pinball",
"token_count": 273
} | 1,087 |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:pinball_theme/pinball_theme.dart';
part 'character_theme_state.dart';
class CharacterThemeCubit extends Cubit<CharacterThemeState> {
CharacterThemeCubit() : super(const CharacterThemeState.initial());
void characterSelected(CharacterTheme characterTheme) {
emit(CharacterThemeState(characterTheme));
}
}
| pinball/lib/select_character/cubit/character_theme_cubit.dart/0 | {
"file_path": "pinball/lib/select_character/cubit/character_theme_cubit.dart",
"repo_id": "pinball",
"token_count": 123
} | 1,088 |
name: authentication_repository
description: Repository to manage user authentication.
version: 1.0.0+1
publish_to: none
environment:
sdk: ">=2.16.0 <3.0.0"
dependencies:
firebase_auth: ^3.3.16
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^0.2.0
very_good_analysis: ^2.4.0 | pinball/packages/authentication_repository/pubspec.yaml/0 | {
"file_path": "pinball/packages/authentication_repository/pubspec.yaml",
"repo_id": "pinball",
"token_count": 138
} | 1,089 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'leaderboard_entry_data.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
LeaderboardEntryData _$LeaderboardEntryFromJson(Map<String, dynamic> json) =>
LeaderboardEntryData(
playerInitials: json['playerInitials'] as String,
score: json['score'] as int,
character: $enumDecode(_$CharacterTypeEnumMap, json['character']),
);
Map<String, dynamic> _$LeaderboardEntryToJson(LeaderboardEntryData instance) =>
<String, dynamic>{
'playerInitials': instance.playerInitials,
'score': instance.score,
'character': _$CharacterTypeEnumMap[instance.character],
};
const _$CharacterTypeEnumMap = {
CharacterType.dash: 'dash',
CharacterType.sparky: 'sparky',
CharacterType.android: 'android',
CharacterType.dino: 'dino',
};
| pinball/packages/leaderboard_repository/lib/src/models/leaderboard_entry_data.g.dart/0 | {
"file_path": "pinball/packages/leaderboard_repository/lib/src/models/leaderboard_entry_data.g.dart",
"repo_id": "pinball",
"token_count": 298
} | 1,090 |
export 'android_bumper_ball_contact_behavior.dart';
export 'android_bumper_blinking_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/android_bumper/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/android_bumper/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 33
} | 1,091 |
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:pinball_theme/pinball_theme.dart';
part 'ball_state.dart';
class BallCubit extends Cubit<BallState> {
BallCubit() : super(const BallState.initial());
void onCharacterSelected(CharacterTheme characterTheme) {
emit(BallState(characterTheme: characterTheme));
}
}
| pinball/packages/pinball_components/lib/src/components/ball/cubit/ball_cubit.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/ball/cubit/ball_cubit.dart",
"repo_id": "pinball",
"token_count": 120
} | 1,092 |
part of 'chrome_dino_cubit.dart';
enum ChromeDinoStatus {
idle,
chomping,
}
class ChromeDinoState extends Equatable {
const ChromeDinoState({
required this.status,
required this.isMouthOpen,
this.ball,
});
const ChromeDinoState.initial()
: this(
status: ChromeDinoStatus.idle,
isMouthOpen: false,
);
final ChromeDinoStatus status;
final bool isMouthOpen;
final Ball? ball;
ChromeDinoState copyWith({
ChromeDinoStatus? status,
bool? isMouthOpen,
Ball? ball,
}) {
final state = ChromeDinoState(
status: status ?? this.status,
isMouthOpen: isMouthOpen ?? this.isMouthOpen,
ball: ball ?? this.ball,
);
return state;
}
@override
List<Object?> get props => [
status,
isMouthOpen,
ball,
];
}
| pinball/packages/pinball_components/lib/src/components/chrome_dino/cubit/chrome_dino_state.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/chrome_dino/cubit/chrome_dino_state.dart",
"repo_id": "pinball",
"token_count": 356
} | 1,093 |
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball_components/pinball_components.dart';
class FlipperMovingBehavior extends Component
with
FlameBlocListenable<FlipperCubit, FlipperState>,
FlameBlocReader<FlipperCubit, FlipperState> {
FlipperMovingBehavior({
required double strength,
}) : assert(strength >= 0, "Strength can't be negative"),
_strength = strength;
final double _strength;
late final Flipper _flipper;
void _moveUp() {
_flipper.body.linearVelocity = Vector2(0, -_strength);
}
void _moveDown() => _flipper.body.linearVelocity = Vector2(0, _strength);
@override
void onNewState(FlipperState state) {
super.onNewState(state);
if (bloc.state.isMovingDown) _moveDown();
}
@override
void update(double dt) {
super.update(dt);
if (bloc.state.isMovingUp) _moveUp();
}
@override
Future<void> onLoad() async {
await super.onLoad();
_flipper = parent!.parent! as Flipper;
_moveDown();
}
}
| pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_moving_behavior.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/flipper/behaviors/flipper_moving_behavior.dart",
"repo_id": "pinball",
"token_count": 393
} | 1,094 |
export 'kicker_ball_contact_behavior.dart';
export 'kicker_blinking_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/kicker/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/kicker/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 29
} | 1,095 |
part of 'multiplier_cubit.dart';
enum MultiplierSpriteState {
lit,
dimmed,
}
class MultiplierState extends Equatable {
const MultiplierState({
required this.value,
required this.spriteState,
});
const MultiplierState.initial(MultiplierValue multiplierValue)
: this(
value: multiplierValue,
spriteState: MultiplierSpriteState.dimmed,
);
/// Current value for the [Multiplier]
final MultiplierValue value;
/// The [MultiplierSpriteGroupComponent] current sprite state
final MultiplierSpriteState spriteState;
MultiplierState copyWith({
MultiplierSpriteState? spriteState,
}) {
return MultiplierState(
value: value,
spriteState: spriteState ?? this.spriteState,
);
}
@override
List<Object> get props => [value, spriteState];
}
extension MultiplierValueX on MultiplierValue {
bool equals(int value) {
switch (this) {
case MultiplierValue.x2:
return value == 2;
case MultiplierValue.x3:
return value == 3;
case MultiplierValue.x4:
return value == 4;
case MultiplierValue.x5:
return value == 5;
case MultiplierValue.x6:
return value == 6;
}
}
}
| pinball/packages/pinball_components/lib/src/components/multiplier/cubit/multiplier_state.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/multiplier/cubit/multiplier_state.dart",
"repo_id": "pinball",
"token_count": 477
} | 1,096 |
part of 'signpost_cubit.dart';
enum SignpostState {
/// Signpost with no active eggs.
inactive,
/// Signpost with a single sign of lit up eggs.
active1,
/// Signpost with two signs of lit up eggs.
active2,
/// Signpost with all signs of lit up eggs.
active3,
}
| pinball/packages/pinball_components/lib/src/components/signpost/cubit/signpost_state.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/signpost/cubit/signpost_state.dart",
"repo_id": "pinball",
"token_count": 92
} | 1,097 |
export 'sparky_bumper_ball_contact_behavior.dart';
export 'sparky_bumper_blinking_behavior.dart';
| pinball/packages/pinball_components/lib/src/components/sparky_bumper/behaviors/behaviors.dart/0 | {
"file_path": "pinball/packages/pinball_components/lib/src/components/sparky_bumper/behaviors/behaviors.dart",
"repo_id": "pinball",
"token_count": 37
} | 1,098 |
import 'dart:async';
import 'package:flame/input.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class SpaceshipRampGame extends BallGame with KeyboardEvents {
SpaceshipRampGame()
: super(
ballPriority: ZIndexes.ballOnSpaceshipRamp,
ballLayer: Layer.spaceshipEntranceRamp,
imagesFileNames: [
Assets.images.android.ramp.railingBackground.keyName,
Assets.images.android.ramp.main.keyName,
Assets.images.android.ramp.boardOpening.keyName,
Assets.images.android.ramp.railingForeground.keyName,
Assets.images.android.ramp.arrow.inactive.keyName,
Assets.images.android.ramp.arrow.active1.keyName,
Assets.images.android.ramp.arrow.active2.keyName,
Assets.images.android.ramp.arrow.active3.keyName,
Assets.images.android.ramp.arrow.active4.keyName,
Assets.images.android.ramp.arrow.active5.keyName,
],
);
static const description = '''
Shows how SpaceshipRamp is rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a ball into the game.
- Press space to progress arrow sprites.
''';
@override
Color backgroundColor() => Colors.white;
late final SpaceshipRamp _spaceshipRamp;
@override
Future<void> onLoad() async {
await super.onLoad();
camera.followVector2(Vector2(-12, -50));
_spaceshipRamp = SpaceshipRamp();
await add(_spaceshipRamp);
await traceAllBodies();
}
@override
KeyEventResult onKeyEvent(
RawKeyEvent event,
Set<LogicalKeyboardKey> keysPressed,
) {
if (event is RawKeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.space) {
_spaceshipRamp
.readBloc<SpaceshipRampCubit, SpaceshipRampState>()
.onProgressed();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/android_acres/spaceship_ramp_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/android_acres/spaceship_ramp_game.dart",
"repo_id": "pinball",
"token_count": 866
} | 1,099 |
import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class SlingshotsGame extends BallGame {
SlingshotsGame()
: super(
imagesFileNames: [
Assets.images.slingshot.upper.keyName,
Assets.images.slingshot.lower.keyName,
],
);
static const description = '''
Shows how Slingshots are rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a ball into the game.
''';
@override
Future<void> onLoad() async {
await super.onLoad();
camera.followVector2(Vector2.zero());
await add(Slingshots());
await ready();
await traceAllBodies();
}
}
| pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/slingshots_game.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/dino_desert/slingshots_game.dart",
"repo_id": "pinball",
"token_count": 297
} | 1,100 |
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/layer/layer_game.dart';
void addLayerStories(Dashbook dashbook) {
dashbook.storiesOf('Layer').addGame(
title: 'Example',
description: LayerGame.description,
gameBuilder: (_) => LayerGame(),
);
}
| pinball/packages/pinball_components/sandbox/lib/stories/layer/stories.dart/0 | {
"file_path": "pinball/packages/pinball_components/sandbox/lib/stories/layer/stories.dart",
"repo_id": "pinball",
"token_count": 129
} | 1,101 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_theme/pinball_theme.dart' as theme;
import '../../../helpers/helpers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
theme.Assets.images.android.background.keyName,
theme.Assets.images.dash.background.keyName,
theme.Assets.images.dino.background.keyName,
theme.Assets.images.sparky.background.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
group('ArcadeBackground', () {
test(
'can be instantiated',
() {
expect(ArcadeBackground(), isA<ArcadeBackground>());
expect(ArcadeBackground.test(), isA<ArcadeBackground>());
},
);
flameTester.test(
'loads correctly',
(game) async {
final ball = ArcadeBackground();
await game.ready();
await game.ensureAdd(ball);
expect(game.contains(ball), isTrue);
},
);
flameTester.test(
'has only one SpriteComponent',
(game) async {
final ball = ArcadeBackground();
await game.ready();
await game.ensureAdd(ball);
expect(
ball.descendants().whereType<SpriteComponent>().length,
equals(1),
);
},
);
flameTester.test(
'ArcadeBackgroundSpriteComponent changes sprite onNewState',
(game) async {
final ball = ArcadeBackground();
await game.ready();
await game.ensureAdd(ball);
final ballSprite = ball
.descendants()
.whereType<ArcadeBackgroundSpriteComponent>()
.single;
final originalSprite = ballSprite.sprite;
ballSprite.onNewState(
const ArcadeBackgroundState(characterTheme: theme.DinoTheme()),
);
await game.ready();
final newSprite = ballSprite.sprite;
expect(newSprite != originalSprite, isTrue);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/arcade_background/arcade_background_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/arcade_background/arcade_background_test.dart",
"repo_id": "pinball",
"token_count": 876
} | 1,102 |
// ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/src/components/bumping_behavior.dart';
import '../../helpers/helpers.dart';
class _MockContact extends Mock implements Contact {}
class _MockContactImpulse extends Mock implements ContactImpulse {}
class _TestBodyComponent extends BodyComponent {
@override
Body createBody() => world.createBody(
BodyDef(type: BodyType.dynamic),
)..createFixtureFromShape(CircleShape(), 1);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
group('BumpingBehavior', () {
test('can be instantiated', () {
expect(
BumpingBehavior(strength: 0),
isA<BumpingBehavior>(),
);
});
test('throws assertion error when strength is negative ', () {
expect(
() => BumpingBehavior(strength: -1),
throwsAssertionError,
);
});
flameTester.test('can be added', (game) async {
final behavior = BumpingBehavior(strength: 0);
final component = _TestBodyComponent();
await component.add(behavior);
await game.ensureAdd(component);
});
flameTester.testGameWidget(
'the bump is greater when the strength is greater',
setUp: (game, tester) async {
final component1 = _TestBodyComponent();
final behavior1 = BumpingBehavior(strength: 1)
..worldManifold.normal.setFrom(Vector2.all(1));
await component1.add(behavior1);
final component2 = _TestBodyComponent();
final behavior2 = BumpingBehavior(strength: 2)
..worldManifold.normal.setFrom(Vector2.all(1));
await component2.add(behavior2);
final dummy1 = _TestBodyComponent();
final dummy2 = _TestBodyComponent();
await game.ensureAddAll([
component1,
component2,
dummy1,
dummy2,
]);
final contact = _MockContact();
final contactImpulse = _MockContactImpulse();
behavior1.postSolve(dummy1, contact, contactImpulse);
behavior2.postSolve(dummy2, contact, contactImpulse);
expect(
dummy2.body.linearVelocity.x,
greaterThan(dummy1.body.linearVelocity.x),
);
expect(
dummy2.body.linearVelocity.y,
greaterThan(dummy1.body.linearVelocity.y),
);
},
);
});
}
| pinball/packages/pinball_components/test/src/components/bumping_behavior_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/bumping_behavior_test.dart",
"repo_id": "pinball",
"token_count": 1048
} | 1,103 |
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/bumping_behavior.dart';
import 'package:pinball_components/src/components/dash_bumper/behaviors/behaviors.dart';
class _TestGame extends Forge2DGame {
@override
Future<void> onLoad() async {
images.prefix = '';
await images.loadAll([
Assets.images.dash.bumper.main.active.keyName,
Assets.images.dash.bumper.main.inactive.keyName,
Assets.images.dash.bumper.a.active.keyName,
Assets.images.dash.bumper.a.inactive.keyName,
Assets.images.dash.bumper.b.active.keyName,
Assets.images.dash.bumper.b.inactive.keyName,
]);
}
Future<void> pump(DashBumper child) async {
await ensureAdd(
FlameBlocProvider<DashBumpersCubit, DashBumpersState>.value(
value: DashBumpersCubit(),
children: [child],
),
);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(_TestGame.new);
group('DashBumper', () {
flameTester.test('"main" can be added', (game) async {
final bumper = DashBumper.main();
await game.pump(bumper);
expect(game.descendants().contains(bumper), isTrue);
});
flameTester.test('"a" can be added', (game) async {
final bumper = DashBumper.a();
await game.pump(bumper);
expect(game.descendants().contains(bumper), isTrue);
});
flameTester.test('"b" can be added', (game) async {
final bumper = DashBumper.b();
await game.pump(bumper);
expect(game.descendants().contains(bumper), isTrue);
});
flameTester.test('adds a DashBumperBallContactBehavior', (game) async {
final bumper = DashBumper.a();
await game.pump(bumper);
expect(
bumper.children.whereType<DashBumperBallContactBehavior>().single,
isNotNull,
);
});
group("'main' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final bumper = DashBumper.main(
children: [component],
);
await game.pump(bumper);
expect(bumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final bumper = DashBumper.main();
await game.pump(bumper);
expect(
bumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
group("'a' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final bumper = DashBumper.a(
children: [component],
);
await game.pump(bumper);
expect(bumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final bumper = DashBumper.a();
await game.pump(bumper);
expect(
bumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
group("'b' adds", () {
flameTester.test('new children', (game) async {
final component = Component();
final bumper = DashBumper.b(
children: [component],
);
await game.pump(bumper);
expect(bumper.children, contains(component));
});
flameTester.test('a BumpingBehavior', (game) async {
final bumper = DashBumper.b();
await game.pump(bumper);
expect(
bumper.children.whereType<BumpingBehavior>().single,
isNotNull,
);
});
});
group('SpriteGroupComponent', () {
const mainBumperActivatedState = DashBumpersState(
bumperSpriteStates: {
DashBumperId.main: DashBumperSpriteState.active,
DashBumperId.a: DashBumperSpriteState.inactive,
DashBumperId.b: DashBumperSpriteState.inactive,
},
);
group('listenWhen', () {
flameTester.test(
'is true when the sprite state for the given ID has changed',
(game) async {
final bumper = DashBumper.main();
await game.pump(bumper);
final listenWhen =
bumper.firstChild<DashBumperSpriteGroupComponent>()!.listenWhen(
DashBumpersState.initial(),
mainBumperActivatedState,
);
expect(listenWhen, isTrue);
},
);
flameTester.test(
'onNewState updates the current sprite',
(game) async {
final bumper = DashBumper.main();
await game.pump(bumper);
final spriteGroupComponent =
bumper.firstChild<DashBumperSpriteGroupComponent>()!;
final originalSprite = spriteGroupComponent.current;
spriteGroupComponent.onNewState(mainBumperActivatedState);
await game.ready();
final newSprite = spriteGroupComponent.current;
expect(newSprite, isNot(equals(originalSprite)));
},
);
});
});
});
}
| pinball/packages/pinball_components/test/src/components/dash_nest_bumper/dash_bumper_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/dash_nest_bumper/dash_bumper_test.dart",
"repo_id": "pinball",
"token_count": 2350
} | 1,104 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group('GoogleWordState', () {
test('supports value equality', () {
expect(
GoogleWordState(
letterSpriteStates: const {
0: GoogleLetterSpriteState.dimmed,
1: GoogleLetterSpriteState.dimmed,
2: GoogleLetterSpriteState.dimmed,
3: GoogleLetterSpriteState.dimmed,
4: GoogleLetterSpriteState.dimmed,
5: GoogleLetterSpriteState.dimmed,
},
),
equals(
GoogleWordState(
letterSpriteStates: const {
0: GoogleLetterSpriteState.dimmed,
1: GoogleLetterSpriteState.dimmed,
2: GoogleLetterSpriteState.dimmed,
3: GoogleLetterSpriteState.dimmed,
4: GoogleLetterSpriteState.dimmed,
5: GoogleLetterSpriteState.dimmed,
},
),
),
);
});
group('constructor', () {
test('can be instantiated', () {
expect(
const GoogleWordState(letterSpriteStates: {}),
isNotNull,
);
});
test('initial has all dimmed sprite states', () {
const initialState = GoogleWordState(
letterSpriteStates: {
0: GoogleLetterSpriteState.dimmed,
1: GoogleLetterSpriteState.dimmed,
2: GoogleLetterSpriteState.dimmed,
3: GoogleLetterSpriteState.dimmed,
4: GoogleLetterSpriteState.dimmed,
5: GoogleLetterSpriteState.dimmed,
},
);
expect(GoogleWordState.initial(), equals(initialState));
});
});
});
}
| pinball/packages/pinball_components/test/src/components/google_word/cubit/google_word_state_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/google_word/cubit/google_word_state_test.dart",
"repo_id": "pinball",
"token_count": 849
} | 1,105 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/src/pinball_components.dart';
void main() {
group('MultiplierState', () {
test('supports value equality', () {
expect(
MultiplierState(
value: MultiplierValue.x2,
spriteState: MultiplierSpriteState.lit,
),
equals(
MultiplierState(
value: MultiplierValue.x2,
spriteState: MultiplierSpriteState.lit,
),
),
);
});
group('constructor', () {
test('can be instantiated', () {
expect(
MultiplierState(
value: MultiplierValue.x2,
spriteState: MultiplierSpriteState.lit,
),
isNotNull,
);
});
});
group('copyWith', () {
test(
'copies correctly '
'when no argument specified',
() {
const multiplierState = MultiplierState(
value: MultiplierValue.x2,
spriteState: MultiplierSpriteState.lit,
);
expect(
multiplierState.copyWith(),
equals(multiplierState),
);
},
);
test(
'copies correctly '
'when all arguments specified',
() {
const multiplierState = MultiplierState(
value: MultiplierValue.x2,
spriteState: MultiplierSpriteState.lit,
);
final otherMultiplierState = MultiplierState(
value: MultiplierValue.x2,
spriteState: MultiplierSpriteState.dimmed,
);
expect(multiplierState, isNot(equals(otherMultiplierState)));
expect(
multiplierState.copyWith(
spriteState: MultiplierSpriteState.dimmed,
),
equals(otherMultiplierState),
);
},
);
});
});
}
| pinball/packages/pinball_components/test/src/components/multiplier/cubit/multiplier_state_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/multiplier/cubit/multiplier_state_test.dart",
"repo_id": "pinball",
"token_count": 967
} | 1,106 |
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group(
'SkillShotCubit',
() {
blocTest<SkillShotCubit, SkillShotState>(
'onBallContacted emits lit and true',
build: SkillShotCubit.new,
act: (bloc) => bloc.onBallContacted(),
expect: () => [
SkillShotState(
spriteState: SkillShotSpriteState.lit,
isBlinking: true,
),
],
);
blocTest<SkillShotCubit, SkillShotState>(
'switched emits lit when dimmed',
build: SkillShotCubit.new,
act: (bloc) => bloc.switched(),
expect: () => [
isA<SkillShotState>().having(
(state) => state.spriteState,
'spriteState',
SkillShotSpriteState.lit,
)
],
);
blocTest<SkillShotCubit, SkillShotState>(
'switched emits dimmed when lit',
build: SkillShotCubit.new,
seed: () => SkillShotState(
spriteState: SkillShotSpriteState.lit,
isBlinking: false,
),
act: (bloc) => bloc.switched(),
expect: () => [
isA<SkillShotState>().having(
(state) => state.spriteState,
'spriteState',
SkillShotSpriteState.dimmed,
)
],
);
blocTest<SkillShotCubit, SkillShotState>(
'onBlinkingFinished emits dimmed and false',
build: SkillShotCubit.new,
act: (bloc) => bloc.onBlinkingFinished(),
expect: () => [
SkillShotState(
spriteState: SkillShotSpriteState.dimmed,
isBlinking: false,
),
],
);
},
);
}
| pinball/packages/pinball_components/test/src/components/skill_shot/cubit/skill_shot_cubit_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/skill_shot/cubit/skill_shot_cubit_test.dart",
"repo_id": "pinball",
"token_count": 896
} | 1,107 |
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/sparky_computer/behaviors/behaviors.dart';
import '../../../helpers/helpers.dart';
class _MockSparkyComputerCubit extends Mock implements SparkyComputerCubit {}
void main() {
group('SparkyComputer', () {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.sparky.computer.base.keyName,
Assets.images.sparky.computer.top.keyName,
Assets.images.sparky.computer.glow.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
flameTester.test('loads correctly', (game) async {
final component = SparkyComputer();
await game.ensureAdd(component);
expect(game.contains(component), isTrue);
});
flameTester.testGameWidget(
'renders correctly',
setUp: (game, tester) async {
await game.images.loadAll(assets);
await game.ensureAdd(SparkyComputer());
await tester.pump();
game.camera
..followVector2(Vector2(0, -20))
..zoom = 7;
},
verify: (game, tester) async {
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('../golden/sparky_computer.png'),
);
},
);
flameTester.test('closes bloc when removed', (game) async {
final bloc = _MockSparkyComputerCubit();
whenListen(
bloc,
const Stream<SparkyComputerState>.empty(),
initialState: SparkyComputerState.withoutBall,
);
when(bloc.close).thenAnswer((_) async {});
final sparkyComputer = SparkyComputer.test(bloc: bloc);
await game.ensureAdd(sparkyComputer);
game.remove(sparkyComputer);
await game.ready();
verify(bloc.close).called(1);
});
group('adds', () {
flameTester.test('new children', (game) async {
final component = Component();
final sparkyComputer = SparkyComputer(
children: [component],
);
await game.ensureAdd(sparkyComputer);
expect(sparkyComputer.children, contains(component));
});
flameTester.test('a SparkyComputerSensorBallContactBehavior',
(game) async {
final sparkyComputer = SparkyComputer();
await game.ensureAdd(sparkyComputer);
expect(
sparkyComputer.children
.whereType<SparkyComputerSensorBallContactBehavior>()
.single,
isNotNull,
);
});
});
});
}
| pinball/packages/pinball_components/test/src/components/sparky_computer/sparky_computer_test.dart/0 | {
"file_path": "pinball/packages/pinball_components/test/src/components/sparky_computer/sparky_computer_test.dart",
"repo_id": "pinball",
"token_count": 1159
} | 1,108 |
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
/// {@template layered}
/// Modifies maskBits and categoryBits of all the [BodyComponent]'s [Fixture]s
/// to specify what other [BodyComponent]s it can collide with.
///
/// [BodyComponent]s with compatible [Layer]s can collide with each other,
/// ignoring others. This compatibility depends on bit masking operation
/// between layers. For more information read: https://en.wikipedia.org/wiki/Mask_(computing).
/// {@endtemplate}
mixin Layered on BodyComponent {
Layer _layer = Layer.all;
/// {@macro layered}
Layer get layer => _layer;
set layer(Layer value) {
_layer = value;
if (!isLoaded) {
loaded.whenComplete(_applyMaskBits);
} else {
_applyMaskBits();
}
}
void _applyMaskBits() {
for (final fixture in body.fixtures) {
fixture
..filterData.categoryBits = layer.maskBits
..filterData.maskBits = layer.maskBits;
}
}
}
/// The [Layer]s a [BodyComponent] can be in.
///
/// Each [Layer] is associated with a maskBits value to define possible
/// collisions within that plane.
///
/// Usually used with [Layered].
enum Layer {
/// Collide with all elements.
all,
/// Collide only with board elements (the ground level).
board,
/// Collide only with ramps opening elements.
opening,
/// Collide only with Spaceship entrance ramp group elements.
spaceshipEntranceRamp,
/// Collide only with Launcher group elements.
launcher,
/// Collide only with Spaceship group elements.
spaceship,
/// Collide only with Spaceship exit rail group elements.
spaceshipExitRail,
}
/// {@template layer_mask_bits}
/// Specifies the maskBits of each [Layer].
///
/// Used by [Layered] to specify what other [BodyComponent]s it can collide
///
/// Note: the maximum value for maskBits is 2^16.
/// {@endtemplate}
@visibleForTesting
extension LayerMaskBits on Layer {
/// {@macro layer_mask_bits}
@visibleForTesting
int get maskBits {
switch (this) {
case Layer.all:
return 0xFFFF;
case Layer.board:
return 0x0001;
case Layer.opening:
return 0x0007;
case Layer.spaceshipEntranceRamp:
return 0x0002;
case Layer.launcher:
return 0x0008;
case Layer.spaceship:
return 0x000A;
case Layer.spaceshipExitRail:
return 0x0004;
}
}
}
| pinball/packages/pinball_flame/lib/src/layer.dart/0 | {
"file_path": "pinball/packages/pinball_flame/lib/src/layer.dart",
"repo_id": "pinball",
"token_count": 838
} | 1,109 |
// ignore_for_file: cascade_invocations
import 'package:bloc/bloc.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_flame/pinball_flame.dart';
class _FakeCubit extends Fake implements Cubit<Object> {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(FlameGame.new);
group(
'FlameProvider',
() {
test('can be instantiated', () {
expect(
FlameProvider<bool>.value(true),
isA<FlameProvider<bool>>(),
);
});
flameTester.test('can be loaded', (game) async {
final component = FlameProvider<bool>.value(true);
await game.ensureAdd(component);
expect(game.children, contains(component));
});
flameTester.test('adds children', (game) async {
final component = Component();
final provider = FlameProvider<bool>.value(
true,
children: [component],
);
await game.ensureAdd(provider);
expect(provider.children, contains(component));
});
},
);
group('MultiFlameProvider', () {
test('can be instantiated', () {
expect(
MultiFlameProvider(
providers: [
FlameProvider<bool>.value(true),
],
),
isA<MultiFlameProvider>(),
);
});
flameTester.test('adds multiple providers', (game) async {
final provider1 = FlameProvider<bool>.value(true);
final provider2 = FlameProvider<bool>.value(true);
final providers = MultiFlameProvider(
providers: [provider1, provider2],
);
await game.ensureAdd(providers);
expect(providers.children, contains(provider1));
expect(provider1.children, contains(provider2));
});
flameTester.test('adds children under provider', (game) async {
final component = Component();
final provider = FlameProvider<bool>.value(true);
final providers = MultiFlameProvider(
providers: [provider],
children: [component],
);
await game.ensureAdd(providers);
expect(provider.children, contains(component));
});
});
group(
'ReadFlameProvider',
() {
flameTester.test('loads provider', (game) async {
final component = Component();
final provider = FlameProvider<bool>.value(
true,
children: [component],
);
await game.ensureAdd(provider);
expect(component.readProvider<bool>(), isTrue);
});
flameTester.test(
'throws assertionError when no provider is found',
(game) async {
final component = Component();
await game.ensureAdd(component);
expect(
() => component.readProvider<bool>(),
throwsAssertionError,
);
},
);
},
);
group(
'ReadFlameBlocProvider',
() {
flameTester.test('loads provider', (game) async {
final component = Component();
final bloc = _FakeCubit();
final provider = FlameBlocProvider<_FakeCubit, Object>.value(
value: bloc,
children: [component],
);
await game.ensureAdd(provider);
expect(component.readBloc<_FakeCubit, Object>(), equals(bloc));
});
flameTester.test(
'throws assertionError when no provider is found',
(game) async {
final component = Component();
await game.ensureAdd(component);
expect(
() => component.readBloc<_FakeCubit, Object>(),
throwsAssertionError,
);
},
);
},
);
}
| pinball/packages/pinball_flame/test/src/flame_provider_test.dart/0 | {
"file_path": "pinball/packages/pinball_flame/test/src/flame_provider_test.dart",
"repo_id": "pinball",
"token_count": 1601
} | 1,110 |
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_theme/pinball_theme.dart';
void main() {
group('DinoTheme', () {
test('can be instantiated', () {
expect(DinoTheme(), isNotNull);
});
test('supports value equality', () {
expect(DinoTheme(), equals(DinoTheme()));
});
});
}
| pinball/packages/pinball_theme/test/src/themes/dino_theme_test.dart/0 | {
"file_path": "pinball/packages/pinball_theme/test/src/themes/dino_theme_test.dart",
"repo_id": "pinball",
"token_count": 143
} | 1,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.