Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions packages/pigeon/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build/
e2e_tests/test_objc/ios/Flutter/
3 changes: 3 additions & 0 deletions packages/pigeon/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 0.1.0-experimental.0

* Initial release.
27 changes: 27 additions & 0 deletions packages/pigeon/LICENSE
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.
112 changes: 112 additions & 0 deletions packages/pigeon/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# 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.
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.

### 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.

## Feedback

File an issue in [flutter/flutter](https://github.com/flutter/flutter) with the
word 'pigeon' clearly in the title and cc **@gaaclarke**.
38 changes: 38 additions & 0 deletions packages/pigeon/bin/pigeon.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// 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);
String code = '';
if (opts.input != null) {
code = 'import \'${opts.input}\';\n';
}
code += """
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);
}
81 changes: 81 additions & 0 deletions packages/pigeon/lib/ast.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2014 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 Func extends Node {
/// Parametric constructor for [Func].
Func({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 [Func]s that are hosted ona given [location].
class Api extends Node {
/// Parametric constructor for [Api].
Api({this.name, this.location, this.functions});

/// The name of the API.
String name;

/// Where the API's implementation is located, host or Flutter.
ApiLocation location;

/// List of functions inside the API.
List<Func> functions;
}

/// 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;
}
114 changes: 114 additions & 0 deletions packages/pigeon/lib/dart_generator.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright 2014 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.writeln('// ignore: unused_element');
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.writeln('// ignore: unused_element');
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 (Func func in api.functions) {
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('');
} else if (api.location == ApiLocation.flutter) {
indent.write('abstract class ${api.name} ');
indent.scoped('{', '}', () {
for (Func func in api.functions) {
indent
.writeln('${func.returnType} ${func.name}(${func.argType} arg);');
}
});
indent.addln('');
indent.write('void ${api.name}Setup(${api.name} api) ');
indent.scoped('{', '}', () {
for (Func func in api.functions) {
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();');
});
});
}
});
}
}
}
Loading