From 5bcddb5b02988bc7d829935a141f0ae1423914dd Mon Sep 17 00:00:00 2001 From: chenyang Date: Thu, 19 Sep 2024 22:18:24 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E2=80=9Cpigeon=5F3.22.0=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=9E=9A=E4=B8=BE=E7=B1=BB=E5=9E=8B=E5=8F=8A=E6=99=AE=E9=80=9A?= =?UTF-8?q?=E7=B1=BB=E5=B5=8C=E5=A5=97=E6=9E=9A=E4=B8=BE=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E7=9A=84=E4=BD=BF=E7=94=A8=EF=BC=8C=E4=BF=AE=E5=A4=8D=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E7=94=9F=E6=88=90=E6=8A=A5=E9=94=99=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: chenyang --- packages/pigeon/example/app/lib/main.dart | 168 ++++++++-------- .../src/main/ets/plugins/MessagePlugin.ets | 29 ++- .../entry/src/main/ets/plugins/Messages.ets | 22 ++- packages/pigeon/lib/arkts_generator.dart | 183 ++++++++++++------ packages/pigeon/lib/dart_generator.dart | 43 ++-- 5 files changed, 275 insertions(+), 170 deletions(-) diff --git a/packages/pigeon/example/app/lib/main.dart b/packages/pigeon/example/app/lib/main.dart index 871cb0697..314d8fd65 100644 --- a/packages/pigeon/example/app/lib/main.dart +++ b/packages/pigeon/example/app/lib/main.dart @@ -9,21 +9,34 @@ import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'src/messages.g.dart'; +//import 'src/messages.g.dart'; +import 'src/pigeonFlutter.dart'; // #docregion main-dart-flutter -class _ExampleFlutterApi implements MessageFlutterApi { +class _ExampleFlutterApi implements MyFlutterApi { @override String flutterMethod(String? aString) { return aString ?? ''; } + + @override + Future platformInvokeAsync() { + // TODO: implement platformInvokeAsync + throw UnimplementedError(); + } + + @override + String platformInvokeSync() { + // TODO: implement platformInvokeSync + throw UnimplementedError(); + } } // #enddocregion main-dart-flutter void main() { WidgetsFlutterBinding.ensureInitialized(); // #docregion main-dart-flutter - MessageFlutterApi.setUp(_ExampleFlutterApi()); + MyFlutterApi.setUp(_ExampleFlutterApi()); // #enddocregion main-dart-flutter runApp(const MyApp()); } @@ -54,53 +67,18 @@ class MyHomePage extends StatefulWidget { } class _MyHomePageState extends State { - final ExampleHostApi _hostApi = ExampleHostApi(); + BasicMessageChannel channel = const BasicMessageChannel( + 'flutter/pigeonTest', + StringCodec(), + ); + final MyHostApi _hostApi = MyHostApi(); String? _hostCallResult; var _methodResult; - /// Calls host method `add` with provided arguments. - Future add(int a, int b) async { - try { - return await _hostApi.add(a, b); - } catch (e) { - // handle error. - return 0; - } - } - - /// Sends message through host api using `MessageData` class - /// and api `sendMessage` method. - Future sendMessage(String messageText) { - final MessageData message = MessageData( - code: Code.one, - data: {'header': 'this is a header'}, - description: 'uri text', - ); - try { - return _hostApi.sendMessage(message); - } catch (e) { - // handle error. - return Future(() => true); - } - } - // #enddocregion main-dart @override void initState() { super.initState(); - _getHostLanguage(); - } - - void _getHostLanguage() { - _hostApi.getHostLanguage().then((String response) { - setState(() { - _hostCallResult = 'Hello from $response!'; - }); - }).onError((PlatformException error, StackTrace _) { - setState(() { - _hostCallResult = 'Failed to get host language: ${error.message}'; - }); - }); } @override @@ -118,28 +96,6 @@ class _MyHomePageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Container( - child: Text( - _hostCallResult ?? 'Waiting for host language...', - ), - padding: const EdgeInsets.symmetric(vertical: 16.0), - ), - if (_hostCallResult == null) - const CircularProgressIndicator(), - Container( - width: MediaQuery.of(context).size.width, - padding: const EdgeInsets.only(top: 12.0), - child: Center( - child: ElevatedButton( - onPressed: () { - add(3, 4).then((onValue) { - setState(() { - _methodResult = '$onValue'; - }); - }); - }, - child: const Text('add')), - )), Container( width: MediaQuery.of(context).size.width, padding: const EdgeInsets.only(top: 12.0), @@ -270,6 +226,16 @@ class _MyHomePageState extends State { }, child: const Text('sendCustomClassMessage')), )), + Container( + width: MediaQuery.of(context).size.width, + padding: const EdgeInsets.only(top: 12.0), + child: Center( + child: ElevatedButton( + onPressed: () { + _sendNestedDatatypeToPlatform(); + }, + child: const Text('_sendNestedDatatype')), + )), Container( width: MediaQuery.of(context).size.width, padding: const EdgeInsets.only(top: 12.0), @@ -320,6 +286,26 @@ class _MyHomePageState extends State { }, child: const Text('taskQueueTest')), )), + Container( + width: MediaQuery.of(context).size.width, + padding: const EdgeInsets.only(top: 12.0), + child: Center( + child: ElevatedButton( + onPressed: () { + _platformInvokeFlutterSync(); + }, + child: const Text('platformInvokeFlutterSync')), + )), + Container( + width: MediaQuery.of(context).size.width, + padding: const EdgeInsets.only(top: 12.0), + child: Center( + child: ElevatedButton( + onPressed: () { + _platformInvokeFlutterAsync(); + }, + child: const Text('platformInvokeFlutterAsync')), + )), ], ), ), @@ -451,29 +437,42 @@ class _MyHomePageState extends State { } Future _SendCustomClassMessage() async { - final MessageData message = MessageData( - code: Code.one, - data: {'header': 'this is a header'}, - description: 'uri text', - ); - try { - Object? result = await _hostApi.sendMessage(message); + Object? result = + await _hostApi.sendCustomClass(Student(name: "zhangsan", age: 18)); + Student student = result as Student; + String studentStr = "Student{name='${student.name}', age=${student.age}}"; + setState(() { + _methodResult = studentStr; + }); + } + + Future _sendNestedDatatypeToPlatform() async { + try{ + Object? result = await _hostApi.sendNestedDatatype( + Person(name: "lisi", age: 20, identity: Identity.teacher)); + Person person = result as Person; + String personStr = + "Person{name='${person.name}', age=${person.age}, identity=${person.identity}}"; + print(personStr); setState(() { - _methodResult = result; + _methodResult = personStr; }); - } catch (e) { + }catch(e){ // handle error. } + } Future _SendEnum() async { try { - Object? result = await _hostApi.sendEnum(Code.one); + Object? result = await _hostApi.sendEnum(Identity.student); print(result); setState(() { _methodResult = result; }); - } catch (e) {} + } catch (e) { + // handle error. + } } Future _FlutterInvokeSync() async { @@ -504,6 +503,23 @@ class _MyHomePageState extends State { Object? result = await _hostApi.taskQueueTest(); setState(() { _methodResult = result; + _methodResult = '已废弃,不需要使用此方法了'; + }); + } + + Future _platformInvokeFlutterSync() async { + Object? result = await channel.send("platformInvokeSync"); + setState(() { + _methodResult = result; + _methodResult = 'Sync改为参数方式了'; + }); + } + + Future _platformInvokeFlutterAsync() async { + Object? result = await channel.send("platformInvokeAsync"); + setState(() { + _methodResult = result; + _methodResult = 'Async改为参数方式了'; }); } } diff --git a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/MessagePlugin.ets b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/MessagePlugin.ets index 3e7418e73..8e9929a0c 100644 --- a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/MessagePlugin.ets +++ b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/MessagePlugin.ets @@ -17,10 +17,19 @@ import { FlutterPlugin, FlutterPluginBinding } from '@ohos/flutter_ohos/src/main/ets/embedding/engine/plugins/FlutterPlugin'; -import { ExampleHostApi, FlutterError, Code, MessageData, Result } from './Messages'; +//import { ExampleHostApi, FlutterError, CodeEnum, MessageData, Result } from './Messages'; +import { MyHostApi, IdentityEnum,FlutterError, Result, Person, Student } from './PigeonOhos'; -class HostApiImp extends ExampleHostApi { +class HostApiImp extends MyHostApi { + sendCustomClass(data: Student): Student { + return data; + } + + sendNestedDatatype(data: Person): Person { + //throw new Error('Method not implemented.'); + return data; + } getHostLanguage(): string { console.log("testFlutter-Pigeon " + "ets HostApiImp " + " getHostLanguage "); return 'ArkTS'; @@ -30,16 +39,6 @@ class HostApiImp extends ExampleHostApi { return a + b; } - ///尝试将MessageData返回 - sendMessage(message: MessageData, result: Result): void { - let mapData = message.getData(); - if (mapData) { - for (let key of mapData.keys()) { - let value = mapData.get(key); - } - } - result.success(true); - } sendNull(data: Object): Object { return data; @@ -95,7 +94,7 @@ class HostApiImp extends ExampleHostApi { return data; } - sendEnum(data: Code): Code { + sendEnum(data: IdentityEnum): IdentityEnum { return data; } @@ -127,10 +126,10 @@ export default class MessagePlugin implements FlutterPlugin { } onAttachedToEngine(binding: FlutterPluginBinding) { - ExampleHostApi.setup(binding.getBinaryMessenger(), new HostApiImp()); + MyHostApi.setup(binding.getBinaryMessenger(), new HostApiImp()); } onDetachedFromEngine(binding: FlutterPluginBinding) { - ExampleHostApi.setup(binding.getBinaryMessenger(), null); + MyHostApi.setup(binding.getBinaryMessenger(), null); } } \ No newline at end of file diff --git a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/Messages.ets b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/Messages.ets index b0f6b4ba2..ba24beb0f 100644 --- a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/Messages.ets +++ b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/Messages.ets @@ -50,6 +50,13 @@ export enum Code { TWO } +export class CodeEnum { + index: number | null = null; + constructor(index: number) { + this.index = index; + } +} + /* Generated class from Pigeon that represents data sent in messages.*/ export class MessageData { private name?: string; @@ -72,13 +79,13 @@ export class MessageData { return this.description; } - private code?: Code; + private code?: CodeEnum; - public setCode(code: Code): void { + public setCode(code: CodeEnum): void { this.code = code; } - getCode(): Code | undefined { + getCode(): CodeEnum | undefined { return this.code; } @@ -92,7 +99,7 @@ export class MessageData { return this.data; } - constructor(name?: string, description?: string, code?: Code, data?: Map) { + constructor(name?: string, description?: string, code?: CodeEnum, data?: Map) { this.name = name; this.description = description; this.code = code; @@ -122,8 +129,7 @@ export class MessageData { pigeonResult.setName(name as string); let description: Object = arr[1]; pigeonResult.setDescription(description as string); - let code: Object = arr[2]; - pigeonResult.setCode(code as Code); + pigeonResult.setCode(new CodeEnum(arr[2]! as number)); let data: Object = arr[3]; pigeonResult.setData(data as Map); return pigeonResult; @@ -205,7 +211,7 @@ export abstract class ExampleHostApi { abstract sendMap(data: Map): Map; - abstract sendEnum(data: Code): Code; + abstract sendEnum(data: CodeEnum): CodeEnum; abstract flutterInvokeSync(): string; @@ -593,7 +599,7 @@ export abstract class ExampleHostApi { let args: Array = message as Array; let res: Array = []; try { - let output: Code = api!.sendEnum(args[0] as Code); + let output: CodeEnum = api!.sendEnum(new CodeEnum(args[0] as number)); res.push(output); } catch (error) { let wrappedError: Array = wrapError(error); diff --git a/packages/pigeon/lib/arkts_generator.dart b/packages/pigeon/lib/arkts_generator.dart index ceb7b1ee4..ab4a1c2ee 100644 --- a/packages/pigeon/lib/arkts_generator.dart +++ b/packages/pigeon/lib/arkts_generator.dart @@ -34,6 +34,8 @@ const String _codecName = 'PigeonCodec'; const String _overflowClassName = '${classNamePrefix}CodecOverflow'; // Used to create classes with type number rather than long. const String _forceInt = '${varNamePrefix}forceInt'; +///Enum companion suffix +const String _enumCompanionSuffix = 'Enum'; /// Documentation comment spec. const DocumentCommentSpecification _docCommentSpec = @@ -117,11 +119,13 @@ class ArkTSGenerator extends StructuredGenerator { .replaceAllMapped(regex, (Match m) => '${m[1]}_${m[2]}') .toUpperCase(); } - + const List generatedEnumMessages = [ + ' Generated enum from Pigeon that represents data sent in messages.' + ]; indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, _docCommentSpec); - + indent, anEnum.documentationComments, _docCommentSpec, + generatorComments:generatedEnumMessages); indent.write('export enum ${anEnum.name} '); indent.addScoped('{', '}', () { enumerate(anEnum.members, (int index, final EnumMember member) { @@ -131,6 +135,23 @@ class ArkTSGenerator extends StructuredGenerator { '${camelToSnake(member.name)}${index == anEnum.members.length - 1 ? '' : ','}'); }); }); + const List generatedEnumCompanionMessages = [ + ''' + Generated enum Companion class from Pigeon that represents data sent + in messages.Do not delete otherwise enum type data transfer will failed''' + ]; + indent.newln(); + addDocumentationComments( + indent, anEnum.documentationComments, _docCommentSpec, + generatorComments:generatedEnumCompanionMessages); + indent.write('export class ${anEnum.name}$_enumCompanionSuffix '); + indent.addScoped('{', '}', () { + indent.writeln('index:number|null = null;'); + indent.addScoped('constructor(index:number){', '}', () { + indent.writeln('this.index = index;'); + }); + + }); } @override @@ -181,21 +202,35 @@ class ArkTSGenerator extends StructuredGenerator { NamedType field,{bool isPrimitive = false,}) { final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _arkTSTypeForBuiltinDartType(x)); - indent.writeln('private ${field.name}?: ${hostDatatype.datatype};'); - indent.newln(); - - indent.writeScoped( - 'public ${_makeSetter(field)}(${field.name}:${hostDatatype.datatype}):void {', - '}', () { - indent.writeln('this.${field.name} = ${field.name};'); - }); - - indent.newln(); - indent - .write('${_makeGetter(field)}(): ${hostDatatype.datatype} | undefined'); - indent.addScoped('{', '}', () { - indent.writeln('return this.${field.name};'); - }); + if(field.type.isEnum){ + indent.writeln('private ${field.name}?: ${hostDatatype.datatype}$_enumCompanionSuffix;'); + indent.newln(); + indent.writeScoped( + 'public ${_makeSetter(field)}(${field.name}:${hostDatatype.datatype}$_enumCompanionSuffix):void {', + '}', () { + indent.writeln('this.${field.name} = ${field.name};'); + }); + indent.newln(); + indent + .write('${_makeGetter(field)}(): ${hostDatatype.datatype}$_enumCompanionSuffix | undefined'); + indent.addScoped('{', '}', () { + indent.writeln('return this.${field.name};'); + }); + }else{ + indent.writeln('private ${field.name}?: ${hostDatatype.datatype};'); + indent.newln(); + indent.writeScoped( + 'public ${_makeSetter(field)}(${field.name}:${hostDatatype.datatype}):void {', + '}', () { + indent.writeln('this.${field.name} = ${field.name};'); + }); + indent.newln(); + indent + .write('${_makeGetter(field)}(): ${hostDatatype.datatype} | undefined'); + indent.addScoped('{', '}', () { + indent.writeln('return this.${field.name};'); + }); + } } void _writeDataClassSignature( @@ -234,7 +269,11 @@ class ArkTSGenerator extends StructuredGenerator { for (final NamedType element in klass.fields) { final String type = _arkTSTypeForDartType(element.type); final String name = getSafeConstructorArgument(element.name); - argSignature.add('$name?: $type'); + if(element.type.isEnum){ + argSignature.add('$name?: $type$_enumCompanionSuffix'); + }else{ + argSignature.add('$name?: $type'); + } } } indent.add('(${argSignature.join(', ')}) '); @@ -260,10 +299,16 @@ class ArkTSGenerator extends StructuredGenerator { indent.writeln('let arr: Object[] = new Array();'); for (final NamedType field in getFieldsInSerializationOrder(klass)) { final String fieldName = field.name; - - indent.writeScoped('if(this.$fieldName !==undefined){', '}', () { - indent.writeln('arr.push(this.$fieldName);'); - }); + if(field.type.isEnum){ + indent.writeScoped('if(this.$fieldName !==undefined){', '}', () { + indent.writeln('arr.push(Object.values(${field.type.baseName})' + '.indexOf(this.$fieldName.index! as ${field.type.baseName}));'); + }); + }else{ + indent.writeScoped('if(this.$fieldName !==undefined){', '}', () { + indent.writeln('arr.push(this.$fieldName);'); + }); + } } indent.writeln('return arr;'); }); @@ -287,9 +332,14 @@ class ArkTSGenerator extends StructuredGenerator { (int index, final NamedType field) { final String fieldVariable = field.name; final String setter = _makeSetter(field); - indent.writeln('let $fieldVariable: Object = arr[$index];'); - indent - .writeln('$result.$setter(${_castObject(field, fieldVariable)});'); + if(field.type.isEnum){ + indent + .writeln('$result.$setter(new ${field.type.baseName}$_enumCompanionSuffix(arr[$index]! as number));'); + }else{ + indent.writeln('let $fieldVariable: Object = arr[$index];'); + indent + .writeln('$result.$setter(${_castObject(field, fieldVariable)});'); + } }); indent.writeln('return ${result};'); }); @@ -307,11 +357,7 @@ class ArkTSGenerator extends StructuredGenerator { String _castObject(NamedType field, String varName) { final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _arkTSTypeForDartType(x)); - if (field.type.baseName == 'int') { - return '($varName == null) ? null : ((typeof $varName === \'number\' ) ? $varName as number: $varName as ${hostDatatype.datatype})'; - } else { - return _cast(varName, artTSType: hostDatatype.datatype); - } + return _cast(varName, artTSType: hostDatatype.datatype); } @override @@ -535,23 +581,13 @@ class ArkTSGenerator extends StructuredGenerator { final String channelName = makeChannelName(api, method, dartPackageName); indent.write(''); indent.addScoped('{', '}', () { - String? taskQueue; - if (method.taskQueueType != TaskQueueType.serial) { - taskQueue = 'taskQueue'; - indent.writeln( - 'let taskQueue: TaskQueue = binaryMessenger.makeBackgroundTaskQueue();'); - } indent.writeln('let channel: BasicMessageChannel ='); indent.nest(2, () { indent.writeln('new BasicMessageChannel('); indent.nest(2, () { indent .write('binaryMessenger, "$channelName", ${api.name}.getCodec()'); - if (taskQueue != null) { - indent.addln(', $taskQueue);'); - } else { - indent.addln(');'); - } + indent.addln(');'); }); }); indent.write('if (api != null) '); @@ -568,8 +604,13 @@ class ArkTSGenerator extends StructuredGenerator { indent.writeln( 'let args: Array = message as Array;'); enumerate(method.parameters, (int index, NamedType arg) { - final String argExpression = + String argExpression = 'args[$index] as ${_arkTSTypeForDartType(arg.type)}'; + if (method.returnType.isEnum) { + argExpression = + 'new ${_arkTSTypeForDartType(arg.type)}$_enumCompanionSuffix' + '${'(args[$index] as number)'}'; + } methodArgument.add(argExpression); }); } @@ -607,7 +648,11 @@ let $resultName: Result<$returnType> = new ResultImp(); indent.writeln('$call;'); indent.writeln('res.push(null);'); } else { - indent.writeln('let output: $returnType = $call;'); + if(method.returnType.isEnum){ + indent.writeln('let output: $returnType$_enumCompanionSuffix = $call;'); + }else{ + indent.writeln('let output: $returnType = $call;'); + } indent.writeln('res.push(output);'); } }); @@ -647,7 +692,11 @@ let $resultName: Result<$returnType> = new ResultImp(); method.parameters.map((NamedType e) => e.name); argSignature .addAll(map2(argTypes, argNames, (String argType, String argName) { - return '$argName: $argType '; + if(method.returnType.isEnum){ + return '$argName: $argType$_enumCompanionSuffix '; + }else{ + return '$argName: $argType '; + } })); } if (method.isAsynchronous) { @@ -662,8 +711,13 @@ let $resultName: Result<$returnType> = new ResultImp(); } else { indent.newln(); } - indent.writeln( - 'abstract ${method.name}(${argSignature.join(', ')}): $returnType;'); + if (method.returnType.isEnum) { + indent.writeln('abstract ${method.name}(${argSignature.join(', ')}): ' + '$returnType$_enumCompanionSuffix;'); + } else { + indent.writeln( + 'abstract ${method.name}(${argSignature.join(', ')}): $returnType;'); + } } void _writeResultInterface(Indent indent) { @@ -847,16 +901,15 @@ getByte(n: number): number { {required String dartPackageName}) { final List enumeratedTypes = getEnumeratedTypes(root).toList(); - void writeEncodeLogic(EnumeratedType customType) { - bool isEnum = customType.type != CustomTypes.customClass; + bool isEnum = customType.type == CustomTypes.customEnum; final String nullCheck = customType.type == CustomTypes.customEnum ? 'value == null ? null : ' : ''; - String valueString =""; + String valueString =''; if(isEnum){ valueString = customType.enumeration < maximumCodecFieldKey - ? '$nullCheck Object.values(${customType.name}).indexOf(value as ${customType.name})' + ? '$nullCheck Object.values(${customType.name}).indexOf(value.index as ${customType.name})' : 'wrap.toList()'; }else{ valueString = customType.enumeration < maximumCodecFieldKey @@ -867,7 +920,8 @@ getByte(n: number): number { final int enumeration = customType.enumeration < maximumCodecFieldKey ? customType.enumeration : maximumCodecFieldKey; - if(!isEnum){ + final bool isCustom = customType.type == CustomTypes.customClass; + if(isCustom){ indent.add('if (value instanceof ${customType.name}) '); indent.addScoped('{', '} else ', () { if (customType.enumeration >= maximumCodecFieldKey) { @@ -875,17 +929,28 @@ getByte(n: number): number { 'let wrap:$_overflowClassName = new $_overflowClassName();'); indent.writeln( 'wrap.setType(${customType.enumeration - maximumCodecFieldKey});'); - if (isEnum) { - indent.writeln( - 'wrap.setWrapped($nullCheck Object.values(${customType.name}).indexOf(value as ${customType.name});'); - } else { - indent.writeln( - 'wrap.setWrapped($nullCheck(value as ${customType.name}).toList());'); - } + + indent.writeln( + 'wrap.setWrapped($nullCheck(value as ${customType.name}).toList());'); } indent.writeln('stream.writeUint8(this.getByte(${enumeration}));'); indent.writeln('this.writeValue(stream, $valueString);'); }, addTrailingNewline: false); + } else { + indent.add('if (value instanceof ${customType.name}$_enumCompanionSuffix) '); + indent.addScoped('{', '} else ', () { + if (customType.enumeration >= maximumCodecFieldKey) { + indent.writeln( + 'let wrap:$_overflowClassName = new $_overflowClassName();'); + indent.writeln( + 'wrap.setType(${customType.enumeration + - maximumCodecFieldKey});'); + indent.writeln( + 'wrap.setWrapped($nullCheck(value as ${customType.name}).toList());'); + } + indent.writeln('stream.writeUint8(this.getByte($enumeration));'); + indent.writeln('this.writeValue(stream, $valueString);'); + }, addTrailingNewline: false); } } diff --git a/packages/pigeon/lib/dart_generator.dart b/packages/pigeon/lib/dart_generator.dart index df9f31759..840d717d0 100644 --- a/packages/pigeon/lib/dart_generator.dart +++ b/packages/pigeon/lib/dart_generator.dart @@ -246,18 +246,37 @@ class DartGenerator extends StructuredGenerator { final String castCall = _makeGenericCastCall(field.type); final String nullableTag = field.type.isNullable ? '?' : ''; if (field.type.typeArguments.isNotEmpty) { - indent.add( - '($resultAt as $genericType?)$castCallPrefix$castCall', - ); + if(field.type.isEnum){ + indent.add( + '($resultAt as ${"int"}?)$castCallPrefix$castCall', + ); + }else{ + indent.add( + '($resultAt as $genericType?)$castCallPrefix$castCall', + ); + } } else { final String castCallForcePrefix = field.type.isNullable ? '' : '!'; - final String castString = field.type.baseName == 'Object' - ? '' - : ' as $genericType$nullableTag'; - - indent.add( - '$resultAt$castCallForcePrefix$castString', - ); + String castString = ''; + if (field.type.isEnum) { + castString = field.type.baseName == 'Object' + ? '' + : ' as ${'int'}$nullableTag'; + } else { + castString = field.type.baseName == 'Object' + ? '' + : ' as $genericType$nullableTag'; + } + if(field.type.isEnum){ + ///Identity.values + indent.add( + '$genericType.values[$resultAt$castCallForcePrefix$castString]', + ); + }else{ + indent.add( + '$resultAt$castCallForcePrefix$castString', + ); + } } } @@ -271,8 +290,8 @@ class DartGenerator extends StructuredGenerator { enumerate(getFieldsInSerializationOrder(classDefinition), (int index, final NamedType field) { indent.write('${field.name}: '); - writeValueDecode(field, index); - indent.addln(','); + writeValueDecode(field, index); + indent.addln(','); }); }); }); -- Gitee From 4f46d14158afefa984df29aa96f656baa23e957e Mon Sep 17 00:00:00 2001 From: chenyang Date: Thu, 19 Sep 2024 22:18:24 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E2=80=9Cpigeon=5F3.22.0=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=9E=9A=E4=B8=BE=E7=B1=BB=E5=9E=8B=E5=8F=8A=E6=99=AE=E9=80=9A?= =?UTF-8?q?=E7=B1=BB=E5=B5=8C=E5=A5=97=E6=9E=9A=E4=B8=BE=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E7=9A=84=E4=BD=BF=E7=94=A8=EF=BC=8C=E4=BF=AE=E5=A4=8D=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E7=94=9F=E6=88=90=E6=8A=A5=E9=94=99=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: chenyang --- packages/pigeon/example/app/lib/main.dart | 196 +++-- .../pigeon/example/app/lib/pigeonTest.dart | 89 ++ .../example/app/lib/src/pigeonFlutter.dart | 695 +++++++++++++++ .../src/main/ets/plugins/MessagePlugin.ets | 29 +- .../entry/src/main/ets/plugins/Messages.ets | 22 +- .../entry/src/main/ets/plugins/PigeonOhos.ets | 796 ++++++++++++++++++ packages/pigeon/lib/arkts_generator.dart | 183 ++-- packages/pigeon/lib/dart_generator.dart | 42 +- 8 files changed, 1864 insertions(+), 188 deletions(-) create mode 100644 packages/pigeon/example/app/lib/pigeonTest.dart create mode 100644 packages/pigeon/example/app/lib/src/pigeonFlutter.dart create mode 100644 packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/PigeonOhos.ets diff --git a/packages/pigeon/example/app/lib/main.dart b/packages/pigeon/example/app/lib/main.dart index 871cb0697..b407ba63a 100644 --- a/packages/pigeon/example/app/lib/main.dart +++ b/packages/pigeon/example/app/lib/main.dart @@ -9,22 +9,29 @@ import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'src/messages.g.dart'; +import 'src/pigeonFlutter.dart'; -// #docregion main-dart-flutter -class _ExampleFlutterApi implements MessageFlutterApi { + +class _ExampleFlutterApi implements DemoFlutterApi { @override String flutterMethod(String? aString) { return aString ?? ''; } + + @override + Future platformInvokeAsync() { + throw UnimplementedError(); + } + + @override + String platformInvokeSync() { + throw UnimplementedError(); + } } -// #enddocregion main-dart-flutter void main() { WidgetsFlutterBinding.ensureInitialized(); -// #docregion main-dart-flutter - MessageFlutterApi.setUp(_ExampleFlutterApi()); -// #enddocregion main-dart-flutter + DemoFlutterApi.setUp(_ExampleFlutterApi()); runApp(const MyApp()); } @@ -54,53 +61,14 @@ class MyHomePage extends StatefulWidget { } class _MyHomePageState extends State { - final ExampleHostApi _hostApi = ExampleHostApi(); - String? _hostCallResult; - var _methodResult; - /// Calls host method `add` with provided arguments. - Future add(int a, int b) async { - try { - return await _hostApi.add(a, b); - } catch (e) { - // handle error. - return 0; - } - } + final DemoHostApi _hostApi = DemoHostApi(); - /// Sends message through host api using `MessageData` class - /// and api `sendMessage` method. - Future sendMessage(String messageText) { - final MessageData message = MessageData( - code: Code.one, - data: {'header': 'this is a header'}, - description: 'uri text', - ); - try { - return _hostApi.sendMessage(message); - } catch (e) { - // handle error. - return Future(() => true); - } - } - // #enddocregion main-dart + var _methodResult; @override void initState() { super.initState(); - _getHostLanguage(); - } - - void _getHostLanguage() { - _hostApi.getHostLanguage().then((String response) { - setState(() { - _hostCallResult = 'Hello from $response!'; - }); - }).onError((PlatformException error, StackTrace _) { - setState(() { - _hostCallResult = 'Failed to get host language: ${error.message}'; - }); - }); } @override @@ -118,28 +86,6 @@ class _MyHomePageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Container( - child: Text( - _hostCallResult ?? 'Waiting for host language...', - ), - padding: const EdgeInsets.symmetric(vertical: 16.0), - ), - if (_hostCallResult == null) - const CircularProgressIndicator(), - Container( - width: MediaQuery.of(context).size.width, - padding: const EdgeInsets.only(top: 12.0), - child: Center( - child: ElevatedButton( - onPressed: () { - add(3, 4).then((onValue) { - setState(() { - _methodResult = '$onValue'; - }); - }); - }, - child: const Text('add')), - )), Container( width: MediaQuery.of(context).size.width, padding: const EdgeInsets.only(top: 12.0), @@ -270,6 +216,16 @@ class _MyHomePageState extends State { }, child: const Text('sendCustomClassMessage')), )), + Container( + width: MediaQuery.of(context).size.width, + padding: const EdgeInsets.only(top: 12.0), + child: Center( + child: ElevatedButton( + onPressed: () { + _sendNestedDatatypeToPlatform(); + }, + child: const Text('_sendNestedDatatype')), + )), Container( width: MediaQuery.of(context).size.width, padding: const EdgeInsets.only(top: 12.0), @@ -320,6 +276,26 @@ class _MyHomePageState extends State { }, child: const Text('taskQueueTest')), )), + Container( + width: MediaQuery.of(context).size.width, + padding: const EdgeInsets.only(top: 12.0), + child: Center( + child: ElevatedButton( + onPressed: () { + _platformInvokeFlutterSync(); + }, + child: const Text('platformInvokeFlutterSync')), + )), + Container( + width: MediaQuery.of(context).size.width, + padding: const EdgeInsets.only(top: 12.0), + child: Center( + child: ElevatedButton( + onPressed: () { + _platformInvokeFlutterAsync(); + }, + child: const Text('platformInvokeFlutterAsync')), + )), ], ), ), @@ -338,7 +314,7 @@ class _MyHomePageState extends State { ); } - //sendNull + ///sendNull Future _SendNull() async { Object? result = await _hostApi.sendNull(null); print(result); @@ -347,7 +323,7 @@ class _MyHomePageState extends State { }); } - //sendTrue + ///sendTrue Future _SendTrue() async { Object? result = _hostApi.sendTrue(true); print(result); @@ -356,8 +332,7 @@ class _MyHomePageState extends State { }); } - //sendFalse - + ///sendFalse Future _SendFalse() async { Object? result = _hostApi.sendFalse(false); print(result); @@ -366,7 +341,7 @@ class _MyHomePageState extends State { }); } - //sendInt + ///sendInt Future _SendInt() async { Object? result = _hostApi.sendInt(100); print(result); @@ -375,7 +350,7 @@ class _MyHomePageState extends State { }); } - //sendDouble + ///sendDouble Future _SendDouble() async { Object? result = await _hostApi.sendDouble(100.256861); print(result); @@ -384,7 +359,7 @@ class _MyHomePageState extends State { }); } - //sendString + ///sendString Future _SendString() async { Object? result = await _hostApi.sendString('sendStringValue'); print(result); @@ -393,7 +368,7 @@ class _MyHomePageState extends State { }); } - //sendUint8List + ///sendUint8List Future _SendUint8List() async { Object? result = await _hostApi.sendUint8List(Uint8List.fromList([1, 2, 3])); @@ -403,7 +378,7 @@ class _MyHomePageState extends State { }); } - //sendInt32List + ///sendInt32List Future _SendInt32List() async { Object? result = await _hostApi.sendInt32List(Int32List.fromList([4, 5, 6])); @@ -413,7 +388,7 @@ class _MyHomePageState extends State { }); } - //sendInt64List + ///sendInt64List Future _SendInt64List() async { Object? result = await _hostApi.sendInt64List(Int64List.fromList( [9223372036854775807, 9223372036854775806, 9223372036854775805])); @@ -423,7 +398,7 @@ class _MyHomePageState extends State { }); } - //sendFloat64List + ///sendFloat64List Future _SendFloat64List() async { Object? result = await _hostApi .sendFloat64List(Float64List.fromList([12.3, 45.6, 78.9])); @@ -433,6 +408,7 @@ class _MyHomePageState extends State { }); } + ///sendList Future _SendList() async { Object? result = await _hostApi.sendList(['zhangsan', 'lisi', 'zhangwu']); print(result); @@ -441,6 +417,7 @@ class _MyHomePageState extends State { }); } + ///sendMap Future _SendMap() async { Object? result = await _hostApi.sendMap({'Name': 'zhangsan', 'Country': 'China'}); @@ -450,32 +427,48 @@ class _MyHomePageState extends State { }); } + ///sendCustomClass Future _SendCustomClassMessage() async { - final MessageData message = MessageData( - code: Code.one, - data: {'header': 'this is a header'}, - description: 'uri text', - ); - try { - Object? result = await _hostApi.sendMessage(message); + Object? result = + await _hostApi.sendCustomClass(Student(name: "zhangsan", age: 18)); + Student student = result as Student; + String studentStr = "Student{name='${student.name}', age=${student.age}}"; + setState(() { + _methodResult = studentStr; + }); + } + + ///sendNestedData + Future _sendNestedDatatypeToPlatform() async { + try{ + Object? result = await _hostApi.sendNestedDatatype( + Person(name: "lisi", age: 20, identity: Identity.teacher)); + Person person = result as Person; + String personStr = + "Person{name='${person.name}', age=${person.age}, identity=${person.identity}}"; + print(personStr); setState(() { - _methodResult = result; + _methodResult = personStr; }); } catch (e) { - // handle error. + print(e); } } + ///sendEnum Future _SendEnum() async { try { - Object? result = await _hostApi.sendEnum(Code.one); + Object? result = await _hostApi.sendEnum(Identity.student); print(result); setState(() { _methodResult = result; }); - } catch (e) {} + } catch (e) { + print(e); + } } + ///InvokeSync Future _FlutterInvokeSync() async { Object? result = await _hostApi.flutterInvokeSync(); setState(() { @@ -490,6 +483,7 @@ class _MyHomePageState extends State { }); } + ///ErrorHandling Future _ErrorHandlingTest() async { try { await _hostApi.errorHandling(); @@ -500,8 +494,26 @@ class _MyHomePageState extends State { } } + ///Deprecated Future _TaskQueueTest() async { Object? result = await _hostApi.taskQueueTest(); + setState(() { + _methodResult = result; + _methodResult = '已废弃,不需要使用此方法了'; + }); + } + + ///platformInvokeFlutterSync + Future _platformInvokeFlutterSync() async { + Object? result = await _hostApi.flutterInvokeSync(); + setState(() { + _methodResult = result; + }); + } + + ///platformInvokeFlutterAsync + Future _platformInvokeFlutterAsync() async { + Object? result = await _hostApi.flutterInvokeAsync(); setState(() { _methodResult = result; }); diff --git a/packages/pigeon/example/app/lib/pigeonTest.dart b/packages/pigeon/example/app/lib/pigeonTest.dart new file mode 100644 index 000000000..7f8577348 --- /dev/null +++ b/packages/pigeon/example/app/lib/pigeonTest.dart @@ -0,0 +1,89 @@ +import 'package:pigeon/pigeon.dart'; + +// @ConfigurePigeon(PigeonOptions( +// // javaOut: 'android/app/src/main/java/io/flutter/plugins/pigeon/PigeonAndroid.java', +// // javaOptions: JavaOptions( +// // className: 'PigeonAndroid', +// // package: 'io.flutter.plugins.pigeon', +// // ), +// dartOut: 'lib/src/pigeonFlutter.dart', +// dartOptions: DartOptions(), +// )) + +// 枚举 +enum Identity { student, teacher } + +// 嵌套 +class Person { + Person({required this.name, required this.age, required this.identity}); + String name; + int age; + Identity identity; +} + +// 自定义类 +class Student { + Student({required this.name, required this.age}); + String name; + int age; +} + +@HostApi() +abstract class DemoHostApi { + Object? sendNull(Object? data); + + bool sendTrue(bool data); + + bool sendFalse(bool data); + + int sendInt(int data); + + double sendDouble(double data); + + String sendString(String data); + + Uint8List sendUint8List(Uint8List data); + + Int32List sendInt32List(Int32List data); + + Int64List sendInt64List(Int64List data); + + // Float32List sendFloat32List(Float32List data); + + Float64List sendFloat64List(Float64List data); + + List sendList(List data); + + Map sendMap(Map data); + + Student sendCustomClass(Student data); + + Person sendNestedDatatype(Person data); + + Identity sendEnum(Identity data); + + // Flutter调用平台侧同步方法 + String flutterInvokeSync(); + + // Flutter调用平台侧异步方法 + @async + String flutterInvokeAsync(); + + // 错误处理 + @async + String errorHandling(); + + // 任务队列 + @TaskQueue(type: TaskQueueType.serialBackgroundThread) + String taskQueueTest(); +} + +@FlutterApi() +abstract class DemoFlutterApi { + // 平台侧调用Flutter同步方法 + String platformInvokeSync(); + + // 平台侧调用Flutter异步方法 + @async + String platformInvokeAsync(); +} \ No newline at end of file diff --git a/packages/pigeon/example/app/lib/src/pigeonFlutter.dart b/packages/pigeon/example/app/lib/src/pigeonFlutter.dart new file mode 100644 index 000000000..e2df8157c --- /dev/null +++ b/packages/pigeon/example/app/lib/src/pigeonFlutter.dart @@ -0,0 +1,695 @@ +// Autogenerated from Pigeon (v21.2.0), do not edit directly. +// See also: https://pub.dev/packages/pigeon +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers + +import 'dart:async'; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; + +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; +import 'package:flutter/services.dart'; + +PlatformException _createConnectionError(String channelName) { + return PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); +} + +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { + if (empty) { + return []; + } + if (error == null) { + return [result]; + } + return [error.code, error.message, error.details]; +} + +enum Identity { + student, + teacher, +} + +class Person { + Person({ + required this.name, + required this.age, + required this.identity, + }); + + String name; + + int age; + + Identity identity; + + Object encode() { + return [ + name, + age, + identity, + ]; + } + + static Person decode(Object result) { + result as List; + return Person( + name: result[0]! as String, + age: result[1]! as int, + identity: Identity.values[result[2]! as int], + ); + } +} + +class Student { + Student({ + required this.name, + required this.age, + }); + + String name; + + int age; + + Object encode() { + return [ + name, + age, + ]; + } + + static Student decode(Object result) { + result as List; + return Student( + name: result[0]! as String, + age: result[1]! as int, + ); + } +} + + +class _PigeonCodec extends StandardMessageCodec { + const _PigeonCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is Identity) { + buffer.putUint8(129); + writeValue(buffer, value.index); + } else if (value is Person) { + buffer.putUint8(130); + writeValue(buffer, value.encode()); + } else if (value is Student) { + buffer.putUint8(131); + writeValue(buffer, value.encode()); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 129: + final int? value = readValue(buffer) as int?; + return value == null ? null : Identity.values[value]; + case 130: + return Person.decode(readValue(buffer)!); + case 131: + return Student.decode(readValue(buffer)!); + default: + return super.readValueOfType(type, buffer); + } + } +} + +class DemoHostApi { + /// Constructor for [DemoHostApi]. The [binaryMessenger] named argument is + /// available for dependency injection. If it is left null, the default + /// BinaryMessenger will be used which routes to the host platform. + DemoHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + final BinaryMessenger? pigeonVar_binaryMessenger; + + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + final String pigeonVar_messageChannelSuffix; + + Future sendNull(Object? data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendNull$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return pigeonVar_replyList[0]; + } + } + + Future sendTrue(bool data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendTrue$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as bool?)!; + } + } + + Future sendFalse(bool data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendFalse$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as bool?)!; + } + } + + Future sendInt(int data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendInt$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as int?)!; + } + } + + Future sendDouble(double data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendDouble$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as double?)!; + } + } + + Future sendString(String data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendString$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + Future sendUint8List(Uint8List data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendUint8List$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Uint8List?)!; + } + } + + Future sendInt32List(Int32List data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendInt32List$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Int32List?)!; + } + } + + Future sendInt64List(Int64List data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendInt64List$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Int64List?)!; + } + } + + Future sendFloat64List(Float64List data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendFloat64List$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Float64List?)!; + } + } + + Future> sendList(List data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendList$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as List?)!.cast(); + } + } + + Future> sendMap(Map data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendMap$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Map?)!.cast(); + } + } + + Future sendCustomClass(Student data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendCustomClass$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Student?)!; + } + } + + Future sendNestedDatatype(Person data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendNestedDatatype$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Person?)!; + } + } + + Future sendEnum(Identity data) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendEnum$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send([data]) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Identity?)!; + } + } + + Future flutterInvokeSync() async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.flutterInvokeSync$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send(null) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + Future flutterInvokeAsync() async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.flutterInvokeAsync$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send(null) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + Future errorHandling() async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.errorHandling$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send(null) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + Future taskQueueTest() async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_app.DemoHostApi.taskQueueTest$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = + await pigeonVar_channel.send(null) as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } +} + +abstract class DemoFlutterApi { + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + String platformInvokeSync(); + + Future platformInvokeAsync(); + + static void setUp(DemoFlutterApi? api, {BinaryMessenger? binaryMessenger, String messageChannelSuffix = '',}) { + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + { + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_example_app.DemoFlutterApi.platformInvokeSync$messageChannelSuffix', pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (api == null) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + try { + final String output = api.platformInvokeSync(); + return wrapResponse(result: output); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse(error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + { + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_example_app.DemoFlutterApi.platformInvokeAsync$messageChannelSuffix', pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (api == null) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + try { + final String output = await api.platformInvokeAsync(); + return wrapResponse(result: output); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse(error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } +} diff --git a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/MessagePlugin.ets b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/MessagePlugin.ets index 3e7418e73..ee57f19ae 100644 --- a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/MessagePlugin.ets +++ b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/MessagePlugin.ets @@ -17,12 +17,18 @@ import { FlutterPlugin, FlutterPluginBinding } from '@ohos/flutter_ohos/src/main/ets/embedding/engine/plugins/FlutterPlugin'; -import { ExampleHostApi, FlutterError, Code, MessageData, Result } from './Messages'; +import { DemoHostApi, IdentityEnum,FlutterError, Result, Person, Student } from './PigeonOhos'; -class HostApiImp extends ExampleHostApi { +class HostApiImp extends DemoHostApi { + sendCustomClass(data: Student): Student { + return data; + } + + sendNestedDatatype(data: Person): Person { + return data; + } getHostLanguage(): string { - console.log("testFlutter-Pigeon " + "ets HostApiImp " + " getHostLanguage "); return 'ArkTS'; } @@ -30,17 +36,6 @@ class HostApiImp extends ExampleHostApi { return a + b; } - ///尝试将MessageData返回 - sendMessage(message: MessageData, result: Result): void { - let mapData = message.getData(); - if (mapData) { - for (let key of mapData.keys()) { - let value = mapData.get(key); - } - } - result.success(true); - } - sendNull(data: Object): Object { return data; } @@ -95,7 +90,7 @@ class HostApiImp extends ExampleHostApi { return data; } - sendEnum(data: Code): Code { + sendEnum(data: IdentityEnum): IdentityEnum { return data; } @@ -127,10 +122,10 @@ export default class MessagePlugin implements FlutterPlugin { } onAttachedToEngine(binding: FlutterPluginBinding) { - ExampleHostApi.setup(binding.getBinaryMessenger(), new HostApiImp()); + DemoHostApi.setup(binding.getBinaryMessenger(), new HostApiImp()); } onDetachedFromEngine(binding: FlutterPluginBinding) { - ExampleHostApi.setup(binding.getBinaryMessenger(), null); + DemoHostApi.setup(binding.getBinaryMessenger(), null); } } \ No newline at end of file diff --git a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/Messages.ets b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/Messages.ets index b0f6b4ba2..ba24beb0f 100644 --- a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/Messages.ets +++ b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/Messages.ets @@ -50,6 +50,13 @@ export enum Code { TWO } +export class CodeEnum { + index: number | null = null; + constructor(index: number) { + this.index = index; + } +} + /* Generated class from Pigeon that represents data sent in messages.*/ export class MessageData { private name?: string; @@ -72,13 +79,13 @@ export class MessageData { return this.description; } - private code?: Code; + private code?: CodeEnum; - public setCode(code: Code): void { + public setCode(code: CodeEnum): void { this.code = code; } - getCode(): Code | undefined { + getCode(): CodeEnum | undefined { return this.code; } @@ -92,7 +99,7 @@ export class MessageData { return this.data; } - constructor(name?: string, description?: string, code?: Code, data?: Map) { + constructor(name?: string, description?: string, code?: CodeEnum, data?: Map) { this.name = name; this.description = description; this.code = code; @@ -122,8 +129,7 @@ export class MessageData { pigeonResult.setName(name as string); let description: Object = arr[1]; pigeonResult.setDescription(description as string); - let code: Object = arr[2]; - pigeonResult.setCode(code as Code); + pigeonResult.setCode(new CodeEnum(arr[2]! as number)); let data: Object = arr[3]; pigeonResult.setData(data as Map); return pigeonResult; @@ -205,7 +211,7 @@ export abstract class ExampleHostApi { abstract sendMap(data: Map): Map; - abstract sendEnum(data: Code): Code; + abstract sendEnum(data: CodeEnum): CodeEnum; abstract flutterInvokeSync(): string; @@ -593,7 +599,7 @@ export abstract class ExampleHostApi { let args: Array = message as Array; let res: Array = []; try { - let output: Code = api!.sendEnum(args[0] as Code); + let output: CodeEnum = api!.sendEnum(new CodeEnum(args[0] as number)); res.push(output); } catch (error) { let wrappedError: Array = wrapError(error); diff --git a/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/PigeonOhos.ets b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/PigeonOhos.ets new file mode 100644 index 000000000..bc4a9a4de --- /dev/null +++ b/packages/pigeon/example/app/ohos/entry/src/main/ets/plugins/PigeonOhos.ets @@ -0,0 +1,796 @@ +import StandardMessageCodec from '@ohos/flutter_ohos/src/main/ets/plugin/common/StandardMessageCodec'; +import BasicMessageChannel, { Reply } from '@ohos/flutter_ohos/src/main/ets/plugin/common/BasicMessageChannel'; +import { BinaryMessenger, TaskQueue } from '@ohos/flutter_ohos/src/main/ets/plugin/common/BinaryMessenger'; +import MessageCodec from '@ohos/flutter_ohos/src/main/ets/plugin/common/MessageCodec'; +import { ByteBuffer } from '@ohos/flutter_ohos/src/main/ets/util/ByteBuffer'; + + +/** Error class for passing custom error details to Flutter via a thrown PlatformException. */ +export class FlutterError implements Error { + /** The error code. */ + public code: string; + /** The error name. */ + public name: string; + /** The error message. */ + public message: string; + /** The error stack. */ + public stack?: string; + + constructor(code: string, name: string, message: string, stack?: string) { + this.code = code; + this.name = name; + this.message = message; + this.stack = stack; + } +} + +function wrapError(error: Error): Array { + let errorList: Array = new Array(3); + if (error instanceof FlutterError) { + let err: FlutterError = error as FlutterError; + errorList[0] = err.code; + errorList[1] = err.name; + errorList[2] = err.message; + } else { + errorList[0] = error.toString(); + errorList[1] = error.name; + errorList[2] = "Cause: " + error.message + ", Stacktrace: " + error.stack; + } + return errorList; +} + + +/* Generated enum from Pigeon that represents data sent in messages.*/ +export enum Identity { + STUDENT, + TEACHER +} + +/* Generated enum Companion class from Pigeon that represents data sent + in messages.Do not delete otherwise enum type data transfer will failed*/ +export class IdentityEnum { + index: number | null = null; + + constructor(index: number) { + this.index = index; + } +} + +/* Generated class from Pigeon that represents data sent in messages.*/ +export class Person { + private name?: string; + + public setName(name: string): void { + this.name = name; + } + + getName(): string | undefined { + return this.name; + } + + private age?: number; + + public setAge(age: number): void { + this.age = age; + } + + getAge(): number | undefined { + return this.age; + } + + private identity?: IdentityEnum; + + public setIdentity(identity: IdentityEnum): void { + this.identity = identity; + } + + getIdentity(): IdentityEnum | undefined { + return this.identity; + } + + constructor(name?: string, age?: number, identity?: IdentityEnum) { + this.name = name; + this.age = age; + this.identity = identity; + } + + toList(): Object[] { + let arr: Object[] = new Array(); + if (this.name !== undefined) { + arr.push(this.name); + } + if (this.age !== undefined) { + arr.push(this.age); + } + if (this.identity !== undefined) { + arr.push(Object.values(Identity).indexOf(this.identity.index! as Identity)); + } + return arr; + } + + static fromList(arr: Object[]): Person { + let pigeonResult: Person = new Person(); + let name: Object = arr[0]; + pigeonResult.setName(name as string); + let age: Object = arr[1]; + pigeonResult.setAge(age as number); + pigeonResult.setIdentity(new IdentityEnum(arr[2]! as number)); + return pigeonResult; + } +} + +/* Generated class from Pigeon that represents data sent in messages.*/ +export class Student { + private name?: string; + + public setName(name: string): void { + this.name = name; + } + + getName(): string | undefined { + return this.name; + } + + private age?: number; + + public setAge(age: number): void { + this.age = age; + } + + getAge(): number | undefined { + return this.age; + } + + constructor(name?: string, age?: number) { + this.name = name; + this.age = age; + } + + toList(): Object[] { + let arr: Object[] = new Array(); + if (this.name !== undefined) { + arr.push(this.name); + } + if (this.age !== undefined) { + arr.push(this.age); + } + return arr; + } + + static fromList(arr: Object[]): Student { + let pigeonResult: Student = new Student(); + let name: Object = arr[0]; + pigeonResult.setName(name as string); + let age: Object = arr[1]; + pigeonResult.setAge(age as number); + return pigeonResult; + } +} + +class PigeonCodec extends StandardMessageCodec { + static readonly INSTANCE: PigeonCodec = new PigeonCodec(); + + getByte(n: number): number { + let byteArray = new Uint8Array(1); + byteArray[0] = n; + return byteArray[0] as number; + } + + private constructor() { + super(); + } + + readValueOfType(type: number, buffer: ByteBuffer): ESObject { + switch (type) { + case this.getByte(129): { + let value: Object = super.readValue(buffer); + return value == null ? null : Identity[value as number]; + } + case this.getByte(130): + return Person.fromList(super.readValue(buffer) as Object[]); + case this.getByte(131): + return Student.fromList(super.readValue(buffer) as Object[]); + default: + return super.readValueOfType(type, buffer); + } + } + + writeValue(stream: ByteBuffer, value: ESObject): ESObject { + if (value instanceof IdentityEnum) { + stream.writeUint8(this.getByte(129)); + this.writeValue(stream, value == null ? null : Object.values(Identity).indexOf(value.index as Identity)); + } else if (value instanceof Person) { + stream.writeUint8(this.getByte(130)); + this.writeValue(stream, (value as Person).toList()); + } else if (value instanceof Student) { + stream.writeUint8(this.getByte(131)); + this.writeValue(stream, (value as Student).toList()); + } else { + super.writeValue(stream, value); + } + } +} + + +export interface Result { + success(result: T): void; + + error(error: Error): void; +} + +/* Generated abstract class from Pigeon that represents a handler of messages from Flutter.*/ +export abstract class DemoHostApi { + abstract sendNull(data: Object): Object; + + abstract sendTrue(data: boolean): boolean; + + abstract sendFalse(data: boolean): boolean; + + abstract sendInt(data: number): number; + + abstract sendDouble(data: number): number; + + abstract sendString(data: string): string; + + abstract sendUint8List(data: number[]): number[]; + + abstract sendInt32List(data: number[]): number[]; + + abstract sendInt64List(data: number[]): number[]; + + abstract sendFloat64List(data: number[]): number[]; + + abstract sendList(data: Array): Array; + + abstract sendMap(data: Map): Map; + + abstract sendCustomClass(data: Student): Student; + + abstract sendNestedDatatype(data: Person): Person; + + abstract sendEnum(data: IdentityEnum): IdentityEnum; + + abstract flutterInvokeSync(): string; + + abstract flutterInvokeAsync(result: Result): void; + + abstract errorHandling(result: Result): void; + + abstract taskQueueTest(): string; + + /** The codec used by DemoHostApi. */ + static getCodec(): MessageCodec { + return PigeonCodec.INSTANCE; + } + + /*Sets up an instance of `DemoHostApi` to handle messages through the `binaryMessenger`.*/ + static setup(binaryMessenger: BinaryMessenger, api: DemoHostApi | null): void { + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendNull", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: Object = api!.sendNull(args[0] as Object); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendTrue", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: boolean = api!.sendTrue(args[0] as boolean); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendFalse", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: boolean = api!.sendFalse(args[0] as boolean); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendInt", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: number = api!.sendInt(args[0] as number); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendDouble", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: number = api!.sendDouble(args[0] as number); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendString", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: string = api!.sendString(args[0] as string); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendUint8List", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: number[] = api!.sendUint8List(args[0] as number[]); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendInt32List", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: number[] = api!.sendInt32List(args[0] as number[]); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendInt64List", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: number[] = api!.sendInt64List(args[0] as number[]); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendFloat64List", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: number[] = api!.sendFloat64List(args[0] as number[]); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendList", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: Array = api!.sendList(args[0] as Array); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendMap", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: Map = api!.sendMap(args[0] as Map); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendCustomClass", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: Student = api!.sendCustomClass(args[0] as Student); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendNestedDatatype", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: Person = api!.sendNestedDatatype(args[0] as Person); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.sendEnum", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let args: Array = message as Array; + let res: Array = []; + try { + let output: IdentityEnum = api!.sendEnum(new IdentityEnum(args[0] as number)); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.flutterInvokeSync", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let res: Array = []; + try { + let output: string = api!.flutterInvokeSync(); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.flutterInvokeAsync", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + class ResultImp implements Result { + success(result: string): void { + let res: Array = []; + res.push(result); + reply.reply(res); + } + + error(error: Error): void { + let wrappedError: Array = wrapError(error); + reply.reply(wrappedError); + } + } + + let resultCallback: Result = new ResultImp(); + + api!.flutterInvokeAsync(resultCallback); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.errorHandling", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + class ResultImp implements Result { + success(result: string): void { + let res: Array = []; + res.push(result); + reply.reply(res); + } + + error(error: Error): void { + let wrappedError: Array = wrapError(error); + reply.reply(wrappedError); + } + } + + let resultCallback: Result = new ResultImp(); + + api!.errorHandling(resultCallback); + } + }); + } else { + channel.setMessageHandler(null); + } + } + { + let channel: BasicMessageChannel = + new BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.pigeon_example_app.DemoHostApi.taskQueueTest", DemoHostApi.getCodec()); + if (api != null) { + channel.setMessageHandler({ + onMessage(message: Object, reply: Reply) { + let res: Array = []; + try { + let output: string = api!.taskQueueTest(); + res.push(output); + } catch (error) { + let wrappedError: Array = wrapError(error); + res = wrappedError; + } + reply.reply(res); + } + }); + } else { + channel.setMessageHandler(null); + } + } + } +} + +/* Generated class from Pigeon that represents Flutter messages that can be called from ArkTS.*/ +export class DemoFlutterApi { + binaryMessenger: BinaryMessenger; + + constructor(binaryMessenger: BinaryMessenger) { + this.binaryMessenger = binaryMessenger; + } + + /** The codec used by DemoFlutterApi. */ + static getCodec(): MessageCodec { + return PigeonCodec.INSTANCE; + } + + platformInvokeSync(callback: Reply): void { + const channelName: string = 'dev.flutter.pigeon.pigeon_example_app.DemoFlutterApi.platformInvokeSync'; + let channel: BasicMessageChannel = + new BasicMessageChannel( + this.binaryMessenger, channelName, DemoFlutterApi.getCodec()); + channel.send( + null, + channelReply => { + if (Array.isArray(channelReply)) { + let listReply: Object[] = channelReply as Object[]; + if (listReply.length > 1) { + let arrFirst: string = listReply[0] as string; + let arrSecond: string = listReply[1] as string; + let arrThird: string = listReply[2] as string; + let replyArr: string = + 'FlutterError:{"code":' + arrFirst + ',"name":' + arrSecond + ',"message":' + arrThird + '}'; + callback.reply(replyArr); + } else if (listReply[0] == null) { + let replyNull: string = + 'FlutterError:{"code":null-error,"name":Flutter api returned null value for non-null return value.,"message":}' + callback.reply(replyNull); + } else { + let output: string = listReply[0] as string; + callback.reply(output); + } + } else { + let connErr: string = + 'FlutterError:{"code":channel-error,"name":Unable to establish connection on channel:channelName,"message":.}' + callback.reply(connErr); + } + }); + } + + platformInvokeAsync(callback: Reply): void { + const channelName: string = 'dev.flutter.pigeon.pigeon_example_app.DemoFlutterApi.platformInvokeAsync'; + let channel: BasicMessageChannel = + new BasicMessageChannel( + this.binaryMessenger, channelName, DemoFlutterApi.getCodec()); + channel.send( + null, + channelReply => { + if (Array.isArray(channelReply)) { + let listReply: Object[] = channelReply as Object[]; + if (listReply.length > 1) { + let arrFirst: string = listReply[0] as string; + let arrSecond: string = listReply[1] as string; + let arrThird: string = listReply[2] as string; + let replyArr: string = + 'FlutterError:{"code":' + arrFirst + ',"name":' + arrSecond + ',"message":' + arrThird + '}'; + callback.reply(replyArr); + } else if (listReply[0] == null) { + let replyNull: string = + 'FlutterError:{"code":null-error,"name":Flutter api returned null value for non-null return value.,"message":}' + callback.reply(replyNull); + } else { + let output: string = listReply[0] as string; + callback.reply(output); + } + } else { + let connErr: string = + 'FlutterError:{"code":channel-error,"name":Unable to establish connection on channel:channelName,"message":.}' + callback.reply(connErr); + } + }); + } +} diff --git a/packages/pigeon/lib/arkts_generator.dart b/packages/pigeon/lib/arkts_generator.dart index ceb7b1ee4..ab4a1c2ee 100644 --- a/packages/pigeon/lib/arkts_generator.dart +++ b/packages/pigeon/lib/arkts_generator.dart @@ -34,6 +34,8 @@ const String _codecName = 'PigeonCodec'; const String _overflowClassName = '${classNamePrefix}CodecOverflow'; // Used to create classes with type number rather than long. const String _forceInt = '${varNamePrefix}forceInt'; +///Enum companion suffix +const String _enumCompanionSuffix = 'Enum'; /// Documentation comment spec. const DocumentCommentSpecification _docCommentSpec = @@ -117,11 +119,13 @@ class ArkTSGenerator extends StructuredGenerator { .replaceAllMapped(regex, (Match m) => '${m[1]}_${m[2]}') .toUpperCase(); } - + const List generatedEnumMessages = [ + ' Generated enum from Pigeon that represents data sent in messages.' + ]; indent.newln(); addDocumentationComments( - indent, anEnum.documentationComments, _docCommentSpec); - + indent, anEnum.documentationComments, _docCommentSpec, + generatorComments:generatedEnumMessages); indent.write('export enum ${anEnum.name} '); indent.addScoped('{', '}', () { enumerate(anEnum.members, (int index, final EnumMember member) { @@ -131,6 +135,23 @@ class ArkTSGenerator extends StructuredGenerator { '${camelToSnake(member.name)}${index == anEnum.members.length - 1 ? '' : ','}'); }); }); + const List generatedEnumCompanionMessages = [ + ''' + Generated enum Companion class from Pigeon that represents data sent + in messages.Do not delete otherwise enum type data transfer will failed''' + ]; + indent.newln(); + addDocumentationComments( + indent, anEnum.documentationComments, _docCommentSpec, + generatorComments:generatedEnumCompanionMessages); + indent.write('export class ${anEnum.name}$_enumCompanionSuffix '); + indent.addScoped('{', '}', () { + indent.writeln('index:number|null = null;'); + indent.addScoped('constructor(index:number){', '}', () { + indent.writeln('this.index = index;'); + }); + + }); } @override @@ -181,21 +202,35 @@ class ArkTSGenerator extends StructuredGenerator { NamedType field,{bool isPrimitive = false,}) { final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _arkTSTypeForBuiltinDartType(x)); - indent.writeln('private ${field.name}?: ${hostDatatype.datatype};'); - indent.newln(); - - indent.writeScoped( - 'public ${_makeSetter(field)}(${field.name}:${hostDatatype.datatype}):void {', - '}', () { - indent.writeln('this.${field.name} = ${field.name};'); - }); - - indent.newln(); - indent - .write('${_makeGetter(field)}(): ${hostDatatype.datatype} | undefined'); - indent.addScoped('{', '}', () { - indent.writeln('return this.${field.name};'); - }); + if(field.type.isEnum){ + indent.writeln('private ${field.name}?: ${hostDatatype.datatype}$_enumCompanionSuffix;'); + indent.newln(); + indent.writeScoped( + 'public ${_makeSetter(field)}(${field.name}:${hostDatatype.datatype}$_enumCompanionSuffix):void {', + '}', () { + indent.writeln('this.${field.name} = ${field.name};'); + }); + indent.newln(); + indent + .write('${_makeGetter(field)}(): ${hostDatatype.datatype}$_enumCompanionSuffix | undefined'); + indent.addScoped('{', '}', () { + indent.writeln('return this.${field.name};'); + }); + }else{ + indent.writeln('private ${field.name}?: ${hostDatatype.datatype};'); + indent.newln(); + indent.writeScoped( + 'public ${_makeSetter(field)}(${field.name}:${hostDatatype.datatype}):void {', + '}', () { + indent.writeln('this.${field.name} = ${field.name};'); + }); + indent.newln(); + indent + .write('${_makeGetter(field)}(): ${hostDatatype.datatype} | undefined'); + indent.addScoped('{', '}', () { + indent.writeln('return this.${field.name};'); + }); + } } void _writeDataClassSignature( @@ -234,7 +269,11 @@ class ArkTSGenerator extends StructuredGenerator { for (final NamedType element in klass.fields) { final String type = _arkTSTypeForDartType(element.type); final String name = getSafeConstructorArgument(element.name); - argSignature.add('$name?: $type'); + if(element.type.isEnum){ + argSignature.add('$name?: $type$_enumCompanionSuffix'); + }else{ + argSignature.add('$name?: $type'); + } } } indent.add('(${argSignature.join(', ')}) '); @@ -260,10 +299,16 @@ class ArkTSGenerator extends StructuredGenerator { indent.writeln('let arr: Object[] = new Array();'); for (final NamedType field in getFieldsInSerializationOrder(klass)) { final String fieldName = field.name; - - indent.writeScoped('if(this.$fieldName !==undefined){', '}', () { - indent.writeln('arr.push(this.$fieldName);'); - }); + if(field.type.isEnum){ + indent.writeScoped('if(this.$fieldName !==undefined){', '}', () { + indent.writeln('arr.push(Object.values(${field.type.baseName})' + '.indexOf(this.$fieldName.index! as ${field.type.baseName}));'); + }); + }else{ + indent.writeScoped('if(this.$fieldName !==undefined){', '}', () { + indent.writeln('arr.push(this.$fieldName);'); + }); + } } indent.writeln('return arr;'); }); @@ -287,9 +332,14 @@ class ArkTSGenerator extends StructuredGenerator { (int index, final NamedType field) { final String fieldVariable = field.name; final String setter = _makeSetter(field); - indent.writeln('let $fieldVariable: Object = arr[$index];'); - indent - .writeln('$result.$setter(${_castObject(field, fieldVariable)});'); + if(field.type.isEnum){ + indent + .writeln('$result.$setter(new ${field.type.baseName}$_enumCompanionSuffix(arr[$index]! as number));'); + }else{ + indent.writeln('let $fieldVariable: Object = arr[$index];'); + indent + .writeln('$result.$setter(${_castObject(field, fieldVariable)});'); + } }); indent.writeln('return ${result};'); }); @@ -307,11 +357,7 @@ class ArkTSGenerator extends StructuredGenerator { String _castObject(NamedType field, String varName) { final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _arkTSTypeForDartType(x)); - if (field.type.baseName == 'int') { - return '($varName == null) ? null : ((typeof $varName === \'number\' ) ? $varName as number: $varName as ${hostDatatype.datatype})'; - } else { - return _cast(varName, artTSType: hostDatatype.datatype); - } + return _cast(varName, artTSType: hostDatatype.datatype); } @override @@ -535,23 +581,13 @@ class ArkTSGenerator extends StructuredGenerator { final String channelName = makeChannelName(api, method, dartPackageName); indent.write(''); indent.addScoped('{', '}', () { - String? taskQueue; - if (method.taskQueueType != TaskQueueType.serial) { - taskQueue = 'taskQueue'; - indent.writeln( - 'let taskQueue: TaskQueue = binaryMessenger.makeBackgroundTaskQueue();'); - } indent.writeln('let channel: BasicMessageChannel ='); indent.nest(2, () { indent.writeln('new BasicMessageChannel('); indent.nest(2, () { indent .write('binaryMessenger, "$channelName", ${api.name}.getCodec()'); - if (taskQueue != null) { - indent.addln(', $taskQueue);'); - } else { - indent.addln(');'); - } + indent.addln(');'); }); }); indent.write('if (api != null) '); @@ -568,8 +604,13 @@ class ArkTSGenerator extends StructuredGenerator { indent.writeln( 'let args: Array = message as Array;'); enumerate(method.parameters, (int index, NamedType arg) { - final String argExpression = + String argExpression = 'args[$index] as ${_arkTSTypeForDartType(arg.type)}'; + if (method.returnType.isEnum) { + argExpression = + 'new ${_arkTSTypeForDartType(arg.type)}$_enumCompanionSuffix' + '${'(args[$index] as number)'}'; + } methodArgument.add(argExpression); }); } @@ -607,7 +648,11 @@ let $resultName: Result<$returnType> = new ResultImp(); indent.writeln('$call;'); indent.writeln('res.push(null);'); } else { - indent.writeln('let output: $returnType = $call;'); + if(method.returnType.isEnum){ + indent.writeln('let output: $returnType$_enumCompanionSuffix = $call;'); + }else{ + indent.writeln('let output: $returnType = $call;'); + } indent.writeln('res.push(output);'); } }); @@ -647,7 +692,11 @@ let $resultName: Result<$returnType> = new ResultImp(); method.parameters.map((NamedType e) => e.name); argSignature .addAll(map2(argTypes, argNames, (String argType, String argName) { - return '$argName: $argType '; + if(method.returnType.isEnum){ + return '$argName: $argType$_enumCompanionSuffix '; + }else{ + return '$argName: $argType '; + } })); } if (method.isAsynchronous) { @@ -662,8 +711,13 @@ let $resultName: Result<$returnType> = new ResultImp(); } else { indent.newln(); } - indent.writeln( - 'abstract ${method.name}(${argSignature.join(', ')}): $returnType;'); + if (method.returnType.isEnum) { + indent.writeln('abstract ${method.name}(${argSignature.join(', ')}): ' + '$returnType$_enumCompanionSuffix;'); + } else { + indent.writeln( + 'abstract ${method.name}(${argSignature.join(', ')}): $returnType;'); + } } void _writeResultInterface(Indent indent) { @@ -847,16 +901,15 @@ getByte(n: number): number { {required String dartPackageName}) { final List enumeratedTypes = getEnumeratedTypes(root).toList(); - void writeEncodeLogic(EnumeratedType customType) { - bool isEnum = customType.type != CustomTypes.customClass; + bool isEnum = customType.type == CustomTypes.customEnum; final String nullCheck = customType.type == CustomTypes.customEnum ? 'value == null ? null : ' : ''; - String valueString =""; + String valueString =''; if(isEnum){ valueString = customType.enumeration < maximumCodecFieldKey - ? '$nullCheck Object.values(${customType.name}).indexOf(value as ${customType.name})' + ? '$nullCheck Object.values(${customType.name}).indexOf(value.index as ${customType.name})' : 'wrap.toList()'; }else{ valueString = customType.enumeration < maximumCodecFieldKey @@ -867,7 +920,8 @@ getByte(n: number): number { final int enumeration = customType.enumeration < maximumCodecFieldKey ? customType.enumeration : maximumCodecFieldKey; - if(!isEnum){ + final bool isCustom = customType.type == CustomTypes.customClass; + if(isCustom){ indent.add('if (value instanceof ${customType.name}) '); indent.addScoped('{', '} else ', () { if (customType.enumeration >= maximumCodecFieldKey) { @@ -875,17 +929,28 @@ getByte(n: number): number { 'let wrap:$_overflowClassName = new $_overflowClassName();'); indent.writeln( 'wrap.setType(${customType.enumeration - maximumCodecFieldKey});'); - if (isEnum) { - indent.writeln( - 'wrap.setWrapped($nullCheck Object.values(${customType.name}).indexOf(value as ${customType.name});'); - } else { - indent.writeln( - 'wrap.setWrapped($nullCheck(value as ${customType.name}).toList());'); - } + + indent.writeln( + 'wrap.setWrapped($nullCheck(value as ${customType.name}).toList());'); } indent.writeln('stream.writeUint8(this.getByte(${enumeration}));'); indent.writeln('this.writeValue(stream, $valueString);'); }, addTrailingNewline: false); + } else { + indent.add('if (value instanceof ${customType.name}$_enumCompanionSuffix) '); + indent.addScoped('{', '} else ', () { + if (customType.enumeration >= maximumCodecFieldKey) { + indent.writeln( + 'let wrap:$_overflowClassName = new $_overflowClassName();'); + indent.writeln( + 'wrap.setType(${customType.enumeration + - maximumCodecFieldKey});'); + indent.writeln( + 'wrap.setWrapped($nullCheck(value as ${customType.name}).toList());'); + } + indent.writeln('stream.writeUint8(this.getByte($enumeration));'); + indent.writeln('this.writeValue(stream, $valueString);'); + }, addTrailingNewline: false); } } diff --git a/packages/pigeon/lib/dart_generator.dart b/packages/pigeon/lib/dart_generator.dart index df9f31759..a79b6fab2 100644 --- a/packages/pigeon/lib/dart_generator.dart +++ b/packages/pigeon/lib/dart_generator.dart @@ -246,18 +246,36 @@ class DartGenerator extends StructuredGenerator { final String castCall = _makeGenericCastCall(field.type); final String nullableTag = field.type.isNullable ? '?' : ''; if (field.type.typeArguments.isNotEmpty) { - indent.add( - '($resultAt as $genericType?)$castCallPrefix$castCall', - ); + if(field.type.isEnum){ + indent.add( + '($resultAt as ${"int"}?)$castCallPrefix$castCall', + ); + }else{ + indent.add( + '($resultAt as $genericType?)$castCallPrefix$castCall', + ); + } } else { final String castCallForcePrefix = field.type.isNullable ? '' : '!'; - final String castString = field.type.baseName == 'Object' - ? '' - : ' as $genericType$nullableTag'; - - indent.add( - '$resultAt$castCallForcePrefix$castString', - ); + String castString = ''; + if (field.type.isEnum) { + castString = field.type.baseName == 'Object' + ? '' + : ' as ${'int'}$nullableTag'; + } else { + castString = field.type.baseName == 'Object' + ? '' + : ' as $genericType$nullableTag'; + } + if(field.type.isEnum){ + indent.add( + '$genericType.values[$resultAt$castCallForcePrefix$castString]', + ); + }else{ + indent.add( + '$resultAt$castCallForcePrefix$castString', + ); + } } } @@ -271,8 +289,8 @@ class DartGenerator extends StructuredGenerator { enumerate(getFieldsInSerializationOrder(classDefinition), (int index, final NamedType field) { indent.write('${field.name}: '); - writeValueDecode(field, index); - indent.addln(','); + writeValueDecode(field, index); + indent.addln(','); }); }); }); -- Gitee