Flutter channels for iOS (flutter/engine#3470)

Flutter channels now also supported on iOS. Use FlutterMessageChannel or FlutterMethodChannel with binary/string/json/standard codecs.
This commit is contained in:
Mikkel Nygaard Ravn
2017-03-13 23:57:46 +01:00
committed by GitHub
parent b0063039a9
commit 6afc504feb
24 changed files with 1420 additions and 148 deletions

View File

@@ -22,6 +22,11 @@ group("flutter") {
# If on the host, compile all unittests targets.
if (current_toolchain == host_toolchain) {
if (is_mac) {
deps += [
"//flutter/shell/platform/darwin:flutter_channels_unittests",
]
}
deps += [
"//flutter/sky/engine/wtf:wtf_unittests",
"//flutter/synchronization:synchronization_unittests",

View File

@@ -7,6 +7,7 @@ package io.flutter.plugin.common;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
@@ -58,6 +59,7 @@ public final class StandardMessageCodec implements MessageCodec<Object> {
if (message == null || !message.hasRemaining()) {
return null;
}
message.order(ByteOrder.nativeOrder());
final Object value = readValue(message);
if (message.hasRemaining()) {
throw new IllegalArgumentException("Message corrupted");
@@ -65,6 +67,7 @@ public final class StandardMessageCodec implements MessageCodec<Object> {
return value;
}
private static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN;
private static final Charset UTF8 = Charset.forName("UTF8");
private static final byte NULL = 0;
private static final byte TRUE = 1;
@@ -87,30 +90,57 @@ public final class StandardMessageCodec implements MessageCodec<Object> {
stream.write(value);
} else if (value <= 0xffff) {
stream.write(254);
stream.write(value >>> 8);
stream.write(value);
writeChar(stream, value);
} else {
stream.write(255);
writeInt(stream, value);
}
}
private static void writeChar(ByteArrayOutputStream stream, int value) {
if (LITTLE_ENDIAN) {
stream.write(value);
stream.write(value >>> 8);
} else {
stream.write(value >>> 8);
stream.write(value);
}
}
private static void writeInt(ByteArrayOutputStream stream, int value) {
stream.write(value >>> 24);
stream.write(value >>> 16);
stream.write(value >>> 8);
stream.write(value);
if (LITTLE_ENDIAN) {
stream.write(value);
stream.write(value >>> 8);
stream.write(value >>> 16);
stream.write(value >>> 24);
} else {
stream.write(value >>> 24);
stream.write(value >>> 16);
stream.write(value >>> 8);
stream.write(value);
}
}
private static void writeLong(ByteArrayOutputStream stream, long value) {
stream.write((byte) (value >>> 56));
stream.write((byte) (value >>> 48));
stream.write((byte) (value >>> 40));
stream.write((byte) (value >>> 32));
stream.write((byte) (value >>> 24));
stream.write((byte) (value >>> 16));
stream.write((byte) (value >>> 8));
stream.write((byte) value);
if (LITTLE_ENDIAN) {
stream.write((byte) value);
stream.write((byte) (value >>> 8));
stream.write((byte) (value >>> 16));
stream.write((byte) (value >>> 24));
stream.write((byte) (value >>> 32));
stream.write((byte) (value >>> 40));
stream.write((byte) (value >>> 48));
stream.write((byte) (value >>> 56));
} else {
stream.write((byte) (value >>> 56));
stream.write((byte) (value >>> 48));
stream.write((byte) (value >>> 40));
stream.write((byte) (value >>> 32));
stream.write((byte) (value >>> 24));
stream.write((byte) (value >>> 16));
stream.write((byte) (value >>> 8));
stream.write((byte) value);
}
}
private static void writeDouble(ByteArrayOutputStream stream, double value) {
@@ -213,13 +243,9 @@ public final class StandardMessageCodec implements MessageCodec<Object> {
if (value < 254) {
return value;
} else if (value == 254) {
return ((buffer.get() & 0xff) << 8)
| ((buffer.get() & 0xff));
return buffer.getChar();
} else {
return ((buffer.get() & 0xff) << 24)
| ((buffer.get() & 0xff) << 16)
| ((buffer.get() & 0xff) << 8)
| ((buffer.get() & 0xff));
return buffer.getInt();
}
}

View File

@@ -6,6 +6,7 @@ package io.flutter.plugin.common;
import io.flutter.plugin.common.StandardMessageCodec.ExposedByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* A {@link MethodCodec} using the Flutter standard binary encoding.
@@ -26,6 +27,7 @@ public final class StandardMethodCodec implements MethodCodec {
@Override
public MethodCall decodeMethodCall(ByteBuffer methodCall) {
methodCall.order(ByteOrder.nativeOrder());
final Object method = StandardMessageCodec.readValue(methodCall);
final Object arguments = StandardMessageCodec.readValue(methodCall);
if (method instanceof String) {

View File

@@ -18,3 +18,52 @@ group("darwin") {
assert(false, "Unknown darwin platform type.")
}
}
source_set("flutter_channels") {
set_sources_assignment_filter([])
sources = [
"ios/framework/Headers/FlutterBinaryMessenger.h",
"ios/framework/Headers/FlutterChannels.h",
"ios/framework/Headers/FlutterCodecs.h",
"ios/framework/Source/FlutterChannels.mm",
"ios/framework/Source/FlutterCodecs.mm",
"ios/framework/Source/FlutterStandardCodec_Internal.h",
"ios/framework/Source/FlutterStandardCodec.mm",
"common/buffer_conversions.h",
"common/buffer_conversions.mm",
]
set_sources_assignment_filter(sources_assignment_filter)
deps = [
"//base",
"//base:i18n",
"//dart/runtime:libdart",
"//flutter/common",
"//flutter/flow",
"//flutter/fml",
"//flutter/runtime",
"//flutter/shell/common",
"//flutter/shell/gpu",
"//flutter/shell/testing",
"//flutter/sky/engine/wtf",
"//lib/ftl",
"//third_party/skia",
]
}
executable("flutter_channels_unittests") {
testonly = true
set_sources_assignment_filter([])
sources = [
"ios/framework/Source/flutter_codecs_unittest.mm",
"ios/framework/Source/flutter_standard_codec_unittest.mm",
]
set_sources_assignment_filter(sources_assignment_filter)
deps = [
":flutter_channels",
"//flutter/testing",
]
}

View File

@@ -11,8 +11,8 @@ source_set("common") {
"platform_mac.mm",
"process_info_mac.cc",
"process_info_mac.h",
"string_conversions.h",
"string_conversions.mm",
"buffer_conversions.h",
"buffer_conversions.mm",
]
set_sources_assignment_filter(sources_assignment_filter)

View File

@@ -0,0 +1,20 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_BUFFER_CONVERSIONS_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_BUFFER_CONVERSIONS_H_
#include <Foundation/Foundation.h>
#include <vector>
namespace shell {
std::vector<uint8_t> GetVectorFromNSData(NSData* data);
NSData* GetNSDataFromVector(const std::vector<uint8_t>& buffer);
} // namespace shell
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_BUFFER_CONVERSIONS_H_

View File

@@ -0,0 +1,20 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/common/buffer_conversions.h"
namespace shell {
std::vector<uint8_t> GetVectorFromNSData(NSData* data) {
if (!data.length)
return std::vector<uint8_t>();
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(data.bytes);
return std::vector<uint8_t>(bytes, bytes + data.length);
}
NSData* GetNSDataFromVector(const std::vector<uint8_t>& buffer) {
return [NSData dataWithBytes:buffer.data() length:buffer.size()];
}
} // namespace shell

View File

@@ -1,20 +0,0 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_STRING_CONVERSIONS_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_STRING_CONVERSIONS_H_
#include <Foundation/Foundation.h>
#include <vector>
namespace shell {
std::vector<uint8_t> GetVectorFromNSString(NSString* string);
NSString* GetNSStringFromVector(const std::vector<uint8_t>& buffer);
} // namespace shell
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_STRING_CONVERSIONS_H_

View File

@@ -1,25 +0,0 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/common/string_conversions.h"
namespace shell {
std::vector<uint8_t> GetVectorFromNSString(NSString* string) {
if (!string.length)
return std::vector<uint8_t>();
const char* chars = string.UTF8String;
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(chars);
return std::vector<uint8_t>(bytes, bytes + strlen(chars));
}
NSString* GetNSStringFromVector(const std::vector<uint8_t>& buffer) {
NSString* string = [[NSString alloc] initWithBytes:buffer.data()
length:buffer.size()
encoding:NSUTF8StringEncoding];
[string autorelease];
return string;
}
} // namespace shell

View File

@@ -18,12 +18,17 @@ shared_library("flutter_framework_dylib") {
"framework/Headers/Flutter.h",
"framework/Headers/FlutterAppDelegate.h",
"framework/Headers/FlutterAsyncMessageListener.h",
"framework/Headers/FlutterChannels.h",
"framework/Headers/FlutterCodecs.h",
"framework/Headers/FlutterBinaryMessenger.h",
"framework/Headers/FlutterDartProject.h",
"framework/Headers/FlutterJSONMessageListener.h",
"framework/Headers/FlutterMacros.h",
"framework/Headers/FlutterMessageListener.h",
"framework/Headers/FlutterViewController.h",
"framework/Source/FlutterAppDelegate.mm",
"framework/Source/FlutterChannels.mm",
"framework/Source/FlutterCodecs.mm",
"framework/Source/FlutterDartProject.mm",
"framework/Source/FlutterDartProject_Internal.h",
"framework/Source/FlutterDartSource.h",
@@ -31,6 +36,8 @@ shared_library("flutter_framework_dylib") {
"framework/Source/FlutterJSONMessageListener.mm",
"framework/Source/FlutterPlatformPlugin.h",
"framework/Source/FlutterPlatformPlugin.mm",
"framework/Source/FlutterStandardCodec_Internal.h",
"framework/Source/FlutterStandardCodec.mm",
"framework/Source/FlutterTextInputDelegate.h",
"framework/Source/FlutterTextInputPlugin.h",
"framework/Source/FlutterTextInputPlugin.mm",
@@ -152,6 +159,9 @@ copy("framework_headers") {
"framework/Headers/Flutter.h",
"framework/Headers/FlutterAppDelegate.h",
"framework/Headers/FlutterAsyncMessageListener.h",
"framework/Headers/FlutterBinaryMessenger.h",
"framework/Headers/FlutterChannels.h",
"framework/Headers/FlutterCodecs.h",
"framework/Headers/FlutterDartProject.h",
"framework/Headers/FlutterJSONMessageListener.h",
"framework/Headers/FlutterMacros.h",

View File

@@ -7,6 +7,9 @@
#include "FlutterAppDelegate.h"
#include "FlutterAsyncMessageListener.h"
#include "FlutterBinaryMessenger.h"
#include "FlutterChannels.h"
#include "FlutterCodecs.h"
#include "FlutterDartProject.h"
#include "FlutterJSONMessageListener.h"
#include "FlutterMacros.h"

View File

@@ -0,0 +1,29 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERBINARYMESSAGES_H_
#define FLUTTER_FLUTTERBINARYMESSAGES_H_
#import <Foundation/Foundation.h>
#include "FlutterMacros.h"
typedef void (^FlutterBinaryReplyHandler)(NSData* reply);
typedef void (^FlutterBinaryMessageHandler)(
NSData* message,
FlutterBinaryReplyHandler replyHandler);
FLUTTER_EXPORT
@protocol FlutterBinaryMessenger<NSObject>
- (void)sendBinaryMessage:(NSData*)message channelName:(NSString*)channelName;
- (void)sendBinaryMessage:(NSData*)message
channelName:(NSString*)channelName
binaryReplyHandler:(FlutterBinaryReplyHandler)handler;
- (void)setBinaryMessageHandlerOnChannel:(NSString*)channelName
binaryMessageHandler:(FlutterBinaryMessageHandler)handler;
@end
#endif // FLUTTER_FLUTTERBINARYMESSAGES_H_

View File

@@ -0,0 +1,44 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERCHANNELS_H_
#define FLUTTER_FLUTTERCHANNELS_H_
#include "FlutterBinaryMessenger.h"
#include "FlutterCodecs.h"
typedef void (^FlutterReplyHandler)(id reply);
typedef void (^FlutterMessageHandler)(id message,
FlutterReplyHandler replyHandler);
FLUTTER_EXPORT
@interface FlutterMessageChannel : NSObject
+ (instancetype)messageChannelNamed:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMessageCodec>*)codec;
- (void)sendMessage:(id)message replyHandler:(FlutterReplyHandler)handler;
- (void)setMessageHandler:(FlutterMessageHandler)handler;
@end
typedef void (^FlutterResultReceiver)(id successResult,
FlutterError* errorResult);
typedef void (^FlutterEventReceiver)(id successEvent,
FlutterError* errorEvent,
BOOL done);
typedef void (^FlutterMethodCallHandler)(FlutterMethodCall* call,
FlutterResultReceiver resultReceiver);
typedef void (^FlutterStreamHandler)(FlutterMethodCall* call,
FlutterResultReceiver resultReceiver,
FlutterEventReceiver eventReceiver);
FLUTTER_EXPORT
@interface FlutterMethodChannel : NSObject
+ (instancetype)methodChannelNamed:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec;
- (void)setMethodCallHandler:(FlutterMethodCallHandler)handler;
- (void)setStreamHandler:(FlutterStreamHandler)handler;
@end
#endif // FLUTTER_FLUTTERCHANNELS_H_

View File

@@ -0,0 +1,93 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLUTTERCODECS_H_
#define FLUTTER_FLUTTERCODECS_H_
#import <Foundation/Foundation.h>
#include "FlutterMacros.h"
FLUTTER_EXPORT
@protocol FlutterMessageCodec
+ (instancetype)sharedInstance;
- (NSData*)encode:(id)message;
- (id)decode:(NSData*)message;
@end
FLUTTER_EXPORT
@interface FlutterBinaryCodec : NSObject<FlutterMessageCodec>
@end
FLUTTER_EXPORT
@interface FlutterStringCodec : NSObject<FlutterMessageCodec>
@end
FLUTTER_EXPORT
@interface FlutterJSONMessageCodec : NSObject<FlutterMessageCodec>
@end
FLUTTER_EXPORT
@interface FlutterStandardMessageCodec : NSObject<FlutterMessageCodec>
@end
FLUTTER_EXPORT
@interface FlutterMethodCall : NSObject
+ (instancetype)methodCallWithMethodName:(NSString*)method
arguments:(id)arguments;
@property(readonly) NSString* method;
@property(readonly) id arguments;
@end
FLUTTER_EXPORT
@interface FlutterError : NSObject
+ (instancetype)errorWithCode:(NSString*)code
message:(NSString*)message
details:(id)details;
@property(readonly) NSString* code;
@property(readonly) NSString* message;
@property(readonly) id details;
@end
typedef NS_ENUM(NSInteger, FlutterStandardDataType) {
FlutterStandardDataTypeUInt8,
FlutterStandardDataTypeInt32,
FlutterStandardDataTypeInt64,
FlutterStandardDataTypeFloat64,
};
FLUTTER_EXPORT
@interface FlutterStandardTypedData : NSObject
+ (instancetype)typedDataWithBytes:(NSData*)data;
+ (instancetype)typedDataWithInt32:(NSData*)data;
+ (instancetype)typedDataWithInt64:(NSData*)data;
+ (instancetype)typedDataWithFloat64:(NSData*)data;
@property(readonly) NSData* data;
@property(readonly) FlutterStandardDataType type;
@property(readonly) UInt32 elementCount;
@property(readonly) UInt8 elementSize;
@end
FLUTTER_EXPORT
@interface FlutterStandardBigInteger : NSObject
+ (instancetype)bigIntegerWithHex:(NSString*)hex;
@property(readonly) NSString* hex;
@end
FLUTTER_EXPORT
@protocol FlutterMethodCodec
+ (instancetype)sharedInstance;
- (FlutterMethodCall*)decodeMethodCall:(NSData*)message;
- (NSData*)encodeSuccessEnvelope:(id)result;
- (NSData*)encodeErrorEnvelope:(FlutterError*)error;
@end
FLUTTER_EXPORT
@interface FlutterJSONMethodCodec : NSObject<FlutterMethodCodec>
@end
FLUTTER_EXPORT
@interface FlutterStandardMethodCodec : NSObject<FlutterMethodCodec>
@end
#endif // FLUTTER_FLUTTERCODECS_H_

View File

@@ -9,12 +9,13 @@
#include <sys/cdefs.h>
#include "FlutterAsyncMessageListener.h"
#include "FlutterBinaryMessenger.h"
#include "FlutterDartProject.h"
#include "FlutterMacros.h"
#include "FlutterMessageListener.h"
FLUTTER_EXPORT
@interface FlutterViewController : UIViewController
@interface FlutterViewController : UIViewController<FlutterBinaryMessenger>
- (instancetype)initWithProject:(FlutterDartProject*)project
nibName:(NSString*)nibNameOrNil
@@ -37,8 +38,7 @@ FLUTTER_EXPORT
- (void)removeAsyncMessageListener:
(NSObject<FlutterAsyncMessageListener>*)listener;
- (void)handleStatusBarTouches:(UIEvent *)event;
- (void)handleStatusBarTouches:(UIEvent*)event;
@end
__BEGIN_DECLS

View File

@@ -0,0 +1,200 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterChannels.h"
#pragma mark - Basic message channel
@implementation FlutterMessageChannel {
NSObject<FlutterBinaryMessenger>* _messenger;
NSString* _name;
NSObject<FlutterMessageCodec>* _codec;
}
+ (instancetype)messageChannelNamed:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMessageCodec>*)codec {
return [[[FlutterMessageChannel alloc] initWithName:name
binaryMessenger:messenger
codec:codec] autorelease];
}
- (instancetype)initWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMessageCodec>*)codec {
if (self = [super init]) {
_name = [name retain];
_messenger = [messenger retain];
_codec = [codec retain];
}
return self;
}
- (void)dealloc {
[_name release];
[_messenger release];
[_codec release];
[super dealloc];
}
- (void)sendMessage:(id)message replyHandler:(FlutterReplyHandler)handler {
[_messenger sendBinaryMessage:[_codec encode:message]
channelName:_name
binaryReplyHandler:^(NSData* reply) {
if (handler)
handler([_codec decode:reply]);
}];
}
- (void)setMessageHandler:(FlutterMessageHandler)handler {
if (handler) {
[_messenger setBinaryMessageHandlerOnChannel:_name
binaryMessageHandler:^(
NSData* message,
FlutterBinaryReplyHandler replyHandler) {
handler([_codec decode:message], ^(id reply) {
replyHandler([_codec encode:reply]);
});
}];
} else {
[_messenger setBinaryMessageHandlerOnChannel:_name
binaryMessageHandler:nil];
}
}
@end
#pragma mark - Method channel
@implementation FlutterError
+ (instancetype)errorWithCode:(NSString*)code
message:(NSString*)message
details:(id)details {
return
[[[FlutterError alloc] initWithCode:code message:message details:details]
autorelease];
}
- (instancetype)initWithCode:(NSString*)code
message:(NSString*)message
details:(id)details {
if (self = [super init]) {
_code = [code retain];
_message = [message retain];
_details = [details retain];
}
return self;
}
- (void)dealloc {
[_code release];
[_message release];
[_details release];
[super dealloc];
}
@end
@implementation FlutterMethodCall
+ (instancetype)methodCallWithMethodName:(NSString*)method
arguments:(id)arguments {
return [[[FlutterMethodCall alloc] initWithMethodName:method
arguments:arguments] autorelease];
}
- (instancetype)initWithMethodName:(NSString*)method arguments:(id)arguments {
if (self = [super init]) {
_method = [method retain];
_arguments = [arguments retain];
}
return self;
}
- (void)dealloc {
[_method release];
[_arguments release];
[super dealloc];
}
@end
@implementation FlutterMethodChannel {
NSObject<FlutterBinaryMessenger>* _messenger;
NSString* _name;
NSObject<FlutterMethodCodec>* _codec;
}
+ (instancetype)methodChannelNamed:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec {
return [[[FlutterMethodChannel alloc] initWithName:name
binaryMessenger:messenger
codec:codec] autorelease];
}
- (instancetype)initWithName:(NSString*)name
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger
codec:(NSObject<FlutterMethodCodec>*)codec {
if (self = [super init]) {
_name = [name retain];
_messenger = [messenger retain];
_codec = [codec retain];
}
return self;
}
- (void)dealloc {
[_name release];
[_messenger release];
[_codec release];
[super dealloc];
}
- (void)setMethodCallHandler:(FlutterMethodCallHandler)handler {
[_messenger
setBinaryMessageHandlerOnChannel:_name
binaryMessageHandler:^(NSData* message,
FlutterBinaryReplyHandler reply) {
FlutterMethodCall* call = [_codec decodeMethodCall:message];
handler(call, ^(id result, FlutterError* error) {
if (error)
reply([_codec encodeErrorEnvelope:error]);
else
reply([_codec encodeSuccessEnvelope:result]);
});
}];
}
- (void)setStreamHandler:(FlutterStreamHandler)handler {
if (!handler) {
[_messenger setBinaryMessageHandlerOnChannel:_name
binaryMessageHandler:nil];
return;
}
[_messenger
setBinaryMessageHandlerOnChannel:_name
binaryMessageHandler:^(NSData* message,
FlutterBinaryReplyHandler reply) {
FlutterMethodCall* call = [_codec decodeMethodCall:message];
handler(
call,
^(id result, FlutterError* error) {
if (error)
reply([_codec encodeErrorEnvelope:error]);
else
reply([_codec encodeSuccessEnvelope:nil]);
},
^(id event, FlutterError* error, BOOL done) {
if (error)
[_messenger
sendBinaryMessage:[_codec
encodeErrorEnvelope:error]
channelName:_name];
else if (done)
[_messenger sendBinaryMessage:[NSData data]
channelName:_name];
else
[_messenger sendBinaryMessage:
[_codec encodeSuccessEnvelope:event]
channelName:_name];
});
}];
}
@end

View File

@@ -0,0 +1,97 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterCodecs.h"
@implementation FlutterBinaryCodec
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
_sharedInstance = [FlutterBinaryCodec new];
}
return _sharedInstance;
}
- (NSData*)encode:(NSData*)message {
return message;
}
- (NSData*)decode:(NSData*)message {
return message;
}
@end
@implementation FlutterStringCodec
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
_sharedInstance = [FlutterStringCodec new];
}
return _sharedInstance;
}
- (NSData*)encode:(NSString*)message {
if (!message.length) {
return [NSData data];
}
const char* utf8 = message.UTF8String;
return [NSData dataWithBytes:utf8 length:strlen(utf8)];
}
- (NSString*)decode:(NSData*)message {
return [[[NSString alloc] initWithData:message encoding:NSUTF8StringEncoding]
autorelease];
}
@end
@implementation FlutterJSONMessageCodec
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
_sharedInstance = [FlutterJSONMessageCodec new];
}
return _sharedInstance;
}
- (NSData*)encode:(id)message {
NSData* encoding =
[NSJSONSerialization dataWithJSONObject:message options:0 error:nil];
NSAssert(encoding, @"Invalid JSON message, encoding failed");
return encoding;
}
- (id)decode:(NSData*)message {
id decoded =
[NSJSONSerialization JSONObjectWithData:message options:0 error:nil];
NSAssert(decoded, @"Invalid JSON message, decoding failed");
return decoded;
}
@end
@implementation FlutterJSONMethodCodec
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
_sharedInstance = [FlutterJSONMethodCodec new];
}
return _sharedInstance;
}
- (NSData*)encodeSuccessEnvelope:(id)result {
return [[FlutterJSONMessageCodec sharedInstance] encode:@[ result ]];
}
- (NSData*)encodeErrorEnvelope:(FlutterError*)error {
return [[FlutterJSONMessageCodec sharedInstance]
encode:@[ error.code, error.message, error.details ]];
}
- (FlutterMethodCall*)decodeMethodCall:(NSData*)message {
NSArray* call = [[FlutterJSONMessageCodec sharedInstance] decode:message];
NSAssert(call.count == 2, @"Invalid JSON method call");
NSAssert([call[0] isKindOfClass:[NSString class]],
@"Invalid JSON method call");
return [FlutterMethodCall methodCallWithMethodName:call[0] arguments:call[1]];
}
@end

