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/bindings/js/connector", [
6 "mojo/public/bindings/js/codec",
7 "mojo/bindings/js/core",
8 "mojo/bindings/js/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;
18 this.waitToReadMore_();
21 Connector.prototype.close = function() {
22 if (this.readWaitCookie_) {
23 support.cancelWait(this.readWaitCookie_);
24 this.readWaitCookie_ = null;
26 if (this.handle_ != core.kInvalidHandle) {
27 core.close(this.handle_);
28 this.handle_ = core.kInvalidHandle;
32 Connector.prototype.accept = function(message) {
39 var result = core.writeMessage(this.handle_,
42 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.encounteredError = function() {
74 Connector.prototype.waitToReadMore_ = function() {
75 this.readWaitCookie_ = support.asyncWait(this.handle_,
76 core.WAIT_FLAG_READABLE,
77 this.readMore_.bind(this));
80 Connector.prototype.readMore_ = function(result) {
82 var read = core.readMessage(this.handle_,
83 core.READ_MESSAGE_FLAG_NONE);
84 if (read.result == core.RESULT_SHOULD_WAIT) {
85 this.waitToReadMore_();
88 if (read.result != core.RESULT_OK) {
92 // TODO(abarth): Should core.readMessage return a Uint8Array?
93 var memory = new Uint8Array(read.buffer);
94 var message = new codec.Message(memory, read.handles);
95 if (this.incomingReceiver_)
96 this.incomingReceiver_.accept(message);
101 exports.Connector = Connector;