Visitar URL original
[pigeon] added code generator for host->flutter calls for objc by gaaclarke · Pull Request #88 · flutter/packages · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/pigeon/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.1.0-experimental.1

* Added Host->Flutter calls for Objective-C

## 0.1.0-experimental.0

* Initial release.
5 changes: 2 additions & 3 deletions packages/pigeon/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# Pigeon

<aside class="warning">
Pigeon is experimental and unsupported. It can be removed or changed at any time.
</aside>
**Warning: Pigeon is experimental and unsupported. It can be removed or changed
at any time.**

Pigeon is a code generator tool to make communication between Flutter and the
host platform type-safe and easier.
Expand Down
35 changes: 35 additions & 0 deletions packages/pigeon/lib/dart_generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ void generateDart(Root root, StringSink sink) {
for (Field field in klass.fields) {
indent.writeln('${field.dataType} ${field.name};');
}
indent.writeln('// ignore: unused_element');
indent.write('Map _toMap() ');
indent.scoped('{', '}', () {
indent.writeln('Map dartleMap = Map();');
Expand All @@ -34,6 +35,7 @@ void generateDart(Root root, StringSink sink) {
}
indent.writeln('return dartleMap;');
});
indent.writeln('// ignore: unused_element');
indent.write('static ${klass.name} _fromMap(Map dartleMap) ');
indent.scoped('{', '}', () {
indent.writeln('var result = ${klass.name}();');
Expand Down Expand Up @@ -74,6 +76,39 @@ void generateDart(Root root, StringSink sink) {
}
});
indent.writeln('');
} else if (api.location == ApiLocation.flutter) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

subjective style nit: At this point I'd this point this function should really be split up into private helper methods. It's really long, multiple levels of scoping and for loops, and relatively complex. I think it's OK to have private helper methods that are just called once, it brings the cyclomatic complexity of whatever the reader has to understand at one point down.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, split off some helper functions

indent.write('abstract class ${api.name} ');
indent.scoped('{', '}', () {
for (Method func in api.methods) {
indent
.writeln('${func.returnType} ${func.name}(${func.argType} arg);');
}
});
indent.addln('');
indent.write('void ${api.name}Setup(${api.name} api) ');
indent.scoped('{', '}', () {
for (Method func in api.methods) {
indent.write('');
indent.scoped('{', '}', () {
indent.writeln('BasicMessageChannel channel =');
indent.inc();
indent.inc();
indent.writeln(
'BasicMessageChannel("${makeChannelName(api, func)}", StandardMessageCodec());');
indent.dec();
indent.dec();
indent.write('channel.setMessageHandler((dynamic message) async ');
indent.scoped('{', '});', () {
final String argType = func.argType;
final String returnType = func.returnType;
indent.writeln('Map mapMessage = message as Map;');
indent.writeln('$argType input = $argType._fromMap(mapMessage);');
indent.writeln('$returnType output = api.${func.name}(input);');
indent.writeln('return output._toMap();');
});
});
}
});
}
}
}
59 changes: 57 additions & 2 deletions packages/pigeon/lib/objc_generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ void generateObjcHeader(ObjcOptions options, Root root, StringSink sink) {
}

