forked from Rexios80/packages_flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
objc_generator.dart
1571 lines (1464 loc) · 53.9 KB
/
objc_generator.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'ast.dart';
import 'functional.dart';
import 'generator.dart';
import 'generator_tools.dart';
import 'pigeon_lib.dart' show Error, TaskQueueType;
/// Documentation comment open symbol.
const String _docCommentPrefix = '///';
/// Documentation comment spec.
const DocumentCommentSpecification _docCommentSpec =
DocumentCommentSpecification(_docCommentPrefix);
/// Options that control how Objective-C code will be generated.
class ObjcOptions {
/// Parametric constructor for ObjcOptions.
const ObjcOptions({
this.headerIncludePath,
this.prefix,
this.copyrightHeader,
});
/// The path to the header that will get placed in the source filed (example:
/// "foo.h").
final String? headerIncludePath;
/// Prefix that will be appended before all generated classes and protocols.
final String? prefix;
/// A copyright header that will get prepended to generated code.
final Iterable<String>? copyrightHeader;
/// Creates a [ObjcOptions] from a Map representation where:
/// `x = ObjcOptions.fromMap(x.toMap())`.
static ObjcOptions fromMap(Map<String, Object> map) {
final Iterable<dynamic>? copyrightHeader =
map['copyrightHeader'] as Iterable<dynamic>?;
return ObjcOptions(
headerIncludePath: map['header'] as String?,
prefix: map['prefix'] as String?,
copyrightHeader: copyrightHeader?.cast<String>(),
);
}
/// Converts a [ObjcOptions] to a Map representation where:
/// `x = ObjcOptions.fromMap(x.toMap())`.
Map<String, Object> toMap() {
final Map<String, Object> result = <String, Object>{
if (headerIncludePath != null) 'header': headerIncludePath!,
if (prefix != null) 'prefix': prefix!,
if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!,
};
return result;
}
/// Overrides any non-null parameters from [options] into this to make a new
/// [ObjcOptions].
ObjcOptions merge(ObjcOptions options) {
return ObjcOptions.fromMap(mergeMaps(toMap(), options.toMap()));
}
}
/// Class that manages all Objc code generation.
class ObjcGenerator extends Generator<OutputFileOptions<ObjcOptions>> {
/// Instantiates a Objc Generator.
const ObjcGenerator();
/// Generates Objc file of type specified in [generatorOptions]
@override
void generate(
OutputFileOptions<ObjcOptions> generatorOptions,
Root root,
StringSink sink, {
required String dartPackageName,
}) {
if (generatorOptions.fileType == FileType.header) {
const ObjcHeaderGenerator().generate(
generatorOptions.languageOptions,
root,
sink,
dartPackageName: dartPackageName,
);
} else if (generatorOptions.fileType == FileType.source) {
const ObjcSourceGenerator().generate(
generatorOptions.languageOptions,
root,
sink,
dartPackageName: dartPackageName,
);
}
}
}
/// Generates Objc .h file.
class ObjcHeaderGenerator extends StructuredGenerator<ObjcOptions> {
/// Constructor.
const ObjcHeaderGenerator();
@override
void writeFilePrologue(
ObjcOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
if (generatorOptions.copyrightHeader != null) {
addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// ');
}
indent.writeln('// ${getGeneratedCodeWarning()}');
indent.writeln('// $seeAlsoWarning');
indent.newln();
}
@override
void writeFileImports(
ObjcOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
indent.writeln('#import <Foundation/Foundation.h>');
indent.newln();
indent.writeln('@protocol FlutterBinaryMessenger;');
indent.writeln('@protocol FlutterMessageCodec;');
indent.writeln('@class FlutterError;');
indent.writeln('@class FlutterStandardTypedData;');
indent.newln();
indent.writeln('NS_ASSUME_NONNULL_BEGIN');
}
@override
void writeEnum(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Enum anEnum, {
required String dartPackageName,
}) {
final String enumName =
_enumName(anEnum.name, prefix: generatorOptions.prefix);
indent.newln();
addDocumentationComments(
indent, anEnum.documentationComments, _docCommentSpec);
indent.write('typedef NS_ENUM(NSUInteger, $enumName) ');
indent.addScoped('{', '};', () {
enumerate(anEnum.members, (int index, final EnumMember member) {
addDocumentationComments(
indent, member.documentationComments, _docCommentSpec);
// Capitalized first letter to ensure Swift compatibility
indent.writeln(
'$enumName${member.name[0].toUpperCase()}${member.name.substring(1)} = $index,');
});
});
_writeEnumWrapper(indent, enumName);
}
void _writeEnumWrapper(Indent indent, String enumName) {
indent.newln();
indent.writeln('/// Wrapper for $enumName to allow for nullability.');
indent.writeln(
'@interface ${_enumName(enumName, prefix: '', box: true)} : NSObject');
indent.writeln('@property(nonatomic, assign) $enumName value;');
indent.writeln('- (instancetype)initWithValue:($enumName)value;');
indent.writeln('@end');
}
@override
void writeDataClasses(
ObjcOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
indent.newln();
for (final Class classDefinition in root.classes) {
indent.writeln(
'@class ${_className(generatorOptions.prefix, classDefinition.name)};');
}
indent.newln();
super.writeDataClasses(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
}
@override
void writeDataClass(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
final List<Class> classes = root.classes;
final List<Enum> enums = root.enums;
final String? prefix = generatorOptions.prefix;
addDocumentationComments(
indent, classDefinition.documentationComments, _docCommentSpec);
indent.writeln(
'@interface ${_className(prefix, classDefinition.name)} : NSObject');
if (getFieldsInSerializationOrder(classDefinition).isNotEmpty) {
if (getFieldsInSerializationOrder(classDefinition)
.map((NamedType e) => !e.type.isNullable)
.any((bool e) => e)) {
indent.writeln(
'$_docCommentPrefix `init` unavailable to enforce nonnull fields, see the `make` class method.');
indent.writeln('- (instancetype)init NS_UNAVAILABLE;');
}
_writeObjcSourceClassInitializerDeclaration(
indent,
generatorOptions,
root,
classDefinition,
classes,
enums,
prefix,
);
indent.addln(';');
}
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
final HostDatatype hostDatatype = getFieldHostDatatype(
field,
(TypeDeclaration x) => _objcTypeStringForPrimitiveDartType(prefix, x,
beforeString: true),
customResolver: field.type.isEnum
? (String x) => _enumName(x, prefix: prefix)
: (String x) => '${_className(prefix, x)} *');
late final String propertyType;
addDocumentationComments(
indent, field.documentationComments, _docCommentSpec);
propertyType = _propertyTypeForDartType(field.type,
isNullable: field.type.isNullable, isEnum: field.type.isEnum);
final String nullability = field.type.isNullable ? ', nullable' : '';
final String fieldType = field.type.isEnum && field.type.isNullable
? _enumName(field.type.baseName,
suffix: ' *',
prefix: generatorOptions.prefix,
box: field.type.isNullable)
: hostDatatype.datatype;
indent.writeln(
'@property(nonatomic, $propertyType$nullability) $fieldType ${field.name};');
}
indent.writeln('@end');
indent.newln();
}
@override
void writeClassEncode(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {}
@override
void writeClassDecode(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {}
@override
void writeApis(
ObjcOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
super.writeApis(generatorOptions, root, indent,
dartPackageName: dartPackageName);
indent.writeln('NS_ASSUME_NONNULL_END');
}
@override
void writeFlutterApi(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Api api, {
required String dartPackageName,
}) {
indent.writeln(
'$_docCommentPrefix The codec used by ${_className(generatorOptions.prefix, api.name)}.');
indent.writeln(
'NSObject<FlutterMessageCodec> *${_getCodecGetterName(generatorOptions.prefix, api.name)}(void);');
indent.newln();
final String apiName = _className(generatorOptions.prefix, api.name);
addDocumentationComments(
indent, api.documentationComments, _docCommentSpec);
indent.writeln('@interface $apiName : NSObject');
indent.writeln(
'- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;');
indent.writeln(
'- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger messageChannelSuffix:(nullable NSString *)messageChannelSuffix;');
for (final Method func in api.methods) {
final _ObjcType returnType = _objcTypeForDartType(
generatorOptions.prefix, func.returnType,
// Nullability is required since the return must be nil if NSError is set.
forceNullability: true,
);
final String callbackType =
_callbackForType(func.returnType, returnType, generatorOptions);
addDocumentationComments(
indent, func.documentationComments, _docCommentSpec);
indent.writeln('${_makeObjcSignature(
func: func,
options: generatorOptions,
returnType: 'void',
lastArgName: 'completion',
lastArgType: callbackType,
)};');
}
indent.writeln('@end');
indent.newln();
}
@override
void writeHostApi(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Api api, {
required String dartPackageName,
}) {
indent.writeln(
'$_docCommentPrefix The codec used by ${_className(generatorOptions.prefix, api.name)}.');
indent.writeln(
'NSObject<FlutterMessageCodec> *${_getCodecGetterName(generatorOptions.prefix, api.name)}(void);');
indent.newln();
final String apiName = _className(generatorOptions.prefix, api.name);
addDocumentationComments(
indent, api.documentationComments, _docCommentSpec);
indent.writeln('@protocol $apiName');
for (final Method func in api.methods) {
final _ObjcType returnTypeName = _objcTypeForDartType(
generatorOptions.prefix,
func.returnType,
// Nullability is required since the return must be nil if NSError is
// set.
forceNullability: true,
);
String? lastArgName;
String? lastArgType;
String? returnType;
final String enumReturnType = _enumName(
func.returnType.baseName,
suffix: ' *_Nullable',
prefix: generatorOptions.prefix,
box: true,
);
if (func.isAsynchronous) {
returnType = 'void';
lastArgName = 'completion';
if (func.returnType.isVoid) {
lastArgType = 'void (^)(FlutterError *_Nullable)';
} else if (func.returnType.isEnum) {
lastArgType = 'void (^)($enumReturnType, FlutterError *_Nullable)';
} else {
lastArgType =
'void (^)(${returnTypeName.beforeString}_Nullable, FlutterError *_Nullable)';
}
} else {
if (func.returnType.isVoid) {
returnType = 'void';
} else if (func.returnType.isEnum) {
returnType = enumReturnType;
} else {
returnType = 'nullable $returnTypeName';
}
lastArgType = 'FlutterError *_Nullable *_Nonnull';
lastArgName = 'error';
}
final List<String> generatorComments = <String>[];
if (!func.returnType.isNullable &&
!func.returnType.isVoid &&
!func.isAsynchronous) {
generatorComments.add(' @return `nil` only when `error != nil`.');
}
addDocumentationComments(
indent, func.documentationComments, _docCommentSpec,
generatorComments: generatorComments);
final String signature = _makeObjcSignature(
func: func,
options: generatorOptions,
returnType: returnType,
lastArgName: lastArgName,
lastArgType: lastArgType,
);
indent.writeln('$signature;');
}
indent.writeln('@end');
indent.newln();
indent.writeln(
'extern void SetUp$apiName(id<FlutterBinaryMessenger> binaryMessenger, NSObject<$apiName> *_Nullable api);');
indent.newln();
indent.writeln(
'extern void SetUp${apiName}WithSuffix(id<FlutterBinaryMessenger> binaryMessenger, NSObject<$apiName> *_Nullable api, NSString *messageChannelSuffix);');
indent.newln();
}
}
/// Generates Objc .m file.
class ObjcSourceGenerator extends StructuredGenerator<ObjcOptions> {
/// Constructor.
const ObjcSourceGenerator();
@override
void writeFilePrologue(
ObjcOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
if (generatorOptions.copyrightHeader != null) {
addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// ');
}
indent.writeln('// ${getGeneratedCodeWarning()}');
indent.writeln('// $seeAlsoWarning');
indent.newln();
}
@override
void writeFileImports(
ObjcOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
indent.writeln('#import "${generatorOptions.headerIncludePath}"');
indent.newln();
indent.writeln('#if TARGET_OS_OSX');
indent.writeln('#import <FlutterMacOS/FlutterMacOS.h>');
indent.writeln('#else');
indent.writeln('#import <Flutter/Flutter.h>');
indent.writeln('#endif');
indent.newln();
indent.writeln('#if !__has_feature(objc_arc)');
indent.writeln('#error File requires ARC to be enabled.');
indent.writeln('#endif');
indent.newln();
}
@override
void writeEnum(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Enum anEnum, {
required String dartPackageName,
}) {
final String enumName =
_enumName(anEnum.name, prefix: generatorOptions.prefix);
indent.newln();
addDocumentationComments(
indent, anEnum.documentationComments, _docCommentSpec);
indent.writeln(
'@implementation ${_enumName(enumName, prefix: '', box: true)}');
indent.writeScoped('- (instancetype)initWithValue:($enumName)value {', '}',
() {
indent.writeln('self = [super init];');
indent.writeScoped('if (self) {', '}', () {
indent.writeln('_value = value;');
});
indent.writeln('return self;');
});
indent.writeln('@end');
}
@override
void writeDataClasses(
ObjcOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
for (final Class classDefinition in root.classes) {
_writeObjcSourceDataClassExtension(
generatorOptions, indent, classDefinition);
}
indent.newln();
super.writeDataClasses(
generatorOptions,
root,
indent,
dartPackageName: dartPackageName,
);
}
@override
void writeDataClass(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
final Set<String> customClassNames =
root.classes.map((Class x) => x.name).toSet();
final Set<String> customEnumNames =
root.enums.map((Enum x) => x.name).toSet();
final String className =
_className(generatorOptions.prefix, classDefinition.name);
indent.writeln('@implementation $className');
_writeObjcSourceClassInitializer(generatorOptions, root, indent,
classDefinition, customClassNames, customEnumNames, className);
writeClassDecode(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
writeClassEncode(
generatorOptions,
root,
indent,
classDefinition,
dartPackageName: dartPackageName,
);
indent.writeln('@end');
indent.newln();
}
@override
void writeClassEncode(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
indent.write('- (NSArray *)toList ');
indent.addScoped('{', '}', () {
indent.write('return');
indent.addScoped(' @[', '];', () {
for (final NamedType field in classDefinition.fields) {
indent.writeln('${_arrayValue(field)},');
}
});
});
}
@override
void writeClassDecode(
ObjcOptions generatorOptions,
Root root,
Indent indent,
Class classDefinition, {
required String dartPackageName,
}) {
final String className =
_className(generatorOptions.prefix, classDefinition.name);
indent.write('+ ($className *)fromList:(NSArray *)list ');
indent.addScoped('{', '}', () {
const String resultName = 'pigeonResult';
indent.writeln('$className *$resultName = [[$className alloc] init];');
enumerate(getFieldsInSerializationOrder(classDefinition),
(int index, final NamedType field) {
final bool isEnumType = field.type.isEnum;
final String valueGetter = 'GetNullableObjectAtIndex(list, $index)';
final String? primitiveExtractionMethod =
_nsnumberExtractionMethod(field.type);
final String ivarValueExpression;
if (primitiveExtractionMethod != null) {
ivarValueExpression = '[$valueGetter $primitiveExtractionMethod]';
} else if (isEnumType) {
indent.writeln('NSNumber *${field.name}AsNumber = $valueGetter;');
indent.writeln(
'${_enumName(field.type.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: true)}${field.name} = ${field.name}AsNumber == nil ? nil : [[${_enumName(field.type.baseName, prefix: generatorOptions.prefix, box: true)} alloc] initWithValue:[${field.name}AsNumber integerValue]];');
ivarValueExpression = field.name;
} else {
ivarValueExpression = valueGetter;
}
indent.writeln('$resultName.${field.name} = $ivarValueExpression;');
});
indent.writeln('return $resultName;');
});
indent.write('+ (nullable $className *)nullableFromList:(NSArray *)list ');
indent.addScoped('{', '}', () {
indent.writeln('return (list) ? [$className fromList:list] : nil;');
});
}
void _writeCodecAndGetter(
ObjcOptions generatorOptions, Root root, Indent indent, Api api) {
final String codecName = _getCodecName(generatorOptions.prefix, api.name);
if (getCodecClasses(api, root).isNotEmpty) {
_writeCodec(indent, codecName, generatorOptions, api, root);
indent.newln();
}
_writeCodecGetter(indent, codecName, generatorOptions, api, root);
indent.newln();
}
@override
void writeFlutterApi(
ObjcOptions generatorOptions,
Root root,
Indent indent,
AstFlutterApi api, {
required String dartPackageName,
}) {
final String apiName = _className(generatorOptions.prefix, api.name);
_writeCodecAndGetter(generatorOptions, root, indent, api);
_writeExtension(indent, apiName);
indent.newln();
indent.writeln('@implementation $apiName');
indent.newln();
_writeInitializers(indent);
for (final Method func in api.methods) {
_writeMethod(
generatorOptions,
root,
indent,
api,
func,
dartPackageName: dartPackageName,
);
}
indent.writeln('@end');
indent.newln();
}
@override
void writeHostApi(
ObjcOptions generatorOptions,
Root root,
Indent indent,
AstHostApi api, {
required String dartPackageName,
}) {
final String apiName = _className(generatorOptions.prefix, api.name);
_writeCodecAndGetter(generatorOptions, root, indent, api);
const String channelName = 'channel';
indent.write(
'void SetUp$apiName(id<FlutterBinaryMessenger> binaryMessenger, NSObject<$apiName> *api) ');
indent.addScoped('{', '}', () {
indent.writeln('SetUp${apiName}WithSuffix(binaryMessenger, api, @"");');
});
indent.newln();
indent.write(
'void SetUp${apiName}WithSuffix(id<FlutterBinaryMessenger> binaryMessenger, NSObject<$apiName> *api, NSString *messageChannelSuffix) ');
indent.addScoped('{', '}', () {
indent.writeln(
'messageChannelSuffix = messageChannelSuffix.length > 0 ? [NSString stringWithFormat: @".%@", messageChannelSuffix] : @"";');
for (final Method func in api.methods) {
addDocumentationComments(
indent, func.documentationComments, _docCommentSpec);
indent.writeScoped('{', '}', () {
String? taskQueue;
if (func.taskQueueType != TaskQueueType.serial) {
taskQueue = 'taskQueue';
indent.writeln(
'NSObject<FlutterTaskQueue> *$taskQueue = [binaryMessenger makeBackgroundTaskQueue];');
}
_writeChannelAllocation(
generatorOptions,
indent,
api,
func,
channelName,
taskQueue,
dartPackageName: dartPackageName,
);
indent.write('if (api) ');
indent.addScoped('{', '}', () {
_writeChannelApiBinding(
generatorOptions, root, indent, apiName, func, channelName);
}, addTrailingNewline: false);
indent.add(' else ');
indent.addScoped('{', '}', () {
indent.writeln('[$channelName setMessageHandler:nil];');
});
});
}
});
}
@override
void writeGeneralUtilities(
ObjcOptions generatorOptions,
Root root,
Indent indent, {
required String dartPackageName,
}) {
final bool hasHostApi = root.apis
.whereType<AstHostApi>()
.any((Api api) => api.methods.isNotEmpty);
final bool hasFlutterApi = root.apis
.whereType<AstFlutterApi>()
.any((Api api) => api.methods.isNotEmpty);
if (hasHostApi) {
_writeWrapError(indent);
indent.newln();
}
if (hasFlutterApi) {
_writeCreateConnectionError(indent);
indent.newln();
}
if (hasHostApi || hasFlutterApi) {
_writeGetNullableObjectAtIndex(indent);
}
}
void _writeWrapError(Indent indent) {
indent.format('''
static NSArray *wrapResult(id result, FlutterError *error) {
\tif (error) {
\t\treturn @[
\t\t\terror.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null]
\t\t];
\t}
\treturn @[ result ?: [NSNull null] ];
}''');
}
void _writeGetNullableObjectAtIndex(Indent indent) {
indent.format('''
static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) {
\tid result = array[key];
\treturn (result == [NSNull null]) ? nil : result;
}''');
}
void _writeCreateConnectionError(Indent indent) {
indent.format('''
static FlutterError *createConnectionError(NSString *channelName) {
\treturn [FlutterError errorWithCode:@"channel-error" message:[NSString stringWithFormat:@"%@/%@/%@", @"Unable to establish connection on channel: '", channelName, @"'."] details:@""];
}''');
}
void _writeChannelApiBinding(ObjcOptions generatorOptions, Root root,
Indent indent, String apiName, Method func, String channel) {
void unpackArgs(String variable) {
indent.writeln('NSArray *args = $variable;');
int count = 0;
for (final NamedType arg in func.parameters) {
final String argName = _getSafeArgName(count, arg);
final String valueGetter = 'GetNullableObjectAtIndex(args, $count)';
final String? primitiveExtractionMethod =
_nsnumberExtractionMethod(arg.type);
final _ObjcType objcArgType = _objcTypeForDartType(
generatorOptions.prefix,
arg.type,
);
if (primitiveExtractionMethod != null) {
indent.writeln(
'${objcArgType.beforeString}$argName = [$valueGetter $primitiveExtractionMethod];');
} else if (arg.type.isEnum) {
indent.writeln('NSNumber *${argName}AsNumber = $valueGetter;');
indent.writeln(
'${_enumName(arg.type.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: true)}$argName = ${argName}AsNumber == nil ? nil : [[${_enumName(arg.type.baseName, prefix: generatorOptions.prefix, box: true)} alloc] initWithValue:[${argName}AsNumber integerValue]];');
} else {
indent.writeln('${objcArgType.beforeString}$argName = $valueGetter;');
}
count++;
}
}
void writeAsyncBindings(Iterable<String> selectorComponents,
String callSignature, _ObjcType returnType) {
if (func.returnType.isVoid) {
const String callback = 'callback(wrapResult(nil, error));';
if (func.parameters.isEmpty) {
indent.writeScoped(
'[api ${selectorComponents.first}:^(FlutterError *_Nullable error) {',
'}];', () {
indent.writeln(callback);
});
} else {
indent.writeScoped(
'[api $callSignature ${selectorComponents.last}:^(FlutterError *_Nullable error) {',
'}];', () {
indent.writeln(callback);
});
}
} else {
const String callback = 'callback(wrapResult(output, error));';
String returnTypeString = '${returnType.beforeString}_Nullable output';
const String numberOutput = 'NSNumber *output =';
const String enumConversionExpression =
'enumValue == nil ? nil : [NSNumber numberWithInteger:enumValue.value];';
if (func.returnType.isEnum) {
returnTypeString =
'${_enumName(func.returnType.baseName, suffix: ' *_Nullable', prefix: generatorOptions.prefix, box: true)} enumValue';
}
if (func.parameters.isEmpty) {
indent.writeScoped(
'[api ${selectorComponents.first}:^($returnTypeString, FlutterError *_Nullable error) {',
'}];', () {
if (func.returnType.isEnum) {
indent.writeln('$numberOutput $enumConversionExpression');
}
indent.writeln(callback);
});
} else {
indent.writeScoped(
'[api $callSignature ${selectorComponents.last}:^($returnTypeString, FlutterError *_Nullable error) {',
'}];', () {
if (func.returnType.isEnum) {
indent.writeln('$numberOutput $enumConversionExpression');
}
indent.writeln(callback);
});
}
}
}
void writeSyncBindings(String call, _ObjcType returnType) {
indent.writeln('FlutterError *error;');
if (func.returnType.isVoid) {
indent.writeln('$call;');
indent.writeln('callback(wrapResult(nil, error));');
} else {
if (func.returnType.isEnum) {
indent.writeln(
'${_enumName(func.returnType.baseName, suffix: ' *', prefix: generatorOptions.prefix, box: true)} enumBox = $call;');
indent.writeln(
'NSNumber *output = enumBox == nil ? nil : [NSNumber numberWithInteger:enumBox.value];');
} else {
indent.writeln('${returnType.beforeString}output = $call;');
}
indent.writeln('callback(wrapResult(output, error));');
}
}
// TODO(gaaclarke): Incorporate this into _getSelectorComponents.
final String lastSelectorComponent =
func.isAsynchronous ? 'completion' : 'error';
final String selector = _getSelector(func, lastSelectorComponent);
indent.writeln(
'NSCAssert([api respondsToSelector:@selector($selector)], @"$apiName api (%@) doesn\'t respond to @selector($selector)", api);');
indent.write(
'[$channel setMessageHandler:^(id _Nullable message, FlutterReply callback) ');
indent.addScoped('{', '}];', () {
final _ObjcType returnType = _objcTypeForDartType(
generatorOptions.prefix, func.returnType,
// Nullability is required since the return must be nil if NSError is set.
forceNullability: true,
);
final Iterable<String> selectorComponents =
_getSelectorComponents(func, lastSelectorComponent);
final Iterable<String> argNames =
indexMap(func.parameters, _getSafeArgName);
final String callSignature =
map2(selectorComponents.take(argNames.length), argNames,
(String selectorComponent, String argName) {
return '$selectorComponent:$argName';
}).join(' ');
if (func.parameters.isNotEmpty) {
unpackArgs('message');
}
if (func.isAsynchronous) {
writeAsyncBindings(selectorComponents, callSignature, returnType);
} else {
final String syncCall = func.parameters.isEmpty
? '[api ${selectorComponents.first}:&error]'
: '[api $callSignature error:&error]';
writeSyncBindings(syncCall, returnType);
}
});
}
void _writeChannelAllocation(
ObjcOptions generatorOptions,
Indent indent,
Api api,
Method func,
String varName,
String? taskQueue, {
required String dartPackageName,
}) {
indent.writeln('FlutterBasicMessageChannel *$varName =');
indent.nest(1, () {
indent.writeln('[[FlutterBasicMessageChannel alloc]');
indent.nest(1, () {
indent.writeln(
'initWithName:[NSString stringWithFormat:@"%@%@", @"${makeChannelName(api, func, dartPackageName)}", messageChannelSuffix]');
indent.writeln('binaryMessenger:binaryMessenger');
indent.write('codec:');
indent
.add('${_getCodecGetterName(generatorOptions.prefix, api.name)}()');
if (taskQueue != null) {
indent.newln();
indent.addln('taskQueue:$taskQueue];');
} else {
indent.addln('];');
}
});
});
}
void _writeObjcSourceDataClassExtension(
ObjcOptions languageOptions, Indent indent, Class classDefinition) {
final String className =
_className(languageOptions.prefix, classDefinition.name);
indent.newln();
indent.writeln('@interface $className ()');
indent.writeln('+ ($className *)fromList:(NSArray *)list;');
indent
.writeln('+ (nullable $className *)nullableFromList:(NSArray *)list;');
indent.writeln('- (NSArray *)toList;');
indent.writeln('@end');
}
void _writeObjcSourceClassInitializer(
ObjcOptions languageOptions,
Root root,
Indent indent,
Class classDefinition,
Set<String> customClassNames,
Set<String> customEnumNames,
String className,
) {
_writeObjcSourceClassInitializerDeclaration(
indent,
languageOptions,
root,
classDefinition,
root.classes,
root.enums,
languageOptions.prefix,
);
indent.writeScoped(' {', '}', () {
const String result = 'pigeonResult';
indent.writeln('$className* $result = [[$className alloc] init];');
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
indent.writeln('$result.${field.name} = ${field.name};');
}
indent.writeln('return $result;');
});
}
/// Writes the codec that will be used for encoding messages for the [api].
///
/// Example:
/// @interface FooHostApiCodecReader : FlutterStandardReader
/// ...
/// @interface FooHostApiCodecWriter : FlutterStandardWriter
/// ...
/// @interface FooHostApiCodecReaderWriter : FlutterStandardReaderWriter
/// ...
/// NSObject<FlutterMessageCodec> *FooHostApiCodecGetCodec(void) {...}
void _writeCodec(
Indent indent, String name, ObjcOptions options, Api api, Root root) {
assert(getCodecClasses(api, root).isNotEmpty);
final Iterable<EnumeratedClass> codecClasses = getCodecClasses(api, root);
final String readerWriterName = '${name}ReaderWriter';
final String readerName = '${name}Reader';
final String writerName = '${name}Writer';
indent.writeln('@interface $readerName : FlutterStandardReader');
indent.writeln('@end');
indent.writeln('@implementation $readerName');
indent.write('- (nullable id)readValueOfType:(UInt8)type ');
indent.addScoped('{', '}', () {
indent.write('switch (type) ');
indent.addScoped('{', '}', () {
for (final EnumeratedClass customClass in codecClasses) {
indent.writeln('case ${customClass.enumeration}: ');
indent.nest(1, () {
indent.writeln(
'return [${_className(options.prefix, customClass.name)} fromList:[self readValue]];');
});
}
indent.writeln('default:');
indent.nest(1, () {