dom/messages/SystemMessageManager.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/dom/messages/SystemMessageManager.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,331 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this file,
     1.6 + * You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +"use strict";
     1.9 +
    1.10 +const Cc = Components.classes;
    1.11 +const Ci = Components.interfaces;
    1.12 +const Cu = Components.utils;
    1.13 +const Cr = Components.results;
    1.14 +
    1.15 +Cu.import("resource://gre/modules/XPCOMUtils.jsm");
    1.16 +Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
    1.17 +Cu.import("resource://gre/modules/Services.jsm");
    1.18 +
    1.19 +const kSystemMessageInternalReady = "system-message-internal-ready";
    1.20 +
    1.21 +XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
    1.22 +                                   "@mozilla.org/childprocessmessagemanager;1",
    1.23 +                                   "nsISyncMessageSender");
    1.24 +
    1.25 +function debug(aMsg) {
    1.26 +   // dump("-- SystemMessageManager " + Date.now() + " : " + aMsg + "\n");
    1.27 +}
    1.28 +
    1.29 +// Implementation of the DOM API for system messages
    1.30 +
    1.31 +function SystemMessageManager() {
    1.32 +  // If we have a system message handler registered for messages of type
    1.33 +  // |type|, this._dispatchers[type] equals {handler, messages, isHandling},
    1.34 +  // where
    1.35 +  //  - |handler| is the message handler that the page registered,
    1.36 +  //  - |messages| is a list of messages which we've received while
    1.37 +  //    dispatching messages to the handler, but haven't yet sent, and
    1.38 +  //  - |isHandling| indicates whether we're currently dispatching messages
    1.39 +  //    to this handler.
    1.40 +  this._dispatchers = {};
    1.41 +
    1.42 +  // Pending messages for this page, keyed by message type.
    1.43 +  this._pendings = {};
    1.44 +
    1.45 +  // Flag to specify if this process has already registered the manifest URL.
    1.46 +  this._registerManifestURLReady = false;
    1.47 +
    1.48 +  // Flag to determine this process is a parent or child process.
    1.49 +  let appInfo = Cc["@mozilla.org/xre/app-info;1"];
    1.50 +  this._isParentProcess =
    1.51 +    !appInfo || appInfo.getService(Ci.nsIXULRuntime)
    1.52 +                  .processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
    1.53 +
    1.54 +  // An oberver to listen to whether the |SystemMessageInternal| is ready.
    1.55 +  if (this._isParentProcess) {
    1.56 +    Services.obs.addObserver(this, kSystemMessageInternalReady, false);
    1.57 +  }
    1.58 +}
    1.59 +
    1.60 +SystemMessageManager.prototype = {
    1.61 +  __proto__: DOMRequestIpcHelper.prototype,
    1.62 +
    1.63 +  _dispatchMessage: function(aType, aDispatcher, aMessage) {
    1.64 +    if (aDispatcher.isHandling) {
    1.65 +      // Queue up the incomming message if we're currently dispatching a
    1.66 +      // message; we'll send the message once we finish with the current one.
    1.67 +      //
    1.68 +      // _dispatchMethod is reentrant because a page can spin up a nested
    1.69 +      // event loop from within a system message handler (e.g. via alert()),
    1.70 +      // and we can then try to send the page another message while it's
    1.71 +      // inside this nested event loop.
    1.72 +      aDispatcher.messages.push(aMessage);
    1.73 +      return;
    1.74 +    }
    1.75 +
    1.76 +    aDispatcher.isHandling = true;
    1.77 +
    1.78 +    // We get a json blob, but in some cases we want another kind of object
    1.79 +    // to be dispatched. To do so, we check if we have a valid contract ID of
    1.80 +    // "@mozilla.org/dom/system-messages/wrapper/TYPE;1" component implementing
    1.81 +    // nsISystemMessageWrapper.
    1.82 +    debug("Dispatching " + JSON.stringify(aMessage) + "\n");
    1.83 +    let contractID = "@mozilla.org/dom/system-messages/wrapper/" + aType + ";1";
    1.84 +    let wrapped = false;
    1.85 +
    1.86 +    if (contractID in Cc) {
    1.87 +      debug(contractID + " is registered, creating an instance");
    1.88 +      let wrapper = Cc[contractID].createInstance(Ci.nsISystemMessagesWrapper);
    1.89 +      if (wrapper) {
    1.90 +        aMessage = wrapper.wrapMessage(aMessage, this._window);
    1.91 +        wrapped = true;
    1.92 +        debug("wrapped = " + aMessage);
    1.93 +      }
    1.94 +    }
    1.95 +
    1.96 +    aDispatcher.handler
    1.97 +      .handleMessage(wrapped ? aMessage
    1.98 +                             : Cu.cloneInto(aMessage, this._window));
    1.99 +
   1.100 +    // We need to notify the parent one of the system messages has been handled,
   1.101 +    // so the parent can release the CPU wake lock it took on our behalf.
   1.102 +    cpmm.sendAsyncMessage("SystemMessageManager:HandleMessagesDone",
   1.103 +                          { type: aType,
   1.104 +                            manifestURL: this._manifestURL,
   1.105 +                            pageURL: this._pageURL,
   1.106 +                            handledCount: 1 });
   1.107 +
   1.108 +    aDispatcher.isHandling = false;
   1.109 +
   1.110 +    if (aDispatcher.messages.length > 0) {
   1.111 +      this._dispatchMessage(aType, aDispatcher, aDispatcher.messages.shift());
   1.112 +    } else {
   1.113 +      // No more messages that need to be handled, we can notify the
   1.114 +      // ContentChild to release the CPU wake lock grabbed by the ContentParent
   1.115 +      // (i.e. NewWakeLockOnBehalfOfProcess()) and reset the process's priority.
   1.116 +      //
   1.117 +      // TODO: Bug 874353 - Remove SystemMessageHandledListener in ContentParent
   1.118 +      Services.obs.notifyObservers(/* aSubject */ null,
   1.119 +                                   "handle-system-messages-done",
   1.120 +                                   /* aData */ null);
   1.121 +    }
   1.122 +  },
   1.123 +
   1.124 +  mozSetMessageHandler: function(aType, aHandler) {
   1.125 +    debug("set message handler for [" + aType + "] " + aHandler);
   1.126 +
   1.127 +    if (this._isInBrowserElement) {
   1.128 +      debug("the app loaded in the browser cannot set message handler");
   1.129 +      // Don't throw there, but ignore the registration.
   1.130 +      return;
   1.131 +    }
   1.132 +
   1.133 +    if (!aType) {
   1.134 +      // Just bail out if we have no type.
   1.135 +      return;
   1.136 +    }
   1.137 +
   1.138 +    let dispatchers = this._dispatchers;
   1.139 +    if (!aHandler) {
   1.140 +      // Setting the dispatcher to null means we don't want to handle messages
   1.141 +      // for this type anymore.
   1.142 +      delete dispatchers[aType];
   1.143 +      return;
   1.144 +    }
   1.145 +
   1.146 +    // Last registered handler wins.
   1.147 +    dispatchers[aType] = { handler: aHandler, messages: [], isHandling: false };
   1.148 +
   1.149 +    // Ask for the list of currently pending messages.
   1.150 +    cpmm.sendAsyncMessage("SystemMessageManager:GetPendingMessages",
   1.151 +                          { type: aType,
   1.152 +                            pageURL: this._pageURL,
   1.153 +                            manifestURL: this._manifestURL });
   1.154 +  },
   1.155 +
   1.156 +  mozHasPendingMessage: function(aType) {
   1.157 +    debug("asking pending message for [" + aType + "]");
   1.158 +
   1.159 +    if (this._isInBrowserElement) {
   1.160 +      debug("the app loaded in the browser cannot ask pending message");
   1.161 +      // Don't throw there, but pretend to have no messages available.
   1.162 +      return false;
   1.163 +    }
   1.164 +
   1.165 +    // If we have a handler for this type, we can't have any pending message.
   1.166 +    if (aType in this._dispatchers) {
   1.167 +      return false;
   1.168 +    }
   1.169 +
   1.170 +    return cpmm.sendSyncMessage("SystemMessageManager:HasPendingMessages",
   1.171 +                                { type: aType,
   1.172 +                                  pageURL: this._pageURL,
   1.173 +                                  manifestURL: this._manifestURL })[0];
   1.174 +  },
   1.175 +
   1.176 +  uninit: function()  {
   1.177 +    this._dispatchers = null;
   1.178 +    this._pendings = null;
   1.179 +
   1.180 +    if (this._isParentProcess) {
   1.181 +      Services.obs.removeObserver(this, kSystemMessageInternalReady);
   1.182 +    }
   1.183 +
   1.184 +    if (this._isInBrowserElement) {
   1.185 +      debug("the app loaded in the browser doesn't need to unregister " +
   1.186 +            "the manifest URL for listening to the system messages");
   1.187 +      return;
   1.188 +    }
   1.189 +
   1.190 +    cpmm.sendAsyncMessage("SystemMessageManager:Unregister",
   1.191 +                          { manifestURL: this._manifestURL,
   1.192 +                            pageURL: this._pageURL,
   1.193 +                            innerWindowID: this.innerWindowID });
   1.194 +  },
   1.195 +
   1.196 +  // Possible messages:
   1.197 +  //
   1.198 +  //   - SystemMessageManager:Message
   1.199 +  //     This one will only be received when the child process is alive when
   1.200 +  //     the message is initially sent.
   1.201 +  //
   1.202 +  //   - SystemMessageManager:GetPendingMessages:Return
   1.203 +  //     This one will be received when the starting child process wants to
   1.204 +  //     retrieve the pending system messages from the parent (i.e. after
   1.205 +  //     sending SystemMessageManager:GetPendingMessages).
   1.206 +  receiveMessage: function(aMessage) {
   1.207 +    let msg = aMessage.data;
   1.208 +    debug("receiveMessage " + aMessage.name + " for [" + msg.type + "] " +
   1.209 +          "with manifest URL = " + msg.manifestURL +
   1.210 +          " and page URL = " + msg.pageURL);
   1.211 +
   1.212 +    // Multiple windows can share the same target (process), the content
   1.213 +    // window needs to check if the manifest/page URL is matched. Only
   1.214 +    // *one* window should handle the system message.
   1.215 +    if (msg.manifestURL !== this._manifestURL ||
   1.216 +        msg.pageURL !== this._pageURL) {
   1.217 +      debug("This page shouldn't handle the messages because its " +
   1.218 +            "manifest URL = " + this._manifestURL +
   1.219 +            " and page URL = " + this._pageURL);
   1.220 +      return;
   1.221 +    }
   1.222 +
   1.223 +    let messages = (aMessage.name == "SystemMessageManager:Message")
   1.224 +                   ? [msg.msg]
   1.225 +                   : msg.msgQueue;
   1.226 +
   1.227 +    // We only dispatch messages when a handler is registered.
   1.228 +    let dispatcher = this._dispatchers[msg.type];
   1.229 +    if (dispatcher) {
   1.230 +      if (aMessage.name == "SystemMessageManager:Message") {
   1.231 +        // Send an acknowledgement to parent to clean up the pending message
   1.232 +        // before we dispatch the message to apps, so a re-launched app won't
   1.233 +        // handle it again, which is redundant.
   1.234 +        cpmm.sendAsyncMessage("SystemMessageManager:Message:Return:OK",
   1.235 +                              { type: msg.type,
   1.236 +                                manifestURL: this._manifestURL,
   1.237 +                                pageURL: this._pageURL,
   1.238 +                                msgID: msg.msgID });
   1.239 +      }
   1.240 +
   1.241 +      messages.forEach(function(aMsg) {
   1.242 +        this._dispatchMessage(msg.type, dispatcher, aMsg);
   1.243 +      }, this);
   1.244 +    } else {
   1.245 +      // Since no handlers are registered, we need to notify the parent as if
   1.246 +      // all the queued system messages have been handled (notice |handledCount:
   1.247 +      // messages.length|), so the parent can release the CPU wake lock it took
   1.248 +      // on our behalf.
   1.249 +      cpmm.sendAsyncMessage("SystemMessageManager:HandleMessagesDone",
   1.250 +                            { type: msg.type,
   1.251 +                              manifestURL: this._manifestURL,
   1.252 +                              pageURL: this._pageURL,
   1.253 +                              handledCount: messages.length });
   1.254 +
   1.255 +      // We also need to notify the ContentChild to release the CPU wake lock
   1.256 +      // grabbed by the ContentParent (i.e. NewWakeLockOnBehalfOfProcess()) and
   1.257 +      // reset the process's priority.
   1.258 +      //
   1.259 +      // TODO: Bug 874353 - Remove SystemMessageHandledListener in ContentParent
   1.260 +      Services.obs.notifyObservers(/* aSubject */ null,
   1.261 +                                   "handle-system-messages-done",
   1.262 +                                   /* aData */ null);
   1.263 +    }
   1.264 +  },
   1.265 +
   1.266 +  // nsIDOMGlobalPropertyInitializer implementation.
   1.267 +  init: function(aWindow) {
   1.268 +    debug("init");
   1.269 +    this.initDOMRequestHelper(aWindow,
   1.270 +                              ["SystemMessageManager:Message",
   1.271 +                               "SystemMessageManager:GetPendingMessages:Return"]);
   1.272 +
   1.273 +    let principal = aWindow.document.nodePrincipal;
   1.274 +    this._isInBrowserElement = principal.isInBrowserElement;
   1.275 +    this._pageURL = principal.URI.spec;
   1.276 +
   1.277 +    let appsService = Cc["@mozilla.org/AppsService;1"]
   1.278 +                        .getService(Ci.nsIAppsService);
   1.279 +    this._manifestURL = appsService.getManifestURLByLocalId(principal.appId);
   1.280 +
   1.281 +    // Two cases are valid to register the manifest URL for the current process:
   1.282 +    // 1. This is asked by a child process (parent process must be ready).
   1.283 +    // 2. Parent process has already constructed the |SystemMessageInternal|.
   1.284 +    // Otherwise, delay to do it when the |SystemMessageInternal| is ready.
   1.285 +    let readyToRegister = true;
   1.286 +    if (this._isParentProcess) {
   1.287 +      let ready = cpmm.sendSyncMessage(
   1.288 +        "SystemMessageManager:AskReadyToRegister", null);
   1.289 +      if (ready.length == 0 || !ready[0]) {
   1.290 +        readyToRegister = false;
   1.291 +      }
   1.292 +    }
   1.293 +    if (readyToRegister) {
   1.294 +      this._registerManifestURL();
   1.295 +    }
   1.296 +
   1.297 +    debug("done");
   1.298 +  },
   1.299 +
   1.300 +  observe: function(aSubject, aTopic, aData) {
   1.301 +    if (aTopic === kSystemMessageInternalReady) {
   1.302 +      this._registerManifestURL();
   1.303 +    }
   1.304 +
   1.305 +    // Call the DOMRequestIpcHelper.observe method.
   1.306 +    this.__proto__.__proto__.observe.call(this, aSubject, aTopic, aData);
   1.307 +  },
   1.308 +
   1.309 +  _registerManifestURL: function() {
   1.310 +    if (this._isInBrowserElement) {
   1.311 +      debug("the app loaded in the browser doesn't need to register " +
   1.312 +            "the manifest URL for listening to the system messages");
   1.313 +      return;
   1.314 +    }
   1.315 +
   1.316 +    if (!this._registerManifestURLReady) {
   1.317 +      cpmm.sendAsyncMessage("SystemMessageManager:Register",
   1.318 +                            { manifestURL: this._manifestURL,
   1.319 +                              pageURL: this._pageURL,
   1.320 +                              innerWindowID: this.innerWindowID });
   1.321 +
   1.322 +      this._registerManifestURLReady = true;
   1.323 +    }
   1.324 +  },
   1.325 +
   1.326 +  classID: Components.ID("{bc076ea0-609b-4d8f-83d7-5af7cbdc3bb2}"),
   1.327 +
   1.328 +  QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMNavigatorSystemMessages,
   1.329 +                                         Ci.nsIDOMGlobalPropertyInitializer,
   1.330 +                                         Ci.nsIObserver,
   1.331 +                                         Ci.nsISupportsWeakReference])
   1.332 +}
   1.333 +
   1.334 +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SystemMessageManager]);

mercurial