for (Api api in root.apis) {
final String apiName = _className(options.prefix, api.name);
if (api.location == ApiLocation.host) {
final String apiName = _className(options.prefix, api.name);
indent.writeln('@protocol $apiName');
for (Method func in api.methods) {
final String returnType = _className(options.prefix, func.returnType);
Expand All @@ -109,6 +109,17 @@ void generateObjcHeader(ObjcOptions options, Root root, StringSink sink) {
indent.writeln(
'extern void ${apiName}Setup(id<FlutterBinaryMessenger> binaryMessenger, id<$apiName> api);');
indent.writeln('');
} else if (api.location == ApiLocation.flutter) {
indent.writeln('@interface $apiName : NSObject');
indent.writeln(
'- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger;');
for (Method func in api.methods) {
final String returnType = _className(options.prefix, func.returnType);
final String argType = _className(options.prefix, func.argType);
indent.writeln(
'- (void)${func.name}:($argType*)input completion:(void(^)($returnType*, NSError*))completion;');
}
indent.writeln('@end');
}
}
}
Expand Down Expand Up @@ -181,8 +192,8 @@ void generateObjcSource(ObjcOptions options, Root root, StringSink sink) {
}

for (Api api in root.apis) {
final String apiName = _className(options.prefix, api.name);
if (api.location == ApiLocation.host) {
final String apiName = _className(options.prefix, api.name);
indent.write(
'void ${apiName}Setup(id<FlutterBinaryMessenger> binaryMessenger, id<$apiName> api) ');
indent.scoped('{', '}', () {
Expand Down Expand Up @@ -212,6 +223,50 @@ void generateObjcSource(ObjcOptions options, Root root, StringSink sink) {
});
}
});
} else if (api.location == ApiLocation.flutter) {
indent.writeln('@interface $apiName ()');
indent.writeln(
'@property (nonatomic, strong) NSObject<FlutterBinaryMessenger>* binaryMessenger;');
indent.writeln('@end');
indent.addln('');
indent.writeln('@implementation $apiName');
indent.write(
'- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger>*)binaryMessenger ');
indent.scoped('{', '}', () {
indent.writeln('self = [super init];');
indent.write('if (self) ');
indent.scoped('{', '}', () {
indent.writeln('self.binaryMessenger = binaryMessenger;');
});
indent.writeln('return self;');
});
indent.addln('');
for (Method func in api.methods) {
final String returnType = _className(options.prefix, func.returnType);
final String argType = _className(options.prefix, func.argType);
indent.write(
'- (void)${func.name}:($argType*)input completion:(void(^)($returnType*, NSError*))completion ');
indent.scoped('{', '}', () {
indent.writeln('FlutterBasicMessageChannel *channel =');
indent.inc();
indent.writeln('[FlutterBasicMessageChannel');
indent.inc();
indent.writeln(
'messageChannelWithName:@"${makeChannelName(api, func)}"');
indent.writeln('binaryMessenger:self.binaryMessenger];');
indent.dec();
indent.dec();
indent.writeln('NSDictionary* inputMap = [input toMap];');
indent.write('[channel sendMessage:inputMap reply:^(id reply) ');
indent.scoped('{', '}];', () {
indent.writeln('NSDictionary* outputMap = reply;');
indent.writeln(
'$returnType * output = [$returnType fromMap:outputMap];');
indent.writeln('completion(output, nil);');
});
});
}
indent.writeln('@end');
}
}
}
41 changes: 25 additions & 16 deletions packages/pigeon/lib/pigeon_lib.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ class Error {
}

bool _isApi(ClassMirror classMirror) {
return classMirror.isAbstract && _isHostApi(classMirror);
return classMirror.isAbstract &&
(_isHostApi(classMirror) || _isFlutterApi(classMirror));
}

