diff --git a/engine/src/flutter/shell/platform/android/BUILD.gn b/engine/src/flutter/shell/platform/android/BUILD.gn index aed01d9bbf..5fb22c3b4d 100644 --- a/engine/src/flutter/shell/platform/android/BUILD.gn +++ b/engine/src/flutter/shell/platform/android/BUILD.gn @@ -82,7 +82,18 @@ android_library("java") { "io/flutter/app/FlutterActivity.java", "io/flutter/app/FlutterApplication.java", "io/flutter/plugin/common/ActivityLifecycleListener.java", + "io/flutter/plugin/common/BinaryMessageCodec.java", + "io/flutter/plugin/common/FlutterMessageChannel.java", + "io/flutter/plugin/common/FlutterMethodChannel.java", + "io/flutter/plugin/common/JSONMessageCodec.java", "io/flutter/plugin/common/JSONMessageListener.java", + "io/flutter/plugin/common/JSONMethodCodec.java", + "io/flutter/plugin/common/MessageCodec.java", + "io/flutter/plugin/common/MethodCodec.java", + "io/flutter/plugin/common/MethodCall.java", + "io/flutter/plugin/common/StandardMessageCodec.java", + "io/flutter/plugin/common/StandardMethodCodec.java", + "io/flutter/plugin/common/StringMessageCodec.java", "io/flutter/plugin/editing/InputConnectionAdaptor.java", "io/flutter/plugin/editing/TextInputPlugin.java", "io/flutter/plugin/platform/PlatformPlugin.java", diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessageCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessageCodec.java new file mode 100644 index 0000000000..d4d1926916 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/BinaryMessageCodec.java @@ -0,0 +1,28 @@ +// 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. + +package io.flutter.plugin.common; + +import java.nio.ByteBuffer; + +/** + * A {@link MessageCodec} using unencoded binary messages, represented as {@link ByteBuffer}s. + */ +public final class BinaryMessageCodec implements MessageCodec { + // This codec must match the Dart codec of the same name in package flutter/services. + public static final BinaryMessageCodec INSTANCE = new BinaryMessageCodec(); + + private BinaryMessageCodec() { + } + + @Override + public ByteBuffer encodeMessage(ByteBuffer message) { + return message; + } + + @Override + public ByteBuffer decodeMessage(ByteBuffer message) { + return message; + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterMessageChannel.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterMessageChannel.java new file mode 100644 index 0000000000..001ab35cf6 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterMessageChannel.java @@ -0,0 +1,163 @@ +// 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. + +package io.flutter.plugin.common; + +import android.util.Log; +import io.flutter.view.FlutterView; +import io.flutter.view.FlutterView.BinaryMessageReplyCallback; +import io.flutter.view.FlutterView.BinaryMessageResponse; +import io.flutter.view.FlutterView.OnBinaryMessageListenerAsync; +import java.nio.ByteBuffer; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A named channel for communicating with the Flutter application using semi-structured messages. + * + * Messages are encoded into binary before being sent, and binary messages received are decoded + * into Java objects. The {@link MessageCodec} used must be compatible with the + * one used by the Flutter application. This can be achieved by creating a PlatformChannel + * counterpart of this channel on the Dart side. The static Java type of messages sent and received + * is Object, but only values supported by the specified {@link MessageCodec} can be used. + * + * The channel supports basic message send/receive operations, handling incoming method + * invocations, and emitting event streams. All communication is asynchronous. + * + * Identically named channels may interfere with each other's communication. + */ +public final class FlutterMessageChannel { + private static final String TAG = "FlutterMessageChannel#"; + + private final FlutterView view; + private final String name; + private final MessageCodec codec; + + /** + * Creates a new channel associated with the specified {@link FlutterView} and with the + * specified name and {@link MessageCodec}. + * + * @param view a {@link FlutterView}. + * @param name a channel name String. + * @param codec a {@link MessageCodec}. + */ + public FlutterMessageChannel(FlutterView view, String name, MessageCodec codec) { + this.view = Objects.requireNonNull(view); + this.name = Objects.requireNonNull(name); + this.codec = Objects.requireNonNull(codec); + } + + /** + * Sends the specified message to the Flutter application on this channel. + * + * @param message the message, possibly null. + */ + public void send(T message) { + send(message, null); + } + + /** + * Sends the specified message to the Flutter application, optionally expecting a reply. + * + * @param message the message, possibly null. + * @param handler a {@link ReplyHandler} call-back, possibly null. + */ + public void send(T message, final ReplyHandler handler) { + view.sendBinaryMessage(name, codec.encodeMessage(message), + handler == null ? null : new ReplyCallback(handler)); + } + + /** + * Registers a message handler on this channel. + * + * Overrides any existing handler registration (for messages, method calls, or streams). + * + * @param handler a {@link MessageHandler}, or null to deregister. + */ + public void setMessageHandler(final MessageHandler handler) { + view.addOnBinaryMessageListenerAsync(name, + handler == null ? null : new MessageListener(handler)); + } + + /** + * A call-back interface for handling replies to outgoing messages. + */ + public interface ReplyHandler { + /** + * Handle the specified reply. + * + * @param reply the reply, possibly null. + */ + void onReply(T reply); + } + + /** + * A call-back interface for handling incoming messages. + */ + public interface MessageHandler { + + /** + * Handles the specified message. + * + * @param message The message, possibly null. + * @param reply A {@link Reply} for providing a single message reply. + */ + void onMessage(T message, Reply reply); + } + + /** + * Response interface for sending results back to Flutter. + */ + public interface Reply { + /** + * Submits a reply. + * + * @param reply The result, possibly null. + */ + void send(T reply); + } + + private final class ReplyCallback implements BinaryMessageReplyCallback { + private final ReplyHandler handler; + + private ReplyCallback(ReplyHandler handler) { + this.handler = handler; + } + + @Override + public void onReply(ByteBuffer reply) { + handler.onReply(codec.decodeMessage(reply)); + } + } + + private final class MessageListener implements OnBinaryMessageListenerAsync { + private final MessageHandler handler; + + private MessageListener(MessageHandler handler) { + this.handler = handler; + } + + @Override + public void onMessage(FlutterView view, ByteBuffer message, + final BinaryMessageResponse response) { + try { + handler.onMessage(codec.decodeMessage(message), new Reply() { + private boolean done = false; + + @Override + public void send(T reply) { + if (done) { + throw new IllegalStateException("Call result already provided"); + } + response.send(codec.encodeMessage(reply)); + done = true; + } + }); + } catch (Exception e) { + Log.e(TAG + name, "Failed to handle message", e); + response.send(null); + } + } + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterMethodChannel.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterMethodChannel.java new file mode 100644 index 0000000000..1a980233c4 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/FlutterMethodChannel.java @@ -0,0 +1,257 @@ +// 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. + +package io.flutter.plugin.common; + +import android.util.Log; +import io.flutter.view.FlutterView; +import io.flutter.view.FlutterView.BinaryMessageResponse; +import io.flutter.view.FlutterView.OnBinaryMessageListenerAsync; +import java.nio.ByteBuffer; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A named channel for communicating with the Flutter application using asynchronous + * method calls and event streams. + * + * Incoming method calls are decoded from binary on receipt, and Java results are encoded + * into binary before being transmitted back to Flutter. The {@link MethodCodec} used must be + * compatible with the one used by the Flutter application. This can be achieved + * by creating a PlatformMethodChannel counterpart of this channel on the + * Flutter side. The Java type of method call arguments and results is Object, + * but only values supported by the specified {@link MethodCodec} can be used. + * + * The identity of the channel is given by its name, so other uses of that name + * with may interfere with this channel's communication. + */ +public final class FlutterMethodChannel { + private static final String TAG = "FlutterMethodChannel#"; + + private final FlutterView view; + private final String name; + private final MethodCodec codec; + + /** + * Creates a new channel associated with the specified {@link FlutterView} and with the + * specified name and the standard {@link MethodCodec}. + * + * @param view a {@link FlutterView}. + * @param name a channel name String. + */ + public FlutterMethodChannel(FlutterView view, String name) { + this(view, name, StandardMethodCodec.INSTANCE); + } + + /** + * Creates a new channel associated with the specified {@link FlutterView} and with the + * specified name and {@link MethodCodec}. + * + * @param view a {@link FlutterView}. + * @param name a channel name String. + * @param codec a {@link MessageCodec}. + */ + public FlutterMethodChannel(FlutterView view, String name, MethodCodec codec) { + this.view = Objects.requireNonNull(view); + this.name = Objects.requireNonNull(name); + this.codec = Objects.requireNonNull(codec); + } + + /** + * Registers a method call handler on this channel. + * + * Overrides any existing handler registration (for messages, method calls, or streams). + * + * @param handler a {@link MethodCallHandler}, or null to deregister. + */ + public void setMethodCallHandler(final MethodCallHandler handler) { + view.addOnBinaryMessageListenerAsync(name, + handler == null ? null : new MethodCallListener(handler)); + } + + /** + * Registers a stream handler on this channel. + * + * Overrides any existing handler registration (for messages, method calls, or streams). + * + * @param handler a {@link StreamHandler}, or null to deregister. + */ + public void setStreamHandler(final StreamHandler handler) { + view.addOnBinaryMessageListenerAsync(name, + handler == null ? null : new StreamListener(handler)); + } + + /** + * A call-back interface for handling incoming method calls. + */ + public interface MethodCallHandler { + + /** + * Handles the specified method call. + * + * @param call A {@link MethodCall}. + * @param response A {@link Response} for providing a single method call result. + */ + void onMethodCall(MethodCall call, Response response); + } + + /** + * A call-back interface for handling stream setup and teardown requests. + */ + public interface StreamHandler { + /** + * Handles a stream setup request. + * + * @param arguments Stream configuration arguments, possibly null. + * @param eventSink A {@link EventSink} used to emit events once the stream has been set up. + */ + void listen(Object arguments, EventSink eventSink); + + /** + * Handles a stream tear-down request. + * + * @param arguments Stream configuration arguments, possibly null. + */ + void cancel(Object arguments); + } + + /** + * Response interface for sending results back to Flutter. + */ + public interface Response { + /** + * Submits a successful result. + * + * @param result The result, possibly null. + */ + void success(Object result); + + /** + * Submits an error during message handling, an error result of a method call, or an error + * event. + * + * @param errorCode An error code String. + * @param errorMessage A human-readable error message String, possibly null. + * @param errorDetails Error details, possibly null + */ + void error(String errorCode, String errorMessage, Object errorDetails); + } + + /** + * A {@link Response} supporting multiple results and which can be terminated. + */ + public interface EventSink extends Response { + /** + * Signals that no more events will be emitted. + */ + void done(); + } + + private final class MethodCallListener implements OnBinaryMessageListenerAsync { + private final MethodCallHandler handler; + + MethodCallListener(MethodCallHandler handler) { + this.handler = handler; + } + + @Override + public void onMessage(FlutterView view, ByteBuffer message, + final BinaryMessageResponse response) { + final MethodCall call = codec.decodeMethodCall(message); + try { + handler.onMethodCall(call, new Response() { + private boolean done = false; + + @Override + public void success(Object result) { + checkDone(); + response.send(codec.encodeSuccessEnvelope(result)); + done = true; + } + + @Override + public void error(String errorCode, String errorMessage, Object errorDetails) { + checkDone(); + response.send(codec.encodeErrorEnvelope( + errorCode, errorMessage, errorDetails)); + done = true; + } + + private void checkDone() { + if (done) { + throw new IllegalStateException("Call result already provided"); + } + } + }); + } catch (Exception e) { + Log.e(TAG + name, "Failed to handle method call", e); + response.send(codec.encodeErrorEnvelope("error", e.getMessage(),null)); + } + } + } + + private final class StreamListener implements OnBinaryMessageListenerAsync { + private final StreamHandler handler; + + StreamListener(StreamHandler handler) { + this.handler = handler; + } + + @Override + public void onMessage(FlutterView view, ByteBuffer message, + final BinaryMessageResponse response) { + final MethodCall call = codec.decodeMethodCall(message); + final AtomicBoolean cancelled = new AtomicBoolean(false); + if (call.method.equals("listen")) { + try { + handler.listen(call.arguments, new EventSink() { + @Override + public void success(Object event) { + if (cancelled.get()) { + return; + } + FlutterMethodChannel.this.view.sendBinaryMessage( + name, + codec.encodeSuccessEnvelope(event), + null); + } + + @Override + public void error(String errorCode, String errorMessage, + Object errorDetails) { + if (cancelled.get()) { + return; + } + FlutterMethodChannel.this.view.sendBinaryMessage( + name, + codec.encodeErrorEnvelope(errorCode, errorMessage, errorDetails), + null); + } + + @Override + public void done() { + if (cancelled.get()) { + return; + } + FlutterMethodChannel.this.view.sendToFlutter(name,null); + } + }); + response.send(codec.encodeSuccessEnvelope(null)); + } catch (Exception e) { + Log.e(TAG + name, "Failed to open event stream", e); + response.send(codec.encodeErrorEnvelope("error", e.getMessage(),null)); + } + } else if (call.method.equals("cancel")) { + cancelled.set(true); + try { + handler.cancel(call.arguments); + response.send(codec.encodeSuccessEnvelope(null)); + } catch (Exception e) { + Log.e(TAG + name, "Failed to close event stream", e); + response.send(codec.encodeErrorEnvelope("error", e.getMessage(),null)); + } + } + } + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageCodec.java new file mode 100644 index 0000000000..ba29f41116 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageCodec.java @@ -0,0 +1,49 @@ +// 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. + +package io.flutter.plugin.common; + +import java.nio.ByteBuffer; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + +/** + * A {@link MessageCodec} using UTF-8 encoded JSON messages. + * + * Supports the same Java values as {@link JSONObject#wrap(Object)}. + */ +public final class JSONMessageCodec implements MessageCodec { + // This codec must match the Dart codec of the same name in package flutter/services. + public static final JSONMessageCodec INSTANCE = new JSONMessageCodec(); + + private JSONMessageCodec() { + } + + @Override + public ByteBuffer encodeMessage(Object message) { + if (message == null) { + return null; + } + return StringMessageCodec.INSTANCE.encodeMessage(JSONObject.wrap(message).toString()); + } + + @Override + public Object decodeMessage(ByteBuffer message) { + if (message == null) { + return null; + } + try { + final String json = StringMessageCodec.INSTANCE.decodeMessage(message); + final JSONTokener tokener = new JSONTokener(json); + final Object value = tokener.nextValue(); + if (tokener.more()) { + throw new IllegalArgumentException("Invalid JSON"); + } + return value; + } catch (JSONException e) { + throw new IllegalArgumentException("Invalid JSON", e); + } + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageListener.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageListener.java index 547b214f4b..7dcddf09d0 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageListener.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMessageListener.java @@ -11,6 +11,8 @@ import org.json.JSONObject; import io.flutter.view.FlutterView; +/** @deprecated Use {@link FlutterMessageChannel} and {@link JSONMessageCodec} instead. */ +@Deprecated public abstract class JSONMessageListener implements FlutterView.OnMessageListener { static final String TAG = "FlutterView"; diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java new file mode 100644 index 0000000000..0cb88836db --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/JSONMethodCodec.java @@ -0,0 +1,47 @@ +package io.flutter.plugin.common; + +import java.nio.ByteBuffer; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * A {@link MethodCodec} using UTF-8 encoded JSON method calls and result envelopes. + * Values supported as methods arguments and result payloads are those supported by + * {@link JSONMessageCodec}. + */ +public final class JSONMethodCodec implements MethodCodec { + public static final JSONMethodCodec INSTANCE = new JSONMethodCodec(); + + private JSONMethodCodec() { + } + + @Override + public MethodCall decodeMethodCall(ByteBuffer message) { + try { + final Object json = JSONMessageCodec.INSTANCE.decodeMessage(message); + if (json instanceof JSONArray) { + final JSONArray pair = (JSONArray) json; + if (pair.length() == 2 && pair.get(0) instanceof String) { + return new MethodCall(pair.getString(0), pair.get(1)); + } + } + throw new IllegalArgumentException("Invalid method call: " + json); + } catch (JSONException e) { + throw new IllegalArgumentException("Invalid JSON", e); + } + } + + @Override + public ByteBuffer encodeSuccessEnvelope(Object result) { + return JSONMessageCodec.INSTANCE.encodeMessage(new JSONArray().put(JSONObject.wrap(result))); + } + + @Override + public ByteBuffer encodeErrorEnvelope(String errorCode, String errorMessage, Object errorDetails) { + return JSONMessageCodec.INSTANCE.encodeMessage(new JSONArray() + .put(errorCode) + .put(errorMessage) + .put(JSONObject.wrap(errorDetails))); + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MessageCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MessageCodec.java new file mode 100644 index 0000000000..125186f213 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MessageCodec.java @@ -0,0 +1,32 @@ +// 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. + +package io.flutter.plugin.common; + +import java.nio.ByteBuffer; + +/** + * A message encoding/decoding mechanism. + * + * Both operations throw {@link IllegalArgumentException}, if conversion fails. + */ +public interface MessageCodec { + /** + * Encodes the specified message into binary. + * + * @param message the T message, possibly null. + * @return a ByteBuffer containing the encoding between position 0 and + * the current position, or null, if message is null. + */ + ByteBuffer encodeMessage(T message); + + /** + * Decodes the specified message from binary. + * + * @param message the {@link ByteBuffer} message, possibly null. + * @return a T value representation of the bytes between the given buffer's current + * position and its limit, or null, if message is null. + */ + T decodeMessage(ByteBuffer message); +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCall.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCall.java new file mode 100644 index 0000000000..8184383298 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCall.java @@ -0,0 +1,33 @@ +// 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. + +package io.flutter.plugin.common; + +import java.util.Objects; + +/** + * Command object representing a method call on a {@link FlutterMessageChannel}. + */ +public final class MethodCall { + /** + * The name of the called method. + */ + public final String method; + + /** + * Arguments for the call. + */ + public final Object arguments; + + /** + * Creates a {@link MethodCall} with the specified method name and arguments. + * + * @param method the method name String, not null. + * @param arguments the arguments, a value supported by the channel's message codec. + */ + public MethodCall(String method, Object arguments) { + this.method = Objects.requireNonNull(method); + this.arguments = arguments; + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCodec.java new file mode 100644 index 0000000000..fcb295dc38 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/MethodCodec.java @@ -0,0 +1,47 @@ +// 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. + +package io.flutter.plugin.common; + +import java.nio.ByteBuffer; + +/** + * A codec for method calls and enveloped results. + * + * Method calls are encoded as binary messages with enough structure that the codec can + * extract a method name String and an arguments Object. These data items are used to populate a + * {@link MethodCall}. + * + * All operations throw {@link IllegalArgumentException}, if conversion fails. + */ +public interface MethodCodec { + /** + * Decodes a message call from binary. + * + * @param methodCall the binary encoding of the method call as a {@link ByteBuffer}. + * @return a {@link MethodCall} representation of the bytes between the given buffer's current + * position and its limit. + */ + MethodCall decodeMethodCall(ByteBuffer methodCall); + + /** + * Encodes a successful result into a binary envelope message. + * + * @param result The result value, possibly null. + * @return a ByteBuffer containing the encoding between position 0 and + * the current position. + */ + ByteBuffer encodeSuccessEnvelope(Object result); + + /** + * Encodes an error result into a binary envelope message. + * + * @param errorCode An error code String. + * @param errorMessage An error message String, possibly null. + * @param errorDetails Error details, possibly null. + * @return a ByteBuffer containing the encoding between position 0 and + * the current position. + */ + ByteBuffer encodeErrorEnvelope(String errorCode, String errorMessage, Object errorDetails); +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java new file mode 100644 index 0000000000..99079ba84d --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMessageCodec.java @@ -0,0 +1,333 @@ +// 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. + +package io.flutter.plugin.common; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +/** + * MessageCodec using the Flutter standard binary encoding. + * + * The standard encoding is guaranteed to be compatible with the corresponding standard codec + * for PlatformMessageChannels on the Flutter side. These parts of the Flutter SDK are evolved + * synchronously. + * + * Supported messages are acyclic values of these forms: + * + *
    + *
  • null
  • + *
  • Booleans
  • + *
  • Bytes, Shorts, Integers, Longs, BigIntegers
  • + *
  • Floats, Doubles
  • + *
  • Strings
  • + *
  • byte[], int[], long[], double[]
  • + *
  • Lists of supported values
  • + *
  • Maps with supported keys and values
  • + *
+ */ +public final class StandardMessageCodec implements MessageCodec { + // This codec must match the Dart codec of the same name in package flutter/services. + public static final StandardMessageCodec INSTANCE = new StandardMessageCodec(); + + private StandardMessageCodec() { + } + + @Override + public ByteBuffer encodeMessage(Object message) { + if (message == null) { + return null; + } + final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); + writeValue(stream, message); + final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); + buffer.put(stream.buffer(), 0, stream.size()); + return buffer; + } + + @Override + public Object decodeMessage(ByteBuffer message) { + if (message == null || !message.hasRemaining()) { + return null; + } + final Object value = readValue(message); + if (message.hasRemaining()) { + throw new IllegalArgumentException("Message corrupted"); + } + return value; + } + + private static final byte NULL = 0; + private static final byte TRUE = 1; + private static final byte FALSE = 2; + private static final byte INT = 3; + private static final byte LONG = 4; + private static final byte BIGINT = 5; + private static final byte DOUBLE = 6; + private static final byte STRING = 7; + private static final byte BYTE_ARRAY = 8; + private static final byte INT_ARRAY = 9; + private static final byte LONG_ARRAY = 10; + private static final byte DOUBLE_ARRAY = 11; + private static final byte LIST = 12; + private static final byte MAP = 13; + + private static void writeSize(ByteArrayOutputStream stream, int value) { + assert 0 <= value; + if (value < 254) { + stream.write(value); + } else if (value < 0xffff) { + stream.write(254); + stream.write(value >>> 8); + stream.write(value); + } else { + stream.write(255); + writeInt(stream, value); + } + } + + private static void writeInt(ByteArrayOutputStream stream, int value) { + 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); + } + + private static void writeDouble(ByteArrayOutputStream stream, double value) { + writeLong(stream, Double.doubleToLongBits(value)); + } + + private static void writeBytes(ByteArrayOutputStream stream, byte[] bytes) { + writeSize(stream, bytes.length); + stream.write(bytes, 0, bytes.length); + } + + private static void writeAlignment(ByteArrayOutputStream stream, int alignment) { + final int mod = stream.size() % alignment; + if (mod != 0) { + for (int i = 0; i < alignment - mod; i++) { + stream.write(0); + } + } + } + + static void writeValue(ByteArrayOutputStream stream, Object value) { + if (value == null) { + stream.write(NULL); + } else if (value == Boolean.TRUE) { + stream.write(TRUE); + } else if (value == Boolean.FALSE) { + stream.write(FALSE); + } else if (value instanceof Number) { + if (value instanceof Integer || value instanceof Short || value instanceof Byte) { + stream.write(INT); + writeInt(stream, ((Number) value).intValue()); + } else if (value instanceof Long) { + stream.write(LONG); + writeLong(stream, (long) value); + } else if (value instanceof Float || value instanceof Double) { + stream.write(DOUBLE); + writeDouble(stream, ((Number) value).doubleValue()); + } else if (value instanceof BigInteger) { + stream.write(BIGINT); + writeBytes(stream, + ((BigInteger) value).toString(16).getBytes(StandardCharsets.UTF_8)); + } else { + throw new IllegalArgumentException("Unsupported Number type: " + value.getClass()); + } + } else if (value instanceof String) { + stream.write(STRING); + writeBytes(stream, ((String) value).getBytes(StandardCharsets.UTF_8)); + } else if (value instanceof byte[]) { + stream.write(BYTE_ARRAY); + writeBytes(stream, (byte[]) value); + } else if (value instanceof int[]) { + stream.write(INT_ARRAY); + final int[] array = (int[]) value; + writeSize(stream, array.length); + writeAlignment(stream, 4); + for (final int n : array) { + writeInt(stream, n); + } + } else if (value instanceof long[]) { + stream.write(LONG_ARRAY); + final long[] array = (long[]) value; + writeSize(stream, array.length); + writeAlignment(stream, 8); + for (final long n : array) { + writeLong(stream, n); + } + } else if (value instanceof double[]) { + stream.write(DOUBLE_ARRAY); + final double[] array = (double[]) value; + writeSize(stream, array.length); + writeAlignment(stream, 8); + for (final double d : array) { + writeDouble(stream, d); + } + } else if (value instanceof List) { + stream.write(LIST); + final List list = (List) value; + writeSize(stream, list.size()); + for (final Object o : list) { + writeValue(stream, o); + } + } else if (value instanceof Map) { + stream.write(MAP); + final Map map = (Map) value; + writeSize(stream, map.size()); + for (final Entry entry: map.entrySet()) { + writeValue(stream, entry.getKey()); + writeValue(stream, entry.getValue()); + } + } else { + throw new IllegalArgumentException("Unsupported value: " + value); + } + } + + private static int readSize(ByteBuffer buffer) { + if (!buffer.hasRemaining()) { + throw new IllegalArgumentException("Message corrupted"); + } + final int value = buffer.get() & 0xff; + if (value < 254) { + return value; + } else if (value == 254) { + return ((buffer.get() & 0xff) << 8) + | ((buffer.get() & 0xff)); + } else { + return ((buffer.get() & 0xff) << 24) + | ((buffer.get() & 0xff) << 16) + | ((buffer.get() & 0xff) << 8) + | ((buffer.get() & 0xff)); + } + } + + private static byte[] readBytes(ByteBuffer buffer) { + final int length = readSize(buffer); + final byte[] bytes = new byte[length]; + buffer.get(bytes); + return bytes; + } + + private static void readAlignment(ByteBuffer buffer, int alignment) { + final int mod = buffer.position() % alignment; + if (mod != 0) { + buffer.position(buffer.position() + alignment - mod); + } + } + + static Object readValue(ByteBuffer buffer) { + if (!buffer.hasRemaining()) { + throw new IllegalArgumentException("Message corrupted"); + } + final Object result; + switch (buffer.get()) { + case NULL: + result = null; + break; + case TRUE: + result = true; + break; + case FALSE: + result = false; + break; + case INT: + result = buffer.getInt(); + break; + case LONG: + result = buffer.getLong(); + break; + case BIGINT: { + final byte[] hex = readBytes(buffer); + result = new BigInteger(new String(hex, StandardCharsets.UTF_8), 16); + break; + } + case DOUBLE: + result = buffer.getDouble(); + break; + case STRING: { + final byte[] bytes = readBytes(buffer); + result = new String(bytes, StandardCharsets.UTF_8); + break; + } + case BYTE_ARRAY: { + result = readBytes(buffer); + break; + } + case INT_ARRAY: { + final int length = readSize(buffer); + final int[] array = new int[length]; + readAlignment(buffer, 4); + buffer.asIntBuffer().get(array); + result = array; + buffer.position(buffer.position() + 4 * length); + break; + } + case LONG_ARRAY: { + final int length = readSize(buffer); + final long[] array = new long[length]; + readAlignment(buffer, 8); + buffer.asLongBuffer().get(array); + result = array; + buffer.position(buffer.position() + 8 * length); + break; + } + case DOUBLE_ARRAY: { + final int length = readSize(buffer); + final double[] array = new double[length]; + readAlignment(buffer, 8); + buffer.asDoubleBuffer().get(array); + result = array; + buffer.position(buffer.position() + 8 * length); + break; + } + case LIST: { + final int size = readSize(buffer); + final List list = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + list.add(readValue(buffer)); + } + result = list; + break; + } + case MAP: { + final int size = readSize(buffer); + final Map map = new HashMap<>(); + for (int i = 0; i < size; i++) { + map.put(readValue(buffer), readValue(buffer)); + } + result = map; + break; + } + default: + throw new IllegalArgumentException("Message corrupted"); + } + return result; + } + + static final class ExposedByteArrayOutputStream extends ByteArrayOutputStream { + byte[] buffer() { + return buf; + } + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.java new file mode 100644 index 0000000000..50990baa2d --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StandardMethodCodec.java @@ -0,0 +1,59 @@ +// 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. + +package io.flutter.plugin.common; + +import io.flutter.plugin.common.StandardMessageCodec.ExposedByteArrayOutputStream; +import java.nio.ByteBuffer; + +/** + * A {@link MethodCodec} using the Flutter standard binary encoding. + * + * The standard codec is guaranteed to be compatible with the corresponding standard codec for + * PlatformMethodChannels on the Flutter side. These parts of the Flutter SDK are evolved + * synchronously. + * + * Values supported as method arguments and result payloads are those supported by + * {@link StandardMessageCodec}. + */ +public final class StandardMethodCodec implements MethodCodec { + // This codec must match the Dart codec of the same name in package flutter/services. + public static final StandardMethodCodec INSTANCE = new StandardMethodCodec(); + + private StandardMethodCodec() { + } + + @Override + public MethodCall decodeMethodCall(ByteBuffer methodCall) { + final Object method = StandardMessageCodec.readValue(methodCall); + final Object arguments = StandardMessageCodec.readValue(methodCall); + if (method instanceof String) { + return new MethodCall((String) method, arguments); + } + throw new IllegalArgumentException("Method call corrupted"); + } + + @Override + public ByteBuffer encodeSuccessEnvelope(Object result) { + final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); + stream.write(0); + StandardMessageCodec.writeValue(stream, result); + final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); + buffer.put(stream.buffer(), 0, stream.size()); + return buffer; + } + + @Override + public ByteBuffer encodeErrorEnvelope(String errorCode, String errorMessage, + Object errorDetails) { + final ExposedByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); + stream.write(1); + StandardMessageCodec.writeValue(stream, errorCode); + StandardMessageCodec.writeValue(stream, errorMessage); + StandardMessageCodec.writeValue(stream, errorDetails); + final ByteBuffer buffer = ByteBuffer.allocateDirect(stream.size()); + buffer.put(stream.buffer(), 0, stream.size()); + return buffer; + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StringMessageCodec.java b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StringMessageCodec.java new file mode 100644 index 0000000000..f47e39c2a2 --- /dev/null +++ b/engine/src/flutter/shell/platform/android/io/flutter/plugin/common/StringMessageCodec.java @@ -0,0 +1,51 @@ +// 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. + +package io.flutter.plugin.common; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +/** + * A {@link MessageCodec} using UTF-8 encoded String messages. + */ +public final class StringMessageCodec implements MessageCodec { + // This codec must match the Dart codec of the same name in package flutter/services. + public static final StringMessageCodec INSTANCE = new StringMessageCodec(); + + private StringMessageCodec() { + } + + @Override + public ByteBuffer encodeMessage(String message) { + if (message == null) { + return null; + } + // TODO(mravn): Avoid the extra copy below. + final byte[] bytes = message.getBytes(StandardCharsets.UTF_8); + final ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length); + buffer.put(bytes); + return buffer; + } + + @Override + public String decodeMessage(ByteBuffer message) { + if (message == null) { + return null; + } + final byte[] bytes; + final int offset; + final int length = message.remaining(); + if (message.hasArray()) { + bytes = message.array(); + offset = message.arrayOffset(); + } else { + // TODO(mravn): Avoid the extra copy below. + bytes = new byte[length]; + message.get(bytes); + offset = 0; + } + return new String(bytes, offset, length, StandardCharsets.UTF_8); + } +} diff --git a/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java b/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java index 7615563f4c..28181b65ff 100644 --- a/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java +++ b/engine/src/flutter/shell/platform/android/io/flutter/view/FlutterView.java @@ -11,7 +11,6 @@ import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.res.Configuration; -import android.opengl.Matrix; import android.graphics.Bitmap; import android.graphics.Rect; import android.os.Build; @@ -23,13 +22,12 @@ import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; -import android.view.View; import android.view.WindowInsets; import android.view.accessibility.AccessibilityManager; -import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; +import io.flutter.plugin.common.StringMessageCodec; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -40,7 +38,6 @@ import org.chromium.base.JNINamespace; import java.net.URI; import java.nio.ByteBuffer; import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -74,8 +71,7 @@ public class FlutterView extends SurfaceView private long mNativePlatformView; private TextInputPlugin mTextInputPlugin; - private HashMap mOnMessageListeners; - private HashMap mAsyncOnMessageListeners; + private HashMap mMessageListeners; private final SurfaceHolder.Callback mSurfaceCallback; private final ViewportMetrics mMetrics; private final AccessibilityManager mAccessibilityManager; @@ -128,8 +124,7 @@ public class FlutterView extends SurfaceView mAccessibilityManager = (AccessibilityManager)getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); - mOnMessageListeners = new HashMap(); - mAsyncOnMessageListeners = new HashMap(); + mMessageListeners = new HashMap(); mActivityLifecycleListeners = new ArrayList(); setLocale(getResources().getConfiguration().locale); @@ -557,13 +552,13 @@ public class FlutterView extends SurfaceView private static native Bitmap nativeGetBitmap(long nativePlatformViewAndroid); // Send a platform message to Dart. - private static native void nativeDispatchPlatformMessage(long nativePlatformViewAndroid, String channel, String message, int responseId); + private static native void nativeDispatchPlatformMessage(long nativePlatformViewAndroid, String channel, ByteBuffer message, int position, int responseId); private static native void nativeDispatchPointerDataPacket(long nativePlatformViewAndroid, ByteBuffer buffer, int position); private static native void nativeDispatchSemanticsAction(long nativePlatformViewAndroid, int id, int action); private static native void nativeSetSemanticsEnabled(long nativePlatformViewAndroid, boolean enabled); // Send a response to a platform message received from Dart. - private static native void nativeInvokePlatformMessageResponseCallback(long nativePlatformViewAndroid, int responseId, String message); + private static native void nativeInvokePlatformMessageResponseCallback(long nativePlatformViewAndroid, int responseId, ByteBuffer message, int position); private void updateViewportMetrics() { nativeSetViewportMetrics(mNativePlatformView, @@ -578,51 +573,41 @@ public class FlutterView extends SurfaceView // Called by native to send us a platform message. @CalledByNative - private void handlePlatformMessage(String channel, String message, final int responseId) { - OnMessageListener listener = mOnMessageListeners.get(channel); + private void handlePlatformMessage(String channel, ByteBuffer message, final int responseId) { + OnBinaryMessageListenerAsync listener = mMessageListeners.get(channel); if (listener != null) { - String response = null; try { - response = listener.onMessage(this, message); + listener.onMessage(this, message, + new BinaryMessageResponse() { + @Override + public void send(ByteBuffer response) { + nativeInvokePlatformMessageResponseCallback(mNativePlatformView, + responseId, response, response == null ? 0 : response.position()); + } + }); } catch (Exception ex) { - Log.e(TAG, "Uncaught exception in message listener", ex); - } - nativeInvokePlatformMessageResponseCallback(mNativePlatformView, responseId, response); - return; - } - - OnMessageListenerAsync asyncListener = mAsyncOnMessageListeners.get(channel); - if (asyncListener != null) { - try { - asyncListener.onMessage(this, message, new MessageResponse() { - @Override - public void send(String response) { - nativeInvokePlatformMessageResponseCallback(mNativePlatformView, responseId, response); - } - }); - } catch (Exception ex) { - Log.e(TAG, "Uncaught exception in async message listener", ex); - nativeInvokePlatformMessageResponseCallback(mNativePlatformView, responseId, null); + Log.e(TAG, "Uncaught exception in binary message listener", ex); + nativeInvokePlatformMessageResponseCallback(mNativePlatformView, responseId, + null, 0); } return; } - - nativeInvokePlatformMessageResponseCallback(mNativePlatformView, responseId, null); + nativeInvokePlatformMessageResponseCallback(mNativePlatformView, responseId, null, 0); } private int mNextResponseId = 1; - private final Map mPendingResponses = new HashMap(); + private final Map mPendingResponses + = new HashMap(); // Called by native to respond to a platform message that we sent. @CalledByNative - private void handlePlatformMessageResponse(int responseId, String response) { - MessageReplyCallback callback = mPendingResponses.remove(responseId); + private void handlePlatformMessageResponse(int responseId, ByteBuffer response) { + BinaryMessageReplyCallback callback = mPendingResponses.remove(responseId); if (callback != null) { try { callback.onReply(response); } catch (Exception ex) { - Log.e(TAG, "Uncaught exception in message listener reply", ex); - return; + Log.e(TAG, "Uncaught exception in binary message listener reply", ex); } } } @@ -747,14 +732,12 @@ public class FlutterView extends SurfaceView * @param channel Name of the channel that will receive this message. * @param message Message payload. * @param callback Callback that receives a reply from the application. + * @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. */ + @Deprecated public void sendPlatformMessage(String channel, String message, MessageReplyCallback callback) { - int responseId = 0; - if (callback != null) { - responseId = mNextResponseId++; - mPendingResponses.put(responseId, callback); - } - nativeDispatchPlatformMessage(mNativePlatformView, channel, message, responseId); + sendToFlutter(channel, message, callback); } /** @@ -763,28 +746,107 @@ public class FlutterView extends SurfaceView * @param channel Name of the channel that will receive this message. * @param message Message payload. * @param callback Callback that receives a reply from the application. + * @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. */ - public void sendToFlutter(String channel, String message, MessageReplyCallback callback) { - sendPlatformMessage(channel, message, callback); + @Deprecated + public void sendToFlutter(String channel, String message, final MessageReplyCallback callback) { + sendBinaryMessage(channel, StringMessageCodec.INSTANCE.encodeMessage(message), + callback == null ? null : new BinaryMessageReplyCallback() { + @Override + public void onReply(ByteBuffer reply) { + callback.onReply(StringMessageCodec.INSTANCE.decodeMessage(reply)); + } + }); } + /** @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. + */ + @Deprecated public void sendToFlutter(String channel, String message) { sendToFlutter(channel, message, null); } - /** Callback invoked when the app replies to a message sent with sendToFlutter. */ + /** + * Send a binary message to the Flutter application. The Flutter Dart code can register a + * platform message handler that will receive these messages. + * @param channel Name of the channel that will receive this message. + * @param message Message payload, a {@link ByteBuffer} with the message bytes between position + * zero and current position, or null. + * @param callback Callback that receives a reply from the Flutter application. + */ + public void sendBinaryMessage(String channel, ByteBuffer message, BinaryMessageReplyCallback callback) { + int responseId = 0; + if (callback != null) { + responseId = mNextResponseId++; + mPendingResponses.put(responseId, callback); + } + nativeDispatchPlatformMessage(mNativePlatformView, channel, message, + message == null ? 0 : message.position(), responseId); + } + + /** Callback invoked when the app replies to a String message sent with sendToFlutter. + * @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. + */ public interface MessageReplyCallback { void onReply(String reply); } + /** Callback invoked when the app replies to a binary message sent with sendBinaryMessage. */ + public interface BinaryMessageReplyCallback { + void onReply(ByteBuffer reply); + } + /** * Register a callback to be invoked when the Flutter application sends a message * to its host. * @param channel Name of the channel used by the application. * @param listener Called when messages arrive. + * @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. */ - public void addOnMessageListener(String channel, OnMessageListener listener) { - mOnMessageListeners.put(channel, listener); + @Deprecated + public void addOnMessageListener(String channel, final OnMessageListener listener) { + addOnBinaryMessageListenerAsync(channel, + listener == null ? null : new OnBinaryMessageListenerAsync() { + @Override + public void onMessage(FlutterView view, ByteBuffer message, + BinaryMessageResponse response) { + response.send(StringMessageCodec.INSTANCE.encodeMessage(listener.onMessage( + view, StringMessageCodec.INSTANCE.decodeMessage(message)))); + } + } + ); + } + + /** + * Register a callback to be invoked when the Flutter application sends a message + * to its host. The reply to the message can be provided asynchronously. + * @param channel Name of the channel used by the application. + * @param listener Called when messages arrive. + * @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. + */ + @Deprecated + public void addOnMessageListenerAsync(String channel, final OnMessageListenerAsync listener) { + addOnBinaryMessageListenerAsync(channel, + listener == null ? null : new OnBinaryMessageListenerAsync() { + @Override + public void onMessage(FlutterView view, ByteBuffer message, + final BinaryMessageResponse response) { + listener.onMessage(view, StringMessageCodec.INSTANCE.decodeMessage(message), + new MessageResponse() { + @Override + public void send(String reply) { + response.send(StringMessageCodec.INSTANCE.encodeMessage(reply)); + } + } + ); + } + } + ); } /** @@ -793,10 +855,19 @@ public class FlutterView extends SurfaceView * @param channel Name of the channel used by the application. * @param listener Called when messages arrive. */ - public void addOnMessageListenerAsync(String channel, OnMessageListenerAsync listener) { - mAsyncOnMessageListeners.put(channel, listener); + public void addOnBinaryMessageListenerAsync(String channel, OnBinaryMessageListenerAsync listener) { + if (listener == null) { + mMessageListeners.remove(channel); + } else { + mMessageListeners.put(channel, listener); + } } + /** + * @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. + */ + @Deprecated public interface OnMessageListener { /** * Called when a message is received from the Flutter app. @@ -805,8 +876,13 @@ public class FlutterView extends SurfaceView * @return the reply to the message (can be null) */ String onMessage(FlutterView view, String message); - }; + } + /** + * @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. + */ + @Deprecated public interface OnMessageListenerAsync { /** * Called when a message is received from the Flutter app. @@ -817,10 +893,29 @@ public class FlutterView extends SurfaceView void onMessage(FlutterView view, String message, MessageResponse response); } + public interface OnBinaryMessageListenerAsync { + /** + * Called when a message is received from the Flutter app. + * @param view The Flutter view hosting the app. + * @param message Message payload. + * @param response Used to send a reply back to the app. + */ + void onMessage(FlutterView view, ByteBuffer message, BinaryMessageResponse response); + } + + /** + * @deprecated Use {@link io.flutter.plugin.common.FlutterMessageChannel} + * with {@link StringMessageCodec} instead. + */ + @Deprecated public interface MessageResponse { void send(String reply); } + public interface BinaryMessageResponse { + void send(ByteBuffer reply); + } + /** Broadcast receiver used to discover active Flutter instances. */ private class DiscoveryReceiver extends BroadcastReceiver { @Override diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.cc b/engine/src/flutter/shell/platform/android/platform_view_android.cc index 67a054ce0d..a2a4bd7dcd 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android.cc +++ b/engine/src/flutter/shell/platform/android/platform_view_android.cc @@ -232,12 +232,16 @@ void PlatformViewAndroid::SetViewportMetrics(JNIEnv* env, void PlatformViewAndroid::DispatchPlatformMessage(JNIEnv* env, jobject obj, jstring java_name, - jstring java_message_data, + jobject java_message_data, + jint java_message_position, jint response_id) { std::string name = base::android::ConvertJavaStringToUTF8(env, java_name); - std::string data; - if (java_message_data) - data = base::android::ConvertJavaStringToUTF8(env, java_message_data); + std::vector message; + if (java_message_data) { + uint8_t* message_data = static_cast(env->GetDirectBufferAddress(java_message_data)); + message = std::vector(message_data, message_data + java_message_position); + } + ftl::RefPtr response; if (response_id) { @@ -245,11 +249,9 @@ void PlatformViewAndroid::DispatchPlatformMessage(JNIEnv* env, response_id, GetWeakPtr()); } - const uint8_t* buffer = reinterpret_cast(data.data()); PlatformView::DispatchPlatformMessage( - ftl::MakeRefCounted( - std::move(name), std::vector(buffer, buffer + data.size()), - std::move(response))); + ftl::MakeRefCounted(std::move(name), std::move(message), + std::move(response))); } void PlatformViewAndroid::DispatchPointerDataPacket(JNIEnv* env, @@ -271,20 +273,21 @@ void PlatformViewAndroid::InvokePlatformMessageResponseCallback( JNIEnv* env, jobject obj, jint response_id, - jstring java_response) { + jobject java_response_data, + jint java_response_position) { if (!response_id) return; auto it = pending_responses_.find(response_id); if (it == pending_responses_.end()) return; - std::string response; - if (java_response) - response = base::android::ConvertJavaStringToUTF8(env, java_response); + std::vector response; + if (java_response_data) { + uint8_t* response_data = static_cast(env->GetDirectBufferAddress(java_response_data)); + response = std::vector(response_data, response_data + java_response_position); + } auto message_response = std::move(it->second); pending_responses_.erase(it); - // TODO(abarth): There's an extra copy here. - message_response->Complete( - std::vector(response.data(), response.data() + response.size())); + message_response->Complete(std::move(response)); } void PlatformViewAndroid::HandlePlatformMessage( @@ -301,18 +304,14 @@ void PlatformViewAndroid::HandlePlatformMessage( } auto data = message->data(); - base::StringPiece message_data(reinterpret_cast(data.data()), - data.size()); - auto java_channel = base::android::ConvertUTF8ToJavaString(env, message->channel()); - auto java_message_data = - base::android::ConvertUTF8ToJavaString(env, message_data); message = nullptr; // This call can re-enter in InvokePlatformMessageResponseCallback. Java_FlutterView_handlePlatformMessage(env, view.obj(), java_channel.obj(), - java_message_data.obj(), response_id); + env->NewDirectByteBuffer(data.data(), data.size()), + response_id); } void PlatformViewAndroid::HandlePlatformMessageResponse( @@ -323,13 +322,8 @@ void PlatformViewAndroid::HandlePlatformMessageResponse( if (view.is_null()) return; - base::StringPiece message_data(reinterpret_cast(data.data()), - data.size()); - auto java_message_data = - base::android::ConvertUTF8ToJavaString(env, message_data); - Java_FlutterView_handlePlatformMessageResponse(env, view.obj(), response_id, - java_message_data.obj()); + env->NewDirectByteBuffer(data.data(), data.size())); } void PlatformViewAndroid::DispatchSemanticsAction(JNIEnv* env, diff --git a/engine/src/flutter/shell/platform/android/platform_view_android.h b/engine/src/flutter/shell/platform/android/platform_view_android.h index 03b7f1c274..cd642bb576 100644 --- a/engine/src/flutter/shell/platform/android/platform_view_android.h +++ b/engine/src/flutter/shell/platform/android/platform_view_android.h @@ -63,7 +63,8 @@ class PlatformViewAndroid : public PlatformView { void DispatchPlatformMessage(JNIEnv* env, jobject obj, jstring name, - jstring message, + jobject message_data, + jint message_position, jint response_id); void DispatchPointerDataPacket(JNIEnv* env, @@ -74,7 +75,8 @@ class PlatformViewAndroid : public PlatformView { void InvokePlatformMessageResponseCallback(JNIEnv* env, jobject obj, jint response_id, - jstring response); + jobject response_data, + jint response_position); void DispatchSemanticsAction(JNIEnv* env, jobject obj, jint id, jint action);