1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 define("mojo/public/js/bindings/connector", [
6 "mojo/public/js/bindings/codec",
7 "mojo/public/js/bindings/core",
8 "mojo/public/js/bindings/support",
9 ], function(codec, core, support) {
11 function Connector(handle) {
12 this.handle_ = handle;
13 this.dropWrites_ = false;
15 this.incomingReceiver_ = null;
16 this.readWaitCookie_ = null;
17 this.errorHandler_ = null;
19 this.waitToReadMore_();
22 Connector.prototype.close = function() {
23 if (this.readWaitCookie_) {
24 support.cancelWait(this.readWaitCookie_);
25 this.readWaitCookie_ = null;
27 if (this.handle_ != core.kInvalidHandle) {
28 core.close(this.handle_);
29 this.handle_ = core.kInvalidHandle;
33 Connector.prototype.accept = function(message) {
40 var result = core.writeMessage(this.handle_,
41 new Uint8Array(message.buffer.arrayBuffer),
43 core.WRITE_MESSAGE_FLAG_NONE);
46 // The handles were successfully transferred, so we don't own them
50 case core.RESULT_FAILED_PRECONDITION:
51 // There's no point in continuing to write to this pipe since the other
52 // end is gone. Avoid writing any future messages. Hide write failures
53 // from the caller since we'd like them to continue consuming any
54 // backlog of incoming messages before regarding the message pipe as
56 this.dropWrites_ = true;
59 // This particular write was rejected, presumably because of bad input.
60 // The pipe is not necessarily in a bad state.
66 Connector.prototype.setIncomingReceiver = function(receiver) {
67 this.incomingReceiver_ = receiver;
70 Connector.prototype.setErrorHandler = function(handler) {
71 this.errorHandler_ = handler;
74 Connector.prototype.encounteredError = function() {
78 Connector.prototype.waitToReadMore_ = function() {
79 this.readWaitCookie_ = support.asyncWait(this.handle_,
80 core.WAIT_FLAG_READABLE,
81 this.readMore_.bind(this));
84 Connector.prototype.readMore_ = function(result) {
86 var read = core.readMessage(this.handle_,
87 core.READ_MESSAGE_FLAG_NONE);
88 if (read.result == core.RESULT_SHOULD_WAIT) {
89 this.waitToReadMore_();
92 if (read.result != core.RESULT_OK) {
94 if (this.errorHandler_)
95 this.errorHandler_.onError(read.result);
98 var buffer = new codec.Buffer(read.buffer);
99 var message = new codec.Message(buffer, read.handles);
100 if (this.incomingReceiver_) {
101 this.incomingReceiver_.accept(message);
107 exports.Connector = Connector;