forked from flutter/packages
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added experimental code generator tool for platform channels: Pigeon (f…
- Loading branch information
Showing
16 changed files
with
1,471 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
build/ | ||
e2e_tests/test_objc/ios/Flutter/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
## 0.1.0-experimental.0 | ||
|
||
* Initial release. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
Copyright 2019 The Chromium Authors. All rights reserved. | ||
|
||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions are | ||
met: | ||
|
||
* Redistributions of source code must retain the above copyright | ||
notice, this list of conditions and the following disclaimer. | ||
* Redistributions in binary form must reproduce the above | ||
copyright notice, this list of conditions and the following | ||
disclaimer in the documentation and/or other materials provided | ||
with the distribution. | ||
* Neither the name of Google Inc. nor the names of its | ||
contributors may be used to endorse or promote products derived | ||
from this software without specific prior written permission. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | ||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | ||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | ||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | ||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | ||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
# Pigeon | ||
|
||
<aside class="warning"> | ||
Pigeon is experimental and unsupported. It can be removed or changed at any time. | ||
</aside> | ||
|
||
Pigeon is a code generator tool to make communication between Flutter and the | ||
host platform type-safe and easier. | ||
|
||
## Supported Platforms | ||
|
||
Currently Pigeon only supports generating Objective-C code for usage on iOS and calling host functions from Flutter. | ||
|
||
## Runtime Requirements | ||
|
||
Pigeon generates all the code that is needed to communicate between Flutter and the host platform, there is no extra runtime requirement. A plugin author doesn't need to worry about conflicting versions of Pigeon. | ||
|
||
## Usage | ||
|
||
### Steps | ||
|
||
1) Add Pigeon as a dev_dependency. | ||
1) Make a ".dart" file outside of your "lib" directory for defining the communication interface. | ||
1) Run pigeon on your ".dart" file to generate the required Dart and Objective-C code. | ||
1) Add the generated code to your `ios/Runner.xcworkspace` XCode project for compilation. | ||
1) Implement the generated iOS protocol for handling the calls on iOS, set it up | ||
as the handler for the messages. | ||
1) Call the generated Dart methods. | ||
|
||
### Rules for defining your communication interface | ||
|
||
1) The file should contain no methods or function definitions. | ||
1) Datatypes are defined as classes with fields of the supported datatypes (see | ||
the supported Datatypes section). | ||
1) Api's should be defined as an `abstract class` with either `HostApi()` or | ||
`FlutterApi()` as metadata. The former being for procedures that are defined | ||
on the host platform and the latter for procedures that are defined in Dart. | ||
1) Method declarations on the Api classes should have one argument and a return | ||
value whose types are defined in the file. | ||
|
||
### Example | ||
|
||
#### message.dart | ||
|
||
```dart | ||
import 'package:pigeon/pigeon_lib.dart'; | ||
class SearchRequest { | ||
String query; | ||
} | ||
class SearchReply { | ||
String result; | ||
} | ||
@HostApi() | ||
abstract class Api { | ||
SearchReply search(SearchRequest request); | ||
} | ||
``` | ||
|
||
#### invocation | ||
|
||
```sh | ||
pub run pigeon \ | ||
--input pigeons/message.dart \ | ||
--dart_out lib/pigeon.dart \ | ||
--objc_header_out ios/Runner/pigeon.h \ | ||
--objc_source_out ios/Runner/pigeon.m | ||
``` | ||
|
||
#### AppDelegate.m | ||
|
||
```objc | ||
#import "AppDelegate.h" | ||
#import <Flutter/Flutter.h> | ||
#import "pigeon.h" | ||
|
||
@interface MyApi : NSObject <Api> | ||
@end | ||
|
||
@implementation MyApi | ||
-(SearchReply*)search:(SearchRequest*)request { | ||
SearchReply *reply = [[SearchReply alloc] init]; | ||
reply.result = | ||
[NSString stringWithFormat:@"Hi %@!", request.query]; | ||
return reply; | ||
} | ||
@end | ||
|
||
- (BOOL)application:(UIApplication *)application | ||
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions { | ||
MyApi *api = [[MyApi alloc] init]; | ||
ApiSetup(getFlutterEngine().binaryMessenger, api); | ||
return YES; | ||
} | ||
``` | ||
#### test.dart | ||
```dart | ||
import 'pigeon.dart'; | ||
void main() { | ||
testWidgets("test pigeon", (WidgetTester tester) async { | ||
SearchRequest request = SearchRequest()..query = "Aaron"; | ||
Api api = Api(); | ||
SearchReply reply = await api.search(request); | ||
expect(reply.result, equals("Hi Aaron!")); | ||
}); | ||
} | ||
``` | ||
|
||
## Supported Datatypes | ||
|
||
Pigeon uses the `StandardMessageCodec` so it supports any data-type platform | ||
channels supports | ||
[[documentation](https://flutter.dev/docs/development/platform-integration/platform-channels#codec)]. Nested data-types are supported, too. | ||
|
||
Note: Generics for List and Map aren't supported yet. | ||
|
||
## Feedback | ||
|
||
File an issue in [flutter/flutter](https://github.com/flutter/flutter) with the | ||
word 'pigeon' clearly in the title and cc **@gaaclarke**. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// 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 'dart:convert'; | ||
import 'dart:io'; | ||
import 'package:pigeon/pigeon_lib.dart'; | ||
|
||
Future<void> main(List<String> args) async { | ||
final PigeonOptions opts = Pigeon.parseArgs(args); | ||
assert(opts.input != null); | ||
final String importLine = | ||
(opts.input != null) ? 'import \'${opts.input}\';\n' : ''; | ||
final String code = """$importLine | ||
import 'dart:io'; | ||
import 'package:pigeon/pigeon_lib.dart'; | ||
void main(List<String> args) async { | ||
exit(await Pigeon.run(args)); | ||
} | ||
"""; | ||
// TODO(aaclarke): Start using a system temp file. | ||
const String tempFilename = '_pigeon_temp_.dart'; | ||
final File tempFile = await File(tempFilename).writeAsString(code); | ||
final Process process = | ||
await Process.start('dart', <String>[tempFilename] + args); | ||
process.stdout.transform(utf8.decoder).listen((String data) => print(data)); | ||
process.stderr.transform(utf8.decoder).listen((String data) => print(data)); | ||
final int exitCode = await process.exitCode; | ||
tempFile.deleteSync(); | ||
exit(exitCode); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
// 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. | ||
|
||
/// Enum that represents where an [Api] is located, on the host or Flutter. | ||
enum ApiLocation { | ||
/// The API is for calling functions defined on the host. | ||
host, | ||
|
||
/// The API is for calling functions defined in Flutter. | ||
flutter, | ||
} | ||
|
||
/// Superclass for all AST nodes. | ||
class Node {} | ||
|
||
/// Represents a method on an [Api]. | ||
class Method extends Node { | ||
/// Parametric constructor for [Method]. | ||
Method({this.name, this.returnType, this.argType}); | ||
|
||
/// The name of the method. | ||
String name; | ||
|
||
/// The data-type of the return value. | ||
String returnType; | ||
|
||
/// The data-type of the argument. | ||
String argType; | ||
} | ||
|
||
/// Represents a collection of [Method]s that are hosted ona given [location]. | ||
class Api extends Node { | ||
/// Parametric constructor for [Api]. | ||
Api({this.name, this.location, this.methods}); | ||
|
||
/// The name of the API. | ||
String name; | ||
|
||
/// Where the API's implementation is located, host or Flutter. | ||
ApiLocation location; | ||
|
||
/// List of methods inside the API. | ||
List<Method> methods; | ||
} | ||
|
||
/// Represents a field on a [Class]. | ||
class Field extends Node { | ||
/// Parametric constructor for [Field]. | ||
Field({this.name, this.dataType}); | ||
|
||
/// The name of the field. | ||
String name; | ||
|
||
/// The data-type of the field (ex 'String' or 'int'). | ||
String dataType; | ||
} | ||
|
||
/// Represents a class with [Field]s. | ||
class Class extends Node { | ||
/// Parametric constructor for [Class]. | ||
Class({this.name, this.fields}); | ||
|
||
/// The name of the class. | ||
String name; | ||
|
||
/// All the fields contained in the class. | ||
List<Field> fields; | ||
} | ||
|
||
/// Top-level node for the AST. | ||
class Root extends Node { | ||
/// Parametric constructor for [Root]. | ||
Root({this.classes, this.apis}); | ||
|
||
/// All the classes contained in the AST. | ||
List<Class> classes; | ||
|
||
/// All the API's contained in the AST. | ||
List<Api> apis; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
// 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 'ast.dart'; | ||
import 'generator_tools.dart'; | ||
|
||
/// Generates Dart source code for the given AST represented by [root], | ||
/// outputting the code to [sink]. | ||
void generateDart(Root root, StringSink sink) { | ||
final List<String> customClassNames = | ||
root.classes.map((Class x) => x.name).toList(); | ||
final Indent indent = Indent(sink); | ||
indent.writeln('// Autogenerated from Dartle, do not edit directly.'); | ||
indent.writeln('import \'package:flutter/services.dart\';'); | ||
indent.writeln(''); | ||
|
||
for (Class klass in root.classes) { | ||
sink.write('class ${klass.name} '); | ||
indent.scoped('{', '}', () { | ||
for (Field field in klass.fields) { | ||
indent.writeln('${field.dataType} ${field.name};'); | ||
} | ||
indent.write('Map _toMap() '); | ||
indent.scoped('{', '}', () { | ||
indent.writeln('Map dartleMap = Map();'); | ||
for (Field field in klass.fields) { | ||
indent.write('dartleMap["${field.name}"] = '); | ||
if (customClassNames.contains(field.dataType)) { | ||
indent.addln('${field.name}._toMap();'); | ||
} else { | ||
indent.addln('${field.name};'); | ||
} | ||
} | ||
indent.writeln('return dartleMap;'); | ||
}); | ||
indent.write('static ${klass.name} _fromMap(Map dartleMap) '); | ||
indent.scoped('{', '}', () { | ||
indent.writeln('var result = ${klass.name}();'); | ||
for (Field field in klass.fields) { | ||
indent.write('result.${field.name} = '); | ||
if (customClassNames.contains(field.dataType)) { | ||
indent.addln( | ||
'${field.dataType}._fromMap(dartleMap["${field.name}"]);'); | ||
} else { | ||
indent.addln('dartleMap["${field.name}"];'); | ||
} | ||
} | ||
indent.writeln('return result;'); | ||
}); | ||
}); | ||
indent.writeln(''); | ||
} | ||
for (Api api in root.apis) { | ||
if (api.location == ApiLocation.host) { | ||
indent.write('class ${api.name} '); | ||
indent.scoped('{', '}', () { | ||
for (Method func in api.methods) { | ||
indent.write( | ||
'Future<${func.returnType}> ${func.name}(${func.argType} arg) async '); | ||
indent.scoped('{', '}', () { | ||
indent.writeln('Map requestMap = arg._toMap();'); | ||
final String channelName = makeChannelName(api, func); | ||
indent.writeln('BasicMessageChannel channel ='); | ||
indent.inc(); | ||
indent.inc(); | ||
indent.writeln( | ||
'BasicMessageChannel(\'$channelName\', StandardMessageCodec());'); | ||
indent.dec(); | ||
indent.dec(); | ||
indent.writeln('Map replyMap = await channel.send(requestMap);'); | ||
indent.writeln('return ${func.returnType}._fromMap(replyMap);'); | ||
}); | ||
} | ||
}); | ||
indent.writeln(''); | ||
} | ||
} | ||
} |
Oops, something went wrong.