Skip to content
Merged
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.
126 changes: 126 additions & 0 deletions packages/pigeon/README.md
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.
Comment thread
blasten marked this conversation as resolved.
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
Comment thread
mklim marked this conversation as resolved.
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 \
Comment thread
mklim marked this conversation as resolved.
--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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is this actually calling the objective-C implementation under the hood?

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.

Yep.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I think from other conversations on this PR this actually doesn't support the full range, so it's worth mentioning that as a caveat here. The platform channels codec does support stuff like Map<int, List<String>> natively.

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.

added to README


Note: Generics for List and Map aren't supported yet.

## Feedback

File an issue in [flutter/flutter](https://github.com/flutter/flutter) with the
Comment thread
mklim marked this conversation as resolved.
word 'pigeon' clearly in the title and cc **@gaaclarke**.
32 changes: 32 additions & 0 deletions packages/pigeon/bin/pigeon.dart
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What if the file already exists? Can you use createTempSync?

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.

That's the plan, added a todo. It's not trivial since I have to make dart able to read in the current package from a different directory.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what if the main process is killed before reaching this line? It probably needs to handle SIGINT and SIGTERM. e.g. https://github.com/flutter/flutter/blob/ec2d58335a1b4273ddc0f855bd3666d8bc0b09b6/packages/flutter_tools/lib/src/commands/logs.dart#L69-L77

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.

I don't think so. If the subprocess is killed with a signal that will be represented in the exit code. I don't need to take any special different action.

FWIW I'd like to get this executing in an isolate instead of a subprocess eventually to avoid the overhead of a new process. This was the easiest thing to get up and running for now.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this probably needs the copyright header. Same for each of the source code files in this PR.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: Copyright header in Dart files like this should be the current year. It's just the engine that has older dates, I'm not sure why.

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

enum ApiLocation {
/// The API is for calling functions defined on the host.
host,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: what about platform? I'm thinking about the plugin case.

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.

That will use the terminology 'host' as well. It means the language you'd be writing in if you were writing in Flutter.


/// 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what about this type extend an ApiType? It could have multiple constructors, including one that points to the Class type defined down below.

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.

These are typically generated and consumed behind the scenes. If these were getting generated by users, trying to provide more type support could be helpful. I don't think there is any benefit as things stand.

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.

Sorry, didn't explain this well. We have to represent syntactically correct, semantically incorrect AST's. If I made the proposed change we wouldn't be able to do that which would limit our ability to report errors.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For my prototype I needed this to be a class in order to handle generics FWIW. I couldn't store things like Map<int, List<String>> in just a string.


/// The data-type of the argument.
String argType;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ditto

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.

ditto

}

/// 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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should each of this entities have a location in code? The location contains the line number and column, which can be used to provide syntax errors? e.g. a type or construct isn't supported, etc..

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.

Yep, we'll have to have that in the future. That is already showing up in my Error class. It's also why I have the Node superclass, i'll probably put source and line in that.

79 changes: 79 additions & 0 deletions packages/pigeon/lib/dart_generator.dart
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';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: copyright header

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

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.');
Comment thread
mklim marked this conversation as resolved.
indent.writeln('import \'package:flutter/services.dart\';');
indent.writeln('');

for (Class klass in root.classes) {
Comment thread
mklim marked this conversation as resolved.
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('{', '}', () {
Comment thread
mklim marked this conversation as resolved.
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('');
}
}
}
Loading