Bug 859372 - Refactor transport.js; r=past
authorEddy Bruel <ejpbruel@mozilla.com
Thu, 24 Apr 2014 13:23:30 +0200
changeset 180420 85175645b7dafe82d9e82e611462d67d4bec2e08
parent 180419 0d41508524a1aa47667bcb8237fd03ad33012212
child 180421 27a7bd55597e1e746365578c38c4dae3fd53283b
push id272
push userpvanderbeken@mozilla.com
push dateMon, 05 May 2014 16:31:18 +0000
reviewerspast
bugs859372
milestone31.0a1
Bug 859372 - Refactor transport.js; r=past
testing/marionette/marionette-server.js
toolkit/devtools/server/actors/script.js
toolkit/devtools/server/main.js
toolkit/devtools/server/transport.js
--- a/testing/marionette/marionette-server.js
+++ b/testing/marionette/marionette-server.js
@@ -30,20 +30,16 @@ specialpowers.specialPowersObserver = ne
 specialpowers.specialPowersObserver.init();
 
 Cu.import("resource://gre/modules/FileUtils.jsm");
 Cu.import("resource://gre/modules/NetUtil.jsm");
 
 Services.prefs.setBoolPref("marionette.contentListener", false);
 let appName = Services.appinfo.name;
 
-// dumpn needed/used by dbg-transport.js
-this.dumpn = function dumpn(str) {
-  logger.trace(str);
-}
 let { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
 let DevToolsUtils = devtools.require("devtools/toolkit/DevToolsUtils.js");
 this.DevToolsUtils = DevToolsUtils;
 loader.loadSubScript("resource://gre/modules/devtools/server/transport.js");
 
 let bypassOffline = false;
 let qemu = "0";
 let device = null;
--- a/toolkit/devtools/server/actors/script.js
+++ b/toolkit/devtools/server/actors/script.js
@@ -1,13 +1,14 @@
 /* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; js-indent-level: 2; -*- */
 /* vim: set ft=javascript ts=2 et sw=2 tw=80: */
 /* 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";
 
 let B2G_ID = "{3c2e2abc-06d4-11e1-ac3b-374f68613e61}";
 
 let TYPED_ARRAY_CLASSES = ["Uint8Array", "Uint8ClampedArray", "Uint16Array",
       "Uint32Array", "Int8Array", "Int16Array", "Int32Array", "Float32Array",
       "Float64Array"];
 
@@ -549,17 +550,17 @@ ThreadActor.prototype = {
   get prettyPrintWorker() {
     if (!this._prettyPrintWorker) {
       this._prettyPrintWorker = new ChromeWorker(
         "resource://gre/modules/devtools/server/actors/pretty-print-worker.js");
 
       this._prettyPrintWorker.addEventListener(
         "error", this._onPrettyPrintError, false);
 
-      if (wantLogging) {
+      if (dumpn.wantLogging) {
         this._prettyPrintWorker.addEventListener("message", this._onPrettyPrintMsg, false);
 
         const postMsg = this._prettyPrintWorker.postMessage;
         this._prettyPrintWorker.postMessage = data => {
           dumpn("Sending message to prettyPrintWorker: "
                 + JSON.stringify(data, null, 2) + "\n");
           return postMsg.call(this._prettyPrintWorker, data);
         };
--- a/toolkit/devtools/server/main.js
+++ b/toolkit/devtools/server/main.js
@@ -8,16 +8,17 @@
 /**
  * Toolkit glue for the remote debugging protocol, loaded into the
  * debugging global.
  */
 let { Ci, Cc, CC, Cu, Cr } = require("chrome");
 let Debugger = require("Debugger");
 let Services = require("Services");
 let { ActorPool } = require("devtools/server/actors/common");
+let { DebuggerTransport, LocalDebuggerTransport, ChildDebuggerTransport } = require("devtools/server/transport");
 let DevToolsUtils = require("devtools/toolkit/DevToolsUtils");
 let { dumpn, dbg_assert } = DevToolsUtils;
 let Services = require("Services");
 let EventEmitter = require("devtools/toolkit/event-emitter");
 
 // Until all Debugger server code is converted to SDK modules,
 // imports Components.* alias from chrome module.
 var { Ci, Cc, CC, Cu, Cr } = require("chrome");
@@ -42,16 +43,17 @@ Object.defineProperty(this, "Components"
   get: function () require("chrome").components
 });
 
 const DBG_STRINGS_URI = "chrome://global/locale/devtools/debugger.properties";
 
 const nsFile = CC("@mozilla.org/file/local;1", "nsIFile", "initWithPath");
 Cu.import("resource://gre/modules/reflect.jsm");
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/NetUtil.jsm");
 dumpn.wantLogging = Services.prefs.getBoolPref("devtools.debugger.log");
 
 Cu.import("resource://gre/modules/devtools/deprecated-sync-thenables.js");
 
 function loadSubScript(aURL)
 {
   try {
     let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
@@ -78,18 +80,16 @@ Cu.import("resource://gre/modules/devtoo
 
 XPCOMUtils.defineLazyModuleGetter(this, "console",
                                   "resource://gre/modules/devtools/Console.jsm");
 
 XPCOMUtils.defineLazyGetter(this, "NetworkMonitorManager", () => {
   return require("devtools/toolkit/webconsole/network-monitor").NetworkMonitorManager;
 });
 
-loadSubScript.call(this, "resource://gre/modules/devtools/server/transport.js");
-
 // XPCOM constructors
 const ServerSocket = CC("@mozilla.org/network/server-socket;1",
                         "nsIServerSocket",
                         "initSpecialConnection");
 const UnixDomainServerSocket = CC("@mozilla.org/network/server-socket;1",
                                   "nsIServerSocket",
                                   "initWithFilename");
 
--- a/toolkit/devtools/server/transport.js
+++ b/toolkit/devtools/server/transport.js
@@ -1,18 +1,38 @@
 /* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ft=javascript ts=2 et sw=2 tw=80: */
 /* 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/. */
 
+// TODO: Get rid of this code once the marionette server loads transport.js as
+// an SDK module (see bug 1000814)
+(function (factory) { // Module boilerplate
+  if (this.module && module.id.indexOf("transport") >= 0) { // require
+    factory(require, exports);
+  } else { // loadSubScript
+    if (this.require) {
+      factory(require, this);
+    } else {
+      const Cu = Components.utils;
+      const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
+      factory(devtools.require, this);
+    }
+  }
+}).call(this, function (require, exports) {
+
 "use strict";
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
 
-let wantLogging = Services.prefs.getBoolPref("devtools.debugger.log");
+const { Cc, Ci, Cr, Cu } = require("chrome");
+const Services = require("Services");
+const DevToolsUtils = require("devtools/toolkit/DevToolsUtils");
+const { dumpn } = DevToolsUtils;
+
+Cu.import("resource://gre/modules/NetUtil.jsm");
 
 /**
  * An adapter that handles data transfers between the debugger client and
  * server. It can work with both nsIPipe and nsIServerSocket transports so
  * long as the properly created input and output streams are specified.
  * (However, for intra-process connections, LocalDebuggerTransport, below,
  * is more efficient than using an nsIPipe pair with DebuggerTransport.)
  *
@@ -38,17 +58,17 @@ let wantLogging = Services.prefs.getBool
  * - onClosed(status) - called when the connection is closed. |Status| is
  *   an nsresult, of the sort passed to nsIRequestObserver.
  *
  * Data is transferred as a JSON packet serialized into a string, with the
  * string length prepended to the packet, followed by a colon
  * ([length]:[packet]). The contents of the JSON packet are specified in
  * the Remote Debugging Protocol specification.
  */
-this.DebuggerTransport = function DebuggerTransport(aInput, aOutput)
+function DebuggerTransport(aInput, aOutput)
 {
   this._input = aInput;
   this._output = aOutput;
 
   this._converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
     .createInstance(Ci.nsIScriptableUnicodeConverter);
   this._converter.charset = "UTF-8";
 
@@ -93,17 +113,17 @@ DebuggerTransport.prototype = {
     }
   },
 
   onOutputStreamReady:
   DevToolsUtils.makeInfallible(function DT_onOutputStreamReady(aStream) {
     let written = 0;
     try {
       written = aStream.write(this._outgoing, this._outgoing.length);
-    } catch(e if e.result == Components.results.NS_BASE_STREAM_CLOSED) {
+    } catch(e if e.result == Cr.NS_BASE_STREAM_CLOSED) {
       dumpn("Connection closed.");
       this.close();
       return;
     }
     this._outgoing = this._outgoing.slice(written);
     this._flushOutgoing();
   }, "DebuggerTransport.prototype.onOutputStreamReady"),
 
@@ -185,45 +205,46 @@ DebuggerTransport.prototype = {
       let msg = "Error parsing incoming packet: " + packet + " (" + e + " - " + e.stack + ")";
       if (Cu.reportError) {
         Cu.reportError(msg);
       }
       dump(msg + "\n");
       return true;
     }
 
-    if (wantLogging) {
+    if (dumpn.wantLogging) {
       dumpn("Got: " + JSON.stringify(parsed, null, 2));
     }
     let self = this;
     Services.tm.currentThread.dispatch(DevToolsUtils.makeInfallible(function() {
       // Ensure the hooks are still around by the time this runs (they will go
       // away when the transport is closed).
       if (self.hooks) {
         self.hooks.onPacket(parsed);
       }
     }, "DebuggerTransport instance's this.hooks.onPacket"), 0);
 
     return true;
   }
 }
 
+exports.DebuggerTransport = DebuggerTransport;
 
 /**
  * An adapter that handles data transfers between the debugger client and
  * server when they both run in the same process. It presents the same API as
  * DebuggerTransport, but instead of transmitting serialized messages across a
  * connection it merely calls the packet dispatcher of the other side.
  *
  * @param aOther LocalDebuggerTransport
  *        The other endpoint for this debugger connection.
  *
  * @see DebuggerTransport
  */
-this.LocalDebuggerTransport = function LocalDebuggerTransport(aOther)
+function LocalDebuggerTransport(aOther)
 {
   this.other = aOther;
   this.hooks = null;
 
   /*
    * A packet number, shared between this and this.other. This isn't used
    * by the protocol at all, but it makes the packet traces a lot easier to
    * follow.
@@ -233,30 +254,30 @@ this.LocalDebuggerTransport = function L
 
 LocalDebuggerTransport.prototype = {
   /**
    * Transmit a message by directly calling the onPacket handler of the other
    * endpoint.
    */
   send: function LDT_send(aPacket) {
     let serial = this._serial.count++;
-    if (wantLogging) {
+    if (dumpn.wantLogging) {
       /* Check 'from' first, as 'echo' packets have both. */
       if (aPacket.from) {
         dumpn("Packet " + serial + " sent from " + uneval(aPacket.from));
       } else if (aPacket.to) {
         dumpn("Packet " + serial + " sent to " + uneval(aPacket.to));
       }
     }
     this._deepFreeze(aPacket);
     let other = this.other;
     if (other) {
       Services.tm.currentThread.dispatch(DevToolsUtils.makeInfallible(function() {
         // Avoid the cost of JSON.stringify() when logging is disabled.
-        if (wantLogging) {
+        if (dumpn.wantLogging) {
           dumpn("Received packet " + serial + ": " + JSON.stringify(aPacket, null, 2));
         }
         if (other.hooks) {
           other.hooks.onPacket(aPacket);
         }
       }, "LocalDebuggerTransport instance's this.other.hooks.onPacket"), 0);
     }
   },
@@ -271,17 +292,17 @@ LocalDebuggerTransport.prototype = {
       let other = this.other;
       this.other = null;
       other.close();
     }
     if (this.hooks) {
       try {
         this.hooks.onClosed();
       } catch(ex) {
-        Components.utils.reportError(ex);
+        Cu.reportError(ex);
       }
       this.hooks = null;
     }
   },
 
   /**
    * An empty method for emulating the DebuggerTransport API.
    */
@@ -300,32 +321,34 @@ LocalDebuggerTransport.prototype = {
       if (aObject.hasOwnProperty(prop) && typeof aObject === "object" &&
           !Object.isFrozen(aObject)) {
         this._deepFreeze(o[prop]);
       }
     }
   }
 };
 
+exports.LocalDebuggerTransport = LocalDebuggerTransport;
+
 /**
  * A transport for the debugging protocol that uses nsIMessageSenders to
  * exchange packets with servers running in child processes.
  *
  * In the parent process, |aSender| should be the nsIMessageSender for the
  * child process. In a child process, |aSender| should be the child process
  * message manager, which sends packets to the parent.
  *
  * aPrefix is a string included in the message names, to distinguish
  * multiple servers running in the same child process.
  *
  * This transport exchanges messages named 'debug:<prefix>:packet', where
  * <prefix> is |aPrefix|, whose data is the protocol packet.
  */
 function ChildDebuggerTransport(aSender, aPrefix) {
-  this._sender = aSender.QueryInterface(Components.interfaces.nsIMessageSender);
+  this._sender = aSender.QueryInterface(Ci.nsIMessageSender);
   this._messageName = "debug:" + aPrefix + ":packet";
 }
 
 /*
  * To avoid confusion, we use 'message' to mean something that
  * nsIMessageSender conveys, and 'packet' to mean a remote debugging
  * protocol packet.
  */
@@ -346,8 +369,12 @@ ChildDebuggerTransport.prototype = {
   receiveMessage: function ({data}) {
     this.hooks.onPacket(data);
   },
 
   send: function (packet) {
     this._sender.sendAsyncMessage(this._messageName, packet);
   }
 };
+
+exports.ChildDebuggerTransport = ChildDebuggerTransport;
+
+});