diff options
Diffstat (limited to 'mojo/public/dart')
-rw-r--r-- | mojo/public/dart/DEPS | 4 | ||||
-rw-r--r-- | mojo/public/dart/README | 27 | ||||
-rw-r--r-- | mojo/public/dart/bindings.dart | 17 | ||||
-rw-r--r-- | mojo/public/dart/core.dart | 20 | ||||
-rw-r--r-- | mojo/public/dart/src/buffer.dart | 104 | ||||
-rw-r--r-- | mojo/public/dart/src/client.dart | 82 | ||||
-rw-r--r-- | mojo/public/dart/src/codec.dart | 731 | ||||
-rw-r--r-- | mojo/public/dart/src/data_pipe.dart | 192 | ||||
-rw-r--r-- | mojo/public/dart/src/event_stream.dart | 207 | ||||
-rw-r--r-- | mojo/public/dart/src/handle.dart | 74 | ||||
-rw-r--r-- | mojo/public/dart/src/handle_watcher.dart | 347 | ||||
-rw-r--r-- | mojo/public/dart/src/interface.dart | 103 | ||||
-rw-r--r-- | mojo/public/dart/src/message.dart | 97 | ||||
-rw-r--r-- | mojo/public/dart/src/message_pipe.dart | 155 | ||||
-rw-r--r-- | mojo/public/dart/src/struct.dart | 38 | ||||
-rw-r--r-- | mojo/public/dart/src/timer_impl.dart | 333 | ||||
-rw-r--r-- | mojo/public/dart/src/timer_queue.dart | 53 | ||||
-rw-r--r-- | mojo/public/dart/src/types.dart | 207 |
18 files changed, 0 insertions, 2791 deletions
diff --git a/mojo/public/dart/DEPS b/mojo/public/dart/DEPS deleted file mode 100644 index 53d0007..0000000 --- a/mojo/public/dart/DEPS +++ /dev/null @@ -1,4 +0,0 @@ -include_rules = [ - "+dart", - "+base", -]
\ No newline at end of file diff --git a/mojo/public/dart/README b/mojo/public/dart/README deleted file mode 100644 index f9cd6e6..0000000 --- a/mojo/public/dart/README +++ /dev/null @@ -1,27 +0,0 @@ -These are interim instructions for building and testing Dart's Mojo bindings. -These instructions currently only work for Linux, and assume you already have a -Mojo checkout. - -1.) Add a Dart VM source checkout to your client: - - Edit your .gclient file. Replace "DEPS" with "DEPS.dart". - Then, run: - - $ gclient sync - - You should now have a directory //dart - - -2.) Configure Mojo with Dart. - - $ ./mojo/tools/mojob.py gn --release --with-dart - - -3.) Build Mojo with Dart. - - $ ./mojo/tools/mojob.py build --release - - -4.) Run Dart tests. - - $ ./mojo/tools/mojob.py darttest --release diff --git a/mojo/public/dart/bindings.dart b/mojo/public/dart/bindings.dart deleted file mode 100644 index 5d6298e..0000000 --- a/mojo/public/dart/bindings.dart +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2014 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. - -library bindings; - -import 'dart:async'; -import 'dart:convert'; -import 'dart:mirrors'; -import 'dart:mojo_core' as core; -import 'dart:typed_data'; - -part 'src/client.dart'; -part 'src/codec.dart'; -part 'src/interface.dart'; -part 'src/message.dart'; -part 'src/struct.dart'; diff --git a/mojo/public/dart/core.dart b/mojo/public/dart/core.dart deleted file mode 100644 index e9fb716..0000000 --- a/mojo/public/dart/core.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2014 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. - -library core; - -import 'dart:async'; -import 'dart:collection'; -import 'dart:isolate'; -import 'dart:typed_data'; - -part 'src/buffer.dart'; -part 'src/data_pipe.dart'; -part 'src/event_stream.dart'; -part 'src/handle.dart'; -part 'src/handle_watcher.dart'; -part 'src/message_pipe.dart'; -part 'src/timer_impl.dart'; -part 'src/timer_queue.dart'; -part 'src/types.dart'; diff --git a/mojo/public/dart/src/buffer.dart b/mojo/public/dart/src/buffer.dart deleted file mode 100644 index 4467315..0000000 --- a/mojo/public/dart/src/buffer.dart +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2014 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. - -part of core; - -class _MojoSharedBufferNatives { - static List Create(int numBytes, int flags) - native "MojoSharedBuffer_Create"; - - static List Duplicate(int bufferHandle, int flags) - native "MojoSharedBuffer_Duplicate"; - - static List Map(MojoSharedBuffer buffer, - int bufferHandle, - int offset, - int numBytes, - int flags) - native "MojoSharedBuffer_Map"; - - static int Unmap(ByteData buffer) - native "MojoSharedBuffer_Unmap"; -} - - -class MojoSharedBuffer { - static const int CREATE_FLAG_NONE = 0; - static const int DUPLICATE_FLAG_NONE = 0; - static const int MAP_FLAG_NONE = 0; - - MojoHandle handle; - MojoResult status; - ByteData mapping; - - MojoSharedBuffer( - this.handle, [this.status = MojoResult.OK, this.mapping = null]); - - factory MojoSharedBuffer.create(int numBytes, [int flags = 0]) { - List result = _MojoSharedBufferNatives.Create(numBytes, flags); - if (result == null) { - return null; - } - assert((result is List) && (result.length == 2)); - var r = new MojoResult(result[0]); - if (!r.isOk) { - return null; - } - - MojoSharedBuffer buf = - new MojoSharedBuffer(new MojoHandle(result[1]), r, null); - return buf; - } - - factory MojoSharedBuffer.duplicate(MojoSharedBuffer msb, [int flags = 0]) { - List result = _MojoSharedBufferNatives.Duplicate(msb.handle.h, flags); - if (result == null) { - return null; - } - assert((result is List) && (result.length == 2)); - var r = new MojoResult(result[0]); - if(!r.isOk) { - return null; - } - - MojoSharedBuffer dupe = - new MojoSharedBuffer(new MojoHandle(result[1]), r, null); - return dupe; - } - - MojoResult close() { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - MojoResult r = handle.close(); - status = r; - mapping = null; - return status; - } - - MojoResult map(int offset, int numBytes, [int flags = 0]) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - List result = _MojoSharedBufferNatives.Map( - this, handle.h, offset, numBytes, flags); - if (result == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - assert((result is List) && (result.length == 2)); - status = new MojoResult(result[0]); - mapping = result[1]; - return status; - } - - MojoResult unmap() { - int r = _MojoSharedBufferNatives.Unmap(mapping); - status = new MojoResult(r); - mapping = null; - return status; - } -} diff --git a/mojo/public/dart/src/client.dart b/mojo/public/dart/src/client.dart deleted file mode 100644 index f8ec73c..0000000 --- a/mojo/public/dart/src/client.dart +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2014 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. - -part of bindings; - -abstract class Client extends core.MojoEventStreamListener { - Map<int, Completer> _completerMap; - int _nextId = 0; - - Client(core.MojoMessagePipeEndpoint endpoint) : - _completerMap = {}, - super(endpoint); - - Client.fromHandle(core.MojoHandle handle) : - _completerMap = {}, - super.fromHandle(handle); - - Client.unbound() : - _completerMap = {}, - super.unbound(); - - void handleResponse(ServiceMessage reader); - - void handleRead() { - // Query how many bytes are available. - var result = endpoint.query(); - assert(result.status.isOk || result.status.isResourceExhausted); - - // Read the data. - var bytes = new ByteData(result.bytesRead); - var handles = new List<core.MojoHandle>(result.handlesRead); - result = endpoint.read(bytes, result.bytesRead, handles); - assert(result.status.isOk || result.status.isResourceExhausted); - var message = new ServiceMessage.fromMessage(new Message(bytes, handles)); - handleResponse(message); - } - - void handleWrite() { - throw 'Unexpected write signal in client.'; - } - - void sendMessage(Struct message, int name) { - if (!isOpen) { - listen(); - } - var header = new MessageHeader(name); - var serviceMessage = message.serializeWithHeader(header); - endpoint.write(serviceMessage.buffer, - serviceMessage.buffer.lengthInBytes, - serviceMessage.handles); - if (!endpoint.status.isOk) { - throw "message pipe write failed"; - } - } - - Future sendMessageWithRequestId( - Struct message, int name, int id, int flags) { - if (!isOpen) { - listen(); - } - if (id == -1) { - id = _nextId++; - } - - var header = new MessageHeader.withRequestId(name, flags, id); - var serviceMessage = message.serializeWithHeader(header); - endpoint.write(serviceMessage.buffer, - serviceMessage.buffer.lengthInBytes, - serviceMessage.handles); - if (!endpoint.status.isOk) { - throw "message pipe write failed"; - } - - var completer = new Completer(); - _completerMap[id] = completer; - return completer.future; - } - - // Need a getter for this for access in subclasses. - Map<int, Completer> get completerMap => _completerMap; -} diff --git a/mojo/public/dart/src/codec.dart b/mojo/public/dart/src/codec.dart deleted file mode 100644 index d5f5b90..0000000 --- a/mojo/public/dart/src/codec.dart +++ /dev/null @@ -1,731 +0,0 @@ -// Copyright 2014 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. - -part of bindings; - -int align(int size) => size + (kAlignment - (size % kAlignment)) % kAlignment; - -const int kAlignment = 8; -const int kSerializedHandleSize = 4; -const int kPointerSize = 8; -const DataHeader kMapStructHeader = const DataHeader(24, 2); -const int kUnspecifiedArrayLength = -1; -const int kNothingNullable = 0; -const int kArrayNullable = (1 << 0); -const int kElementNullable = (1 << 1); - -bool isArrayNullable(int nullability) => (nullability & kArrayNullable) > 0; -bool isElementNullable(int nullability) => (nullability & kElementNullable) > 0; - -class _EncoderBuffer { - ByteData buffer; - List<core.MojoHandle> handles; - int extent; - - static const int kInitialBufferSize = 1024; - - _EncoderBuffer([int size = -1]) : - buffer = new ByteData(size > 0 ? size : kInitialBufferSize), - handles = [], - extent = 0; - - void _grow(int newSize) { - Uint8List newBuffer = new Uint8List(newSize); - newBuffer.setRange(0, buffer.lengthInBytes, buffer.buffer.asUint8List()); - buffer = newBuffer.buffer.asByteData(); - } - - void claimMemory(int claimSize) { - extent += claimSize; - if (extent > buffer.lengthInBytes) { - int newSize = buffer.lengthInBytes + claimSize; - newSize += newSize ~/ 2; - _grow(newSize); - } - } - - ByteData get trimmed => new ByteData.view(buffer.buffer, 0, extent); -} - -class Encoder { - _EncoderBuffer _buffer; - int _base; - - Encoder([int size = -1]) : _buffer = new _EncoderBuffer(size), _base = 0; - - Encoder._fromBuffer(_EncoderBuffer buffer) : - _buffer = buffer, - _base = buffer.extent; - - Encoder getEncoderAtOffset(DataHeader dataHeader) { - var result = new Encoder._fromBuffer(_buffer); - result.encodeDataHeader(dataHeader); - return result; - } - - Message get message => new Message(_buffer.trimmed, _buffer.handles); - - void encodeDataHeader(DataHeader dataHeader) { - _buffer.claimMemory(align(dataHeader.size)); - encodeUint32(dataHeader.size, DataHeader.kSizeOffset); - encodeUint32(dataHeader.numFields, DataHeader.kNumFieldsOffset); - } - - static const String kErrorUnsigned = - 'Passing negative value to unsigned encoder'; - - void encodeBool(bool value, int offset, int bit) { - if (value) { - int encodedValue = _buffer.buffer.getUint8(_base + offset); - encodedValue |= (1 << bit); - _buffer.buffer.setUint8(_base + offset, encodedValue); - } - } - - void encodeInt8(int value, int offset) => - _buffer.buffer.setInt8(_base + offset, value); - - void encodeUint8(int value, int offset) { - if (value < 0) { - throw '$kErrorUnsigned: $val'; - } - _buffer.buffer.setUint8(_base + offset, value); - } - - void encodeInt16(int value, int offset) => - _buffer.buffer.setInt16(_base + offset, value, Endianness.LITTLE_ENDIAN); - - void encodeUint16(int value, int offset) { - if (value < 0) { - throw '$kErrorUnsigned: $val'; - } - _buffer.buffer.setUint16(_base + offset, value, Endianness.LITTLE_ENDIAN); - } - - void encodeInt32(int value, int offset) => - _buffer.buffer.setInt32(_base + offset, value, Endianness.LITTLE_ENDIAN); - - void encodeUint32(int value, int offset) { - if (value < 0) { - throw '$kErrorUnsigned: $val'; - } - _buffer.buffer.setUint32(_base + offset, value, Endianness.LITTLE_ENDIAN); - } - - void encodeInt64(int value, int offset) => - _buffer.buffer.setInt64(_base + offset, value, Endianness.LITTLE_ENDIAN); - - void encodeUint64(int value, int offset) { - if (value < 0) { - throw '$kErrorUnsigned: $val'; - } - _buffer.buffer.setUint64(_base + offset, value, Endianness.LITTLE_ENDIAN); - } - - void encodeFloat(double value, int offset) => - _buffer.buffer.setFloat32(_base + offset, value, Endianness.LITTLE_ENDIAN); - - void encodeDouble(double value, int offset) => - _buffer.buffer.setFloat64(_base + offset, value, Endianness.LITTLE_ENDIAN); - - void encodeHandle(core.MojoHandle value, int offset, bool nullable) { - if ((value == null) || !value.isValid) { - encodeInvalideHandle(offset, nullable); - } else { - encodeUint32(_buffer.handles.length, offset); - _buffer.handles.add(value); - } - } - - void encodeMessagePipeHandle( - core.MojoMessagePipeEndpoint value, int offset, bool nullable) => - encodeHandle(value != null ? value.handle : null, offset, nullable); - - void encodeConsumerHandle( - core.MojoDataPipeConsumer value, int offset, bool nullable) => - encodeHandle(value != null ? value.handle : null, offset, nullable); - - void encodeProducerHandle( - core.MojoDataPipeProducer value, int offset, bool nullable) => - encodeHandle(value != null ? value.handle : null, offset, nullable); - - void encodeSharedBufferHandle( - core.MojoSharedBuffer value, int offset, bool nullable) => - encodeHandle(value != null ? value.handle : null, offset, nullable); - - void encodeInterface(Interface interface, int offset, bool nullable) { - if (interface == null) { - encodeInvalideHandle(offset, nullable); - return; - } - var pipe = new core.MojoMessagePipe(); - interface.bind(pipe.endpoints[0]); - encodeMessagePipeHandle(pipe.endpoints[1], offset, nullable); - } - - void encodeInterfaceRequest(Client client, int offset, bool nullable) { - if (client == null) { - encodeInvalideHandle(offset, nullable); - return; - } - var pipe = new core.MojoMessagePipe(); - client.bind(pipe.endpoints[0]); - encodeMessagePipeHandle(pipe.endpoints[1], offset, nullable); - } - - void encodeNullPointer(int offset, bool nullable) { - if (!nullable) { - throw 'Trying to encode a null pointer for a non-nullable type'; - } - _buffer.buffer.setUint64(_base + offset, 0, Endianness.LITTLE_ENDIAN); - } - - void encodeInvalideHandle(int offset, bool nullable) { - if (!nullable) { - throw 'Trying to encode a null pointer for a non-nullable type'; - } - _buffer.buffer.setInt32(_base + offset, -1, Endianness.LITTLE_ENDIAN); - } - - void encodePointerToNextUnclaimed(int offset) => - encodeUint64(_buffer.extent - (_base + offset), offset); - - void encodeStruct(Struct value, int offset, bool nullable) { - if (value == null) { - encodeNullPointer(offset, nullable); - return; - } - encodePointerToNextUnclaimed(offset); - value.encode(this); - } - - Encoder encodePointerArray(int length, int offset, int expectedLength) => - encoderForArray(kPointerSize, length, offset, expectedLength); - - Encoder encoderForArray( - int elementSize, int length, int offset, int expectedLength) { - if ((expectedLength != kUnspecifiedArrayLength) && - (expectedLength != length)) { - throw 'Trying to encode a fixed array of incorrect length'; - } - return encoderForArrayByTotalSize(length * elementSize, length, offset); - } - - Encoder encoderForArrayByTotalSize(int size, int length, int offset) { - encodePointerToNextUnclaimed(offset); - return getEncoderAtOffset( - new DataHeader(DataHeader.kHeaderSize + size, length)); - } - - void encodeBoolArray( - List<bool> value, int offset, int nullability, int expectedLength) { - if (value == null) { - encodeNullPointer(offset, isArrayNullable(nullability)); - return; - } - if ((expectedLength != kUnspecifiedArrayLength) && - (expectedLength != value.length)) { - throw 'Trying to encode a fixed array of incorrect size.'; - } - var bytes = new Uint8List((value.length + 7) ~/ kAlignment); - for (int i = 0; i < bytes.length; ++i) { - for (int j = 0; j < kAlignment; ++j) { - int boolIndex = kAlignment * i + j; - if ((boolIndex < value.length) && value[boolIndex]) { - bytes[i] |= (1 << j); - } - } - } - var encoder = encoderForArrayByTotalSize( - bytes.length, value.length, offset); - encoder.appendUint8Array(bytes); - } - - void encodeArray(Function arrayAppend, - int elementBytes, - List<int> value, - int offset, - int nullability, - int expectedLength) { - if (value == null) { - encodeNullPointer(offset, isArrayNullable(nullability)); - return; - } - var encoder = encoderForArray( - elementBytes, value.length, offset, expectedLength); - arrayAppend(encoder, value); - } - - void encodeInt8Array( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendInt8Array(v), - 1, value, offset, nullability, expectedLength); - - void encodeUint8Array( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendUint8Array(v), - 1, value, offset, nullability, expectedLength); - - void encodeInt16Array( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendInt16Array(v), - 2, value, offset, nullability, expectedLength); - - void encodeUint16Array( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendUint16Array(v), - 2, value, offset, nullability, expectedLength); - - void encodeInt32Array( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendInt32Array(v), - 4, value, offset, nullability, expectedLength); - - void encodeUint32Array( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendUint32Array(v), - 4, value, offset, nullability, expectedLength); - - void encodeInt64Array( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendInt64Array(v), - 8, value, offset, nullability, expectedLength); - - void encodeUint64Array( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendUint64Array(v), - 8, value, offset, nullability, expectedLength); - - void encodeFloatArray( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendFloatArray(v), - 4, value, offset, nullability, expectedLength); - - void encodeDoubleArray( - List<int> value, int offset, int nullability, int expectedLength) => - encodeArray((e, v) => e.appendDoubleArray(v), - 8, value, offset, nullability, expectedLength); - - void _handleArrayEncodeHelper(Function elementEncoder, - List value, - int offset, - int nullability, - int expectedLength) { - if (value == null) { - encodeNullPointer(offset, isArrayNullable(nullability)); - return; - } - var encoder = encoderForArray( - kSerializedHandleSize, value.length, offset, expectedLength); - for (int i = 0; i < value.length; ++i) { - int handleOffset = DataHeader.kHeaderSize + kSerializedHandleSize * i; - elementEncoder( - encoder, value[i], handleOffset, isElementNullable(nullability)); - } - } - - void encodeHandleArray( - List<core.MojoHandle> value, - int offset, - int nullability, - int expectedLength) => - _handleArrayEncodeHelper( - (e, v, o, n) => e.encodeHandle(v, o, n), - value, offset, nullability, expectedLength); - - void encodeMessagePipeHandleArray( - List<core.MojoMessagePipeEndpoint> value, - int offset, - int nullability, - int expectedLength) => - _handleArrayEncodeHelper( - (e, v, o, n) => e.encodeMessagePipeHandle(v, o, n), - value, offset, nullability, expectedLength); - - void encodeConsumerHandleArray( - List<core.MojoDataPipeConsumer> value, - int offset, - int nullability, - int expectedLength) => - _handleArrayEncodeHelper( - (e, v, o, n) => e.encodeConsumerHandle(v, o, n), - value, offset, nullability, expectedLength); - - void encodeProducerHandleArray( - List<core.MojoDataPipeProducer> value, - int offset, - int nullability, - int expectedLength) => - _handleArrayEncodeHelper( - (e, v, o, n) => e.encodeProducerHandle(v, o, n), - value, offset, nullability, expectedLength); - - void encodeSharedBufferHandleArray( - List<core.MojoSharedBuffer> value, - int offset, - int nullability, - int expectedLength) => - _handleArrayEncodeHelper( - (e, v, o, n) => e.encodeSharedBufferHandle(v, o, n), - value, offset, nullability, expectedLength); - - void encodeInterfaceRequestArray( - List<Client> value, - int offset, - int nullability, - int expectedLength) => - _handleArrayEncodeHelper( - (e, v, o, n) => e.encodeInterfaceRequest(v, o, n), - value, offset, nullability, expectedLength); - - void encodeInterfaceArray( - List<Interface> value, - int offset, - int nullability, - int expectedLength) => - _handleArrayEncodeHelper( - (e, v, o, n) => e.encodeInterface(v, o, n), - value, offset, nullability, expectedLength); - - static Uint8List _utf8OfString(String s) => - (new Uint8List.fromList((const Utf8Encoder()).convert(s))); - - void encodeString(String value, int offset, bool nullable) { - if (value == null) { - encodeNullPointer(offset, nullable); - return; - } - int nullability = nullable ? kArrayNullable : kNothingNullable; - encodeUint8Array(_utf8OfString(value), - offset, - nullability, - kUnspecifiedArrayLength); - } - - void appendBytes(Uint8List value) { - _buffer.buffer.buffer.asUint8List().setRange( - _base + DataHeader.kHeaderSize, - _base + DataHeader.kHeaderSize + value.lengthInBytes, - value); - } - - void appendInt8Array(List<int> value) => - appendBytes(new Uint8List.view(new Int8List.fromList(value))); - - void appendUint8Array(List<int> value) => - appendBytes(new Uint8List.fromList(value)); - - void appendInt16Array(List<int> value) => - appendBytes(new Uint8List.view(new Int16List.fromList(value))); - - void appendUint16Array(List<int> value) => - appendBytes(new Uint8List.view(new Uint16List.fromList(value))); - - void appendInt32Array(List<int> value) => - appendBytes(new Uint8List.view(new Int32List.fromList(value))); - - void appendUint32Array(List<int> value) => - appendBytes(new Uint8List.view(new Uint32List.fromList(value))); - - void appendInt64Array(List<int> value) => - appendBytes(new Uint8List.view(new Int64List.fromList(value))); - - void appendUint64Array(List<int> value) => - appendBytes(new Uint8List.view(new Uint64List.fromList(value))); - - void appendFloatArray(List<int> value) => - appendBytes(new Uint8List.view(new Float32List.fromList(value))); - - void appendDoubleArray(List<int> value) => - appendBytes(new Uint8List.view(new Float64List.fromList(value))); - - Encoder encoderForMap(int offset) { - encodePointerToNextUnclaimed(offset); - return getEncoderAtOffset(kMapStructHeader); - } -} - - -class Decoder { - Message _message; - int _base = 0; - - Decoder(this._message, [this._base = 0]); - - Decoder getDecoderAtPosition(int offset) => new Decoder(_message, offset); - - factory Decoder.atOffset(Decoder d, int offset) => - new Decoder(d._message, offset); - - ByteData get _buffer => _message.buffer; - List<core.MojoHandle> get _handles => _message.handles; - - int decodeInt8(int offset) => _buffer.getInt8(_base + offset); - int decodeUint8(int offset) => _buffer.getUint8(_base + offset); - int decodeInt16(int offset) => - _buffer.getInt16(_base + offset, Endianness.LITTLE_ENDIAN); - int decodeUint16(int offset) => - _buffer.getUint16(_base + offset, Endianness.LITTLE_ENDIAN); - int decodeInt32(int offset) => - _buffer.getInt32(_base + offset, Endianness.LITTLE_ENDIAN); - int decodeUint32(int offset) => - _buffer.getUint32(_base + offset, Endianness.LITTLE_ENDIAN); - int decodeInt64(int offset) => - _buffer.getInt64(_base + offset, Endianness.LITTLE_ENDIAN); - int decodeUint64(int offset) => - _buffer.getUint64(_base + offset,Endianness.LITTLE_ENDIAN); - double decodeFloat(int offset) => - _buffer.getFloat32(_base + offset, Endianness.LITTLE_ENDIAN); - double decodeDouble(int offset) => - _buffer.getFloat64(_base + offset, Endianness.LITTLE_ENDIAN); - - bool decodeBool(int offset, int bit) => - (decodeUint8(offset) & (1 << bit)) != 0; - - core.MojoHandle decodeHandle(int offset, bool nullable) { - int index = decodeInt32(offset); - if (index == -1) { - if (!nullable) { - throw 'Trying to decode an invalid handle from a non-nullable type.'; - } - return new core.MojoHandle(core.MojoHandle.INVALID); - } - return _handles[index]; - } - - core.MojoMessagePipeEndpoint decodeMessagePipeHandle( - int offset, bool nullable) => - new core.MojoMessagePipeEndpoint(decodeHandle(offset, nullable)); - - core.MojoDataPipeConsumer decodeConsumerHandle(int offset, bool nullable) => - new core.MojoDataPipeConsumer(decodeHandle(offset, nullable)); - - core.MojoDataPipeProducer decodeProducerHandle(int offset, bool nullable) => - new core.MojoDataPipeProducer(decodeHandle(offset, nullable)); - - core.MojoSharedBuffer decodeSharedBufferHandle(int offset, bool nullable) => - new core.MojoSharedBuffer(decodeHandle(offset, nullable)); - - Client decodeServiceInterface( - int offset, bool nullable, Function clientFactory) { - var endpoint = decodeMessagePipeHandle(offset, nullable); - return endpoint.handle.isValid ? clientFactory(endpoint) : null; - } - - Interface decodeInterfaceRequest( - int offset, bool nullable, Function interfaceFactory) { - var endpoint = decodeMessagePipeHandle(offset, nullable); - return endpoint.handle.isValid ? interfaceFactory(endpoint) : null; - } - - Decoder decodePointer(int offset, bool nullable) { - int basePosition = _base + offset; - int pointerOffset = decodeUint64(offset); - if (pointerOffset == 0) { - if (!nullable) { - throw 'Trying to decode a null pointer for a non-nullable type'; - } - return null; - } - int newPosition = (basePosition + pointerOffset); - return new Decoder.atOffset(this, newPosition); - } - - DataHeader decodeDataHeader() { - int size = decodeUint32(DataHeader.kSizeOffset); - int numFields = decodeUint32(DataHeader.kNumFieldsOffset); - return new DataHeader(size, numFields); - } - - // Decode arrays. - DataHeader decodeDataHeaderForBoolArray(int expectedLength) { - var header = decodeDataHeader(); - if (header.size < DataHeader.kHeaderSize + (header.numFields + 7) ~/ 8) { - throw 'Array header is incorrect'; - } - if ((expectedLength != kUnspecifiedArrayLength) && - (header.numFields != expectedLength)) { - throw 'Incorrect array length'; - } - return header; - } - - List<bool> decodeBoolArray(int offset, int nullability, int expectedLength) { - Decoder d = decodePointer(offset, isArrayNullable(nullability)); - if (d == null) { - return null; - } - var header = d.decodeDataHeaderForBoolArray(expectedLength); - var bytes = new Uint8List.view( - d._buffer.buffer, - d._buffer.offsetInBytes + d._base + DataHeader.kHeaderSize, - (header.numFields + 7) ~/ kAlignment); - var result = new List<bool>(header.numFields); - for (int i = 0; i < bytes.lengthInBytes; ++i) { - for (int j = 0; j < kAlignment; ++j) { - int boolIndex = i * kAlignment + j; - if (boolIndex < result.length) { - result[boolIndex] = (bytes[i] & (1 << j)) != 0; - } - } - } - return result; - } - - DataHeader decodeDataHeaderForArray(int elementSize, int expectedLength) { - var header = decodeDataHeader(); - if (header.size < DataHeader.kHeaderSize + header.numFields * elementSize) { - throw 'Array header is incorrect: $header, elementSize = $elementSize'; - } - if ((expectedLength != kUnspecifiedArrayLength) && - (header.numFields != expectedLength)) { - throw 'Incorrect array length.'; - } - return header; - } - - DataHeader decodeDataHeaderForPointerArray(int expectedLength) => - decodeDataHeaderForArray(kPointerSize, expectedLength); - - List<int> decodeArray(Function arrayViewer, - int elementSize, - int offset, - int nullability, - int expectedLength) { - Decoder d = decodePointer(offset, isArrayNullable(nullability)); - if (d == null) { - return null; - } - var header = d.decodeDataHeaderForArray(elementSize, expectedLength); - return arrayViewer( - d._buffer.buffer, - d._buffer.offsetInBytes + d._base + DataHeader.kHeaderSize, - header.numFields); - } - - List<int> decodeInt8Array( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Int8List.view(b, s, l), - 1, offset, nullability, expectedLength); - - List<int> decodeUint8Array( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Uint8List.view(b, s, l), - 1, offset, nullability, expectedLength); - - List<int> decodeInt16Array( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Int16List.view(b, s, l), - 2, offset, nullability, expectedLength); - - List<int> decodeUint16Array( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Uint16List.view(b, s, l), - 2, offset, nullability, expectedLength); - - List<int> decodeInt32Array( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Int32List.view(b, s, l), - 4, offset, nullability, expectedLength); - - List<int> decodeUint32Array( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Uint32List.view(b, s, l), - 4, offset, nullability, expectedLength); - - List<int> decodeInt64Array( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Int64List.view(b, s, l), - 8, offset, nullability, expectedLength); - - List<int> decodeUint64Array( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Uint64List.view(b, s, l), - 8, offset, nullability, expectedLength); - - List<double> decodeFloatArray( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Float32List.view(b, s, l), - 4, offset, nullability, expectedLength); - - List<double> decodeDoubleArray( - int offset, int nullability, int expectedLength) => - decodeArray((b, s, l) => new Float64List.view(b, s, l), - 8, offset, nullability, expectedLength); - - List _handleArrayDecodeHelper(Function elementDecoder, - int offset, - int nullability, - int expectedLength) { - Decoder d = decodePointer(offset, isArrayNullable(nullability)); - if (d == null) { - return null; - } - var header = d.decodeDataHeaderForArray(4, expectedLength); - var result = new List(header.numFields); - for (int i = 0; i < result.length; ++i) { - result[i] = elementDecoder( - d, - DataHeader.kHeaderSize + kSerializedHandleSize * i, - isElementNullable(nullability)); - } - return result; - - } - - List<core.MojoHandle> decodeHandleArray( - int offset, int nullability, int expectedLength) => - _handleArrayDecodeHelper((d, o, n) => d.decodeHandle(o, n), - offset, nullability, expectedLength); - - List<core.MojoDataPipeConsumer> decodeConsumerHandleArray( - int offset, int nullability, int expectedLength) => - _handleArrayDecodeHelper((d, o, n) => d.decodeConsumerHandle(o, n), - offset, nullability, expectedLength); - - List<core.MojoDataPipeProducer> decodeProducerHandleArray( - int offset, int nullability, int expectedLength) => - _handleArrayDecodeHelper((d, o, n) => d.decodeProducerHandle(o, n), - offset, nullability, expectedLength); - - List<core.MojoMessagePipeEndpoint> decodeMessagePipeHandleArray( - int offset, int nullability, int expectedLength) => - _handleArrayDecodeHelper((d, o, n) => d.decodeMessagePipeHandle(o, n), - offset, nullability, expectedLength); - - List<core.MojoSharedBuffer> decodeSharedBufferHandleArray( - int offset, int nullability, int expectedLength) => - _handleArrayDecodeHelper((d, o, n) => d.decodeSharedBufferHandle(o, n), - offset, nullability, expectedLength); - - List<Interface> decodeInterfaceRequestArray( - int offset, - int nullability, - int expectedLength, - Function interfaceFactory) => - _handleArrayDecodeHelper( - (d, o, n) => d.decodeInterfaceRequest(o, n, interfaceFactory), - offset, nullability, expectedLength); - - List<Client> decodeServiceInterfaceArray( - int offset, - int nullability, - int expectedLength, - Function clientFactory) => - _handleArrayDecodeHelper( - (d, o, n) => d.decodeServiceInterface(o, n, clientFactory), - offset, nullability, expectedLength); - - static String _stringOfUtf8(Uint8List bytes) => - (const Utf8Decoder()).convert(bytes.toList()); - - String decodeString(int offset, bool nullable) { - int nullability = nullable ? kArrayNullable : 0; - var bytes = decodeUint8Array(offset, nullability, kUnspecifiedArrayLength); - if (bytes == null) { - return null; - } - return _stringOfUtf8(bytes); - } -} diff --git a/mojo/public/dart/src/data_pipe.dart b/mojo/public/dart/src/data_pipe.dart deleted file mode 100644 index 7f3b3eb..0000000 --- a/mojo/public/dart/src/data_pipe.dart +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright 2014 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. - -part of core; - - -class _MojoDataPipeNatives { - static List MojoCreateDataPipe( - int elementBytes, int capacityBytes, int flags) - native "MojoDataPipe_Create"; - - static List MojoWriteData(int handle, ByteData data, int numBytes, int flags) - native "MojoDataPipe_WriteData"; - - static List MojoBeginWriteData(int handle, int bufferBytes, int flags) - native "MojoDataPipe_BeginWriteData"; - - static int MojoEndWriteData(int handle, int bytesWritten) - native "MojoDataPipe_EndWriteData"; - - static List MojoReadData(int handle, ByteData data, int numBytes, int flags) - native "MojoDataPipe_ReadData"; - - static List MojoBeginReadData(int handle, int bufferBytes, int flags) - native "MojoDataPipe_BeginReadData"; - - static int MojoEndReadData(int handle, int bytesRead) - native "MojoDataPipe_EndReadData"; -} - - -class MojoDataPipeProducer { - static const int FLAG_NONE = 0; - static const int FLAG_ALL_OR_NONE = 1 << 0; - - MojoHandle handle; - MojoResult status; - final int elementBytes; - - MojoDataPipeProducer( - this.handle, [this.status = MojoResult.OK, this.elementBytes = 1]); - - int write(ByteData data, [int numBytes = -1, int flags = 0]) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - - int data_numBytes = (numBytes == -1) ? data.lengthInBytes : numBytes; - List result = _MojoDataPipeNatives.MojoWriteData( - handle.h, data, data_numBytes, flags); - if (result == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - - assert((result is List) && (result.length == 2)); - status = new MojoResult(result[0]); - return result[1]; - } - - ByteData beginWrite(int bufferBytes, [int flags = 0]) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return null; - } - - List result = _MojoDataPipeNatives.MojoBeginWriteData( - handle.h, bufferBytes, flags); - if (result == null) { - status = MojoResult.INVALID_ARGUMENT; - return null; - } - - assert((result is List) && (result.length == 2)); - status = new MojoResult(result[0]); - return result[1]; - } - - MojoResult endWrite(int bytesWritten) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - int result = _MojoDataPipeNatives.MojoEndWriteData(handle.h, bytesWritten); - status = new MojoResult(result); - return status; - } -} - - -class MojoDataPipeConsumer { - static const int FLAG_NONE = 0; - static const int FLAG_ALL_OR_NONE = 1 << 0; - static const int FLAG_MAY_DISCARD = 1 << 1; - static const int FLAG_QUERY = 1 << 2; - static const int FLAG_PEEK = 1 << 3; - - MojoHandle handle; - MojoResult status; - final int elementBytes; - - MojoDataPipeConsumer( - this.handle, [this.status = MojoResult.OK, this.elementBytes = 1]); - - int read(ByteData data, [int numBytes = -1, int flags = 0]) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - - int data_numBytes = (numBytes == -1) ? data.lengthInBytes : numBytes; - List result = _MojoDataPipeNatives.MojoReadData( - handle.h, data, data_numBytes, flags); - if (result == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - assert((result is List) && (result.length == 2)); - status = new MojoResult(result[0]); - return result[1]; - } - - ByteData beginRead([int bufferBytes = 0, int flags = 0]) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return null; - } - - List result = _MojoDataPipeNatives.MojoBeginReadData( - handle.h, bufferBytes, flags); - if (result == null) { - status = MojoResult.INVALID_ARGUMENT; - return null; - } - - assert((result is List) && (result.length == 2)); - status = new MojoResult(result[0]); - return result[1]; - } - - MojoResult endRead(int bytesRead) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - int result = _MojoDataPipeNatives.MojoEndReadData(handle.h, bytesRead); - status = new MojoResult(result); - return status; - } - - int query() => read(null, 0, FLAG_QUERY); -} - - -class MojoDataPipe { - static const int FLAG_NONE = 0; - static const int FLAG_MAY_DISCARD = 1 << 0; - static const int DEFAULT_ELEMENT_SIZE = 1; - static const int DEFAULT_CAPACITY = 0; - - MojoDataPipeProducer producer; - MojoDataPipeConsumer consumer; - MojoResult status; - - MojoDataPipe._internal() { - producer = null; - consumer = null; - status = MojoResult.OK; - } - - factory MojoDataPipe([int elementBytes = DEFAULT_ELEMENT_SIZE, - int capacityBytes = DEFAULT_CAPACITY, - int flags = FLAG_NONE]) { - List result = _MojoDataPipeNatives.MojoCreateDataPipe( - elementBytes, capacityBytes, flags); - if (result == null) { - return null; - } - assert((result is List) && (result.length == 3)); - MojoHandle producerHandle = new MojoHandle(result[1]); - MojoHandle consumerHandle = new MojoHandle(result[2]); - MojoDataPipe pipe = new MojoDataPipe._internal(); - pipe.producer = new MojoDataPipeProducer( - producerHandle, new MojoResult(result[0]), elementBytes); - pipe.consumer = new MojoDataPipeConsumer( - consumerHandle, new MojoResult(result[0]), elementBytes); - pipe.status = new MojoResult(result[0]); - return pipe; - } -} diff --git a/mojo/public/dart/src/event_stream.dart b/mojo/public/dart/src/event_stream.dart deleted file mode 100644 index 797f0e6..0000000 --- a/mojo/public/dart/src/event_stream.dart +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright 2014 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. - -part of core; - -class MojoEventStream extends Stream<int> { - // The underlying Mojo handle. - MojoHandle _handle; - - // Providing our own stream controller allows us to take custom actions when - // listeners pause/resume/etc. their StreamSubscription. - StreamController _controller; - - // The send port that we give to the handle watcher to notify us of handle - // events. - SendPort _sendPort; - - // The receive port on which we listen and receive events from the handle - // watcher. - ReceivePort _receivePort; - - // The signals on this handle that we're interested in. - MojoHandleSignals _signals; - - // Whether listen has been called. - bool _isListening; - - MojoEventStream(MojoHandle handle, - [MojoHandleSignals signals = MojoHandleSignals.READABLE]) : - _handle = handle, - _signals = signals, - _isListening = false { - MojoResult result = MojoHandle.register(this); - if (!result.isOk) { - throw "Failed to register the MojoHandle: $result."; - } - } - - void close() { - if (_handle != null) { - MojoHandleWatcher.close(_handle); - _handle = null; - } - if (_receivePort != null) { - _receivePort.close(); - _receivePort = null; - } - } - - StreamSubscription<List<int>> listen( - void onData(List event), - {Function onError, void onDone(), bool cancelOnError}) { - if (_isListening) { - throw "Listen has already been called: $_handle."; - } - _receivePort = new ReceivePort(); - _sendPort = _receivePort.sendPort; - _controller = new StreamController(sync: true, - onListen: _onSubscriptionStateChange, - onCancel: _onSubscriptionStateChange, - onPause: _onPauseStateChange, - onResume: _onPauseStateChange); - _controller.addStream(_receivePort); - - if (_signals != MojoHandleSignals.NONE) { - var res = MojoHandleWatcher.add(_handle, _sendPort, _signals.value); - if (!res.isOk) { - throw "MojoHandleWatcher add failed: $res"; - } - } - - _isListening = true; - return _controller.stream.listen( - onData, - onError: onError, - onDone: onDone, - cancelOnError: cancelOnError); - } - - void enableSignals(MojoHandleSignals signals) { - _signals = signals; - if (_isListening) { - var res = MojoHandleWatcher.add(_handle, _sendPort, signals.value); - if (!res.isOk) { - throw "MojoHandleWatcher add failed: $res"; - } - } - } - - void enableReadEvents() => enableSignals(MojoHandleSignals.READABLE); - void enableWriteEvents() => enableSignals(MojoHandleSignals.WRITABLE); - void enableAllEvents() => enableSignals(MojoHandleSignals.READWRITE); - - void _onSubscriptionStateChange() { - if (!_controller.hasListener) { - close(); - } - } - - void _onPauseStateChange() { - if (_controller.isPaused) { - var res = MojoHandleWatcher.remove(_handle); - if (!res.isOk) { - throw "MojoHandleWatcher add failed: $res"; - } - } else { - var res = MojoHandleWatcher.add(_handle, _sendPort, _signals.value); - if (!res.isOk) { - throw "MojoHandleWatcher add failed: $res"; - } - } - } - - bool get readyRead => _handle.readyRead; - bool get readyWrite => _handle.readyWrite; - - String toString() => "$_handle"; -} - - -class MojoEventStreamListener { - MojoMessagePipeEndpoint _endpoint; - MojoEventStream _eventStream; - bool _isOpen = false; - bool _isInHandler = false; - - MojoEventStreamListener(MojoMessagePipeEndpoint endpoint) : - _endpoint = endpoint, - _eventStream = new MojoEventStream(endpoint.handle), - _isOpen = false; - - MojoEventStreamListener.fromHandle(MojoHandle handle) { - _endpoint = new MojoMessagePipeEndpoint(handle); - _eventStream = new MojoEventStream(handle); - _isOpen = false; - } - - MojoEventStreamListener.unbound() : - _endpoint = null, - _eventStream = null, - _isOpen = false; - - void bind(MojoMessagePipeEndpoint endpoint) { - assert(!isBound); - _endpoint = endpoint; - _eventStream = new MojoEventStream(endpoint.handle); - _isOpen = false; - } - - void bindFromHandle(MojoHandle handle) { - assert(!isBound); - _endpoint = new MojoMessagePipeEndpoint(handle); - _eventStream = new MojoEventStream(handle); - _isOpen = false; - } - - StreamSubscription<int> listen() { - _isOpen = true; - return _eventStream.listen((List<int> event) { - var signalsWatched = new MojoHandleSignals(event[0]); - var signalsReceived = new MojoHandleSignals(event[1]); - if (signalsReceived.isPeerClosed) { - handlePeerClosed(); - // The peer being closed obviates any other signal we might - // have received since we won't be able to read or write the handle. - // Thus, we just return before invoking other handlers. - return; - } - _isInHandler = true; - if (signalsReceived.isReadable) { - assert(_eventStream.readyRead); - handleRead(); - } - if (signalsReceived.isWritable) { - assert(_eventStream.readyWrite); - handleWrite(); - } - _eventStream.enableSignals(enableSignals( - signalsWatched, signalsReceived)); - _isInHandler = false; - }); - } - - void close() { - if (_isOpen) { - _eventStream.close(); - _isOpen = false; - _eventStream = null; - _endpoint = null; - } - } - - void handleRead() {} - void handleWrite() {} - void handlePeerClosed() { - close(); - } - - MojoHandleSignals enableSignals(MojoHandleSignals watched, - MojoHandleSignals received) => watched; - - MojoMessagePipeEndpoint get endpoint => _endpoint; - bool get isOpen => _isOpen; - bool get isInHandler => _isInHandler; - bool get isBound => _endpoint != null; -} diff --git a/mojo/public/dart/src/handle.dart b/mojo/public/dart/src/handle.dart deleted file mode 100644 index a819804..0000000 --- a/mojo/public/dart/src/handle.dart +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2014 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. - -part of core; - -class _MojoHandleNatives { - static int register(MojoEventStream eventStream) native "MojoHandle_Register"; - static int close(int handle) native "MojoHandle_Close"; - static List wait(int handle, int signals, int deadline) - native "MojoHandle_Wait"; - static List waitMany( - List<int> handles, List<int> signals, int deadline) - native "MojoHandle_WaitMany"; -} - - -class MojoHandle { - static const int INVALID = 0; - static const int DEADLINE_INDEFINITE = -1; - - int h; - - MojoHandle(this.h); - - MojoResult close() { - int result = _MojoHandleNatives.close(h); - h = INVALID; - return new MojoResult(result); - } - - MojoWaitResult wait(int signals, int deadline) { - List result = _MojoHandleNatives.wait(h, signals, deadline); - return new MojoWaitResult(new MojoResult(result[0]), result[1]); - } - - bool _ready(MojoHandleSignals signal) { - MojoWaitResult mwr = wait(signal.value, 0); - switch (mwr.result) { - case MojoResult.OK: - return true; - case MojoResult.DEADLINE_EXCEEDED: - case MojoResult.CANCELLED: - case MojoResult.INVALID_ARGUMENT: - case MojoResult.FAILED_PRECONDITION: - return false; - default: - // Should be unreachable. - throw "Unexpected result $res for wait on $h"; - } - } - - bool get readyRead => _ready(MojoHandleSignals.READABLE); - bool get readyWrite => _ready(MojoHandleSignals.WRITABLE); - - static MojoWaitManyResult waitMany( - List<int> handles, List<int> signals, int deadline) { - List result = _MojoHandleNatives.waitMany(handles, signals, deadline); - return new MojoWaitManyResult( - new MojoResult(result[0]), result[1], result[2]); - } - - static MojoResult register(MojoEventStream eventStream) { - return new MojoResult(_MojoHandleNatives.register(eventStream)); - } - - bool get isValid => (h != INVALID); - - String toString() => "$h"; - - bool operator ==(MojoHandle other) { - return h == other.h; - } -} diff --git a/mojo/public/dart/src/handle_watcher.dart b/mojo/public/dart/src/handle_watcher.dart deleted file mode 100644 index 3d14f6c..0000000 --- a/mojo/public/dart/src/handle_watcher.dart +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2014 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. - -part of core; - -class _MojoHandleWatcherNatives { - static int sendControlData( - int controlHandle, int mojoHandle, SendPort port, int data) - native "MojoHandleWatcher_SendControlData"; - static List recvControlData(int controlHandle) - native "MojoHandleWatcher_RecvControlData"; - static int setControlHandle(int controlHandle) - native "MojoHandleWatcher_SetControlHandle"; - static int getControlHandle() - native "MojoHandleWatcher_GetControlHandle"; -} - -// The MojoHandleWatcher sends a stream of events to application isolates that -// register Mojo handles with it. Application isolates make the following calls: -// -// Start() - Starts up the MojoHandleWatcher isolate. Should be called only once -// per VM process. -// -// Stop() - Causes the MojoHandleWatcher isolate to exit. -// -// add(handle, port, signals) - Instructs the MojoHandleWatcher isolate to add -// 'handle' to the set of handles it watches, and to notify the calling -// isolate only for the events specified by 'signals' using the send port -// 'port' -// -// remove(handle) - Instructs the MojoHandleWatcher isolate to remove 'handle' -// from the set of handles it watches. This allows the application isolate -// to, e.g., pause the stream of events. -// -// close(handle) - Notifies the HandleWatcherIsolate that a handle it is -// watching should be removed from its set and closed. -class MojoHandleWatcher { - // Control commands. - static const int ADD = 0; - static const int REMOVE = 1; - static const int CLOSE = 2; - static const int TIMER = 3; - static const int SHUTDOWN = 4; - - static int _encodeCommand(int cmd, [int signals = 0]) => - (cmd << 2) | (signals & MojoHandleSignals.kReadWrite); - static int _decodeCommand(int cmd) => cmd >> 2; - - // The Mojo handle over which control messages are sent. - int _controlHandle; - - // Whether the handle watcher should shut down. - bool _shutdown; - - // The list of handles being watched. - List<int> _handles; - int _handleCount; - - // A port for each handle on which to send events back to the isolate that - // owns the handle. - List<SendPort> _ports; - - // The signals that we care about for each handle. - List<int> _signals; - - // A mapping from Mojo handles to their indices in _handles. - Map<int, int> _handleIndices; - - // Since we are not storing wrapped handles, a dummy handle for when we need - // a MojoHandle. - MojoHandle _tempHandle; - - // Priority queue of timers registered with the watcher. - TimerQueue _timerQueue; - - MojoHandleWatcher(this._controlHandle) : - _shutdown = false, - _handles = new List<int>(), - _ports = new List<SendPort>(), - _signals = new List<int>(), - _handleIndices = new Map<int, int>(), - _handleCount = 1, - _tempHandle = new MojoHandle(MojoHandle.INVALID), - _timerQueue = new TimerQueue() { - // Setup control handle. - _handles.add(_controlHandle); - _ports.add(null); // There is no port for the control handle. - _signals.add(MojoHandleSignals.kReadable); - _handleIndices[_controlHandle] = 0; - } - - static void _handleWatcherIsolate(int consumerHandle) { - MojoHandleWatcher watcher = new MojoHandleWatcher(consumerHandle); - while (!watcher._shutdown) { - int deadline = watcher._processTimerDeadlines(); - MojoWaitManyResult mwmr = MojoHandle.waitMany( - watcher._handles, watcher._signals, deadline); - if (mwmr.result.isOk && mwmr.index == 0) { - watcher._handleControlMessage(); - } else if (mwmr.result.isOk && (mwmr.index > 0)) { - int handle = watcher._handles[mwmr.index]; - // Route event. - watcher._routeEvent(mwmr.index); - // Remove the handle from the list. - watcher._removeHandle(handle); - } else if (!mwmr.result.isDeadlineExceeded) { - // Some handle was closed, but not by us. - // Find it and close it on our side. - watcher._pruneClosedHandles(mwmr.states); - } - } - } - - void _routeEvent(int idx) { - int client_handle = _handles[idx]; - var signals = new MojoHandleSignals(_signals[idx]); - SendPort port = _ports[idx]; - - _tempHandle.h = client_handle; - bool readyWrite = signals.isWritable && _tempHandle.readyWrite; - bool readyRead = signals.isReadable && _tempHandle.readyRead; - _tempHandle.h = MojoHandle.INVALID; - - var event = MojoHandleSignals.NONE; - event += readyRead ? MojoHandleSignals.READABLE : MojoHandleSignals.NONE; - event += readyWrite ? MojoHandleSignals.WRITABLE : MojoHandleSignals.NONE; - port.send([signals.value, event.value]); - } - - void _handleControlMessage() { - List result = _MojoHandleWatcherNatives.recvControlData(_controlHandle); - // result[0] = mojo handle if any, or a timer deadline in milliseconds. - // result[1] = SendPort if any. - // result[2] = command << 2 | WRITABLE | READABLE - - var signals = new MojoHandleSignals( - result[2] & MojoHandleSignals.kReadWrite); - int command = _decodeCommand(result[2]); - switch (command) { - case ADD: - _addHandle(result[0], result[1], signals); - break; - case REMOVE: - _removeHandle(result[0]); - break; - case CLOSE: - _close(result[0]); - break; - case TIMER: - _timer(result[1], result[0]); - break; - case SHUTDOWN: - _shutdownHandleWatcher(result[1]); - break; - default: - throw "Invalid Command: $command"; - break; - } - } - - void _addHandle(int mojoHandle, SendPort port, MojoHandleSignals signals) { - int idx = _handleIndices[mojoHandle]; - if (idx == null) { - _handles.add(mojoHandle); - _ports.add(port); - _signals.add(signals.value); - _handleIndices[mojoHandle] = _handleCount; - _handleCount++; - } else { - assert(_ports[idx] == port); - assert(_handles[idx] == mojoHandle); - _signals[idx] |= signals.value; - } - } - - void _removeHandle(int mojoHandle) { - int idx = _handleIndices[mojoHandle]; - if (idx == null) { - throw "Remove on a non-existent handle: idx = $idx."; - } - if (idx == 0) { - throw "The control handle (idx = 0) cannot be removed."; - } - // We don't use List.removeAt so that we know how to fix-up _handleIndices. - if (idx == _handleCount - 1) { - int handle = _handles[idx]; - _handleIndices[handle] = null; - _handles.removeLast(); - _signals.removeLast(); - _ports.removeLast(); - _handleCount--; - } else { - int last = _handleCount - 1; - _handleIndices[_handles[idx]] = null; - _handles[idx] = _handles[last]; - _signals[idx] = _signals[last]; - _ports[idx] = _ports[last]; - _handles.removeLast(); - _signals.removeLast(); - _ports.removeLast(); - _handleIndices[_handles[idx]] = idx; - _handleCount--; - } - } - - void _close(int mojoHandle, {bool pruning : false}) { - int idx = _handleIndices[mojoHandle]; - if (idx == null) { - // A client may request to close a handle that has already been closed on - // the other side and pruned, but before receiving notification from the - // handle watcher. - return; - } - if (idx == 0) { - throw "The control handle (idx = 0) cannot be closed."; - } - _tempHandle.h = _handles[idx]; - _tempHandle.close(); - _tempHandle.h = MojoHandle.INVALID; - if (pruning) { - // If this handle is being pruned, notify the application isolate - // by sending MojoHandleSignals.PEER_CLOSED. - _ports[idx].send([_signals[idx], MojoHandleSignals.kPeerClosed]); - } - _removeHandle(mojoHandle); - } - - // Returns the next timer deadline in units of microseconds from 'now'. - int _processTimerDeadlines() { - int now = (new DateTime.now()).millisecondsSinceEpoch; - while (_timerQueue.hasTimer && (now >= _timerQueue.currentTimeout)) { - _timerQueue.currentPort.send(null); - _timerQueue.removeCurrent(); - now = (new DateTime.now()).millisecondsSinceEpoch; - } - return _timerQueue.hasTimer ? (_timerQueue.currentTimeout - now) * 1000 - : MojoHandle.DEADLINE_INDEFINITE; - } - - void _timer(SendPort port, int deadline) { - _timerQueue.updateTimer(port, deadline); - } - - void _pruneClosedHandles(List<MojoHandleSignalsState> states) { - List<int> closed = new List(); - for (var i = 0; i < _handles.length; i++) { - if (states != null) { - var signals = new MojoHandleSignals(states[i].satisfied_signals); - if (signals.isPeerClosed) { - closed.add(_handles[i]); - } - } else { - _tempHandle.h = _handles[i]; - MojoWaitResult mwr = _tempHandle.wait(MojoHandleSignals.kReadWrite, 0); - if ((!mwr.result.isOk) && (!mwr.result.isDeadlineExceeded)) { - closed.add(_handles[i]); - } - _tempHandle.h = MojoHandle.INVALID; - } - } - for (var h in closed) { - _close(h, pruning: true); - } - // '_close' updated the '_handles' array, so at this point the '_handles' - // array and the caller's 'states' array are mismatched. - } - - void _shutdownHandleWatcher(SendPort shutdownSendPort) { - _shutdown = true; - _tempHandle.h = _controlHandle; - _tempHandle.close(); - _tempHandle.h = MojoHandle.INVALID; - shutdownSendPort.send(null); - } - - static MojoResult _sendControlData(MojoHandle mojoHandle, - SendPort port, - int data) { - int controlHandle = _MojoHandleWatcherNatives.getControlHandle(); - if (controlHandle == MojoHandle.INVALID) { - return MojoResult.FAILED_PRECONDITION; - } - - int rawHandle = MojoHandle.INVALID; - if (mojoHandle != null) { - rawHandle = mojoHandle.h; - } - var result = _MojoHandleWatcherNatives.sendControlData( - controlHandle, rawHandle, port, data); - return new MojoResult(result); - } - - static Future<Isolate> Start() { - // Make a control message pipe, - MojoMessagePipe pipe = new MojoMessagePipe(); - int consumerHandle = pipe.endpoints[0].handle.h; - int producerHandle = pipe.endpoints[1].handle.h; - - // Call setControlHandle with the other end. - assert(producerHandle != MojoHandle.INVALID); - _MojoHandleWatcherNatives.setControlHandle(producerHandle); - - // Spawn the handle watcher isolate with the MojoHandleWatcher, - return Isolate.spawn(_handleWatcherIsolate, consumerHandle); - } - - static void Stop() { - // Create a port for notification that the handle watcher has shutdown. - var shutdownReceivePort = new ReceivePort(); - var shutdownSendPort = shutdownReceivePort.sendPort; - - // Send the shutdown command. - _sendControlData(null, shutdownSendPort, _encodeCommand(SHUTDOWN)); - - // Close the control handle. - int controlHandle = _MojoHandleWatcherNatives.getControlHandle(); - var handle = new MojoHandle(controlHandle); - handle.close(); - - // Invalidate the control handle. - _MojoHandleWatcherNatives.setControlHandle(MojoHandle.INVALID); - - // Wait for the handle watcher isolate to exit. - shutdownReceivePort.first.then((_) { - shutdownReceivePort.close(); - }); - } - - static MojoResult close(MojoHandle mojoHandle) { - return _sendControlData(mojoHandle, null, _encodeCommand(CLOSE)); - } - - static MojoResult add(MojoHandle mojoHandle, SendPort port, int signals) { - return _sendControlData(mojoHandle, port, _encodeCommand(ADD, signals)); - } - - static MojoResult remove(MojoHandle mojoHandle) { - return _sendControlData(mojoHandle, null, _encodeCommand(REMOVE)); - } - - static MojoResult timer(SendPort port, int deadline) { - // The deadline will be unwrapped before sending to the handle watcher. - return _sendControlData( - new MojoHandle(deadline), port, _encodeCommand(TIMER)); - } -} diff --git a/mojo/public/dart/src/interface.dart b/mojo/public/dart/src/interface.dart deleted file mode 100644 index 0e73214..0000000 --- a/mojo/public/dart/src/interface.dart +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2014 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. - -part of bindings; - -abstract class Interface extends core.MojoEventStreamListener { - int _outstandingResponseFutures = 0; - bool _isClosing = false; - - Interface(core.MojoMessagePipeEndpoint endpoint) : super(endpoint); - - Interface.fromHandle(core.MojoHandle handle) : super.fromHandle(handle); - - Interface.unbound() : super.unbound(); - - Future<Message> handleMessage(ServiceMessage message); - - void handleRead() { - // Query how many bytes are available. - var result = endpoint.query(); - assert(result.status.isOk || result.status.isResourceExhausted); - - // Read the data and view as a message. - var bytes = new ByteData(result.bytesRead); - var handles = new List<core.MojoHandle>(result.handlesRead); - result = endpoint.read(bytes, result.bytesRead, handles); - assert(result.status.isOk || result.status.isResourceExhausted); - - // Prepare the response. - var message = new ServiceMessage.fromMessage(new Message(bytes, handles)); - var responseFuture = _isClosing ? null : handleMessage(message); - - // If there's a response, send it. - if (responseFuture != null) { - _outstandingResponseFutures++; - responseFuture.then((response) { - _outstandingResponseFutures--; - if (isOpen) { - endpoint.write(response.buffer, - response.buffer.lengthInBytes, - response.handles); - if (!endpoint.status.isOk) { - throw "message pipe write failed: ${endpoint.status}"; - } - if (_isClosing && (_outstandingResponseFutures == 0)) { - // This was the final response future for which we needed to send - // a response. It is safe to close. - super.close(); - _isClosing = false; - } - } - }); - } else if (_isClosing && (_outstandingResponseFutures == 0)) { - // We are closing, there is no response to send for this message, and - // there are no outstanding response futures. Do the close now. - super.close(); - _isClosing = false; - } - } - - void handleWrite() { - throw 'Unexpected write signal in client.'; - } - - void close() { - if (!isOpen) return; - if (isInHandler || (_outstandingResponseFutures > 0)) { - // Either close() is being called from within handleRead() or - // handleWrite(), or close() is being called while there are outstanding - // response futures. Defer the actual close until all response futures - // have been resolved. - _isClosing = true; - } else { - super.close(); - } - } - - Message buildResponse(Struct response, int name) { - var header = new MessageHeader(name); - return response.serializeWithHeader(header); - } - - Message buildResponseWithId(Struct response, int name, int id, int flags) { - var header = new MessageHeader.withRequestId(name, flags, id); - return response.serializeWithHeader(header); - } - - void sendMessage(Struct message, int name) { - var header = new MessageHeader(name); - var serviceMessage = message.serializeWithHeader(header); - endpoint.write(serviceMessage.buffer, - serviceMessage.buffer.lengthInBytes, - serviceMessage.handles); - if (!endpoint.status.isOk) { - throw "message pipe write failed: ${endpoint.status}"; - } - } - - Future sendMessageWithRequestId(Struct response, int name, int id) { - throw "The client interface should not expect a response"; - } -} diff --git a/mojo/public/dart/src/message.dart b/mojo/public/dart/src/message.dart deleted file mode 100644 index 2cdda8a..0000000 --- a/mojo/public/dart/src/message.dart +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2014 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. - -part of bindings; - -class MessageHeader { - static const int kSimpleMessageSize = 16; - static const int kSimpleMessageNumFields = 2; - static const int kMessageWithRequestIdSize = 24; - static const int kMessageWithRequestIdNumFields = 3; - static const int kMessageTypeOffset = DataHeader.kHeaderSize; - static const int kMessageFlagsOffset = kMessageTypeOffset + 4; - static const int kMessageRequestIdOffset = kMessageFlagsOffset + 4; - static const int kMessageExpectsResponse = 1 << 0; - static const int kMessageIsResponse = 1 << 1; - - DataHeader _header; - int type; - int flags; - int requestId; - - static bool mustHaveRequestId(int flags) => - (flags & (kMessageExpectsResponse | kMessageIsResponse)) != 0; - - MessageHeader(this.type) : - _header = new DataHeader(kSimpleMessageSize, kSimpleMessageNumFields), - flags = 0, - requestId = 0; - - MessageHeader.withRequestId(this.type, this.flags, this.requestId) : - _header = new DataHeader( - kMessageWithRequestIdSize, kMessageWithRequestIdNumFields); - - MessageHeader.fromMessage(Message message) { - var decoder = new Decoder(message); - _header = decoder.decodeDataHeader(); - type = decoder.decodeUint32(kMessageTypeOffset); - flags = decoder.decodeUint32(kMessageFlagsOffset); - if (mustHaveRequestId(flags)) { - if (_header.size < kMessageWithRequestIdSize) { - throw 'Incorrect message size. Got: ${_header.size} ' + - 'wanted $kMessageWithRequestIdSize'; - } - requestId = decoder.decodeUint64(kMessageRequestIdOffset); - } else { - requestId = 0; - } - } - - int get size => _header.size; - bool get hasRequestId => mustHaveRequestId(flags); - - void encode(Encoder encoder) { - encoder.encodeDataHeader(_header); - encoder.encodeUint32(type, kMessageTypeOffset); - encoder.encodeUint32(flags, kMessageFlagsOffset); - if (hasRequestId) { - encoder.encodeUint64(requestId, kMessageRequestIdOffset); - } - } - - ServiceMessage get serviceMessage => new ServiceMessage(this); - - String toString() => "MessageHeader($_header, $type, $flags, $requestId)"; -} - - -class Message { - final ByteData buffer; - final List<core.MojoHandle> handles; - Message(this.buffer, this.handles); - String toString() => - "Message(numBytes=${buffer.lengthInBytes}, numHandles=${handles.length})"; -} - - -class ServiceMessage extends Message { - final MessageHeader header; - Message _payload; - - ServiceMessage(Message message, this.header) - : super(message.buffer, message.handles); - - ServiceMessage.fromMessage(Message message) - : this(message, new MessageHeader.fromMessage(message)); - - Message get payload { - if (_payload == null) { - var truncatedBuffer = new ByteData.view(buffer.buffer, header.size); - _payload = new Message(truncatedBuffer, handles); - } - return _payload; - } - - String toString() => "ServiceMessage($header, $_payload)"; -} diff --git a/mojo/public/dart/src/message_pipe.dart b/mojo/public/dart/src/message_pipe.dart deleted file mode 100644 index 325be42..0000000 --- a/mojo/public/dart/src/message_pipe.dart +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2014 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. - -part of core; - - -class _MojoMessagePipeNatives { - static List MojoCreateMessagePipe(int flags) - native "MojoMessagePipe_Create"; - - static int MojoWriteMessage( - int handle, ByteData data, int numBytes, List<int> handles, int flags) - native "MojoMessagePipe_Write"; - - static List MojoReadMessage( - int handle, ByteData data, int numBytes, List<int> handles, int flags) - native "MojoMessagePipe_Read"; -} - - -class MojoMessagePipeReadResult { - final MojoResult status; - final int bytesRead; - final int handlesRead; - - MojoMessagePipeReadResult(this.status, this.bytesRead, this.handlesRead); - MojoMessagePipeReadResult.fromList(List<int> resultList) - : this(new MojoResult(resultList[0]), resultList[1], resultList[2]); -} - - -class MojoMessagePipeEndpoint { - static const int WRITE_FLAG_NONE = 0; - static const int READ_FLAG_NONE = 0; - static const int READ_FLAG_MAY_DISCARD = 0; - - MojoHandle handle; - MojoResult status; - - MojoMessagePipeEndpoint(this.handle); - - MojoResult write(ByteData data, - [int numBytes = -1, - List<MojoHandle> handles = null, - int flags = 0]) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - - // If numBytes has the default value, use the full length of the data. - int dataNumBytes = (numBytes == -1) ? data.lengthInBytes : numBytes; - if (dataNumBytes > data.lengthInBytes) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - - // handles may be null, otherwise convert to ints. - List<int> mojoHandles = - (handles != null) ? handles.map((h) => h.h).toList() : null; - - // Do the call. - int result = _MojoMessagePipeNatives.MojoWriteMessage( - handle.h, data, dataNumBytes, mojoHandles, flags); - - status = new MojoResult(result); - return status; - } - - - MojoMessagePipeReadResult read(ByteData data, - [int numBytes = -1, - List<MojoHandle> handles = null, - int flags = 0]) { - if (handle == null) { - status = MojoResult.INVALID_ARGUMENT; - return null; - } - - // If numBytes has the default value, use the full length of the data. - int dataNumBytes; - if (data == null) { - dataNumBytes = 0; - } else { - dataNumBytes = (numBytes == -1) ? data.lengthInBytes : numBytes; - if (dataNumBytes > data.lengthInBytes) { - status = MojoResult.INVALID_ARGUMENT; - return status; - } - } - - // handles may be null, otherwise make an int list for the handles. - List<int> mojoHandles; - if (handles == null) { - mojoHandles = null; - } else { - mojoHandles = new List<int>(handles.length); - } - - // Do the call. - List result = _MojoMessagePipeNatives.MojoReadMessage( - handle.h, data, dataNumBytes, mojoHandles, flags); - - if (result == null) { - status = MojoResult.INVALID_ARGUMENT; - return null; - } - - assert((result is List) && (result.length == 3)); - var readResult = new MojoMessagePipeReadResult.fromList(result); - - // Copy out the handles that were read. - if (handles != null) { - for (var i = 0; i < readResult.handlesRead; i++) { - handles[i] = new MojoHandle(mojoHandles[i]); - } - } - - status = readResult.status; - return readResult; - } - - MojoMessagePipeReadResult query() => read(null); -} - - -class MojoMessagePipe { - static const int FLAG_NONE = 0; - - List<MojoMessagePipeEndpoint> endpoints; - MojoResult status; - - MojoMessagePipe._() { - endpoints = null; - status = MojoResult.OK; - } - - factory MojoMessagePipe([int flags = FLAG_NONE]) { - List result = _MojoMessagePipeNatives.MojoCreateMessagePipe(flags); - if (result == null) { - return null; - } - assert((result is List) && (result.length == 3)); - - MojoHandle end1 = new MojoHandle(result[1]); - MojoHandle end2 = new MojoHandle(result[2]); - MojoMessagePipe pipe = new MojoMessagePipe._(); - pipe.endpoints = new List(2); - pipe.endpoints[0] = new MojoMessagePipeEndpoint(end1); - pipe.endpoints[1] = new MojoMessagePipeEndpoint(end2); - pipe.status = new MojoResult(result[0]); - return pipe; - } -} diff --git a/mojo/public/dart/src/struct.dart b/mojo/public/dart/src/struct.dart deleted file mode 100644 index 0111732..0000000 --- a/mojo/public/dart/src/struct.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2014 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. - -part of bindings; - -class DataHeader { - static const int kHeaderSize = 8; - static const int kSizeOffset = 0; - static const int kNumFieldsOffset = 4; - final int size; - final int numFields; - - const DataHeader(this.size, this.numFields); - - String toString() => "DataHeader($size, $numFields)"; -} - -abstract class Struct { - final int encodedSize; - - Struct(this.encodedSize); - - void encode(Encoder encoder); - - Message serialize() { - var encoder = new Encoder(encodedSize); - encode(encoder); - return encoder.message; - } - - ServiceMessage serializeWithHeader(MessageHeader header) { - var encoder = new Encoder(encodedSize + header.size); - header.encode(encoder); - encode(encoder); - return new ServiceMessage(encoder.message, header); - } -} diff --git a/mojo/public/dart/src/timer_impl.dart b/mojo/public/dart/src/timer_impl.dart deleted file mode 100644 index 61fee6d..0000000 --- a/mojo/public/dart/src/timer_impl.dart +++ /dev/null @@ -1,333 +0,0 @@ -// Copyright 2014 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. - -// This code is adapted from the Timer implementation in the standalone Dart VM -// for use in the Mojo embedder. - -part of core; - -// Timer heap implemented as a array-based binary heap[0]. -// This allows for O(1) `first`, O(log(n)) `remove`/`removeFirst` and O(log(n)) -// `add`. -// -// To ensure the timers are ordered by insertion time, the _Timer class has a -// `_id` field set when added to the heap. -// -// [0] http://en.wikipedia.org/wiki/Binary_heap -class _TimerHeap { - List<_Timer> _list; - int _used = 0; - - _TimerHeap([int initSize = 7]) - : _list = new List<_Timer>(initSize); - - bool get isEmpty => _used == 0; - bool get isNotEmpty => _used > 0; - - _Timer get first => _list[0]; - - bool isFirst(_Timer timer) => timer._indexOrNext == 0; - - void add(_Timer timer) { - if (_used == _list.length) { - _resize(); - } - timer._indexOrNext = _used++; - _list[timer._indexOrNext] = timer; - _bubbleUp(timer); - } - - _Timer removeFirst() { - var f = first; - remove(f); - return f; - } - - void remove(_Timer timer) { - _used--; - timer._id = -1; - if (isEmpty) { - _list[0] = null; - timer._indexOrNext = null; - return; - } - var last = _list[_used]; - if (!identical(last, timer)) { - last._indexOrNext = timer._indexOrNext; - _list[last._indexOrNext] = last; - if (last._compareTo(timer) < 0) { - _bubbleUp(last); - } else { - _bubbleDown(last); - } - } - _list[_used] = null; - timer._indexOrNext = null; - } - - void _resize() { - var newList = new List(_list.length * 2 + 1); - newList.setRange(0, _used, _list); - _list = newList; - } - - void _bubbleUp(_Timer timer) { - while (!isFirst(timer)) { - Timer parent = _parent(timer); - if (timer._compareTo(parent) < 0) { - _swap(timer, parent); - } else { - break; - } - } - } - - void _bubbleDown(_Timer timer) { - while (true) { - int leftIndex = _leftChildIndex(timer._indexOrNext); - int rightIndex = _rightChildIndex(timer._indexOrNext); - _Timer newest = timer; - if (leftIndex < _used && _list[leftIndex]._compareTo(newest) < 0) { - newest = _list[leftIndex]; - } - if (rightIndex < _used && _list[rightIndex]._compareTo(newest) < 0) { - newest = _list[rightIndex]; - } - if (identical(newest, timer)) { - // We are where we should be, break. - break; - } - _swap(newest, timer); - } - } - - void _swap(_Timer first, _Timer second) { - int tmp = first._indexOrNext; - first._indexOrNext = second._indexOrNext; - second._indexOrNext = tmp; - _list[first._indexOrNext] = first; - _list[second._indexOrNext] = second; - } - - Timer _parent(_Timer timer) => _list[_parentIndex(timer._indexOrNext)]; - Timer _leftChild(_Timer timer) => _list[_leftChildIndex(timer._indexOrNext)]; - Timer _rightChild(_Timer timer) => - _list[_rightChildIndex(timer._indexOrNext)]; - - static int _parentIndex(int index) => (index - 1) ~/ 2; - static int _leftChildIndex(int index) => 2 * index + 1; - static int _rightChildIndex(int index) => 2 * index + 2; -} - -class _Timer implements Timer { - // Disables the timer. - static const int _NO_TIMER = -1; - - // Timers are ordered by wakeup time. - static _TimerHeap _heap = new _TimerHeap(); - static _Timer _firstZeroTimer; - static _Timer _lastZeroTimer; - static int _idCount = 0; - - static RawReceivePort _receivePort; - static SendPort _sendPort; - static bool _handlingCallbacks = false; - - Function _callback; - int _milliSeconds; - int _wakeupTime = 0; - var _indexOrNext; - int _id = -1; - - static Timer _createTimer(void callback(Timer timer), - int milliSeconds, - bool repeating) { - _Timer timer = new _Timer._internal(); - timer._callback = callback; - if (milliSeconds > 0) { - // Add one because DateTime.now() is assumed to round down - // to nearest millisecond, not up, so that time + duration is before - // duration milliseconds from now. Using micosecond timers like - // Stopwatch allows detecting that the timer fires early. - timer._wakeupTime = - new DateTime.now().millisecondsSinceEpoch + 1 + milliSeconds; - } - timer._milliSeconds = repeating ? milliSeconds : -1; - if (timer._addTimerToHeap()) { - // The new timer is the first in queue. Update event handler. - _notifyEventHandler(); - } - return timer; - } - - factory _Timer(int milliSeconds, void callback(Timer timer)) { - return _createTimer(callback, milliSeconds, false); - } - - factory _Timer.periodic(int milliSeconds, void callback(Timer timer)) { - return _createTimer(callback, milliSeconds, true); - } - - _Timer._internal() {} - - bool get _isInHeap => _id >= 0; - - void _clear() { - _callback = null; - } - - int _compareTo(_Timer other) { - int c = _wakeupTime - other._wakeupTime; - if (c != 0) return c; - return _id - other._id; - } - - bool get _repeating => _milliSeconds >= 0; - - bool get isActive => _callback != null; - - // Cancels a set timer. The timer is removed from the timer list and if - // the given timer is the earliest timer the native timer is reset. - void cancel() { - _clear(); - if (!_isInHeap) return; - assert(_wakeupTime != 0); - bool update = (_firstZeroTimer == null) && _heap.isFirst(this); - _heap.remove(this); - if (update) { - _notifyEventHandler(); - } - } - - void _advanceWakeupTime() { - assert(_milliSeconds >= 0); - _wakeupTime += _milliSeconds; - } - - // Adds a timer to the timer list. Timers with the same wakeup time are - // enqueued in order and notified in FIFO order. - bool _addTimerToHeap() { - if (_wakeupTime == 0) { - if (_firstZeroTimer == null) { - _lastZeroTimer = this; - _firstZeroTimer = this; - return true; - } else { - _lastZeroTimer._indexOrNext = this; - _lastZeroTimer = this; - return false; - } - } else { - _id = _idCount++; - _heap.add(this); - return _firstZeroTimer == null && _heap.isFirst(this); - } - } - - - static void _notifyEventHandler() { - if (_handlingCallbacks) { - // While we are already handling callbacks we will not notify the event - // handler. _handleTimeout will call _notifyEventHandler once all pending - // timers are processed. - return; - } - - if (_firstZeroTimer == null && _heap.isEmpty) { - // No pending timers: Close the receive port and let the event handler - // know. - if (_receivePort != null) { - MojoHandleWatcher.timer(_sendPort, _NO_TIMER); - _shutdownTimerHandler(); - } - } else { - if (_receivePort == null) { - // Create a receive port and register a message handler for the timer - // events. - _createTimerHandler(); - } - if (_firstZeroTimer != null) { - _sendPort.send(null); - } else { - MojoHandleWatcher.timer(_sendPort, _heap.first._wakeupTime); - } - } - } - - static void _handleTimeout(_) { - int currentTime = new DateTime.now().millisecondsSinceEpoch; - // Collect all pending timers. - var timer = _firstZeroTimer; - var nextTimer = _lastZeroTimer; - _firstZeroTimer = null; - _lastZeroTimer = null; - while (_heap.isNotEmpty && _heap.first._wakeupTime <= currentTime) { - var next = _heap.removeFirst(); - if (timer == null) { - nextTimer = next; - timer = next; - } else { - nextTimer._indexOrNext = next; - nextTimer = next; - } - } - - // Trigger all of the pending timers. New timers added as part of the - // callbacks will be enqueued now and notified in the next spin at the - // earliest. - _handlingCallbacks = true; - try { - while (timer != null) { - var next = timer._indexOrNext; - timer._indexOrNext = null; - // One of the timers in the pending_timers list can cancel - // one of the later timers which will set the callback to - // null. - if (timer._callback != null) { - var callback = timer._callback; - if (!timer._repeating) { - // Mark timer as inactive. - timer._callback = null; - } - callback(timer); - // Re-insert repeating timer if not canceled. - if (timer._repeating && timer._callback != null) { - timer._advanceWakeupTime(); - timer._addTimerToHeap(); - } - } - timer = next; - } - } finally { - _handlingCallbacks = false; - _notifyEventHandler(); - } - } - - // Creates a receive port and registers the timer handler on that - // receive port. - static void _createTimerHandler() { - if(_receivePort == null) { - _receivePort = new RawReceivePort(_handleTimeout); - _sendPort = _receivePort.sendPort; - } - } - - static void _shutdownTimerHandler() { - _receivePort.close(); - _receivePort = null; - _sendPort = null; - } -} - -// Provide a closure which will allocate a Timer object to be able to hook -// up the Timer interface in dart:isolate with the implementation here. -_getTimerFactoryClosure() { - return (int milliSeconds, void callback(Timer timer), bool repeating) { - if (repeating) { - return new _Timer.periodic(milliSeconds, callback); - } - return new _Timer(milliSeconds, callback); - }; -} diff --git a/mojo/public/dart/src/timer_queue.dart b/mojo/public/dart/src/timer_queue.dart deleted file mode 100644 index 8f9936b..0000000 --- a/mojo/public/dart/src/timer_queue.dart +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2014 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. - -part of core; - -class Timeout implements Comparable<Timeout> { - int deadline; // milliseconds since the Unix epoch. - SendPort port; - - Timeout(this.port, this.deadline); - - int compareTo(Timeout other) => other.deadline - deadline; -} - -class TimerQueue { - SplayTreeSet _set; - Timeout _nextTimer; - - TimerQueue() : _set = new SplayTreeSet(); - - void updateTimer(SendPort port, int deadline) { - var removedTimeout = null; - _set.removeWhere((timeout) { - if (timeout.port == port) { - removedTimeout = timeout; - return true; - } - return false; - }); - - if ((removedTimeout == null) && (deadline >= 0)) { - _set.add(new Timeout(port, deadline)); - } else { - if (deadline > 0) { - removedTimeout.deadline = deadline; - _set.add(removedTimeout); - } - } - - if (_set.isNotEmpty) { - _nextTimer = _set.first; - } else { - _nextTimer = null; - } - } - - void removeCurrent() => updateTimer(currentPort, -1); - - bool get hasTimer => _nextTimer != null; - int get currentTimeout => _nextTimer.deadline; - SendPort get currentPort => _nextTimer.port; -} diff --git a/mojo/public/dart/src/types.dart b/mojo/public/dart/src/types.dart deleted file mode 100644 index 54c5319..0000000 --- a/mojo/public/dart/src/types.dart +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright 2014 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. - - -part of core; - - -class MojoResult { - static const int kOk = 0; - static const int kCancelled = -1; - static const int kUnknown = -2; - static const int kInvalidArgument = -3; - static const int kDeadlineExceeded = -4; - static const int kNotFound = -5; - static const int kAlreadyExists = -6; - static const int kPermissionDenied = -7; - static const int kResourceExhausted = -8; - static const int kFailedPrecondition = -9; - static const int kAborted = -10; - static const int kOutOfRange = -11; - static const int kUnimplemented = -12; - static const int kInternal = -13; - static const int kUnavailable = -14; - static const int kDataLoss = -15; - static const int kBusy = -16; - static const int kShouldWait = -17; - - static const OK = const MojoResult._(kOk); - static const CANCELLED = const MojoResult._(kCancelled); - static const UNKNOWN = const MojoResult._(kUnknown); - static const INVALID_ARGUMENT = const MojoResult._(kInvalidArgument); - static const DEADLINE_EXCEEDED = const MojoResult._(kDeadlineExceeded); - static const NOT_FOUND = const MojoResult._(kNotFound); - static const ALREADY_EXISTS = const MojoResult._(kAlreadyExists); - static const PERMISSION_DENIED = const MojoResult._(kPermissionDenied); - static const RESOURCE_EXHAUSTED = const MojoResult._(kResourceExhausted); - static const FAILED_PRECONDITION = const MojoResult._(kFailedPrecondition); - static const ABORTED = const MojoResult._(kAborted); - static const OUT_OF_RANGE = const MojoResult._(kOutOfRange); - static const UNIMPLEMENTED = const MojoResult._(kUnimplemented); - static const INTERNAL = const MojoResult._(kInternal); - static const UNAVAILABLE = const MojoResult._(kUnavailable); - static const DATA_LOSS = const MojoResult._(kDataLoss); - static const BUSY = const MojoResult._(kBusy); - static const SHOULD_WAIT = const MojoResult._(kShouldWait); - - final int value; - - const MojoResult._(this.value); - - factory MojoResult(int value) { - switch (value) { - case kOk: return OK; - case kCancelled: return CANCELLED; - case kUnknown: return UNKNOWN; - case kInvalidArgument: return INVALID_ARGUMENT; - case kDeadlineExceeded: return DEADLINE_EXCEEDED; - case kNotFound: return NOT_FOUND; - case kAlreadyExists: return ALREADY_EXISTS; - case kPermissionDenied: return PERMISSION_DENIED; - case kResourceExhausted: return RESOURCE_EXHAUSTED; - case kFailedPrecondition: return FAILED_PRECONDITION; - case kAborted: return ABORTED; - case kOutOfRange: return OUT_OF_RANGE; - case kUnimplemented: return UNIMPLEMENTED; - case kInternal: return INTERNAL; - case kUnavailable: return UNAVAILABLE; - case kDataLoss: return DATA_LOSS; - case kBusy: return BUSY; - case kShouldWait: return SHOULD_WAIT; - default: - throw 'Invalid Mojo result'; - } - } - - bool get isOk => (this == OK); - bool get isCancelled => (this == CANCELLED); - bool get isUnknown => (this == UNKNOWN); - bool get isInvalidArgument => (this == INVALID_ARGUMENT); - bool get isDeadlineExceeded => (this == DEADLINE_EXCEEDED); - bool get isNotFound => (this == NOT_FOUND); - bool get isAlreadExists => (this == ALREADY_EXISTS); - bool get isPermissionDenied => (this == PERMISSION_DENIED); - bool get isResourceExhausted => (this == RESOURCE_EXHAUSTED); - bool get isFailedPrecondition => (this == FAILED_PRECONDITION); - bool get isAborted => (this == ABORTED); - bool get isOutOfRange => (this == OUT_OF_RANGE); - bool get isUnimplemented => (this == UNIMPLEMENTED); - bool get isInternal => (this == INTERNAL); - bool get isUnavailable => (this == UNAVAILABLE); - bool get isDataLoss => (this == DATA_LOSS); - bool get isBusy => (this == BUSY); - bool get isShouldWait => (this == SHOULD_WAIT); - - String toString() { - switch (value) { - case kOk: return "OK"; - case kCancelled: return "CANCELLED"; - case kUnknown: return "UNKNOWN"; - case kInvalidArgument: return "INVALID_ARGUMENT"; - case kDeadlineExceeded: return "DEADLINE_EXCEEDED"; - case kNotFound: return "NOT_FOUND"; - case kAlreadyExists: return "ALREADY_EXISTS"; - case kPermissionDenied: return "PERMISSION_DENIED"; - case kResourceExhausted: return "RESOURCE_EXHAUSTED"; - case kFailedPrecondition: return "FAILED_PRECONDITION"; - case kAborted: return "ABORTED"; - case kOutOfRange: return "OUT_OF_RANGE"; - case kUnimplemented: return "UNIMPLEMENTED"; - case kInternal: return "INTERNAL"; - case kUnavailable: return "UNAVAILABLE"; - case kDataLoss: return "DATA_LOSS"; - case kBusy: return "BUSY"; - case kShouldWait: return "SHOULD_WAIT"; - default: return "<invalid result>"; - } - } -} - - -class MojoHandleSignals { - static const int kNone = 0; - static const int kReadable = 1 << 0; - static const int kWritable = 1 << 1; - static const int kPeerClosed = 1 << 2; - static const int kReadWrite = kReadable | kWritable; - static const int kAll = kReadable | kWritable | kPeerClosed; - - // TODO(zra): Does PEER_CLOSED | anything else make sense? - static const NONE = const MojoHandleSignals._(kNone); - static const READABLE = const MojoHandleSignals._(kReadable); - static const WRITABLE = const MojoHandleSignals._(kWritable); - static const PEER_CLOSED = const MojoHandleSignals._(kPeerClosed); - static const READWRITE = const MojoHandleSignals._(kReadWrite); - static const ALL = const MojoHandleSignals._(kAll); - - final int value; - - const MojoHandleSignals._(this.value); - - factory MojoHandleSignals(int value) { - switch (value) { - case kNone: return NONE; - case kReadable: return READABLE; - case kWritable: return WRITABLE; - case kPeerClosed: return PEER_CLOSED; - case kReadWrite: return READWRITE; - case kAll: return ALL; - default: - throw 'Invalid handle signal'; - } - } - - bool get isNone => (this == NONE); - bool get isReadable => (value & kReadable) == kReadable; - bool get isWritable => (value & kWritable) == kWritable; - bool get isPeerClosed => (value & kPeerClosed) == kPeerClosed; - bool get isReadWrite => (value & kReadWrite) == kReadWrite; - bool get isAll => (this == ALL); - - MojoHandleSignals operator +(MojoHandleSignals other) { - return new MojoHandleSignals(value | other.value); - } - - MojoHandleSignals operator -(MojoHandleSignals other) { - return new MojoHandleSignals(value & ~other.value); - } - - String toString() { - switch (value) { - case kNone: return "NONE"; - case kReadable: return "READABLE"; - case kWritable: return "WRITABLE"; - case kPeerClosed: return "PEER_CLOSED"; - case kReadWrite: return "READWRITE"; - case kAll: return "ALL"; - default: return "<invalid signal>"; - } - } -} - - -class MojoHandleSignalsState { - MojoHandleSignalsState(this.satisfied_signals, - this.satisfiable_signals); - final int satisfied_signals; - final int satisfiable_signals; -} - - -class MojoWaitResult { - MojoWaitResult(this.result, this.state); - final MojoResult result; - MojoHandleSignalsState state; -} - - -class MojoWaitManyResult { - MojoWaitManyResult(this.result, this.index, this.states); - final MojoResult result; - final int index; - List<MojoHandleSignalsState> states; - - bool get isIndexValid => (this.index != null); - bool get areSignalStatesValid => (this.states != null); -} |