View File

@@ -0,0 +1,408 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "FlutterStandardCodec_Internal.h"
#pragma mark - Codec for basic message channel
@implementation FlutterStandardMessageCodec
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
_sharedInstance = [FlutterStandardMessageCodec new];
}
return _sharedInstance;
}
- (NSData*)encode:(id)message {
NSMutableData* data = [NSMutableData dataWithCapacity:32];
FlutterStandardWriter* writer = [FlutterStandardWriter writerWithData:data];
[writer writeValue:message];
return data;
}
- (id)decode:(NSData*)message {
FlutterStandardReader* reader =
[FlutterStandardReader readerWithData:message];
id value = [reader readValue];
NSAssert(![reader hasMore], @"Corrupted standard message");
return value;
}
@end
#pragma mark - Codec for method channel
@implementation FlutterStandardMethodCodec
+ (instancetype)sharedInstance {
static id _sharedInstance = nil;
if (!_sharedInstance) {
_sharedInstance = [FlutterStandardMethodCodec new];
}
return _sharedInstance;
}
- (NSData*)encodeSuccessEnvelope:(id)result {
NSMutableData* data = [NSMutableData dataWithCapacity:32];
FlutterStandardWriter* writer = [FlutterStandardWriter writerWithData:data];
[writer writeByte:0];
[writer writeValue:result];
return data;
}
- (NSData*)encodeErrorEnvelope:(FlutterError*)error {
NSMutableData* data = [NSMutableData dataWithCapacity:32];
FlutterStandardWriter* writer = [FlutterStandardWriter writerWithData:data];
[writer writeByte:1];
[writer writeValue:error.code];
[writer writeValue:error.message];
[writer writeValue:error.details];
return data;
}
- (FlutterMethodCall*)decodeMethodCall:(NSData*)message {
FlutterStandardReader* reader =
[FlutterStandardReader readerWithData:message];
id value1 = [reader readValue];
id value2 = [reader readValue];
NSAssert(![reader hasMore], @"Corrupted standard method call");
NSAssert([value1 isKindOfClass:[NSString class]],
@"Corrupted standard method call");
return [FlutterMethodCall methodCallWithMethodName:value1 arguments:value2];
}
@end
using namespace shell;
#pragma mark - Standard serializable types
@implementation FlutterStandardTypedData
+ (instancetype)typedDataWithBytes:(NSData*)data {
return
[FlutterStandardTypedData typedDataWithData:data
type:FlutterStandardDataTypeUInt8];
}
+ (instancetype)typedDataWithInt32:(NSData*)data {
return
[FlutterStandardTypedData typedDataWithData:data
type:FlutterStandardDataTypeInt32];
}
+ (instancetype)typedDataWithInt64:(NSData*)data {
return
[FlutterStandardTypedData typedDataWithData:data
type:FlutterStandardDataTypeInt64];
}
+ (instancetype)typedDataWithFloat64:(NSData*)data {
return [FlutterStandardTypedData
typedDataWithData:data
type:FlutterStandardDataTypeFloat64];
}
+ (instancetype)typedDataWithData:(NSData*)data
type:(FlutterStandardDataType)type {
return [[[FlutterStandardTypedData alloc] initWithData:data type:type]
autorelease];
}
- (instancetype)initWithData:(NSData*)data type:(FlutterStandardDataType)type {
UInt8 elementSize = elementSizeForFlutterStandardDataType(type);
NSAssert(data.length % elementSize == 0,
@"Data must contain integral number of elements");
if (self = [super init]) {
_data = [data retain];
_type = type;
_elementSize = elementSize;
_elementCount = data.length / elementSize;
}
return self;
}
- (void)dealloc {
[_data release];
[super dealloc];
}
@end
@implementation FlutterStandardBigInteger
+ (instancetype)bigIntegerWithHex:(NSString*)hex {
return [[[FlutterStandardBigInteger alloc] initWithHex:hex] autorelease];
}
- (instancetype)initWithHex:(NSString*)hex {
if (self = [super init]) {
_hex = [hex retain];
}
return self;
}
- (void)dealloc {
[_hex release];
[super dealloc];
}
@end
#pragma mark - Writer and reader of standard codec
@implementation FlutterStandardWriter {
NSMutableData* _data;
}
+ (instancetype)writerWithData:(NSMutableData*)data {
FlutterStandardWriter* writer =
[[FlutterStandardWriter alloc] initWithData:data];
[writer autorelease];
return writer;
}
- (instancetype)initWithData:(NSMutableData*)data {
if (self = [super init]) {
_data = [data retain];
}
return self;
}
- (void)dealloc {
[_data release];
[super dealloc];
}
- (void)writeByte:(UInt8)value {
[_data appendBytes:&value length:1];
}
- (void)writeSize:(UInt32)size {
if (size < 254) {
[self writeByte:(UInt8)size];
} else if (size <= 0xffff) {
[self writeByte:254];
UInt16 value = (UInt16)size;
[_data appendBytes:&value length:2];
} else {
[self writeByte:255];
[_data appendBytes:&size length:4];
}
}
- (void)writeAlignment:(UInt8)alignment {
UInt8 mod = _data.length % alignment;
if (mod) {
for (int i = 0; i < (alignment - mod); i++) {
[self writeByte:0];
}
}
}
- (void)writeUTF8:(NSString*)value {
UInt32 length = [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
[self writeSize:length];
[_data appendBytes:value.UTF8String length:length];
}
- (void)writeValue:(id)value {
if (value == nil || value == [NSNull null]) {
[self writeByte:FlutterStandardFieldNil];
} else if ([value isKindOfClass:[NSNumber class]]) {
NSNumber* number = value;
const char* type = [number objCType];
if (strcmp(type, @encode(BOOL)) == 0) {
BOOL b = number.boolValue;
[self
writeByte:(b ? FlutterStandardFieldTrue : FlutterStandardFieldFalse)];
} else if (strcmp(type, @encode(int)) == 0) {
SInt32 n = number.intValue;
[self writeByte:FlutterStandardFieldInt32];
[_data appendBytes:(UInt8*)&n length:4];
} else if (strcmp(type, @encode(long)) == 0) {
SInt64 n = number.longValue;
[self writeByte:FlutterStandardFieldInt64];
[_data appendBytes:(UInt8*)&n length:8];
} else if (strcmp(type, @encode(double)) == 0) {
Float64 f = number.doubleValue;
[self writeByte:FlutterStandardFieldFloat64];
[_data appendBytes:(UInt8*)&f length:8];
} else {
NSLog(@"Unsupported value: %@", value);
NSAssert(NO, @"Unsupported value for standard codec");
}
} else if ([value isKindOfClass:[NSString class]]) {
NSString* string = value;
[self writeByte:FlutterStandardFieldString];
[self writeUTF8:string];
} else if ([value isKindOfClass:[FlutterStandardBigInteger class]]) {
FlutterStandardBigInteger* bigInt = value;
[self writeByte:FlutterStandardFieldIntHex];
[self writeUTF8:bigInt.hex];
} else if ([value isKindOfClass:[FlutterStandardTypedData class]]) {
FlutterStandardTypedData* typedData = value;
[self writeByte:FlutterStandardFieldForDataType(typedData.type)];
[self writeSize:typedData.elementCount];
[self writeAlignment:typedData.elementSize];
[_data appendData:typedData.data];
} else if ([value isKindOfClass:[NSArray class]]) {
NSArray* array = value;
[self writeByte:FlutterStandardFieldList];
[self writeSize:array.count];
for (id object in array) {
[self writeValue:object];
}
} else if ([value isKindOfClass:[NSDictionary class]]) {
NSDictionary* dict = value;
[self writeByte:FlutterStandardFieldMap];
[self writeSize:dict.count];
for (id key in dict) {
[self writeValue:key];
[self writeValue:[dict objectForKey:key]];
}
} else {
NSLog(@"Unsupported value: %@", value);
NSAssert(NO, @"Unsupported value for standard codec");
}
}
@end
@implementation FlutterStandardReader {
NSData* _data;
NSRange _range;
}
+ (instancetype)readerWithData:(NSData*)data {
FlutterStandardReader* reader =
[[FlutterStandardReader alloc] initWithData:data];
[reader autorelease];
return reader;
}
- (instancetype)initWithData:(NSData*)data {
if (self = [super init]) {
_data = [data retain];
_range = NSMakeRange(0, 0);
}
return self;
}
- (void)dealloc {
[_data release];
[super dealloc];
}
- (BOOL)hasMore {
return _range.location < _data.length;
}
- (void)readBytes:(void*)destination length:(int)length {
_range.length = length;
[_data getBytes:destination range:_range];
_range.location += _range.length;
}
- (UInt8)readByte {
UInt8 value;
[self readBytes:&value length:1];
return value;
}
- (UInt32)readSize {
UInt8 byte = [self readByte];
if (byte < 254) {
return (UInt32)byte;
} else if (byte == 254) {
UInt16 value;
[self readBytes:&value length:2];
return value;
} else {
UInt32 value;
[self readBytes:&value length:4];
return value;
}
}
- (NSData*)readData:(int)length {
_range.length = length;
NSData* data = [_data subdataWithRange:_range];
_range.location += _range.length;
return data;
}
- (NSString*)readUTF8 {
NSData* bytes = [self readData:[self readSize]];
return [[[NSString alloc] initWithData:bytes encoding:NSUTF8StringEncoding]
autorelease];
}
- (void)readAlignment:(UInt8)alignment {
UInt8 mod = _range.location % alignment;
if (mod) {
_range.location += (alignment - mod);
}
}
- (FlutterStandardTypedData*)readTypedDataOfType:(FlutterStandardDataType)type {
UInt32 elementCount = [self readSize];
UInt8 elementSize = elementSizeForFlutterStandardDataType(type);
[self readAlignment:elementSize];
NSData* data = [self readData:elementCount * elementSize];
return [FlutterStandardTypedData typedDataWithData:data type:type];
}
- (id)readValue {
FlutterStandardField field = (FlutterStandardField)[self readByte];
switch (field) {
case FlutterStandardFieldNil:
return nil;
case FlutterStandardFieldTrue:
return @YES;
case FlutterStandardFieldFalse:
return @NO;
case FlutterStandardFieldInt32: {
SInt32 value;
[self readBytes:&value length:4];
return [NSNumber numberWithInt:value];
}
case FlutterStandardFieldInt64: {
SInt64 value;
[self readBytes:&value length:8];
return [NSNumber numberWithLong:value];
}
case FlutterStandardFieldFloat64: {
Float64 value;
[self readBytes:&value length:8];
return [NSNumber numberWithDouble:value];
}
case FlutterStandardFieldIntHex:
return [FlutterStandardBigInteger bigIntegerWithHex:[self readUTF8]];
case FlutterStandardFieldString:
return [self readUTF8];
case FlutterStandardFieldUInt8Data:
case FlutterStandardFieldInt32Data:
case FlutterStandardFieldInt64Data:
case FlutterStandardFieldFloat64Data:
return [self readTypedDataOfType:FlutterStandardDataTypeForField(field)];
case FlutterStandardFieldList: {
UInt32 length = [self readSize];
NSMutableArray* array = [NSMutableArray arrayWithCapacity:length];
for (UInt32 i = 0; i < length; i++) {
id value = [self readValue];
[array addObject:(value == nil ? [NSNull null] : value)];
}
return array;
}
case FlutterStandardFieldMap: {
UInt32 size = [self readSize];
NSMutableDictionary* dict =
[NSMutableDictionary dictionaryWithCapacity:size];
for (UInt32 i = 0; i < size; i++) {
id key = [self readValue];
id val = [self readValue];
[dict setObject:(val == nil ? [NSNull null] : val)
forKey:(key == nil ? [NSNull null] : key)];
}
return dict;
}
default:
NSAssert(NO, @"Corrupted standard message");
}
}
@end

View File

@@ -0,0 +1,62 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECINTERNAL_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECINTERNAL_H_
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterCodecs.h"
typedef NS_ENUM(NSInteger, FlutterStandardField) {
FlutterStandardFieldNil,
FlutterStandardFieldTrue,
FlutterStandardFieldFalse,
FlutterStandardFieldInt32,
FlutterStandardFieldInt64,
FlutterStandardFieldIntHex,
FlutterStandardFieldFloat64,
FlutterStandardFieldString,
FlutterStandardFieldUInt8Data,
FlutterStandardFieldInt32Data,
FlutterStandardFieldInt64Data,
FlutterStandardFieldFloat64Data,
FlutterStandardFieldList,
FlutterStandardFieldMap
};
namespace shell {
FlutterStandardField FlutterStandardFieldForDataType(
FlutterStandardDataType type) {
return (FlutterStandardField)(type + FlutterStandardFieldUInt8Data);
}
FlutterStandardDataType FlutterStandardDataTypeForField(
FlutterStandardField field) {
return (FlutterStandardDataType)(field - FlutterStandardFieldUInt8Data);
}
UInt8 elementSizeForFlutterStandardDataType(FlutterStandardDataType type) {
switch (type) {
case FlutterStandardDataTypeUInt8:
return 1;
case FlutterStandardDataTypeInt32:
return 4;
case FlutterStandardDataTypeInt64:
return 8;
case FlutterStandardDataTypeFloat64:
return 8;
}
}
} // namespace shell
@interface FlutterStandardWriter : NSObject
+ (instancetype)writerWithData:(NSMutableData*)data;
- (void)writeByte:(UInt8)value;
- (void)writeValue:(id)value;
@end
@interface FlutterStandardReader : NSObject
+ (instancetype)readerWithData:(NSData*)data;
- (BOOL)hasMore;
- (id)readValue;
@end
#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERSTANDARDCODECINTERNAL_H_

View File

@@ -10,8 +10,9 @@
#include "base/mac/scoped_nsobject.h"
#include "base/strings/sys_string_conversions.h"
#include "flutter/common/threads.h"
#include "flutter/shell/platform/darwin/common/buffer_conversions.h"
#include "flutter/shell/platform/darwin/common/platform_mac.h"
#include "flutter/shell/platform/darwin/common/string_conversions.h"
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterCodecs.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h"
@@ -24,7 +25,7 @@
namespace {
typedef void (^PlatformMessageResponseCallback)(NSString*);
typedef void (^PlatformMessageResponseCallback)(NSData*);
class PlatformMessageResponseDarwin : public blink::PlatformMessageResponse {
FRIEND_MAKE_REF_COUNTED(PlatformMessageResponseDarwin);
@@ -34,7 +35,7 @@ class PlatformMessageResponseDarwin : public blink::PlatformMessageResponse {
ftl::RefPtr<PlatformMessageResponseDarwin> self(this);
blink::Threads::Platform()->PostTask(
ftl::MakeCopyable([ self, data = std::move(data) ]() mutable {
self->callback_.get()(shell::GetNSStringFromVector(data));
self->callback_.get()(shell::GetNSDataFromVector(data));
}));
}
@@ -539,9 +540,8 @@ constexpr CGFloat kStandardStatusBarHeight = 20.0;
- (void)sendString:(NSString*)message withMessageName:(NSString*)channel {
NSAssert(message, @"The message must not be null");
NSAssert(channel, @"The channel must not be null");
_platformView->DispatchPlatformMessage(
ftl::MakeRefCounted<blink::PlatformMessage>(
channel.UTF8String, shell::GetVectorFromNSString(message), nullptr));
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
[self sendBinaryMessage:[codec encode:message] channelName:channel];
}
- (void)sendString:(NSString*)message
@@ -550,38 +550,39 @@ constexpr CGFloat kStandardStatusBarHeight = 20.0;
NSAssert(message, @"The message must not be null");
NSAssert(channel, @"The channel must not be null");
NSAssert(callback, @"The callback must not be null");
_platformView->DispatchPlatformMessage(
ftl::MakeRefCounted<blink::PlatformMessage>(
channel.UTF8String, shell::GetVectorFromNSString(message),
ftl::MakeRefCounted<PlatformMessageResponseDarwin>(callback)));
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
[self sendBinaryMessage:[codec encode:message]
channelName:channel
binaryReplyHandler:^(NSData* data) {
callback([codec decode:data]);
}];
}
- (void)sendJSON:(NSDictionary*)message withMessageName:(NSString*)channel {
NSData* data =
[NSJSONSerialization dataWithJSONObject:message options:0 error:nil];
if (!data)
return;
const uint8_t* bytes = static_cast<const uint8_t*>(data.bytes);
_platformView->DispatchPlatformMessage(
ftl::MakeRefCounted<blink::PlatformMessage>(
channel.UTF8String, std::vector<uint8_t>(bytes, bytes + data.length),
nullptr));
NSData* data = [[FlutterJSONMessageCodec sharedInstance] encode:message];
[self sendBinaryMessage:data channelName:channel];
}
- (void)addMessageListener:(NSObject<FlutterMessageListener>*)listener {
NSAssert(listener, @"The listener must not be null");
NSString* channel = listener.messageName;
NSAssert(channel, @"The channel must not be null");
_platformView->platform_message_router().SetMessageListener(
channel.UTF8String, listener);
NSString* messageName = listener.messageName;
NSAssert(messageName, @"The messageName must not be null");
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
[self
setBinaryMessageHandlerOnChannel:messageName
binaryMessageHandler:^(
NSData* message, FlutterBinaryReplyHandler replyHandler) {
NSString* reply =
[listener didReceiveString:[codec decode:message]];
replyHandler([codec encode:reply]);
}];
}
- (void)removeMessageListener:(NSObject<FlutterMessageListener>*)listener {
NSAssert(listener, @"The listener must not be null");
NSString* channel = listener.messageName;
NSAssert(channel, @"The channel must not be null");
_platformView->platform_message_router().SetMessageListener(
channel.UTF8String, nil);
NSString* messageName = listener.messageName;
NSAssert(messageName, @"The messageName must not be null");
[self setBinaryMessageHandlerOnChannel:messageName binaryMessageHandler:nil];
}
- (void)addAsyncMessageListener:
@@ -589,8 +590,16 @@ constexpr CGFloat kStandardStatusBarHeight = 20.0;
NSAssert(listener, @"The listener must not be null");
NSString* messageName = listener.messageName;
NSAssert(messageName, @"The messageName must not be null");
_platformView->platform_message_router().SetAsyncMessageListener(
messageName.UTF8String, listener);
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
[self
setBinaryMessageHandlerOnChannel:messageName
binaryMessageHandler:^(
NSData* message, FlutterBinaryReplyHandler replyHandler) {
[listener didReceiveString:[codec decode:message]
callback:^(NSString* reply) {
replyHandler([codec encode:reply]);
}];
}];
}
- (void)removeAsyncMessageListener:
@@ -598,8 +607,36 @@ constexpr CGFloat kStandardStatusBarHeight = 20.0;
NSAssert(listener, @"The listener must not be null");
NSString* messageName = listener.messageName;
NSAssert(messageName, @"The messageName must not be null");
_platformView->platform_message_router().SetAsyncMessageListener(
messageName.UTF8String, nil);
[self setBinaryMessageHandlerOnChannel:messageName binaryMessageHandler:nil];
}
- (void)sendBinaryMessage:(NSData*)message channelName:(NSString*)channel {
NSAssert(message, @"The message must not be null");
NSAssert(channel, @"The channel must not be null");
_platformView->DispatchPlatformMessage(
ftl::MakeRefCounted<blink::PlatformMessage>(
channel.UTF8String, shell::GetVectorFromNSData(message), nil));
}
- (void)sendBinaryMessage:(NSData*)message
channelName:(NSString*)channel
binaryReplyHandler:(FlutterBinaryReplyHandler)callback {
NSAssert(message, @"The message must not be null");
NSAssert(channel, @"The channel must not be null");
NSAssert(callback, @"The callback must not be null");
_platformView->DispatchPlatformMessage(
ftl::MakeRefCounted<blink::PlatformMessage>(
channel.UTF8String, shell::GetVectorFromNSData(message),
ftl::MakeRefCounted<PlatformMessageResponseDarwin>(^(NSData* reply) {
if (callback)
callback(reply);
})));
}
- (void)setBinaryMessageHandlerOnChannel:(NSString*)channel
binaryMessageHandler:(FlutterBinaryMessageHandler)handler {
NSAssert(channel, @"The channel name must not be null");
_platformView->platform_message_router().SetMessageHandler(channel.UTF8String,
handler);
}
@end

View File

@@ -0,0 +1,67 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterCodecs.h"
#include "gtest/gtest.h"
TEST(FlutterStringCodec, CanEncodeAndDecodeNil) {
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
ASSERT_TRUE([[codec encode:nil] isEqualTo:[NSData data]]);
ASSERT_TRUE([[codec decode:nil] isEqualTo:@""]);
}
TEST(FlutterStringCodec, CanEncodeAndDecodeEmptyString) {
NSString* value = @"";
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterStringCodec, CanEncodeAndDecodeAsciiString) {
NSString* value = @"hello world";
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterStringCodec, CanEncodeAndDecodeNonAsciiString) {
NSString* value = @"hello \u263A world";
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterStringCodec, CanEncodeAndDecodeNonBMPString) {
NSString* value = @"hello \U0001F602 world";
FlutterStringCodec* codec = [FlutterStringCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterJSONCodec, CanEncodeAndDecodeArray) {
NSArray* value =
@[ [NSNull null], @"hello", @3.14, @47,
@{ @"a" : @"nested" } ];
FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSArray* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterJSONCodec, CanEncodeAndDecodeDictionary) {
NSDictionary* value = @{
@"a" : @3.14,
@"b" : @47,
@"c" : [NSNull null],
@"d" : @[ @"nested" ]
};
FlutterJSONMessageCodec* codec = [FlutterJSONMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSDictionary* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}

View File

@@ -0,0 +1,166 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterCodecs.h"
#include "gtest/gtest.h"
TEST(FlutterStandardCodec, CanEncodeAndDecodeNil) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:nil];
id decoded = [codec decode:encoded];
ASSERT_TRUE(decoded == nil);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeNSNull) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:[NSNull null]];
id decoded = [codec decode:encoded];
ASSERT_TRUE(decoded == nil);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeInt32) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:@-78];
NSNumber* decoded = [codec decode:encoded];
ASSERT_TRUE([@-78 isEqualTo:decoded]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeInt64) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:@78000000001];
NSNumber* decoded = [codec decode:encoded];
ASSERT_TRUE([@78000000001 isEqualTo:decoded]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat64) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:@3.14];
NSNumber* decoded = [codec decode:encoded];
ASSERT_TRUE([@3.14 isEqualTo:decoded]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeString) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:@"hello world"];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([@"hello world" isEqualTo:decoded]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeStringWithNonAsciiCodePoint) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:@"hello \u263A world"];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([@"hello \u263A world" isEqualTo:decoded]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeStringWithNonBMPCodePoint) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:@"hello \U0001F602 world"];
NSString* decoded = [codec decode:encoded];
ASSERT_TRUE([@"hello \U0001F602 world" isEqualTo:decoded]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeBigInteger) {
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded =
[codec encode:[FlutterStandardBigInteger
bigIntegerWithHex:@"-abcdef120902390239021321abfdec"]];
FlutterStandardBigInteger* decoded = [codec decode:encoded];
ASSERT_TRUE([@"-abcdef120902390239021321abfdec" isEqualTo:decoded.hex]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeArray) {
NSArray* value =
@[ [NSNull null], @"hello", @3.14, @47,
@{ @42 : @"nested" } ];
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSArray* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeDictionary) {
NSDictionary* value = @{
@"a" : @3.14,
@"b" : @47,
[NSNull null] : [NSNull null],
@3.14 : @[ @"nested" ]
};
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
NSDictionary* decoded = [codec decode:encoded];
ASSERT_TRUE([value isEqualTo:decoded]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeByteArray) {
char bytes[4] = {0xBA, 0x5E, 0xBA, 0x11};
NSData* data = [NSData dataWithBytes:bytes length:4];
FlutterStandardTypedData* value =
[FlutterStandardTypedData typedDataWithBytes:data];
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
FlutterStandardTypedData* decoded = [codec decode:encoded];
ASSERT_TRUE(decoded.type == FlutterStandardDataTypeUInt8);
ASSERT_TRUE(decoded.elementCount == 4);
ASSERT_TRUE(decoded.elementSize == 1);
ASSERT_TRUE([data isEqualTo:decoded.data]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeInt32Array) {
char bytes[8] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff};
NSData* data = [NSData dataWithBytes:bytes length:8];
FlutterStandardTypedData* value =
[FlutterStandardTypedData typedDataWithInt32:data];
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
FlutterStandardTypedData* decoded = [codec decode:encoded];
ASSERT_TRUE(decoded.type == FlutterStandardDataTypeInt32);
ASSERT_TRUE(decoded.elementCount == 2);
ASSERT_TRUE(decoded.elementSize == 4);
ASSERT_TRUE([data isEqualTo:decoded.data]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeInt64Array) {
char bytes[8] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff};
NSData* data = [NSData dataWithBytes:bytes length:8];
FlutterStandardTypedData* value =
[FlutterStandardTypedData typedDataWithInt64:data];
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
FlutterStandardTypedData* decoded = [codec decode:encoded];
ASSERT_TRUE(decoded.type == FlutterStandardDataTypeInt64);
ASSERT_TRUE(decoded.elementCount == 1);
ASSERT_TRUE(decoded.elementSize == 8);
ASSERT_TRUE([data isEqualTo:decoded.data]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat64Array) {
char bytes[16] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff,
0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff};
NSData* data = [NSData dataWithBytes:bytes length:16];
FlutterStandardTypedData* value =
[FlutterStandardTypedData typedDataWithFloat64:data];
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
FlutterStandardTypedData* decoded = [codec decode:encoded];
ASSERT_TRUE(decoded.type == FlutterStandardDataTypeFloat64);
ASSERT_TRUE(decoded.elementCount == 2);
ASSERT_TRUE(decoded.elementSize == 8);
ASSERT_TRUE([data isEqualTo:decoded.data]);
}

View File

@@ -8,8 +8,7 @@
#include <unordered_map>
#include "flutter/lib/ui/window/platform_message.h"
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterAsyncMessageListener.h"
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterMessageListener.h"
#include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterBinaryMessenger.h"
#include "lib/ftl/memory/weak_ptr.h"
namespace shell {
@@ -21,16 +20,12 @@ class PlatformMessageRouter {
void HandlePlatformMessage(ftl::RefPtr<blink::PlatformMessage> message);
void SetMessageListener(const std::string& channel,
NSObject<FlutterMessageListener>* listener);
void SetAsyncMessageListener(const std::string& channel,
NSObject<FlutterAsyncMessageListener>* listener);
void SetMessageHandler(const std::string& channel,
FlutterBinaryMessageHandler handler);
private:
std::unordered_map<std::string, NSObject<FlutterMessageListener>*> listeners_;
std::unordered_map<std::string, NSObject<FlutterAsyncMessageListener>*>
async_listeners_;
std::unordered_map<std::string, FlutterBinaryMessageHandler>
message_handlers_;
FTL_DISALLOW_COPY_AND_ASSIGN(PlatformMessageRouter);
};

View File

@@ -7,7 +7,7 @@
#include <vector>
#include "base/strings/sys_string_conversions.h"
#include "flutter/shell/platform/darwin/common/string_conversions.h"
#include "flutter/shell/platform/darwin/common/buffer_conversions.h"
namespace shell {
@@ -17,48 +17,32 @@ PlatformMessageRouter::~PlatformMessageRouter() = default;
void PlatformMessageRouter::HandlePlatformMessage(
ftl::RefPtr<blink::PlatformMessage> message) {
NSString* string = GetNSStringFromVector(message->data());
NSData* data = GetNSDataFromVector(message->data());
ftl::RefPtr<blink::PlatformMessageResponse> completer = message->response();
{
auto it = listeners_.find(message->channel());
if (it != listeners_.end()) {
NSString* response = [it->second didReceiveString:string];
if (completer)
completer->Complete(GetVectorFromNSString(response));
return;
}
}
{
auto it = async_listeners_.find(message->channel());
if (it != async_listeners_.end()) {
[it->second
didReceiveString:string
callback:^(NSString* response) {
if (completer)
completer->Complete(GetVectorFromNSString(response));
}];
}
auto it = message_handlers_.find(message->channel());
if (it != message_handlers_.end()) {
FlutterBinaryMessageHandler handler = it->second;
handler(data, ^(NSData* reply) {
if (completer) {
completer->Complete(GetVectorFromNSData(reply));
}
});
}
}
void PlatformMessageRouter::SetMessageListener(
void PlatformMessageRouter::SetMessageHandler(
const std::string& channel,
NSObject<FlutterMessageListener>* listener) {
if (listener)
listeners_[channel] = listener;
else
listeners_.erase(channel);
}
void PlatformMessageRouter::SetAsyncMessageListener(
const std::string& channel,
NSObject<FlutterAsyncMessageListener>* listener) {
if (listener)
async_listeners_[channel] = listener;
else
async_listeners_.erase(channel);
FlutterBinaryMessageHandler handler) {
if (handler)
message_handlers_[channel] = [handler copy];
else {
auto it = message_handlers_.find(channel);
if (it != message_handlers_.end()) {
[it->second release];
message_handlers_.erase(it);
}
}
}
} // namespace shell