bool _isHostApi(ClassMirror apiMirror) {
Expand All @@ -64,6 +65,15 @@ bool _isHostApi(ClassMirror apiMirror) {
return false;
}

bool _isFlutterApi(ClassMirror apiMirror) {
for (InstanceMirror instance in apiMirror.metadata) {
if (instance.reflectee is FlutterApi) {
return true;
}
}
return false;
}

/// Options used when running the code generator.
class PigeonOptions {
/// Path to the file which will be processed.
Expand Down Expand Up @@ -144,23 +154,22 @@ class Pigeon {

root.apis = <Api>[];
for (ClassMirror apiMirror in apis) {
if (_isHostApi(apiMirror)) {
final List<Method> methods = <Method>[];
for (DeclarationMirror declaration in apiMirror.declarations.values) {
if (declaration is MethodMirror && !declaration.isConstructor) {
methods.add(Method()
..name = MirrorSystem.getName(declaration.simpleName)
..argType = MirrorSystem.getName(
declaration.parameters[0].type.simpleName)
..returnType =
MirrorSystem.getName(declaration.returnType.simpleName));
}
final List<Method> functions = <Method>[];
for (DeclarationMirror declaration in apiMirror.declarations.values) {
if (declaration is MethodMirror && !declaration.isConstructor) {
functions.add(Method()
..name = MirrorSystem.getName(declaration.simpleName)
..argType =
MirrorSystem.getName(declaration.parameters[0].type.simpleName)
..returnType =
MirrorSystem.getName(declaration.returnType.simpleName));
}
root.apis.add(Api()
..name = MirrorSystem.getName(apiMirror.simpleName)
..location = ApiLocation.host
..methods = methods);
}
root.apis.add(Api()
..name = MirrorSystem.getName(apiMirror.simpleName)
..location =
_isHostApi(apiMirror) ? ApiLocation.host : ApiLocation.flutter
..methods = functions);
}

final List<Error> validateErrors = _validateAst(root);
Expand Down
22 changes: 22 additions & 0 deletions packages/pigeon/pigeons/host2flutter.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright 2020 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:pigeon/pigeon_lib.dart';

class SearchRequest {
String query;
}

class SearchReply {
String result;
}

@FlutterApi()
abstract class Api {
SearchReply search(SearchRequest request);
}

void setupPigeon(PigeonOptions options) {
options.objcOptions.prefix = 'AC';
}
5 changes: 5 additions & 0 deletions packages/pigeon/pigeons/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,8 @@ abstract class NestedApi {
void setupPigeon(PigeonOptions options) {
options.objcOptions.prefix = 'AC';
}

@FlutterApi()
abstract class FlutterSearchApi {
SearchReply search(SearchRequest request);
}
2 changes: 1 addition & 1 deletion packages/pigeon/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: pigeon
version: 0.1.0-experimental.0
version: 0.1.0-experimental.1
description: Code generator tool to make communication between Flutter and the host platform type-safe and easier.
homepage: https://github.com/flutter/packages/tree/master/packages/pigeon
dependencies:
Expand Down
87 changes: 52 additions & 35 deletions packages/pigeon/run_tests.sh
Original file line number Diff line number Diff line change
@@ -1,40 +1,57 @@
# exit when any command fails
set -e

flutter=$(which flutter)
flutter_bin=$(dirname $flutter)
framework_path="$flutter_bin/cache/artifacts/engine/ios/"

test_pigeon_ios() {
temp_dir=$(mktemp -d -t pigeon)

pub run pigeon \
--input $1 \
--dart_out $temp_dir/pigeon.dart \
--objc_header_out $temp_dir/pigeon.h \
--objc_source_out $temp_dir/pigeon.m

xcrun clang \
-arch arm64 \
-isysroot $(xcrun --sdk iphoneos --show-sdk-path) \
-F $framework_path \
-Werror \
-c $temp_dir/pigeon.m \
-o $temp_dir/pigeon.o

dartfmt -w $temp_dir/pigeon.dart
if [ -e "e2e_tests" ]; then
dartanalyzer $temp_dir/pigeon.dart --packages ./e2e_tests/test_objc/.packages
fi
rm -rf $temp_dir
}

pub run test test/
test_pigeon_ios ./pigeons/message.dart
test_pigeon_ios ./pigeons/host2flutter.dart

# e2e tests are not checked in until some issues can be worked out with e2e.
if [ -e "e2e_tests" ]; then
DARTLE_H="e2e_tests/test_objc/ios/Runner/dartle.h"
DARTLE_M="e2e_tests/test_objc/ios/Runner/dartle.m"
DARTLE_DART="e2e_tests/test_objc/lib/dartle.dart"
pub run pigeon \
--input pigeons/message.dart \
--dart_out $DARTLE_DART \
--objc_header_out $DARTLE_H \
--objc_source_out $DARTLE_M
dartfmt -w $DARTLE_DART
cd e2e_tests/test_objc

# cd build
# make
# ./dartle --input ../dartles/simple.dartle --dart_out dartle.dart --objc_header_out dartle.h --objc_source_out dartle.m
# cd ..
# cp build/dartle.h tests/test_objc/ios/Runner/
# cp build/dartle.m tests/test_objc/ios/Runner/
# cp build/dartle.dart tests/test_objc/lib/

# e2e tests are disabled while I work to fix iOS e2e.
# DARTLE_H="e2e_tests/test_objc/ios/Runner/dartle.h"
# DARTLE_M="e2e_tests/test_objc/ios/Runner/dartle.m"
# DARTLE_DART="e2e_tests/test_objc/lib/dartle.dart"
# pub run pigeon \
# --input pigeons/message.dart \
# --dart_out $DARTLE_DART \
# --objc_header_out $DARTLE_H \
# --objc_source_out $DARTLE_M
# dartfmt -w $DARTLE_DART
# cd e2e_tests/test_objc

#############################################
# Uncomment to just launch the app.
#############################################
# open -a Simulator
# flutter run
# exit

# flutter build ios -t test/e2e_test.dart --simulator
# cd ios
# xcodebuild \
# -workspace Runner.xcworkspace \
# -scheme RunnerTests \
# -sdk iphonesimulator \
# -destination 'platform=iOS Simulator,name=iPhone 8' \
# test | xcpretty
flutter build ios -t test/e2e_test.dart --simulator
cd ios
xcodebuild \
-workspace Runner.xcworkspace \
-scheme RunnerTests \
-sdk iphonesimulator \
-destination 'platform=iOS Simulator,name=iPhone 8' \
test | xcpretty
fi
20 changes: 20 additions & 0 deletions packages/pigeon/test/dart_generator_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,24 @@ void main() {
expect(
code, contains('result.nested = Input._fromMap(dartleMap["nested"]);'));
});

test('flutterapi', () {
final Root root = Root(apis: <Api>[
Api(name: 'Api', location: ApiLocation.flutter, methods: <Method>[
Method(name: 'doSomething', argType: 'Input', returnType: 'Output')
])
], classes: <Class>[
Class(
name: 'Input',
fields: <Field>[Field(name: 'input', dataType: 'String')]),
Class(
name: 'Output',
fields: <Field>[Field(name: 'output', dataType: 'String')])
]);
final StringBuffer sink = StringBuffer();
generateDart(root, sink);
final String code = sink.toString();
expect(code, contains('abstract class Api'));
expect(code, contains('void ApiSetup(Api'));
});
}
Loading