aboutsummaryrefslogtreecommitdiff
path: root/tools/addon-sdk-1.5/packages/api-utils/lib/message-manager.js
blob: 25ed6f79a867b8d870efb3e4517b14ab7c6791a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const BAD_LISTENER = "The event listener must be a function.";

const { Cc, Ci, Cu, CC } = require("chrome");
const { setTimeout } = require("./timer");

const { ns } = require("./namespace");

const { curry, invoke } = require("./utils/function");

const Sandbox = require("./sandbox");

// JSON.stringify is buggy with cross-sandbox values,
// it may return "{}" on functions. Use a replacer to match them correctly.
const jsonFixer = function (k, v) typeof v === "function" ? undefined : v;

/**
 * Defers invoking the function until the current call stack has cleared.
 *
 * @param {Function} fn
 *    The function to defer.
 *
 * @returns {Function}
 *    The deferred function
 */
const defer =  function(fn) function() {
  setTimeout(invoke, 0, fn, arguments, this)
};

/**
 * Adds a message listener.
 * This listener will receive messages sent from the remote frame.
 *
 * @param {String} name
 *    The name of the message for which to add a listener.
 * @param {Function} listener
 *    The listener function called when the message is received.
 */
function addMessageListener(name, listener) {
  if (typeof listener !== "function")
    throw new Error(BAD_LISTENER);

  let listeners = frame(this).listeners;

  if (name in listeners) {
    if (~listeners[name].indexOf(listener))
      return;
  } else {
    listeners[name] = [];
  }

  listeners[name].push(listener);
}

/**
 * Removes a message listener previously added by calling addMessageListener.
 *
 * @param {String} name
 *    The name of the message for which to remove a listener.
 * @param {Function} listener
 *    The listener function has to be removed.
 */
function removeMessageListener(name, listener) {
  if (typeof listener !== "function")
    throw new Error(BAD_LISTENER);

  let listeners = frame(this).listeners;

  if (!(name in listeners))
    return;

  let index = listeners[name].indexOf(listener);

  if (~index) {
    listeners[name].splice(index, 1);
  }
}

/**
 * Sends a message to the listeners.
 *
 * @param {Boolean} sync
 *    Indicates if the call is synchronous or asynchronous
 * @param {String} name
 *    The name of the message to send to the listeners.
 * @param {Object} [data=null]
 *    A JSON object containing data to be delivered to the listeners.
 *
 * @returns {Array|undefined}
 *    An array with the return values of the listeners if `sync` is `true`,
 *    otherwise `undefined`.
 */
function sendMessage(sync, name, data) {
  typeof data === "undefined" && (data = null);

  let listeners = frame(frame(this).receiver).listeners;

  let responses = [];

  let returnValue = sync ? responses : undefined;

  if (!(name in listeners))
    return returnValue;

  let json = JSON.parse(JSON.stringify(data, jsonFixer));

  for each(let listener in listeners[name]) {
    try {
      let response = listener.call(null, {
        sync : sync,
        name : name,
        json : json,
        target : null
      });

      if (sync) {
        if (typeof response === "undefined")
          responses.push(response);
        else
          responses.push(JSON.parse(JSON.stringify(response, jsonFixer)));
      }

    } catch (e) {
      console.exception(e);
    }
  }
  return returnValue;
};

let sendSyncMessage = curry(sendMessage, true);
let sendAsyncMessage = curry(defer(sendMessage), false);

let frame = ns({receiver: null, listeners: null});

/**
 * The MessageManager object emulates the Message Manager API, without creating
 * new processes. It useful in mono process context, like Fennec.
 *
 * @see
 *    https://developer.mozilla.org/en/The_message_manager
 */
function MessageManager() {

  let sandbox = Sandbox.sandbox(null, { wantXrays : false });

  Object.defineProperties(sandbox, {
    addMessageListener: {value: addMessageListener.bind(sandbox)},

    removeMessageListener: { value: removeMessageListener.bind(sandbox)},

    sendAsyncMessage: {value: sendAsyncMessage.bind(sandbox)},

    sendSyncMessage: { value: sendSyncMessage.bind(sandbox) }
  });

  frame(this).receiver = sandbox;
  frame(sandbox).receiver = this;

  frame(this).listeners = {};
  frame(sandbox).listeners = {};
}

MessageManager.prototype = {
  constructor: MessageManager,

  addMessageListener : addMessageListener,

  removeMessageListener : removeMessageListener,

  sendAsyncMessage : sendAsyncMessage,

  /**
   * Loads a script into the remote frame.
   *
   * @param {String} uri
   *    The URL of the script to load into the frame; this must be an absolute
   *    local URL, but data: URLs are supported.
   * @param {Boolean} allowDelayedLoad
   *    Not used.
   */
  loadFrameScript: function loadFrameScript(uri, async) {
    if (arguments.length < loadFrameScript.length)
      throw new Error("Not enough arguments");

    let sandbox = frame(this).receiver;

    try {
      Sandbox.load(sandbox, uri);
    } catch (e) {
      console.exception(e)
    }
  }
}

Object.freeze(MessageManager);
Object.freeze(MessageManager.prototype);

exports.MessageManager = MessageManager;