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. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #else #error("Unsupported platform.") #endif private func wrapResult(_ result: Any?) -> [Any?] { return [result] } private func wrapError(_ error: Any) -> [Any?] { if let flutterError = error as? FlutterError { return [ flutterError.code, flutterError.message, flutterError.details, ] } return [ "\(error)", "\(type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } private func createConnectionError(withChannelName channelName: String) -> FlutterError { return FlutterError( code: "channel-error", message: "Unable to establish connection on channel: '\(channelName)'.", details: "") } private func isNullish(_ value: Any?) -> Bool { return value is NSNull || value == nil } private func nilOrValue<T>(_ value: Any?) -> T? { if value is NSNull { return nil } return value as! T? } enum AnEnum: Int { case one = 0 case two = 1 case three = 2 case fortyTwo = 3 case fourHundredTwentyTwo = 4 } /// A class containing all supported types. /// /// Generated class from Pigeon that represents data sent in messages. struct AllTypes { var aBool: Bool var anInt: Int64 var anInt64: Int64 var aDouble: Double var aByteArray: FlutterStandardTypedData var a4ByteArray: FlutterStandardTypedData var a8ByteArray: FlutterStandardTypedData var aFloatArray: FlutterStandardTypedData var aList: [Any?] var aMap: [AnyHashable: Any?] var anEnum: AnEnum var aString: String var anObject: Any static func fromList(_ list: [Any?]) -> AllTypes? { let aBool = list[0] as! Bool let anInt = list[1] is Int64 ? list[1] as! Int64 : Int64(list[1] as! Int32) let anInt64 = list[2] is Int64 ? list[2] as! Int64 : Int64(list[2] as! Int32) let aDouble = list[3] as! Double let aByteArray = list[4] as! FlutterStandardTypedData let a4ByteArray = list[5] as! FlutterStandardTypedData let a8ByteArray = list[6] as! FlutterStandardTypedData let aFloatArray = list[7] as! FlutterStandardTypedData let aList = list[8] as! [Any?] let aMap = list[9] as! [AnyHashable: Any?] let anEnum = AnEnum(rawValue: list[10] as! Int)! let aString = list[11] as! String let anObject = list[12]! return AllTypes( aBool: aBool, anInt: anInt, anInt64: anInt64, aDouble: aDouble, aByteArray: aByteArray, a4ByteArray: a4ByteArray, a8ByteArray: a8ByteArray, aFloatArray: aFloatArray, aList: aList, aMap: aMap, anEnum: anEnum, aString: aString, anObject: anObject ) } func toList() -> [Any?] { return [ aBool, anInt, anInt64, aDouble, aByteArray, a4ByteArray, a8ByteArray, aFloatArray, aList, aMap, anEnum.rawValue, aString, anObject, ] } } /// A class containing all supported nullable types. /// /// Generated class from Pigeon that represents data sent in messages. struct AllNullableTypes { var aNullableBool: Bool? = nil var aNullableInt: Int64? = nil var aNullableInt64: Int64? = nil var aNullableDouble: Double? = nil var aNullableByteArray: FlutterStandardTypedData? = nil var aNullable4ByteArray: FlutterStandardTypedData? = nil var aNullable8ByteArray: FlutterStandardTypedData? = nil var aNullableFloatArray: FlutterStandardTypedData? = nil var aNullableList: [Any?]? = nil var aNullableMap: [AnyHashable: Any?]? = nil var nullableNestedList: [[Bool?]?]? = nil var nullableMapWithAnnotations: [String?: String?]? = nil var nullableMapWithObject: [String?: Any?]? = nil var aNullableEnum: AnEnum? = nil var aNullableString: String? = nil var aNullableObject: Any? = nil static func fromList(_ list: [Any?]) -> AllNullableTypes? { let aNullableBool: Bool? = nilOrValue(list[0]) let aNullableInt: Int64? = isNullish(list[1]) ? nil : (list[1] is Int64? ? list[1] as! Int64? : Int64(list[1] as! Int32)) let aNullableInt64: Int64? = isNullish(list[2]) ? nil : (list[2] is Int64? ? list[2] as! Int64? : Int64(list[2] as! Int32)) let aNullableDouble: Double? = nilOrValue(list[3]) let aNullableByteArray: FlutterStandardTypedData? = nilOrValue(list[4]) let aNullable4ByteArray: FlutterStandardTypedData? = nilOrValue(list[5]) let aNullable8ByteArray: FlutterStandardTypedData? = nilOrValue(list[6]) let aNullableFloatArray: FlutterStandardTypedData? = nilOrValue(list[7]) let aNullableList: [Any?]? = nilOrValue(list[8]) let aNullableMap: [AnyHashable: Any?]? = nilOrValue(list[9]) let nullableNestedList: [[Bool?]?]? = nilOrValue(list[10]) let nullableMapWithAnnotations: [String?: String?]? = nilOrValue(list[11]) let nullableMapWithObject: [String?: Any?]? = nilOrValue(list[12]) var aNullableEnum: AnEnum? = nil let aNullableEnumEnumVal: Int? = nilOrValue(list[13]) if let aNullableEnumRawValue = aNullableEnumEnumVal { aNullableEnum = AnEnum(rawValue: aNullableEnumRawValue)! } let aNullableString: String? = nilOrValue(list[14]) let aNullableObject: Any? = list[15] return AllNullableTypes( aNullableBool: aNullableBool, aNullableInt: aNullableInt, aNullableInt64: aNullableInt64, aNullableDouble: aNullableDouble, aNullableByteArray: aNullableByteArray, aNullable4ByteArray: aNullable4ByteArray, aNullable8ByteArray: aNullable8ByteArray, aNullableFloatArray: aNullableFloatArray, aNullableList: aNullableList, aNullableMap: aNullableMap, nullableNestedList: nullableNestedList, nullableMapWithAnnotations: nullableMapWithAnnotations, nullableMapWithObject: nullableMapWithObject, aNullableEnum: aNullableEnum, aNullableString: aNullableString, aNullableObject: aNullableObject ) } func toList() -> [Any?] { return [ aNullableBool, aNullableInt, aNullableInt64, aNullableDouble, aNullableByteArray, aNullable4ByteArray, aNullable8ByteArray, aNullableFloatArray, aNullableList, aNullableMap, nullableNestedList, nullableMapWithAnnotations, nullableMapWithObject, aNullableEnum?.rawValue, aNullableString, aNullableObject, ] } } /// A class for testing nested class handling. /// /// This is needed to test nested nullable and non-nullable classes, /// `AllNullableTypes` is non-nullable here as it is easier to instantiate /// than `AllTypes` when testing doesn't require both (ie. testing null classes). /// /// Generated class from Pigeon that represents data sent in messages. struct AllClassesWrapper { var allNullableTypes: AllNullableTypes var allTypes: AllTypes? = nil static func fromList(_ list: [Any?]) -> AllClassesWrapper? { let allNullableTypes = AllNullableTypes.fromList(list[0] as! [Any?])! var allTypes: AllTypes? = nil if let allTypesList: [Any?] = nilOrValue(list[1]) { allTypes = AllTypes.fromList(allTypesList) } return AllClassesWrapper( allNullableTypes: allNullableTypes, allTypes: allTypes ) } func toList() -> [Any?] { return [ allNullableTypes.toList(), allTypes?.toList(), ] } } /// A data class containing a List, used in unit tests. /// /// Generated class from Pigeon that represents data sent in messages. struct TestMessage { var testList: [Any?]? = nil static func fromList(_ list: [Any?]) -> TestMessage? { let testList: [Any?]? = nilOrValue(list[0]) return TestMessage( testList: testList ) } func toList() -> [Any?] { return [ testList ] } } private class HostIntegrationCoreApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: return AllClassesWrapper.fromList(self.readValue() as! [Any?]) case 129: return AllNullableTypes.fromList(self.readValue() as! [Any?]) case 130: return AllTypes.fromList(self.readValue() as! [Any?]) case 131: return TestMessage.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } } } private class HostIntegrationCoreApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { if let value = value as? AllClassesWrapper { super.writeByte(128) super.writeValue(value.toList()) } else if let value = value as? AllNullableTypes { super.writeByte(129) super.writeValue(value.toList()) } else if let value = value as? AllTypes { super.writeByte(130) super.writeValue(value.toList()) } else if let value = value as? TestMessage { super.writeByte(131) super.writeValue(value.toList()) } else { super.writeValue(value) } } } private class HostIntegrationCoreApiCodecReaderWriter: FlutterStandardReaderWriter { override func reader(with data: Data) -> FlutterStandardReader { return HostIntegrationCoreApiCodecReader(data: data) } override func writer(with data: NSMutableData) -> FlutterStandardWriter { return HostIntegrationCoreApiCodecWriter(data: data) } } class HostIntegrationCoreApiCodec: FlutterStandardMessageCodec { static let shared = HostIntegrationCoreApiCodec( readerWriter: HostIntegrationCoreApiCodecReaderWriter()) } /// The core interface that each host language plugin must implement in /// platform_test integration tests. /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol HostIntegrationCoreApi { /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. func noop() throws /// Returns the passed object, to test serialization and deserialization. func echo(_ everything: AllTypes) throws -> AllTypes /// Returns an error, to test error handling. func throwError() throws -> Any? /// Returns an error from a void function, to test error handling. func throwErrorFromVoid() throws /// Returns a Flutter error, to test error handling. func throwFlutterError() throws -> Any? /// Returns passed in int. func echo(_ anInt: Int64) throws -> Int64 /// Returns passed in double. func echo(_ aDouble: Double) throws -> Double /// Returns the passed in boolean. func echo(_ aBool: Bool) throws -> Bool /// Returns the passed in string. func echo(_ aString: String) throws -> String /// Returns the passed in Uint8List. func echo(_ aUint8List: FlutterStandardTypedData) throws -> FlutterStandardTypedData /// Returns the passed in generic Object. func echo(_ anObject: Any) throws -> Any /// Returns the passed list, to test serialization and deserialization. func echo(_ aList: [Any?]) throws -> [Any?] /// Returns the passed map, to test serialization and deserialization. func echo(_ aMap: [String?: Any?]) throws -> [String?: Any?] /// Returns the passed map to test nested class serialization and deserialization. func echo(_ wrapper: AllClassesWrapper) throws -> AllClassesWrapper /// Returns the passed enum to test serialization and deserialization. func echo(_ anEnum: AnEnum) throws -> AnEnum /// Returns the default string. func echoNamedDefault(_ aString: String) throws -> String /// Returns passed in double. func echoOptionalDefault(_ aDouble: Double) throws -> Double /// Returns passed in int. func echoRequired(_ anInt: Int64) throws -> Int64 /// Returns the passed object, to test serialization and deserialization. func echo(_ everything: AllNullableTypes?) throws -> AllNullableTypes? /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. func extractNestedNullableString(from wrapper: AllClassesWrapper) throws -> String? /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. func createNestedObject(with nullableString: String?) throws -> AllClassesWrapper /// Returns passed in arguments of multiple types. func sendMultipleNullableTypes( aBool aNullableBool: Bool?, anInt aNullableInt: Int64?, aString aNullableString: String? ) throws -> AllNullableTypes /// Returns passed in int. func echo(_ aNullableInt: Int64?) throws -> Int64? /// Returns passed in double. func echo(_ aNullableDouble: Double?) throws -> Double? /// Returns the passed in boolean. func echo(_ aNullableBool: Bool?) throws -> Bool? /// Returns the passed in string. func echo(_ aNullableString: String?) throws -> String? /// Returns the passed in Uint8List. func echo(_ aNullableUint8List: FlutterStandardTypedData?) throws -> FlutterStandardTypedData? /// Returns the passed in generic Object. func echo(_ aNullableObject: Any?) throws -> Any? /// Returns the passed list, to test serialization and deserialization. func echoNullable(_ aNullableList: [Any?]?) throws -> [Any?]? /// Returns the passed map, to test serialization and deserialization. func echoNullable(_ aNullableMap: [String?: Any?]?) throws -> [String?: Any?]? func echoNullable(_ anEnum: AnEnum?) throws -> AnEnum? /// Returns passed in int. func echoOptional(_ aNullableInt: Int64?) throws -> Int64? /// Returns the passed in string. func echoNamed(_ aNullableString: String?) throws -> String? /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. func noopAsync(completion: @escaping (Result<Void, Error>) -> Void) /// Returns passed in int asynchronously. func echoAsync(_ anInt: Int64, completion: @escaping (Result<Int64, Error>) -> Void) /// Returns passed in double asynchronously. func echoAsync(_ aDouble: Double, completion: @escaping (Result<Double, Error>) -> Void) /// Returns the passed in boolean asynchronously. func echoAsync(_ aBool: Bool, completion: @escaping (Result<Bool, Error>) -> Void) /// Returns the passed string asynchronously. func echoAsync(_ aString: String, completion: @escaping (Result<String, Error>) -> Void) /// Returns the passed in Uint8List asynchronously. func echoAsync( _ aUint8List: FlutterStandardTypedData, completion: @escaping (Result<FlutterStandardTypedData, Error>) -> Void) /// Returns the passed in generic Object asynchronously. func echoAsync(_ anObject: Any, completion: @escaping (Result<Any, Error>) -> Void) /// Returns the passed list, to test asynchronous serialization and deserialization. func echoAsync(_ aList: [Any?], completion: @escaping (Result<[Any?], Error>) -> Void) /// Returns the passed map, to test asynchronous serialization and deserialization. func echoAsync( _ aMap: [String?: Any?], completion: @escaping (Result<[String?: Any?], Error>) -> Void) /// Returns the passed enum, to test asynchronous serialization and deserialization. func echoAsync(_ anEnum: AnEnum, completion: @escaping (Result<AnEnum, Error>) -> Void) /// Responds with an error from an async function returning a value. func throwAsyncError(completion: @escaping (Result<Any?, Error>) -> Void) /// Responds with an error from an async void function. func throwAsyncErrorFromVoid(completion: @escaping (Result<Void, Error>) -> Void) /// Responds with a Flutter error from an async function returning a value. func throwAsyncFlutterError(completion: @escaping (Result<Any?, Error>) -> Void) /// Returns the passed object, to test async serialization and deserialization. func echoAsync(_ everything: AllTypes, completion: @escaping (Result<AllTypes, Error>) -> Void) /// Returns the passed object, to test serialization and deserialization. func echoAsync( _ everything: AllNullableTypes?, completion: @escaping (Result<AllNullableTypes?, Error>) -> Void) /// Returns passed in int asynchronously. func echoAsyncNullable(_ anInt: Int64?, completion: @escaping (Result<Int64?, Error>) -> Void) /// Returns passed in double asynchronously. func echoAsyncNullable(_ aDouble: Double?, completion: @escaping (Result<Double?, Error>) -> Void) /// Returns the passed in boolean asynchronously. func echoAsyncNullable(_ aBool: Bool?, completion: @escaping (Result<Bool?, Error>) -> Void) /// Returns the passed string asynchronously. func echoAsyncNullable(_ aString: String?, completion: @escaping (Result<String?, Error>) -> Void) /// Returns the passed in Uint8List asynchronously. func echoAsyncNullable( _ aUint8List: FlutterStandardTypedData?, completion: @escaping (Result<FlutterStandardTypedData?, Error>) -> Void) /// Returns the passed in generic Object asynchronously. func echoAsyncNullable(_ anObject: Any?, completion: @escaping (Result<Any?, Error>) -> Void) /// Returns the passed list, to test asynchronous serialization and deserialization. func echoAsyncNullable(_ aList: [Any?]?, completion: @escaping (Result<[Any?]?, Error>) -> Void) /// Returns the passed map, to test asynchronous serialization and deserialization. func echoAsyncNullable( _ aMap: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, Error>) -> Void) /// Returns the passed enum, to test asynchronous serialization and deserialization. func echoAsyncNullable(_ anEnum: AnEnum?, completion: @escaping (Result<AnEnum?, Error>) -> Void) func callFlutterNoop(completion: @escaping (Result<Void, Error>) -> Void) func callFlutterThrowError(completion: @escaping (Result<Any?, Error>) -> Void) func callFlutterThrowErrorFromVoid(completion: @escaping (Result<Void, Error>) -> Void) func callFlutterEcho( _ everything: AllTypes, completion: @escaping (Result<AllTypes, Error>) -> Void) func callFlutterEcho( _ everything: AllNullableTypes?, completion: @escaping (Result<AllNullableTypes?, Error>) -> Void) func callFlutterSendMultipleNullableTypes( aBool aNullableBool: Bool?, anInt aNullableInt: Int64?, aString aNullableString: String?, completion: @escaping (Result<AllNullableTypes, Error>) -> Void) func callFlutterEcho(_ aBool: Bool, completion: @escaping (Result<Bool, Error>) -> Void) func callFlutterEcho(_ anInt: Int64, completion: @escaping (Result<Int64, Error>) -> Void) func callFlutterEcho(_ aDouble: Double, completion: @escaping (Result<Double, Error>) -> Void) func callFlutterEcho(_ aString: String, completion: @escaping (Result<String, Error>) -> Void) func callFlutterEcho( _ aList: FlutterStandardTypedData, completion: @escaping (Result<FlutterStandardTypedData, Error>) -> Void) func callFlutterEcho(_ aList: [Any?], completion: @escaping (Result<[Any?], Error>) -> Void) func callFlutterEcho( _ aMap: [String?: Any?], completion: @escaping (Result<[String?: Any?], Error>) -> Void) func callFlutterEcho(_ anEnum: AnEnum, completion: @escaping (Result<AnEnum, Error>) -> Void) func callFlutterEchoNullable(_ aBool: Bool?, completion: @escaping (Result<Bool?, Error>) -> Void) func callFlutterEchoNullable( _ anInt: Int64?, completion: @escaping (Result<Int64?, Error>) -> Void) func callFlutterEchoNullable( _ aDouble: Double?, completion: @escaping (Result<Double?, Error>) -> Void) func callFlutterEchoNullable( _ aString: String?, completion: @escaping (Result<String?, Error>) -> Void) func callFlutterEchoNullable( _ aList: FlutterStandardTypedData?, completion: @escaping (Result<FlutterStandardTypedData?, Error>) -> Void) func callFlutterEchoNullable( _ aList: [Any?]?, completion: @escaping (Result<[Any?]?, Error>) -> Void) func callFlutterEchoNullable( _ aMap: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, Error>) -> Void) func callFlutterNullableEcho( _ anEnum: AnEnum?, completion: @escaping (Result<AnEnum?, Error>) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class HostIntegrationCoreApiSetup { /// The codec used by HostIntegrationCoreApi. static var codec: FlutterStandardMessageCodec { HostIntegrationCoreApiCodec.shared } /// Sets up an instance of `HostIntegrationCoreApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: HostIntegrationCoreApi?) { /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. let noopChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noop", binaryMessenger: binaryMessenger, codec: codec) if let api = api { noopChannel.setMessageHandler { _, reply in do { try api.noop() reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { noopChannel.setMessageHandler(nil) } /// Returns the passed object, to test serialization and deserialization. let echoAllTypesChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllTypes", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAllTypesChannel.setMessageHandler { message, reply in let args = message as! [Any?] let everythingArg = args[0] as! AllTypes do { let result = try api.echo(everythingArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoAllTypesChannel.setMessageHandler(nil) } /// Returns an error, to test error handling. let throwErrorChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwError", binaryMessenger: binaryMessenger, codec: codec) if let api = api { throwErrorChannel.setMessageHandler { _, reply in do { let result = try api.throwError() reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { throwErrorChannel.setMessageHandler(nil) } /// Returns an error from a void function, to test error handling. let throwErrorFromVoidChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwErrorFromVoid", binaryMessenger: binaryMessenger, codec: codec) if let api = api { throwErrorFromVoidChannel.setMessageHandler { _, reply in do { try api.throwErrorFromVoid() reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { throwErrorFromVoidChannel.setMessageHandler(nil) } /// Returns a Flutter error, to test error handling. let throwFlutterErrorChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwFlutterError", binaryMessenger: binaryMessenger, codec: codec) if let api = api { throwFlutterErrorChannel.setMessageHandler { _, reply in do { let result = try api.throwFlutterError() reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { throwFlutterErrorChannel.setMessageHandler(nil) } /// Returns passed in int. let echoIntChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoInt", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoIntChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anIntArg = args[0] is Int64 ? args[0] as! Int64 : Int64(args[0] as! Int32) do { let result = try api.echo(anIntArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoIntChannel.setMessageHandler(nil) } /// Returns passed in double. let echoDoubleChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoDouble", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aDoubleArg = args[0] as! Double do { let result = try api.echo(aDoubleArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoDoubleChannel.setMessageHandler(nil) } /// Returns the passed in boolean. let echoBoolChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoBool", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoBoolChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aBoolArg = args[0] as! Bool do { let result = try api.echo(aBoolArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoBoolChannel.setMessageHandler(nil) } /// Returns the passed in string. let echoStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aStringArg = args[0] as! String do { let result = try api.echo(aStringArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoStringChannel.setMessageHandler(nil) } /// Returns the passed in Uint8List. let echoUint8ListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoUint8List", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoUint8ListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aUint8ListArg = args[0] as! FlutterStandardTypedData do { let result = try api.echo(aUint8ListArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoUint8ListChannel.setMessageHandler(nil) } /// Returns the passed in generic Object. let echoObjectChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoObject", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoObjectChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anObjectArg = args[0]! do { let result = try api.echo(anObjectArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoObjectChannel.setMessageHandler(nil) } /// Returns the passed list, to test serialization and deserialization. let echoListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoList", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aListArg = args[0] as! [Any?] do { let result = try api.echo(aListArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoListChannel.setMessageHandler(nil) } /// Returns the passed map, to test serialization and deserialization. let echoMapChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoMap", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoMapChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aMapArg = args[0] as! [String?: Any?] do { let result = try api.echo(aMapArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoMapChannel.setMessageHandler(nil) } /// Returns the passed map to test nested class serialization and deserialization. let echoClassWrapperChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassWrapper", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoClassWrapperChannel.setMessageHandler { message, reply in let args = message as! [Any?] let wrapperArg = args[0] as! AllClassesWrapper do { let result = try api.echo(wrapperArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoClassWrapperChannel.setMessageHandler(nil) } /// Returns the passed enum to test serialization and deserialization. let echoEnumChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnum", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoEnumChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anEnumArg = AnEnum(rawValue: args[0] as! Int)! do { let result = try api.echo(anEnumArg) reply(wrapResult(result.rawValue)) } catch { reply(wrapError(error)) } } } else { echoEnumChannel.setMessageHandler(nil) } /// Returns the default string. let echoNamedDefaultStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNamedDefaultString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNamedDefaultStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aStringArg = args[0] as! String do { let result = try api.echoNamedDefault(aStringArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNamedDefaultStringChannel.setMessageHandler(nil) } /// Returns passed in double. let echoOptionalDefaultDoubleChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoOptionalDefaultDouble", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoOptionalDefaultDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aDoubleArg = args[0] as! Double do { let result = try api.echoOptionalDefault(aDoubleArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoOptionalDefaultDoubleChannel.setMessageHandler(nil) } /// Returns passed in int. let echoRequiredIntChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoRequiredInt", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoRequiredIntChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anIntArg = args[0] is Int64 ? args[0] as! Int64 : Int64(args[0] as! Int32) do { let result = try api.echoRequired(anIntArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoRequiredIntChannel.setMessageHandler(nil) } /// Returns the passed object, to test serialization and deserialization. let echoAllNullableTypesChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllNullableTypes", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAllNullableTypesChannel.setMessageHandler { message, reply in let args = message as! [Any?] let everythingArg: AllNullableTypes? = nilOrValue(args[0]) do { let result = try api.echo(everythingArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoAllNullableTypesChannel.setMessageHandler(nil) } /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. let extractNestedNullableStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.extractNestedNullableString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { extractNestedNullableStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let wrapperArg = args[0] as! AllClassesWrapper do { let result = try api.extractNestedNullableString(from: wrapperArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { extractNestedNullableStringChannel.setMessageHandler(nil) } /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. let createNestedNullableStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.createNestedNullableString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { createNestedNullableStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let nullableStringArg: String? = nilOrValue(args[0]) do { let result = try api.createNestedObject(with: nullableStringArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { createNestedNullableStringChannel.setMessageHandler(nil) } /// Returns passed in arguments of multiple types. let sendMultipleNullableTypesChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.sendMultipleNullableTypes", binaryMessenger: binaryMessenger, codec: codec) if let api = api { sendMultipleNullableTypesChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableBoolArg: Bool? = nilOrValue(args[0]) let aNullableIntArg: Int64? = isNullish(args[1]) ? nil : (args[1] is Int64? ? args[1] as! Int64? : Int64(args[1] as! Int32)) let aNullableStringArg: String? = nilOrValue(args[2]) do { let result = try api.sendMultipleNullableTypes( aBool: aNullableBoolArg, anInt: aNullableIntArg, aString: aNullableStringArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { sendMultipleNullableTypesChannel.setMessageHandler(nil) } /// Returns passed in int. let echoNullableIntChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableInt", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableIntChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableIntArg: Int64? = isNullish(args[0]) ? nil : (args[0] is Int64? ? args[0] as! Int64? : Int64(args[0] as! Int32)) do { let result = try api.echo(aNullableIntArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNullableIntChannel.setMessageHandler(nil) } /// Returns passed in double. let echoNullableDoubleChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableDouble", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableDoubleArg: Double? = nilOrValue(args[0]) do { let result = try api.echo(aNullableDoubleArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNullableDoubleChannel.setMessageHandler(nil) } /// Returns the passed in boolean. let echoNullableBoolChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableBool", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableBoolChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableBoolArg: Bool? = nilOrValue(args[0]) do { let result = try api.echo(aNullableBoolArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNullableBoolChannel.setMessageHandler(nil) } /// Returns the passed in string. let echoNullableStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableStringArg: String? = nilOrValue(args[0]) do { let result = try api.echo(aNullableStringArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNullableStringChannel.setMessageHandler(nil) } /// Returns the passed in Uint8List. let echoNullableUint8ListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableUint8List", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableUint8ListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableUint8ListArg: FlutterStandardTypedData? = nilOrValue(args[0]) do { let result = try api.echo(aNullableUint8ListArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNullableUint8ListChannel.setMessageHandler(nil) } /// Returns the passed in generic Object. let echoNullableObjectChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableObject", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableObjectChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableObjectArg: Any? = args[0] do { let result = try api.echo(aNullableObjectArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNullableObjectChannel.setMessageHandler(nil) } /// Returns the passed list, to test serialization and deserialization. let echoNullableListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableList", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableListArg: [Any?]? = nilOrValue(args[0]) do { let result = try api.echoNullable(aNullableListArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNullableListChannel.setMessageHandler(nil) } /// Returns the passed map, to test serialization and deserialization. let echoNullableMapChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableMap", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableMapChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableMapArg: [String?: Any?]? = nilOrValue(args[0]) do { let result = try api.echoNullable(aNullableMapArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNullableMapChannel.setMessageHandler(nil) } let echoNullableEnumChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnum", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNullableEnumChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anEnumArg: AnEnum? = isNullish(args[0]) ? nil : AnEnum(rawValue: args[0] as! Int)! do { let result = try api.echoNullable(anEnumArg) reply(wrapResult(result?.rawValue)) } catch { reply(wrapError(error)) } } } else { echoNullableEnumChannel.setMessageHandler(nil) } /// Returns passed in int. let echoOptionalNullableIntChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoOptionalNullableInt", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoOptionalNullableIntChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableIntArg: Int64? = isNullish(args[0]) ? nil : (args[0] is Int64? ? args[0] as! Int64? : Int64(args[0] as! Int32)) do { let result = try api.echoOptional(aNullableIntArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoOptionalNullableIntChannel.setMessageHandler(nil) } /// Returns the passed in string. let echoNamedNullableStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNamedNullableString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoNamedNullableStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableStringArg: String? = nilOrValue(args[0]) do { let result = try api.echoNamed(aNullableStringArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { echoNamedNullableStringChannel.setMessageHandler(nil) } /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. let noopAsyncChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noopAsync", binaryMessenger: binaryMessenger, codec: codec) if let api = api { noopAsyncChannel.setMessageHandler { _, reply in api.noopAsync { result in switch result { case .success: reply(wrapResult(nil)) case .failure(let error): reply(wrapError(error)) } } } } else { noopAsyncChannel.setMessageHandler(nil) } /// Returns passed in int asynchronously. let echoAsyncIntChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncInt", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncIntChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anIntArg = args[0] is Int64 ? args[0] as! Int64 : Int64(args[0] as! Int32) api.echoAsync(anIntArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncIntChannel.setMessageHandler(nil) } /// Returns passed in double asynchronously. let echoAsyncDoubleChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncDouble", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aDoubleArg = args[0] as! Double api.echoAsync(aDoubleArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncDoubleChannel.setMessageHandler(nil) } /// Returns the passed in boolean asynchronously. let echoAsyncBoolChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncBool", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncBoolChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aBoolArg = args[0] as! Bool api.echoAsync(aBoolArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncBoolChannel.setMessageHandler(nil) } /// Returns the passed string asynchronously. let echoAsyncStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aStringArg = args[0] as! String api.echoAsync(aStringArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncStringChannel.setMessageHandler(nil) } /// Returns the passed in Uint8List asynchronously. let echoAsyncUint8ListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncUint8List", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncUint8ListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aUint8ListArg = args[0] as! FlutterStandardTypedData api.echoAsync(aUint8ListArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncUint8ListChannel.setMessageHandler(nil) } /// Returns the passed in generic Object asynchronously. let echoAsyncObjectChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncObject", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncObjectChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anObjectArg = args[0]! api.echoAsync(anObjectArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncObjectChannel.setMessageHandler(nil) } /// Returns the passed list, to test asynchronous serialization and deserialization. let echoAsyncListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncList", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aListArg = args[0] as! [Any?] api.echoAsync(aListArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncListChannel.setMessageHandler(nil) } /// Returns the passed map, to test asynchronous serialization and deserialization. let echoAsyncMapChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncMap", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncMapChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aMapArg = args[0] as! [String?: Any?] api.echoAsync(aMapArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncMapChannel.setMessageHandler(nil) } /// Returns the passed enum, to test asynchronous serialization and deserialization. let echoAsyncEnumChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnum", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncEnumChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anEnumArg = AnEnum(rawValue: args[0] as! Int)! api.echoAsync(anEnumArg) { result in switch result { case .success(let res): reply(wrapResult(res.rawValue)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncEnumChannel.setMessageHandler(nil) } /// Responds with an error from an async function returning a value. let throwAsyncErrorChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncError", binaryMessenger: binaryMessenger, codec: codec) if let api = api { throwAsyncErrorChannel.setMessageHandler { _, reply in api.throwAsyncError { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { throwAsyncErrorChannel.setMessageHandler(nil) } /// Responds with an error from an async void function. let throwAsyncErrorFromVoidChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncErrorFromVoid", binaryMessenger: binaryMessenger, codec: codec) if let api = api { throwAsyncErrorFromVoidChannel.setMessageHandler { _, reply in api.throwAsyncErrorFromVoid { result in switch result { case .success: reply(wrapResult(nil)) case .failure(let error): reply(wrapError(error)) } } } } else { throwAsyncErrorFromVoidChannel.setMessageHandler(nil) } /// Responds with a Flutter error from an async function returning a value. let throwAsyncFlutterErrorChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncFlutterError", binaryMessenger: binaryMessenger, codec: codec) if let api = api { throwAsyncFlutterErrorChannel.setMessageHandler { _, reply in api.throwAsyncFlutterError { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { throwAsyncFlutterErrorChannel.setMessageHandler(nil) } /// Returns the passed object, to test async serialization and deserialization. let echoAsyncAllTypesChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncAllTypes", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncAllTypesChannel.setMessageHandler { message, reply in let args = message as! [Any?] let everythingArg = args[0] as! AllTypes api.echoAsync(everythingArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncAllTypesChannel.setMessageHandler(nil) } /// Returns the passed object, to test serialization and deserialization. let echoAsyncNullableAllNullableTypesChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableAllNullableTypes", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableAllNullableTypesChannel.setMessageHandler { message, reply in let args = message as! [Any?] let everythingArg: AllNullableTypes? = nilOrValue(args[0]) api.echoAsync(everythingArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableAllNullableTypesChannel.setMessageHandler(nil) } /// Returns passed in int asynchronously. let echoAsyncNullableIntChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableInt", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableIntChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anIntArg: Int64? = isNullish(args[0]) ? nil : (args[0] is Int64? ? args[0] as! Int64? : Int64(args[0] as! Int32)) api.echoAsyncNullable(anIntArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableIntChannel.setMessageHandler(nil) } /// Returns passed in double asynchronously. let echoAsyncNullableDoubleChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableDouble", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aDoubleArg: Double? = nilOrValue(args[0]) api.echoAsyncNullable(aDoubleArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableDoubleChannel.setMessageHandler(nil) } /// Returns the passed in boolean asynchronously. let echoAsyncNullableBoolChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableBool", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableBoolChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aBoolArg: Bool? = nilOrValue(args[0]) api.echoAsyncNullable(aBoolArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableBoolChannel.setMessageHandler(nil) } /// Returns the passed string asynchronously. let echoAsyncNullableStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aStringArg: String? = nilOrValue(args[0]) api.echoAsyncNullable(aStringArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableStringChannel.setMessageHandler(nil) } /// Returns the passed in Uint8List asynchronously. let echoAsyncNullableUint8ListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableUint8List", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableUint8ListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aUint8ListArg: FlutterStandardTypedData? = nilOrValue(args[0]) api.echoAsyncNullable(aUint8ListArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableUint8ListChannel.setMessageHandler(nil) } /// Returns the passed in generic Object asynchronously. let echoAsyncNullableObjectChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableObject", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableObjectChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anObjectArg: Any? = args[0] api.echoAsyncNullable(anObjectArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableObjectChannel.setMessageHandler(nil) } /// Returns the passed list, to test asynchronous serialization and deserialization. let echoAsyncNullableListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableList", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aListArg: [Any?]? = nilOrValue(args[0]) api.echoAsyncNullable(aListArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableListChannel.setMessageHandler(nil) } /// Returns the passed map, to test asynchronous serialization and deserialization. let echoAsyncNullableMapChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableMap", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableMapChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aMapArg: [String?: Any?]? = nilOrValue(args[0]) api.echoAsyncNullable(aMapArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableMapChannel.setMessageHandler(nil) } /// Returns the passed enum, to test asynchronous serialization and deserialization. let echoAsyncNullableEnumChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnum", binaryMessenger: binaryMessenger, codec: codec) if let api = api { echoAsyncNullableEnumChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anEnumArg: AnEnum? = isNullish(args[0]) ? nil : AnEnum(rawValue: args[0] as! Int)! api.echoAsyncNullable(anEnumArg) { result in switch result { case .success(let res): reply(wrapResult(res?.rawValue)) case .failure(let error): reply(wrapError(error)) } } } } else { echoAsyncNullableEnumChannel.setMessageHandler(nil) } let callFlutterNoopChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterNoop", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterNoopChannel.setMessageHandler { _, reply in api.callFlutterNoop { result in switch result { case .success: reply(wrapResult(nil)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterNoopChannel.setMessageHandler(nil) } let callFlutterThrowErrorChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterThrowError", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterThrowErrorChannel.setMessageHandler { _, reply in api.callFlutterThrowError { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterThrowErrorChannel.setMessageHandler(nil) } let callFlutterThrowErrorFromVoidChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterThrowErrorFromVoid", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterThrowErrorFromVoidChannel.setMessageHandler { _, reply in api.callFlutterThrowErrorFromVoid { result in switch result { case .success: reply(wrapResult(nil)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterThrowErrorFromVoidChannel.setMessageHandler(nil) } let callFlutterEchoAllTypesChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllTypes", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoAllTypesChannel.setMessageHandler { message, reply in let args = message as! [Any?] let everythingArg = args[0] as! AllTypes api.callFlutterEcho(everythingArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoAllTypesChannel.setMessageHandler(nil) } let callFlutterEchoAllNullableTypesChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllNullableTypes", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoAllNullableTypesChannel.setMessageHandler { message, reply in let args = message as! [Any?] let everythingArg: AllNullableTypes? = nilOrValue(args[0]) api.callFlutterEcho(everythingArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoAllNullableTypesChannel.setMessageHandler(nil) } let callFlutterSendMultipleNullableTypesChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterSendMultipleNullableTypes", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterSendMultipleNullableTypesChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aNullableBoolArg: Bool? = nilOrValue(args[0]) let aNullableIntArg: Int64? = isNullish(args[1]) ? nil : (args[1] is Int64? ? args[1] as! Int64? : Int64(args[1] as! Int32)) let aNullableStringArg: String? = nilOrValue(args[2]) api.callFlutterSendMultipleNullableTypes( aBool: aNullableBoolArg, anInt: aNullableIntArg, aString: aNullableStringArg ) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterSendMultipleNullableTypesChannel.setMessageHandler(nil) } let callFlutterEchoBoolChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoBool", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoBoolChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aBoolArg = args[0] as! Bool api.callFlutterEcho(aBoolArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoBoolChannel.setMessageHandler(nil) } let callFlutterEchoIntChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoInt", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoIntChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anIntArg = args[0] is Int64 ? args[0] as! Int64 : Int64(args[0] as! Int32) api.callFlutterEcho(anIntArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoIntChannel.setMessageHandler(nil) } let callFlutterEchoDoubleChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoDouble", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aDoubleArg = args[0] as! Double api.callFlutterEcho(aDoubleArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoDoubleChannel.setMessageHandler(nil) } let callFlutterEchoStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aStringArg = args[0] as! String api.callFlutterEcho(aStringArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoStringChannel.setMessageHandler(nil) } let callFlutterEchoUint8ListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoUint8List", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoUint8ListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aListArg = args[0] as! FlutterStandardTypedData api.callFlutterEcho(aListArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoUint8ListChannel.setMessageHandler(nil) } let callFlutterEchoListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoList", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aListArg = args[0] as! [Any?] api.callFlutterEcho(aListArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoListChannel.setMessageHandler(nil) } let callFlutterEchoMapChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoMap", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoMapChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aMapArg = args[0] as! [String?: Any?] api.callFlutterEcho(aMapArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoMapChannel.setMessageHandler(nil) } let callFlutterEchoEnumChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnum", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoEnumChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anEnumArg = AnEnum(rawValue: args[0] as! Int)! api.callFlutterEcho(anEnumArg) { result in switch result { case .success(let res): reply(wrapResult(res.rawValue)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoEnumChannel.setMessageHandler(nil) } let callFlutterEchoNullableBoolChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableBool", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoNullableBoolChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aBoolArg: Bool? = nilOrValue(args[0]) api.callFlutterEchoNullable(aBoolArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoNullableBoolChannel.setMessageHandler(nil) } let callFlutterEchoNullableIntChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableInt", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoNullableIntChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anIntArg: Int64? = isNullish(args[0]) ? nil : (args[0] is Int64? ? args[0] as! Int64? : Int64(args[0] as! Int32)) api.callFlutterEchoNullable(anIntArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoNullableIntChannel.setMessageHandler(nil) } let callFlutterEchoNullableDoubleChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableDouble", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoNullableDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aDoubleArg: Double? = nilOrValue(args[0]) api.callFlutterEchoNullable(aDoubleArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoNullableDoubleChannel.setMessageHandler(nil) } let callFlutterEchoNullableStringChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableString", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoNullableStringChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aStringArg: String? = nilOrValue(args[0]) api.callFlutterEchoNullable(aStringArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoNullableStringChannel.setMessageHandler(nil) } let callFlutterEchoNullableUint8ListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableUint8List", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoNullableUint8ListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aListArg: FlutterStandardTypedData? = nilOrValue(args[0]) api.callFlutterEchoNullable(aListArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoNullableUint8ListChannel.setMessageHandler(nil) } let callFlutterEchoNullableListChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableList", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoNullableListChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aListArg: [Any?]? = nilOrValue(args[0]) api.callFlutterEchoNullable(aListArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoNullableListChannel.setMessageHandler(nil) } let callFlutterEchoNullableMapChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableMap", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoNullableMapChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aMapArg: [String?: Any?]? = nilOrValue(args[0]) api.callFlutterEchoNullable(aMapArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoNullableMapChannel.setMessageHandler(nil) } let callFlutterEchoNullableEnumChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnum", binaryMessenger: binaryMessenger, codec: codec) if let api = api { callFlutterEchoNullableEnumChannel.setMessageHandler { message, reply in let args = message as! [Any?] let anEnumArg: AnEnum? = isNullish(args[0]) ? nil : AnEnum(rawValue: args[0] as! Int)! api.callFlutterNullableEcho(anEnumArg) { result in switch result { case .success(let res): reply(wrapResult(res?.rawValue)) case .failure(let error): reply(wrapError(error)) } } } } else { callFlutterEchoNullableEnumChannel.setMessageHandler(nil) } } } private class FlutterIntegrationCoreApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: return AllClassesWrapper.fromList(self.readValue() as! [Any?]) case 129: return AllNullableTypes.fromList(self.readValue() as! [Any?]) case 130: return AllTypes.fromList(self.readValue() as! [Any?]) case 131: return TestMessage.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } } } private class FlutterIntegrationCoreApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { if let value = value as? AllClassesWrapper { super.writeByte(128) super.writeValue(value.toList()) } else if let value = value as? AllNullableTypes { super.writeByte(129) super.writeValue(value.toList()) } else if let value = value as? AllTypes { super.writeByte(130) super.writeValue(value.toList()) } else if let value = value as? TestMessage { super.writeByte(131) super.writeValue(value.toList()) } else { super.writeValue(value) } } } private class FlutterIntegrationCoreApiCodecReaderWriter: FlutterStandardReaderWriter { override func reader(with data: Data) -> FlutterStandardReader { return FlutterIntegrationCoreApiCodecReader(data: data) } override func writer(with data: NSMutableData) -> FlutterStandardWriter { return FlutterIntegrationCoreApiCodecWriter(data: data) } } class FlutterIntegrationCoreApiCodec: FlutterStandardMessageCodec { static let shared = FlutterIntegrationCoreApiCodec( readerWriter: FlutterIntegrationCoreApiCodecReaderWriter()) } /// The core interface that the Dart platform_test code implements for host /// integration tests to call into. /// /// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. protocol FlutterIntegrationCoreApiProtocol { /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. func noop(completion: @escaping (Result<Void, FlutterError>) -> Void) /// Responds with an error from an async function returning a value. func throwError(completion: @escaping (Result<Any?, FlutterError>) -> Void) /// Responds with an error from an async void function. func throwErrorFromVoid(completion: @escaping (Result<Void, FlutterError>) -> Void) /// Returns the passed object, to test serialization and deserialization. func echo( _ everythingArg: AllTypes, completion: @escaping (Result<AllTypes, FlutterError>) -> Void) /// Returns the passed object, to test serialization and deserialization. func echoNullable( _ everythingArg: AllNullableTypes?, completion: @escaping (Result<AllNullableTypes?, FlutterError>) -> Void) /// Returns passed in arguments of multiple types. /// /// Tests multiple-arity FlutterApi handling. func sendMultipleNullableTypes( aBool aNullableBoolArg: Bool?, anInt aNullableIntArg: Int64?, aString aNullableStringArg: String?, completion: @escaping (Result<AllNullableTypes, FlutterError>) -> Void) /// Returns the passed boolean, to test serialization and deserialization. func echo(_ aBoolArg: Bool, completion: @escaping (Result<Bool, FlutterError>) -> Void) /// Returns the passed int, to test serialization and deserialization. func echo(_ anIntArg: Int64, completion: @escaping (Result<Int64, FlutterError>) -> Void) /// Returns the passed double, to test serialization and deserialization. func echo(_ aDoubleArg: Double, completion: @escaping (Result<Double, FlutterError>) -> Void) /// Returns the passed string, to test serialization and deserialization. func echo(_ aStringArg: String, completion: @escaping (Result<String, FlutterError>) -> Void) /// Returns the passed byte list, to test serialization and deserialization. func echo( _ aListArg: FlutterStandardTypedData, completion: @escaping (Result<FlutterStandardTypedData, FlutterError>) -> Void) /// Returns the passed list, to test serialization and deserialization. func echo(_ aListArg: [Any?], completion: @escaping (Result<[Any?], FlutterError>) -> Void) /// Returns the passed map, to test serialization and deserialization. func echo( _ aMapArg: [String?: Any?], completion: @escaping (Result<[String?: Any?], FlutterError>) -> Void) /// Returns the passed enum to test serialization and deserialization. func echo(_ anEnumArg: AnEnum, completion: @escaping (Result<AnEnum, FlutterError>) -> Void) /// Returns the passed boolean, to test serialization and deserialization. func echoNullable(_ aBoolArg: Bool?, completion: @escaping (Result<Bool?, FlutterError>) -> Void) /// Returns the passed int, to test serialization and deserialization. func echoNullable( _ anIntArg: Int64?, completion: @escaping (Result<Int64?, FlutterError>) -> Void) /// Returns the passed double, to test serialization and deserialization. func echoNullable( _ aDoubleArg: Double?, completion: @escaping (Result<Double?, FlutterError>) -> Void) /// Returns the passed string, to test serialization and deserialization. func echoNullable( _ aStringArg: String?, completion: @escaping (Result<String?, FlutterError>) -> Void) /// Returns the passed byte list, to test serialization and deserialization. func echoNullable( _ aListArg: FlutterStandardTypedData?, completion: @escaping (Result<FlutterStandardTypedData?, FlutterError>) -> Void) /// Returns the passed list, to test serialization and deserialization. func echoNullable( _ aListArg: [Any?]?, completion: @escaping (Result<[Any?]?, FlutterError>) -> Void) /// Returns the passed map, to test serialization and deserialization. func echoNullable( _ aMapArg: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, FlutterError>) -> Void) /// Returns the passed enum to test serialization and deserialization. func echoNullable( _ anEnumArg: AnEnum?, completion: @escaping (Result<AnEnum?, FlutterError>) -> Void) /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. func noopAsync(completion: @escaping (Result<Void, FlutterError>) -> Void) /// Returns the passed in generic Object asynchronously. func echoAsync(_ aStringArg: String, completion: @escaping (Result<String, FlutterError>) -> Void) } class FlutterIntegrationCoreApi: FlutterIntegrationCoreApiProtocol { private let binaryMessenger: FlutterBinaryMessenger init(binaryMessenger: FlutterBinaryMessenger) { self.binaryMessenger = binaryMessenger } var codec: FlutterStandardMessageCodec { return FlutterIntegrationCoreApiCodec.shared } /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. func noop(completion: @escaping (Result<Void, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noop" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { completion(.success(Void())) } } } /// Responds with an error from an async function returning a value. func throwError(completion: @escaping (Result<Any?, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwError" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: Any? = listResponse[0] completion(.success(result)) } } } /// Responds with an error from an async void function. func throwErrorFromVoid(completion: @escaping (Result<Void, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwErrorFromVoid" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { completion(.success(Void())) } } } /// Returns the passed object, to test serialization and deserialization. func echo( _ everythingArg: AllTypes, completion: @escaping (Result<AllTypes, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([everythingArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! AllTypes completion(.success(result)) } } } /// Returns the passed object, to test serialization and deserialization. func echoNullable( _ everythingArg: AllNullableTypes?, completion: @escaping (Result<AllNullableTypes?, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([everythingArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: AllNullableTypes? = nilOrValue(listResponse[0]) completion(.success(result)) } } } /// Returns passed in arguments of multiple types. /// /// Tests multiple-arity FlutterApi handling. func sendMultipleNullableTypes( aBool aNullableBoolArg: Bool?, anInt aNullableIntArg: Int64?, aString aNullableStringArg: String?, completion: @escaping (Result<AllNullableTypes, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypes" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aNullableBoolArg, aNullableIntArg, aNullableStringArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! AllNullableTypes completion(.success(result)) } } } /// Returns the passed boolean, to test serialization and deserialization. func echo(_ aBoolArg: Bool, completion: @escaping (Result<Bool, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aBoolArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! Bool completion(.success(result)) } } } /// Returns the passed int, to test serialization and deserialization. func echo(_ anIntArg: Int64, completion: @escaping (Result<Int64, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([anIntArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] is Int64 ? listResponse[0] as! Int64 : Int64(listResponse[0] as! Int32) completion(.success(result)) } } } /// Returns the passed double, to test serialization and deserialization. func echo(_ aDoubleArg: Double, completion: @escaping (Result<Double, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aDoubleArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! Double completion(.success(result)) } } } /// Returns the passed string, to test serialization and deserialization. func echo(_ aStringArg: String, completion: @escaping (Result<String, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aStringArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! String completion(.success(result)) } } } /// Returns the passed byte list, to test serialization and deserialization. func echo( _ aListArg: FlutterStandardTypedData, completion: @escaping (Result<FlutterStandardTypedData, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aListArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! FlutterStandardTypedData completion(.success(result)) } } } /// Returns the passed list, to test serialization and deserialization. func echo(_ aListArg: [Any?], completion: @escaping (Result<[Any?], FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aListArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! [Any?] completion(.success(result)) } } } /// Returns the passed map, to test serialization and deserialization. func echo( _ aMapArg: [String?: Any?], completion: @escaping (Result<[String?: Any?], FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aMapArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! [String?: Any?] completion(.success(result)) } } } /// Returns the passed enum to test serialization and deserialization. func echo(_ anEnumArg: AnEnum, completion: @escaping (Result<AnEnum, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([anEnumArg.rawValue] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = AnEnum(rawValue: listResponse[0] as! Int)! completion(.success(result)) } } } /// Returns the passed boolean, to test serialization and deserialization. func echoNullable(_ aBoolArg: Bool?, completion: @escaping (Result<Bool?, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aBoolArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: Bool? = nilOrValue(listResponse[0]) completion(.success(result)) } } } /// Returns the passed int, to test serialization and deserialization. func echoNullable( _ anIntArg: Int64?, completion: @escaping (Result<Int64?, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([anIntArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: Int64? = isNullish(listResponse[0]) ? nil : (listResponse[0] is Int64? ? listResponse[0] as! Int64? : Int64(listResponse[0] as! Int32)) completion(.success(result)) } } } /// Returns the passed double, to test serialization and deserialization. func echoNullable( _ aDoubleArg: Double?, completion: @escaping (Result<Double?, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aDoubleArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: Double? = nilOrValue(listResponse[0]) completion(.success(result)) } } } /// Returns the passed string, to test serialization and deserialization. func echoNullable( _ aStringArg: String?, completion: @escaping (Result<String?, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aStringArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: String? = nilOrValue(listResponse[0]) completion(.success(result)) } } } /// Returns the passed byte list, to test serialization and deserialization. func echoNullable( _ aListArg: FlutterStandardTypedData?, completion: @escaping (Result<FlutterStandardTypedData?, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableUint8List" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aListArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: FlutterStandardTypedData? = nilOrValue(listResponse[0]) completion(.success(result)) } } } /// Returns the passed list, to test serialization and deserialization. func echoNullable( _ aListArg: [Any?]?, completion: @escaping (Result<[Any?]?, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aListArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: [Any?]? = nilOrValue(listResponse[0]) completion(.success(result)) } } } /// Returns the passed map, to test serialization and deserialization. func echoNullable( _ aMapArg: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aMapArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: [String?: Any?]? = nilOrValue(listResponse[0]) completion(.success(result)) } } } /// Returns the passed enum to test serialization and deserialization. func echoNullable( _ anEnumArg: AnEnum?, completion: @escaping (Result<AnEnum?, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([anEnumArg?.rawValue] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { let result: AnEnum? = isNullish(listResponse[0]) ? nil : AnEnum(rawValue: listResponse[0] as! Int)! completion(.success(result)) } } } /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. func noopAsync(completion: @escaping (Result<Void, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noopAsync" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage(nil) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else { completion(.success(Void())) } } } /// Returns the passed in generic Object asynchronously. func echoAsync(_ aStringArg: String, completion: @escaping (Result<String, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aStringArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! String completion(.success(result)) } } } } /// An API that can be implemented for minimal, compile-only tests. /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol HostTrivialApi { func noop() throws } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class HostTrivialApiSetup { /// The codec used by HostTrivialApi. /// Sets up an instance of `HostTrivialApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: HostTrivialApi?) { let noopChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostTrivialApi.noop", binaryMessenger: binaryMessenger) if let api = api { noopChannel.setMessageHandler { _, reply in do { try api.noop() reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { noopChannel.setMessageHandler(nil) } } } /// A simple API implemented in some unit tests. /// /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol HostSmallApi { func echo(aString: String, completion: @escaping (Result<String, Error>) -> Void) func voidVoid(completion: @escaping (Result<Void, Error>) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class HostSmallApiSetup { /// The codec used by HostSmallApi. /// Sets up an instance of `HostSmallApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: HostSmallApi?) { let echoChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo", binaryMessenger: binaryMessenger) if let api = api { echoChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aStringArg = args[0] as! String api.echo(aString: aStringArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { echoChannel.setMessageHandler(nil) } let voidVoidChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid", binaryMessenger: binaryMessenger) if let api = api { voidVoidChannel.setMessageHandler { _, reply in api.voidVoid { result in switch result { case .success: reply(wrapResult(nil)) case .failure(let error): reply(wrapError(error)) } } } } else { voidVoidChannel.setMessageHandler(nil) } } } private class FlutterSmallApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: return TestMessage.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } } } private class FlutterSmallApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { if let value = value as? TestMessage { super.writeByte(128) super.writeValue(value.toList()) } else { super.writeValue(value) } } } private class FlutterSmallApiCodecReaderWriter: FlutterStandardReaderWriter { override func reader(with data: Data) -> FlutterStandardReader { return FlutterSmallApiCodecReader(data: data) } override func writer(with data: NSMutableData) -> FlutterStandardWriter { return FlutterSmallApiCodecWriter(data: data) } } class FlutterSmallApiCodec: FlutterStandardMessageCodec { static let shared = FlutterSmallApiCodec(readerWriter: FlutterSmallApiCodecReaderWriter()) } /// A simple API called in some unit tests. /// /// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. protocol FlutterSmallApiProtocol { func echo( _ msgArg: TestMessage, completion: @escaping (Result<TestMessage, FlutterError>) -> Void) func echo(_ aStringArg: String, completion: @escaping (Result<String, FlutterError>) -> Void) } class FlutterSmallApi: FlutterSmallApiProtocol { private let binaryMessenger: FlutterBinaryMessenger init(binaryMessenger: FlutterBinaryMessenger) { self.binaryMessenger = binaryMessenger } var codec: FlutterStandardMessageCodec { return FlutterSmallApiCodec.shared } func echo( _ msgArg: TestMessage, completion: @escaping (Result<TestMessage, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([msgArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! TestMessage completion(.success(result)) } } } func echo(_ aStringArg: String, completion: @escaping (Result<String, FlutterError>) -> Void) { let channelName: String = "dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString" let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([aStringArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! String completion(.success(result)) } } } }
packages/packages/pigeon/platform_tests/test_plugin/ios/Classes/CoreTests.gen.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/ios/Classes/CoreTests.gen.swift", "repo_id": "packages", "token_count": 47289 }
1,025
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' show Directory, File; import 'package:path/path.dart' as path; import 'package:pigeon/ast.dart'; import 'package:pigeon/dart_generator.dart'; import 'package:pigeon/generator_tools.dart'; import 'package:test/test.dart'; const String DEFAULT_PACKAGE_NAME = 'test_package'; final Class emptyClass = Class(name: 'className', fields: <NamedType>[ NamedType( name: 'namedTypeName', type: const TypeDeclaration(baseName: 'baseName', isNullable: false), ) ]); final Enum emptyEnum = Enum( name: 'enumName', members: <EnumMember>[EnumMember(name: 'enumMemberName')], ); void main() { test('gen one class', () { final Class classDefinition = Class( name: 'Foobar', fields: <NamedType>[ NamedType( type: TypeDeclaration( baseName: 'dataType1', isNullable: true, associatedClass: emptyClass, ), name: 'field1'), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains(' dataType1? field1;')); }); test('gen one enum', () { final Enum anEnum = Enum( name: 'Foobar', members: <EnumMember>[ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[], enums: <Enum>[anEnum], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('enum Foobar')); expect(code, contains(' one,')); expect(code, contains(' two,')); }); test('gen one host api', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: 'input') ], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input') ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output') ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('Future<Output> doSomething(Input input)')); }); 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('Future<int> add(int x, int y)')); expect(code, contains('await __pigeon_channel.send(<Object?>[x, y])')); }); 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('int add(int x, int y)')); expect(code, contains('final List<Object?> args = (message as List<Object?>?)!')); expect(code, contains('final int? arg_x = (args[0] as int?)')); expect(code, contains('final int? arg_y = (args[1] as int?)')); expect(code, contains('final int output = api.add(arg_x!, arg_y!)')); }); test('nested class', () { 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', isNullable: true, associatedClass: emptyClass, ), name: 'nested') ], ) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains( 'nested?.encode(),', ), ); expect( code.replaceAll('\n', ' ').replaceAll(' ', ''), contains( 'nested: result[0] != null ? Input.decode(result[0]! as List<Object?>) : null', ), ); }); test('nested non-nullable class', () { final Root root = Root(apis: <Api>[], classes: <Class>[ Class( name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: false, ), name: 'input') ], ), Class( name: 'Nested', fields: <NamedType>[ NamedType( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: 'nested') ], ) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains( 'nested.encode(),', ), ); expect( code.replaceAll('\n', ' ').replaceAll(' ', ''), contains( 'nested: Input.decode(result[0]! as List<Object?>)', ), ); }); test('flutterApi', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: 'input') ], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input') ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output') ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('abstract class Api')); expect(code, contains('static void setup(Api')); expect(code, contains('Output doSomething(Input input)')); }); test('host void', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: '') ], 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('Future<void> doSomething')); expect(code, contains('return;')); }); test('flutter void return', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: '') ], returnType: 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); // The next line verifies that we're not setting a variable to the value of "doSomething", but // ignores the line where we assert the value of the argument isn't null, since on that line // we mention "doSomething" in the assertion message. expect(code, isNot(matches('[^!]=.*doSomething'))); expect(code, contains('doSomething(')); }); test('flutter void argument', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), ) ]) ], classes: <Class>[ Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output') ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, matches('output.*=.*doSomething[(][)]')); expect(code, contains('Output doSomething();')); }); test('flutter enum argument with enum class', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'EnumClass', isNullable: false, associatedClass: emptyClass, ), name: 'enumClass') ], returnType: TypeDeclaration( baseName: 'EnumClass', isNullable: false, associatedClass: emptyClass, ), ) ]) ], classes: <Class>[ Class(name: 'EnumClass', fields: <NamedType>[ NamedType( type: TypeDeclaration( baseName: 'Enum', isNullable: true, associatedEnum: emptyEnum, ), name: 'enum1') ]), ], enums: <Enum>[ Enum( name: 'Enum', members: <EnumMember>[ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ) ]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('enum1?.index,')); expect(code, contains('? Enum.values[result[0]! as int]')); expect(code, contains('EnumClass doSomething(EnumClass enumClass);')); }); test('primitive enum host', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Bar', methods: <Method>[ Method( name: 'bar', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( name: 'foo', type: TypeDeclaration( baseName: 'Foo', isNullable: true, associatedEnum: emptyEnum, )) ]) ]) ], classes: <Class>[], enums: <Enum>[ Enum(name: 'Foo', members: <EnumMember>[ EnumMember(name: 'one'), EnumMember(name: 'two'), ]) ]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('enum Foo {')); expect(code, contains('Future<void> bar(Foo? foo) async')); expect(code, contains('__pigeon_channel.send(<Object?>[foo?.index])')); }); test('flutter non-nullable enum argument with enum class', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'EnumClass', isNullable: false, associatedClass: emptyClass, ), name: '') ], returnType: TypeDeclaration( baseName: 'EnumClass', isNullable: false, associatedClass: emptyClass, ), ) ]) ], classes: <Class>[ Class(name: 'EnumClass', fields: <NamedType>[ NamedType( type: TypeDeclaration( baseName: 'Enum', isNullable: false, associatedEnum: emptyEnum, ), name: 'enum1') ]), ], enums: <Enum>[ Enum( name: 'Enum', members: <EnumMember>[ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ) ]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('enum1.index,')); expect(code, contains('enum1: Enum.values[result[0]! as int]')); }); test('host void argument', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), ) ]) ], classes: <Class>[ Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output') ]), ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, matches('__pigeon_channel.send[(]null[)]')); }); test('mock dart handler', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', dartHostTestHandler: 'ApiMock', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: '') ], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), ), Method( name: 'voidReturner', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: '') ], returnType: const TypeDeclaration.voidDeclaration(), ) ]) ], 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 mainCodeSink = StringBuffer(); final StringBuffer testCodeSink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, mainCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String mainCode = mainCodeSink.toString(); expect(mainCode, isNot(contains(r"import 'fo\'o.dart';"))); expect(mainCode, contains('class Api {')); expect(mainCode, isNot(contains('abstract class ApiMock'))); expect(mainCode, isNot(contains('.ApiMock.doSomething'))); expect(mainCode, isNot(contains("'${Keys.result}': output"))); expect(mainCode, isNot(contains('return <Object>[];'))); const DartGenerator testGenerator = DartGenerator(); testGenerator.generateTest( const DartOptions( sourceOutPath: "fo'o.dart", testOutPath: 'test.dart', ), root, testCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, dartOutputPackageName: DEFAULT_PACKAGE_NAME, ); final String testCode = testCodeSink.toString(); expect(testCode, contains(r"import 'fo\'o.dart';")); expect(testCode, isNot(contains('class Api {'))); expect(testCode, contains('abstract class ApiMock')); expect(testCode, isNot(contains('.ApiMock.doSomething'))); expect(testCode, contains('output')); expect(testCode, contains('return <Object?>[output];')); }); test('gen one async Flutter Api', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: 'input') ], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), isAsynchronous: true, ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input') ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output') ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('abstract class Api')); expect(code, contains('Future<Output> doSomething(Input input);')); expect(code, contains('final Output output = await api.doSomething(arg_input!);')); }); test('gen one async Flutter Api with void return', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: '') ], returnType: 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, isNot(matches('=.s*doSomething'))); expect(code, contains('await api.doSomething(')); expect(code, isNot(contains('._toMap()'))); }); test('gen one async Host Api', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: '') ], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), isAsynchronous: true, ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input') ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output') ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Api')); expect(code, matches('Output.*doSomething.*Input')); }); test('async host void argument', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.host, parameters: <Parameter>[], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, matches('__pigeon_channel.send[(]null[)]')); }); Iterable<String> makeIterable(String string) sync* { yield string; } test('header', () { final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( DartOptions(copyrightHeader: makeIterable('hello world')), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, startsWith('// hello world')); }); test('generics', () { final Class classDefinition = Class( name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'List', isNullable: true, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'int', isNullable: true) ]), name: 'field1'), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains(' List<int?>? field1;')); }); test('map generics', () { final Class classDefinition = Class( name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'Map', isNullable: true, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'String', isNullable: true), TypeDeclaration(baseName: 'int', isNullable: true), ]), name: 'field1'), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains(' Map<String?, int?>? 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('doit(List<int?> arg')); }); test('flutter generics argument with void return', () { 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('doit(List<int?> 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('Future<List<int?>> doit(')); expect( code, contains( 'return (__pigeon_replyList[0] as List<Object?>?)!.cast<int?>();')); }); test('flutter generics argument non void 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>[ Parameter( type: const TypeDeclaration( baseName: 'List', isNullable: false, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'int', isNullable: true) ]), name: 'foo') ]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('List<int?> doit(')); expect( code, contains( 'final List<int?>? arg_foo = (args[0] as List<Object?>?)?.cast<int?>()')); expect(code, contains('final List<int?> output = api.doit(arg_foo!)')); }); test('return nullable host', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), parameters: <Parameter>[]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('Future<int?> doit()')); expect(code, contains('return (__pigeon_replyList[0] as int?);')); }); test('return nullable collection host', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'List', isNullable: true, typeArguments: <TypeDeclaration>[ TypeDeclaration(baseName: 'int', isNullable: true) ]), parameters: <Parameter>[]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('Future<List<int?>?> doit()')); expect( code, contains( 'return (__pigeon_replyList[0] as List<Object?>?)?.cast<int?>();')); }); test('return nullable async host', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: true, ), parameters: <Parameter>[], isAsynchronous: true) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('Future<int?> doit()')); expect(code, contains('return (__pigeon_replyList[0] as int?);')); }); test('return nullable flutter', () { 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('int? doit();')); expect(code, contains('final int? output = api.doit();')); }); test('return nullable async flutter', () { 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>[], isAsynchronous: true) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('Future<int?> doit();')); expect(code, contains('final int? output = await api.doit();')); }); test('platform error for return nil on nonnull', () { final Root root = Root( apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration( baseName: 'int', isNullable: false, ), parameters: <Parameter>[]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains( 'Host platform returned null value for non-null return value.')); }); 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('Future<void> doit(int? foo) async {')); }); 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('void doit(int? foo);')); }); test('named 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: false, ), isNamed: true, isPositional: false), ]) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('void doit({required int foo});')); expect(code, contains('api.doit(foo: arg_foo!)')); }); test('uses output package name for imports', () { const String overriddenPackageName = 'custom_name'; const String outputPackageName = 'some_output_package'; assert(outputPackageName != DEFAULT_PACKAGE_NAME); final Directory tempDir = Directory.systemTemp.createTempSync('pigeon'); try { final Directory foo = Directory(path.join(tempDir.path, 'lib', 'foo')); foo.createSync(recursive: true); final File pubspecFile = File(path.join(tempDir.path, 'pubspec.yaml')); pubspecFile.writeAsStringSync(''' name: foobar '''); final Root root = Root(classes: <Class>[], apis: <Api>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator testGenerator = DartGenerator(); testGenerator.generateTest( DartOptions( sourceOutPath: path.join(foo.path, 'bar.dart'), testOutPath: path.join(tempDir.path, 'test', 'bar_test.dart'), ), root, sink, dartPackageName: overriddenPackageName, dartOutputPackageName: outputPackageName, ); final String code = sink.toString(); expect( code, contains("import 'package:$outputPackageName/foo/bar.dart';")); } finally { tempDir.deleteSync(recursive: true); } }); 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), 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 DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, isNot(contains('extends StandardMessageCodec'))); expect(code, contains('StandardMessageCodec')); }); test('creates custom codecs if custom datatypes present', () { final Root root = Root(apis: <Api>[ AstFlutterApi(name: 'Api', methods: <Method>[ Method( name: 'doSomething', location: ApiLocation.flutter, parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Input', isNullable: false, associatedClass: emptyClass, ), name: '') ], returnType: TypeDeclaration( baseName: 'Output', isNullable: false, associatedClass: emptyClass, ), isAsynchronous: true, ) ]) ], classes: <Class>[ Class(name: 'Input', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'input') ]), Class(name: 'Output', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'String', isNullable: true, ), name: 'output') ]) ], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect(code, contains('extends StandardMessageCodec')); }); test('host test code handles enums', () { final Root root = Root( apis: <Api>[ AstHostApi( name: 'Api', dartHostTestHandler: 'ApiMock', methods: <Method>[ Method( name: 'doit', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[ Parameter( type: TypeDeclaration( baseName: 'Enum', isNullable: false, associatedEnum: emptyEnum, ), name: 'anEnum') ]) ]) ], classes: <Class>[], enums: <Enum>[ Enum( name: 'Enum', members: <EnumMember>[ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ) ], ); final StringBuffer sink = StringBuffer(); const DartGenerator testGenerator = DartGenerator(); testGenerator.generateTest( const DartOptions( sourceOutPath: 'code.dart', testOutPath: 'test.dart', ), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, dartOutputPackageName: DEFAULT_PACKAGE_NAME, ); final String testCode = sink.toString(); expect( testCode, contains( 'final Enum? arg_anEnum = args[0] == null ? null : Enum.values[args[0]! as int]')); }); test('connection error contains channel name', () { final Root root = Root(apis: <Api>[ AstHostApi(name: 'Api', methods: <Method>[ Method( name: 'method', location: ApiLocation.host, parameters: <Parameter>[], returnType: const TypeDeclaration(baseName: 'Output', isNullable: false), ) ]) ], classes: <Class>[], enums: <Enum>[]); final StringBuffer sink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions(), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String code = sink.toString(); expect( code, contains('throw _createConnectionError(__pigeon_channelName);')); expect( code, contains( '\'Unable to establish connection on channel: "\$channelName".\'')); }); test('generate wrapResponse if is generating tests', () { final Root root = Root( apis: <Api>[ AstHostApi( name: 'Api', dartHostTestHandler: 'ApiMock', methods: <Method>[ Method( name: 'foo', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: <Parameter>[], ) ]) ], classes: <Class>[], enums: <Enum>[], ); final StringBuffer mainCodeSink = StringBuffer(); const DartGenerator generator = DartGenerator(); generator.generate( const DartOptions( testOutPath: 'test.dart', ), root, mainCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, ); final String mainCode = mainCodeSink.toString(); expect(mainCode, contains('List<Object?> wrapResponse(')); }); }
packages/packages/pigeon/test/dart_generator_test.dart/0
{ "file_path": "packages/packages/pigeon/test/dart_generator_test.dart", "repo_id": "packages", "token_count": 26360 }
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. // ignore_for_file: avoid_print import 'dart:io'; import 'package:path/path.dart' as p; import 'generation.dart'; import 'test_suites.dart'; /// Runs the given tests, printing status and exiting with failure if any of /// them fails. Future<void> runTests( List<String> testsToRun, { bool runFormat = false, bool runGeneration = true, }) async { final String baseDir = p.dirname(p.dirname(Platform.script.toFilePath())); if (runGeneration) { // Pre-generate the necessary common output files. // TODO(stuartmorgan): Consider making this conditional on the specific // tests being run, as not all of them need these files. print('# Generating platform_test/ output...'); final int generateExitCode = await generateTestPigeons(baseDir: baseDir); if (generateExitCode == 0) { print('Generation complete!'); } else { print('Generation failed; see above for errors.'); } } if (runFormat) { print('Formatting generated output...'); final int formatExitCode = await formatAllFiles(repositoryRoot: p.dirname(p.dirname(baseDir))); if (formatExitCode != 0) { print('Formatting failed; see above for errors.'); exit(formatExitCode); } } for (final String test in testsToRun) { final TestInfo? info = testSuites[test]; if (info != null) { print('##############################'); print('# Running $test'); final int testCode = await info.function(); if (testCode != 0) { exit(testCode); } print(''); print(''); } else { print('Unknown test: $test'); exit(1); } } }
packages/packages/pigeon/tool/shared/test_runner.dart/0
{ "file_path": "packages/packages/pigeon/tool/shared/test_runner.dart", "repo_id": "packages", "token_count": 638 }
1,027
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="?android:colorBackground" /> </layer-list>
packages/packages/platform/example/android/app/src/main/res/drawable-v21/launch_background.xml/0
{ "file_path": "packages/packages/platform/example/android/app/src/main/res/drawable-v21/launch_background.xml", "repo_id": "packages", "token_count": 67 }
1,028
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/platform/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/platform/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,029
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'default_pointer_interceptor.dart'; /// Platform-specific implementations should set this with their own /// platform-specific class that extends [PointerInterceptorPlatform] when /// they register themselves. abstract class PointerInterceptorPlatform extends PlatformInterface { /// Constructs a PointerInterceptorPlatform. PointerInterceptorPlatform() : super(token: _token); static final Object _token = Object(); static PointerInterceptorPlatform _instance = DefaultPointerInterceptor(); static set instance(PointerInterceptorPlatform? instance) { if (instance == null) { throw AssertionError( 'Platform interfaces can only be set to a non-null instance'); } PlatformInterface.verify(instance, _token); _instance = instance; } /// The default instance of [PointerInterceptorPlatform] to use. /// /// Defaults to [DefaultPointerInterceptor], which does not do anything static PointerInterceptorPlatform get instance => _instance; /// Platform-specific implementations should override this function their own /// implementation of a pointer interceptor widget. Widget buildWidget({ required Widget child, bool debug = false, Key? key, }) { throw UnimplementedError('buildWidget() has not been implemented.'); } }
packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart", "repo_id": "packages", "token_count": 425 }
1,030
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io' show Process, ProcessResult, ProcessSignal, ProcessStartMode, systemEncoding; /// Manages the creation of abstract processes. /// /// Using instances of this class provides level of indirection from the static /// methods in the [Process] class, which in turn allows the underlying /// implementation to be mocked out or decorated for testing and debugging /// purposes. abstract class ProcessManager { /// Starts a process by running the specified [command]. /// /// The first element in [command] will be treated as the executable to run, /// with subsequent elements being passed as arguments to the executable. It /// is left to implementations to decide what element types they support in /// the [command] list. /// /// Returns a `Future<Process>` that completes with a Process instance when /// the process has been successfully started. That [Process] object can be /// used to interact with the process. If the process cannot be started, the /// returned [Future] completes with an exception. /// /// Use [workingDirectory] to set the working directory for the process. Note /// that the change of directory occurs before executing the process on some /// platforms, which may have impact when using relative paths for the /// executable and the arguments. /// /// Use [environment] to set the environment variables for the process. If not /// set, the environment of the parent process is inherited. Currently, only /// US-ASCII environment variables are supported and errors are likely to occur /// if an environment variable with code-points outside the US-ASCII range is /// passed in. /// /// If [includeParentEnvironment] is `true`, the process's environment will /// include the parent process's environment, with [environment] taking /// precedence. Default is `true`. /// /// If [runInShell] is `true`, the process will be spawned through a system /// shell. On Linux and OS X, `/bin/sh` is used, while /// `%WINDIR%\system32\cmd.exe` is used on Windows. /// /// Users must read all data coming on the `stdout` and `stderr` /// streams of processes started with [start]. If the user /// does not read all data on the streams the underlying system /// resources will not be released since there is still pending data. /// /// The following code uses `start` to grep for `main` in the /// file `test.dart` on Linux. /// /// ProcessManager mgr = new LocalProcessManager(); /// mgr.start(['grep', '-i', 'main', 'test.dart']).then((process) { /// stdout.addStream(process.stdout); /// stderr.addStream(process.stderr); /// }); /// /// If [mode] is [ProcessStartMode.normal] (the default) a child /// process will be started with `stdin`, `stdout` and `stderr` /// connected. /// /// If `mode` is [ProcessStartMode.detached] a detached process will /// be created. A detached process has no connection to its parent, /// and can keep running on its own when the parent dies. The only /// information available from a detached process is its `pid`. There /// is no connection to its `stdin`, `stdout` or `stderr`, nor will /// the process' exit code become available when it terminates. /// /// If `mode` is [ProcessStartMode.detachedWithStdio] a detached /// process will be created where the `stdin`, `stdout` and `stderr` /// are connected. The creator can communicate with the child through /// these. The detached process will keep running even if these /// communication channels are closed. The process' exit code will /// not become available when it terminated. /// /// The default value for `mode` is `ProcessStartMode.normal`. Future<Process> start( List<Object> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, ProcessStartMode mode = ProcessStartMode.normal, }); /// Starts a process and runs it non-interactively to completion. /// /// The first element in [command] will be treated as the executable to run, /// with subsequent elements being passed as arguments to the executable. It /// is left to implementations to decide what element types they support in /// the [command] list. /// /// Use [workingDirectory] to set the working directory for the process. Note /// that the change of directory occurs before executing the process on some /// platforms, which may have impact when using relative paths for the /// executable and the arguments. /// /// Use [environment] to set the environment variables for the process. If not /// set the environment of the parent process is inherited. Currently, only /// US-ASCII environment variables are supported and errors are likely to occur /// if an environment variable with code-points outside the US-ASCII range is /// passed in. /// /// If [includeParentEnvironment] is `true`, the process's environment will /// include the parent process's environment, with [environment] taking /// precedence. Default is `true`. /// /// If [runInShell] is true, the process will be spawned through a system /// shell. On Linux and OS X, `/bin/sh` is used, while /// `%WINDIR%\system32\cmd.exe` is used on Windows. /// /// The encoding used for decoding `stdout` and `stderr` into text is /// controlled through [stdoutEncoding] and [stderrEncoding]. The /// default encoding is [systemEncoding]. If `null` is used no /// decoding will happen and the [ProcessResult] will hold binary /// data. /// /// Returns a `Future<ProcessResult>` that completes with the /// result of running the process, i.e., exit code, standard out and /// standard in. /// /// The following code uses `run` to grep for `main` in the /// file `test.dart` on Linux. /// /// ProcessManager mgr = new LocalProcessManager(); /// mgr.run('grep', ['-i', 'main', 'test.dart']).then((result) { /// stdout.write(result.stdout); /// stderr.write(result.stderr); /// }); Future<ProcessResult> run( List<Object> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding, }); /// Starts a process and runs it to completion. This is a synchronous /// call and will block until the child process terminates. /// /// The arguments are the same as for [run]`. /// /// Returns a `ProcessResult` with the result of running the process, /// i.e., exit code, standard out and standard in. ProcessResult runSync( List<Object> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding, }); /// Returns `true` if the [executable] exists and if it can be executed. bool canRun(dynamic executable, {String? workingDirectory}); /// Kills the process with id [pid]. /// /// Where possible, sends the [signal] to the process with id /// `pid`. This includes Linux and OS X. The default signal is /// [ProcessSignal.sigterm] which will normally terminate the /// process. /// /// On platforms without signal support, including Windows, the call /// just terminates the process with id `pid` in a platform specific /// way, and the `signal` parameter is ignored. /// /// Returns `true` if the signal is successfully delivered to the /// process. Otherwise the signal could not be sent, usually meaning /// that the process is already dead. bool killPid(int pid, [ProcessSignal signal = ProcessSignal.sigterm]); }
packages/packages/process/lib/src/interface/process_manager.dart/0
{ "file_path": "packages/packages/process/lib/src/interface/process_manager.dart", "repo_id": "packages", "token_count": 2246 }
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. #import <XCTest/XCTest.h> #import <os/log.h> static const int kElementWaitingTime = 30; @interface RunnerUITests : XCTestCase @end @implementation RunnerUITests { XCUIApplication *_exampleApp; } - (void)setUp { [super setUp]; self.continueAfterFailure = NO; _exampleApp = [[XCUIApplication alloc] init]; } - (void)tearDown { [super tearDown]; [_exampleApp terminate]; _exampleApp = nil; } - (void)testQuickActionWithFreshStart { XCUIApplication *springboard = [[XCUIApplication alloc] initWithBundleIdentifier:@"com.apple.springboard"]; XCUIElement *quickActionsAppIcon = springboard.icons[@"quick_actions_example"]; if (![quickActionsAppIcon waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", springboard.debugDescription); XCTFail(@"Failed due to not able to find the example app from springboard with %@ seconds", @(kElementWaitingTime)); } [quickActionsAppIcon pressForDuration:2]; XCUIElement *actionTwo = springboard.buttons[@"Action two"]; if (![actionTwo waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", springboard.debugDescription); XCTFail(@"Failed due to not able to find the actionTwo button from springboard with %@ seconds", @(kElementWaitingTime)); } [actionTwo tap]; XCUIElement *actionTwoConfirmation = _exampleApp.otherElements[@"action_two"]; if (![actionTwoConfirmation waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", springboard.debugDescription); XCTFail(@"Failed due to not able to find the actionTwoConfirmation in the app with %@ seconds", @(kElementWaitingTime)); } XCTAssertTrue(actionTwoConfirmation.exists); } - (void)testQuickActionWhenAppIsInBackground { [_exampleApp launch]; XCUIElement *actionsReady = _exampleApp.otherElements[@"actions ready"]; if (![actionsReady waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", _exampleApp.debugDescription); XCTFail(@"Failed due to not able to find the actionsReady in the app with %@ seconds", @(kElementWaitingTime)); } [[XCUIDevice sharedDevice] pressButton:XCUIDeviceButtonHome]; XCUIApplication *springboard = [[XCUIApplication alloc] initWithBundleIdentifier:@"com.apple.springboard"]; XCUIElement *quickActionsAppIcon = springboard.icons[@"quick_actions_example"]; if (![quickActionsAppIcon waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", springboard.debugDescription); XCTFail(@"Failed due to not able to find the example app from springboard with %@ seconds", @(kElementWaitingTime)); } [quickActionsAppIcon pressForDuration:2]; XCUIElement *actionOne = springboard.buttons[@"Action one"]; if (![actionOne waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", springboard.debugDescription); XCTFail(@"Failed due to not able to find the actionOne button from springboard with %@ seconds", @(kElementWaitingTime)); } [actionOne tap]; XCUIElement *actionOneConfirmation = _exampleApp.otherElements[@"action_one"]; if (![actionOneConfirmation waitForExistenceWithTimeout:kElementWaitingTime]) { os_log_error(OS_LOG_DEFAULT, "%@", springboard.debugDescription); XCTFail(@"Failed due to not able to find the actionOneConfirmation in the app with %@ seconds", @(kElementWaitingTime)); } XCTAssertTrue(actionOneConfirmation.exists); } @end
packages/packages/quick_actions/quick_actions/example/ios/RunnerUITests/RunnerUITests.m/0
{ "file_path": "packages/packages/quick_actions/quick_actions/example/ios/RunnerUITests/RunnerUITests.m", "repo_id": "packages", "token_count": 1309 }
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. package io.flutter.plugins.quickactions; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ShortcutManager; import android.os.Build; import android.util.Log; import androidx.annotation.ChecksSdkIntAtLeast; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.PluginRegistry.NewIntentListener; import io.flutter.plugins.quickactions.Messages.AndroidQuickActionsFlutterApi; /** QuickActionsPlugin */ public class QuickActionsPlugin implements FlutterPlugin, ActivityAware, NewIntentListener { private static final String TAG = "QuickActionsAndroid"; private QuickActions quickActions; private AndroidQuickActionsFlutterApi quickActionsFlutterApi; private final @NonNull AndroidSdkChecker sdkChecker; // Interface for an injectable SDK version checker. @VisibleForTesting interface AndroidSdkChecker { @ChecksSdkIntAtLeast(parameter = 0) boolean sdkIsAtLeast(int version); } public QuickActionsPlugin() { this((int version) -> Build.VERSION.SDK_INT >= version); } @VisibleForTesting QuickActionsPlugin(@NonNull AndroidSdkChecker capabilityChecker) { this.sdkChecker = capabilityChecker; } /** * Plugin registration. * * <p>Must be called when the application is created. */ @SuppressWarnings("deprecation") public static void registerWith( @NonNull io.flutter.plugin.common.PluginRegistry.Registrar registrar) { QuickActions quickActions = new QuickActions(registrar.context()); quickActions.setActivity(registrar.activity()); Messages.AndroidQuickActionsApi.setup(registrar.messenger(), quickActions); } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { this.quickActions = new QuickActions(binding.getApplicationContext()); Messages.AndroidQuickActionsApi.setup(binding.getBinaryMessenger(), quickActions); this.quickActionsFlutterApi = new AndroidQuickActionsFlutterApi(binding.getBinaryMessenger()); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { Messages.AndroidQuickActionsApi.setup(binding.getBinaryMessenger(), null); this.quickActions = null; } @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { if (this.quickActions == null) { Log.wtf(TAG, "quickActions was never set."); return; } Activity activity = binding.getActivity(); this.quickActions.setActivity(activity); binding.addOnNewIntentListener(this); onNewIntent(activity.getIntent()); } @Override public void onDetachedFromActivity() { quickActions.setActivity(null); } @Override public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { binding.removeOnNewIntentListener(this); onAttachedToActivity(binding); } @Override public void onDetachedFromActivityForConfigChanges() { onDetachedFromActivity(); } @Override public boolean onNewIntent(@NonNull Intent intent) { // Do nothing for anything lower than API 25 as the functionality isn't supported. if (!sdkChecker.sdkIsAtLeast(Build.VERSION_CODES.N_MR1)) { return false; } Activity activity = this.quickActions.getActivity(); // Notify the Dart side if the launch intent has the intent extra relevant to quick actions. if (intent.hasExtra(QuickActions.EXTRA_ACTION) && activity != null) { Context context = activity.getApplicationContext(); ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE); String shortcutId = intent.getStringExtra(QuickActions.EXTRA_ACTION); quickActionsFlutterApi.launchAction( shortcutId, value -> { // noop }); shortcutManager.reportShortcutUsed(shortcutId); } return false; } }
packages/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/QuickActionsPlugin.java/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/android/src/main/java/io/flutter/plugins/quickactions/QuickActionsPlugin.java", "repo_id": "packages", "token_count": 1402 }
1,033
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v12.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #else #error("Unsupported platform.") #endif extension FlutterError: Error {} private func isNullish(_ value: Any?) -> Bool { return value is NSNull || value == nil } private func wrapResult(_ result: Any?) -> [Any?] { return [result] } private func wrapError(_ error: Any) -> [Any?] { if let flutterError = error as? FlutterError { return [ flutterError.code, flutterError.message, flutterError.details, ] } return [ "\(error)", "\(type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } private func nilOrValue<T>(_ value: Any?) -> T? { if value is NSNull { return nil } return value as! T? } /// Home screen quick-action shortcut item. /// /// Generated class from Pigeon that represents data sent in messages. struct ShortcutItemMessage { /// The identifier of this item; should be unique within the app. var type: String /// Localized title of the item. var localizedTitle: String /// Name of native resource to be displayed as the icon for this item. var icon: String? = nil static func fromList(_ list: [Any?]) -> ShortcutItemMessage? { let type = list[0] as! String let localizedTitle = list[1] as! String let icon: String? = nilOrValue(list[2]) return ShortcutItemMessage( type: type, localizedTitle: localizedTitle, icon: icon ) } func toList() -> [Any?] { return [ type, localizedTitle, icon, ] } } private class IOSQuickActionsApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: return ShortcutItemMessage.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } } } private class IOSQuickActionsApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { if let value = value as? ShortcutItemMessage { super.writeByte(128) super.writeValue(value.toList()) } else { super.writeValue(value) } } } private class IOSQuickActionsApiCodecReaderWriter: FlutterStandardReaderWriter { override func reader(with data: Data) -> FlutterStandardReader { return IOSQuickActionsApiCodecReader(data: data) } override func writer(with data: NSMutableData) -> FlutterStandardWriter { return IOSQuickActionsApiCodecWriter(data: data) } } class IOSQuickActionsApiCodec: FlutterStandardMessageCodec { static let shared = IOSQuickActionsApiCodec(readerWriter: IOSQuickActionsApiCodecReaderWriter()) } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol IOSQuickActionsApi { /// Sets the dynamic shortcuts for the app. func setShortcutItems(itemsList: [ShortcutItemMessage]) throws /// Removes all dynamic shortcuts. func clearShortcutItems() throws } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class IOSQuickActionsApiSetup { /// The codec used by IOSQuickActionsApi. static var codec: FlutterStandardMessageCodec { IOSQuickActionsApiCodec.shared } /// Sets up an instance of `IOSQuickActionsApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: IOSQuickActionsApi?) { /// Sets the dynamic shortcuts for the app. let setShortcutItemsChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsApi.setShortcutItems", binaryMessenger: binaryMessenger, codec: codec) if let api = api { setShortcutItemsChannel.setMessageHandler { message, reply in let args = message as! [Any?] let itemsListArg = args[0] as! [ShortcutItemMessage] do { try api.setShortcutItems(itemsList: itemsListArg) reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { setShortcutItemsChannel.setMessageHandler(nil) } /// Removes all dynamic shortcuts. let clearShortcutItemsChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsApi.clearShortcutItems", binaryMessenger: binaryMessenger, codec: codec) if let api = api { clearShortcutItemsChannel.setMessageHandler { _, reply in do { try api.clearShortcutItems() reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { clearShortcutItemsChannel.setMessageHandler(nil) } } } /// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. protocol IOSQuickActionsFlutterApiProtocol { /// Sends a string representing a shortcut from the native platform to the app. func launchAction( action actionArg: String, completion: @escaping (Result<Void, FlutterError>) -> Void) } class IOSQuickActionsFlutterApi: IOSQuickActionsFlutterApiProtocol { private let binaryMessenger: FlutterBinaryMessenger init(binaryMessenger: FlutterBinaryMessenger) { self.binaryMessenger = binaryMessenger } /// Sends a string representing a shortcut from the native platform to the app. func launchAction( action actionArg: String, completion: @escaping (Result<Void, FlutterError>) -> Void ) { let channel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction", binaryMessenger: binaryMessenger) channel.sendMessage([actionArg] as [Any?]) { _ in completion(.success(Void())) } } }
packages/packages/quick_actions/quick_actions_ios/ios/Classes/messages.g.swift/0
{ "file_path": "packages/packages/quick_actions/quick_actions_ios/ios/Classes/messages.g.swift", "repo_id": "packages", "token_count": 2058 }
1,034
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/rfw/example/wasm/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/rfw/example/wasm/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
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. // This file is hand-formatted. import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart' show objectRuntimeType; import '../dart/model.dart'; /// Signature for the callback passed to [DynamicContent.subscribe]. /// /// Do not modify the provided value (e.g. if it is a map or list). Doing so /// would leave the [DynamicContent] in an inconsistent state. typedef SubscriptionCallback = void Function(Object value); /// Returns a copy of a data structure if it consists of only [DynamicMap]s, /// [DynamicList]s, [int]s, [double]s, [bool]s, and [String]s. /// /// This is relatively expensive as the entire data structure must be walked and /// new objects created. Object? deepClone(Object? template) { if (template == null) { return null; } else if (template is DynamicMap) { return template.map((String key, Object? value) => MapEntry<String, Object?>(key, deepClone(value))); } else if (template is DynamicList) { return template.map((Object? value) => deepClone(value)).toList(); } else { assert(template is int || template is double || template is bool || template is String, 'unexpected state object type: ${template.runtimeType} ($template)'); return template; } } /// Configuration data from the remote widgets. /// /// Typically this represents the data model, and is updated frequently (or at /// least, more frequently than the remote widget definitions) by the server /// (or, indeed, by local code, in response to events or other activity). /// /// ## Structure /// /// A [DynamicContent] object represents a tree. A consumer (the remote widgets) /// can subscribe to a node to obtain its value. /// /// The root of a [DynamicContent] tree is a map of string-value pairs. The /// values are: /// /// * Other maps of string-value pairs ([DynamicMap]). /// * Lists of values ([DynamicList]). /// * Booleans ([bool]). /// * Integers ([int]). /// * Doubles ([double]). /// * Strings ([String]). /// /// The keys in the root map are independently updated. Typically each /// represents a different category of data from the server that the server /// updates independently, e.g. theming information and the app state might be /// provided separately. /// /// ## Updates /// /// Data is updated using [update] and [updateAll]. The objects passed to those /// methods are of the types described above. /// /// Objects for [update] can be obtained in several ways: /// /// 1. Dart maps, lists, and literals of the types given above ("raw data") can /// be created directly in code. This is useful for configuring remote /// widgets with local client information such as the current time, GPS /// coordinates, system settings like dark mode, window dimensions, etc, /// where the data was never encoded in the first place. /// /// 2. A Remote Flutter Widgets binary data blob can be parsed using /// [decodeDataBlob]. This is the preferred method for decoding data obtained /// from the network. See [encodeDataBlob] for a function that generates data /// in this format. /// /// 3. A Remote Flutter Widgets text data file can be parsed using /// [parseTextDataFile]. Decoding this text format is about ten times slower /// than decoding the binary format and about five times slower than decoding /// JSON, so it is discouraged in production applications. This text /// representation of the Remote Flutter Widgets binary data blob format is /// similar to JSON. This form is typically not used in applications; it is /// more common for this format to be used on the server side, parsed and /// then encoded in binary form for transmission to the client. /// /// 4. Data in JSON form can be decoded using [JsonCodec.decode] (typically /// using the [json] object); the JSON decoder creates the same types of data /// structures as expected by [update]. This is not generally recommended but /// may be appropriate if the data was obtained from a third-party source in /// JSON form and could not be preprocessed by a server to convert the data /// to the binary form described above. Numbers in JSON are interpreted as /// doubles if they contain a decimal point or an `e` in their source /// representation, and as integers otherwise. This can cause issues as the /// [DynamicContent] and [DataSource] are strongly typed and distinguish /// [int] and [double]. Explicit nulls in the JSON are an error (the data /// format supported by [DynamicContent] does not support nulls). Decoding /// JSON is about 1.5x slower than the binary format. /// /// Subscribers are notified immediately after an update if their data changed. /// /// ## References /// /// To subscribe to a node, the [subscribe] method is used. The method returns /// the current value. When the value later changes, the provided callback is /// invoked with the new value. /// /// The [unsubscribe] method must be called when the client no longer needs /// updates (e.g. when the widget goes away). /// /// To identify a node, a list of keys is used, giving the path from the root to /// the node. Each key is either a string (to index into maps) or an integer (to /// index into lists). If no node is identified, the [missing] value is /// returned. Similarly, if a node goes away, subscribers are given the value /// [missing] as the new value. It is not an error to subscribe to missing data. /// It _is_ an error to add [missing] values to the data model, however. /// /// To subscribe to the root of the [DynamicContent], use an empty list as the /// key when subscribing. /// /// The [LocalWidgetBuilder]s passed to a [LocalWidgetLibrary] use a /// [DataSource] as their interface into the [DynamicContent]. To ensure the /// integrity of the update mechanism, _that_ interface only allows access to /// leaves, not intermediate nodes (maps and lists). /// /// It is an error to subscribe to the same key multiple times with the same /// callback. class DynamicContent { /// Create a fresh [DynamicContent] object. /// /// The `initialData` argument, if provided, is used to update all the keys /// in the [DynamicContent], as if [updateAll] had been called. DynamicContent([ DynamicMap? initialData ]) { if (initialData != null) { updateAll(initialData); } } final _DynamicNode _root = _DynamicNode.root(); /// Update all the keys in the [DynamicContent]. /// /// Each key in the provided map is added to [DynamicContent], replacing any /// data that was there previously, as if [update] had been called for each /// key. /// /// Existing keys that are not present in the given map are left unmodified. /// /// If the root node has subscribers (see [subscribe]), they are called once /// per key in `initialData`, not just a single time. /// /// Collections (maps and lists) in `initialData` must not be mutated after /// calling this method; doing so would leave the [DynamicContent] in an /// inconsistent state. void updateAll(DynamicMap initialData) { for (final String key in initialData.keys) { final Object value = initialData[key] ?? missing; update(key, value); } } /// Updates the content with the specified data. /// /// The given `rootKey` is updated with the data `value`. /// /// The `value` must consist exclusively of [DynamicMap], [DynamicList], [int], /// [double], [bool], and [String] objects. /// /// Collections (maps and lists) in `value` must not be mutated after calling /// this method; doing so would leave the [DynamicContent] in an inconsistent /// state. void update(String rootKey, Object value) { _root.updateKey(rootKey, deepClone(value)!); _scheduleCleanup(); } /// Obtain the value at location `key`, and subscribe `callback` to that key /// so that future [update]s will invoke the callback with the new value. /// /// The value is always non-null; if the value is missing, the [missing] /// object is used instead. /// /// The empty key refers to the root of the [DynamicContent] object (i.e. /// the map manipulated by [updateAll] and [update]). /// /// Use [unsubscribe] when the subscription is no longer needed. /// /// Do not modify the value returned by this method or passed to the given /// `callback` (e.g. if it is a map or list). Changes made in this manner will /// leave the [DynamicContent] in an inconsistent state. Object subscribe(List<Object> key, SubscriptionCallback callback) { return _root.subscribe(key, 0, callback); } /// Removes a subscription created by [subscribe]. void unsubscribe(List<Object> key, SubscriptionCallback callback) { _root.unsubscribe(key, 0, callback); } bool _cleanupPending = false; void _scheduleCleanup() { if (!_cleanupPending) { _cleanupPending = true; scheduleMicrotask(() { _cleanupPending = false; _DynamicNode.cleanup(); }); } } @override String toString() => '${objectRuntimeType(this, 'DynamicContent')}($_root)'; } // Node in the [DynamicContent] tree. This should contain no [BlobNode]s. class _DynamicNode { _DynamicNode(this._key, this._parent, this._value) : assert(_value == missing || _hasValidType(_value)); _DynamicNode.root() : _key = missing, _parent = null, _value = DynamicMap(); // ignore: prefer_collection_literals final Object _key; final _DynamicNode? _parent; Object _value; final Set<SubscriptionCallback> _callbacks = <SubscriptionCallback>{}; final Map<Object, _DynamicNode> _children = <Object, _DynamicNode>{}; bool get isObsolete => _callbacks.isEmpty && _children.isEmpty; static final Set<_DynamicNode> _obsoleteNodes = <_DynamicNode>{}; /// Allow garbage collection to collect unused nodes. /// /// When a node has no subscribers, it is no longer needed (it can be /// recreated if necessary from the raw data). In that situation, the node /// adds itself to a list of "obsolete nodes", but the parent still references /// it and therefore garbage collection would not notice that it is no longer /// used. /// /// This method solves this problem by disconnecting obsolete nodes from the /// tree. static void cleanup() { while (_obsoleteNodes.isNotEmpty) { final _DynamicNode node = _obsoleteNodes.first; _obsoleteNodes.remove(node); if (node.isObsolete) { node._parent?._forget(node._key, node); } } } void _forget(Object childKey, _DynamicNode child) { assert(_children[childKey] == child); _children.remove(childKey); if (isObsolete) { _obsoleteNodes.add(this); } } static bool _hasValidType(Object? value) { if (value is DynamicMap) { return value.values.every(_hasValidType); } if (value is DynamicList) { return value.every(_hasValidType); } return value is int || value is double || value is bool || value is String; } _DynamicNode _prepare(Object childKey) { assert(childKey is String || childKey is int); if (!_children.containsKey(childKey)) { Object value; if (_value is DynamicMap) { if (childKey is String && (_value as DynamicMap).containsKey(childKey)) { value = (_value as DynamicMap)[childKey]!; } else { value = missing; } } else if (_value is DynamicList) { if (childKey is int && childKey >= 0 && childKey < (_value as DynamicList).length) { value = (_value as DynamicList)[childKey]!; } else { value = missing; } } else { value = _value; } _children[childKey] = _DynamicNode(childKey, this, value); } return _children[childKey]!; } Object subscribe(List<Object> key, int index, SubscriptionCallback callback) { _obsoleteNodes.remove(this); if (index == key.length) { assert(!_callbacks.contains(callback)); _callbacks.add(callback); return _value; } final _DynamicNode child = _prepare(key[index]); return child.subscribe(key, index + 1, callback); } void unsubscribe(List<Object> key, int index, SubscriptionCallback callback) { if (index == key.length) { assert(_callbacks.contains(callback)); _callbacks.remove(callback); if (_callbacks.isEmpty) { _obsoleteNodes.add(this); } } else { assert(_children.containsKey(key[index])); _children[key[index]]!.unsubscribe(key, index + 1, callback); } } void update(Object value) { assert(value == missing || _hasValidType(value), 'cannot update $this using $value'); if (value == _value) { return; } _value = value; if (value is DynamicMap) { for (final Object childKey in _children.keys) { Object? childValue; if (childKey is String) { childValue = value[childKey]; } _children[childKey]!.update(childValue ?? missing); } } else if (value is DynamicList) { for (final Object childKey in _children.keys) { Object? childValue; if (childKey is int && childKey >= 0 && childKey < value.length) { childValue = value[childKey]; } _children[childKey]!.update(childValue ?? missing); } } else { for (final _DynamicNode child in _children.values) { child.update(missing); } } _sendUpdates(value); } void updateKey(String rootKey, Object value) { assert(_value is DynamicMap); assert(_hasValidType(value)); if ((_value as DynamicMap)[rootKey] == value) { return; } (_value as DynamicMap)[rootKey] = value; if (_children.containsKey(rootKey)) { _children[rootKey]!.update(value); } _sendUpdates(_value); } void _sendUpdates(Object value) { for (final SubscriptionCallback callback in _callbacks) { callback(value); } } @override String toString() => '$_value'; }
packages/packages/rfw/lib/src/flutter/content.dart/0
{ "file_path": "packages/packages/rfw/lib/src/flutter/content.dart", "repo_id": "packages", "token_count": 4389 }
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. // This file is hand-formatted. // ignore_for_file: use_raw_strings, avoid_escaping_inner_quotes import 'package:flutter_test/flutter_test.dart'; import 'package:rfw/formats.dart'; void main() { testWidgets('empty parseDataFile', (WidgetTester tester) async { final DynamicMap result = parseDataFile('{}'); expect(result, <String, Object?>{ }); }); testWidgets('empty parseLibraryFile', (WidgetTester tester) async { final RemoteWidgetLibrary result = parseLibraryFile(''); expect(result.imports, isEmpty); expect(result.widgets, isEmpty); }); testWidgets('space parseDataFile', (WidgetTester tester) async { final DynamicMap result = parseDataFile(' \n {} \n '); expect(result, <String, Object?>{ }); }); testWidgets('space parseLibraryFile', (WidgetTester tester) async { final RemoteWidgetLibrary result = parseLibraryFile(' \n '); expect(result.imports, isEmpty); expect(result.widgets, isEmpty); }); testWidgets('error handling in parseDataFile', (WidgetTester tester) async { void test(String input, String expectedMessage) { try { parseDataFile(input); fail('parsing `$input` did not result in an error (expected "$expectedMessage").'); } on ParserException catch (e) { expect('$e', expectedMessage); } } test('', 'Expected symbol "{" but found <EOF> at line 1 column 0.'); test('}', 'Expected symbol "{" but found } at line 1 column 1.'); test('1', 'Expected symbol "{" but found 1 at line 1 column 1.'); test('1.2', 'Expected symbol "{" but found 1.2 at line 1 column 3.'); test('a', 'Expected symbol "{" but found a at line 1 column 1.'); test('"a"', 'Expected symbol "{" but found "a" at line 1 column 3.'); test('&', 'Unexpected character U+0026 ("&") at line 1 column 1.'); test('\t', 'Unexpected character U+0009 at line 1 column 1.'); test('{ a: 0, a: 0 }', 'Duplicate key "a" in map at line 1 column 10.'); test('{ a: 0; }', 'Expected symbol "}" but found ; at line 1 column 7.'); test('{ a: [ 0 ; ] }', 'Expected comma but found ; at line 1 column 10.'); test('{ } x', 'Expected end of file but found x at line 1 column 5.'); test('{ a: a }', 'Unexpected a at line 1 column 7.'); test('{ ... }', 'Expected symbol "}" but found … at line 1 column 5.'); test('{ a: ... }', 'Unexpected … at line 1 column 8.'); test('{ a: -', 'Unexpected end of file after minus sign at line 1 column 6.'); test('{ a: -a', 'Unexpected character U+0061 ("a") after minus sign (expected digit) at line 1 column 7.'); test('{ a: 0', 'Expected symbol "}" but found <EOF> at line 1 column 6.'); test('{ a: 0e', 'Unexpected end of file after exponent separator at line 1 column 7.'); test('{ a: 0ee', 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 8.'); test('{ a: 0e-', 'Unexpected end of file after exponent separator and minus sign at line 1 column 8.'); test('{ a: 0e-e', 'Unexpected character U+0065 ("e") in exponent at line 1 column 9.'); test('{ a: 0e-f', 'Unexpected character U+0066 ("f") in exponent at line 1 column 9.'); test('{ a: 0e-.', 'Unexpected character U+002E (".") in exponent at line 1 column 9.'); test('{ a: 0e- ', 'Unexpected character U+0020 in exponent at line 1 column 9.'); test('{ a: 0e-0', 'Expected symbol "}" but found <EOF> at line 1 column 9.'); test('{ a: 0e-0{', 'Expected symbol "}" but found { at line 1 column 10.'); test('{ a: 0e-0;', 'Expected symbol "}" but found ; at line 1 column 10.'); test('{ a: 0e-0e', 'Unexpected character U+0065 ("e") in exponent at line 1 column 10.'); test('{ a: 0 ', 'Expected symbol "}" but found <EOF> at line 1 column 7.'); test('{ a: 0.', 'Unexpected end of file after decimal point at line 1 column 7.'); test('{ a: 0.e', 'Unexpected character U+0065 ("e") in fraction component at line 1 column 8.'); test('{ a: 0. ', 'Unexpected character U+0020 in fraction component at line 1 column 8.'); test('{ a: 00', 'Expected symbol "}" but found <EOF> at line 1 column 7.'); test('{ a: 00e', 'Unexpected end of file after exponent separator at line 1 column 8.'); test('{ a: 00ee', 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 9.'); test('{ a: 00e-', 'Unexpected end of file after exponent separator and minus sign at line 1 column 9.'); test('{ a: 00 ', 'Expected symbol "}" but found <EOF> at line 1 column 8.'); test('{ a: -0', 'Expected symbol "}" but found <EOF> at line 1 column 7.'); test('{ a: -0.', 'Unexpected end of file after decimal point at line 1 column 8.'); test('{ a: -0. ', 'Unexpected character U+0020 in fraction component at line 1 column 9.'); test('{ a: -0.0', 'Expected symbol "}" but found <EOF> at line 1 column 9.'); test('{ a: -0.0 ', 'Expected symbol "}" but found <EOF> at line 1 column 10.'); test('{ a: -0.0e', 'Unexpected end of file after exponent separator at line 1 column 10.'); test('{ a: -0.0ee', 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 11.'); test('{ a: -0.0e-', 'Unexpected end of file after exponent separator and minus sign at line 1 column 11.'); test('{ a: -0.0f', 'Unexpected character U+0066 ("f") in fraction component at line 1 column 10.'); test('{ a: -00', 'Expected symbol "}" but found <EOF> at line 1 column 8.'); test('{ a: 0f', 'Unexpected character U+0066 ("f") after zero at line 1 column 7.'); test('{ a: -0f', 'Unexpected character U+0066 ("f") after negative zero at line 1 column 8.'); test('{ a: 00f', 'Unexpected character U+0066 ("f") at line 1 column 8.'); test('{ a: -00f', 'Unexpected character U+0066 ("f") at line 1 column 9.'); test('{ a: test.0', 'Unexpected test at line 1 column 10.'); test('{ a: test.0 ', 'Unexpected test at line 1 column 10.'); test('{ a: 0x', 'Unexpected end of file after 0x prefix at line 1 column 7.'); test('{ a: 0xg', 'Unexpected character U+0067 ("g") after 0x prefix at line 1 column 8.'); test('{ a: 0xx', 'Unexpected character U+0078 ("x") after 0x prefix at line 1 column 8.'); test('{ a: 0x}', 'Unexpected character U+007D ("}") after 0x prefix at line 1 column 8.'); test('{ a: 0x0', 'Expected symbol "}" but found <EOF> at line 1 column 8.'); test('{ a: 0xff', 'Expected symbol "}" but found <EOF> at line 1 column 9.'); test('{ a: 0xfg', 'Unexpected character U+0067 ("g") in hex literal at line 1 column 9.'); test('{ a: ."hello"', 'Unexpected . at line 1 column 7.'); test('{ a: "hello"."hello"', 'Expected symbol "}" but found . at line 1 column 14.'); test('{ a: "hello"', 'Expected symbol "}" but found <EOF> at line 1 column 12.'); test('{ a: "\n"', 'Unexpected end of line inside string at line 2 column 0.'); test('{ a: "hello\n"', 'Unexpected end of line inside string at line 2 column 0.'); test('{ a: "\\', 'Unexpected end of file inside string at line 1 column 7.'); test('{ a: ."hello"', 'Unexpected . at line 1 column 7.'); test('{ "a": \'hello\'.\'hello\'', 'Expected symbol "}" but found . at line 1 column 16.'); test('{ "a": \'hello\'', 'Expected symbol "}" but found <EOF> at line 1 column 14.'); test('{ "a": \'hello\'h', 'Unexpected character U+0068 ("h") after end quote at line 1 column 15.'); test('{ "a": \'\n\'', 'Unexpected end of line inside string at line 2 column 0.'); test('{ "a": \'hello\n\'', 'Unexpected end of line inside string at line 2 column 0.'); test('{ "a": \'\\', 'Unexpected end of file inside string at line 1 column 9.'); test('{ "a": \'\\\'', 'Unexpected end of file inside string at line 1 column 10.'); test('{ "a": \'\\u', 'Unexpected end of file inside Unicode escape at line 1 column 10.'); test('{ "a": \'\\u0', 'Unexpected end of file inside Unicode escape at line 1 column 11.'); test('{ "a": \'\\u00', 'Unexpected end of file inside Unicode escape at line 1 column 12.'); test('{ "a": \'\\u000', 'Unexpected end of file inside Unicode escape at line 1 column 13.'); test('{ "a": \'\\u0000', 'Unexpected end of file inside string at line 1 column 14.'); test('{ "a": \'\\u|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 11.'); test('{ "a": \'\\u0|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 12.'); test('{ "a": \'\\u00|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 13.'); test('{ "a": \'\\u000|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 14.'); test('{ "a": \'\\u0000|', 'Unexpected end of file inside string at line 1 column 15.'); test('{ "a": \'\\U263A\' }', 'Unexpected character U+0055 ("U") after backslash in string at line 1 column 10.'); test('{ "a": "\\', 'Unexpected end of file inside string at line 1 column 9.'); test('{ "a": "\\"', 'Unexpected end of file inside string at line 1 column 10.'); test('{ "a": "\\u', 'Unexpected end of file inside Unicode escape at line 1 column 10.'); test('{ "a": "\\u0', 'Unexpected end of file inside Unicode escape at line 1 column 11.'); test('{ "a": "\\u00', 'Unexpected end of file inside Unicode escape at line 1 column 12.'); test('{ "a": "\\u000', 'Unexpected end of file inside Unicode escape at line 1 column 13.'); test('{ "a": "\\u0000', 'Unexpected end of file inside string at line 1 column 14.'); test('{ "a": "\\u|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 11.'); test('{ "a": "\\u0|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 12.'); test('{ "a": "\\u00|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 13.'); test('{ "a": "\\u000|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 14.'); test('{ "a": "\\u0000|', 'Unexpected end of file inside string at line 1 column 15.'); test('{ "a": "\\U263A" }', 'Unexpected character U+0055 ("U") after backslash in string at line 1 column 10.'); test('{ "a": ', 'Unexpected <EOF> at line 1 column 7.'); test('{ "a": /', 'Unexpected end of file inside comment delimiter at line 1 column 8.'); test('{ "a": /.', 'Unexpected character U+002E (".") inside comment delimiter at line 1 column 9.'); test('{ "a": //', 'Unexpected <EOF> at line 1 column 9.'); test('{ "a": /*', 'Unexpected end of file in block comment at line 1 column 9.'); test('{ "a": /*/', 'Unexpected end of file in block comment at line 1 column 10.'); test('{ "a": /**', 'Unexpected end of file in block comment at line 1 column 10.'); test('{ "a": /* *', 'Unexpected end of file in block comment at line 1 column 11.'); }); testWidgets('valid values in parseDataFile', (WidgetTester tester) async { expect(parseDataFile('{ }\n\n \n\n'), <String, Object?>{ }); expect(parseDataFile('{ a: "b" }'), <String, Object?>{ 'a': 'b' }); expect(parseDataFile('{ a: [ "b", 9 ] }'), <String, Object?>{ 'a': <Object?>[ 'b', 9 ] }); expect(parseDataFile('{ a: { } }'), <String, Object?>{ 'a': <String, Object?>{ } }); expect(parseDataFile('{ a: 123.456e7 }'), <String, Object?>{ 'a': 123.456e7 }); expect(parseDataFile('{ a: true }'), <String, Object?>{ 'a': true }); expect(parseDataFile('{ a: false }'), <String, Object?>{ 'a': false }); expect(parseDataFile('{ "a": 0 }'), <String, Object?>{ 'a': 0 }); expect(parseDataFile('{ "a": -0, b: "x" }'), <String, Object?>{ 'a': 0, 'b': 'x' }); expect(parseDataFile('{ "a": null }'), <String, Object?>{ }); expect(parseDataFile('{ "a": -6 }'), <String, Object?>{ 'a': -6 }); expect(parseDataFile('{ "a": -7 }'), <String, Object?>{ 'a': -7 }); expect(parseDataFile('{ "a": -8 }'), <String, Object?>{ 'a': -8 }); expect(parseDataFile('{ "a": -9 }'), <String, Object?>{ 'a': -9 }); expect(parseDataFile('{ "a": 01 }'), <String, Object?>{ 'a': 1 }); expect(parseDataFile('{ "a": 0e0 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": 0e1 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": 0e8 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": 1e9 }'), <String, Object?>{ 'a': 1000000000.0 }); expect(parseDataFile('{ "a": -0e1 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": 00e1 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": -00e1 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": 00.0e1 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": -00.0e1 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": -00.0e-1 }'), <String, Object?>{ 'a': 0.0 }); expect(parseDataFile('{ "a": -1e-1 }'), <String, Object?>{ 'a': -0.1 }); expect(parseDataFile('{ "a": -1e-2 }'), <String, Object?>{ 'a': -0.01 }); expect(parseDataFile('{ "a": -1e-3 }'), <String, Object?>{ 'a': -0.001 }); expect(parseDataFile('{ "a": -1e-4 }'), <String, Object?>{ 'a': -0.0001 }); expect(parseDataFile('{ "a": -1e-5 }'), <String, Object?>{ 'a': -0.00001 }); expect(parseDataFile('{ "a": -1e-6 }'), <String, Object?>{ 'a': -0.000001 }); expect(parseDataFile('{ "a": -1e-7 }'), <String, Object?>{ 'a': -0.0000001 }); expect(parseDataFile('{ "a": -1e-8 }'), <String, Object?>{ 'a': -0.00000001 }); expect(parseDataFile('{ "a": -1e-9 }'), <String, Object?>{ 'a': -0.000000001 }); expect(parseDataFile('{ "a": -1e-10 }'), <String, Object?>{ 'a': -0.0000000001 }); expect(parseDataFile('{ "a": -1e-11 }'), <String, Object?>{ 'a': -0.00000000001 }); expect(parseDataFile('{ "a": -1e-12 }'), <String, Object?>{ 'a': -0.000000000001 }); expect(parseDataFile('{ "a": -1e-13 }'), <String, Object?>{ 'a': -0.0000000000001 }); expect(parseDataFile('{ "a": -1e-14 }'), <String, Object?>{ 'a': -0.00000000000001 }); expect(parseDataFile('{ "a": -1e-15 }'), <String, Object?>{ 'a': -0.000000000000001 }); expect(parseDataFile('{ "a": -1e-16 }'), <String, Object?>{ 'a': -0.0000000000000001 }); expect(parseDataFile('{ "a": -1e-17 }'), <String, Object?>{ 'a': -0.00000000000000001 }); expect(parseDataFile('{ "a": -1e-18 }'), <String, Object?>{ 'a': -0.000000000000000001 }); expect(parseDataFile('{ "a": -1e-19 }'), <String, Object?>{ 'a': -0.0000000000000000001 }); expect(parseDataFile('{ "a": 0x0 }'), <String, Object?>{ 'a': 0 }); expect(parseDataFile('{ "a": 0x1 }'), <String, Object?>{ 'a': 1 }); expect(parseDataFile('{ "a": 0x01 }'), <String, Object?>{ 'a': 1 }); expect(parseDataFile('{ "a": 0xa }'), <String, Object?>{ 'a': 10 }); expect(parseDataFile('{ "a": 0xb }'), <String, Object?>{ 'a': 11 }); expect(parseDataFile('{ "a": 0xc }'), <String, Object?>{ 'a': 12 }); expect(parseDataFile('{ "a": 0xd }'), <String, Object?>{ 'a': 13 }); expect(parseDataFile('{ "a": 0xe }'), <String, Object?>{ 'a': 14 }); expect(parseDataFile('{ "a": 0xfa }'), <String, Object?>{ 'a': 250 }); expect(parseDataFile('{ "a": 0xfb }'), <String, Object?>{ 'a': 251 }); expect(parseDataFile('{ "a": 0xfc }'), <String, Object?>{ 'a': 252 }); expect(parseDataFile('{ "a": 0xfd }'), <String, Object?>{ 'a': 253 }); expect(parseDataFile('{ "a": 0xfe }'), <String, Object?>{ 'a': 254 }); expect(parseDataFile('{ "a": "\\"\\/\\\'\\b\\f\\n\\r\\t\\\\" }'), <String, Object?>{ 'a': '\x22\x2F\x27\x08\x0C\x0A\x0D\x09\x5C' }); expect(parseDataFile('{ "a": \'\\"\\/\\\'\\b\\f\\n\\r\\t\\\\\' }'), <String, Object?>{ 'a': '\x22\x2F\x27\x08\x0C\x0A\x0D\x09\x5C' }); expect(parseDataFile('{ "a": \'\\u263A\' }'), <String, Object?>{ 'a': '☺' }); expect(parseDataFile('{ "a": \'\\u0000\' }'), <String, Object?>{ 'a': '\x00' }); expect(parseDataFile('{ "a": \'\\u1111\' }'), <String, Object?>{ 'a': 'ᄑ' }); expect(parseDataFile('{ "a": \'\\u2222\' }'), <String, Object?>{ 'a': '∢' }); expect(parseDataFile('{ "a": \'\\u3333\' }'), <String, Object?>{ 'a': '㌳' }); expect(parseDataFile('{ "a": \'\\u4444\' }'), <String, Object?>{ 'a': '䑄' }); expect(parseDataFile('{ "a": \'\\u5555\' }'), <String, Object?>{ 'a': '啕' }); expect(parseDataFile('{ "a": \'\\u6666\' }'), <String, Object?>{ 'a': '晦' }); expect(parseDataFile('{ "a": \'\\u7777\' }'), <String, Object?>{ 'a': '睷' }); expect(parseDataFile('{ "a": \'\\u8888\' }'), <String, Object?>{ 'a': '袈' }); expect(parseDataFile('{ "a": \'\\u9999\' }'), <String, Object?>{ 'a': '香' }); expect(parseDataFile('{ "a": \'\\uaaaa\' }'), <String, Object?>{ 'a': 'ꪪ' }); expect(parseDataFile('{ "a": \'\\ubbbb\' }'), <String, Object?>{ 'a': '뮻' }); expect(parseDataFile('{ "a": \'\\ucccc\' }'), <String, Object?>{ 'a': '쳌' }); expect(parseDataFile('{ "a": \'\\udddd\' }'), <String, Object?>{ 'a': '\u{dddd}' }); // low surragate expect(parseDataFile('{ "a": \'\\ueeee\' }'), <String, Object?>{ 'a': '\u{eeee}' }); // private use area expect(parseDataFile('{ "a": \'\\uffff\' }'), <String, Object?>{ 'a': '\u{ffff}' }); // not technically a valid Unicode character expect(parseDataFile('{ "a": \'\\uAAAA\' }'), <String, Object?>{ 'a': 'ꪪ' }); expect(parseDataFile('{ "a": \'\\uBBBB\' }'), <String, Object?>{ 'a': '뮻' }); expect(parseDataFile('{ "a": \'\\uCCCC\' }'), <String, Object?>{ 'a': '쳌' }); expect(parseDataFile('{ "a": \'\\uDDDD\' }'), <String, Object?>{ 'a': '\u{dddd}' }); expect(parseDataFile('{ "a": \'\\uEEEE\' }'), <String, Object?>{ 'a': '\u{eeee}' }); expect(parseDataFile('{ "a": \'\\uFFFF\' }'), <String, Object?>{ 'a': '\u{ffff}' }); expect(parseDataFile('{ "a": /**/ "1" }'), <String, Object?>{ 'a': '1' }); expect(parseDataFile('{ "a": /* */ "1" }'), <String, Object?>{ 'a': '1' }); expect(parseDataFile('{ "a": /*\n*/ "1" }'), <String, Object?>{ 'a': '1' }); }); testWidgets('error handling in parseLibraryFile', (WidgetTester tester) async { void test(String input, String expectedMessage) { try { parseLibraryFile(input); fail('parsing `$input` did not result in an error (expected "$expectedMessage").'); } on ParserException catch (e) { expect('$e', expectedMessage); } } test('2', 'Expected keywords "import" or "widget", or end of file but found 2 at line 1 column 1.'); test('impor', 'Expected keywords "import" or "widget", or end of file but found impor at line 1 column 5.'); test('import', 'Expected string but found <EOF> at line 1 column 6.'); test('import 2', 'Expected string but found 2 at line 1 column 8.'); test('import foo', 'Expected symbol ";" but found <EOF> at line 1 column 10.'); test('import foo.', 'Expected string but found <EOF> at line 1 column 11.'); test('import foo,', 'Expected symbol ";" but found , at line 1 column 11.'); test('import foo+', 'Unexpected character U+002B ("+") inside identifier at line 1 column 11.'); test('import foo.1', 'Expected string but found 1 at line 1 column 12.'); test('import foo.+', 'Unexpected character U+002B ("+") after period at line 1 column 12.'); test('import foo."', 'Unexpected end of file inside string at line 1 column 12.'); test('import foo. "', 'Unexpected end of file inside string at line 1 column 13.'); test('import foo.\'', 'Unexpected end of file inside string at line 1 column 12.'); test('import foo. \'', 'Unexpected end of file inside string at line 1 column 13.'); test('widget a = b(c: [ ...for args in []: "e" ]);', 'args is a reserved word at line 1 column 30.'); test('widget a = switch 0 { 0: a(), 0: b() };', 'Switch has duplicate cases for key 0 at line 1 column 32.'); test('widget a = switch 0 { default: a(), default: b() };', 'Switch has multiple default cases at line 1 column 44.'); test('widget a = b(c: args)', 'Expected symbol "." but found ) at line 1 column 21.'); test('widget a = b(c: args.=)', 'Unexpected = at line 1 column 22.'); test('widget a = b(c: args.0', 'Expected symbol ")" but found <EOF> at line 1 column 22.'); test('widget a = b(c: args.0 ', 'Expected symbol ")" but found <EOF> at line 1 column 23.'); test('widget a = b(c: args.0)', 'Expected symbol ";" but found <EOF> at line 1 column 23.'); test('widget a = b(c: args.0f', 'Unexpected character U+0066 ("f") in integer at line 1 column 23.'); test('widget a = b(c: [ ..', 'Unexpected end of file inside "..." symbol at line 1 column 20.'); test('widget a = b(c: [ .. ]);', 'Unexpected character U+0020 inside "..." symbol at line 1 column 21.'); test('widget a = b(c: [ ... ]);', 'Expected identifier but found ] at line 1 column 23.'); test('widget a = b(c: [ ...baa ]);', 'Expected for but found baa at line 1 column 25.'); test('widget a = 0;', 'Expected identifier but found 0 at line 1 column 13.'); test('widget a = a.', 'Expected symbol "(" but found . at line 1 column 13.'); test('widget a = a. ', 'Expected symbol "(" but found . at line 1 column 14.'); test('widget a = a.0', 'Expected symbol "(" but found . at line 1 column 14.'); test('widget a = a.0 ', 'Expected symbol "(" but found . at line 1 column 14.'); }); testWidgets('parseLibraryFile: imports', (WidgetTester tester) async { final RemoteWidgetLibrary result = parseLibraryFile('import foo.bar;'); expect(result.imports, hasLength(1)); expect(result.imports.single.toString(), 'import foo.bar;'); expect(result.widgets, isEmpty); }); testWidgets('parseLibraryFile: loops', (WidgetTester tester) async { final RemoteWidgetLibrary result = parseLibraryFile('widget a = b(c: [ ...for d in []: "e" ]);'); expect(result.imports, isEmpty); expect(result.widgets, hasLength(1)); expect(result.widgets.single.toString(), 'widget a = b({c: [...for loop in []: e]});'); }); testWidgets('parseLibraryFile: switch', (WidgetTester tester) async { expect(parseLibraryFile('widget a = switch 0 { 0: a() };').toString(), 'widget a = switch 0 {0: a({})};'); expect(parseLibraryFile('widget a = switch 0 { default: a() };').toString(), 'widget a = switch 0 {null: a({})};'); expect(parseLibraryFile('widget a = b(c: switch 1 { 2: 3 });').toString(), 'widget a = b({c: switch 1 {2: 3}});'); }); testWidgets('parseLibraryFile: references', (WidgetTester tester) async { expect(parseLibraryFile('widget a = b(c:data.11234567890."e");').toString(), 'widget a = b({c: data.11234567890.e});'); expect(parseLibraryFile('widget a = b(c: [...for d in []: d]);').toString(), 'widget a = b({c: [...for loop in []: loop0.]});'); expect(parseLibraryFile('widget a = b(c:args.foo.bar);').toString(), 'widget a = b({c: args.foo.bar});'); expect(parseLibraryFile('widget a = b(c:data.foo.bar);').toString(), 'widget a = b({c: data.foo.bar});'); expect(parseLibraryFile('widget a = b(c:state.foo.bar);').toString(), 'widget a = b({c: state.foo.bar});'); expect(parseLibraryFile('widget a = b(c: [...for d in []: d.bar]);').toString(), 'widget a = b({c: [...for loop in []: loop0.bar]});'); expect(parseLibraryFile('widget a = b(c:args.foo."bar");').toString(), 'widget a = b({c: args.foo.bar});'); expect(parseLibraryFile('widget a = b(c:data.foo."bar");').toString(), 'widget a = b({c: data.foo.bar});'); expect(parseLibraryFile('widget a = b(c:state.foo."bar");').toString(), 'widget a = b({c: state.foo.bar});'); expect(parseLibraryFile('widget a = b(c: [...for d in []: d."bar"]);').toString(), 'widget a = b({c: [...for loop in []: loop0.bar]});'); expect(parseLibraryFile('widget a = b(c:args.foo.9);').toString(), 'widget a = b({c: args.foo.9});'); expect(parseLibraryFile('widget a = b(c:data.foo.9);').toString(), 'widget a = b({c: data.foo.9});'); expect(parseLibraryFile('widget a = b(c:state.foo.9);').toString(), 'widget a = b({c: state.foo.9});'); expect(parseLibraryFile('widget a = b(c: [...for d in []: d.9]);').toString(), 'widget a = b({c: [...for loop in []: loop0.9]});'); expect(parseLibraryFile('widget a = b(c:args.foo.12);').toString(), 'widget a = b({c: args.foo.12});'); expect(parseLibraryFile('widget a = b(c:data.foo.12);').toString(), 'widget a = b({c: data.foo.12});'); expect(parseLibraryFile('widget a = b(c:state.foo.12);').toString(), 'widget a = b({c: state.foo.12});'); expect(parseLibraryFile('widget a = b(c: [...for d in []: d.12]);').toString(), 'widget a = b({c: [...for loop in []: loop0.12]});'); expect(parseLibraryFile('widget a = b(c:args.foo.98);').toString(), 'widget a = b({c: args.foo.98});'); expect(parseLibraryFile('widget a = b(c:data.foo.98);').toString(), 'widget a = b({c: data.foo.98});'); expect(parseLibraryFile('widget a = b(c:state.foo.98);').toString(), 'widget a = b({c: state.foo.98});'); expect(parseLibraryFile('widget a = b(c: [...for d in []: d.98]);').toString(), 'widget a = b({c: [...for loop in []: loop0.98]});'); expect(parseLibraryFile('widget a = b(c:args.foo.000);').toString(), 'widget a = b({c: args.foo.0});'); expect(parseLibraryFile('widget a = b(c:data.foo.000);').toString(), 'widget a = b({c: data.foo.0});'); expect(parseLibraryFile('widget a = b(c:state.foo.000);').toString(), 'widget a = b({c: state.foo.0});'); expect(parseLibraryFile('widget a = b(c: [...for d in []: d.000]);').toString(), 'widget a = b({c: [...for loop in []: loop0.0]});'); }); testWidgets('parseLibraryFile: event handlers', (WidgetTester tester) async { expect(parseLibraryFile('widget a = b(c: event "d" { });').toString(), 'widget a = b({c: event d {}});'); expect(parseLibraryFile('widget a = b(c: set state.d = 0);').toString(), 'widget a = b({c: set state.d = 0});'); }); testWidgets('parseLibraryFile: stateful widgets', (WidgetTester tester) async { expect(parseLibraryFile('widget a {} = c();').toString(), 'widget a = c({});'); expect(parseLibraryFile('widget a {b: 0} = c();').toString(), 'widget a = c({});'); final RemoteWidgetLibrary result = parseLibraryFile('widget a {b: 0} = c();'); expect(result.widgets.single.initialState, <String, Object?>{'b': 0}); }); testWidgets('parseLibraryFile: widgetBuilders work', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = Builder(builder: (scope) => Container()); '''); expect(libraryFile.toString(), 'widget a = Builder({builder: (scope) => Container({})});'); }); testWidgets('parseLibraryFile: widgetBuilders work with arguments', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = Builder(builder: (scope) => Container(width: scope.width)); '''); expect(libraryFile.toString(), 'widget a = Builder({builder: (scope) => Container({width: scope.width})});'); }); testWidgets('parseLibraryFile: widgetBuilder arguments are lexical scoped', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = A( a: (s1) => B( b: (s2) => T(s1: s1.s1, s2: s2.s2), ), ); '''); expect(libraryFile.toString(), 'widget a = A({a: (s1) => B({b: (s2) => T({s1: s1.s1, s2: s2.s2})})});'); }); testWidgets('parseLibraryFile: widgetBuilder arguments can be shadowed', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = A( a: (s1) => B( b: (s1) => T(t: s1.foo), ), ); '''); expect(libraryFile.toString(), 'widget a = A({a: (s1) => B({b: (s1) => T({t: s1.foo})})});'); }); testWidgets('parseLibraryFile: widgetBuilders check the returned value', (WidgetTester tester) async { void test(String input, String expectedMessage) { try { parseLibraryFile(input); fail('parsing `$input` did not result in an error (expected "$expectedMessage").'); } on ParserException catch (e) { expect('$e', expectedMessage); } } const String expectedErrorMessage = 'Expecting a switch or constructor call got 1 at line 1 column 27.'; test('widget a = B(b: (foo) => 1);', expectedErrorMessage); }); testWidgets('parseLibraryFile: widgetBuilders check reserved words', (WidgetTester tester) async { void test(String input, String expectedMessage) { try { parseLibraryFile(input); fail('parsing `$input` did not result in an error (expected "$expectedMessage").'); } on ParserException catch (e) { expect('$e', expectedMessage); } } const String expectedErrorMessage = 'args is a reserved word at line 1 column 34.'; test('widget a = Builder(builder: (args) => Container(width: args.width));', expectedErrorMessage); }); testWidgets('parseLibraryFile: widgetBuilders check reserved words', (WidgetTester tester) async { void test(String input, String expectedMessage) { try { parseDataFile(input); fail('parsing `$input` did not result in an error (expected "$expectedMessage").'); } on ParserException catch (e) { expect('$e', expectedMessage); } } const String expectedErrorMessage = 'Expected symbol "{" but found widget at line 1 column 7.'; test('widget a = Builder(builder: (args) => Container(width: args.width));', expectedErrorMessage); }); testWidgets('parseLibraryFile: switch works with widgetBuilders', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = A( b: switch args.down { true: (foo) => B(), false: (bar) => C(), } ); '''); expect(libraryFile.toString(), 'widget a = A({b: switch args.down {true: (foo) => B({}), false: (bar) => C({})}});'); }); testWidgets('parseLibraryFile: widgetBuilders work with switch', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = A( b: (foo) => switch foo.letter { 'a': A(), 'b': B(), }, ); '''); expect(libraryFile.toString(), 'widget a = A({b: (foo) => switch foo.letter {a: A({}), b: B({})}});'); }); testWidgets('parseLibraryFile: widgetBuilders work with lists', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = A( b: (s1) => B(c: [s1.c]), ); '''); expect(libraryFile.toString(), 'widget a = A({b: (s1) => B({c: [s1.c]})});' ); }); testWidgets('parseLibraryFile: widgetBuilders work with maps', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = A( b: (s1) => B(c: {d: s1.d}), ); '''); expect(libraryFile.toString(), 'widget a = A({b: (s1) => B({c: {d: s1.d}})});'); }); testWidgets('parseLibraryFile: widgetBuilders work with setters', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a {foo: 0} = A( b: (s1) => B(onTap: set state.foo = s1.foo), ); '''); expect(libraryFile.toString(), 'widget a = A({b: (s1) => B({onTap: set state.foo = s1.foo})});'); }); testWidgets('parseLibraryFile: widgetBuilders work with events', (WidgetTester tester) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a {foo: 0} = A( b: (s1) => B(onTap: event "foo" {result: s1.result}) ); '''); expect(libraryFile.toString(), 'widget a = A({b: (s1) => B({onTap: event foo {result: s1.result}})});'); }); }
packages/packages/rfw/test/text_test.dart/0
{ "file_path": "packages/packages/rfw/test/text_test.dart", "repo_id": "packages", "token_count": 11974 }
1,037
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v10.1.6), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #else #error("Unsupported platform.") #endif private func wrapResult(_ result: Any?) -> [Any?] { return [result] } private func wrapError(_ error: Any) -> [Any?] { if let flutterError = error as? FlutterError { return [ flutterError.code, flutterError.message, flutterError.details, ] } return [ "\(error)", "\(type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } private func nilOrValue<T>(_ value: Any?) -> T? { if value is NSNull { return nil } return value as! T? } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UserDefaultsApi { func remove(key: String) throws func setBool(key: String, value: Bool) throws func setDouble(key: String, value: Double) throws func setValue(key: String, value: Any) throws func getAll(prefix: String, allowList: [String]?) throws -> [String?: Any?] func clear(prefix: String, allowList: [String]?) throws -> Bool } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class UserDefaultsApiSetup { /// The codec used by UserDefaultsApi. /// Sets up an instance of `UserDefaultsApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: UserDefaultsApi?) { let removeChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.remove", binaryMessenger: binaryMessenger) if let api = api { removeChannel.setMessageHandler { message, reply in let args = message as! [Any?] let keyArg = args[0] as! String do { try api.remove(key: keyArg) reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { removeChannel.setMessageHandler(nil) } let setBoolChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setBool", binaryMessenger: binaryMessenger) if let api = api { setBoolChannel.setMessageHandler { message, reply in let args = message as! [Any?] let keyArg = args[0] as! String let valueArg = args[1] as! Bool do { try api.setBool(key: keyArg, value: valueArg) reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { setBoolChannel.setMessageHandler(nil) } let setDoubleChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setDouble", binaryMessenger: binaryMessenger) if let api = api { setDoubleChannel.setMessageHandler { message, reply in let args = message as! [Any?] let keyArg = args[0] as! String let valueArg = args[1] as! Double do { try api.setDouble(key: keyArg, value: valueArg) reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { setDoubleChannel.setMessageHandler(nil) } let setValueChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setValue", binaryMessenger: binaryMessenger) if let api = api { setValueChannel.setMessageHandler { message, reply in let args = message as! [Any?] let keyArg = args[0] as! String let valueArg = args[1]! do { try api.setValue(key: keyArg, value: valueArg) reply(wrapResult(nil)) } catch { reply(wrapError(error)) } } } else { setValueChannel.setMessageHandler(nil) } let getAllChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.getAll", binaryMessenger: binaryMessenger) if let api = api { getAllChannel.setMessageHandler { message, reply in let args = message as! [Any?] let prefixArg = args[0] as! String let allowListArg: [String]? = nilOrValue(args[1]) do { let result = try api.getAll(prefix: prefixArg, allowList: allowListArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { getAllChannel.setMessageHandler(nil) } let clearChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.clear", binaryMessenger: binaryMessenger) if let api = api { clearChannel.setMessageHandler { message, reply in let args = message as! [Any?] let prefixArg = args[0] as! String let allowListArg: [String]? = nilOrValue(args[1]) do { let result = try api.clear(prefix: prefixArg, allowList: allowListArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { clearChannel.setMessageHandler(nil) } } }
packages/packages/shared_preferences/shared_preferences_foundation/darwin/Classes/messages.g.swift/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/darwin/Classes/messages.g.swift", "repo_id": "packages", "token_count": 2177 }
1,038
// 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:shared_preferences_foundation/shared_preferences_foundation.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; import 'test_api.g.dart'; class _MockSharedPreferencesApi implements TestUserDefaultsApi { final Map<String, Object> items = <String, Object>{}; @override Map<String?, Object?> getAll( String prefix, List<String?>? allowList, ) { Set<String?>? allowSet; if (allowList != null) { allowSet = Set<String>.from(allowList); } return <String?, Object?>{ for (final String key in items.keys) if (key.startsWith(prefix) && (allowSet == null || allowSet.contains(key))) key: items[key] }; } @override void remove(String key) { items.remove(key); } @override void setBool(String key, bool value) { items[key] = value; } @override void setDouble(String key, double value) { items[key] = value; } @override void setValue(String key, Object value) { items[key] = value; } @override bool clear(String prefix, List<String?>? allowList) { items.keys.toList().forEach((String key) { if (key.startsWith(prefix) && (allowList == null || allowList.contains(key))) { items.remove(key); } }); return true; } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); late _MockSharedPreferencesApi api; const Map<String, Object> flutterTestValues = <String, Object>{ 'flutter.String': 'hello world', 'flutter.Bool': true, 'flutter.Int': 42, 'flutter.Double': 3.14159, 'flutter.StringList': <String>['foo', 'bar'], }; const Map<String, Object> prefixTestValues = <String, Object>{ 'prefix.String': 'hello world', 'prefix.Bool': true, 'prefix.Int': 42, 'prefix.Double': 3.14159, 'prefix.StringList': <String>['foo', 'bar'], }; const Map<String, Object> nonPrefixTestValues = <String, Object>{ 'String': 'hello world', 'Bool': true, 'Int': 42, 'Double': 3.14159, 'StringList': <String>['foo', 'bar'], }; final Map<String, Object> allTestValues = <String, Object>{}; allTestValues.addAll(flutterTestValues); allTestValues.addAll(prefixTestValues); allTestValues.addAll(nonPrefixTestValues); setUp(() { api = _MockSharedPreferencesApi(); TestUserDefaultsApi.setup(api); }); test('registerWith', () { SharedPreferencesFoundation.registerWith(); expect(SharedPreferencesStorePlatform.instance, isA<SharedPreferencesFoundation>()); }); test('remove', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); api.items['flutter.hi'] = 'world'; expect(await plugin.remove('flutter.hi'), isTrue); expect(api.items.containsKey('flutter.hi'), isFalse); }); test('clear', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); api.items['flutter.hi'] = 'world'; expect(await plugin.clear(), isTrue); expect(api.items.containsKey('flutter.hi'), isFalse); }); test('clearWithPrefix', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } Map<String?, Object?> all = await plugin.getAllWithPrefix('prefix.'); expect(all.length, 5); await plugin.clearWithPrefix('prefix.'); all = await plugin.getAll(); expect(all.length, 5); all = await plugin.getAllWithPrefix('prefix.'); expect(all.length, 0); }); test('clearWithParameters', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } Map<String?, Object?> all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(all.length, 5); await plugin.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); all = await plugin.getAll(); expect(all.length, 5); all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(all.length, 0); }); test('clearWithParameters with allow list', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } Map<String?, Object?> all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(all.length, 5); await plugin.clearWithParameters( ClearParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.String'}, ), ), ); all = await plugin.getAll(); expect(all.length, 5); all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(all.length, 4); }); test('getAll', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in flutterTestValues.keys) { api.items[key] = flutterTestValues[key]!; } final Map<String?, Object?> all = await plugin.getAll(); expect(all.length, 5); expect(all, flutterTestValues); }); test('getAllWithPrefix', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } final Map<String?, Object?> all = await plugin.getAllWithPrefix('prefix.'); expect(all.length, 5); expect(all, prefixTestValues); }); test('getAllWithParameters', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } final Map<String?, Object?> all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(all.length, 5); expect(all, prefixTestValues); }); test('getAllWithParameters with allow list', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } final Map<String?, Object?> all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.Bool'}, ), ), ); expect(all.length, 1); expect(all['prefix.Bool'], prefixTestValues['prefix.Bool']); }); test('setValue', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); expect(await plugin.setValue('Bool', 'flutter.Bool', true), isTrue); expect(api.items['flutter.Bool'], true); expect(await plugin.setValue('Double', 'flutter.Double', 1.5), isTrue); expect(api.items['flutter.Double'], 1.5); expect(await plugin.setValue('Int', 'flutter.Int', 12), isTrue); expect(api.items['flutter.Int'], 12); expect(await plugin.setValue('String', 'flutter.String', 'hi'), isTrue); expect(api.items['flutter.String'], 'hi'); expect( await plugin .setValue('StringList', 'flutter.StringList', <String>['hi']), isTrue); expect(api.items['flutter.StringList'], <String>['hi']); }); test('setValue with unsupported type', () { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); expect(() async { await plugin.setValue('Map', 'flutter.key', <String, String>{}); }, throwsA(isA<PlatformException>())); }); test('getAllWithNoPrefix', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } final Map<String?, Object?> all = await plugin.getAllWithPrefix(''); expect(all.length, 15); expect(all, allTestValues); }); test('clearWithNoPrefix', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } Map<String?, Object?> all = await plugin.getAllWithPrefix(''); expect(all.length, 15); await plugin.clearWithPrefix(''); all = await plugin.getAllWithPrefix(''); expect(all.length, 0); }); test('getAllWithNoPrefix with param', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } final Map<String?, Object?> all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(all.length, 15); expect(all, allTestValues); }); test('clearWithNoPrefix with param', () async { final SharedPreferencesFoundation plugin = SharedPreferencesFoundation(); for (final String key in allTestValues.keys) { api.items[key] = allTestValues[key]!; } Map<String?, Object?> all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(all.length, 15); await plugin.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); all = await plugin.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(all.length, 0); }); }
packages/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_foundation_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_foundation_test.dart", "repo_id": "packages", "token_count": 3808 }
1,039
name: shared_preferences_platform_interface description: A common platform interface for the shared_preferences plugin. repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 version: 2.3.2 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter plugin_platform_interface: ^2.1.7 dev_dependencies: flutter_test: sdk: flutter topics: - persistence - shared-preferences - storage
packages/packages/shared_preferences/shared_preferences_platform_interface/pubspec.yaml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_platform_interface/pubspec.yaml", "repo_id": "packages", "token_count": 231 }
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 'dart:typed_data'; import 'package:standard_message_codec/standard_message_codec.dart'; import 'package:test/test.dart'; const StandardMessageCodec messageCodec = StandardMessageCodec(); void main() { group('Standard method codec', () { test('Should encode and decode objects produced from codec', () { final ByteData? data = messageCodec.encodeMessage(<Object, Object>{ 'foo': true, 3: 'fizz', }); expect(messageCodec.decodeMessage(data), <Object?, Object?>{ 'foo': true, 3: 'fizz', }); }); }); group('Write and read buffer round-trip', () { test('of empty buffer', () { final WriteBuffer write = WriteBuffer(); final ByteData written = write.done(); expect(written.lengthInBytes, 0); }); test('of single byte', () { final WriteBuffer write = WriteBuffer(); write.putUint8(201); final ByteData written = write.done(); expect(written.lengthInBytes, equals(1)); final ReadBuffer read = ReadBuffer(written); expect(read.getUint8(), equals(201)); }); test('of 32-bit integer', () { final WriteBuffer write = WriteBuffer(); write.putInt32(-9); final ByteData written = write.done(); expect(written.lengthInBytes, equals(4)); final ReadBuffer read = ReadBuffer(written); expect(read.getInt32(), equals(-9)); }); test('of 32-bit integer in big endian', () { final WriteBuffer write = WriteBuffer(); write.putInt32(-9, endian: Endian.big); final ByteData written = write.done(); expect(written.lengthInBytes, equals(4)); final ReadBuffer read = ReadBuffer(written); expect(read.getInt32(endian: Endian.big), equals(-9)); }); test('of 64-bit integer', () { final WriteBuffer write = WriteBuffer(); write.putInt64(-9000000000000); final ByteData written = write.done(); expect(written.lengthInBytes, equals(8)); final ReadBuffer read = ReadBuffer(written); expect(read.getInt64(), equals(-9000000000000)); }, testOn: 'vm' /* Int64 isn't supported on web */); test('of 64-bit integer in big endian', () { final WriteBuffer write = WriteBuffer(); write.putInt64(-9000000000000, endian: Endian.big); final ByteData written = write.done(); expect(written.lengthInBytes, equals(8)); final ReadBuffer read = ReadBuffer(written); expect(read.getInt64(endian: Endian.big), equals(-9000000000000)); }, testOn: 'vm' /* Int64 isn't supported on web */); test('of double', () { final WriteBuffer write = WriteBuffer(); write.putFloat64(3.14); final ByteData written = write.done(); expect(written.lengthInBytes, equals(8)); final ReadBuffer read = ReadBuffer(written); expect(read.getFloat64(), equals(3.14)); }); test('of double in big endian', () { final WriteBuffer write = WriteBuffer(); write.putFloat64(3.14, endian: Endian.big); final ByteData written = write.done(); expect(written.lengthInBytes, equals(8)); final ReadBuffer read = ReadBuffer(written); expect(read.getFloat64(endian: Endian.big), equals(3.14)); }); test('of 32-bit int list when unaligned', () { final Int32List integers = Int32List.fromList(<int>[-99, 2, 99]); final WriteBuffer write = WriteBuffer(); write.putUint8(9); write.putInt32List(integers); final ByteData written = write.done(); expect(written.lengthInBytes, equals(16)); final ReadBuffer read = ReadBuffer(written); read.getUint8(); expect(read.getInt32List(3), equals(integers)); }); test('of 64-bit int list when unaligned', () { final Int64List integers = Int64List.fromList(<int>[-99, 2, 99]); final WriteBuffer write = WriteBuffer(); write.putUint8(9); write.putInt64List(integers); final ByteData written = write.done(); expect(written.lengthInBytes, equals(32)); final ReadBuffer read = ReadBuffer(written); read.getUint8(); expect(read.getInt64List(3), equals(integers)); }, testOn: 'vm' /* Int64 isn't supported on web */); test('of float list when unaligned', () { final Float32List floats = Float32List.fromList(<double>[3.14, double.nan]); final WriteBuffer write = WriteBuffer(); write.putUint8(9); write.putFloat32List(floats); final ByteData written = write.done(); expect(written.lengthInBytes, equals(12)); final ReadBuffer read = ReadBuffer(written); read.getUint8(); final Float32List readFloats = read.getFloat32List(2); expect(readFloats[0], closeTo(3.14, 0.0001)); expect(readFloats[1], isNaN); }); test('of double list when unaligned', () { final Float64List doubles = Float64List.fromList(<double>[3.14, double.nan]); final WriteBuffer write = WriteBuffer(); write.putUint8(9); write.putFloat64List(doubles); final ByteData written = write.done(); expect(written.lengthInBytes, equals(24)); final ReadBuffer read = ReadBuffer(written); read.getUint8(); final Float64List readDoubles = read.getFloat64List(2); expect(readDoubles[0], equals(3.14)); expect(readDoubles[1], isNaN); }); test('done twice', () { final WriteBuffer write = WriteBuffer(); write.done(); expect(() => write.done(), throwsStateError); }); test('empty WriteBuffer', () { expect( () => WriteBuffer(startCapacity: 0), throwsA(isA<AssertionError>())); }); test('size 1', () { expect(() => WriteBuffer(startCapacity: 1), returnsNormally); }); }); }
packages/packages/standard_message_codec/test/standard_message_codec_test.dart/0
{ "file_path": "packages/packages/standard_message_codec/test/standard_message_codec_test.dart", "repo_id": "packages", "token_count": 2240 }
1,041
#include "Generated.xcconfig"
packages/packages/two_dimensional_scrollables/example/ios/Flutter/Release.xcconfig/0
{ "file_path": "packages/packages/two_dimensional_scrollables/example/ios/Flutter/Release.xcconfig", "repo_id": "packages", "token_count": 12 }
1,042
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/two_dimensional_scrollables/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/two_dimensional_scrollables/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
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 'dart:collection'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'table_cell.dart'; import 'table_delegate.dart'; import 'table_span.dart'; /// A widget that displays a table, which can scroll in horizontal and vertical /// directions. /// /// A table consists of rows and columns. Rows fill the horizontal space of /// the table, while columns fill it vertically. If there is not enough space /// available to display all the rows at the same time, the table will scroll /// vertically. If there is not enough space for all the columns, it will /// scroll horizontally. /// /// Each child [TableViewCell] can belong to either exactly one row and one /// column as represented by its [TableVicinity], or it can span multiple rows /// and columns through merging. The table supports lazy rendering and will only /// instantiate those cells that are currently visible in the table's viewport /// and those that extend into the [cacheExtent]. Therefore, when merging cells /// in a [TableView], the same child must be returned from every vicinity the /// merged cell contains. The `build` method will only be called once for a /// merged cell, but since the table's children are lazily laid out, returning /// the same child ensures the merged cell can be built no matter which part of /// it is visible. /// /// The layout of the table (e.g. how many rows/columns there are and their /// extents) as well as the content of the individual cells is defined by /// the provided [delegate], a subclass of [TwoDimensionalChildDelegate] with /// the [TableCellDelegateMixin]. The [TableView.builder] and [TableView.list] /// constructors create their own delegate. /// /// This example shows a TableView of 100 children, all sized 100 by 100 /// pixels with a few [TableSpanDecoration]s like background colors and borders. /// The `builder` constructor is called on demand for the cells that are visible /// in the TableView. /// /// ```dart /// TableView.builder( /// cellBuilder: (BuildContext context, TableVicinity vicinity) { /// return TableViewCell( /// child: Center( /// child: Text('Cell ${vicinity.column} : ${vicinity.row}'), /// ), /// ); /// }, /// columnCount: 10, /// columnBuilder: (int column) { /// return TableSpan( /// extent: FixedTableSpanExtent(100), /// foregroundDecoration: TableSpanDecoration( /// border: TableSpanBorder( /// trailing: BorderSide( /// color: Colors.black, /// width: 2, /// style: BorderStyle.solid, /// ), /// ), /// ), /// ); /// }, /// rowCount: 10, /// rowBuilder: (int row) { /// return TableSpan( /// extent: FixedTableSpanExtent(100), /// backgroundDecoration: TableSpanDecoration( /// color: row.isEven? Colors.blueAccent[100] : Colors.white, /// ), /// ); /// }, /// ); /// ``` /// /// See also: /// /// * [TableSpan], describes the configuration for a row or column in the /// TableView. /// * [TwoDimensionalScrollView], the super class that is extended by TableView. /// * [GridView], another scrolling widget that can be used to create tables /// that scroll in one dimension. class TableView extends TwoDimensionalScrollView { /// Creates a [TableView] that scrolls in both dimensions. /// /// A non-null [delegate] must be provided. const TableView({ super.key, super.primary, super.mainAxis, super.horizontalDetails, super.verticalDetails, super.cacheExtent, required TableCellDelegateMixin super.delegate, super.diagonalDragBehavior = DiagonalDragBehavior.none, super.dragStartBehavior, super.keyboardDismissBehavior, super.clipBehavior, }); /// Creates a [TableView] of widgets that are created on demand. /// /// This constructor is appropriate for table views with a large /// number of cells because the [cellbuilder] is called only for those /// cells that are actually visible. /// /// This constructor generates a [TableCellBuilderDelegate] for building /// children on demand using the required [cellBuilder], /// [columnBuilder], and [rowBuilder]. TableView.builder({ super.key, super.primary, super.mainAxis, super.horizontalDetails, super.verticalDetails, super.cacheExtent, super.diagonalDragBehavior = DiagonalDragBehavior.none, super.dragStartBehavior, super.keyboardDismissBehavior, super.clipBehavior, int pinnedRowCount = 0, int pinnedColumnCount = 0, required int columnCount, required int rowCount, required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, required TableViewCellBuilder cellBuilder, }) : assert(pinnedRowCount >= 0), assert(rowCount >= 0), assert(rowCount >= pinnedRowCount), assert(columnCount >= 0), assert(pinnedColumnCount >= 0), assert(columnCount >= pinnedColumnCount), super( delegate: TableCellBuilderDelegate( columnCount: columnCount, rowCount: rowCount, pinnedColumnCount: pinnedColumnCount, pinnedRowCount: pinnedRowCount, cellBuilder: cellBuilder, columnBuilder: columnBuilder, rowBuilder: rowBuilder, ), ); /// Creates a [TableView] from an explicit two dimensional array of children. /// /// This constructor is appropriate for list views with a small number of /// children because constructing the [List] requires doing work for every /// child that could possibly be displayed in the list view instead of just /// those children that are actually visible. /// /// The [children] are accessed for each [TableVicinity.column] and /// [TableVicinity.row] of the [TwoDimensionalViewport] as /// `children[vicinity.column][vicinity.row]`. TableView.list({ super.key, super.primary, super.mainAxis, super.horizontalDetails, super.verticalDetails, super.cacheExtent, super.diagonalDragBehavior = DiagonalDragBehavior.none, super.dragStartBehavior, super.keyboardDismissBehavior, super.clipBehavior, int pinnedRowCount = 0, int pinnedColumnCount = 0, required TableSpanBuilder columnBuilder, required TableSpanBuilder rowBuilder, List<List<TableViewCell>> cells = const <List<TableViewCell>>[], }) : assert(pinnedRowCount >= 0), assert(pinnedColumnCount >= 0), super( delegate: TableCellListDelegate( pinnedColumnCount: pinnedColumnCount, pinnedRowCount: pinnedRowCount, cells: cells, columnBuilder: columnBuilder, rowBuilder: rowBuilder, ), ); @override TableViewport buildViewport( BuildContext context, ViewportOffset verticalOffset, ViewportOffset horizontalOffset, ) { return TableViewport( verticalOffset: verticalOffset, verticalAxisDirection: verticalDetails.direction, horizontalOffset: horizontalOffset, horizontalAxisDirection: horizontalDetails.direction, delegate: delegate as TableCellDelegateMixin, mainAxis: mainAxis, cacheExtent: cacheExtent, clipBehavior: clipBehavior, ); } } /// A widget through which a portion of a Table of [Widget] children are viewed, /// typically in combination with a [TableView]. class TableViewport extends TwoDimensionalViewport { /// Creates a viewport for [Widget]s that extend and scroll in both /// horizontal and vertical dimensions. const TableViewport({ super.key, required super.verticalOffset, required super.verticalAxisDirection, required super.horizontalOffset, required super.horizontalAxisDirection, required TableCellDelegateMixin super.delegate, required super.mainAxis, super.cacheExtent, super.clipBehavior, }); @override RenderTwoDimensionalViewport createRenderObject(BuildContext context) { return RenderTableViewport( horizontalOffset: horizontalOffset, horizontalAxisDirection: horizontalAxisDirection, verticalOffset: verticalOffset, verticalAxisDirection: verticalAxisDirection, mainAxis: mainAxis, cacheExtent: cacheExtent, clipBehavior: clipBehavior, delegate: delegate as TableCellDelegateMixin, childManager: context as TwoDimensionalChildManager, ); } @override void updateRenderObject( BuildContext context, RenderTableViewport renderObject, ) { renderObject ..horizontalOffset = horizontalOffset ..horizontalAxisDirection = horizontalAxisDirection ..verticalOffset = verticalOffset ..verticalAxisDirection = verticalAxisDirection ..mainAxis = mainAxis ..cacheExtent = cacheExtent ..clipBehavior = clipBehavior ..delegate = delegate as TableCellDelegateMixin; } } /// A render object for viewing [RenderBox]es in a table format that extends in /// both the horizontal and vertical dimensions. /// /// [RenderTableViewport] is the visual workhorse of the [TableView]. It /// displays a subset of its children according to its own dimensions and the /// given [verticalOffset] and [horizontalOffset]. As the offset varies, /// different children are visible through the viewport. class RenderTableViewport extends RenderTwoDimensionalViewport { /// Creates a viewport for [RenderBox] objects in a table format of rows and /// columns. RenderTableViewport({ required super.horizontalOffset, required super.horizontalAxisDirection, required super.verticalOffset, required super.verticalAxisDirection, required TableCellDelegateMixin super.delegate, required super.mainAxis, required super.childManager, super.cacheExtent, super.clipBehavior, }); @override TableCellDelegateMixin get delegate => super.delegate as TableCellDelegateMixin; @override set delegate(TableCellDelegateMixin value) { super.delegate = value; } // Skipped vicinities for the current frame based on merged cells. // This prevents multiple build calls for the same cell that spans multiple // vicinities. // The key represents a skipped vicinity, the value is the resolved vicinity // of the merged child. final Map<TableVicinity, TableVicinity> _mergedVicinities = <TableVicinity, TableVicinity>{}; // These contain the indexes of rows/columns that contain merged cells to // optimize decoration drawing for rows/columns that don't contain merged // cells. final List<int> _mergedRows = <int>[]; final List<int> _mergedColumns = <int>[]; // Cached Table metrics Map<int, _Span> _columnMetrics = <int, _Span>{}; Map<int, _Span> _rowMetrics = <int, _Span>{}; int? _firstNonPinnedRow; int? _firstNonPinnedColumn; int? _lastNonPinnedRow; int? _lastNonPinnedColumn; TableVicinity? get _firstNonPinnedCell { if (_firstNonPinnedRow == null || _firstNonPinnedColumn == null) { return null; } return TableVicinity( column: _firstNonPinnedColumn!, row: _firstNonPinnedRow!, ); } TableVicinity? get _lastNonPinnedCell { if (_lastNonPinnedRow == null || _lastNonPinnedColumn == null) { return null; } return TableVicinity( column: _lastNonPinnedColumn!, row: _lastNonPinnedRow!, ); } // TODO(Piinks): Pinned rows/cols do not account for what is visible on the // screen. Ostensibly, we would not want to have pinned rows/columns that // extend beyond the viewport, we would never see them as they would never // scroll into view. So this currently implementation is fairly assuming // we will never have rows/cols that are outside of the viewport. We should // maybe add an assertion for this during layout. // https://github.com/flutter/flutter/issues/136833 int? get _lastPinnedRow => delegate.pinnedRowCount > 0 ? delegate.pinnedRowCount - 1 : null; int? get _lastPinnedColumn => delegate.pinnedColumnCount > 0 ? delegate.pinnedColumnCount - 1 : null; double get _pinnedRowsExtent => _lastPinnedRow != null ? _rowMetrics[_lastPinnedRow]!.trailingOffset : 0.0; double get _pinnedColumnsExtent => _lastPinnedColumn != null ? _columnMetrics[_lastPinnedColumn]!.trailingOffset : 0.0; @override TableViewParentData parentDataOf(RenderBox child) => super.parentDataOf(child) as TableViewParentData; @override void setupParentData(RenderBox child) { if (child.parentData is! TableViewParentData) { child.parentData = TableViewParentData(); } } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { RenderBox? cell = firstChild; while (cell != null) { final TableViewParentData cellParentData = parentDataOf(cell); if (!cellParentData.isVisible) { // This cell is not visible, so it cannot be hit. cell = childAfter(cell); continue; } final Rect cellRect = cellParentData.paintOffset! & cell.size; if (cellRect.contains(position)) { result.addWithPaintOffset( offset: cellParentData.paintOffset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - cellParentData.paintOffset!); return cell!.hitTest(result, position: transformed); }, ); switch (mainAxis) { case Axis.vertical: // Row major order, rows go first. result.add( HitTestEntry(_rowMetrics[cellParentData.tableVicinity.row]!), ); result.add( HitTestEntry( _columnMetrics[cellParentData.tableVicinity.column]!), ); case Axis.horizontal: // Column major order, columns go first. result.add( HitTestEntry( _columnMetrics[cellParentData.tableVicinity.column]!), ); result.add( HitTestEntry(_rowMetrics[cellParentData.tableVicinity.row]!), ); } return true; } cell = childAfter(cell); } return false; } // Updates the cached metrics for the table. // // Will iterate through all columns and rows to define the layout pattern of // the cells of the table. // // TODO(Piinks): Add back infinite separately for easier review, https://github.com/flutter/flutter/issues/131226 // Only relevant when the number of rows and columns is finite void _updateAllMetrics() { assert(needsDelegateRebuild || didResize); _firstNonPinnedColumn = null; _lastNonPinnedColumn = null; double startOfRegularColumn = 0; double startOfPinnedColumn = 0; final Map<int, _Span> newColumnMetrics = <int, _Span>{}; for (int column = 0; column < delegate.columnCount; column++) { final bool isPinned = column < delegate.pinnedColumnCount; final double leadingOffset = isPinned ? startOfPinnedColumn : startOfRegularColumn; _Span? span = _columnMetrics.remove(column); assert(needsDelegateRebuild || span != null); final TableSpan configuration = needsDelegateRebuild ? delegate.buildColumn(column) : span!.configuration; span ??= _Span(); span.update( isPinned: isPinned, configuration: configuration, leadingOffset: leadingOffset, extent: configuration.extent.calculateExtent( TableSpanExtentDelegate( viewportExtent: viewportDimension.width, precedingExtent: leadingOffset, ), ), ); newColumnMetrics[column] = span; if (!isPinned) { if (span.trailingOffset >= horizontalOffset.pixels && _firstNonPinnedColumn == null) { _firstNonPinnedColumn = column; } final double targetColumnPixel = cacheExtent + horizontalOffset.pixels + viewportDimension.width - startOfPinnedColumn; if (span.trailingOffset >= targetColumnPixel && _lastNonPinnedColumn == null) { _lastNonPinnedColumn = column; } startOfRegularColumn = span.trailingOffset; } else { startOfPinnedColumn = span.trailingOffset; } } assert(newColumnMetrics.length >= delegate.pinnedColumnCount); for (final _Span span in _columnMetrics.values) { span.dispose(); } _columnMetrics = newColumnMetrics; _firstNonPinnedRow = null; _lastNonPinnedRow = null; double startOfRegularRow = 0; double startOfPinnedRow = 0; final Map<int, _Span> newRowMetrics = <int, _Span>{}; for (int row = 0; row < delegate.rowCount; row++) { final bool isPinned = row < delegate.pinnedRowCount; final double leadingOffset = isPinned ? startOfPinnedRow : startOfRegularRow; _Span? span = _rowMetrics.remove(row); assert(needsDelegateRebuild || span != null); final TableSpan configuration = needsDelegateRebuild ? delegate.buildRow(row) : span!.configuration; span ??= _Span(); span.update( isPinned: isPinned, configuration: configuration, leadingOffset: leadingOffset, extent: configuration.extent.calculateExtent( TableSpanExtentDelegate( viewportExtent: viewportDimension.height, precedingExtent: leadingOffset, ), ), ); newRowMetrics[row] = span; if (!isPinned) { if (span.trailingOffset >= verticalOffset.pixels && _firstNonPinnedRow == null) { _firstNonPinnedRow = row; } final double targetRowPixel = cacheExtent + verticalOffset.pixels + viewportDimension.height - startOfPinnedRow; if (span.trailingOffset >= targetRowPixel && _lastNonPinnedRow == null) { _lastNonPinnedRow = row; } startOfRegularRow = span.trailingOffset; } else { startOfPinnedRow = span.trailingOffset; } } assert(newRowMetrics.length >= delegate.pinnedRowCount); for (final _Span span in _rowMetrics.values) { span.dispose(); } _rowMetrics = newRowMetrics; final double maxVerticalScrollExtent; if (_rowMetrics.length <= delegate.pinnedRowCount) { assert(_firstNonPinnedRow == null && _lastNonPinnedRow == null); maxVerticalScrollExtent = 0.0; } else { final int lastRow = _rowMetrics.length - 1; if (_firstNonPinnedRow != null) { _lastNonPinnedRow ??= lastRow; } maxVerticalScrollExtent = math.max( 0.0, _rowMetrics[lastRow]!.trailingOffset - viewportDimension.height + startOfPinnedRow, ); } final double maxHorizontalScrollExtent; if (_columnMetrics.length <= delegate.pinnedColumnCount) { assert(_firstNonPinnedColumn == null && _lastNonPinnedColumn == null); maxHorizontalScrollExtent = 0.0; } else { final int lastColumn = _columnMetrics.length - 1; if (_firstNonPinnedColumn != null) { _lastNonPinnedColumn ??= lastColumn; } maxHorizontalScrollExtent = math.max( 0.0, _columnMetrics[lastColumn]!.trailingOffset - viewportDimension.width + startOfPinnedColumn, ); } final bool acceptedDimension = horizontalOffset.applyContentDimensions( 0.0, maxHorizontalScrollExtent) && verticalOffset.applyContentDimensions(0.0, maxVerticalScrollExtent); if (!acceptedDimension) { _updateFirstAndLastVisibleCell(); } } // Uses the cached metrics to update the currently visible cells // // TODO(Piinks): Add back infinite separately for easier review, https://github.com/flutter/flutter/issues/131226 // Only relevant when the number of rows and columns is finite void _updateFirstAndLastVisibleCell() { _firstNonPinnedColumn = null; _lastNonPinnedColumn = null; final double targetColumnPixel = cacheExtent + horizontalOffset.pixels + viewportDimension.width - _pinnedColumnsExtent; for (int column = 0; column < _columnMetrics.length; column++) { if (_columnMetrics[column]!.isPinned) { continue; } final double endOfColumn = _columnMetrics[column]!.trailingOffset; if (endOfColumn >= horizontalOffset.pixels && _firstNonPinnedColumn == null) { _firstNonPinnedColumn = column; } if (endOfColumn >= targetColumnPixel && _lastNonPinnedColumn == null) { _lastNonPinnedColumn = column; break; } } if (_firstNonPinnedColumn != null) { _lastNonPinnedColumn ??= _columnMetrics.length - 1; } _firstNonPinnedRow = null; _lastNonPinnedRow = null; final double targetRowPixel = cacheExtent + verticalOffset.pixels + viewportDimension.height - _pinnedRowsExtent; for (int row = 0; row < _rowMetrics.length; row++) { if (_rowMetrics[row]!.isPinned) { continue; } final double endOfRow = _rowMetrics[row]!.trailingOffset; if (endOfRow >= verticalOffset.pixels && _firstNonPinnedRow == null) { _firstNonPinnedRow = row; } if (endOfRow >= targetRowPixel && _lastNonPinnedRow == null) { _lastNonPinnedRow = row; break; } } if (_firstNonPinnedRow != null) { _lastNonPinnedRow ??= _rowMetrics.length - 1; } } @override void layoutChildSequence() { // Reset for a new frame _mergedVicinities.clear(); _mergedRows.clear(); _mergedColumns.clear(); if (needsDelegateRebuild || didResize) { // Recomputes the table metrics, invalidates any cached information. _updateAllMetrics(); } else { // Updates the visible cells based on cached table metrics. _updateFirstAndLastVisibleCell(); } if (_firstNonPinnedCell == null && _lastPinnedRow == null && _lastPinnedColumn == null) { assert(_lastNonPinnedCell == null); return; } final double? offsetIntoColumn = _firstNonPinnedColumn != null ? horizontalOffset.pixels - _columnMetrics[_firstNonPinnedColumn]!.leadingOffset - _pinnedColumnsExtent : null; final double? offsetIntoRow = _firstNonPinnedRow != null ? verticalOffset.pixels - _rowMetrics[_firstNonPinnedRow]!.leadingOffset - _pinnedRowsExtent : null; if (_lastPinnedRow != null && _lastPinnedColumn != null) { // Layout cells that are contained in both pinned rows and columns _layoutCells( start: TableVicinity.zero, end: TableVicinity(column: _lastPinnedColumn!, row: _lastPinnedRow!), offset: Offset.zero, ); } if (_lastPinnedRow != null && _firstNonPinnedColumn != null) { // Layout cells of pinned rows - those that do not intersect with pinned // columns above assert(_lastNonPinnedColumn != null); assert(offsetIntoColumn != null); _layoutCells( start: TableVicinity(column: _firstNonPinnedColumn!, row: 0), end: TableVicinity(column: _lastNonPinnedColumn!, row: _lastPinnedRow!), offset: Offset(offsetIntoColumn!, 0), ); } if (_lastPinnedColumn != null && _firstNonPinnedRow != null) { // Layout cells of pinned columns - those that do not intersect with // pinned rows above assert(_lastNonPinnedRow != null); assert(offsetIntoRow != null); _layoutCells( start: TableVicinity(column: 0, row: _firstNonPinnedRow!), end: TableVicinity(column: _lastPinnedColumn!, row: _lastNonPinnedRow!), offset: Offset(0, offsetIntoRow!), ); } if (_firstNonPinnedCell != null) { // Layout all other cells. assert(_lastNonPinnedCell != null); assert(offsetIntoColumn != null); assert(offsetIntoRow != null); _layoutCells( start: _firstNonPinnedCell!, end: _lastNonPinnedCell!, offset: Offset(offsetIntoColumn!, offsetIntoRow!), ); } } bool _debugCheckMergeBounds({ required String spanOrientation, required int currentSpan, required int spanMergeStart, required int spanMergeEnd, required int spanCount, required int pinnedSpanCount, required TableVicinity currentVicinity, }) { if (spanMergeStart == spanMergeEnd) { // Not merged return true; } final String lowerSpanOrientation = spanOrientation.toLowerCase(); assert( spanMergeStart <= currentSpan, 'The ${lowerSpanOrientation}MergeStart of $spanMergeStart is greater ' 'than the current $lowerSpanOrientation at $currentVicinity.', ); assert( spanMergeEnd < spanCount, '$spanOrientation merge configuration exceeds number of ' '${lowerSpanOrientation}s in the table. $spanOrientation merge ' 'containing $currentVicinity starts at $spanMergeStart, and ends at ' '$spanMergeEnd. The TableView contains $spanCount.', ); if (spanMergeStart < pinnedSpanCount) { // Merged cells cannot span pinned and unpinned cells. assert( spanMergeEnd < pinnedSpanCount, 'Merged cells cannot span pinned and unpinned cells. $spanOrientation ' 'merge containing $currentVicinity starts at $spanMergeStart, and ends ' 'at $spanMergeEnd. ${spanOrientation}s are currently pinned up to ' '$lowerSpanOrientation ${pinnedSpanCount - 1}.', ); } return true; } void _layoutCells({ required TableVicinity start, required TableVicinity end, required Offset offset, }) { _Span colSpan, rowSpan; double rowOffset = -offset.dy; for (int row = start.row; row <= end.row; row += 1) { double columnOffset = -offset.dx; rowSpan = _rowMetrics[row]!; final double standardRowHeight = rowSpan.extent; double? mergedRowHeight; double? mergedRowOffset; rowOffset += rowSpan.configuration.padding.leading; for (int column = start.column; column <= end.column; column += 1) { colSpan = _columnMetrics[column]!; final double standardColumnWidth = colSpan.extent; double? mergedColumnWidth; double? mergedColumnOffset; columnOffset += colSpan.configuration.padding.leading; final TableVicinity vicinity = TableVicinity(column: column, row: row); final RenderBox? cell = _mergedVicinities.keys.contains(vicinity) ? null : buildOrObtainChildFor(vicinity); if (cell != null) { final TableViewParentData cellParentData = parentDataOf(cell); // Merged cell handling if (cellParentData.rowMergeStart != null || cellParentData.columnMergeStart != null) { final int firstRow = cellParentData.rowMergeStart ?? row; final int lastRow = cellParentData.rowMergeStart == null ? row : firstRow + cellParentData.rowMergeSpan! - 1; assert(_debugCheckMergeBounds( spanOrientation: 'Row', currentSpan: row, spanMergeStart: firstRow, spanMergeEnd: lastRow, spanCount: delegate.rowCount, pinnedSpanCount: delegate.pinnedRowCount, currentVicinity: vicinity, )); final int firstColumn = cellParentData.columnMergeStart ?? column; final int lastColumn = cellParentData.columnMergeStart == null ? column : firstColumn + cellParentData.columnMergeSpan! - 1; assert(_debugCheckMergeBounds( spanOrientation: 'Column', currentSpan: column, spanMergeStart: firstColumn, spanMergeEnd: lastColumn, spanCount: delegate.columnCount, pinnedSpanCount: delegate.pinnedColumnCount, currentVicinity: vicinity, )); // Leading padding on the leading cell, and trailing padding on the // trailing cell should be excluded. Interim leading/trailing // paddings are consumed by the merged cell. // Example: This is one whole cell spanning 2 merged columns. // l indicates leading padding, t trailing padding // +---------------------------------------------------------+ // | l | column extent | t | l | column extent | t | // +---------------------------------------------------------+ // | <--------- extent of merged cell ---------> | // Compute height and layout offset for merged rows. final bool rowIsInPinnedColumn = _lastPinnedColumn != null && vicinity.column <= _lastPinnedColumn!; final bool rowIsPinned = _lastPinnedRow != null && firstRow <= _lastPinnedRow!; final double baseRowOffset = switch ((rowIsInPinnedColumn, rowIsPinned)) { // Both row and column are pinned at this cell, or just pinned row. (true, true) || (false, true) => 0.0, // Cell is within a pinned column, or no pinned area at all. (true, false) || (false, false) => _pinnedRowsExtent - verticalOffset.pixels, }; mergedRowOffset = baseRowOffset + _rowMetrics[firstRow]!.leadingOffset + _rowMetrics[firstRow]!.configuration.padding.leading; mergedRowHeight = _rowMetrics[lastRow]!.trailingOffset - _rowMetrics[firstRow]!.leadingOffset - _rowMetrics[lastRow]!.configuration.padding.trailing - _rowMetrics[firstRow]!.configuration.padding.leading; // Compute width and layout offset for merged columns. final bool columnIsInPinnedRow = _lastPinnedRow != null && vicinity.row <= _lastPinnedRow!; final bool columnIsPinned = _lastPinnedColumn != null && firstColumn <= _lastPinnedColumn!; final double baseColumnOffset = switch ((columnIsInPinnedRow, columnIsPinned)) { // Both row and column are pinned at this cell, or just pinned column. (true, true) || (false, true) => 0.0, // Cell is within a pinned row, or no pinned area at all. (true, false) || (false, false) => _pinnedColumnsExtent - horizontalOffset.pixels, }; mergedColumnOffset = baseColumnOffset + _columnMetrics[firstColumn]!.leadingOffset + _columnMetrics[firstColumn]!.configuration.padding.leading; mergedColumnWidth = _columnMetrics[lastColumn]!.trailingOffset - _columnMetrics[firstColumn]!.leadingOffset - _columnMetrics[lastColumn]!.configuration.padding.trailing - _columnMetrics[firstColumn]!.configuration.padding.leading; // Collect all of the vicinities that will not need to be built now. int currentRow = firstRow; while (currentRow <= lastRow) { if (cellParentData.rowMergeStart != null) { _mergedRows.add(currentRow); } int currentColumn = firstColumn; while (currentColumn <= lastColumn) { if (cellParentData.columnMergeStart != null) { _mergedColumns.add(currentColumn); } final TableVicinity key = TableVicinity( row: currentRow, column: currentColumn, ); _mergedVicinities[key] = vicinity; currentColumn++; } currentRow++; } } final BoxConstraints cellConstraints = BoxConstraints.tightFor( width: mergedColumnWidth ?? standardColumnWidth, height: mergedRowHeight ?? standardRowHeight, ); cell.layout(cellConstraints); cellParentData.layoutOffset = Offset( mergedColumnOffset ?? columnOffset, mergedRowOffset ?? rowOffset, ); mergedRowOffset = null; mergedRowHeight = null; mergedColumnOffset = null; mergedColumnWidth = null; } columnOffset += standardColumnWidth + _columnMetrics[column]!.configuration.padding.trailing; } rowOffset += standardRowHeight + _rowMetrics[row]!.configuration.padding.trailing; } } final LayerHandle<ClipRectLayer> _clipPinnedRowsHandle = LayerHandle<ClipRectLayer>(); final LayerHandle<ClipRectLayer> _clipPinnedColumnsHandle = LayerHandle<ClipRectLayer>(); final LayerHandle<ClipRectLayer> _clipCellsHandle = LayerHandle<ClipRectLayer>(); @override void paint(PaintingContext context, Offset offset) { if (_firstNonPinnedCell == null && _lastPinnedRow == null && _lastPinnedColumn == null) { assert(_lastNonPinnedCell == null); return; } // Subclasses of RenderTwoDimensionalViewport will typically use // firstChild to traverse children in a standard paint order that // follows row or column major ordering. Here is slightly different // as we break the cells up into 4 main paint passes to clip for overlap. if (_firstNonPinnedCell != null) { // Paint all visible un-pinned cells assert(_lastNonPinnedCell != null); _clipCellsHandle.layer = context.pushClipRect( needsCompositing, offset, Rect.fromLTWH( axisDirectionIsReversed(horizontalAxisDirection) ? 0.0 : _pinnedColumnsExtent, axisDirectionIsReversed(verticalAxisDirection) ? 0.0 : _pinnedRowsExtent, viewportDimension.width - _pinnedColumnsExtent, viewportDimension.height - _pinnedRowsExtent, ), (PaintingContext context, Offset offset) { _paintCells( context: context, offset: offset, leadingVicinity: _firstNonPinnedCell!, trailingVicinity: _lastNonPinnedCell!, ); }, clipBehavior: clipBehavior, oldLayer: _clipCellsHandle.layer, ); } else { _clipCellsHandle.layer = null; } if (_lastPinnedColumn != null && _firstNonPinnedRow != null) { // Paint all visible pinned column cells that do not intersect with pinned // row cells. _clipPinnedColumnsHandle.layer = context.pushClipRect( needsCompositing, offset, Rect.fromLTWH( axisDirectionIsReversed(horizontalAxisDirection) ? viewportDimension.width - _pinnedColumnsExtent : 0.0, axisDirectionIsReversed(verticalAxisDirection) ? 0.0 : _pinnedRowsExtent, _pinnedColumnsExtent, viewportDimension.height - _pinnedRowsExtent, ), (PaintingContext context, Offset offset) { _paintCells( context: context, offset: offset, leadingVicinity: TableVicinity(column: 0, row: _firstNonPinnedRow!), trailingVicinity: TableVicinity( column: _lastPinnedColumn!, row: _lastNonPinnedRow!), ); }, clipBehavior: clipBehavior, oldLayer: _clipPinnedColumnsHandle.layer, ); } else { _clipPinnedColumnsHandle.layer = null; } if (_lastPinnedRow != null && _firstNonPinnedColumn != null) { // Paint all visible pinned row cells that do not intersect with pinned // column cells. _clipPinnedRowsHandle.layer = context.pushClipRect( needsCompositing, offset, Rect.fromLTWH( axisDirectionIsReversed(horizontalAxisDirection) ? 0.0 : _pinnedColumnsExtent, axisDirectionIsReversed(verticalAxisDirection) ? viewportDimension.height - _pinnedRowsExtent : 0.0, viewportDimension.width - _pinnedColumnsExtent, _pinnedRowsExtent, ), (PaintingContext context, Offset offset) { _paintCells( context: context, offset: offset, leadingVicinity: TableVicinity(column: _firstNonPinnedColumn!, row: 0), trailingVicinity: TableVicinity( column: _lastNonPinnedColumn!, row: _lastPinnedRow!), ); }, clipBehavior: clipBehavior, oldLayer: _clipPinnedRowsHandle.layer, ); } else { _clipPinnedRowsHandle.layer = null; } if (_lastPinnedRow != null && _lastPinnedColumn != null) { // Paint remaining visible pinned cells that represent the intersection of // both pinned rows and columns. _paintCells( context: context, offset: offset, leadingVicinity: TableVicinity.zero, trailingVicinity: TableVicinity(column: _lastPinnedColumn!, row: _lastPinnedRow!), ); } } // If mapMergedVicinityToCanonicalChild is true, it will return the canonical // child for the merged cell, if false, it will return whatever value in the // underlying child data structure is, which could be null if the given // vicinity is covered by a merged cell. // This is relevant for scenarios like painting, where we only want to paint // one merged cell. @override RenderBox? getChildFor( ChildVicinity vicinity, { bool mapMergedVicinityToCanonicalChild = true, }) { return super.getChildFor(vicinity) ?? (mapMergedVicinityToCanonicalChild ? _getMergedChildFor(vicinity as TableVicinity) : null); } RenderBox _getMergedChildFor(TableVicinity vicinity) { // A merged cell spans multiple vicinities, but only lays out one child for // the full area. Returns the child that has been laid out to span the given // vicinity. assert(_mergedVicinities.keys.contains(vicinity)); final TableVicinity mergedVicinity = _mergedVicinities[vicinity]!; // This vicinity must resolve to a child, unless something has gone wrong! return getChildFor( mergedVicinity, mapMergedVicinityToCanonicalChild: false, )!; } void _paintCells({ required PaintingContext context, required TableVicinity leadingVicinity, required TableVicinity trailingVicinity, required Offset offset, }) { // Column decorations final LinkedHashMap<Rect, TableSpanDecoration> foregroundColumns = LinkedHashMap<Rect, TableSpanDecoration>(); final LinkedHashMap<Rect, TableSpanDecoration> backgroundColumns = LinkedHashMap<Rect, TableSpanDecoration>(); final TableSpan rowSpan = _rowMetrics[leadingVicinity.row]!.configuration; for (int column = leadingVicinity.column; column <= trailingVicinity.column; column++) { TableSpan columnSpan = _columnMetrics[column]!.configuration; if (columnSpan.backgroundDecoration != null || columnSpan.foregroundDecoration != null || _mergedColumns.contains(column)) { final List<({RenderBox leading, RenderBox trailing})> decorationCells = <({RenderBox leading, RenderBox trailing})>[]; if (_mergedColumns.isEmpty || !_mergedColumns.contains(column)) { // One decoration across the whole column. decorationCells.add(( leading: getChildFor(TableVicinity( column: column, row: leadingVicinity.row, ))!, trailing: getChildFor(TableVicinity( column: column, row: trailingVicinity.row, ))!, )); } else { // Walk through the rows to separate merged cells for decorating. A // merged column takes the decoration of its leading column. // +---------+-------+-------+ // | | | | // | 1 rect | | | // +---------+-------+-------+ // | merged | | // | 1 rect | | // +---------+-------+-------+ // | 1 rect | | | // | | | | // +---------+-------+-------+ late RenderBox leadingCell; late RenderBox trailingCell; int currentRow = leadingVicinity.row; while (currentRow <= trailingVicinity.row) { TableVicinity vicinity = TableVicinity( column: column, row: currentRow, ); leadingCell = getChildFor(vicinity)!; if (parentDataOf(leadingCell).columnMergeStart != null) { // Merged portion decorated individually since it exceeds the // single column width. decorationCells.add(( leading: leadingCell, trailing: leadingCell, )); currentRow++; continue; } // If this is not a merged cell, collect up all of the cells leading // up to, or following after, the merged cell so we can decorate // efficiently with as few rects as possible. RenderBox? nextCell = leadingCell; while (nextCell != null && parentDataOf(nextCell).columnMergeStart == null) { final TableViewParentData parentData = parentDataOf(nextCell); if (parentData.rowMergeStart != null) { currentRow = parentData.rowMergeStart! + parentData.rowMergeSpan!; } else { currentRow += 1; } trailingCell = nextCell; vicinity = vicinity.copyWith(row: currentRow); nextCell = getChildFor( vicinity, mapMergedVicinityToCanonicalChild: false, ); } decorationCells.add(( leading: leadingCell, trailing: trailingCell, )); } } Rect getColumnRect({ required RenderBox leadingCell, required RenderBox trailingCell, required bool consumePadding, }) { final ({double leading, double trailing}) offsetCorrection = axisDirectionIsReversed(verticalAxisDirection) ? ( leading: leadingCell.size.height, trailing: trailingCell.size.height, ) : (leading: 0.0, trailing: 0.0); return Rect.fromPoints( parentDataOf(leadingCell).paintOffset! + offset - Offset( consumePadding ? columnSpan.padding.leading : 0.0, rowSpan.padding.leading - offsetCorrection.leading, ), parentDataOf(trailingCell).paintOffset! + offset + Offset(trailingCell.size.width, trailingCell.size.height) + Offset( consumePadding ? columnSpan.padding.trailing : 0.0, rowSpan.padding.trailing - offsetCorrection.trailing, ), ); } for (final ({RenderBox leading, RenderBox trailing}) cell in decorationCells) { // If this was a merged cell, the decoration is defined by the leading // cell, which may come from a different column. final int columnIndex = parentDataOf(cell.leading).columnMergeStart ?? parentDataOf(cell.leading).tableVicinity.column; columnSpan = _columnMetrics[columnIndex]!.configuration; if (columnSpan.backgroundDecoration != null) { final Rect rect = getColumnRect( leadingCell: cell.leading, trailingCell: cell.trailing, consumePadding: columnSpan.backgroundDecoration!.consumeSpanPadding, ); backgroundColumns[rect] = columnSpan.backgroundDecoration!; } if (columnSpan.foregroundDecoration != null) { final Rect rect = getColumnRect( leadingCell: cell.leading, trailingCell: cell.trailing, consumePadding: columnSpan.foregroundDecoration!.consumeSpanPadding, ); foregroundColumns[rect] = columnSpan.foregroundDecoration!; } } } } // Row decorations final LinkedHashMap<Rect, TableSpanDecoration> foregroundRows = LinkedHashMap<Rect, TableSpanDecoration>(); final LinkedHashMap<Rect, TableSpanDecoration> backgroundRows = LinkedHashMap<Rect, TableSpanDecoration>(); final TableSpan columnSpan = _columnMetrics[leadingVicinity.column]!.configuration; for (int row = leadingVicinity.row; row <= trailingVicinity.row; row++) { TableSpan rowSpan = _rowMetrics[row]!.configuration; if (rowSpan.backgroundDecoration != null || rowSpan.foregroundDecoration != null || _mergedRows.contains(row)) { final List<({RenderBox leading, RenderBox trailing})> decorationCells = <({RenderBox leading, RenderBox trailing})>[]; if (_mergedRows.isEmpty || !_mergedRows.contains(row)) { // One decoration across the whole row. decorationCells.add(( leading: getChildFor(TableVicinity( column: leadingVicinity.column, row: row, ))!, // leading trailing: getChildFor(TableVicinity( column: trailingVicinity.column, row: row, ))!, // trailing )); } else { // Walk through the columns to separate merged cells for decorating. A // merged row takes the decoration of its leading row. // +---------+--------+--------+ // | 1 rect | merged | 1 rect | // | | 1 rect | | // +---------+ +--------+ // | | | | // | | | | // +---------+--------+--------+ // | | | | // | | | | // +---------+--------+--------+ late RenderBox leadingCell; late RenderBox trailingCell; int currentColumn = leadingVicinity.column; while (currentColumn <= trailingVicinity.column) { TableVicinity vicinity = TableVicinity( column: currentColumn, row: row, ); leadingCell = getChildFor(vicinity)!; if (parentDataOf(leadingCell).rowMergeStart != null) { // Merged portion decorated individually since it exceeds the // single row height. decorationCells.add(( leading: leadingCell, trailing: leadingCell, )); currentColumn++; continue; } // If this is not a merged cell, collect up all of the cells leading // up to, or following after, the merged cell so we can decorate // efficiently with as few rects as possible. RenderBox? nextCell = leadingCell; while (nextCell != null && parentDataOf(nextCell).rowMergeStart == null) { final TableViewParentData parentData = parentDataOf(nextCell); if (parentData.columnMergeStart != null) { currentColumn = parentData.columnMergeStart! + parentData.columnMergeSpan!; } else { currentColumn += 1; } trailingCell = nextCell; vicinity = vicinity.copyWith(column: currentColumn); nextCell = getChildFor( vicinity, mapMergedVicinityToCanonicalChild: false, ); } decorationCells.add(( leading: leadingCell, trailing: trailingCell, )); } } Rect getRowRect({ required RenderBox leadingCell, required RenderBox trailingCell, required bool consumePadding, }) { final ({double leading, double trailing}) offsetCorrection = axisDirectionIsReversed(horizontalAxisDirection) ? ( leading: leadingCell.size.width, trailing: trailingCell.size.width, ) : (leading: 0.0, trailing: 0.0); return Rect.fromPoints( parentDataOf(leadingCell).paintOffset! + offset - Offset( columnSpan.padding.leading - offsetCorrection.leading, consumePadding ? rowSpan.padding.leading : 0.0, ), parentDataOf(trailingCell).paintOffset! + offset + Offset(trailingCell.size.width, trailingCell.size.height) + Offset( columnSpan.padding.leading - offsetCorrection.trailing, consumePadding ? rowSpan.padding.trailing : 0.0, ), ); } for (final ({RenderBox leading, RenderBox trailing}) cell in decorationCells) { // If this was a merged cell, the decoration is defined by the leading // cell, which may come from a different row. final int rowIndex = parentDataOf(cell.leading).rowMergeStart ?? parentDataOf(cell.trailing).tableVicinity.row; rowSpan = _rowMetrics[rowIndex]!.configuration; if (rowSpan.backgroundDecoration != null) { final Rect rect = getRowRect( leadingCell: cell.leading, trailingCell: cell.trailing, consumePadding: rowSpan.backgroundDecoration!.consumeSpanPadding, ); backgroundRows[rect] = rowSpan.backgroundDecoration!; } if (rowSpan.foregroundDecoration != null) { final Rect rect = getRowRect( leadingCell: cell.leading, trailingCell: cell.trailing, consumePadding: rowSpan.foregroundDecoration!.consumeSpanPadding, ); foregroundRows[rect] = rowSpan.foregroundDecoration!; } } } } // Get to painting. // Painting is done in row or column major ordering according to the main // axis, with background decorations first, cells next, and foreground // decorations last. // Background decorations switch (mainAxis) { // Default, row major order. Rows go first. case Axis.vertical: backgroundRows.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( canvas: context.canvas, rect: rect, axisDirection: horizontalAxisDirection, ); decoration.paint(paintingDetails); }); backgroundColumns.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( canvas: context.canvas, rect: rect, axisDirection: verticalAxisDirection, ); decoration.paint(paintingDetails); }); // Column major order. Columns go first. case Axis.horizontal: backgroundColumns.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( canvas: context.canvas, rect: rect, axisDirection: verticalAxisDirection, ); decoration.paint(paintingDetails); }); backgroundRows.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( canvas: context.canvas, rect: rect, axisDirection: horizontalAxisDirection, ); decoration.paint(paintingDetails); }); } // Cells for (int column = leadingVicinity.column; column <= trailingVicinity.column; column++) { for (int row = leadingVicinity.row; row <= trailingVicinity.row; row++) { final TableVicinity vicinity = TableVicinity(column: column, row: row); final RenderBox? cell = getChildFor( vicinity, mapMergedVicinityToCanonicalChild: false, ); if (cell == null) { // Covered by a merged cell assert( _mergedVicinities.keys.contains(vicinity), 'TableViewCell for $vicinity could not be found. If merging ' 'cells, the same TableViewCell must be returned for every ' 'TableVicinity that is contained in the merged area of the ' 'TableView.', ); continue; } final TableViewParentData cellParentData = parentDataOf(cell); if (cellParentData.isVisible) { context.paintChild(cell, offset + cellParentData.paintOffset!); } } } // Foreground decorations switch (mainAxis) { // Default, row major order. Rows go first. case Axis.vertical: foregroundRows.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( canvas: context.canvas, rect: rect, axisDirection: horizontalAxisDirection, ); decoration.paint(paintingDetails); }); foregroundColumns.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( canvas: context.canvas, rect: rect, axisDirection: verticalAxisDirection, ); decoration.paint(paintingDetails); }); // Column major order. Columns go first. case Axis.horizontal: foregroundColumns.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( canvas: context.canvas, rect: rect, axisDirection: verticalAxisDirection, ); decoration.paint(paintingDetails); }); foregroundRows.forEach((Rect rect, TableSpanDecoration decoration) { final TableSpanDecorationPaintDetails paintingDetails = TableSpanDecorationPaintDetails( canvas: context.canvas, rect: rect, axisDirection: horizontalAxisDirection, ); decoration.paint(paintingDetails); }); } } @override void dispose() { _clipPinnedRowsHandle.layer = null; _clipPinnedColumnsHandle.layer = null; _clipCellsHandle.layer = null; super.dispose(); } } class _Span with Diagnosticable implements HitTestTarget, MouseTrackerAnnotation { double get leadingOffset => _leadingOffset; late double _leadingOffset; double get extent => _extent; late double _extent; TableSpan get configuration => _configuration!; TableSpan? _configuration; bool get isPinned => _isPinned; late bool _isPinned; double get trailingOffset { return leadingOffset + extent + configuration.padding.leading + configuration.padding.trailing; } // ---- Span Management ---- void update({ required TableSpan configuration, required double leadingOffset, required double extent, required bool isPinned, }) { _leadingOffset = leadingOffset; _extent = extent; _isPinned = isPinned; if (configuration == _configuration) { return; } _configuration = configuration; // Only sync recognizers if they are in use already. if (_recognizers != null) { _syncRecognizers(); } } void dispose() { _disposeRecognizers(); } // ---- Recognizers management ---- Map<Type, GestureRecognizer>? _recognizers; void _syncRecognizers() { if (configuration.recognizerFactories.isEmpty) { _disposeRecognizers(); return; } final Map<Type, GestureRecognizer> newRecognizers = <Type, GestureRecognizer>{}; for (final Type type in configuration.recognizerFactories.keys) { assert(!newRecognizers.containsKey(type)); newRecognizers[type] = _recognizers?.remove(type) ?? configuration.recognizerFactories[type]!.constructor(); assert( newRecognizers[type].runtimeType == type, 'GestureRecognizerFactory of type $type created a GestureRecognizer of ' 'type ${newRecognizers[type].runtimeType}. The ' 'GestureRecognizerFactory must be specialized with the type of the ' 'class that it returns from its constructor method.', ); configuration.recognizerFactories[type]! .initializer(newRecognizers[type]!); } _disposeRecognizers(); // only disposes the ones that where not re-used above. _recognizers = newRecognizers; } void _disposeRecognizers() { if (_recognizers != null) { for (final GestureRecognizer recognizer in _recognizers!.values) { recognizer.dispose(); } _recognizers = null; } } // ---- HitTestTarget ---- @override void handleEvent(PointerEvent event, HitTestEntry entry) { if (event is PointerDownEvent && configuration.recognizerFactories.isNotEmpty) { if (_recognizers == null) { _syncRecognizers(); } assert(_recognizers != null); for (final GestureRecognizer recognizer in _recognizers!.values) { recognizer.addPointer(event); } } } // ---- MouseTrackerAnnotation ---- @override MouseCursor get cursor => configuration.cursor; @override PointerEnterEventListener? get onEnter => configuration.onEnter; @override PointerExitEventListener? get onExit => configuration.onExit; @override bool get validForMouseTracker => true; }
packages/packages/two_dimensional_scrollables/lib/src/table_view/table.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/lib/src/table_view/table.dart", "repo_id": "packages", "token_count": 24532 }
1,044
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; // PreferredLaunchMode is hidden to prevent accidentally using it in APIs at // this layer. If it is ever needed in this file, it should be imported // separately with a prefix. import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart' hide PreferredLaunchMode; import '../url_launcher_string.dart'; import 'type_conversion.dart'; /// Passes [url] to the underlying platform for handling. /// /// [mode] support varies significantly by platform. Clients can use /// [supportsLaunchMode] to query for support, but platforms will fall back to /// other modes if the requested mode is not supported, so checking is not /// required. The default behavior of [LaunchMode.platformDefault] is up to each /// platform, and its behavior for a given platform may change over time as new /// modes are supported, so clients that want a specific mode should request it /// rather than rely on any currently observed default behavior. /// /// For web, [webOnlyWindowName] specifies a target for the launch. This /// supports the standard special link target names. For example: /// - "_blank" opens the new URL in a new tab. /// - "_self" opens the new URL in the current tab. /// Default behaviour when unset is to open the url in a new tab. /// /// Web browsers prevent launching URLs in a new tab/window, unless /// triggered by a user action (e.g. a button click). See /// [package:url_launcher_web](https://pub.dev/packages/url_launcher_web#limitations-on-the-web-platform) /// for more details. /// /// Returns true if the URL was launched successfully, otherwise either returns /// false or throws a [PlatformException] depending on the failure. Future<bool> launchUrl( Uri url, { LaunchMode mode = LaunchMode.platformDefault, WebViewConfiguration webViewConfiguration = const WebViewConfiguration(), String? webOnlyWindowName, }) async { if ((mode == LaunchMode.inAppWebView || mode == LaunchMode.inAppBrowserView) && !(url.scheme == 'https' || url.scheme == 'http')) { throw ArgumentError.value(url, 'url', 'To use an in-app web view, you must provide an http(s) URL.'); } return UrlLauncherPlatform.instance.launchUrl( url.toString(), LaunchOptions( mode: convertLaunchMode(mode), webViewConfiguration: convertConfiguration(webViewConfiguration), webOnlyWindowName: webOnlyWindowName, ), ); } /// Checks whether the specified URL can be handled by some app installed on the /// device. /// /// Returns true if it is possible to verify that there is a handler available. /// A false return value can indicate either that there is no handler available, /// or that the application does not have permission to check. For example: /// - On recent versions of Android and iOS, this will always return false /// unless the application has been configuration to allow /// querying the system for launch support. See /// [the README](https://pub.dev/packages/url_launcher#configuration) for /// details. /// - On web, this will always return false except for a few specific schemes /// that are always assumed to be supported (such as http(s)), as web pages /// are never allowed to query installed applications. Future<bool> canLaunchUrl(Uri url) async { return UrlLauncherPlatform.instance.canLaunch(url.toString()); } /// Closes the current in-app web view, if one was previously opened by /// [launchUrl]. /// /// This works only if [supportsCloseForLaunchMode] returns true for the mode /// that was used by [launchUrl]. Future<void> closeInAppWebView() async { return UrlLauncherPlatform.instance.closeWebView(); } /// Returns true if [mode] is supported by the current platform implementation. /// /// Calling [launchUrl] with an unsupported mode will fall back to a supported /// mode, so calling this method is only necessary for cases where the caller /// needs to know which mode will be used. Future<bool> supportsLaunchMode(LaunchMode mode) { return UrlLauncherPlatform.instance.supportsMode(convertLaunchMode(mode)); } /// Returns true if [closeInAppWebView] is supported for [mode] in the current /// platform implementation. /// /// If this returns false, [closeInAppWebView] will not work when launching /// URLs with [mode]. Future<bool> supportsCloseForLaunchMode(LaunchMode mode) { return UrlLauncherPlatform.instance.supportsMode(convertLaunchMode(mode)); }
packages/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart", "repo_id": "packages", "token_count": 1238 }
1,045
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v10.1.6), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.urllauncher; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.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; } /** * Configuration options for an in-app WebView. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class WebViewOptions { private @NonNull Boolean enableJavaScript; public @NonNull Boolean getEnableJavaScript() { return enableJavaScript; } public void setEnableJavaScript(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"enableJavaScript\" is null."); } this.enableJavaScript = setterArg; } private @NonNull Boolean enableDomStorage; public @NonNull Boolean getEnableDomStorage() { return enableDomStorage; } public void setEnableDomStorage(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"enableDomStorage\" is null."); } this.enableDomStorage = setterArg; } private @NonNull Map<String, String> headers; public @NonNull Map<String, String> getHeaders() { return headers; } public void setHeaders(@NonNull Map<String, String> setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"headers\" is null."); } this.headers = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ WebViewOptions() {} public static final class Builder { private @Nullable Boolean enableJavaScript; public @NonNull Builder setEnableJavaScript(@NonNull Boolean setterArg) { this.enableJavaScript = setterArg; return this; } private @Nullable Boolean enableDomStorage; public @NonNull Builder setEnableDomStorage(@NonNull Boolean setterArg) { this.enableDomStorage = setterArg; return this; } private @Nullable Map<String, String> headers; public @NonNull Builder setHeaders(@NonNull Map<String, String> setterArg) { this.headers = setterArg; return this; } public @NonNull WebViewOptions build() { WebViewOptions pigeonReturn = new WebViewOptions(); pigeonReturn.setEnableJavaScript(enableJavaScript); pigeonReturn.setEnableDomStorage(enableDomStorage); pigeonReturn.setHeaders(headers); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(3); toListResult.add(enableJavaScript); toListResult.add(enableDomStorage); toListResult.add(headers); return toListResult; } static @NonNull WebViewOptions fromList(@NonNull ArrayList<Object> list) { WebViewOptions pigeonResult = new WebViewOptions(); Object enableJavaScript = list.get(0); pigeonResult.setEnableJavaScript((Boolean) enableJavaScript); Object enableDomStorage = list.get(1); pigeonResult.setEnableDomStorage((Boolean) enableDomStorage); Object headers = list.get(2); pigeonResult.setHeaders((Map<String, String>) headers); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class BrowserOptions { private @NonNull Boolean showTitle; public @NonNull Boolean getShowTitle() { return showTitle; } public void setShowTitle(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"showTitle\" is null."); } this.showTitle = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ BrowserOptions() {} public static final class Builder { private @Nullable Boolean showTitle; public @NonNull Builder setShowTitle(@NonNull Boolean setterArg) { this.showTitle = setterArg; return this; } public @NonNull BrowserOptions build() { BrowserOptions pigeonReturn = new BrowserOptions(); pigeonReturn.setShowTitle(showTitle); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(1); toListResult.add(showTitle); return toListResult; } static @NonNull BrowserOptions fromList(@NonNull ArrayList<Object> list) { BrowserOptions pigeonResult = new BrowserOptions(); Object showTitle = list.get(0); pigeonResult.setShowTitle((Boolean) showTitle); return pigeonResult; } } private static class UrlLauncherApiCodec extends StandardMessageCodec { public static final UrlLauncherApiCodec INSTANCE = new UrlLauncherApiCodec(); private UrlLauncherApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return BrowserOptions.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 129: return WebViewOptions.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof BrowserOptions) { stream.write(128); writeValue(stream, ((BrowserOptions) value).toList()); } else if (value instanceof WebViewOptions) { stream.write(129); writeValue(stream, ((WebViewOptions) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface UrlLauncherApi { /** Returns true if the URL can definitely be launched. */ @NonNull Boolean canLaunchUrl(@NonNull String url); /** Opens the URL externally, returning true if successful. */ @NonNull Boolean launchUrl(@NonNull String url, @NonNull Map<String, String> headers); /** Opens the URL in an in-app WebView, returning true if it opens successfully. */ @NonNull Boolean openUrlInApp( @NonNull String url, @NonNull Boolean allowCustomTab, @NonNull WebViewOptions webViewOptions, @NonNull BrowserOptions browserOptions); @NonNull Boolean supportsCustomTabs(); /** Closes the view opened by [openUrlInSafariViewController]. */ void closeWebView(); /** The codec used by UrlLauncherApi. */ static @NonNull MessageCodec<Object> getCodec() { return UrlLauncherApiCodec.INSTANCE; } /** Sets up an instance of `UrlLauncherApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable UrlLauncherApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.canLaunchUrl", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String urlArg = (String) args.get(0); try { Boolean output = api.canLaunchUrl(urlArg); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.launchUrl", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String urlArg = (String) args.get(0); Map<String, String> headersArg = (Map<String, String>) args.get(1); try { Boolean output = api.launchUrl(urlArg, headersArg); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.openUrlInApp", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String urlArg = (String) args.get(0); Boolean allowCustomTabArg = (Boolean) args.get(1); WebViewOptions webViewOptionsArg = (WebViewOptions) args.get(2); BrowserOptions browserOptionsArg = (BrowserOptions) args.get(3); try { Boolean output = api.openUrlInApp( urlArg, allowCustomTabArg, webViewOptionsArg, browserOptionsArg); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.supportsCustomTabs", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { Boolean output = api.supportsCustomTabs(); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.closeWebView", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { api.closeWebView(); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } }
packages/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/Messages.java/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/Messages.java", "repo_id": "packages", "token_count": 5769 }
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. #include <flutter_linux/flutter_linux.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <memory> #include <string> #include "include/url_launcher_linux/url_launcher_plugin.h" #include "url_launcher_plugin_private.h" namespace url_launcher_plugin { namespace test { TEST(UrlLauncherPlugin, CanLaunchSuccess) { g_autoptr(FlValue) args = fl_value_new_string("https://flutter.dev"); g_autoptr(FlMethodResponse) response = can_launch(nullptr, args); ASSERT_NE(response, nullptr); ASSERT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response)); g_autoptr(FlValue) expected = fl_value_new_bool(true); EXPECT_TRUE(fl_value_equal(fl_method_success_response_get_result( FL_METHOD_SUCCESS_RESPONSE(response)), expected)); } TEST(UrlLauncherPlugin, CanLaunchFailureUnhandled) { g_autoptr(FlValue) args = fl_value_new_string("madeup:scheme"); g_autoptr(FlMethodResponse) response = can_launch(nullptr, args); ASSERT_NE(response, nullptr); ASSERT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response)); g_autoptr(FlValue) expected = fl_value_new_bool(false); EXPECT_TRUE(fl_value_equal(fl_method_success_response_get_result( FL_METHOD_SUCCESS_RESPONSE(response)), expected)); } TEST(UrlLauncherPlugin, CanLaunchFileSuccess) { g_autoptr(FlValue) args = fl_value_new_string("file:///"); g_autoptr(FlMethodResponse) response = can_launch(nullptr, args); ASSERT_NE(response, nullptr); ASSERT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response)); g_autoptr(FlValue) expected = fl_value_new_bool(true); EXPECT_TRUE(fl_value_equal(fl_method_success_response_get_result( FL_METHOD_SUCCESS_RESPONSE(response)), expected)); } TEST(UrlLauncherPlugin, CanLaunchFailureInvalidFileExtension) { g_autoptr(FlValue) args = fl_value_new_string("file:///madeup.madeupextension"); g_autoptr(FlMethodResponse) response = can_launch(nullptr, args); ASSERT_NE(response, nullptr); ASSERT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response)); g_autoptr(FlValue) expected = fl_value_new_bool(false); EXPECT_TRUE(fl_value_equal(fl_method_success_response_get_result( FL_METHOD_SUCCESS_RESPONSE(response)), expected)); } // For consistency with the established mobile implementations, // an invalid URL should return false, not an error. TEST(UrlLauncherPlugin, CanLaunchFailureInvalidUrl) { g_autoptr(FlValue) args = fl_value_new_string(""); g_autoptr(FlMethodResponse) response = can_launch(nullptr, args); ASSERT_NE(response, nullptr); ASSERT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response)); g_autoptr(FlValue) expected = fl_value_new_bool(false); EXPECT_TRUE(fl_value_equal(fl_method_success_response_get_result( FL_METHOD_SUCCESS_RESPONSE(response)), expected)); } } // namespace test } // namespace url_launcher_plugin
packages/packages/url_launcher/url_launcher_linux/linux/test/url_launcher_linux_test.cc/0
{ "file_path": "packages/packages/url_launcher/url_launcher_linux/linux/test/url_launcher_linux_test.cc", "repo_id": "packages", "token_count": 1363 }
1,047
name: url_launcher_macos description: macOS implementation of the url_launcher plugin. repository: https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher_macos issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+url_launcher%22 version: 3.1.0 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: url_launcher platforms: macos: pluginClass: UrlLauncherPlugin fileName: url_launcher_macos.dart dartPluginClass: UrlLauncherMacOS dependencies: flutter: sdk: flutter url_launcher_platform_interface: ^2.2.0 dev_dependencies: flutter_test: sdk: flutter pigeon: ^10.1.3 test: ^1.16.3 topics: - links - os-integration - url-launcher - urls
packages/packages/url_launcher/url_launcher_macos/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/pubspec.yaml", "repo_id": "packages", "token_count": 341 }
1,048
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "../FVPDisplayLink.h" #import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> /// A proxy object to act as a CADisplayLink target, to avoid retain loops, since FVPDisplayLink /// owns its CADisplayLink, but CADisplayLink retains its target. @interface FVPDisplayLinkTarget : NSObject @property(nonatomic) void (^callback)(void); /// Initializes a target object that runs the given callback when onDisplayLink: is called. - (instancetype)initWithCallback:(void (^)(void))callback; /// Method to be called when a CADisplayLink fires. - (void)onDisplayLink:(CADisplayLink *)link; @end @implementation FVPDisplayLinkTarget - (instancetype)initWithCallback:(void (^)(void))callback { self = [super init]; if (self) { _callback = callback; } return self; } - (void)onDisplayLink:(CADisplayLink *)link { self.callback(); } @end #pragma mark - @interface FVPDisplayLink () // The underlying display link implementation. @property(nonatomic) CADisplayLink *displayLink; @property(nonatomic) FVPDisplayLinkTarget *target; @end @implementation FVPDisplayLink - (instancetype)initWithRegistrar:(id<FlutterPluginRegistrar>)registrar callback:(void (^)(void))callback { self = [super init]; if (self) { _target = [[FVPDisplayLinkTarget alloc] initWithCallback:callback]; _displayLink = [CADisplayLink displayLinkWithTarget:_target selector:@selector(onDisplayLink:)]; [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; _displayLink.paused = YES; } return self; } - (void)dealloc { [_displayLink invalidate]; } - (BOOL)running { return !self.displayLink.paused; } - (void)setRunning:(BOOL)running { self.displayLink.paused = !running; } @end
packages/packages/video_player/video_player_avfoundation/darwin/Classes/ios/FVPDisplayLink.m/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/ios/FVPDisplayLink.m", "repo_id": "packages", "token_count": 662 }
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:video_player_platform_interface/video_player_platform_interface.dart'; void main() { // Store the initial instance before any tests change it. final VideoPlayerPlatform initialInstance = VideoPlayerPlatform.instance; test('default implementation init throws unimplemented', () async { await expectLater(() => initialInstance.init(), throwsUnimplementedError); }); test('default implementation setWebOptions throws unimplemented', () async { await expectLater( () => initialInstance.setWebOptions( 1, const VideoPlayerWebOptions(), ), throwsUnimplementedError, ); }); }
packages/packages/video_player/video_player_platform_interface/test/video_player_platform_interface_test.dart/0
{ "file_path": "packages/packages/video_player/video_player_platform_interface/test/video_player_platform_interface_test.dart", "repo_id": "packages", "token_count": 252 }
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. /// A single benchmark score value collected from the benchmark. class BenchmarkScore { /// Creates a benchmark score. /// /// [metric] and [value] must not be null. BenchmarkScore({ required this.metric, required this.value, this.delta, }); /// Deserializes a JSON object to create a [BenchmarkScore] object. factory BenchmarkScore.parse(Map<String, Object?> json) { final String metric = json[metricKey]! as String; final double value = (json[valueKey]! as num).toDouble(); final num? delta = json[deltaKey] as num?; return BenchmarkScore(metric: metric, value: value, delta: delta); } /// The key for the value [metric] in the [BenchmarkScore] JSON /// representation. static const String metricKey = 'metric'; /// The key for the value [value] in the [BenchmarkScore] JSON representation. static const String valueKey = 'value'; /// The key for the value [delta] in the [BenchmarkScore] JSON representation. static const String deltaKey = 'delta'; /// The name of the metric that this score is categorized under. /// /// Scores collected over time under the same name can be visualized as a /// timeline. final String metric; /// The result of measuring a particular metric in this benchmark run. final num value; /// Optional delta value describing the difference between this metric's score /// and the score of a matching metric from another [BenchmarkResults]. /// /// This value may be assigned by the [computeDelta] analysis method. final num? delta; /// Serializes the benchmark metric to a JSON object. Map<String, Object?> toJson() { return <String, Object?>{ metricKey: metric, valueKey: value, if (delta != null) deltaKey: delta, }; } } /// The result of running a benchmark. class BenchmarkResults { /// Constructs a result containing scores from a single run benchmark run. BenchmarkResults(this.scores); /// Deserializes a JSON object to create a [BenchmarkResults] object. factory BenchmarkResults.parse(Map<String, Object?> json) { final Map<String, List<BenchmarkScore>> results = <String, List<BenchmarkScore>>{}; for (final String key in json.keys) { final List<BenchmarkScore> scores = (json[key]! as List<Object?>) .cast<Map<String, Object?>>() .map(BenchmarkScore.parse) .toList(growable: false); results[key] = scores; } return BenchmarkResults(results); } /// Scores collected in a benchmark run. final Map<String, List<BenchmarkScore>> scores; /// Serializes benchmark metrics to JSON. Map<String, List<Map<String, Object?>>> toJson() { return scores.map<String, List<Map<String, Object?>>>( (String benchmarkName, List<BenchmarkScore> scores) { return MapEntry<String, List<Map<String, Object?>>>( benchmarkName, scores.map((BenchmarkScore score) => score.toJson()).toList(), ); }); } }
packages/packages/web_benchmarks/lib/src/benchmark_result.dart/0
{ "file_path": "packages/packages/web_benchmarks/lib/src/benchmark_result.dart", "repo_id": "packages", "token_count": 990 }
1,051
include: ../../../../analysis_options.yaml linter: rules: # This is test code. Do not enforce docs. package_api_docs: false public_member_api_docs: false
packages/packages/web_benchmarks/testing/test_app/analysis_options.yaml/0
{ "file_path": "packages/packages/web_benchmarks/testing/test_app/analysis_options.yaml", "repo_id": "packages", "token_count": 62 }
1,052
## 4.7.0 * Adds support to track scroll position changes. * Updates minimum supported SDK version to Flutter 3.16.6/Dart 3.2.3. ## 4.6.0 * Adds support for custom handling of JavaScript dialogs. See `WebViewController.setOnJavaScriptAlertDialog`, `WebViewController.setOnJavaScriptConfirmDialog` and `WebViewController.setOnJavaScriptTextInputDialog`. * Updates minimum Dart version to 3.2.3 and minimum Flutter version to 3.16.6. ## 4.5.0 * Adds support for HTTP basic authentication. See `NavigationDelegate(onReceivedHttpAuthRequest)`. * Updates support matrix in README to indicate that iOS 11 is no longer supported. * Clients on versions of Flutter that still support iOS 11 can continue to use this package with iOS 11, but will not receive any further updates to the iOS implementation. ## 4.4.4 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 4.4.3 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 4.4.2 * Fixes `use_build_context_synchronously` lint violations in the example app. ## 4.4.1 * Exposes `JavaScriptLogLevel` from platform interface. ## 4.4.0 * Adds support to register a callback to receive JavaScript console messages. See `WebViewController.setOnConsoleMessage`. ## 4.3.0 * Adds support to retrieve the user agent. See `WebViewController.getUserAgent`. ## 4.2.4 * Adds pub topics to package metadata. ## 4.2.3 * Fixes the code sample in the dartdocs for `WebViewController.addJavaScriptChannel`. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 4.2.2 * Fixes documentation typo. ## 4.2.1 * Removes obsolete null checks on non-nullable values. ## 4.2.0 * Adds support to receive permission requests. See `WebViewController(onPermissionRequest)`. ## 4.1.0 * Adds support to track URL changes. See `NavigationDelegate(onUrlChange)`. * Updates minimum Flutter version to 3.3. * Fixes common typos in tests and documentation. * Fixes documentation for `WebViewController` and `WebViewCookieManager`. ## 4.0.7 * Updates the README with the migration of `WebView.initialCookies` and Hybrid Composition on Android. ## 4.0.6 * Updates iOS minimum version in README. ## 4.0.5 * Updates links for the merge of flutter/plugins into flutter/packages. ## 4.0.4 * Adds examples of accessing platform-specific features for each class. ## 4.0.3 * Updates example code for `use_build_context_synchronously` lint. ## 4.0.2 * Updates code for stricter lint checks. ## 4.0.1 * Exposes `WebResourceErrorType` from platform interface. ## 4.0.0 * **BREAKING CHANGE** Updates implementation to use the `2.0.0` release of `webview_flutter_platform_interface`. See `Usage` section in the README for updated usage. See `Migrating from 3.0 to 4.0` section in the README for details on migrating to this version. * Updates minimum Flutter version to 3.0.0. * Updates code for new analysis options. * Updates references to the obsolete master branch. ## 3.0.4 * Minor fixes for new analysis options. ## 3.0.3 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 3.0.2 * Migrates deprecated `Scaffold.showSnackBar` to `ScaffoldMessenger` in example app. * Adds OS version support information to README. ## 3.0.1 * Removes a duplicate Android-specific integration test. * Fixes an integration test race condition. * Fixes comments (accidentally mixed // with ///). ## 3.0.0 * **BREAKING CHANGE**: On Android, hybrid composition (SurfaceAndroidWebView) is now the default. The previous default, virtual display, can be specified with `WebView.platform = AndroidWebView()` ## 2.8.0 * Adds support for the `loadFlutterAsset` method. ## 2.7.0 * Adds `setCookie` to CookieManager. * CreationParams now supports setting `initialCookies`. ## 2.6.0 * Adds support for the `loadRequest` method. ## 2.5.0 * Adds an option to set the background color of the webview. ## 2.4.0 * Adds support for the `loadFile` and `loadHtmlString` methods. * Updates example app Android compileSdkVersion to 31. * Integration test fixes. * Updates code for new analysis options. ## 2.3.1 * Add iOS-specific note to set `JavascriptMode.unrestricted` in order to set `zoomEnabled: false`. ## 2.3.0 * Add ability to enable/disable zoom functionality. ## 2.2.0 * Added `runJavascript` and `runJavascriptForResult` to supersede `evaluateJavascript`. * Deprecated `evaluateJavascript`. ## 2.1.2 * Fix typos in the README. ## 2.1.1 * Fixed `_CastError` that was thrown when running the example App. ## 2.1.0 * Migrated to fully federated architecture. ## 2.0.14 * Update minimum Flutter SDK to 2.5 and iOS deployment target to 9.0. ## 2.0.13 * Send URL of File to download to the NavigationDelegate on Android just like it is already done on iOS. * Updated Android lint settings. ## 2.0.12 * Improved the documentation on using the different Android Platform View modes. * So that Android and iOS behave the same, `onWebResourceError` is now only called for the main page. ## 2.0.11 * Remove references to the Android V1 embedding. ## 2.0.10 * Fix keyboard issues link in the README. ## 2.0.9 * Add iOS UI integration test target. * Suppress deprecation warning for iOS APIs deprecated in iOS 9. ## 2.0.8 * Migrate maven repository from jcenter to mavenCentral. ## 2.0.7 * Republished 2.0.6 with Flutter 2.2 to avoid https://github.com/dart-lang/pub/issues/3001 ## 2.0.6 * WebView requires at least Android 19 if you are using hybrid composition ([flutter/issues/59894](https://github.com/flutter/flutter/issues/59894)). ## 2.0.5 * Example app observes `uiMode`, so the WebView isn't reattached when the UI mode changes. (e.g. switching to Dark mode). ## 2.0.4 * Fix a bug where `allowsInlineMediaPlayback` is not respected on iOS. ## 2.0.3 * Fixes bug where scroll bars on the Android non-hybrid WebView are rendered on the wrong side of the screen. ## 2.0.2 * Fixes bug where text fields are hidden behind the keyboard when hybrid composition is used [flutter/issues/75667](https://github.com/flutter/flutter/issues/75667). ## 2.0.1 * Run CocoaPods iOS tests in RunnerUITests target ## 2.0.0 * Migration to null-safety. * Added support for progress tracking. * Add section to the wiki explaining how to use Material components. * Update integration test to workaround an iOS 14 issue with `evaluateJavascript`. * Fix `onWebResourceError` on iOS. * Fix outdated links across a number of markdown files ([#3276](https://github.com/flutter/plugins/pull/3276)) * Added `allowsInlineMediaPlayback` property. ## 1.0.8 * Update Flutter SDK constraint. ## 1.0.7 * Minor documentation update to indicate known issue on iOS 13.4 and 13.5. * See: https://github.com/flutter/flutter/issues/53490 ## 1.0.6 * Invoke the WebView.onWebResourceError on iOS when the webview content process crashes. ## 1.0.5 * Fix example in the readme. ## 1.0.4 * Suppress the `deprecated_member_use` warning in the example app for `ScaffoldMessenger.showSnackBar`. ## 1.0.3 * Update android compileSdkVersion to 29. ## 1.0.2 * Android Code Inspection and Clean up. ## 1.0.1 * Add documentation for `WebViewPlatformCreatedCallback`. ## 1.0.0 - Out of developer preview 🎉. * Bumped the minimal Flutter SDK to 1.22 where platform views are out of developer preview, and performing better on iOS. Flutter 1.22 no longer requires adding the `io.flutter.embedded_views_preview` flag to `Info.plist`. * Added support for Hybrid Composition on Android (see opt-in instructions in [README](https://github.com/flutter/plugins/blob/main/packages/webview_flutter/README.md#android)) * Lowered the required Android API to 19 (was previously 20): [#23728](https://github.com/flutter/flutter/issues/23728). * Fixed the following issues: * 🎹 Keyboard: [#41089](https://github.com/flutter/flutter/issues/41089), [#36478](https://github.com/flutter/flutter/issues/36478), [#51254](https://github.com/flutter/flutter/issues/51254), [#50716](https://github.com/flutter/flutter/issues/50716), [#55724](https://github.com/flutter/flutter/issues/55724), [#56513](https://github.com/flutter/flutter/issues/56513), [#56515](https://github.com/flutter/flutter/issues/56515), [#61085](https://github.com/flutter/flutter/issues/61085), [#62205](https://github.com/flutter/flutter/issues/62205), [#62547](https://github.com/flutter/flutter/issues/62547), [#58943](https://github.com/flutter/flutter/issues/58943), [#56361](https://github.com/flutter/flutter/issues/56361), [#56361](https://github.com/flutter/flutter/issues/42902), [#40716](https://github.com/flutter/flutter/issues/40716), [#37989](https://github.com/flutter/flutter/issues/37989), [#27924](https://github.com/flutter/flutter/issues/27924). * ♿️ Accessibility: [#50716](https://github.com/flutter/flutter/issues/50716). * ⚡️ Performance: [#61280](https://github.com/flutter/flutter/issues/61280), [#31243](https://github.com/flutter/flutter/issues/31243), [#52211](https://github.com/flutter/flutter/issues/52211). * 📹 Video: [#5191](https://github.com/flutter/flutter/issues/5191). ## 0.3.24 * Keep handling deprecated Android v1 classes for backward compatibility. ## 0.3.23 * Handle WebView multi-window support. ## 0.3.22+2 * Update package:e2e reference to use the local version in the flutter/plugins repository. ## 0.3.22+1 * Update the `setAndGetScrollPosition` to use hard coded values and add a `pumpAndSettle` call. ## 0.3.22 * Add support for passing a failing url. ## 0.3.21 * Enable programmatic scrolling using Android's WebView.scrollTo & iOS WKWebView.scrollView.contentOffset. ## 0.3.20+2 * Fix CocoaPods podspec lint warnings. ## 0.3.20+1 * OCMock module import -> #import, unit tests compile generated as library. * Fix select drop down crash on old Android tablets (https://github.com/flutter/flutter/issues/54164). ## 0.3.20 * Added support for receiving web resource loading errors. See `WebView.onWebResourceError`. ## 0.3.19+10 * Replace deprecated `getFlutterEngine` call on Android. ## 0.3.19+9 * Remove example app's iOS workspace settings. ## 0.3.19+8 * Make the pedantic dev_dependency explicit. ## 0.3.19+7 * Remove the Flutter SDK constraint upper bound. ## 0.3.19+6 * Enable opening links that target the "_blank" window (links open in same window). ## 0.3.19+5 * On iOS, always keep contentInsets of the WebView to be 0. * Fix XCTest case to follow XCTest naming convention. ## 0.3.19+4 * On iOS, fix the scroll view content inset is automatically adjusted. After the fix, the content position of the WebView is customizable by Flutter. * Fix an iOS 13 bug where the scroll indicator shows at random location. ## 0.3.19+3 * Setup XCTests. ## 0.3.19+2 * Migrate from deprecated BinaryMessages to ServicesBinding.instance.defaultBinaryMessenger. ## 0.3.19+1 * Raise min Flutter SDK requirement to the latest stable. v2 embedding apps no longer need to special case their Flutter SDK requirement like they have since v0.3.15+3. ## 0.3.19 * Add setting for iOS to allow gesture based navigation. ## 0.3.18+1 * Be explicit that keyboard is not ready for production in README.md. ## 0.3.18 * Add support for onPageStarted event. * Remove the deprecated `author:` field from pubspec.yaml * Migrate to the new pubspec platforms manifest. * Require Flutter SDK 1.10.0 or greater. ## 0.3.17 * Fix pedantic lint errors. Added missing documentation and awaited some futures in tests and the example app. ## 0.3.16 * Add support for async NavigationDelegates. Synchronous NavigationDelegates should still continue to function without any change in behavior. ## 0.3.15+3 * Re-land support for the v2 Android embedding. This correctly sets the minimum SDK to the latest stable and avoid any compile errors. *WARNING:* the V2 embedding itself still requires the current Flutter master channel (flutter/flutter@1d4d63a) for text input to work properly on all Android versions. ## 0.3.15+2 * Remove AndroidX warnings. ## 0.3.15+1 * Revert the prior embedding support add since it requires an API that hasn't rolled to stable. ## 0.3.15 * Add support for the v2 Android embedding. This shouldn't affect existing functionality. Plugin authors who use the V2 embedding can now register the plugin and expect that it correctly responds to app lifecycle changes. ## 0.3.14+2 * Define clang module for iOS. ## 0.3.14+1 * Allow underscores anywhere for Javascript Channel name. ## 0.3.14 * Added a getTitle getter to WebViewController. ## 0.3.13 * Add an optional `userAgent` property to set a custom User Agent. ## 0.3.12+1 * Temporarily revert getTitle (doing this as a patch bump shortly after publishing). ## 0.3.12 * Added a getTitle getter to WebViewController. ## 0.3.11+6 * Calling destroy on Android webview when flutter webview is getting disposed. ## 0.3.11+5 * Reduce compiler warnings regarding iOS9 compatibility by moving a single method back into a `@available` block. ## 0.3.11+4 * Removed noisy log messages on iOS. ## 0.3.11+3 * Apply the display listeners workaround that was shipped in 0.3.11+1 on all Android versions prior to P. ## 0.3.11+2 * Add fix for input connection being dropped after a screen resize on certain Android devices. ## 0.3.11+1 * Work around a bug in old Android WebView versions that was causing a crash when resizing the webview on old devices. ## 0.3.11 * Add an initialAutoMediaPlaybackPolicy setting for controlling how auto media playback is restricted. ## 0.3.10+5 * Add dependency on `androidx.annotation:annotation:1.0.0`. ## 0.3.10+4 * Add keyboard text to README. ## 0.3.10+3 * Don't log an unknown setting key error for 'debuggingEnabled' on iOS. ## 0.3.10+2 * Fix InputConnection being lost when combined with route transitions. ## 0.3.10+1 * Add support for simultaenous Flutter `TextInput` and WebView text fields. ## 0.3.10 * Add partial WebView keyboard support for Android versions prior to N. Support for UIs that also have Flutter `TextInput` fields is still pending. This basic support currently only works with Flutter `master`. The keyboard will still appear when it previously did not when run with older versions of Flutter. But if the WebView is resized while showing the keyboard the text field will need to be focused multiple times for any input to be registered. ## 0.3.9+2 * Update Dart code to conform to current Dart formatter. ## 0.3.9+1 * Add missing template type parameter to `invokeMethod` calls. * Bump minimum Flutter version to 1.5.0. * Replace invokeMethod with invokeMapMethod wherever necessary. ## 0.3.9 * Allow external packages to provide webview implementations for new platforms. ## 0.3.8+1 * Suppress deprecation warning for BinaryMessages. See: https://github.com/flutter/flutter/issues/33446 ## 0.3.8 * Add `debuggingEnabled` property. ## 0.3.7+1 * Fix an issue where JavaScriptChannel messages weren't sent from the platform thread on Android. ## 0.3.7 * Fix loadUrlWithHeaders flaky test. ## 0.3.6+1 * Remove un-used method params in webview\_flutter ## 0.3.6 * Add an optional `headers` field to the controller. ## 0.3.5+5 * Fixed error in documentation of `javascriptChannels`. ## 0.3.5+4 * Fix bugs in the example app by updating it to use a `StatefulWidget`. ## 0.3.5+3 * Make sure to post javascript channel messages from the platform thread. ## 0.3.5+2 * Fix crash from `NavigationDelegate` on later versions of Android. ## 0.3.5+1 * Fix a bug where updates to onPageFinished were ignored. ## 0.3.5 * Added an onPageFinished callback. ## 0.3.4 * Support specifying navigation delegates that can prevent navigations from being executed. ## 0.3.3+2 * Exclude LongPress handler from semantics tree since it does nothing. ## 0.3.3+1 * Fixed a memory leak on Android - the WebView was not properly disposed. ## 0.3.3 * Add clearCache method to WebView controller. ## 0.3.2+1 * Log a more detailed warning at build time about the previous AndroidX migration. ## 0.3.2 * Added CookieManager to interface with WebView cookies. Currently has the ability to clear cookies. ## 0.3.1 * Added JavaScript channels to facilitate message passing from JavaScript code running inside the WebView to the Flutter app's Dart code. ## 0.3.0 * **Breaking change**. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to [also migrate](https://developer.android.com/jetpack/androidx/migrate) if they're using the original support library. ## 0.2.0 * Added a evaluateJavascript method to WebView controller. * (BREAKING CHANGE) Renamed the `JavaScriptMode` enum to `JavascriptMode`, and the WebView `javasScriptMode` parameter to `javascriptMode`. ## 0.1.2 * Added a reload method to the WebView controller. ## 0.1.1 * Added a `currentUrl` accessor for the WebView controller to look up what URL is being displayed. ## 0.1.0+1 * Fix null crash when initialUrl is unset on iOS. ## 0.1.0 * Add goBack, goForward, canGoBack, and canGoForward methods to the WebView controller. ## 0.0.1+1 * Fix case for "FLTWebViewFlutterPlugin" (iOS was failing to buld on case-sensitive file systems). ## 0.0.1 * Initial release.
packages/packages/webview_flutter/webview_flutter/CHANGELOG.md/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter/CHANGELOG.md", "repo_id": "packages", "token_count": 5504 }
1,053
rootProject.name = 'webview_flutter'
packages/packages/webview_flutter/webview_flutter_android/android/settings.gradle/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/settings.gradle", "repo_id": "packages", "token_count": 13 }
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. package io.flutter.plugins.webviewflutter; import android.webkit.HttpAuthHandler; import androidx.annotation.NonNull; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.HttpAuthHandlerHostApi; import java.util.Objects; /** * Host api implementation for {@link HttpAuthHandler}. * * <p>Handles creating {@link HttpAuthHandler}s that intercommunicate with a paired Dart object. */ public class HttpAuthHandlerHostApiImpl implements HttpAuthHandlerHostApi { // To ease adding additional methods, this value is added prematurely. @SuppressWarnings({"unused", "FieldCanBeLocal"}) private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; /** * Constructs a {@link HttpAuthHandlerHostApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public HttpAuthHandlerHostApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; } @NonNull @Override public Boolean useHttpAuthUsernamePassword(@NonNull Long instanceId) { return getHttpAuthHandlerInstance(instanceId).useHttpAuthUsernamePassword(); } @Override public void cancel(@NonNull Long instanceId) { getHttpAuthHandlerInstance(instanceId).cancel(); } @Override public void proceed( @NonNull Long instanceId, @NonNull String username, @NonNull String password) { getHttpAuthHandlerInstance(instanceId).proceed(username, password); } private HttpAuthHandler getHttpAuthHandlerInstance(@NonNull Long instanceId) { return Objects.requireNonNull(instanceManager.getInstance(instanceId)); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/HttpAuthHandlerHostApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/HttpAuthHandlerHostApiImpl.java", "repo_id": "packages", "token_count": 579 }
1,055
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebViewFlutterApi; import java.util.Objects; /** * Flutter API implementation for `WebView`. * * <p>This class may handle adding native instances that are attached to a Dart instance or passing * arguments of callbacks methods to a Dart instance. */ public class WebViewFlutterApiImpl { // To ease adding additional methods, this value is added prematurely. @SuppressWarnings({"unused", "FieldCanBeLocal"}) private final BinaryMessenger binaryMessenger; private final InstanceManager instanceManager; private WebViewFlutterApi api; /** * Constructs a {@link WebViewFlutterApiImpl}. * * @param binaryMessenger used to communicate with Dart over asynchronous messages * @param instanceManager maintains instances stored to communicate with attached Dart objects */ public WebViewFlutterApiImpl( @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { this.binaryMessenger = binaryMessenger; this.instanceManager = instanceManager; api = new WebViewFlutterApi(binaryMessenger); } /** * Stores the `WebView` instance and notifies Dart to create and store a new `WebView` instance * that is attached to this one. If `instance` has already been added, this method does nothing. */ public void create(@NonNull WebView instance, @NonNull WebViewFlutterApi.Reply<Void> callback) { if (!instanceManager.containsInstance(instance)) { api.create(instanceManager.addHostCreatedInstance(instance), callback); } } /** * Sets the Flutter API used to send messages to Dart. * * <p>This is only visible for testing. */ @VisibleForTesting void setApi(@NonNull WebViewFlutterApi api) { this.api = api; } public void onScrollChanged( @NonNull WebView instance, @NonNull Long left, @NonNull Long top, @NonNull Long oldLeft, @NonNull Long oldTop, @NonNull WebViewFlutterApi.Reply<Void> callback) { api.onScrollChanged( Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(instance)), left, top, oldLeft, oldTop, callback); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterApiImpl.java", "repo_id": "packages", "token_count": 821 }
1,056
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.res.AssetManager; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; @SuppressWarnings("deprecation") public class RegistrarFlutterAssetManagerTest { @Mock AssetManager mockAssetManager; @Mock io.flutter.plugin.common.PluginRegistry.Registrar mockRegistrar; io.flutter.plugins.webviewflutter.FlutterAssetManager.RegistrarFlutterAssetManager testRegistrarFlutterAssetManager; @Before public void setUp() { mockAssetManager = mock(AssetManager.class); mockRegistrar = mock(io.flutter.plugin.common.PluginRegistry.Registrar.class); testRegistrarFlutterAssetManager = new io.flutter.plugins.webviewflutter.FlutterAssetManager.RegistrarFlutterAssetManager( mockAssetManager, mockRegistrar); } @Test public void list() { try { when(mockAssetManager.list("test/path")) .thenReturn(new String[] {"index.html", "styles.css"}); String[] actualFilePaths = testRegistrarFlutterAssetManager.list("test/path"); verify(mockAssetManager).list("test/path"); assertArrayEquals(new String[] {"index.html", "styles.css"}, actualFilePaths); } catch (IOException ex) { fail(); } } @Test public void registrar_getAssetFilePathByName() { testRegistrarFlutterAssetManager.getAssetFilePathByName("sample_movie.mp4"); verify(mockRegistrar).lookupKeyForAsset("sample_movie.mp4"); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/RegistrarFlutterAssetManagerTest.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/RegistrarFlutterAssetManagerTest.java", "repo_id": "packages", "token_count": 656 }
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:ui'; import 'package:flutter/services.dart' show BinaryMessenger, Uint8List; import 'android_webview.dart'; import 'android_webview.g.dart'; import 'instance_manager.dart'; export 'android_webview.g.dart' show ConsoleMessage, ConsoleMessageLevel, FileChooserMode; /// Converts [WebResourceRequestData] to [WebResourceRequest] WebResourceRequest _toWebResourceRequest(WebResourceRequestData data) { return WebResourceRequest( url: data.url, isForMainFrame: data.isForMainFrame, isRedirect: data.isRedirect, hasGesture: data.hasGesture, method: data.method, requestHeaders: data.requestHeaders.cast<String, String>(), ); } /// Converts [WebResourceResponseData] to [WebResourceResponse] WebResourceResponse _toWebResourceResponse(WebResourceResponseData data) { return WebResourceResponse( statusCode: data.statusCode, ); } /// Converts [WebResourceErrorData] to [WebResourceError]. WebResourceError _toWebResourceError(WebResourceErrorData data) { return WebResourceError( errorCode: data.errorCode, description: data.description, ); } /// Handles initialization of Flutter APIs for Android WebView. class AndroidWebViewFlutterApis { /// Creates a [AndroidWebViewFlutterApis]. AndroidWebViewFlutterApis({ JavaObjectFlutterApiImpl? javaObjectFlutterApi, DownloadListenerFlutterApiImpl? downloadListenerFlutterApi, WebViewClientFlutterApiImpl? webViewClientFlutterApi, WebChromeClientFlutterApiImpl? webChromeClientFlutterApi, JavaScriptChannelFlutterApiImpl? javaScriptChannelFlutterApi, FileChooserParamsFlutterApiImpl? fileChooserParamsFlutterApi, GeolocationPermissionsCallbackFlutterApiImpl? geolocationPermissionsCallbackFlutterApi, WebViewFlutterApiImpl? webViewFlutterApi, PermissionRequestFlutterApiImpl? permissionRequestFlutterApi, CustomViewCallbackFlutterApiImpl? customViewCallbackFlutterApi, ViewFlutterApiImpl? viewFlutterApi, HttpAuthHandlerFlutterApiImpl? httpAuthHandlerFlutterApi, }) { this.javaObjectFlutterApi = javaObjectFlutterApi ?? JavaObjectFlutterApiImpl(); this.downloadListenerFlutterApi = downloadListenerFlutterApi ?? DownloadListenerFlutterApiImpl(); this.webViewClientFlutterApi = webViewClientFlutterApi ?? WebViewClientFlutterApiImpl(); this.webChromeClientFlutterApi = webChromeClientFlutterApi ?? WebChromeClientFlutterApiImpl(); this.javaScriptChannelFlutterApi = javaScriptChannelFlutterApi ?? JavaScriptChannelFlutterApiImpl(); this.fileChooserParamsFlutterApi = fileChooserParamsFlutterApi ?? FileChooserParamsFlutterApiImpl(); this.geolocationPermissionsCallbackFlutterApi = geolocationPermissionsCallbackFlutterApi ?? GeolocationPermissionsCallbackFlutterApiImpl(); this.webViewFlutterApi = webViewFlutterApi ?? WebViewFlutterApiImpl(); this.permissionRequestFlutterApi = permissionRequestFlutterApi ?? PermissionRequestFlutterApiImpl(); this.customViewCallbackFlutterApi = customViewCallbackFlutterApi ?? CustomViewCallbackFlutterApiImpl(); this.viewFlutterApi = viewFlutterApi ?? ViewFlutterApiImpl(); this.httpAuthHandlerFlutterApi = httpAuthHandlerFlutterApi ?? HttpAuthHandlerFlutterApiImpl(); } static bool _haveBeenSetUp = false; /// Mutable instance containing all Flutter Apis for Android WebView. /// /// This should only be changed for testing purposes. static AndroidWebViewFlutterApis instance = AndroidWebViewFlutterApis(); /// Handles callbacks methods for the native Java Object class. late final JavaObjectFlutterApi javaObjectFlutterApi; /// Flutter Api for [DownloadListener]. late final DownloadListenerFlutterApiImpl downloadListenerFlutterApi; /// Flutter Api for [WebViewClient]. late final WebViewClientFlutterApiImpl webViewClientFlutterApi; /// Flutter Api for [WebChromeClient]. late final WebChromeClientFlutterApiImpl webChromeClientFlutterApi; /// Flutter Api for [JavaScriptChannel]. late final JavaScriptChannelFlutterApiImpl javaScriptChannelFlutterApi; /// Flutter Api for [FileChooserParams]. late final FileChooserParamsFlutterApiImpl fileChooserParamsFlutterApi; /// Flutter Api for [GeolocationPermissionsCallback]. late final GeolocationPermissionsCallbackFlutterApiImpl geolocationPermissionsCallbackFlutterApi; /// Flutter Api for [WebView]. late final WebViewFlutterApiImpl webViewFlutterApi; /// Flutter Api for [PermissionRequest]. late final PermissionRequestFlutterApiImpl permissionRequestFlutterApi; /// Flutter Api for [CustomViewCallback]. late final CustomViewCallbackFlutterApiImpl customViewCallbackFlutterApi; /// Flutter Api for [View]. late final ViewFlutterApiImpl viewFlutterApi; /// Flutter Api for [HttpAuthHandler]. late final HttpAuthHandlerFlutterApiImpl httpAuthHandlerFlutterApi; /// Ensures all the Flutter APIs have been setup to receive calls from native code. void ensureSetUp() { if (!_haveBeenSetUp) { JavaObjectFlutterApi.setup(javaObjectFlutterApi); DownloadListenerFlutterApi.setup(downloadListenerFlutterApi); WebViewClientFlutterApi.setup(webViewClientFlutterApi); WebChromeClientFlutterApi.setup(webChromeClientFlutterApi); JavaScriptChannelFlutterApi.setup(javaScriptChannelFlutterApi); FileChooserParamsFlutterApi.setup(fileChooserParamsFlutterApi); GeolocationPermissionsCallbackFlutterApi.setup( geolocationPermissionsCallbackFlutterApi); WebViewFlutterApi.setup(webViewFlutterApi); PermissionRequestFlutterApi.setup(permissionRequestFlutterApi); CustomViewCallbackFlutterApi.setup(customViewCallbackFlutterApi); ViewFlutterApi.setup(viewFlutterApi); HttpAuthHandlerFlutterApi.setup(httpAuthHandlerFlutterApi); _haveBeenSetUp = true; } } } /// Handles methods calls to the native Java Object class. class JavaObjectHostApiImpl extends JavaObjectHostApi { /// Constructs a [JavaObjectHostApiImpl]. JavaObjectHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// 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; } /// Handles callbacks methods for the native Java Object class. class JavaObjectFlutterApiImpl implements JavaObjectFlutterApi { /// Constructs a [JavaObjectFlutterApiImpl]. JavaObjectFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; @override void dispose(int identifier) { instanceManager.remove(identifier); } } /// Host api implementation for [WebView]. class WebViewHostApiImpl extends WebViewHostApi { /// Constructs a [WebViewHostApiImpl]. WebViewHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebView instance) { return create(instanceManager.addDartCreatedInstance(instance)); } /// Helper method to convert the instances ids to objects. Future<void> loadDataFromInstance( WebView instance, String data, String? mimeType, String? encoding, ) { return loadData( instanceManager.getIdentifier(instance)!, data, mimeType, encoding, ); } /// Helper method to convert instances ids to objects. Future<void> loadDataWithBaseUrlFromInstance( WebView instance, String? baseUrl, String data, String? mimeType, String? encoding, String? historyUrl, ) { return loadDataWithBaseUrl( instanceManager.getIdentifier(instance)!, baseUrl, data, mimeType, encoding, historyUrl, ); } /// Helper method to convert instances ids to objects. Future<void> loadUrlFromInstance( WebView instance, String url, Map<String, String> headers, ) { return loadUrl(instanceManager.getIdentifier(instance)!, url, headers); } /// Helper method to convert instances ids to objects. Future<void> postUrlFromInstance( WebView instance, String url, Uint8List data, ) { return postUrl(instanceManager.getIdentifier(instance)!, url, data); } /// Helper method to convert instances ids to objects. Future<String?> getUrlFromInstance(WebView instance) { return getUrl(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<bool> canGoBackFromInstance(WebView instance) { return canGoBack(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<bool> canGoForwardFromInstance(WebView instance) { return canGoForward(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> goBackFromInstance(WebView instance) { return goBack(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> goForwardFromInstance(WebView instance) { return goForward(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> reloadFromInstance(WebView instance) { return reload(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> clearCacheFromInstance(WebView instance, bool includeDiskFiles) { return clearCache( instanceManager.getIdentifier(instance)!, includeDiskFiles, ); } /// Helper method to convert instances ids to objects. Future<String?> evaluateJavascriptFromInstance( WebView instance, String javascriptString, ) { return evaluateJavascript( instanceManager.getIdentifier(instance)!, javascriptString, ); } /// Helper method to convert instances ids to objects. Future<String?> getTitleFromInstance(WebView instance) { return getTitle(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<void> scrollToFromInstance(WebView instance, int x, int y) { return scrollTo(instanceManager.getIdentifier(instance)!, x, y); } /// Helper method to convert instances ids to objects. Future<void> scrollByFromInstance(WebView instance, int x, int y) { return scrollBy(instanceManager.getIdentifier(instance)!, x, y); } /// Helper method to convert instances ids to objects. Future<int> getScrollXFromInstance(WebView instance) { return getScrollX(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<int> getScrollYFromInstance(WebView instance) { return getScrollY(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instances ids to objects. Future<Offset> getScrollPositionFromInstance(WebView instance) async { final WebViewPoint position = await getScrollPosition(instanceManager.getIdentifier(instance)!); return Offset(position.x.toDouble(), position.y.toDouble()); } /// Helper method to convert instances ids to objects. Future<void> setWebViewClientFromInstance( WebView instance, WebViewClient webViewClient, ) { return setWebViewClient( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(webViewClient)!, ); } /// Helper method to convert instances ids to objects. Future<void> addJavaScriptChannelFromInstance( WebView instance, JavaScriptChannel javaScriptChannel, ) { return addJavaScriptChannel( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(javaScriptChannel)!, ); } /// Helper method to convert instances ids to objects. Future<void> removeJavaScriptChannelFromInstance( WebView instance, JavaScriptChannel javaScriptChannel, ) { return removeJavaScriptChannel( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(javaScriptChannel)!, ); } /// Helper method to convert instances ids to objects. Future<void> setDownloadListenerFromInstance( WebView instance, DownloadListener? listener, ) { return setDownloadListener( instanceManager.getIdentifier(instance)!, listener != null ? instanceManager.getIdentifier(listener) : null, ); } /// Helper method to convert instances ids to objects. Future<void> setWebChromeClientFromInstance( WebView instance, WebChromeClient? client, ) { return setWebChromeClient( instanceManager.getIdentifier(instance)!, client != null ? instanceManager.getIdentifier(client) : null, ); } /// Helper method to convert instances ids to objects. Future<void> setBackgroundColorFromInstance(WebView instance, int color) { return setBackgroundColor(instanceManager.getIdentifier(instance)!, color); } } /// Flutter API implementation for [WebView]. /// /// 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 WebViewFlutterApiImpl implements WebViewFlutterApi { /// Constructs a [WebViewFlutterApiImpl]. WebViewFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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(WebView.detached(), identifier); } @override void onScrollChanged( int webViewInstanceId, int left, int top, int oldLeft, int oldTop) { final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); webViewInstance!.onScrollChanged?.call(left, top, oldLeft, oldTop); } } /// Host api implementation for [WebSettings]. class WebSettingsHostApiImpl extends WebSettingsHostApi { /// Constructs a [WebSettingsHostApiImpl]. WebSettingsHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebSettings instance, WebView webView) { return create( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(webView)!, ); } /// Helper method to convert instances ids to objects. Future<void> setDomStorageEnabledFromInstance( WebSettings instance, bool flag, ) { return setDomStorageEnabled(instanceManager.getIdentifier(instance)!, flag); } /// Helper method to convert instances ids to objects. Future<void> setJavaScriptCanOpenWindowsAutomaticallyFromInstance( WebSettings instance, bool flag, ) { return setJavaScriptCanOpenWindowsAutomatically( instanceManager.getIdentifier(instance)!, flag, ); } /// Helper method to convert instances ids to objects. Future<void> setSupportMultipleWindowsFromInstance( WebSettings instance, bool support, ) { return setSupportMultipleWindows( instanceManager.getIdentifier(instance)!, support); } /// Helper method to convert instances ids to objects. Future<void> setJavaScriptEnabledFromInstance( WebSettings instance, bool flag, ) { return setJavaScriptEnabled( instanceManager.getIdentifier(instance)!, flag, ); } /// Helper method to convert instances ids to objects. Future<void> setUserAgentStringFromInstance( WebSettings instance, String? userAgentString, ) { return setUserAgentString( instanceManager.getIdentifier(instance)!, userAgentString, ); } /// Helper method to convert instances ids to objects. Future<void> setMediaPlaybackRequiresUserGestureFromInstance( WebSettings instance, bool require, ) { return setMediaPlaybackRequiresUserGesture( instanceManager.getIdentifier(instance)!, require, ); } /// Helper method to convert instances ids to objects. Future<void> setSupportZoomFromInstance( WebSettings instance, bool support, ) { return setSupportZoom(instanceManager.getIdentifier(instance)!, support); } /// Helper method to convert instances ids to objects. Future<void> setSetTextZoomFromInstance( WebSettings instance, int textZoom, ) { return setTextZoom(instanceManager.getIdentifier(instance)!, textZoom); } /// Helper method to convert instances ids to objects. Future<void> setLoadWithOverviewModeFromInstance( WebSettings instance, bool overview, ) { return setLoadWithOverviewMode( instanceManager.getIdentifier(instance)!, overview, ); } /// Helper method to convert instances ids to objects. Future<void> setUseWideViewPortFromInstance( WebSettings instance, bool use, ) { return setUseWideViewPort(instanceManager.getIdentifier(instance)!, use); } /// Helper method to convert instances ids to objects. Future<void> setDisplayZoomControlsFromInstance( WebSettings instance, bool enabled, ) { return setDisplayZoomControls( instanceManager.getIdentifier(instance)!, enabled, ); } /// Helper method to convert instances ids to objects. Future<void> setBuiltInZoomControlsFromInstance( WebSettings instance, bool enabled, ) { return setBuiltInZoomControls( instanceManager.getIdentifier(instance)!, enabled, ); } /// Helper method to convert instances ids to objects. Future<void> setAllowFileAccessFromInstance( WebSettings instance, bool enabled, ) { return setAllowFileAccess( instanceManager.getIdentifier(instance)!, enabled, ); } /// Helper method to convert instances ids to objects. Future<String> getUserAgentStringFromInstance(WebSettings instance) { return getUserAgentString(instanceManager.getIdentifier(instance)!); } } /// Host api implementation for [JavaScriptChannel]. class JavaScriptChannelHostApiImpl extends JavaScriptChannelHostApi { /// Constructs a [JavaScriptChannelHostApiImpl]. JavaScriptChannelHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(JavaScriptChannel instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); await create( identifier, instance.channelName, ); } } } /// Flutter api implementation for [JavaScriptChannel]. class JavaScriptChannelFlutterApiImpl extends JavaScriptChannelFlutterApi { /// Constructs a [JavaScriptChannelFlutterApiImpl]. JavaScriptChannelFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void postMessage(int instanceId, String message) { final JavaScriptChannel? instance = instanceManager .getInstanceWithWeakReference(instanceId) as JavaScriptChannel?; assert( instance != null, 'InstanceManager does not contain a JavaScriptChannel with instanceId: $instanceId', ); instance!.postMessage(message); } } /// Host api implementation for [WebViewClient]. class WebViewClientHostApiImpl extends WebViewClientHostApi { /// Constructs a [WebViewClientHostApiImpl]. WebViewClientHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebViewClient instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); return create(identifier); } } /// Helper method to convert instances ids to objects. Future<void> setShouldOverrideUrlLoadingReturnValueFromInstance( WebViewClient instance, bool value, ) { return setSynchronousReturnValueForShouldOverrideUrlLoading( instanceManager.getIdentifier(instance)!, value, ); } } /// Flutter api implementation for [WebViewClient]. class WebViewClientFlutterApiImpl extends WebViewClientFlutterApi { /// Constructs a [WebViewClientFlutterApiImpl]. WebViewClientFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void onPageFinished(int instanceId, int webViewInstanceId, String url) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain a WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); if (instance!.onPageFinished != null) { instance.onPageFinished!(webViewInstance!, url); } } @override void onPageStarted(int instanceId, int webViewInstanceId, String url) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain a WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); if (instance!.onPageStarted != null) { instance.onPageStarted!(webViewInstance!, url); } } @override void onReceivedHttpError( int instanceId, int webViewInstanceId, WebResourceRequestData request, WebResourceResponseData response, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain an WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain an WebView with instanceId: $webViewInstanceId', ); if (instance!.onReceivedHttpError != null) { instance.onReceivedHttpError!( webViewInstance!, _toWebResourceRequest(request), _toWebResourceResponse(response), ); } } @override void onReceivedError( int instanceId, int webViewInstanceId, int errorCode, String description, String failingUrl, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain a WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); if (instance!.onReceivedError != null) { instance.onReceivedError!( webViewInstance!, errorCode, description, failingUrl, ); } } @override void onReceivedRequestError( int instanceId, int webViewInstanceId, WebResourceRequestData request, WebResourceErrorData error, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain a WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); if (instance!.onReceivedRequestError != null) { instance.onReceivedRequestError!( webViewInstance!, _toWebResourceRequest(request), _toWebResourceError(error), ); } } @override void requestLoading( int instanceId, int webViewInstanceId, WebResourceRequestData request, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain a WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); if (instance!.requestLoading != null) { instance.requestLoading!( webViewInstance!, _toWebResourceRequest(request), ); } } @override void urlLoading( int instanceId, int webViewInstanceId, String url, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain a WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); if (instance!.urlLoading != null) { instance.urlLoading!(webViewInstance!, url); } } @override void doUpdateVisitedHistory( int instanceId, int webViewInstanceId, String url, bool isReload, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain a WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); if (instance!.doUpdateVisitedHistory != null) { instance.doUpdateVisitedHistory!(webViewInstance!, url, isReload); } } @override void onReceivedHttpAuthRequest( int instanceId, int webViewInstanceId, int httpAuthHandlerInstanceId, String host, String realm, ) { final WebViewClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebViewClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; final HttpAuthHandler? httpAuthHandlerInstance = instanceManager.getInstanceWithWeakReference(httpAuthHandlerInstanceId) as HttpAuthHandler?; assert( instance != null, 'InstanceManager does not contain a WebViewClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); assert( httpAuthHandlerInstance != null, 'InstanceManager does not contain a HttpAuthHandler with instanceId: $httpAuthHandlerInstanceId', ); if (instance!.onReceivedHttpAuthRequest != null) { return instance.onReceivedHttpAuthRequest!( webViewInstance!, httpAuthHandlerInstance!, host, realm); } } } /// Host api implementation for [DownloadListener]. class DownloadListenerHostApiImpl extends DownloadListenerHostApi { /// Constructs a [DownloadListenerHostApiImpl]. DownloadListenerHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(DownloadListener instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); return create(identifier); } } } /// Flutter api implementation for [DownloadListener]. class DownloadListenerFlutterApiImpl extends DownloadListenerFlutterApi { /// Constructs a [DownloadListenerFlutterApiImpl]. DownloadListenerFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void onDownloadStart( int instanceId, String url, String userAgent, String contentDisposition, String mimetype, int contentLength, ) { final DownloadListener? instance = instanceManager .getInstanceWithWeakReference(instanceId) as DownloadListener?; assert( instance != null, 'InstanceManager does not contain a DownloadListener with instanceId: $instanceId', ); instance!.onDownloadStart( url, userAgent, contentDisposition, mimetype, contentLength, ); } } /// Host api implementation for [DownloadListener]. class WebChromeClientHostApiImpl extends WebChromeClientHostApi { /// Constructs a [WebChromeClientHostApiImpl]. WebChromeClientHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebChromeClient instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); return create(identifier); } } /// Helper method to convert instances ids to objects. Future<void> setSynchronousReturnValueForOnShowFileChooserFromInstance( WebChromeClient instance, bool value, ) { return setSynchronousReturnValueForOnShowFileChooser( instanceManager.getIdentifier(instance)!, value, ); } /// Helper method to convert instances ids to objects. Future<void> setSynchronousReturnValueForOnConsoleMessageFromInstance( WebChromeClient instance, bool value, ) { return setSynchronousReturnValueForOnConsoleMessage( instanceManager.getIdentifier(instance)!, value, ); } /// Helper method to convert instances ids to objects. Future<void> setSynchronousReturnValueForOnJsAlertFromInstance( WebChromeClient instance, bool value, ) { return setSynchronousReturnValueForOnJsAlert( instanceManager.getIdentifier(instance)!, value); } /// Helper method to convert instances ids to objects. Future<void> setSynchronousReturnValueForOnJsConfirmFromInstance( WebChromeClient instance, bool value, ) { return setSynchronousReturnValueForOnJsConfirm( instanceManager.getIdentifier(instance)!, value); } /// Helper method to convert instances ids to objects. Future<void> setSynchronousReturnValueForOnJsPromptFromInstance( WebChromeClient instance, bool value, ) { return setSynchronousReturnValueForOnJsPrompt( instanceManager.getIdentifier(instance)!, value); } } /// Flutter api implementation for [DownloadListener]. class WebChromeClientFlutterApiImpl extends WebChromeClientFlutterApi { /// Constructs a [DownloadListenerFlutterApiImpl]. WebChromeClientFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; @override void onProgressChanged(int instanceId, int webViewInstanceId, int progress) { final WebChromeClient? instance = instanceManager .getInstanceWithWeakReference(instanceId) as WebChromeClient?; final WebView? webViewInstance = instanceManager .getInstanceWithWeakReference(webViewInstanceId) as WebView?; assert( instance != null, 'InstanceManager does not contain a WebChromeClient with instanceId: $instanceId', ); assert( webViewInstance != null, 'InstanceManager does not contain a WebView with instanceId: $webViewInstanceId', ); if (instance!.onProgressChanged != null) { instance.onProgressChanged!(webViewInstance!, progress); } } @override Future<List<String?>> onShowFileChooser( int instanceId, int webViewInstanceId, int paramsInstanceId, ) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; if (instance.onShowFileChooser != null) { return instance.onShowFileChooser!( instanceManager.getInstanceWithWeakReference(webViewInstanceId)! as WebView, instanceManager.getInstanceWithWeakReference(paramsInstanceId)! as FileChooserParams, ); } return Future<List<String>>.value(const <String>[]); } @override void onGeolocationPermissionsShowPrompt( int instanceId, int paramsInstanceId, String origin) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; final GeolocationPermissionsCallback callback = instanceManager.getInstanceWithWeakReference(paramsInstanceId)! as GeolocationPermissionsCallback; final GeolocationPermissionsShowPrompt? onShowPrompt = instance.onGeolocationPermissionsShowPrompt; if (onShowPrompt != null) { onShowPrompt(origin, callback); } } @override void onGeolocationPermissionsHidePrompt(int identifier) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(identifier)!; final GeolocationPermissionsHidePrompt? onHidePrompt = instance.onGeolocationPermissionsHidePrompt; if (onHidePrompt != null) { return onHidePrompt(instance); } } @override void onPermissionRequest( int instanceId, int requestInstanceId, ) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; if (instance.onPermissionRequest != null) { instance.onPermissionRequest!( instance, instanceManager.getInstanceWithWeakReference(requestInstanceId)!, ); } else { // The method requires calling grant or deny if the Java method is // overridden, so this calls deny by default if `onPermissionRequest` is // null. final PermissionRequest request = instanceManager.getInstanceWithWeakReference(requestInstanceId)!; request.deny(); } } @override void onShowCustomView( int instanceId, int viewIdentifier, int callbackIdentifier, ) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; if (instance.onShowCustomView != null) { return instance.onShowCustomView!( instance, instanceManager.getInstanceWithWeakReference(viewIdentifier)!, instanceManager.getInstanceWithWeakReference(callbackIdentifier)!, ); } } @override void onHideCustomView(int instanceId) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; if (instance.onHideCustomView != null) { return instance.onHideCustomView!( instance, ); } } @override void onConsoleMessage(int instanceId, ConsoleMessage message) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; instance.onConsoleMessage?.call(instance, message); } @override Future<void> onJsAlert(int instanceId, String url, String message) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; return instance.onJsAlert!(url, message); } @override Future<bool> onJsConfirm(int instanceId, String url, String message) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; return instance.onJsConfirm!(url, message); } @override Future<String> onJsPrompt( int instanceId, String url, String message, String defaultValue) { final WebChromeClient instance = instanceManager.getInstanceWithWeakReference(instanceId)!; return instance.onJsPrompt!(url, message, defaultValue); } } /// Host api implementation for [WebStorage]. class WebStorageHostApiImpl extends WebStorageHostApi { /// Constructs a [WebStorageHostApiImpl]. WebStorageHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> createFromInstance(WebStorage instance) async { if (instanceManager.getIdentifier(instance) == null) { final int identifier = instanceManager.addDartCreatedInstance(instance); return create(identifier); } } /// Helper method to convert instances ids to objects. Future<void> deleteAllDataFromInstance(WebStorage instance) { return deleteAllData(instanceManager.getIdentifier(instance)!); } } /// Flutter api implementation for [FileChooserParams]. class FileChooserParamsFlutterApiImpl extends FileChooserParamsFlutterApi { /// Constructs a [FileChooserParamsFlutterApiImpl]. FileChooserParamsFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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 java objects. final InstanceManager instanceManager; @override void create( int instanceId, bool isCaptureEnabled, List<String?> acceptTypes, FileChooserMode mode, String? filenameHint, ) { instanceManager.addHostCreatedInstance( FileChooserParams.detached( isCaptureEnabled: isCaptureEnabled, acceptTypes: acceptTypes.cast(), mode: mode, filenameHint: filenameHint, binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), instanceId, ); } } /// Host api implementation for [GeolocationPermissionsCallback]. class GeolocationPermissionsCallbackHostApiImpl extends GeolocationPermissionsCallbackHostApi { /// Constructs a [GeolocationPermissionsCallbackHostApiImpl]. GeolocationPermissionsCallbackHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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 java objects. final InstanceManager instanceManager; /// Helper method to convert instances ids to objects. Future<void> invokeFromInstances( GeolocationPermissionsCallback instance, String origin, bool allow, bool retain, ) { return invoke( instanceManager.getIdentifier(instance)!, origin, allow, retain, ); } } /// Flutter API implementation for [GeolocationPermissionsCallback]. /// /// 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 GeolocationPermissionsCallbackFlutterApiImpl implements GeolocationPermissionsCallbackFlutterApi { /// Constructs a [GeolocationPermissionsCallbackFlutterApiImpl]. GeolocationPermissionsCallbackFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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 instanceId) { instanceManager.addHostCreatedInstance( GeolocationPermissionsCallback.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), instanceId, ); } } /// Host api implementation for [PermissionRequest]. class PermissionRequestHostApiImpl extends PermissionRequestHostApi { /// Constructs a [PermissionRequestHostApiImpl]. PermissionRequestHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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 native language objects. final InstanceManager instanceManager; /// Helper method to convert instance ids to objects. Future<void> grantFromInstances( PermissionRequest instance, List<String> resources, ) { return grant(instanceManager.getIdentifier(instance)!, resources); } /// Helper method to convert instance ids to objects. Future<void> denyFromInstances(PermissionRequest instance) { return deny(instanceManager.getIdentifier(instance)!); } } /// Flutter API implementation for [PermissionRequest]. /// /// 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 PermissionRequestFlutterApiImpl implements PermissionRequestFlutterApi { /// Constructs a [PermissionRequestFlutterApiImpl]. PermissionRequestFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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, List<String?> resources, ) { instanceManager.addHostCreatedInstance( PermissionRequest.detached( resources: resources.cast<String>(), binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), identifier, ); } } /// Host api implementation for [CustomViewCallback]. class CustomViewCallbackHostApiImpl extends CustomViewCallbackHostApi { /// Constructs a [CustomViewCallbackHostApiImpl]. CustomViewCallbackHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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 native language objects. final InstanceManager instanceManager; /// Helper method to convert instance ids to objects. Future<void> onCustomViewHiddenFromInstances(CustomViewCallback instance) { return onCustomViewHidden(instanceManager.getIdentifier(instance)!); } } /// Flutter API implementation for [CustomViewCallback]. /// /// 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 CustomViewCallbackFlutterApiImpl implements CustomViewCallbackFlutterApi { /// Constructs a [CustomViewCallbackFlutterApiImpl]. CustomViewCallbackFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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( CustomViewCallback.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), identifier, ); } } /// Flutter API implementation for [View]. /// /// 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 ViewFlutterApiImpl implements ViewFlutterApi { /// Constructs a [ViewFlutterApiImpl]. ViewFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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( View.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), identifier, ); } } /// Host api implementation for [CookieManager]. class CookieManagerHostApiImpl extends CookieManagerHostApi { /// Constructs a [CookieManagerHostApiImpl]. CookieManagerHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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 native language objects. final InstanceManager instanceManager; /// Helper method to convert instance ids to objects. CookieManager attachInstanceFromInstances(CookieManager instance) { attachInstance(instanceManager.addDartCreatedInstance(instance)); return instance; } /// Helper method to convert instance ids to objects. Future<void> setCookieFromInstances( CookieManager instance, String url, String value, ) { return setCookie( instanceManager.getIdentifier(instance)!, url, value, ); } /// Helper method to convert instance ids to objects. Future<bool> removeAllCookiesFromInstances(CookieManager instance) { return removeAllCookies(instanceManager.getIdentifier(instance)!); } /// Helper method to convert instance ids to objects. Future<void> setAcceptThirdPartyCookiesFromInstances( CookieManager instance, WebView webView, bool accept, ) { return setAcceptThirdPartyCookies( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(webView)!, accept, ); } } /// Host api implementation for [HttpAuthHandler]. class HttpAuthHandlerHostApiImpl extends HttpAuthHandlerHostApi { /// Constructs a [HttpAuthHandlerHostApiImpl]. HttpAuthHandlerHostApiImpl({ super.binaryMessenger, InstanceManager? instanceManager, }) : _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager _instanceManager; /// Helper method to convert instance ids to objects. Future<void> cancelFromInstance(HttpAuthHandler instance) { return cancel(_instanceManager.getIdentifier(instance)!); } /// Helper method to convert instance ids to objects. Future<void> proceedFromInstance( HttpAuthHandler instance, String username, String password, ) { return proceed( _instanceManager.getIdentifier(instance)!, username, password, ); } /// Helper method to convert instance ids to objects. Future<bool> useHttpAuthUsernamePasswordFromInstance( HttpAuthHandler instance, ) { return useHttpAuthUsernamePassword( _instanceManager.getIdentifier(instance)!, ); } } /// Flutter API implementation for [HttpAuthHandler]. class HttpAuthHandlerFlutterApiImpl extends HttpAuthHandlerFlutterApi { /// Constructs a [HttpAuthHandlerFlutterApiImpl]. HttpAuthHandlerFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? JavaObject.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 instanceId) { instanceManager.addHostCreatedInstance( HttpAuthHandler(), instanceId, ); } }
packages/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_api_impls.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_api_impls.dart", "repo_id": "packages", "token_count": 16508 }
1,058
// Mocks generated by Mockito 5.4.4 from annotations // in webview_flutter_android/test/android_navigation_delegate_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; import 'package:mockito/mockito.dart' as _i1; import 'package:webview_flutter_android/src/android_webview.dart' as _i2; import 'test_android_webview.g.dart' as _i3; // 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 _FakeJavaObject_0 extends _i1.SmartFake implements _i2.JavaObject { _FakeJavaObject_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [TestInstanceManagerHostApi]. /// /// See the documentation for Mockito's code generation for more information. class MockTestInstanceManagerHostApi extends _i1.Mock implements _i3.TestInstanceManagerHostApi { MockTestInstanceManagerHostApi() { _i1.throwOnMissingStub(this); } @override void clear() => super.noSuchMethod( Invocation.method( #clear, [], ), returnValueForMissingStub: null, ); } /// A class which mocks [HttpAuthHandler]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpAuthHandler extends _i1.Mock implements _i2.HttpAuthHandler { MockHttpAuthHandler() { _i1.throwOnMissingStub(this); } @override _i4.Future<void> cancel() => (super.noSuchMethod( Invocation.method( #cancel, [], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<void> proceed( String? username, String? password, ) => (super.noSuchMethod( Invocation.method( #proceed, [ username, password, ], ), returnValue: _i4.Future<void>.value(), returnValueForMissingStub: _i4.Future<void>.value(), ) as _i4.Future<void>); @override _i4.Future<bool> useHttpAuthUsernamePassword() => (super.noSuchMethod( Invocation.method( #useHttpAuthUsernamePassword, [], ), returnValue: _i4.Future<bool>.value(false), ) as _i4.Future<bool>); @override _i2.JavaObject copy() => (super.noSuchMethod( Invocation.method( #copy, [], ), returnValue: _FakeJavaObject_0( this, Invocation.method( #copy, [], ), ), ) as _i2.JavaObject); }
packages/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart", "repo_id": "packages", "token_count": 1333 }
1,059
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 2.10.0 * Adds `WebResourceRequest` and `WebResourceResponse` to `HttpResponseError`. ## 2.9.1 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 2.9.0 * Adds support to show JavaScript dialog. See `PlatformWebViewController.setOnJavaScriptAlertDialog`, `PlatformWebViewController.setOnJavaScriptConfirmDialog` and `PlatformWebViewController.setOnJavaScriptTextInputDialog`. ## 2.8.0 * Adds support to track scroll position changes. See `PlatformWebViewController.setOnScrollPositionChange`. ## 2.7.0 * Adds support for handling HTTP basic authentication requests. See `PlatformNavigationDelegate.setOnHttpAuthRequest`. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 2.6.0 * Adds support to register a callback to intercept messages that are written to the JavaScript console. See `PlatformWebViewController.setOnConsoleMessage`. ## 2.5.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.5.0 * Adds support to retrieve the user agent. See `PlatformWebViewController.getUserAgent`. ## 2.4.0 * Adds support to retrieve the url from a web resource loading error. See `WebResourceError.url`. ## 2.3.1 * Removes obsolete null checks on non-nullable values. ## 2.3.0 * Adds support to receive permission requests. See `PlatformWebViewController.setOnPlatformPermissionRequest`. ## 2.2.0 * Updates minimum Flutter version to 3.3. * Fixes common typos in tests and documentation. * Adds support for listening to HTTP errors. See `PlatformNavigationDelegate.setOnHttpError`. ## 2.1.0 * Adds support to track url changes. See `PlatformNavigationDelegate.setOnUrlChange`. * Aligns Dart and Flutter SDK constraints. ## 2.0.2 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.0.1 * Improves error message when a platform interface class is used before `WebViewPlatform.instance` has been set. ## 2.0.0 * **Breaking Change**: Releases new interface. See [documentation](https://pub.dev/documentation/webview_flutter_platform_interface/2.0.0/) and [design doc](https://flutter.dev/go/webview_flutter_4_interface) for more details. * **Breaking Change**: Removes MethodChannel implementation of interface. All platform implementations will now need to create their own by implementing `WebViewPlatform`. ## 1.9.5 * Updates code for `no_leading_underscores_for_local_identifiers` lint. ## 1.9.4 * Updates imports for `prefer_relative_imports`. ## 1.9.3 * Updates minimum Flutter version to 2.10. * Removes `BuildParams` from v4 interface and adds `layoutDirection` to the creation params. ## 1.9.2 * 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). * Adds missing build params for v4 WebViewWidget interface. ## 1.9.1 * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231). ## 1.9.0 * Adds the first iteration of the v4 webview_flutter interface implementation. * Removes unnecessary imports. ## 1.8.2 * Migrates from `ui.hash*` to `Object.hash*`. * Updates minimum Flutter version to 2.5.0. ## 1.8.1 * Update to use the `verify` method introduced in platform_plugin_interface 2.1.0. ## 1.8.0 * Adds the `loadFlutterAsset` method to the platform interface. ## 1.7.0 * Add an option to set the background color of the webview. ## 1.6.1 * Revert deprecation of `clearCookies` in WebViewPlatform for later deprecation. ## 1.6.0 * Adds platform interface for cookie manager. * Deprecates `clearCookies` in WebViewPlatform in favour of `CookieManager#clearCookies`. * Expanded `CreationParams` to include cookies to be set at webview creation. ## 1.5.2 * Mirgrates from analysis_options_legacy.yaml to the more strict analysis_options.yaml. ## 1.5.1 * Reverts the addition of `onUrlChanged`, which was unintentionally a breaking change. ## 1.5.0 * Added `onUrlChanged` callback to platform callback handler. ## 1.4.0 * Added `loadFile` and `loadHtml` interface methods. ## 1.3.0 * Added `loadRequest` method to platform interface. ## 1.2.0 * Added `runJavascript` and `runJavascriptReturningResult` interface methods to supersede `evaluateJavascript`. ## 1.1.0 * Add `zoomEnabled` functionality to `WebSettings`. ## 1.0.0 * Extracted platform interface from `webview_flutter`.
packages/packages/webview_flutter/webview_flutter_platform_interface/CHANGELOG.md/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/CHANGELOG.md", "repo_id": "packages", "token_count": 1407 }
1,060
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'package:webview_flutter_web/webview_flutter_web.dart'; void main() { group('WebWebViewPlatform', () { test('registerWith', () { WebWebViewPlatform.registerWith(Registrar()); expect(WebViewPlatform.instance, isA<WebWebViewPlatform>()); }); }); }
packages/packages/webview_flutter/webview_flutter_web/test/webview_flutter_web_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_web/test/webview_flutter_web_test.dart", "repo_id": "packages", "token_count": 213 }
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 Flutter; @import XCTest; @import webview_flutter_wkwebview; #import <OCMock/OCMock.h> @interface FWFURLTests : XCTestCase @end @implementation FWFURLTests - (void)testAbsoluteString { NSURL *mockUrl = OCMClassMock([NSURL class]); OCMStub([mockUrl absoluteString]).andReturn(@"https://www.google.com"); FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; [instanceManager addDartCreatedInstance:mockUrl withIdentifier:0]; FWFURLHostApiImpl *hostApi = [[FWFURLHostApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; FlutterError *error; XCTAssertEqualObjects([hostApi absoluteStringForNSURLWithIdentifier:0 error:&error], @"https://www.google.com"); XCTAssertNil(error); } - (void)testFlutterApiCreate { FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init]; FWFURLFlutterApiImpl *flutterApi = [[FWFURLFlutterApiImpl alloc] initWithBinaryMessenger:OCMProtocolMock(@protocol(FlutterBinaryMessenger)) instanceManager:instanceManager]; flutterApi.api = OCMClassMock([FWFNSUrlFlutterApi class]); NSURL *url = [[NSURL alloc] initWithString:@"https://www.google.com"]; [flutterApi create:url completion:^(FlutterError *error){ }]; long identifier = [instanceManager identifierWithStrongReferenceForInstance:url]; OCMVerify([flutterApi.api createWithIdentifier:identifier completion:OCMOCK_ANY]); } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFURLTests.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFURLTests.m", "repo_id": "packages", "token_count": 617 }
1,062
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFPreferencesHostApi.h" #import "FWFWebViewConfigurationHostApi.h" @interface FWFPreferencesHostApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFPreferencesHostApiImpl - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _instanceManager = instanceManager; } return self; } - (WKPreferences *)preferencesForIdentifier:(NSInteger)identifier { return (WKPreferences *)[self.instanceManager instanceForIdentifier:identifier]; } - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable *_Nonnull)error { WKPreferences *preferences = [[WKPreferences alloc] init]; [self.instanceManager addDartCreatedInstance:preferences withIdentifier:identifier]; } - (void)createFromWebViewConfigurationWithIdentifier:(NSInteger)identifier configurationIdentifier:(NSInteger)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error { WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager instanceForIdentifier:configurationIdentifier]; [self.instanceManager addDartCreatedInstance:configuration.preferences withIdentifier:identifier]; } - (void)setJavaScriptEnabledForPreferencesWithIdentifier:(NSInteger)identifier isEnabled:(BOOL)enabled error:(FlutterError *_Nullable *_Nonnull)error { [[self preferencesForIdentifier:identifier] setJavaScriptEnabled:enabled]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFPreferencesHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFPreferencesHostApi.m", "repo_id": "packages", "token_count": 672 }
1,063
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFURLHostApi.h" @interface FWFURLHostApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @interface FWFURLFlutterApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFURLHostApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; } return self; } - (nullable NSString *) absoluteStringForNSURLWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { NSURL *instance = [self urlForIdentifier:identifier error:error]; if (*error) { return nil; } return instance.absoluteString; } - (nullable NSURL *)urlForIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { NSURL *instance = (NSURL *)[self.instanceManager instanceForIdentifier:identifier]; if (!instance) { NSString *message = [NSString stringWithFormat:@"InstanceManager does not contain an NSURL with identifier: %li", (long)identifier]; *error = [FlutterError errorWithCode:NSInternalInconsistencyException message:message details:nil]; } return instance; } @end @implementation FWFURLFlutterApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _instanceManager = instanceManager; _api = [[FWFNSUrlFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; } return self; } - (void)create:(NSURL *)instance completion:(void (^)(FlutterError *_Nullable))completion { [self.api createWithIdentifier:[self.instanceManager addHostCreatedInstance:instance] completion:completion]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLHostApi.m", "repo_id": "packages", "token_count": 957 }
1,064
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as path; import 'package:test/fake.dart'; import 'package:test/test.dart'; import 'package:xdg_directories/xdg_directories.dart' as xdg; void main() { final Map<String, String> fakeEnv = <String, String>{}; late Directory tmpDir; String testRootPath() { final String basePath = tmpDir.path; return Platform.isWindows // Strip the drive specifier when running tests on Windows since // environment variables use : as a path list separator. ? basePath.substring(basePath.indexOf(':') + 1) : basePath; } String testPath(String subdir) => path.join(testRootPath(), subdir); setUp(() { xdg.xdgProcessRunner = FakeProcessRunner(<String, String>{}, canRunExecutable: false); tmpDir = Directory.systemTemp.createTempSync('xdg_test'); fakeEnv.clear(); fakeEnv['HOME'] = testRootPath(); fakeEnv['XDG_CACHE_HOME'] = testPath('.test_cache'); fakeEnv['XDG_CONFIG_DIRS'] = testPath('etc/test_xdg'); fakeEnv['XDG_CONFIG_HOME'] = testPath('.test_config'); fakeEnv['XDG_DATA_DIRS'] = '${testPath('usr/local/test_share')}:${testPath('usr/test_share')}'; fakeEnv['XDG_DATA_HOME'] = testPath('.local/test_share'); fakeEnv['XDG_RUNTIME_DIR'] = testPath('.local/test_runtime'); Directory(fakeEnv['XDG_CONFIG_HOME']!).createSync(recursive: true); Directory(fakeEnv['XDG_CACHE_HOME']!).createSync(recursive: true); Directory(fakeEnv['XDG_DATA_HOME']!).createSync(recursive: true); Directory(fakeEnv['XDG_RUNTIME_DIR']!).createSync(recursive: true); File(path.join(fakeEnv['XDG_CONFIG_HOME']!, 'user-dirs.dirs')) .writeAsStringSync(r''' XDG_DESKTOP_DIR="$HOME/Desktop" XDG_DOCUMENTS_DIR="$HOME/Documents" XDG_DOWNLOAD_DIR="$HOME/Downloads" XDG_MUSIC_DIR="$HOME/Music" XDG_PICTURES_DIR="$HOME/Pictures" XDG_PUBLICSHARE_DIR="$HOME/Public" XDG_TEMPLATES_DIR="$HOME/Templates" XDG_VIDEOS_DIR="$HOME/Videos" '''); xdg.xdgEnvironmentOverride = (String key) => fakeEnv[key]; }); tearDown(() { tmpDir.deleteSync(recursive: true); // Stop overriding the environment accessor. xdg.xdgEnvironmentOverride = null; }); void expectDirList(List<Directory> values, List<String> expected) { final List<String> valueStr = values.map<String>((Directory directory) => directory.path).toList(); expect(valueStr, orderedEquals(expected)); } test('Default fallback values work', () { fakeEnv.clear(); fakeEnv['HOME'] = testRootPath(); expect(xdg.cacheHome.path, equals(testPath('.cache'))); expect(xdg.configHome.path, equals(testPath('.config'))); expect(xdg.dataHome.path, equals(testPath('.local/share'))); expect(xdg.runtimeDir, isNull); expectDirList(xdg.configDirs, <String>['/etc/xdg']); expectDirList(xdg.dataDirs, <String>['/usr/local/share', '/usr/share']); }); test('Values pull from environment', () { expect(xdg.cacheHome.path, equals(testPath('.test_cache'))); expect(xdg.configHome.path, equals(testPath('.test_config'))); expect(xdg.dataHome.path, equals(testPath('.local/test_share'))); expect(xdg.runtimeDir, isNotNull); expect(xdg.runtimeDir!.path, equals(testPath('.local/test_runtime'))); expectDirList(xdg.configDirs, <String>[testPath('etc/test_xdg')]); expectDirList(xdg.dataDirs, <String>[ testPath('usr/local/test_share'), testPath('usr/test_share'), ]); }); test('Can get userDirs', () { final Map<String, String> expected = <String, String>{ 'DESKTOP': testPath('Desktop'), 'DOCUMENTS': testPath('Documents'), 'DOWNLOAD': testPath('Downloads'), 'MUSIC': testPath('Music'), 'PICTURES': testPath('Pictures'), 'PUBLICSHARE': testPath('Public'), 'TEMPLATES': testPath('Templates'), 'VIDEOS': testPath('Videos'), }; xdg.xdgProcessRunner = FakeProcessRunner(expected); final Set<String> userDirs = xdg.getUserDirectoryNames(); expect(userDirs, equals(expected.keys.toSet())); for (final String key in userDirs) { expect(xdg.getUserDirectory(key)!.path, equals(expected[key]), reason: 'Path $key value not correct'); } }); test('Returns null when xdg-user-dir executable is not present', () { xdg.xdgProcessRunner = FakeProcessRunner( <String, String>{}, canRunExecutable: false, ); expect(xdg.getUserDirectory('DESKTOP'), isNull, reason: 'Found xdg user directory without access to xdg-user-dir'); }); test('Throws StateError when HOME not set', () { fakeEnv.clear(); expect(() { xdg.configHome; }, throwsStateError); }); } class FakeProcessRunner extends Fake implements xdg.XdgProcessRunner { FakeProcessRunner(this.expected, {this.canRunExecutable = true}); Map<String, String> expected; final bool canRunExecutable; @override ProcessResult runSync( String executable, List<String> arguments, { Encoding? stdoutEncoding = systemEncoding, Encoding? stderrEncoding = systemEncoding, }) { if (!canRunExecutable) { throw ProcessException(executable, arguments, 'No such executable', 2); } return ProcessResult(0, 0, expected[arguments.first], ''); } }
packages/packages/xdg_directories/test/xdg_directories_test.dart/0
{ "file_path": "packages/packages/xdg_directories/test/xdg_directories_test.dart", "repo_id": "packages", "token_count": 2105 }
1,065
# Running the somes tests from these packages on an AVD with Android 34 causes failures. - webview_flutter
packages/script/configs/still_requires_api_33_avd.yaml/0
{ "file_path": "packages/script/configs/still_requires_api_33_avd.yaml", "repo_id": "packages", "token_count": 27 }
1,066
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/repository_package.dart'; /// A command to run Dart's "fix" command on packages. class FixCommand extends PackageLoopingCommand { /// Creates a fix command instance. FixCommand( super.packagesDir, { super.processRunner, super.platform, }); @override final String name = 'fix'; @override final String description = 'Fixes packages using dart fix.\n\n' 'This command requires "dart" and "flutter" to be in your path, and ' 'assumes that dependencies have already been fetched (e.g., by running ' 'the analyze command first).'; @override final bool hasLongOutput = false; @override PackageLoopingType get packageLoopingType => PackageLoopingType.includeAllSubpackages; @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final int exitCode = await processRunner.runAndStream( 'dart', <String>['fix', '--apply'], workingDir: package.directory); if (exitCode != 0) { printError('Unable to automatically fix package.'); return PackageResult.fail(); } return PackageResult.success(); } }
packages/script/tool/lib/src/fix_command.dart/0
{ "file_path": "packages/script/tool/lib/src/fix_command.dart", "repo_id": "packages", "token_count": 443 }
1,067
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:file/file.dart'; import 'package:http/http.dart' as http; import 'package:pub_semver/pub_semver.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'package:yaml_edit/yaml_edit.dart'; import 'common/core.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/pub_utils.dart'; import 'common/pub_version_finder.dart'; import 'common/repository_package.dart'; const int _exitIncorrectTargetDependency = 3; const int _exitNoTargetVersion = 4; const int _exitInvalidTargetVersion = 5; /// A command to update a dependency in packages. /// /// This is intended to expand over time to support any sort of dependency that /// packages use, including pub packages and native dependencies, and should /// include any tasks related to the dependency (e.g., regenerating files when /// updating a dependency that is responsible for code generation). class UpdateDependencyCommand extends PackageLoopingCommand { /// Creates an instance of the version check command. UpdateDependencyCommand( super.packagesDir, { super.processRunner, http.Client? httpClient, }) : _pubVersionFinder = PubVersionFinder(httpClient: httpClient ?? http.Client()) { argParser.addOption( _pubPackageFlag, help: 'A pub package to update.', ); argParser.addOption(_androidDependency, help: 'An Android dependency to update.', allowed: <String>[ _AndroidDepdencyType.gradle, _AndroidDepdencyType.compileSdk, _AndroidDepdencyType.compileSdkForExamples, ], allowedHelp: <String, String>{ _AndroidDepdencyType.gradle: 'Updates Gradle version used in plugin example apps.', _AndroidDepdencyType.compileSdk: 'Updates compileSdk version used to compile plugins.', _AndroidDepdencyType.compileSdkForExamples: 'Updates compileSdk version used to compile plugin examples.', }); argParser.addOption( _versionFlag, help: 'The version to update to.\n\n' '- For pub, defaults to the latest published version if not ' 'provided. This can be any constraint that pubspec.yaml allows; a ' 'specific version will be treated as the exact version for ' 'dependencies that are alread pinned, or a ^ range for those that ' 'are unpinned.\n' '- For Android dependencies, a version must be provided.', ); } static const String _pubPackageFlag = 'pub-package'; static const String _androidDependency = 'android-dependency'; static const String _versionFlag = 'version'; final PubVersionFinder _pubVersionFinder; late final String? _targetPubPackage; late final String? _targetAndroidDependency; late final String _targetVersion; @override final String name = 'update-dependency'; @override final String description = 'Updates a dependency in a package.'; @override bool get hasLongOutput => false; @override PackageLoopingType get packageLoopingType => PackageLoopingType.includeAllSubpackages; @override Future<void> initializeRun() async { const Set<String> targetFlags = <String>{ _pubPackageFlag, _androidDependency }; final Set<String> passedTargetFlags = targetFlags.where((String flag) => argResults![flag] != null).toSet(); if (passedTargetFlags.length != 1) { printError( 'Exactly one of the target flags must be provided: (${targetFlags.join(', ')})'); throw ToolExit(_exitIncorrectTargetDependency); } // Setup for updating pub dependency. _targetPubPackage = getNullableStringArg(_pubPackageFlag); if (_targetPubPackage != null) { final String? version = getNullableStringArg(_versionFlag); if (version == null) { final PubVersionFinderResponse response = await _pubVersionFinder .getPackageVersion(packageName: _targetPubPackage!); switch (response.result) { case PubVersionFinderResult.success: _targetVersion = response.versions.first.toString(); case PubVersionFinderResult.fail: printError(''' Error fetching $_targetPubPackage version from pub: ${response.httpResponse.statusCode}: ${response.httpResponse.body} '''); throw ToolExit(_exitNoTargetVersion); case PubVersionFinderResult.noPackageFound: printError('$_targetPubPackage does not exist on pub'); throw ToolExit(_exitNoTargetVersion); } } else { _targetVersion = version; return; } } // Setup for updating Android dependency. _targetAndroidDependency = getNullableStringArg(_androidDependency); if (_targetAndroidDependency != null) { final String? version = getNullableStringArg(_versionFlag); if (version == null) { printError('A version must be provided to update this dependency.'); throw ToolExit(_exitNoTargetVersion); } else if (_targetAndroidDependency == _AndroidDepdencyType.gradle) { final RegExp validGradleVersionPattern = RegExp(r'^\d+(?:\.\d+){1,2}$'); final bool isValidGradleVersion = validGradleVersionPattern.stringMatch(version) == version; if (!isValidGradleVersion) { printError( 'A version with a valid format (maximum 2-3 numbers separated by period) must be provided.'); throw ToolExit(_exitInvalidTargetVersion); } } else if (_targetAndroidDependency == _AndroidDepdencyType.compileSdk || _targetAndroidDependency == _AndroidDepdencyType.compileSdkForExamples) { final RegExp validSdkVersion = RegExp(r'^\d{1,2}$'); final bool isValidSdkVersion = validSdkVersion.stringMatch(version) == version; if (!isValidSdkVersion) { printError( 'A valid Android SDK version number (1-2 digit numbers) must be provided.'); throw ToolExit(_exitInvalidTargetVersion); } } else { // TODO(camsim99): Add other supported Android dependencies like the min/target Android SDK and AGP. printError( 'Target Android dependency $_targetAndroidDependency is unrecognized.'); throw ToolExit(_exitIncorrectTargetDependency); } _targetVersion = version; } } @override Future<void> completeRun() async { _pubVersionFinder.httpClient.close(); } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { if (_targetPubPackage != null) { return _runForPubDependency(package, _targetPubPackage!); } if (_targetAndroidDependency != null) { return _runForAndroidDependency(package); } // TODO(stuartmorgan): Add other dependency types here (e.g., maven). return PackageResult.fail(); } /// Handles all of the updates for [package] when the target dependency is /// a pub dependency. Future<PackageResult> _runForPubDependency( RepositoryPackage package, String dependency) async { final _PubDependencyInfo? dependencyInfo = _getPubDependencyInfo(package, dependency); if (dependencyInfo == null) { return PackageResult.skip('Does not depend on $dependency'); } else if (!dependencyInfo.hosted) { return PackageResult.skip('$dependency in not a hosted dependency'); } // Determine the target version constraint. final String sectionKey = dependencyInfo.type == _PubDependencyType.dev ? 'dev_dependencies' : 'dependencies'; final String versionString; final VersionConstraint parsedConstraint = VersionConstraint.parse(_targetVersion); // If the provided string was a constraint, or if it's a specific // version but the package has a pinned dependency, use it as-is. if (dependencyInfo.pinned || parsedConstraint is! VersionRange || parsedConstraint.min != parsedConstraint.max) { versionString = _targetVersion; } else { // Otherwise, it's a specific version; treat it as '^version'. final Version minVersion = parsedConstraint.min!; versionString = '^$minVersion'; } // Update pubspec.yaml with the new version. print('${indentation}Updating to "$versionString"'); if (versionString == dependencyInfo.constraintString) { return PackageResult.skip('Already depends on $versionString'); } final YamlEditor editablePubspec = YamlEditor(package.pubspecFile.readAsStringSync()); editablePubspec.update( <String>[sectionKey, dependency], versionString, ); package.pubspecFile.writeAsStringSync(editablePubspec.toString()); // Do any dependency-specific extra processing. if (dependency == 'pigeon') { if (!await _regeneratePigeonFiles(package)) { return PackageResult.fail(<String>['Failed to update pigeon files']); } } else if (dependency == 'mockito') { if (!await _regenerateMocks(package)) { return PackageResult.fail(<String>['Failed to update mocks']); } } // TODO(stuartmorgan): Add additional handling of known packages that // do file generation. return PackageResult.success(); } /// Handles all of the updates for [package] when the target dependency is /// an Android dependency. Future<PackageResult> _runForAndroidDependency( RepositoryPackage package) async { if (_targetAndroidDependency == _AndroidDepdencyType.compileSdk) { return _runForCompileSdkVersion(package); } else if (_targetAndroidDependency == _AndroidDepdencyType.gradle || _targetAndroidDependency == _AndroidDepdencyType.compileSdkForExamples) { return _runForAndroidDependencyOnExamples(package); } return PackageResult.fail(<String>[ 'Target Android dependency $_androidDependency is unrecognized.' ]); } Future<PackageResult> _runForAndroidDependencyOnExamples( RepositoryPackage package) async { final Iterable<RepositoryPackage> packageExamples = package.getExamples(); bool updateRanForExamples = false; for (final RepositoryPackage example in packageExamples) { if (!example.platformDirectory(FlutterPlatform.android).existsSync()) { continue; } updateRanForExamples = true; final Directory androidDirectory = example.platformDirectory(FlutterPlatform.android); final List<File> filesToUpdate = <File>[]; final RegExp dependencyVersionPattern; final String newDependencyVersionEntry; if (_targetAndroidDependency == _AndroidDepdencyType.gradle) { if (androidDirectory .childDirectory('gradle') .childDirectory('wrapper') .existsSync()) { filesToUpdate.add(androidDirectory .childDirectory('gradle') .childDirectory('wrapper') .childFile('gradle-wrapper.properties')); } if (androidDirectory .childDirectory('app') .childDirectory('gradle') .childDirectory('wrapper') .existsSync()) { filesToUpdate.add(androidDirectory .childDirectory('app') .childDirectory('gradle') .childDirectory('wrapper') .childFile('gradle-wrapper.properties')); } dependencyVersionPattern = RegExp(r'^\s*distributionUrl\s*=\s*.*\.zip', multiLine: true); // TODO(camsim99): Validate current AGP version against target Gradle // version: https://github.com/flutter/flutter/issues/133887. newDependencyVersionEntry = 'distributionUrl=https\\://services.gradle.org/distributions/gradle-$_targetVersion-all.zip'; } else if (_targetAndroidDependency == _AndroidDepdencyType.compileSdkForExamples) { filesToUpdate.add( androidDirectory.childDirectory('app').childFile('build.gradle')); dependencyVersionPattern = RegExp( r'(compileSdk|compileSdkVersion) (\d{1,2}|flutter.compileSdkVersion)'); newDependencyVersionEntry = 'compileSdk $_targetVersion'; } else { printError( 'Target Android dependency $_targetAndroidDependency is unrecognized.'); throw ToolExit(_exitIncorrectTargetDependency); } for (final File fileToUpdate in filesToUpdate) { final String oldFileToUpdateContents = fileToUpdate.readAsStringSync(); if (!dependencyVersionPattern.hasMatch(oldFileToUpdateContents)) { return PackageResult.fail(<String>[ 'Unable to find a $_targetAndroidDependency version entry to update for ${example.displayName}.' ]); } print( '${indentation}Updating ${getRelativePosixPath(example.directory, from: package.directory)} to "$_targetVersion"'); final String newGradleWrapperPropertiesContents = oldFileToUpdateContents.replaceFirst( dependencyVersionPattern, newDependencyVersionEntry); fileToUpdate.writeAsStringSync(newGradleWrapperPropertiesContents); } } return updateRanForExamples ? PackageResult.success() : PackageResult.skip('No example apps run on Android.'); } Future<PackageResult> _runForCompileSdkVersion( RepositoryPackage package) async { if (!package.platformDirectory(FlutterPlatform.android).existsSync()) { return PackageResult.skip( 'Package ${package.displayName} does not run on Android.'); } else if (package.isExample) { // We skip examples for this command. return PackageResult.skip( 'Package ${package.displayName} is not a top-level package; run with "compileSdkForExamples" to update.'); } final File buildConfigurationFile = package .platformDirectory(FlutterPlatform.android) .childFile('build.gradle'); final String buildConfigurationContents = buildConfigurationFile.readAsStringSync(); final RegExp validCompileSdkVersion = RegExp(r'(compileSdk|compileSdkVersion) \d{1,2}'); if (!validCompileSdkVersion.hasMatch(buildConfigurationContents)) { return PackageResult.fail(<String>[ 'Unable to find a compileSdk version entry to update for ${package.displayName}.' ]); } print('${indentation}Updating ${package.directory} to "$_targetVersion"'); final String newBuildConfigurationContents = buildConfigurationContents .replaceFirst(validCompileSdkVersion, 'compileSdk $_targetVersion'); buildConfigurationFile.writeAsStringSync(newBuildConfigurationContents); return PackageResult.success(); } /// Returns information about the current dependency of [package] on /// the package named [dependencyName], or null if there is no dependency. _PubDependencyInfo? _getPubDependencyInfo( RepositoryPackage package, String dependencyName) { final Pubspec pubspec = package.parsePubspec(); Dependency? dependency; final _PubDependencyType type; if (pubspec.dependencies.containsKey(dependencyName)) { dependency = pubspec.dependencies[dependencyName]; type = _PubDependencyType.normal; } else if (pubspec.devDependencies.containsKey(dependencyName)) { dependency = pubspec.devDependencies[dependencyName]; type = _PubDependencyType.dev; } else { return null; } if (dependency != null && dependency is HostedDependency) { final VersionConstraint version = dependency.version; return _PubDependencyInfo( type, pinned: version is VersionRange && version.min == version.max, hosted: true, constraintString: version.toString(), ); } return _PubDependencyInfo(type, pinned: false, hosted: false); } /// Returns all of the files in [package] that are, according to repository /// convention, Pigeon input files. Iterable<File> _getPigeonInputFiles(RepositoryPackage package) { // Repo convention is that the Pigeon input files are the Dart files in a // top-level "pigeons" directory. final Directory pigeonsDir = package.directory.childDirectory('pigeons'); if (!pigeonsDir.existsSync()) { return <File>[]; } return pigeonsDir .listSync() .whereType<File>() .where((File file) => file.basename.endsWith('.dart')); } /// Re-runs Pigeon generation for [package]. /// /// This assumes that all output configuration is set in the input files, so /// no additional arguments are needed. If that assumption stops holding true, /// the tooling will need a way for packages to control the generation (e.g., /// with a script file with a known name in the pigeons/ directory.) Future<bool> _regeneratePigeonFiles(RepositoryPackage package) async { final Iterable<File> inputs = _getPigeonInputFiles(package); if (inputs.isEmpty) { logWarning('No pigeon input files found.'); return true; } print('${indentation}Running pub get...'); if (!await runPubGet(package, processRunner, platform, streamOutput: false)) { printError('${indentation}Fetching dependencies failed'); return false; } print('${indentation}Updating Pigeon files...'); for (final File input in inputs) { final String relativePath = getRelativePosixPath(input, from: package.directory); final io.ProcessResult pigeonResult = await processRunner.run( 'dart', <String>['run', 'pigeon', '--input', relativePath], workingDir: package.directory); if (pigeonResult.exitCode != 0) { printError('dart run pigeon failed (${pigeonResult.exitCode}):\n' '${pigeonResult.stdout}\n${pigeonResult.stderr}\n'); return false; } } return true; } /// Re-runs Mockito mock generation for [package] if necessary. Future<bool> _regenerateMocks(RepositoryPackage package) async { final Pubspec pubspec = package.parsePubspec(); if (!pubspec.devDependencies.keys.contains('build_runner')) { print( '${indentation}No build_runner dependency; skipping mock regeneration.'); return true; } print('${indentation}Running pub get...'); if (!await runPubGet(package, processRunner, platform, streamOutput: false)) { printError('${indentation}Fetching dependencies failed'); return false; } print('${indentation}Updating mocks...'); final io.ProcessResult buildRunnerResult = await processRunner.run( 'dart', <String>[ 'run', 'build_runner', 'build', '--delete-conflicting-outputs' ], workingDir: package.directory); if (buildRunnerResult.exitCode != 0) { printError( '"dart run build_runner build" failed (${buildRunnerResult.exitCode}):\n' '${buildRunnerResult.stdout}\n${buildRunnerResult.stderr}\n'); return false; } return true; } } class _PubDependencyInfo { const _PubDependencyInfo(this.type, {required this.pinned, required this.hosted, this.constraintString}); final _PubDependencyType type; final bool pinned; final bool hosted; final String? constraintString; } enum _PubDependencyType { normal, dev } class _AndroidDepdencyType { static const String gradle = 'gradle'; static const String compileSdk = 'compileSdk'; static const String compileSdkForExamples = 'compileSdkForExamples'; }
packages/script/tool/lib/src/update_dependency_command.dart/0
{ "file_path": "packages/script/tool/lib/src/update_dependency_command.dart", "repo_id": "packages", "token_count": 7176 }
1,068
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/git_version_finder.dart'; import 'package:flutter_plugin_tools/src/common/package_state_utils.dart'; import 'package:test/fake.dart'; import 'package:test/test.dart'; import '../util.dart'; void main() { late FileSystem fileSystem; late Directory packagesDir; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); }); group('checkPackageChangeState', () { test('reports version change needed for code changes', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_package/lib/plugin.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_package'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('handles trailing slash on package path', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_package/lib/plugin.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_package/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); expect(state.hasChangelogChange, false); }); test('does not flag version- and changelog-change-exempt changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/CHANGELOG.md', // Dev-facing docs. 'packages/a_plugin/CONTRIBUTING.md', // Analysis. 'packages/a_plugin/example/android/lint-baseline.xml', // Tests. 'packages/a_plugin/example/android/src/androidTest/foo/bar/FooTest.java', 'packages/a_plugin/example/ios/RunnerTests/Foo.m', 'packages/a_plugin/example/ios/RunnerUITests/info.plist', // Pigeon input. 'packages/a_plugin/pigeons/messages.dart', // Test scripts. 'packages/a_plugin/run_tests.sh', 'packages/a_plugin/dart_test.yaml', // Tools. 'packages/a_plugin/tool/a_development_tool.dart', // Example build files. 'packages/a_plugin/example/android/build.gradle', 'packages/a_plugin/example/android/gradle/wrapper/gradle-wrapper.properties', 'packages/a_plugin/example/ios/Runner.xcodeproj/project.pbxproj', 'packages/a_plugin/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme', 'packages/a_plugin/example/linux/flutter/CMakeLists.txt', 'packages/a_plugin/example/macos/Podfile', 'packages/a_plugin/example/macos/Runner.xcodeproj/project.pbxproj', 'packages/a_plugin/example/macos/Runner.xcworkspace/contents.xcworkspacedata', 'packages/a_plugin/example/windows/CMakeLists.txt', 'packages/a_plugin/example/pubspec.yaml', // Pigeon platform tests, which have an unusual structure. 'packages/a_plugin/platform_tests/shared_test_plugin_code/lib/integration_tests.dart', 'packages/a_plugin/platform_tests/test_plugin/windows/test_plugin.cpp', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, false); expect(state.hasChangelogChange, true); }); test('only considers a root "tool" folder to be special', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/lib/foo/tool/tool_thing.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires a version change for example/lib/main.dart', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/lib/main.dart']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/lib/main.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires a version change for example/main.dart', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/main.dart']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/main.dart', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires a version change for example readme.md', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/README.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires a version change for example/example.md', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/example.md']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/example.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test( 'requires a changelog change but no version change for ' 'lower-priority examples when example.md is present', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/example.md']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/lib/main.dart', 'packages/a_plugin/example/main.dart', 'packages/a_plugin/example/README.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, true); }); test( 'requires a changelog change but no version change for README.md when ' 'code example is present', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin', packagesDir, extraFiles: <String>['example/lib/main.dart']); const List<String> changedFiles = <String>[ 'packages/a_plugin/example/README.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, true); }); test( 'requires neither a changelog nor version change for README.md when ' 'code example is present in a federated plugin implementation', () async { final RepositoryPackage package = createFakePlugin( 'a_plugin_android', packagesDir.childDirectory('a_plugin'), extraFiles: <String>['example/lib/main.dart']); const List<String> changedFiles = <String>[ 'packages/a_plugin/a_plugin_android/example/README.md', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/a_plugin_android'); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, false); }); test( 'does not requires changelog or version change for build.gradle ' 'test-dependency-only changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/android/build.gradle', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/android/build.gradle': <String>[ "- androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'", "- testImplementation 'junit:junit:4.10.0'", "+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'", "+ testImplementation 'junit:junit:4.13.2'", ] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, false); }); test('requires changelog or version change for other build.gradle changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/android/build.gradle', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/android/build.gradle': <String>[ "- androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'", "- testImplementation 'junit:junit:4.10.0'", "+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'", "+ testImplementation 'junit:junit:4.13.2'", "- implementation 'com.google.android.gms:play-services-maps:18.0.0'", "+ implementation 'com.google.android.gms:play-services-maps:18.0.2'", ] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test( 'does not requires changelog or version change for ' 'non-doc-comment-only changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/lib/a_plugin.dart', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/lib/a_plugin.dart': <String>[ '- // Old comment.', '+ // New comment.', '+ ', // Allow whitespace line changes as part of comment changes. ] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, false); expect(state.needsChangelogChange, false); }); test('requires changelog or version change for doc comment changes', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/lib/a_plugin.dart', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/lib/a_plugin.dart': <String>[ '- /// Old doc comment.', '+ /// New doc comment.', ] }); final PackageChangeState state = await checkPackageChangeState( package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git, ); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test('requires changelog or version change for Dart code change', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/lib/a_plugin.dart', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/lib/a_plugin.dart': <String>[ // Include inline comments to ensure the comment check doesn't have // false positives for lines that include comment changes but aren't // only comment changes. '- callOldMethod(); // inline comment', '+ callNewMethod(); // inline comment', ] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test( 'requires changelog or version change if build.gradle diffs cannot ' 'be checked', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/android/build.gradle', ]; final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/'); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); test( 'requires changelog or version change if build.gradle diffs cannot ' 'be determined', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir); const List<String> changedFiles = <String>[ 'packages/a_plugin/android/build.gradle', ]; final GitVersionFinder git = FakeGitVersionFinder(<String, List<String>>{ 'packages/a_plugin/android/build.gradle': <String>[] }); final PackageChangeState state = await checkPackageChangeState(package, changedPaths: changedFiles, relativePackagePath: 'packages/a_plugin/', git: git); expect(state.hasChanges, true); expect(state.needsVersionChange, true); expect(state.needsChangelogChange, true); }); }); } class FakeGitVersionFinder extends Fake implements GitVersionFinder { FakeGitVersionFinder(this.fileDiffs); final Map<String, List<String>> fileDiffs; @override Future<List<String>> getDiffContents({ String? targetPath, bool includeUncommitted = false, }) async { return fileDiffs[targetPath]!; } }
packages/script/tool/test/common/package_state_utils_test.dart/0
{ "file_path": "packages/script/tool/test/common/package_state_utils_test.dart", "repo_id": "packages", "token_count": 6420 }
1,069
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/gradle_check_command.dart'; import 'package:test/test.dart'; import 'util.dart'; const String _defaultFakeNamespace = 'dev.flutter.foo'; void main() { late CommandRunner<void> runner; late FileSystem fileSystem; late Directory packagesDir; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = fileSystem.currentDirectory.childDirectory('packages'); createPackagesDirectory(parentDir: packagesDir.parent); final GradleCheckCommand command = GradleCheckCommand( packagesDir, ); runner = CommandRunner<void>( 'gradle_check_command', 'Test for gradle_check_command'); runner.addCommand(command); }); /// Writes a fake android/build.gradle file for plugin [package] with the /// given options. void writeFakePluginBuildGradle( RepositoryPackage package, { bool includeLanguageVersion = false, bool includeSourceCompat = false, bool includeTargetCompat = false, bool commentSourceLanguage = false, bool includeNamespace = true, bool conditionalizeNamespace = true, bool commentNamespace = false, bool warningsConfigured = true, }) { final File buildGradle = package .platformDirectory(FlutterPlatform.android) .childFile('build.gradle'); buildGradle.createSync(recursive: true); const String warningConfig = ''' lintOptions { checkAllWarnings true warningsAsErrors true disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' baseline file("lint-baseline.xml") } '''; final String javaSection = ''' java { toolchain { ${commentSourceLanguage ? '// ' : ''}languageVersion = JavaLanguageVersion.of(8) } } '''; final String sourceCompat = '${commentSourceLanguage ? '// ' : ''}sourceCompatibility JavaVersion.VERSION_1_8'; final String targetCompat = '${commentSourceLanguage ? '// ' : ''}targetCompatibility JavaVersion.VERSION_1_8'; String namespace = " ${commentNamespace ? '// ' : ''}namespace '$_defaultFakeNamespace'"; if (conditionalizeNamespace) { namespace = ''' if (project.android.hasProperty("namespace")) { $namespace } '''; } buildGradle.writeAsStringSync(''' group 'dev.flutter.plugins.fake' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' ${includeLanguageVersion ? javaSection : ''} android { ${includeNamespace ? namespace : ''} compileSdk 33 defaultConfig { minSdkVersion 30 } ${warningsConfigured ? warningConfig : ''} compileOptions { ${includeSourceCompat ? sourceCompat : ''} ${includeTargetCompat ? targetCompat : ''} } testOptions { unitTests.includeAndroidResources = true } } dependencies { implementation 'fake.package:fake:1.0.0' } '''); } /// Writes a fake android/build.gradle file for an example [package] with the /// given options. void writeFakeExampleTopLevelBuildGradle( RepositoryPackage package, { required String pluginName, required bool warningsConfigured, String? kotlinVersion, bool includeArtifactHub = true, }) { final File buildGradle = package .platformDirectory(FlutterPlatform.android) .childFile('build.gradle'); buildGradle.createSync(recursive: true); final String warningConfig = ''' gradle.projectsEvaluated { project(":$pluginName") { tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:all" << "-Werror" } } } '''; buildGradle.writeAsStringSync(''' buildscript { ${kotlinVersion == null ? '' : "ext.kotlin_version = '$kotlinVersion'"} repositories { ${includeArtifactHub ? GradleCheckCommand.exampleRootGradleArtifactHubString : ''} google() mavenCentral() } dependencies { classpath 'fake.package:fake:1.0.0' } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "\${rootProject.buildDir}/\${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } ${warningsConfigured ? warningConfig : ''} '''); } /// Writes a fake android/build.gradle file for an example [package] with the /// given options. void writeFakeExampleTopLevelSettingsGradle( RepositoryPackage package, { bool includeArtifactHub = true, }) { final File settingsGradle = package .platformDirectory(FlutterPlatform.android) .childFile('settings.gradle'); settingsGradle.createSync(recursive: true); settingsGradle.writeAsStringSync(''' include ':app' def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() def plugins = new Properties() def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') if (pluginsFile.exists()) { pluginsFile.withInputStream { stream -> plugins.load(stream) } } plugins.each { name, path -> def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() include ":\$name" project(":\$name").projectDir = pluginDirectory } ${includeArtifactHub ? GradleCheckCommand.exampleRootSettingsArtifactHubString : ''} '''); } /// Writes a fake android/app/build.gradle file for an example [package] with /// the given options. void writeFakeExampleAppBuildGradle( RepositoryPackage package, { required bool includeNamespace, required bool commentNamespace, }) { final File buildGradle = package .platformDirectory(FlutterPlatform.android) .childDirectory('app') .childFile('build.gradle'); buildGradle.createSync(recursive: true); final String namespace = "${commentNamespace ? '// ' : ''}namespace '$_defaultFakeNamespace'"; buildGradle.writeAsStringSync(''' def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } apply plugin: 'com.android.application' apply from: "\$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { ${includeNamespace ? namespace : ''} compileSdk flutter.compileSdkVersion lintOptions { disable 'InvalidPackage' } defaultConfig { applicationId "io.flutter.plugins.cameraexample" minSdkVersion 21 targetSdkVersion 28 } } flutter { source '../..' } dependencies { testImplementation 'fake.package:fake:1.0.0' } '''); } void writeFakeExampleBuildGradles( RepositoryPackage package, { required String pluginName, bool includeNamespace = true, bool commentNamespace = false, bool warningsConfigured = true, String? kotlinVersion, bool includeBuildArtifactHub = true, bool includeSettingsArtifactHub = true, }) { writeFakeExampleTopLevelBuildGradle( package, pluginName: pluginName, warningsConfigured: warningsConfigured, kotlinVersion: kotlinVersion, includeArtifactHub: includeBuildArtifactHub, ); writeFakeExampleAppBuildGradle(package, includeNamespace: includeNamespace, commentNamespace: commentNamespace); writeFakeExampleTopLevelSettingsGradle( package, includeArtifactHub: includeSettingsArtifactHub, ); } void writeFakeManifest( RepositoryPackage package, { bool isApp = false, String packageName = _defaultFakeNamespace, }) { final Directory androidDir = package.platformDirectory(FlutterPlatform.android); final Directory startDir = isApp ? androidDir.childDirectory('app') : androidDir; final File manifest = startDir .childDirectory('src') .childDirectory('main') .childFile('AndroidManifest.xml'); manifest.createSync(recursive: true); manifest.writeAsString(''' <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="$packageName"> </manifest>'''); } test('skips when package has no Android directory', () async { createFakePackage('a_package', packagesDir, examples: <String>[]); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Skipped 1 package(s)'), ]), ); }); test('fails when build.gradle has no java compatibility version', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package); writeFakeManifest(package); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'build.gradle must set an explicit Java compatibility version.'), ]), ); }); test( 'fails when sourceCompatibility is provided with out targetCompatibility', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeSourceCompat: true); writeFakeManifest(package); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'build.gradle must set an explicit Java compatibility version.'), ]), ); }); test('passes when sourceCompatibility and targetCompatibility are specified', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeSourceCompat: true, includeTargetCompat: true); writeFakeManifest(package); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Validating android/build.gradle'), ]), ); }); test('passes when toolchain languageVersion is specified', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Validating android/build.gradle'), ]), ); }); test('does not require java version in examples', () async { const String pluginName = 'a_plugin'; final RepositoryPackage package = createFakePlugin(pluginName, packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: pluginName); writeFakeManifest(example, isApp: true); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Validating android/build.gradle'), contains('Ran for 2 package(s)'), ]), ); }); test('fails when java compatibility version is commented out', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeSourceCompat: true, includeTargetCompat: true, commentSourceLanguage: true); writeFakeManifest(package); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'build.gradle must set an explicit Java compatibility version.'), ]), ); }); test('fails when languageVersion is commented out', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeLanguageVersion: true, commentSourceLanguage: true); writeFakeManifest(package); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'build.gradle must set an explicit Java compatibility version.'), ]), ); }); test('fails when plugin namespace does not match AndroidManifest.xml', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package, packageName: 'wrong.package.name'); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'build.gradle "namespace" must match the "package" attribute in AndroidManifest.xml'), ]), ); }); test('fails when plugin namespace is not conditional', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeLanguageVersion: true, conditionalizeNamespace: false); writeFakeManifest(package); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('build.gradle for a plugin must conditionalize "namespace"'), ]), ); }); test('fails when namespace is missing', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeLanguageVersion: true, includeNamespace: false); writeFakeManifest(package); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('build.gradle must set a "namespace"'), ]), ); }); test('fails when namespace is missing from example', () async { const String pluginName = 'a_plugin'; final RepositoryPackage package = createFakePlugin(pluginName, packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: pluginName, includeNamespace: false); writeFakeManifest(example, isApp: true); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('build.gradle must set a "namespace"'), ]), ); }); // TODO(stuartmorgan): Consider removing this in the future; we may at some // point decide that we have a use case of example apps having different // app IDs and namespaces. For now, it's enforced for consistency so they // don't just accidentally diverge. test('fails when namespace in example does not match AndroidManifest.xml', () async { const String pluginName = 'a_plugin'; final RepositoryPackage package = createFakePlugin(pluginName, packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: pluginName); writeFakeManifest(example, isApp: true, packageName: 'wrong.package.name'); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains( 'build.gradle "namespace" must match the "package" attribute in AndroidManifest.xml'), ]), ); }); test('fails when namespace is commented out', () async { final RepositoryPackage package = createFakePlugin('a_plugin', packagesDir, examples: <String>[]); writeFakePluginBuildGradle(package, includeLanguageVersion: true, commentNamespace: true); writeFakeManifest(package); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('build.gradle must set a "namespace"'), ]), ); }); test('fails if gradle-driven lint-warnings-as-errors is missing', () async { const String pluginName = 'a_plugin'; final RepositoryPackage plugin = createFakePlugin(pluginName, packagesDir, examples: <String>[]); writeFakePluginBuildGradle(plugin, includeLanguageVersion: true, warningsConfigured: false); writeFakeManifest(plugin); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('This package is not configured to enable all ' 'Gradle-driven lint warnings and treat them as errors.'), contains('The following packages had errors:'), ], )); }); test('fails if plugin example javac lint-warnings-as-errors is missing', () async { const String pluginName = 'a_plugin'; final RepositoryPackage plugin = createFakePlugin(pluginName, packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline), }); writeFakePluginBuildGradle(plugin, includeLanguageVersion: true); writeFakeManifest(plugin); final RepositoryPackage example = plugin.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: pluginName, warningsConfigured: false); writeFakeManifest(example, isApp: true); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('The example "example" is not configured to treat javac ' 'lints and warnings as errors.'), contains('The following packages had errors:'), ], )); }); test( 'passes if non-plugin package example javac lint-warnings-as-errors is missing', () async { const String packageName = 'a_package'; final RepositoryPackage plugin = createFakePackage(packageName, packagesDir); final RepositoryPackage example = plugin.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: packageName, warningsConfigured: false); writeFakeManifest(example, isApp: true); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder( <Matcher>[ contains('Validating android/build.gradle'), ], )); }); group('Artifact Hub check', () { test('passes build.gradle artifact hub check when set', () async { const String packageName = 'a_package'; final RepositoryPackage package = createFakePackage('a_package', packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles( example, pluginName: packageName, // ignore: avoid_redundant_argument_values includeBuildArtifactHub: true, // ignore: avoid_redundant_argument_values includeSettingsArtifactHub: true, ); writeFakeManifest(example, isApp: true); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Validating android/build.gradle'), contains('Validating android/settings.gradle'), ]), ); }); test('fails artifact hub check when build and settings sections missing', () async { const String packageName = 'a_package'; final RepositoryPackage package = createFakePackage('a_package', packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles( example, pluginName: packageName, includeBuildArtifactHub: false, includeSettingsArtifactHub: false, ); writeFakeManifest(example, isApp: true); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains(GradleCheckCommand.exampleRootGradleArtifactHubString), contains(GradleCheckCommand.exampleRootSettingsArtifactHubString), ]), ); }); test('fails build.gradle artifact hub check when missing', () async { const String packageName = 'a_package'; final RepositoryPackage package = createFakePackage('a_package', packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: packageName, includeBuildArtifactHub: false, // ignore: avoid_redundant_argument_values includeSettingsArtifactHub: true); writeFakeManifest(example, isApp: true); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains(GradleCheckCommand.exampleRootGradleArtifactHubString), ]), ); expect( output, isNot( contains(GradleCheckCommand.exampleRootSettingsArtifactHubString)), ); }); test('fails settings.gradle artifact hub check when missing', () async { const String packageName = 'a_package'; final RepositoryPackage package = createFakePackage('a_package', packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: packageName, // ignore: avoid_redundant_argument_values includeBuildArtifactHub: true, includeSettingsArtifactHub: false); writeFakeManifest(example, isApp: true); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains(GradleCheckCommand.exampleRootSettingsArtifactHubString), ]), ); expect( output, isNot(contains(GradleCheckCommand.exampleRootGradleArtifactHubString)), ); }); }); group('Kotlin version check', () { test('passes if not set', () async { const String packageName = 'a_package'; final RepositoryPackage package = createFakePackage('a_package', packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: packageName); writeFakeManifest(example, isApp: true); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Validating android/build.gradle'), ]), ); }); test('passes if at the minimum allowed version', () async { const String packageName = 'a_package'; final RepositoryPackage package = createFakePackage('a_package', packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: packageName, kotlinVersion: minKotlinVersion.toString()); writeFakeManifest(example, isApp: true); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Validating android/build.gradle'), ]), ); }); test('passes if above the minimum allowed version', () async { const String packageName = 'a_package'; final RepositoryPackage package = createFakePackage('a_package', packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: packageName, kotlinVersion: '99.99.0'); writeFakeManifest(example, isApp: true); final List<String> output = await runCapturingPrint(runner, <String>['gradle-check']); expect( output, containsAllInOrder(<Matcher>[ contains('Validating android/build.gradle'), ]), ); }); test('fails if below the minimum allowed version', () async { const String packageName = 'a_package'; final RepositoryPackage package = createFakePackage('a_package', packagesDir); writeFakePluginBuildGradle(package, includeLanguageVersion: true); writeFakeManifest(package); final RepositoryPackage example = package.getExamples().first; writeFakeExampleBuildGradles(example, pluginName: packageName, kotlinVersion: '1.6.21'); writeFakeManifest(example, isApp: true); Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['gradle-check'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder(<Matcher>[ contains('build.gradle sets "ext.kotlin_version" to "1.6.21". The ' 'minimum Kotlin version that can be specified is ' '$minKotlinVersion, for compatibility with modern dependencies.'), ]), ); }); }); }
packages/script/tool/test/gradle_check_command_test.dart/0
{ "file_path": "packages/script/tool/test/gradle_check_command_test.dart", "repo_id": "packages", "token_count": 10749 }
1,070
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/update_min_sdk_command.dart'; import 'package:test/test.dart'; import 'util.dart'; void main() { late FileSystem fileSystem; late Directory packagesDir; late CommandRunner<void> runner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); final UpdateMinSdkCommand command = UpdateMinSdkCommand( packagesDir, ); runner = CommandRunner<void>( 'update_min_sdk_command', 'Test for update_min_sdk_command'); runner.addCommand(command); }); test('fails if --flutter-min is missing', () async { Error? commandError; await runCapturingPrint(runner, <String>[ 'update-min-sdk', ], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ArgumentError>()); }); test('updates Dart when only Dart is present, with manual range', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, dartConstraint: '>=3.0.0 <4.0.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; expect(dartVersion, '^3.1.0'); }); test('updates Dart when only Dart is present, with carrot', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, dartConstraint: '^3.0.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; expect(dartVersion, '^3.1.0'); }); test('does not update Dart if it is already higher', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, dartConstraint: '^3.2.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; expect(dartVersion, '^3.2.0'); }); test('updates both Dart and Flutter when both are present', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, isFlutter: true, dartConstraint: '>=3.0.0 <4.0.0', flutterConstraint: '>=3.10.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; final String flutterVersion = package.parsePubspec().environment?['flutter'].toString() ?? ''; expect(dartVersion, '^3.1.0'); expect(flutterVersion, '>=3.13.0'); }); test('does not update Flutter if it is already higher', () async { final RepositoryPackage package = createFakePackage( 'a_package', packagesDir, isFlutter: true, dartConstraint: '^3.2.0', flutterConstraint: '>=3.16.0'); await runCapturingPrint(runner, <String>[ 'update-min-sdk', '--flutter-min', '3.13.0', // Corresponds to Dart 3.1.0 ]); final String dartVersion = package.parsePubspec().environment?['sdk'].toString() ?? ''; final String flutterVersion = package.parsePubspec().environment?['flutter'].toString() ?? ''; expect(dartVersion, '^3.2.0'); expect(flutterVersion, '>=3.16.0'); }); }
packages/script/tool/test/update_min_sdk_command_test.dart/0
{ "file_path": "packages/script/tool/test/update_min_sdk_command_test.dart", "repo_id": "packages", "token_count": 1558 }
1,071
name: cupertino_icons description: Default icons asset for Cupertino widgets based on Apple styled icons repository: https://github.com/flutter/packages/tree/main/third_party/packages/cupertino_icons issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+cupertino_icons%22 version: 1.0.7 environment: sdk: ^3.1.0 dev_dependencies: flutter: sdk: flutter flutter_test: sdk: flutter flutter: fonts: - family: CupertinoIcons fonts: - asset: assets/CupertinoIcons.ttf topics: - assets - icons - ui
packages/third_party/packages/cupertino_icons/pubspec.yaml/0
{ "file_path": "packages/third_party/packages/cupertino_icons/pubspec.yaml", "repo_id": "packages", "token_count": 236 }
1,072
# Firebase Functions This folder contains firebase functions to support the Photobooth project. ## 'share' function This function validates the requested path is valid for sharing (that it is /share/filename.ext) and that the extension is an expected image file type. It will validate the file exists in storage, and if so return HTML will valid <head> to support open graph and twitter sharing. ## Serving the functions locally From the root folder of the project, run `firebase serve`. The console will output localhost paths that you can access in your browser. For instance, to test the "share" function, try `http://localhost:5001/io-photobooth-dev/us-central1/shareImage/share/upload.jpg` ## Running tests In this folder run `npm test` ## Lint and format files - `npm run lint` - `npm run lint:fix`
photobooth/functions/README.md/0
{ "file_path": "photobooth/functions/README.md", "repo_id": "photobooth", "token_count": 216 }
1,073
import 'dart:developer'; import 'package:bloc/bloc.dart'; class AppBlocObserver extends BlocObserver { @override void onTransition( Bloc<dynamic, dynamic> bloc, Transition<dynamic, dynamic> transition, ) { super.onTransition(bloc, transition); log('onTransition(${bloc.runtimeType}, $transition)'); } @override void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) { log('onError(${bloc.runtimeType}, $error, $stackTrace)'); super.onError(bloc, error, stackTrace); } }
photobooth/lib/app/app_bloc_observer.dart/0
{ "file_path": "photobooth/lib/app/app_bloc_observer.dart", "repo_id": "photobooth", "token_count": 200 }
1,074
{ "@@locale": "vi", "landingPageHeading": "Chào mừng đã đến với tới buồng chụp ảnh I∕O", "landingPageSubheading": "Chụp ảnh và chia sẻ với cộng đồng!", "landingPageTakePhotoButtonText": "Bắt đầu", "footerMadeWithText": "Làm bởi ", "footerMadeWithFlutterLinkText": "Flutter", "footerMadeWithFirebaseLinkText": "Firebase", "footerGoogleIOLinkText": "Google I∕O", "footerCodelabLinkText": "Codelab", "footerHowItsMadeLinkText": "Nó được làm như thế nào", "footerTermsOfServiceLinkText": "Điều khoản dịch vụ", "footerPrivacyPolicyLinkText": "Chính sách bảo mật", "sharePageHeading": "Chia sẻ ảnh của bạn với cộng đồng!", "sharePageSubheading": "Chia sẻ ảnh của bạn với cộng đồng!", "sharePageSuccessHeading": "Chia sẻ ảnh!", "sharePageSuccessSubheading": "Cảm ơn vì đã sử dụng Flutter web app! Ảnh của bạn đã được xuất bản tại URL này", "sharePageSuccessCaption1": "Ảnh của bạn sẽ có sẵn tại URL trong 30 ngày và sau đó tự động bị xóa. Để yêu cầu xóa sớm ảnh của bạn, vui lòng liên hệ ", "sharePageSuccessCaption2": "[email protected]", "sharePageSuccessCaption3": " và hãy chắc chắn bao gồm URL duy nhất của bạn trong yêu cầu của bạn.", "sharePageRetakeButtonText": "Chụp ảnh mới", "sharePageShareButtonText": "Chia sẻ", "sharePageDownloadButtonText": "Tải xuống", "socialMediaShareLinkText": "Chỉ cần chụp ảnh tự sướng tại #IOPhotoBooth. Hẹn gặp bạn tại #GoogleIO!", "previewPageCameraNotAllowedText": "Bạn đã từ chối quyền camera.Vui lòng cấp quyền truy cập để sử dụng ứng dụng.", "sharePageSocialMediaShareClarification1": "Nếu bạn chọn chia sẻ ảnh của mình trên phương tiện truyền thông xã hội, nó sẽ có sẵn tại một URL duy nhất trong 30 ngày và sau đó tự động bị xóa. Ảnh không được chia sẻ, không được lưu trữ. Để yêu cầu xóa sớm ảnh của bạn, vui lòng liên hệ ", "sharePageSocialMediaShareClarification2": "[email protected]", "sharePageSocialMediaShareClarification3": " và hãy chắc chắn bao gồm URL duy nhất của bạn trong yêu cầu của bạn.", "sharePageCopyLinkButton": "Sao chép", "sharePageLinkedCopiedButton": "Đã sao chép.", "sharePageErrorHeading": "Chúng tôi đang gặp sự cố khi xử lý hình ảnh của bạn", "sharePageErrorSubheading": "Vui lòng đảm bảo thiết bị và trình duyệt của bạn được cập nhật. Nếu vấn đề này vẫn còn, xin vui lòng liên hệ [email protected].", "shareDialogHeading": "Chia sẻ ảnh của bạn!", "shareDialogSubheading": "Hãy để mọi người biết bạn đang ở Google I∕O bằng cách chia sẻ ảnh của bạn và cập nhật ảnh hồ sơ của bạn trong sự kiện!", "shareErrorDialogHeading": "Oops!", "shareErrorDialogTryAgainButton": "Quay lại", "shareErrorDialogSubheading": "Một cái gì đó đã sai và chúng tôi không thể tải ảnh của bạn.", "sharePageProgressOverlayHeading": "Chúng tôi đang làm cho pixel ảnh của bạn hoàn hảo với Flutter!", "sharePageProgressOverlaySubheading": "Xin vui lòng không đóng tab này.", "shareDialogTwitterButtonText": "Twitter.", "shareDialogFacebookButtonText": "Facebook", "photoBoothCameraAccessDeniedHeadline": "Truy cập camera bị từ chối", "photoBoothCameraAccessDeniedSubheadline": "Để chụp ảnh, bạn phải cho phép trình duyệt truy cập vào máy ảnh của bạn.", "photoBoothCameraNotFoundHeadline": "Chúng tôi không thể tìm thấy máy ảnh của bạn", "photoBoothCameraNotFoundSubheadline1": "Có vẻ như thiết bị của bạn không có máy ảnh hoặc nó không hoạt động.", "photoBoothCameraNotFoundSubheadline2": "Để chụp ảnh, xin vui lòng truy cập buồng chụp ảnh I∕O từ một thiết bị có camera.", "photoBoothCameraErrorHeadline": "Oops! Đã xảy ra lỗi", "photoBoothCameraErrorSubheadline1": "Vui lòng làm mới trình duyệt của bạn và thử lại.", "photoBoothCameraErrorSubheadline2": "Nếu vấn đề này vẫn còn, xin vui lòng liên hệ [email protected]", "photoBoothCameraNotSupportedHeadline": "Oops! Đã xảy ra lỗi", "photoBoothCameraNotSupportedSubheadline": "Vui lòng đảm bảo thiết bị và trình duyệt của bạn được cập nhật.", "stickersDrawerTitle": "Thêm sticker", "openStickersTooltip": "Thêm sticker", "retakeButtonTooltip": "Chụp lại", "clearStickersButtonTooltip": "Xoá sticker", "charactersCaptionText": "Thêm bạn bè", "sharePageLearnMoreAboutTextPart1": "Học nhiều hơn về ", "sharePageLearnMoreAboutTextPart2": " và ", "sharePageLearnMoreAboutTextPart3": " hoặc lặn ngay vào ", "sharePageLearnMoreAboutTextPart4": "open source code", "goToGoogleIOButtonText": "Đi đến Google I∕O", "clearStickersDialogHeading": "Xóa tất cả các sticker?", "clearStickersDialogSubheading": "Bạn có muốn loại bỏ tất cả các sticker ra khỏi màn hình?", "clearStickersDialogCancelButtonText": "Không, đưa tôi về", "clearStickersDialogConfirmButtonText": "Vâng, xóa tất cả các sticker", "propsReminderText": "Thêm một số sticker", "stickersNextConfirmationHeading": "Sẵn sàng để xem ảnh cuối cùng?", "stickersNextConfirmationSubheading": "Khi bạn rời khỏi màn hình này, bạn sẽ không thể thực hiện bất kỳ thay đổi nào", "stickersNextConfirmationCancelButtonText": "Không, tôi vẫn đang tạo ra", "stickersNextConfirmationConfirmButtonText": "Vâng, hãy cho tôi xem", "stickersRetakeConfirmationHeading": "Bạn có chắc không?", "stickersRetakeConfirmationSubheading": "Lấy lại ảnh sẽ loại bỏ bất kỳ sticker nào bạn đã thêm", "stickersRetakeConfirmationCancelButtonText": "Không, ở lại đây", "stickersRetakeConfirmationConfirmButtonText": "Có, phát lại ảnh", "shareRetakeConfirmationHeading": "Sẵn sàng để chụp ảnh mới?", "shareRetakeConfirmationSubheading": "Hãy nhớ tải về hoặc chia sẻ ảnh", "shareRetakeConfirmationCancelButtonText": "Không, ở lại đây", "shareRetakeConfirmationConfirmButtonText": "Có, chụp ảnh lại", "shutterButtonLabelText": "Chụp hình", "stickersNextButtonLabelText": "Tạo ảnh cuối cùng", "dashButtonLabelText": "Thêm bạn Dash.", "sparkyButtonLabelText": "Thêm bạn Sparky", "dinoButtonLabelText": "Thêm bạn Dino", "androidButtonLabelText": "Thêm bạn Jetpack Android", "addStickersButtonLabelText": "Thêm sticker", "retakePhotoButtonLabelText": "Chụp lại ảnh", "clearAllStickersButtonLabelText": "Xóa tất cả các sticker" }
photobooth/lib/l10n/arb/app_vi.arb/0
{ "file_path": "photobooth/lib/l10n/arb/app_vi.arb", "repo_id": "photobooth", "token_count": 4136 }
1,075
part of 'photobooth_bloc.dart'; const emptyAssetId = ''; class PhotoConstraint extends Equatable { const PhotoConstraint({this.width = 1, this.height = 1}); final double width; final double height; @override List<Object> get props => [width, height]; } class PhotoAssetSize extends Equatable { const PhotoAssetSize({this.width = 1, this.height = 1}); final double width; final double height; @override List<Object?> get props => [width, height]; } class PhotoAssetPosition extends Equatable { const PhotoAssetPosition({this.dx = 0, this.dy = 0}); final double dx; final double dy; @override List<Object> get props => [dx, dy]; } class PhotoAsset extends Equatable { const PhotoAsset({ required this.id, required this.asset, this.angle = 0.0, this.constraint = const PhotoConstraint(), this.position = const PhotoAssetPosition(), this.size = const PhotoAssetSize(), }); final String id; final Asset asset; final double angle; final PhotoConstraint constraint; final PhotoAssetPosition position; final PhotoAssetSize size; @override List<Object> get props => [id, asset.name, angle, constraint, position, size]; PhotoAsset copyWith({ Asset? asset, double? angle, PhotoConstraint? constraint, PhotoAssetPosition? position, PhotoAssetSize? size, }) { return PhotoAsset( id: id, asset: asset ?? this.asset, angle: angle ?? this.angle, constraint: constraint ?? this.constraint, position: position ?? this.position, size: size ?? this.size, ); } } class PhotoboothState extends Equatable { const PhotoboothState({ this.aspectRatio = PhotoboothAspectRatio.landscape, this.characters = const <PhotoAsset>[], this.stickers = const <PhotoAsset>[], this.selectedAssetId = emptyAssetId, this.image, this.imageId = '', }); bool get isDashSelected => characters.containsAsset(named: 'dash'); bool get isAndroidSelected => characters.containsAsset(named: 'android'); bool get isSparkySelected => characters.containsAsset(named: 'sparky'); bool get isDinoSelected => characters.containsAsset(named: 'dino'); bool get isAnyCharacterSelected => characters.isNotEmpty; List<PhotoAsset> get assets => characters + stickers; final double aspectRatio; final CameraImage? image; final String imageId; final List<PhotoAsset> characters; final List<PhotoAsset> stickers; final String selectedAssetId; @override List<Object?> get props => [ aspectRatio, image, imageId, characters, stickers, selectedAssetId, ]; PhotoboothState copyWith({ double? aspectRatio, CameraImage? image, String? imageId, List<PhotoAsset>? characters, List<PhotoAsset>? stickers, String? selectedAssetId, }) { return PhotoboothState( aspectRatio: aspectRatio ?? this.aspectRatio, image: image ?? this.image, imageId: imageId ?? this.imageId, characters: characters ?? this.characters, stickers: stickers ?? this.stickers, selectedAssetId: selectedAssetId ?? this.selectedAssetId, ); } } extension PhotoAssetsX on List<PhotoAsset> { bool containsAsset({required String named}) { return indexWhere((e) => e.asset.name == named) != -1; } }
photobooth/lib/photobooth/bloc/photobooth_state.dart/0
{ "file_path": "photobooth/lib/photobooth/bloc/photobooth_state.dart", "repo_id": "photobooth", "token_count": 1148 }
1,076
import 'package:flutter/widgets.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; class StickersLayer extends StatelessWidget { const StickersLayer({super.key}); @override Widget build(BuildContext context) { final state = context.watch<PhotoboothBloc>().state; return LayoutBuilder( builder: (context, constraints) { return Stack( children: [ for (final sticker in state.stickers) Builder( builder: (context) { final widthFactor = constraints.maxWidth / sticker.constraint.width; final heightFactor = constraints.maxHeight / sticker.constraint.height; return Positioned( key: Key( '''stickersLayer_${sticker.asset.name}_${sticker.id}_positioned''', ), top: sticker.position.dy * heightFactor, left: sticker.position.dx * widthFactor, child: Transform.rotate( angle: sticker.angle, child: Image.asset( sticker.asset.path, fit: BoxFit.fill, height: sticker.size.height * heightFactor, width: sticker.size.width * widthFactor, ), ), ); }, ), ], ); }, ); } }
photobooth/lib/photobooth/widgets/stickers_layer.dart/0
{ "file_path": "photobooth/lib/photobooth/widgets/stickers_layer.dart", "repo_id": "photobooth", "token_count": 860 }
1,077
import 'dart:typed_data'; import 'package:analytics/analytics.dart'; import 'package:cross_file/cross_file.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:io_photobooth/external_links/external_links.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class ShareBody extends StatelessWidget { const ShareBody({super.key}); @override Widget build(BuildContext context) { final image = context.select((PhotoboothBloc bloc) => bloc.state.image); final file = context.select((ShareBloc bloc) => bloc.state.file); final compositeStatus = context.select( (ShareBloc bloc) => bloc.state.compositeStatus, ); final compositedImage = context.select( (ShareBloc bloc) => bloc.state.bytes, ); final isUploadSuccess = context.select( (ShareBloc bloc) => bloc.state.uploadStatus.isSuccess, ); final shareUrl = context.select( (ShareBloc bloc) => bloc.state.explicitShareUrl, ); return Padding( padding: const EdgeInsets.symmetric(horizontal: 24), child: Column( mainAxisSize: MainAxisSize.min, children: [ const AnimatedPhotoIndicator(), AnimatedPhotoboothPhoto(image: image), if (compositeStatus.isSuccess) AnimatedFadeIn( child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 20), if (isUploadSuccess) const ShareSuccessHeading() else const ShareHeading(), const SizedBox(height: 20), if (isUploadSuccess) const ShareSuccessSubheading() else const ShareSubheading(), const SizedBox(height: 30), if (isUploadSuccess) Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 30, ), child: ShareCopyableLink(link: shareUrl), ), if (compositedImage != null && file != null) ResponsiveLayoutBuilder( small: (_, __) => MobileButtonsLayout( image: compositedImage, file: file, ), large: (_, __) => DesktopButtonsLayout( image: compositedImage, file: file, ), ), const SizedBox(height: 28), if (isUploadSuccess) ConstrainedBox( constraints: const BoxConstraints(maxWidth: 1000), child: const ShareSuccessCaption(), ), ], ), ), if (compositeStatus.isFailure) const AnimatedFadeIn( child: Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox(height: 20), ShareErrorHeading(), SizedBox(height: 20), ShareErrorSubheading(), SizedBox(height: 30), ], ), ) ], ), ); } } @visibleForTesting class DesktopButtonsLayout extends StatelessWidget { const DesktopButtonsLayout({ required this.image, required this.file, super.key, }); final Uint8List image; final XFile file; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Flexible(child: DownloadButton(file: file)), const SizedBox(width: 36), Flexible(child: ShareButton(image: image)), const SizedBox(width: 36), const GoToGoogleIOButton(), ], ); } } @visibleForTesting class MobileButtonsLayout extends StatelessWidget { const MobileButtonsLayout({ required this.image, required this.file, super.key, }); final Uint8List image; final XFile file; @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ DownloadButton(file: file), const SizedBox(height: 20), ShareButton(image: image), const SizedBox(height: 20), const GoToGoogleIOButton(), ], ); } } @visibleForTesting class GoToGoogleIOButton extends StatelessWidget { const GoToGoogleIOButton({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: PhotoboothColors.white, ), onPressed: launchGoogleIOLink, child: Text( l10n.goToGoogleIOButtonText, style: theme.textTheme.labelLarge?.copyWith( color: PhotoboothColors.black, ), ), ); } } @visibleForTesting class DownloadButton extends StatelessWidget { const DownloadButton({required this.file, super.key}); final XFile file; @override Widget build(BuildContext context) { final l10n = context.l10n; return OutlinedButton( onPressed: () { trackEvent( category: 'button', action: 'click-download-photo', label: 'download-photo', ); file.saveTo(''); }, child: Text(l10n.sharePageDownloadButtonText), ); } }
photobooth/lib/share/widgets/share_body.dart/0
{ "file_path": "photobooth/lib/share/widgets/share_body.dart", "repo_id": "photobooth", "token_count": 2845 }
1,078
export 'bloc/stickers_bloc.dart'; export 'view/stickers_page.dart'; export 'widgets/widgets.dart';
photobooth/lib/stickers/stickers.dart/0
{ "file_path": "photobooth/lib/stickers/stickers.dart", "repo_id": "photobooth", "token_count": 40 }
1,079
/// Method which tracks an event for the provided /// [category], [action], and [label]. void trackEvent({ required String category, required String action, required String label, }) { // no-op on mobile }
photobooth/packages/analytics/lib/src/analytics_io.dart/0
{ "file_path": "photobooth/packages/analytics/lib/src/analytics_io.dart", "repo_id": "photobooth", "token_count": 58 }
1,080
import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; void main() => runApp(const App()); class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: HomePage()); } } class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { late CameraController _controller; @override void initState() { super.initState(); _initializeCameraController(); } Future<void> _initializeCameraController() async { _controller = CameraController(); await _controller.initialize(); await _controller.play(); } @override void dispose() { _controller.dispose(); super.dispose(); } Future<void> _onSnapPressed() async { final navigator = Navigator.of(context); final image = await _controller.takePicture(); final previewPageRoute = PreviewPage.route(image: image.data); await _controller.stop(); await navigator.push(previewPageRoute); await _controller.play(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Camera( controller: _controller, placeholder: (context) => const Center( child: CircularProgressIndicator(), ), preview: (context, preview) => CameraFrame( onSnapPressed: _onSnapPressed, child: preview, ), error: (context, error) => Center(child: Text(error.description)), ), ), ); } } class CameraFrame extends StatelessWidget { const CameraFrame({ required this.onSnapPressed, required this.child, super.key, }); final Widget child; final void Function() onSnapPressed; @override Widget build(BuildContext context) { return Stack( children: [ child, Align( alignment: Alignment.bottomCenter, child: ElevatedButton( onPressed: onSnapPressed, child: const Text('Take Photo'), ), ), ], ); } } class PreviewPage extends StatelessWidget { const PreviewPage({required this.image, super.key}); static Route<void> route({required String image}) { return MaterialPageRoute(builder: (_) => PreviewPage(image: image)); } final String image; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Preview')), body: Center( child: Image.network( image, errorBuilder: (context, error, stackTrace) { return Text('Error, $error, $stackTrace'); }, ), ), ); } }
photobooth/packages/camera/camera/example/lib/main.dart/0
{ "file_path": "photobooth/packages/camera/camera/example/lib/main.dart", "repo_id": "photobooth", "token_count": 1075 }
1,081
abstract class CameraException implements Exception { const CameraException(this.description); final String description; } class CameraUnknownException implements CameraException { const CameraUnknownException(); @override String get description => 'Unknown Error'; } class CameraNotSupportedException implements CameraException { const CameraNotSupportedException(); @override String get description => 'Not Supported'; } class CameraAbortException implements CameraException { const CameraAbortException(); @override String get description => 'Aborted'; } class CameraNotAllowedException implements CameraException { const CameraNotAllowedException(); @override String get description => 'Not Allowed'; } class CameraNotFoundException implements CameraException { const CameraNotFoundException(); @override String get description => 'Not Found'; } class CameraNotReadableException implements CameraException { const CameraNotReadableException(); @override String get description => 'Not Readable'; } class CameraOverconstrainedException implements CameraException { const CameraOverconstrainedException(); @override String get description => 'Overconstrained'; } class CameraSecurityException implements CameraException { const CameraSecurityException(); @override String get description => 'Security Error'; } class CameraTypeException implements CameraException { const CameraTypeException(); @override String get description => 'Type Error'; }
photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_exception.dart/0
{ "file_path": "photobooth/packages/camera/camera_platform_interface/lib/src/types/camera_exception.dart", "repo_id": "photobooth", "token_count": 357 }
1,082
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:html' as html; import 'dart:js_util' as js_util; /// {@template offscreen_canvas} /// Polyfill for html.OffscreenCanvas that is not supported on some browsers. /// {@endtemplate} class OffScreenCanvas { /// {@macro offscreen_canvas} OffScreenCanvas(this.width, this.height) { if (OffScreenCanvas.supported) { _offScreenCanvas = html.OffscreenCanvas(width, height); } else { _canvasElement = html.CanvasElement( width: width, height: height, ); _canvasElement!.className = 'gl-canvas'; final cssWidth = width / html.window.devicePixelRatio; final cssHeight = height / html.window.devicePixelRatio; _canvasElement!.style ..position = 'absolute' ..width = '${cssWidth}px' ..height = '${cssHeight}px'; } /// Initialize context. getContext2d(); } html.OffscreenCanvas? _offScreenCanvas; html.CanvasElement? _canvasElement; /// The desired width of the canvas. final int width; /// The desired height of the canvas. final int height; Object? _context; static bool? _supported; /// Clears internal state which includes references various canvas elements. void dispose() { _offScreenCanvas = null; _canvasElement = null; } /// Generates a data url from the offscreen canvas. Future<String> toDataUrl() { final completer = Completer<String>(); if (_offScreenCanvas != null) { _offScreenCanvas!.convertToBlob().then((html.Blob value) { final fileReader = html.FileReader(); fileReader.onLoad.listen((event) { completer.complete( js_util.getProperty( js_util.getProperty(event, 'target')!, 'result', ), ); }); fileReader.readAsDataUrl(value); }); return completer.future; } else { return Future.value(_canvasElement!.toDataUrl()); } } /// Returns CanvasRenderContext2D or OffscreenCanvasRenderingContext2D to /// paint into. Object? getContext2d() => _context ??= _offScreenCanvas != null ? _offScreenCanvas!.getContext('2d') : _canvasElement!.getContext('2d'); /// Proxy to `canvas.getContext('2d').save()`. void save() { js_util.callMethod<void>(_context!, 'save', const <dynamic>[]); } /// Proxy to `canvas.getContext('2d').restore()`. void restore() { js_util.callMethod<void>(_context!, 'restore', const <dynamic>[]); } /// Proxy to `canvas.getContext('2d').translate()`. void translate(double x, double y) { js_util.callMethod<void>(_context!, 'translate', <dynamic>[x, y]); } /// Proxy to `canvas.getContext('2d').rotate()`. void rotate(double angle) { js_util.callMethod<void>(_context!, 'rotate', <dynamic>[angle]); } /// Proxy to `canvas.getContext('2d').drawImage()`. void drawImage(Object image, int x, int y, int width, int height) { js_util.callMethod<void>( _context!, 'drawImage', <dynamic>[image, x, y, width, height], ); } /// Creates a rectangular path whose starting point is at (x, y) and /// whose size is specified by width and height and clips the path. void clipRect(int x, int y, int width, int height) { js_util.callMethod<void>(_context!, 'beginPath', const <dynamic>[]); js_util.callMethod<void>(_context!, 'rect', <dynamic>[x, y, width, height]); js_util.callMethod<void>(_context!, 'clip', const <dynamic>[]); } /// Feature detection for transferToImageBitmap on OffscreenCanvas. bool get transferToImageBitmapSupported => js_util.hasProperty(_offScreenCanvas!, 'transferToImageBitmap'); /// Creates an ImageBitmap object from the most recently rendered image /// of the OffscreenCanvas. /// /// !Warning API still in experimental status, feature detect before using. Object? transferToImageBitmap() { return js_util .callMethod(_offScreenCanvas!, 'transferToImageBitmap', <dynamic>[]); } /// Draws canvas contents to a rendering context. void transferImage(Object targetContext) { // Actual size of canvas may be larger than viewport size. Use // source/destination to draw part of the image data. js_util.callMethod<void>(targetContext, 'drawImage', <dynamic>[ _offScreenCanvas ?? _canvasElement!, 0, 0, width, height, 0, 0, width, height ]); } /// Feature detects OffscreenCanvas. static bool get supported => _supported ??= js_util.hasProperty(html.window, 'OffscreenCanvas'); }
photobooth/packages/image_compositor/lib/src/offscreen_canvas.dart/0
{ "file_path": "photobooth/packages/image_compositor/lib/src/offscreen_canvas.dart", "repo_id": "photobooth", "token_count": 1738 }
1,083
/// A UI library for the Photobooth app. library photobooth_ui; export 'package:flame/flame.dart' show Flame; export 'src/colors.dart'; export 'src/helpers/helpers.dart'; export 'src/layout/layout.dart'; export 'src/models/models.dart'; export 'src/navigation/navigation.dart'; export 'src/platform/platform.dart'; export 'src/theme.dart'; export 'src/typography/typography.dart'; export 'src/widgets/widgets.dart';
photobooth/packages/photobooth_ui/lib/photobooth_ui.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/photobooth_ui.dart", "repo_id": "photobooth", "token_count": 150 }
1,084
import 'package:flutter/widgets.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; /// Photobooth Text Style Definitions class PhotoboothTextStyle { static const _baseTextStyle = TextStyle( package: 'photobooth_ui', fontFamily: 'GoogleSans', color: PhotoboothColors.black, fontWeight: PhotoboothFontWeight.regular, ); /// Headline 1 Text Style static TextStyle get headline1 { return _baseTextStyle.copyWith( fontSize: 56, fontWeight: PhotoboothFontWeight.medium, ); } /// Headline 2 Text Style static TextStyle get headline2 { return _baseTextStyle.copyWith( fontSize: 30, fontWeight: PhotoboothFontWeight.regular, ); } /// Headline 3 Text Style static TextStyle get headline3 { return _baseTextStyle.copyWith( fontSize: 24, fontWeight: PhotoboothFontWeight.regular, ); } /// Headline 4 Text Style static TextStyle get headline4 { return _baseTextStyle.copyWith( fontSize: 22, fontWeight: PhotoboothFontWeight.bold, ); } /// Headline 5 Text Style static TextStyle get headline5 { return _baseTextStyle.copyWith( fontSize: 22, fontWeight: PhotoboothFontWeight.medium, ); } /// Headline 6 Text Style static TextStyle get headline6 { return _baseTextStyle.copyWith( fontSize: 22, fontWeight: PhotoboothFontWeight.bold, ); } /// Subtitle 1 Text Style static TextStyle get subtitle1 { return _baseTextStyle.copyWith( fontSize: 16, fontWeight: PhotoboothFontWeight.bold, ); } /// Subtitle 2 Text Style static TextStyle get subtitle2 { return _baseTextStyle.copyWith( fontSize: 14, fontWeight: PhotoboothFontWeight.bold, ); } /// Body Text 1 Text Style static TextStyle get bodyText1 { return _baseTextStyle.copyWith( fontSize: 18, fontWeight: PhotoboothFontWeight.medium, ); } /// Body Text 2 Text Style (the default) static TextStyle get bodyText2 { return _baseTextStyle.copyWith( fontSize: 16, fontWeight: PhotoboothFontWeight.regular, ); } /// Caption Text Style static TextStyle get caption { return _baseTextStyle.copyWith( fontSize: 14, fontWeight: PhotoboothFontWeight.regular, ); } /// Overline Text Style static TextStyle get overline { return _baseTextStyle.copyWith( fontSize: 16, fontWeight: PhotoboothFontWeight.regular, ); } /// Button Text Style static TextStyle get button { return _baseTextStyle.copyWith( fontSize: 18, fontWeight: PhotoboothFontWeight.medium, ); } }
photobooth/packages/photobooth_ui/lib/src/typography/text_styles.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/typography/text_styles.dart", "repo_id": "photobooth", "token_count": 979 }
1,085
export 'animated_fade_in.dart'; export 'animated_pulse.dart'; export 'animated_sprite.dart'; export 'app_animated_cross_fade.dart'; export 'app_circular_progress_indicator.dart'; export 'app_dialog.dart'; export 'app_page_view.dart'; export 'app_tooltip.dart'; export 'app_tooltip_button.dart'; export 'clickable.dart'; export 'draggable_resizable.dart'; export 'platform_builder.dart'; export 'preview_image.dart'; export 'responsive_layout_builder.dart';
photobooth/packages/photobooth_ui/lib/src/widgets/widgets.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/widgets.dart", "repo_id": "photobooth", "token_count": 172 }
1,086
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; void main() { group('AppCircularProgressIndicator', () { testWidgets('renders', (tester) async { await tester.pumpWidget(AppCircularProgressIndicator()); expect(find.byType(AppCircularProgressIndicator), findsOneWidget); }); testWidgets('renders with default colors', (tester) async { await tester.pumpWidget(AppCircularProgressIndicator()); final widget = tester.widget<AppCircularProgressIndicator>( find.byType(AppCircularProgressIndicator), ); expect(widget.color, PhotoboothColors.orange); expect(widget.backgroundColor, PhotoboothColors.white); }); testWidgets('renders with provided colors', (tester) async { const color = PhotoboothColors.black; const backgroundColor = PhotoboothColors.blue; await tester.pumpWidget( AppCircularProgressIndicator( color: color, backgroundColor: backgroundColor, ), ); final widget = tester.widget<AppCircularProgressIndicator>( find.byType(AppCircularProgressIndicator), ); expect(widget.color, color); expect(widget.backgroundColor, backgroundColor); }); }); }
photobooth/packages/photobooth_ui/test/src/widgets/app_circular_progress_indicator_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/widgets/app_circular_progress_indicator_test.dart", "repo_id": "photobooth", "token_count": 494 }
1,087
// ignore_for_file: prefer_const_constructors // ignore_for_file: avoid_dynamic_calls import 'dart:async'; import 'dart:typed_data'; import 'package:firebase_storage/firebase_storage.dart' as firebase_storage; import 'package:flutter_test/flutter_test.dart'; import 'package:image_compositor/image_compositor.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photos_repository/photos_repository.dart'; class MockImageCompositor extends Mock implements ImageCompositor {} class MockFirebaseStorage extends Mock implements firebase_storage.FirebaseStorage {} class MockReference extends Mock implements firebase_storage.Reference {} class MockUploadTask extends Mock implements firebase_storage.UploadTask {} class MockTaskSnapshot extends Mock implements firebase_storage.TaskSnapshot {} class FakeSettableMetadata extends Fake implements firebase_storage.SettableMetadata {} typedef UploadTaskSnapshot = FutureOr<firebase_storage.TaskSnapshot> Function( firebase_storage.TaskSnapshot, ); void main() { setUpAll(() { registerFallbackValue(Uint8List(0)); registerFallbackValue(MockUploadTask()); registerFallbackValue(MockTaskSnapshot()); registerFallbackValue(FakeSettableMetadata()); registerFallbackValue((_) async => MockTaskSnapshot()); }); group('UploadPhotoException', () { test('sets message', () { final exception = UploadPhotoException('msg'); expect(exception.message, 'msg'); }); test('overrides toString with message', () { final exception = UploadPhotoException('msg'); expect(exception.toString(), 'msg'); }); }); group('PhotosRepository', () { late ImageCompositor imageCompositor; late firebase_storage.FirebaseStorage firebaseStorage; late PhotosRepository photosRepository; late firebase_storage.Reference reference; late firebase_storage.UploadTask uploadTask; late firebase_storage.TaskSnapshot taskSnapshot; const photoName = 'photo.jpg'; final photoData = Uint8List(0); const referenceFullPath = 'uploads/$photoName'; const shareText = 'Share text'; setUp(() { imageCompositor = MockImageCompositor(); firebaseStorage = MockFirebaseStorage(); photosRepository = PhotosRepository( firebaseStorage: firebaseStorage, ); reference = MockReference(); uploadTask = MockUploadTask(); taskSnapshot = MockTaskSnapshot(); when(() => firebaseStorage.ref(any())).thenReturn(reference); when(() => reference.putData(any())).thenAnswer((_) => uploadTask); when(() => reference.fullPath).thenReturn(referenceFullPath); when( () => uploadTask.then<dynamic>( any(), onError: any(named: 'onError'), ), ).thenAnswer((invocation) async { (invocation.positionalArguments.first as Function).call(taskSnapshot); return taskSnapshot; }); }); group('sharePhoto', () { test('calls firebaseStorage.ref with appropriate path', () async { await photosRepository.sharePhoto( fileName: photoName, data: photoData, shareText: shareText, ); verify(() => firebaseStorage.ref('uploads/$photoName')).called(1); }); test('calls putData on reference', () async { await photosRepository.sharePhoto( fileName: photoName, data: photoData, shareText: shareText, ); verify(() => reference.putData(photoData)).called(1); }); test('does not putData when reference already exists', () async { when(() => reference.getDownloadURL()).thenAnswer((_) async => 'url'); await photosRepository.sharePhoto( fileName: photoName, data: photoData, shareText: shareText, ); verifyNever(() => reference.putData(photoData)); }); test('returns correct share urls', () async { final shareUrls = await photosRepository.sharePhoto( fileName: photoName, data: photoData, shareText: shareText, ); expect( shareUrls.explicitShareUrl, equals( 'https://io-photobooth-dev.web.app/share/photo.jpg', ), ); expect( shareUrls.facebookShareUrl, equals( 'https://www.facebook.com/sharer.php?u=https://io-photobooth-dev.web.app/share/photo.jpg&quote=Share%20text', ), ); expect( shareUrls.twitterShareUrl, equals( 'https://twitter.com/intent/tweet?url=https://io-photobooth-dev.web.app/share/photo.jpg&text=Share%20text', ), ); }); test( 'throws UploadPhotoException ' 'when firebaseStorage.ref throws', () async { when(() => firebaseStorage.ref(any())).thenThrow(Exception.new); expect( () => photosRepository.sharePhoto( fileName: photoName, data: photoData, shareText: shareText, ), throwsA(isA<UploadPhotoException>()), ); }); test( 'throws UploadPhotoException ' 'when reference.putData throws', () async { when(() => reference.putData(photoData)).thenThrow(Exception.new); expect( () => photosRepository.sharePhoto( fileName: photoName, data: photoData, shareText: shareText, ), throwsA(isA<UploadPhotoException>()), ); }); }); group('composite', () { const image = <int>[]; const data = ''; const width = 4; const height = 4; const layers = [ CompositeLayer( angle: 0, assetPath: 'path', constraints: Vector2D(1, 2), position: Vector2D(3, 4), size: Vector2D(5, 6), ), ]; const aspectRatio = 4 / 3; setUp(() { when( () => imageCompositor.composite( data: any(named: 'data'), width: any(named: 'width'), height: any(named: 'height'), layers: any(named: 'layers'), aspectRatio: any(named: 'aspectRatio'), ), ).thenAnswer((_) async => image); photosRepository = PhotosRepository( firebaseStorage: firebaseStorage, imageCompositor: imageCompositor, ); }); test('invokes composite api on ImageCompositor with serialized data', () async { final actual = await photosRepository.composite( width: width, height: height, data: data, layers: layers, aspectRatio: aspectRatio, ); expect(actual, equals(image)); verify( () => imageCompositor.composite( data: data, width: width, height: height, layers: any( named: 'layers', that: isA<List<Map<String, dynamic>>>().having( (m) => m.first['assetPath'], 'assetPath', layers.first.assetPath, ), ), aspectRatio: aspectRatio, ), ).called(1); }); test('throws CompositePhotoException when compositor fails', () async { when( () => imageCompositor.composite( data: any(named: 'data'), width: any(named: 'width'), height: any(named: 'height'), layers: any(named: 'layers'), aspectRatio: any(named: 'aspectRatio'), ), ).thenThrow(Exception('oops')); expect( () => photosRepository.composite( width: width, height: height, data: data, layers: layers, aspectRatio: aspectRatio, ), throwsA( isA<CompositePhotoException>().having( (e) => e.toString(), 'toString', contains('compositing photo failed.'), ), ), ); }); }); }); }
photobooth/packages/photos_repository/test/photos_repository_test.dart/0
{ "file_path": "photobooth/packages/photos_repository/test/photos_repository_test.dart", "repo_id": "photobooth", "token_count": 3609 }
1,088
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/footer/footer.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import '../../helpers/helpers.dart'; void main() { group('WhiteFooter', () { testWidgets('renders Footer with white text color', (tester) async { await tester.pumpApp(WhiteFooter()); final footer = tester.widget<Footer>(find.byType(Footer)); expect(footer.textColor, PhotoboothColors.white); }); }); group('BlackFooter', () { testWidgets('renders Footer with black text color', (tester) async { await tester.pumpApp(BlackFooter()); final footer = tester.widget<Footer>(find.byType(Footer)); expect(footer.textColor, PhotoboothColors.black); }); }); group('Footer', () { testWidgets('renders column when screen is small', (tester) async { tester.setDisplaySize(const Size(320, 800)); await tester.pumpApp(Footer(textColor: PhotoboothColors.black)); expect(find.byKey(const Key('footer_column')), findsOneWidget); }); testWidgets('renders row when screen is big', (tester) async { tester.setDisplaySize(const Size(1920, 1080)); await tester.pumpApp(Footer(textColor: PhotoboothColors.black)); expect(find.byKey(const Key('footer_row')), findsOneWidget); }); testWidgets('renders FooterGoogleIOLink widget', (tester) async { await tester.pumpApp(Footer(textColor: PhotoboothColors.black)); expect(find.byType(FooterGoogleIOLink), findsOneWidget); }); testWidgets('renders FooterCodelabLink widget', (tester) async { await tester.pumpApp(Footer(textColor: PhotoboothColors.black)); expect(find.byType(FooterCodelabLink), findsOneWidget); }); testWidgets('renders FooterHowItsMadeLink widget', (tester) async { await tester.pumpApp(Footer(textColor: PhotoboothColors.black)); expect(find.byType(FooterHowItsMadeLink), findsOneWidget); }); testWidgets('renders FooterTermsOfServiceLink widget', (tester) async { await tester.pumpApp(Footer(textColor: PhotoboothColors.black)); expect(find.byType(FooterTermsOfServiceLink), findsOneWidget); }); testWidgets('renders FooterPrivacyPolicyLink widget', (tester) async { await tester.pumpApp(Footer(textColor: PhotoboothColors.black)); expect(find.byType(FooterPrivacyPolicyLink), findsOneWidget); }); }); }
photobooth/test/app/widgets/footer_test.dart/0
{ "file_path": "photobooth/test/app/widgets/footer_test.dart", "repo_id": "photobooth", "token_count": 950 }
1,089
// ignore_for_file: prefer_const_constructors import 'package:camera/camera.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import '../../helpers/helpers.dart'; class FakePhotoboothEvent extends Fake implements PhotoboothEvent {} class FakePhotoboothState extends Fake implements PhotoboothState {} void main() { const width = 1; const height = 1; const data = ''; const image = CameraImage(width: width, height: height, data: data); late PhotoboothBloc photoboothBloc; setUpAll(() { registerFallbackValue(FakePhotoboothEvent()); registerFallbackValue(FakePhotoboothState()); }); setUp(() { photoboothBloc = MockPhotoboothBloc(); when(() => photoboothBloc.state).thenReturn(PhotoboothState(image: image)); }); group('PhotoboothPhoto', () { testWidgets('displays PreviewImage', (tester) async { await tester.pumpApp( PhotoboothPhoto(image: data), photoboothBloc: photoboothBloc, ); expect(find.byType(PreviewImage), findsOneWidget); }); testWidgets('displays CharactersLayer', (tester) async { await tester.pumpApp( PhotoboothPhoto(image: data), photoboothBloc: photoboothBloc, ); expect(find.byType(CharactersLayer), findsOneWidget); }); testWidgets('displays StickersLayer', (tester) async { await tester.pumpApp( PhotoboothPhoto(image: data), photoboothBloc: photoboothBloc, ); expect(find.byType(StickersLayer), findsOneWidget); }); }); }
photobooth/test/photobooth/widgets/photobooth_photo_test.dart/0
{ "file_path": "photobooth/test/photobooth/widgets/photobooth_photo_test.dart", "repo_id": "photobooth", "token_count": 633 }
1,090
// ignore_for_file: prefer_const_constructors import 'dart:typed_data'; import 'package:bloc_test/bloc_test.dart'; import 'package:cross_file/cross_file.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:mocktail/mocktail.dart'; import 'package:platform_helper/platform_helper.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import '../../helpers/helpers.dart'; class MockPlatformHelper extends Mock implements PlatformHelper {} class MockUrlLauncher extends Mock with MockPlatformInterfaceMixin implements UrlLauncherPlatform {} class MockXFile extends Mock implements XFile {} void main() { const shareUrl = 'http://share-url.com'; final bytes = Uint8List.fromList([]); late ShareBloc shareBloc; late PlatformHelper platformHelper; late XFile file; late UrlLauncherPlatform originalUrlLauncher; setUpAll(() { registerFallbackValue(FakeShareEvent()); registerFallbackValue(FakeShareState()); registerFallbackValue(const LaunchOptions()); }); setUp(() { shareBloc = MockShareBloc(); when(() => shareBloc.state).thenReturn(ShareState()); file = MockXFile(); platformHelper = MockPlatformHelper(); originalUrlLauncher = UrlLauncherPlatform.instance; }); tearDown(() { UrlLauncherPlatform.instance = originalUrlLauncher; }); group('ShareStateListener', () { group('error', () { testWidgets( 'displays ShareErrorBottomSheet ' 'when ShareBloc emits error ' 'and platform is mobile', (tester) async { whenListen( shareBloc, Stream.fromIterable([ ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.loading, file: file, bytes: bytes, ), ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.failure, file: file, bytes: bytes, ), ]), ); when(() => platformHelper.isMobile).thenReturn(true); await tester.pumpApp( ShareStateListener( platformHelper: platformHelper, child: SizedBox(), ), shareBloc: shareBloc, ); await tester.pumpAndSettle(); expect(find.byType(ShareErrorBottomSheet), findsOneWidget); }); testWidgets( 'displays ShareErrorDialog ' 'when ShareBloc emits error ' 'and platform is not mobile and it is landscape', (tester) async { whenListen( shareBloc, Stream.fromIterable([ ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.loading, file: file, bytes: bytes, ), ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.failure, file: file, bytes: bytes, ), ]), ); when(() => platformHelper.isMobile).thenReturn(false); tester.setLandscapeDisplaySize(); await tester.pumpApp( ShareStateListener( platformHelper: platformHelper, child: SizedBox(), ), shareBloc: shareBloc, ); await tester.pumpAndSettle(); expect(find.byType(ShareErrorDialog), findsOneWidget); }); testWidgets( 'does not display ShareErrorBottomSheet ' 'when ShareBloc emits state other than error ' 'and platform is mobile', (tester) async { whenListen( shareBloc, Stream.fromIterable([ ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.loading, file: file, bytes: bytes, ), ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.success, file: file, bytes: bytes, twitterShareUrl: shareUrl, facebookShareUrl: shareUrl, ), ]), ); when(() => platformHelper.isMobile).thenReturn(true); await tester.pumpApp( ShareStateListener( platformHelper: platformHelper, child: SizedBox(), ), shareBloc: shareBloc, ); await tester.pumpAndSettle(); expect(find.byType(ShareErrorBottomSheet), findsNothing); }); testWidgets( 'does not display ShareErrorDialog ' 'when ShareBloc emits state different than error ' 'and platform is desktop', (tester) async { whenListen( shareBloc, Stream.fromIterable([ShareState()]), ); when(() => platformHelper.isMobile).thenReturn(false); await tester.pumpApp( ShareStateListener( platformHelper: platformHelper, child: SizedBox(), ), shareBloc: shareBloc, ); await tester.pumpAndSettle(); expect(find.byType(ShareErrorDialog), findsNothing); }); }); group('success', () { testWidgets( 'opens share link ' 'when ShareBloc emits success', (tester) async { final mock = MockUrlLauncher(); UrlLauncherPlatform.instance = mock; when(() => mock.canLaunch(any())).thenAnswer((_) async => true); when(() => mock.launchUrl(shareUrl, any())) .thenAnswer((_) async => true); whenListen( shareBloc, Stream.fromIterable([ ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.loading, file: file, bytes: bytes, ), ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.success, shareUrl: ShareUrl.twitter, file: file, bytes: bytes, twitterShareUrl: shareUrl, facebookShareUrl: shareUrl, ), ]), ); await tester.pumpApp( ShareStateListener(child: SizedBox()), shareBloc: shareBloc, ); await tester.pumpAndSettle(); verify(() => mock.launchUrl(shareUrl, any())).called(1); }); }); }); }
photobooth/test/share/widgets/share_state_listener_test.dart/0
{ "file_path": "photobooth/test/share/widgets/share_state_listener_test.dart", "repo_id": "photobooth", "token_count": 3092 }
1,091
{ "firestore": { "rules": "firestore.rules" }, "hosting": { "public": "build/web", "site": "", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "headers": [ { "source": "**/*.@(jpg|jpeg|gif|png)", "headers": [ { "key": "Cache-Control", "value": "max-age=3600" } ] }, { "source": "**", "headers": [ { "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" } ] } ] }, "storage": { "rules": "storage.rules" } }
pinball/firebase.json/0
{ "file_path": "pinball/firebase.json", "repo_id": "pinball", "token_count": 365 }
1,092
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/select_character/select_character.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Spawns a new [Ball] into the game when all balls are lost and still /// [GameStatus.playing]. class BallSpawningBehavior extends Component with FlameBlocListenable<GameBloc, GameState>, HasGameRef { @override bool listenWhen(GameState? previousState, GameState newState) { if (!newState.status.isPlaying) return false; final startedGame = (previousState?.status.isWaiting ?? true) || (previousState?.status.isGameOver ?? true); final lostRound = (previousState?.rounds ?? newState.rounds + 1) > newState.rounds; return startedGame || lostRound; } @override void onNewState(GameState state) { final plunger = gameRef.descendants().whereType<Plunger>().single; final canvas = gameRef.descendants().whereType<ZCanvasComponent>().single; final characterTheme = readBloc<CharacterThemeCubit, CharacterThemeState>() .state .characterTheme; final ball = Ball(assetPath: characterTheme.ball.keyName) ..initialPosition = Vector2( plunger.body.position.x, plunger.body.position.y - Ball.size.y, ) ..layer = Layer.launcher ..zIndex = ZIndexes.ballOnLaunchRamp; canvas.add(ball); } }
pinball/lib/game/behaviors/ball_spawning_behavior.dart/0
{ "file_path": "pinball/lib/game/behaviors/ball_spawning_behavior.dart", "repo_id": "pinball", "token_count": 539 }
1,093
export 'android_spaceship_bonus_behavior.dart'; export 'ramp_bonus_behavior.dart'; export 'ramp_multiplier_behavior.dart'; export 'ramp_progress_behavior.dart'; export 'ramp_reset_behavior.dart'; export 'ramp_shot_behavior.dart';
pinball/lib/game/components/android_acres/behaviors/behaviors.dart/0
{ "file_path": "pinball/lib/game/components/android_acres/behaviors/behaviors.dart", "repo_id": "pinball", "token_count": 84 }
1,094
import 'package:flame/components.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template leaderboard_failure_display} /// Display showing an error message when the leaderboard couldn't be loaded /// {@endtemplate} class LeaderboardFailureDisplay extends Component { /// {@macro leaderboard_failure_display} LeaderboardFailureDisplay(); @override Future<void> onLoad() async { final l10n = readProvider<AppLocalizations>(); await add( ErrorComponent( label: l10n.leaderboardErrorMessage, position: Vector2(0, -18), ), ); } }
pinball/lib/game/components/backbox/displays/leaderboard_failure_display.dart/0
{ "file_path": "pinball/lib/game/components/backbox/displays/leaderboard_failure_display.dart", "repo_id": "pinball", "token_count": 240 }
1,095
import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:pinball/game/behaviors/behaviors.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Adds a [GameBonus.googleWord] when all [GoogleLetter]s are activated. class GoogleWordBonusBehavior extends Component { @override Future<void> onLoad() async { await super.onLoad(); await add( FlameBlocListener<GoogleWordCubit, GoogleWordState>( listenWhen: (_, state) => state.letterSpriteStates.values .every((element) => element == GoogleLetterSpriteState.lit), onNewState: (_) { readBloc<GameBloc, GameState>() .add(const BonusActivated(GameBonus.googleWord)); readBloc<GoogleWordCubit, GoogleWordState>().onReset(); add(BonusBallSpawningBehavior()); add(GoogleWordAnimatingBehavior()); }, ), ); } }
pinball/lib/game/components/google_gallery/behaviors/google_word_bonus_behavior.dart/0
{ "file_path": "pinball/lib/game/components/google_gallery/behaviors/google_word_bonus_behavior.dart", "repo_id": "pinball", "token_count": 399 }
1,096
export 'pinball_game_page.dart'; export 'widgets/widgets.dart';
pinball/lib/game/view/view.dart/0
{ "file_path": "pinball/lib/game/view/view.dart", "repo_id": "pinball", "token_count": 25 }
1,097
import 'package:flutter/widgets.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; export 'package:flutter_gen/gen_l10n/app_localizations.dart'; extension AppLocalizationsX on BuildContext { AppLocalizations get l10n => AppLocalizations.of(this); }
pinball/lib/l10n/l10n.dart/0
{ "file_path": "pinball/lib/l10n/l10n.dart", "repo_id": "pinball", "token_count": 95 }
1,098
include: package:very_good_analysis/analysis_options.2.4.0.yaml
pinball/packages/leaderboard_repository/analysis_options.yaml/0
{ "file_path": "pinball/packages/leaderboard_repository/analysis_options.yaml", "repo_id": "pinball", "token_count": 22 }
1,099
name: pinball_audio description: Package with the sound manager for the pinball game version: 1.0.0+1 publish_to: none environment: sdk: ">=2.16.0 <3.0.0" dependencies: audioplayers: ^0.20.1 clock: ^1.1.0 flame_audio: ^1.0.1 flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter mocktail: ^0.3.0 very_good_analysis: ^2.4.0 flutter_gen: line_length: 80 assets: package_parameter_enabled: true flutter: assets: - assets/sfx/ - assets/music/
pinball/packages/pinball_audio/pubspec.yaml/0
{ "file_path": "pinball/packages/pinball_audio/pubspec.yaml", "repo_id": "pinball", "token_count": 221 }
1,100
// ignore_for_file: public_member_api_docs import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class AndroidAnimatronicBallContactBehavior extends ContactBehavior<AndroidAnimatronic> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; readBloc<AndroidSpaceshipCubit, AndroidSpaceshipState>().onBallContacted(); } }
pinball/packages/pinball_components/lib/src/components/android_animatronic/behaviors/android_animatronic_ball_contact_behavior.dart.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/android_animatronic/behaviors/android_animatronic_ball_contact_behavior.dart.dart", "repo_id": "pinball", "token_count": 176 }
1,101
import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// Scales the ball's gravity according to its position on the board. class BallGravitatingBehavior extends Component with ParentIsA<Ball>, HasGameRef<Forge2DGame> { @override void update(double dt) { super.update(dt); final defaultGravity = gameRef.world.gravity.y; final maxXDeviationFromCenter = BoardDimensions.bounds.width / 2; const maxXGravityPercentage = (1 - BoardDimensions.perspectiveShrinkFactor) / 2; final xDeviationFromCenter = parent.body.position.x; final positionalXForce = ((xDeviationFromCenter / maxXDeviationFromCenter) * maxXGravityPercentage) * defaultGravity; final positionalYForce = math.sqrt( math.pow(defaultGravity, 2) - math.pow(positionalXForce, 2), ); final gravityOverride = parent.body.gravityOverride; if (gravityOverride != null) { gravityOverride.setValues(positionalXForce, positionalYForce); } else { parent.body.gravityOverride = Vector2(positionalXForce, positionalYForce); } } }
pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_gravitating_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/ball/behaviors/ball_gravitating_behavior.dart", "repo_id": "pinball", "token_count": 449 }
1,102
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template chrome_dino_mouth_opening_behavior} /// Allows a [Ball] to enter the [ChromeDino] mouth when it is open. /// {@endtemplate} class ChromeDinoMouthOpeningBehavior extends ContactBehavior<ChromeDino> { @override void preSolve(Object other, Contact contact, Manifold oldManifold) { super.preSolve(other, contact, oldManifold); if (other is! Ball) return; if (parent.bloc.state.isMouthOpen && parent.firstChild<Ball>() == null) { contact.setEnabled(false); } } }
pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_mouth_opening_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/chrome_dino/behaviors/chrome_dino_mouth_opening_behavior.dart", "repo_id": "pinball", "token_count": 237 }
1,103
import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; class FlapperSpinningBehavior extends ContactBehavior<FlapperEntrance> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; parent.parent?.firstChild<SpriteAnimationComponent>()?.playing = true; } }
pinball/packages/pinball_components/lib/src/components/flapper/behaviors/flapper_spinning_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/flapper/behaviors/flapper_spinning_behavior.dart", "repo_id": "pinball", "token_count": 164 }
1,104
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:pinball_components/pinball_components.dart'; part 'google_word_state.dart'; class GoogleWordCubit extends Cubit<GoogleWordState> { GoogleWordCubit() : super(GoogleWordState.initial()); static const _lettersInGoogle = 6; int _lastLitLetter = 0; void onRolloverContacted() { final spriteStatesMap = {...state.letterSpriteStates}; if (_lastLitLetter < _lettersInGoogle) { spriteStatesMap.update( _lastLitLetter, (_) => GoogleLetterSpriteState.lit, ); emit(GoogleWordState(letterSpriteStates: spriteStatesMap)); _lastLitLetter++; } } void switched() { switch (state.letterSpriteStates[0]!) { case GoogleLetterSpriteState.lit: emit( GoogleWordState( letterSpriteStates: { for (int i = 0; i < _lettersInGoogle; i++) if (i.isEven) i: GoogleLetterSpriteState.dimmed else i: GoogleLetterSpriteState.lit }, ), ); break; case GoogleLetterSpriteState.dimmed: emit( GoogleWordState( letterSpriteStates: { for (int i = 0; i < _lettersInGoogle; i++) if (i.isEven) i: GoogleLetterSpriteState.lit else i: GoogleLetterSpriteState.dimmed }, ), ); break; } } void onBonusAwarded() { emit( GoogleWordState( letterSpriteStates: { for (int i = 0; i < _lettersInGoogle; i++) if (i.isEven) i: GoogleLetterSpriteState.lit else i: GoogleLetterSpriteState.dimmed }, ), ); } void onReset() { emit(GoogleWordState.initial()); _lastLitLetter = 0; } }
pinball/packages/pinball_components/lib/src/components/google_word/cubit/google_word_cubit.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/google_word/cubit/google_word_cubit.dart", "repo_id": "pinball", "token_count": 941 }
1,105
import 'package:flame/components.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template multiball_blinking_behavior} /// Makes a [Multiball] blink back to [MultiballLightState.lit] when /// [MultiballLightState.dimmed]. /// {@endtemplate} class MultiballBlinkingBehavior extends TimerComponent with ParentIsA<Multiball> { /// {@macro multiball_blinking_behavior} MultiballBlinkingBehavior() : super(period: 0.18); final _maxBlinks = 28; int _blinksCounter = 0; bool _isAnimating = false; void _onNewState(MultiballState state) { final animationEnabled = state.animationState == MultiballAnimationState.blinking; final canBlink = _blinksCounter < _maxBlinks; if (animationEnabled && canBlink) { _start(); } else { _stop(); } } void _start() { if (!_isAnimating) { _isAnimating = true; timer ..reset() ..start(); _animate(); } } void _animate() { parent.bloc.onBlink(); _blinksCounter++; } void _stop() { if (_isAnimating) { _isAnimating = false; timer.stop(); _blinksCounter = 0; parent.bloc.onStop(); } } @override Future<void> onLoad() async { await super.onLoad(); parent.bloc.stream.listen(_onNewState); } @override void onTick() { super.onTick(); if (!_isAnimating) { timer.stop(); } else { if (_blinksCounter < _maxBlinks) { _animate(); timer ..reset() ..start(); } else { timer.stop(); } } } }
pinball/packages/pinball_components/lib/src/components/multiball/behaviors/multiball_blinking_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/multiball/behaviors/multiball_blinking_behavior.dart", "repo_id": "pinball", "token_count": 699 }
1,106
import 'package:flame/components.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/pinball_components.dart' hide Assets; import 'package:pinball_flame/pinball_flame.dart'; /// {@template rocket_sprite_component} /// A [SpriteComponent] for the rocket over [Plunger]. /// {@endtemplate} class RocketSpriteComponent extends SpriteComponent with HasGameRef, ZIndex { /// {@macro rocket_sprite_component} RocketSpriteComponent() : super(anchor: Anchor.center) { zIndex = ZIndexes.rocket; } @override Future<void> onLoad() async { await super.onLoad(); final sprite = Sprite( gameRef.images.fromCache( Assets.images.plunger.rocket.keyName, ), ); this.sprite = sprite; size = sprite.originalSize / 10; } }
pinball/packages/pinball_components/lib/src/components/rocket.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/rocket.dart", "repo_id": "pinball", "token_count": 288 }
1,107
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart'; /// {@template ramp_ball_ascending_contact_behavior} /// Detects an ascending [Ball] that enters into the [SpaceshipRamp]. /// /// The [Ball] can hit with sensor to recognize if a [Ball] goes into or out of /// the [SpaceshipRamp]. /// {@endtemplate} class RampBallAscendingContactBehavior extends ContactBehavior<SpaceshipRampBoardOpening> { @override void beginContact(Object other, Contact contact) { super.beginContact(other, contact); if (other is! Ball) return; if (other.body.linearVelocity.y < 0) { readBloc<SpaceshipRampCubit, SpaceshipRampState>() .onAscendingBallEntered(); } } }
pinball/packages/pinball_components/lib/src/components/spaceship_ramp/behavior/ramp_ball_ascending_contact_behavior.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/spaceship_ramp/behavior/ramp_ball_ascending_contact_behavior.dart", "repo_id": "pinball", "token_count": 281 }
1,108
/// Z-Indexes for the component rendering order in the pinball game. abstract class ZIndexes { static const _base = 0; static const _above = 1; static const _below = -1; // Ball static const ballOnBoard = _base; static const ballOnSpaceshipRamp = _above + spaceshipRampBackgroundRailing; static const ballOnSpaceship = _above + spaceshipSaucer; static const ballOnSpaceshipRail = _above + spaceshipRail; static const ballOnLaunchRamp = _above + launchRamp; // Background static const arcadeBackground = _below + boardBackground; static const boardBackground = 5 * _below + _base; static const decal = _above + boardBackground; // Boundaries static const bottomBoundary = _above + dinoBottomWall; static const outerBoundary = _above + boardBackground; static const outerBottomBoundary = _above + bottomBoundary; // Bottom Group static const bottomGroup = _above + ballOnBoard; // Launcher static const launchRamp = _above + outerBoundary; static const launchRampForegroundRailing = _above + ballOnLaunchRamp; static const flapperBack = _above + outerBoundary; static const flapperFront = _above + flapper; static const flapper = _above + ballOnLaunchRamp; static const plunger = _above + launchRamp; static const rocket = _below + bottomBoundary; // Dino Desert static const dinoTopWall = _above + ballOnBoard; static const dinoTopWallTunnel = _below + ballOnBoard; static const dino = _above + dinoTopWall; static const dinoBottomWall = _above + dino; static const slingshots = _above + dinoBottomWall; // Flutter Forest static const flutterForest = _above + ballOnBoard; // Sparky Scorch static const computerBase = _below + ballOnBoard; static const computerTop = _above + ballOnBoard; static const computerGlow = _above + computerTop; static const sparkyAnimatronic = _above + spaceshipRampForegroundRailing; static const sparkyBumper = _above + ballOnBoard; static const turboChargeFlame = _above + ballOnBoard; // Android Acres static const spaceshipRail = _above + bottomGroup; static const spaceshipRailExit = _above + ballOnSpaceshipRail; static const spaceshipSaucer = _above + ballOnSpaceshipRail; static const spaceshipLightBeam = _below + spaceshipSaucer; static const androidHead = _above + ballOnSpaceship; static const spaceshipRamp = _above + sparkyBumper; static const spaceshipRampBackgroundRailing = _above + spaceshipRamp; static const spaceshipRampArrow = _above + spaceshipRamp; static const spaceshipRampForegroundRailing = _above + ballOnSpaceshipRamp; static const spaceshipRampBoardOpening = _below + ballOnBoard; static const androidBumper = _above + ballOnBoard; // Score static const score = _above + sparkyAnimatronic; // Debug information static const debugInfo = _above + score; // Backbox static const backbox = _below + outerBoundary; }
pinball/packages/pinball_components/lib/src/components/z_indexes.dart/0
{ "file_path": "pinball/packages/pinball_components/lib/src/components/z_indexes.dart", "repo_id": "pinball", "token_count": 830 }
1,109
import 'dart:async'; import 'package:flame/extensions.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class AndroidBumperAGame extends BallGame { AndroidBumperAGame() : super( imagesFileNames: [ Assets.images.android.bumper.a.lit.keyName, Assets.images.android.bumper.a.dimmed.keyName, ], ); static const description = ''' Shows how a AndroidBumperA is rendered. - Activate the "trace" parameter to overlay the body. '''; @override Future<void> onLoad() async { await super.onLoad(); camera.followVector2(Vector2.zero()); await add( AndroidBumper.a()..priority = 1, ); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_bumper_a_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/android_acres/android_bumper_a_game.dart", "repo_id": "pinball", "token_count": 311 }
1,110
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/bottom_group/baseboard_game.dart'; import 'package:sandbox/stories/bottom_group/flipper_game.dart'; import 'package:sandbox/stories/bottom_group/kicker_game.dart'; void addBottomGroupStories(Dashbook dashbook) { dashbook.storiesOf('Bottom Group') ..addGame( title: 'Flipper', description: FlipperGame.description, gameBuilder: (_) => FlipperGame(), ) ..addGame( title: 'Kicker', description: KickerGame.description, gameBuilder: (_) => KickerGame(), ) ..addGame( title: 'Baseboard', description: BaseboardGame.description, gameBuilder: (_) => BaseboardGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/bottom_group/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/bottom_group/stories.dart", "repo_id": "pinball", "token_count": 289 }
1,111
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class GoogleLetterGame extends BallGame { GoogleLetterGame() : super( imagesFileNames: [ Assets.images.googleWord.letter1.lit.keyName, Assets.images.googleWord.letter1.dimmed.keyName, ], ); static const description = ''' Shows how a GoogleLetter is rendered. - 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(GoogleLetter(0)); await traceAllBodies(); } }
pinball/packages/pinball_components/sandbox/lib/stories/google_word/google_letter_game.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/google_word/google_letter_game.dart", "repo_id": "pinball", "token_count": 292 }
1,112
import 'package:dashbook/dashbook.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/sparky_scorch/sparky_bumper_game.dart'; import 'package:sandbox/stories/sparky_scorch/sparky_computer_game.dart'; void addSparkyScorchStories(Dashbook dashbook) { dashbook.storiesOf('Sparky Scorch') ..addGame( title: 'Sparky Computer', description: SparkyComputerGame.description, gameBuilder: (_) => SparkyComputerGame(), ) ..addGame( title: 'Sparky Bumper', description: SparkyBumperGame.description, gameBuilder: (_) => SparkyBumperGame(), ); }
pinball/packages/pinball_components/sandbox/lib/stories/sparky_scorch/stories.dart/0
{ "file_path": "pinball/packages/pinball_components/sandbox/lib/stories/sparky_scorch/stories.dart", "repo_id": "pinball", "token_count": 244 }
1,113
// ignore_for_file: cascade_invocations import 'package:bloc_test/bloc_test.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/android_bumper/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockBall extends Mock implements Ball {} class _MockContact extends Mock implements Contact {} class _MockAndroidBumperCubit extends Mock implements AndroidBumperCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'AndroidBumperBallContactBehavior', () { test('can be instantiated', () { expect( AndroidBumperBallContactBehavior(), isA<AndroidBumperBallContactBehavior>(), ); }); flameTester.test( 'beginContact emits onBallContacted when contacts with a ball', (game) async { final behavior = AndroidBumperBallContactBehavior(); final bloc = _MockAndroidBumperCubit(); whenListen( bloc, const Stream<AndroidBumperState>.empty(), initialState: AndroidBumperState.lit, ); final androidBumper = AndroidBumper.test(bloc: bloc); await androidBumper.add(behavior); await game.ensureAdd(androidBumper); behavior.beginContact(_MockBall(), _MockContact()); verify(androidBumper.bloc.onBallContacted).called(1); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/android_bumper/behaviors/android_bumper_ball_contact_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/android_bumper/behaviors/android_bumper_ball_contact_behavior_test.dart", "repo_id": "pinball", "token_count": 671 }
1,114
// ignore_for_file: cascade_invocations import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; import '../../helpers/helpers.dart'; void main() { group('Baseboard', () { TestWidgetsFlutterBinding.ensureInitialized(); final assets = [ Assets.images.baseboard.left.keyName, Assets.images.baseboard.right.keyName, ]; final flameTester = FlameTester(() => TestGame(assets)); flameTester.testGameWidget( 'renders correctly', setUp: (game, tester) async { await game.images.loadAll(assets); final leftBaseboard = Baseboard( side: BoardSide.left, )..initialPosition = Vector2(-20, 0); final rightBaseboard = Baseboard( side: BoardSide.right, )..initialPosition = Vector2(20, 0); await game.ensureAddAll([leftBaseboard, rightBaseboard]); game.camera.followVector2(Vector2.zero()); await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/baseboard.png'), ); }, ); flameTester.test( 'loads correctly', (game) async { await game.ready(); final leftBaseboard = Baseboard( side: BoardSide.left, ); final rightBaseboard = Baseboard( side: BoardSide.right, ); await game.ensureAddAll([leftBaseboard, rightBaseboard]); expect(game.contains(leftBaseboard), isTrue); expect(game.contains(rightBaseboard), isTrue); }, ); group('body', () { flameTester.test( 'is static', (game) async { final baseboard = Baseboard( side: BoardSide.left, ); await game.ensureAdd(baseboard); expect(baseboard.body.bodyType, equals(BodyType.static)); }, ); flameTester.test( 'is at an angle', (game) async { final leftBaseboard = Baseboard( side: BoardSide.left, ); final rightBaseboard = Baseboard( side: BoardSide.right, ); await game.ensureAddAll([leftBaseboard, rightBaseboard]); expect(leftBaseboard.body.angle, isPositive); expect(rightBaseboard.body.angle, isNegative); }, ); }); group('fixtures', () { flameTester.test( 'has seven', (game) async { final baseboard = Baseboard( side: BoardSide.left, ); await game.ensureAdd(baseboard); expect(baseboard.body.fixtures.length, equals(7)); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/baseboard_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/baseboard_test.dart", "repo_id": "pinball", "token_count": 1286 }
1,115
// ignore_for_file: cascade_invocations import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; class _TestGame extends Forge2DGame { @override Future<void> onLoad() async { images.prefix = ''; await images.loadAll([ Assets.images.googleWord.letter1.lit.keyName, Assets.images.googleWord.letter1.dimmed.keyName, Assets.images.googleWord.letter2.lit.keyName, Assets.images.googleWord.letter2.dimmed.keyName, Assets.images.googleWord.letter3.lit.keyName, Assets.images.googleWord.letter3.dimmed.keyName, Assets.images.googleWord.letter4.lit.keyName, Assets.images.googleWord.letter4.dimmed.keyName, Assets.images.googleWord.letter5.lit.keyName, Assets.images.googleWord.letter5.dimmed.keyName, Assets.images.googleWord.letter6.lit.keyName, Assets.images.googleWord.letter6.dimmed.keyName, ]); } Future<void> pump(GoogleLetter child) async { await ensureAdd( FlameBlocProvider<GoogleWordCubit, GoogleWordState>.value( value: GoogleWordCubit(), children: [child], ), ); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(_TestGame.new); group('Google Letter', () { test('can be instantiated', () { expect(GoogleLetter(0), isA<GoogleLetter>()); }); flameTester.test( '0th loads correctly', (game) async { final googleLetter = GoogleLetter(0); await game.pump(googleLetter); expect(game.descendants().contains(googleLetter), isTrue); }, ); flameTester.test( '1st loads correctly', (game) async { final googleLetter = GoogleLetter(1); await game.pump(googleLetter); expect(game.descendants().contains(googleLetter), isTrue); }, ); flameTester.test( '2nd loads correctly', (game) async { final googleLetter = GoogleLetter(2); await game.pump(googleLetter); expect(game.descendants().contains(googleLetter), isTrue); }, ); flameTester.test( '3d loads correctly', (game) async { final googleLetter = GoogleLetter(3); await game.pump(googleLetter); expect(game.descendants().contains(googleLetter), isTrue); }, ); flameTester.test( '4th loads correctly', (game) async { final googleLetter = GoogleLetter(4); await game.pump(googleLetter); expect(game.descendants().contains(googleLetter), isTrue); }, ); flameTester.test( '5th loads correctly', (game) async { final googleLetter = GoogleLetter(5); await game.pump(googleLetter); expect(game.descendants().contains(googleLetter), isTrue); }, ); test('throws error when index out of range', () { expect(() => GoogleLetter(-1), throwsA(isA<RangeError>())); expect(() => GoogleLetter(6), throwsA(isA<RangeError>())); }); group('sprite', () { const firstLetterLitState = GoogleWordState( letterSpriteStates: { 0: GoogleLetterSpriteState.lit, 1: GoogleLetterSpriteState.dimmed, 2: GoogleLetterSpriteState.dimmed, 3: GoogleLetterSpriteState.dimmed, 4: GoogleLetterSpriteState.dimmed, 5: GoogleLetterSpriteState.dimmed, }, ); flameTester.test( "listens when its index's state changes", (game) async { final googleLetter = GoogleLetter(0); await game.pump(googleLetter); expect( googleLetter.listenWhen( GoogleWordState.initial(), firstLetterLitState, ), isTrue, ); }, ); flameTester.test( 'changes current sprite onNewState', (game) async { final googleLetter = GoogleLetter(0); await game.pump(googleLetter); final originalSprite = googleLetter.current; googleLetter.onNewState(firstLetterLitState); await game.ready(); final newSprite = googleLetter.current; expect(newSprite, isNot(equals(originalSprite))); }, ); }); }); }
pinball/packages/pinball_components/test/src/components/google_letter_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/google_letter_test.dart", "repo_id": "pinball", "token_count": 1885 }
1,116
// ignore_for_file: prefer_const_constructors, cascade_invocations import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/multiball/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockMultiballCubit extends Mock implements MultiballCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'MultiballBlinkingBehavior', () { flameTester.testGameWidget( 'calls onBlink every 0.18 seconds when animation state is animated', setUp: (game, tester) async { final behavior = MultiballBlinkingBehavior(); final bloc = _MockMultiballCubit(); final streamController = StreamController<MultiballState>(); whenListen( bloc, streamController.stream, initialState: MultiballState.initial(), ); final multiball = Multiball.test(bloc: bloc); await multiball.add(behavior); await game.ensureAdd(multiball); streamController.add( MultiballState( animationState: MultiballAnimationState.blinking, lightState: MultiballLightState.lit, ), ); await tester.pump(); game.update(0); verify(bloc.onBlink).called(1); await tester.pump(); game.update(0.18); await streamController.close(); verify(bloc.onBlink).called(1); }, ); flameTester.testGameWidget( 'calls onStop when animation state is stopped', setUp: (game, tester) async { final behavior = MultiballBlinkingBehavior(); final bloc = _MockMultiballCubit(); final streamController = StreamController<MultiballState>(); whenListen( bloc, streamController.stream, initialState: MultiballState.initial(), ); when(bloc.onBlink).thenAnswer((_) async {}); final multiball = Multiball.test(bloc: bloc); await multiball.add(behavior); await game.ensureAdd(multiball); streamController.add( MultiballState( animationState: MultiballAnimationState.blinking, lightState: MultiballLightState.lit, ), ); await tester.pump(); streamController.add( MultiballState( animationState: MultiballAnimationState.idle, lightState: MultiballLightState.lit, ), ); await streamController.close(); verify(bloc.onStop).called(1); }, ); flameTester.testGameWidget( 'onTick stops when there is no animation', setUp: (game, tester) async { final behavior = MultiballBlinkingBehavior(); final bloc = _MockMultiballCubit(); final streamController = StreamController<MultiballState>(); whenListen( bloc, streamController.stream, initialState: MultiballState.initial(), ); when(bloc.onBlink).thenAnswer((_) async {}); final multiball = Multiball.test(bloc: bloc); await multiball.add(behavior); await game.ensureAdd(multiball); streamController.add( MultiballState( animationState: MultiballAnimationState.idle, lightState: MultiballLightState.lit, ), ); await tester.pump(); behavior.onTick(); expect(behavior.timer.isRunning(), false); }, ); flameTester.testGameWidget( 'onTick stops after 28 blinks', setUp: (game, tester) async { final behavior = MultiballBlinkingBehavior(); final bloc = _MockMultiballCubit(); final streamController = StreamController<MultiballState>(); whenListen( bloc, streamController.stream, initialState: MultiballState.initial(), ); when(bloc.onBlink).thenAnswer((_) async {}); final multiball = Multiball.test(bloc: bloc); await multiball.add(behavior); await game.ensureAdd(multiball); streamController.add( MultiballState( animationState: MultiballAnimationState.blinking, lightState: MultiballLightState.dimmed, ), ); await tester.pump(); for (var i = 0; i < 28; i++) { behavior.onTick(); } expect(behavior.timer.isRunning(), false); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/multiball/behaviors/multiball_blinking_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/multiball/behaviors/multiball_blinking_behavior_test.dart", "repo_id": "pinball", "token_count": 2316 }
1,117
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame/effects.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/score_component/behaviors/behaviors.dart'; import '../../../helpers/helpers.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester( () => TestGame([ Assets.images.score.fiveThousand.keyName, Assets.images.score.twentyThousand.keyName, Assets.images.score.twoHundredThousand.keyName, Assets.images.score.oneMillion.keyName, ]), ); group('ScoreComponent', () { test('can be instantiated', () { expect( ScoreComponent( points: Points.fiveThousand, position: Vector2.zero(), effectController: EffectController(duration: 1), ), isA<ScoreComponent>(), ); }); flameTester.testGameWidget( 'loads correctly', setUp: (game, tester) async { await game.onLoad(); game.camera.followVector2(Vector2.zero()); await game.ensureAdd( ScoreComponent( points: Points.oneMillion, position: Vector2.zero(), effectController: EffectController(duration: 1), ), ); }, verify: (game, tester) async { final texts = game.descendants().whereType<SpriteComponent>().length; expect(texts, equals(1)); }, ); flameTester.test( 'adds a ScoreComponentScalingBehavior', (game) async { await game.onLoad(); game.camera.followVector2(Vector2.zero()); final component = ScoreComponent( points: Points.oneMillion, position: Vector2.zero(), effectController: EffectController(duration: 1), ); await game.ensureAdd(component); expect( component.children.whereType<ScoreComponentScalingBehavior>().length, equals(1), ); }, ); flameTester.testGameWidget( 'has a movement effect', setUp: (game, tester) async { await game.onLoad(); game.camera.followVector2(Vector2.zero()); await game.ensureAdd( ScoreComponent.test( points: Points.oneMillion, position: Vector2.zero(), effectController: EffectController(duration: 1), ), ); game.update(0.5); await tester.pump(); }, verify: (game, tester) async { final text = game.descendants().whereType<SpriteComponent>().first; expect(text.firstChild<MoveEffect>(), isNotNull); }, ); flameTester.testGameWidget( 'is removed once finished', setUp: (game, tester) async { await game.onLoad(); game.camera.followVector2(Vector2.zero()); await game.ensureAdd( ScoreComponent.test( points: Points.oneMillion, position: Vector2.zero(), effectController: EffectController(duration: 1), ), ); game.update(1); game.update(0); // Ensure all component removals await tester.pump(); }, verify: (game, tester) async { expect(game.children.length, equals(0)); }, ); group('renders correctly', () { const goldensPath = '../golden/score/'; flameTester.testGameWidget( '5000 points', setUp: (game, tester) async { await game.onLoad(); await game.ensureAdd( ScoreComponent.test( points: Points.fiveThousand, position: Vector2.zero(), effectController: EffectController(duration: 1), ), ); game.camera ..followVector2(Vector2.zero()) ..zoom = 8; await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldensPath}5k.png'), ); }, ); flameTester.testGameWidget( '20000 points', setUp: (game, tester) async { await game.onLoad(); await game.ensureAdd( ScoreComponent.test( points: Points.twentyThousand, position: Vector2.zero(), effectController: EffectController(duration: 1), ), ); game.camera ..followVector2(Vector2.zero()) ..zoom = 8; await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldensPath}20k.png'), ); }, ); flameTester.testGameWidget( '200000 points', setUp: (game, tester) async { await game.onLoad(); await game.ensureAdd( ScoreComponent.test( points: Points.twoHundredThousand, position: Vector2.zero(), effectController: EffectController(duration: 1), ), ); game.camera ..followVector2(Vector2.zero()) ..zoom = 8; await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldensPath}200k.png'), ); }, ); flameTester.testGameWidget( '1000000 points', setUp: (game, tester) async { await game.onLoad(); await game.ensureAdd( ScoreComponent.test( points: Points.oneMillion, position: Vector2.zero(), effectController: EffectController(duration: 1), ), ); game.camera ..followVector2(Vector2.zero()) ..zoom = 8; await tester.pump(); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('${goldensPath}1m.png'), ); }, ); }); }); group('PointsX', () { test('5k value return 5000', () { expect(Points.fiveThousand.value, 5000); }); test('20k value return 20000', () { expect(Points.twentyThousand.value, 20000); }); test('200k value return 200000', () { expect(Points.twoHundredThousand.value, 200000); }); test('1m value return 1000000', () { expect(Points.oneMillion.value, 1000000); }); }); }
pinball/packages/pinball_components/test/src/components/score_component/score_component_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/score_component/score_component_test.dart", "repo_id": "pinball", "token_count": 3194 }
1,118
import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/src/components/sparky_bumper/behaviors/behaviors.dart'; import '../../../../helpers/helpers.dart'; class _MockSparkyBumperCubit extends Mock implements SparkyBumperCubit {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(TestGame.new); group( 'SparkyBumperBlinkingBehavior', () { flameTester.testGameWidget( 'calls onBlinked after 0.05 seconds when dimmed', setUp: (game, tester) async { final behavior = SparkyBumperBlinkingBehavior(); final bloc = _MockSparkyBumperCubit(); final streamController = StreamController<SparkyBumperState>(); whenListen( bloc, streamController.stream, initialState: SparkyBumperState.lit, ); final sparkyBumper = SparkyBumper.test(bloc: bloc); await sparkyBumper.add(behavior); await game.ensureAdd(sparkyBumper); streamController.add(SparkyBumperState.dimmed); await tester.pump(); game.update(0.05); await streamController.close(); verify(bloc.onBlinked).called(1); }, ); }, ); }
pinball/packages/pinball_components/test/src/components/sparky_bumper/behaviors/sparky_bumper_blinking_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_components/test/src/components/sparky_bumper/behaviors/sparky_bumper_blinking_behavior_test.dart", "repo_id": "pinball", "token_count": 637 }
1,119
import 'dart:ui'; import 'package:flame/components.dart'; import 'package:pinball_flame/src/canvas/canvas_wrapper.dart'; /// Called right before [Canvas.drawImageRect] is called. /// /// This is useful since [Sprite.render] uses [Canvas.drawImageRect] to draw /// the [Sprite]. typedef PaintFunction = void Function(Paint); /// {@template canvas_component} /// Allows listening before the rendering of [Sprite]s. /// /// The existence of this class is to hack around the fact that Flame doesn't /// provide a global way to modify the default [Paint] before rendering a /// [Sprite]. /// {@endtemplate} class CanvasComponent extends Component { /// {@macro canvas_component} CanvasComponent({ PaintFunction? onSpritePainted, Iterable<Component>? children, }) : _canvas = _Canvas(onSpritePainted: onSpritePainted), super(children: children); final _Canvas _canvas; @override void renderTree(Canvas canvas) { _canvas.canvas = canvas; super.renderTree(_canvas); } } class _Canvas extends CanvasWrapper { _Canvas({PaintFunction? onSpritePainted}) : _onSpritePainted = onSpritePainted; final PaintFunction? _onSpritePainted; @override void drawImageRect(Image image, Rect src, Rect dst, Paint paint) { _onSpritePainted?.call(paint); super.drawImageRect(image, src, dst, paint); } }
pinball/packages/pinball_flame/lib/src/canvas/canvas_component.dart/0
{ "file_path": "pinball/packages/pinball_flame/lib/src/canvas/canvas_component.dart", "repo_id": "pinball", "token_count": 451 }
1,120
// ignore_for_file: cascade_invocations import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_flame/pinball_flame.dart'; class _TestBodyComponent extends BodyComponent { @override Body createBody() { final shape = CircleShape()..radius = 1; return world.createBody(BodyDef())..createFixtureFromShape(shape); } } class _TestLayeredBodyComponent extends _TestBodyComponent with Layered { _TestLayeredBodyComponent({required Layer layer}) { layer = layer; } } class _MockContact extends Mock implements Contact {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester(Forge2DGame.new); group('LayerContactBehavior', () { test('can be instantiated', () { expect( LayerContactBehavior(layer: Layer.all), isA<LayerContactBehavior>(), ); }); flameTester.test('can be loaded', (game) async { final behavior = LayerContactBehavior(layer: Layer.all); final parent = _TestBodyComponent(); await game.ensureAdd(parent); await parent.ensureAdd(behavior); expect(parent.children, contains(behavior)); }); flameTester.test('beginContact changes layer', (game) async { const oldLayer = Layer.all; const newLayer = Layer.board; final behavior = LayerContactBehavior(layer: newLayer); final parent = _TestBodyComponent(); await game.ensureAdd(parent); await parent.ensureAdd(behavior); final component = _TestLayeredBodyComponent(layer: oldLayer); behavior.beginContact(component, _MockContact()); expect(component.layer, newLayer); }); flameTester.test('endContact changes layer', (game) async { const oldLayer = Layer.all; const newLayer = Layer.board; final behavior = LayerContactBehavior( layer: newLayer, onBegin: false, ); final parent = _TestBodyComponent(); await game.ensureAdd(parent); await parent.ensureAdd(behavior); final component = _TestLayeredBodyComponent(layer: oldLayer); behavior.endContact(component, _MockContact()); expect(component.layer, newLayer); }); }); }
pinball/packages/pinball_flame/test/src/behaviors/layer_contact_behavior_test.dart/0
{ "file_path": "pinball/packages/pinball_flame/test/src/behaviors/layer_contact_behavior_test.dart", "repo_id": "pinball", "token_count": 819 }
1,121
import 'package:pinball_theme/pinball_theme.dart'; /// {@template sparky_theme} /// Defines Sparky character theme assets and attributes. /// {@endtemplate} class SparkyTheme extends CharacterTheme { /// {@macro sparky_theme} const SparkyTheme(); @override AssetGenImage get ball => Assets.images.sparky.ball; @override String get name => 'Sparky'; @override AssetGenImage get background => Assets.images.sparky.background; @override AssetGenImage get icon => Assets.images.sparky.icon; @override AssetGenImage get leaderboardIcon => Assets.images.sparky.leaderboardIcon; @override AssetGenImage get animation => Assets.images.sparky.animation; }
pinball/packages/pinball_theme/lib/src/themes/sparky_theme.dart/0
{ "file_path": "pinball/packages/pinball_theme/lib/src/themes/sparky_theme.dart", "repo_id": "pinball", "token_count": 214 }
1,122
import 'package:flutter/material.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template crt_background} /// [BoxDecoration] that provides a CRT-like background effect. /// {@endtemplate} class CrtBackground extends BoxDecoration { /// {@macro crt_background} const CrtBackground() : super( gradient: const LinearGradient( begin: Alignment(1, 0.015), stops: [0.0, 0.5, 0.5, 1], colors: [ PinballColors.darkBlue, PinballColors.darkBlue, PinballColors.crtBackground, PinballColors.crtBackground, ], tileMode: TileMode.repeated, ), ); }
pinball/packages/pinball_ui/lib/src/widgets/crt_background.dart/0
{ "file_path": "pinball/packages/pinball_ui/lib/src/widgets/crt_background.dart", "repo_id": "pinball", "token_count": 330 }
1,123
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_ui/pinball_ui.dart'; void main() { group('PinballLoadingIndicator', () { group('assert value', () { test('throws error if value <= 0.0', () { expect( () => PinballLoadingIndicator(value: -0.5), throwsA(isA<AssertionError>()), ); }); test('throws error if value >= 1.0', () { expect( () => PinballLoadingIndicator(value: 1.5), throwsA(isA<AssertionError>()), ); }); }); testWidgets( 'renders 12 LinearProgressIndicators and ' '6 FractionallySizedBox to indicate progress', (tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: PinballLoadingIndicator(value: 0.75), ), ), ); expect(find.byType(FractionallySizedBox), findsNWidgets(6)); expect(find.byType(LinearProgressIndicator), findsNWidgets(12)); final progressIndicators = tester.widgetList<LinearProgressIndicator>( find.byType(LinearProgressIndicator), ); for (final i in progressIndicators) { expect(i.value, 0.75); } }); }); }
pinball/packages/pinball_ui/test/src/widgets/pinball_loading_indicator_test.dart/0
{ "file_path": "pinball/packages/pinball_ui/test/src/widgets/pinball_loading_indicator_test.dart", "repo_id": "pinball", "token_count": 582 }
1,124