Commit c4a86788 authored by Adam Barth's avatar Adam Barth Committed by Jason Simmons

Add an ergonomic wrapper for platform messages (#6281)

This wrapper will eventually replace HostMessages.
parent 6777766d
......@@ -27,6 +27,7 @@ export 'src/services/image_resolution.dart';
export 'src/services/image_stream.dart';
export 'src/services/keyboard.dart';
export 'src/services/path_provider.dart';
export 'src/services/platform_messages.dart';
export 'src/services/shell.dart';
export 'src/services/system_chrome.dart';
export 'src/services/system_sound.dart';
......
// 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.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui' as ui;
String _decodeUTF8(ByteData data) {
return data != null ? UTF8.decoder.convert(data.buffer.asUint8List()) : null;
}
dynamic _decodeJSON(String message) {
return message != null ? JSON.decode(message) : null;
}
void _sendString(String name, String message, void callback(String reply)) {
Uint8List encoded = UTF8.encoder.convert(message);
ui.window.sendPlatformMesssage(name, encoded.buffer.asByteData(), (ByteData reply) {
callback(_decodeUTF8(reply));
});
}
/// Sends messages to the hosting application.
class PlatformMessages {
/// Send a string message to the host application.
static Future<String> sendString(String name, String message) {
Completer<String> completer = new Completer<String>();
_sendString(name, message, (String reply) {
completer.complete(reply);
});
return completer.future;
}
/// Sends a JSON-encoded message to the host application and JSON-decodes the response.
static Future<dynamic> sendJSON(String name, dynamic json) {
Completer<dynamic> completer = new Completer<dynamic>();
_sendString(name, JSON.encode(json), (String reply) {
completer.complete(_decodeJSON(reply));
});
return completer.future;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment