1. Satyr Murky
  2. Ubiquity

Commits

Satyr Murky  committed 57be61b

Removed some unused files.

  • Participants
  • Parent commits 93f6b41
  • Branches default

Comments (0)

Files changed (57)

File components/Makefile.in

-DEPTH		= ../../..
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-DIRS = public src
-
-XPI_NAME = ubiquity
-INSTALL_EXTENSION_ID = ubiquity-components@labs.mozilla.com
-XPI_PKGNAME = ubiquity-components
-
-DIST_FILES = install.rdf
-
-include $(topsrcdir)/config/rules.mk

File components/install.rdf

-<?xml version="1.0"?>
-
-<!-- This isn't the install.rdf for a 'real' extension; it's just
-     a placeholder so that the Mozilla build system will generate
-     an XPI that we can pull binary XPCOM components out of.  --> 
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-     xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-  <Description about="urn:mozilla:install-manifest">
-    <em:id>ubiquity-components@labs.mozilla.com</em:id>
-    <em:version>0.1.2</em:version>
-    <em:type>2</em:type>
-
-    <!-- Target Application this extension can install into, 
-         with minimum and maximum supported versions. --> 
-    <em:targetApplication>
-      <Description>
-        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
-        <em:minVersion>3.0</em:minVersion>
-        <em:maxVersion>3.1.*</em:maxVersion>
-      </Description>
-    </em:targetApplication>
-   
-    <!-- Front End MetaData -->
-    <em:name>Ubiquity Components</em:name>
-    <em:description>Binary XPCOM components for Ubiquity</em:description>
-    <em:creator>Mozilla Corporation</em:creator>
-  </Description>
-</RDF>

File components/public/Makefile.in

-DEPTH   = ../../../..
-topsrcdir = @top_srcdir@
-srcdir    = @srcdir@
-VPATH   = @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MODULE = ubiquity
-XPIDL_MODULE  = ubiquity
-
-XPI_NAME = ubiquity
-
-XPIDLSRCS = nsIUbiquityDesktopIntegration.idl \
-            $(NULL)
-
-include $(topsrcdir)/config/rules.mk

File components/public/nsIUbiquityDesktopIntegration.idl

-#include "nsISupports.idl"
-
-[scriptable, uuid(0ad2b8aa-f4cd-11dd-abef-b07a56d89593)]
-interface nsIUbiquityDesktopIntegration : nsISupports
-{
-  void registerGlobalHotkey(in long keyCode,
-                            in long modifiers);
-
-  void unregisterGlobalHotkey();
-
-  void bringAppToForeground();
-
-  void deactivateApp();
-
-  void hideApp();
-
-  void unhideAppWithoutActivation();
-
-  void isAppActive(out boolean isActive);
-
-  void switchToLastApp();
-
-  void clickAt(in long x,
-               in long y);
-};

File components/src/Makefile.in

-DEPTH   = ../../../..
-topsrcdir = @top_srcdir@
-srcdir    = @srcdir@
-VPATH   = @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-IS_COMPONENT = 1
-MODULE = ubiquity
-LIBRARY_NAME = ubiquity
-USE_STATIC_LIBS = 1
-#FORCE_SHARED_LIB = 1
-#FORCE_USE_PIC = 1
-
-XPI_NAME = ubiquity
-
-REQUIRES	= \
-		  $(NULL)
-
-CPPSRCS = ubiquitymodule.cpp \
-          $(NULL)
-
-ifeq ($(OS_ARCH),Darwin)
-CMMSRCS = nsUbiquityDesktopIntegration.mm \
-          $(NULL)
-endif
-
-include $(topsrcdir)/config/rules.mk
-
-EXTRA_DSO_LDOPTS += \
-    $(XPCOM_GLUE_LDOPTS) \
-    $(NSPR_LIBS) \
-    $(NULL)
-
-ifeq ($(OS_ARCH),Darwin)
-LDFLAGS += \
-        -framework Carbon \
-        -framework AppKit \
-        -framework ApplicationServices \
-        $(NULL)
-endif
-
-clobber::
-	rm -f $(DIST)/lib/$(LIBRARY_NAME).lib

File components/src/nsUbiquityDesktopIntegration.h

-#include "nsIUbiquityDesktopIntegration.h"
-
-#define NSUBIQUITYDI_CONTRACTID "@labs.mozilla.com/ubiquitydi;1"
-#define NSUBIQUITYDI_CLASSNAME "nsUbiquityDesktopIntegration"
-#define NSUBIQUITYDI_CID \
-  {0xd7c743dd, 0x34b0, 0x4290, \
-    { 0xb2, 0x13, 0xa3, 0xb6, 0x1d, 0x2b, 0x9f, 0x9b }}
-
-class nsUbiquityDesktopIntegration : public nsIUbiquityDesktopIntegration
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIUBIQUITYDESKTOPINTEGRATION
-
-  nsUbiquityDesktopIntegration();
-
-private:
-  ~nsUbiquityDesktopIntegration();
-
-protected:
-  /* additional members */
-};

File components/src/nsUbiquityDesktopIntegration.mm

-#include <Carbon/Carbon.h>
-#include <AppKit/NSApplication.h>
-#include <ApplicationServices/ApplicationServices.h>
-
-#include "nsServiceManagerUtils.h"
-#include "nsStringAPI.h"
-#include "nsIObserverService.h"
-#include "nsUbiquityDesktopIntegration.h"
-
-NS_IMPL_ISUPPORTS1(nsUbiquityDesktopIntegration,
-                   nsIUbiquityDesktopIntegration)
-
-static nsISupports *gSingleton;
-static EventHotKeyRef gMyHotKeyRef;
-static EventHotKeyID gMyHotKeyID;
-static EventHandlerRef gEventHandlerRef;
-
-// TODO: This class should really be a singleton that's accessed
-// through the service manager.
-
-nsUbiquityDesktopIntegration::nsUbiquityDesktopIntegration()
-{
-  /* member initializers and constructor code */
-}
-
-nsUbiquityDesktopIntegration::~nsUbiquityDesktopIntegration()
-{
-  /* destructor code */
-}
-
-// This is called by the operating system in what I believe is the 
-// main thread of Firefox, which I believe is also the UI thread.
-// Hopefully it's ok to use XPCOM here--in any case, Firefox doesn't
-// crash when we use it, so we're hopefully doing everything right!
-// - A.V.
-static OSStatus HotKeyHandler(EventHandlerCallRef nextHandler,
-                              EventRef theEvent,
-                              void *userData) {
-  nsresult rv;
-  nsCOMPtr<nsIObserverService>                                        \
-      obSvc(do_GetService(NS_OBSERVERSERVICE_CONTRACTID, &rv));
-
-  // TODO: Do something?
-  if (NS_FAILED(rv)) {};
-
-  rv = obSvc->NotifyObservers(gSingleton,
-                              "ubiquity:hotkey",
-                              NS_LITERAL_STRING("keypress").get());
-
-  // TODO: Do something?
-  if (NS_FAILED(rv)) {}
-
-  return noErr;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::RegisterGlobalHotkey(
-  PRInt32 keyCode,
-  PRInt32 modifiers
-  )
-{
-  if (gSingleton)
-    return NS_ERROR_FAILURE;
-
-  OSStatus result;
-
-  EventTypeSpec eventType;
-  eventType.eventClass=kEventClassKeyboard;
-  eventType.eventKind=kEventHotKeyPressed;
-  result = InstallEventHandler(GetApplicationEventTarget(),
-                               &HotKeyHandler,
-                               1,
-                               &eventType,
-                               NULL,
-                               &gEventHandlerRef);
-  if (result != noErr)
-    return NS_ERROR_FAILURE;
-
-  gMyHotKeyID.signature='htk1';
-  gMyHotKeyID.id=1;
-  result = RegisterEventHotKey(keyCode, modifiers, gMyHotKeyID, 
-                               GetApplicationEventTarget(), 0,
-                               &gMyHotKeyRef);
-  if (result != noErr) {
-    RemoveEventHandler(gEventHandlerRef);
-    return NS_ERROR_FAILURE;
-  }
-
-  this->AddRef();
-  gSingleton = this;
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::UnregisterGlobalHotkey()
-{
-  if (!gSingleton)
-    return NS_ERROR_FAILURE;
-
-  gSingleton = NULL;
-  this->Release();
-  if (UnregisterEventHotKey(gMyHotKeyRef) != noErr)
-    return NS_ERROR_FAILURE;
-  if (RemoveEventHandler(gEventHandlerRef) != noErr)
-    return NS_ERROR_FAILURE;
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::BringAppToForeground()
-{
-  NSApplication *sharedApp = [NSApplication sharedApplication];
-  [sharedApp activateIgnoringOtherApps: YES];
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::DeactivateApp()
-{
-  NSApplication *sharedApp = [NSApplication sharedApplication];
-  [sharedApp deactivate];
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::HideApp()
-{
-  NSApplication *sharedApp = [NSApplication sharedApplication];
-  [sharedApp hide: sharedApp];
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::UnhideAppWithoutActivation()
-{
-  NSApplication *sharedApp = [NSApplication sharedApplication];
-  [sharedApp unhideWithoutActivation];
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::IsAppActive(PRBool *isActive)
-{
-  NSApplication *sharedApp = [NSApplication sharedApplication];
-  *isActive = [sharedApp isActive];
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::SwitchToLastApp()
-{
-  // Simulate the pressing of alt-tab.
-
-  CGEventRef events[2];
-  events[0] = CGEventCreateKeyboardEvent(NULL, (CGKeyCode) 48, true);
-  if (events[0] == NULL)
-    return NS_ERROR_FAILURE;
-  CGEventSetFlags(events[0], kCGEventFlagMaskCommand);
-
-  events[1] = CGEventCreateKeyboardEvent(NULL, (CGKeyCode) 48, false);
-  if (events[1] == NULL)
-    return NS_ERROR_FAILURE;
-  CGEventSetFlags(events[1], kCGEventFlagMaskCommand);
-
-  CGEventTapLocation loc = kCGHIDEventTap;
-  CGEventPost(loc, events[0]);
-  CGEventPost(loc, events[1]);
-
-  CFRelease(events[0]);
-  CFRelease(events[1]);
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsUbiquityDesktopIntegration::ClickAt(PRInt32 x,
-                                                    PRInt32 y)
-{
-  // Simulate a mouse click.
-
-  CGPoint point;
-  point.x = 5;
-  point.y = 30;
-  CGEventRef events[2];
-  events[0] = CGEventCreateMouseEvent(
-    NULL,
-    kCGEventLeftMouseDown,
-    point,
-    NULL
-    );
-  if (events[0] == NULL)
-    return NS_ERROR_FAILURE;
-  CGEventSetFlags(events[0], 0);
-
-  events[1] = CGEventCreateMouseEvent(
-    NULL,
-    kCGEventLeftMouseUp,
-    point,
-    NULL
-    );
-  if (events[1] == NULL)
-    return NS_ERROR_FAILURE;
-  CGEventSetFlags(events[1], 0);
-
-  CGEventTapLocation loc = kCGHIDEventTap;
-  CGEventPost(loc, events[0]);
-  CGEventPost(loc, events[1]);
-
-  CFRelease(events[0]);
-  CFRelease(events[1]);
-  return NS_OK;
-}

File components/src/ubiquitymodule.cpp

-#include "nsIGenericFactory.h"
-
-#if XP_MACOSX
-#include "nsUbiquityDesktopIntegration.h"
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsUbiquityDesktopIntegration)
-#endif
-
-static nsModuleComponentInfo components[] =
-{
-#if XP_MACOSX
-    {
-        NSUBIQUITYDI_CLASSNAME,
-        NSUBIQUITYDI_CID,
-        NSUBIQUITYDI_CONTRACTID,
-        nsUbiquityDesktopIntegrationConstructor,
-    }
-#endif
-};
-
-NS_IMPL_NSGETMODULE("nsUbiquityModule", components)

File get_xpcom_info.js

-var xulr = Components.classes["@mozilla.org/xre/app-info;1"]
-                     .getService(Components.interfaces.nsIXULRuntime);
-
-dump(xulr.OS + "\n");
-dump(xulr.XPCOMABI + "\n");

File python-modules/jsbridge/__init__.py

-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-# 
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-# 
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-# 
-# The Original Code is Mozilla Corporation Code.
-# 
-# The Initial Developer of the Original Code is
-# Mikeal Rogers.
-# Portions created by the Initial Developer are Copyright (C) 2008 -2009
-# the Initial Developer. All Rights Reserved.
-# 
-# Contributor(s):
-#  Mikeal Rogers <mikeal.rogers@gmail.com>
-# 
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-# 
-# ***** END LICENSE BLOCK *****
-
-import socket
-import os
-import copy
-from time import sleep
-
-import mozrunner
-
-from network import Bridge, BackChannel, create_network
-from jsobjects import JSObject
-
-settings_env = 'JSBRIDGE_SETTINGS_FILE'
-
-parent = os.path.abspath(os.path.dirname(__file__))
-extension_path = os.path.join(parent, 'extension')
-
-window_string = "Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow('')"
-
-def wait_and_create_network(host, port, timeout=10):
-    ttl = 0
-    while ttl < timeout:
-        sleep(.25)
-        try:
-            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-            s.connect((host, port))
-            s.close()
-            break
-        except socket.error:
-            pass
-    return create_network(host, port)
-
-class CLI(mozrunner.CLI):
-    
-    parser_options = copy.copy(mozrunner.CLI.parser_options)
-    parser_options[('-D', '--debug',)] = dict(dest="debug", 
-                                             action="store_true",
-                                             help="Install debugging plugins.", 
-                                             metavar="JSBRIDGE_DEBUG",
-                                             default=False )
-    parser_options[('-s', '--shell',)] = dict(dest="shell", 
-                                             action="store_true",
-                                             help="Start a Python shell",
-                                             metavar="JSBRIDGE_SHELL",
-                                             default=False )
-    parser_options[('-u', '--usecode',)] = dict(dest="usecode", action="store_true",
-                                               help="Use code module instead of iPython",
-                                               default=False)
-    parser_options[('-P', '--port')] = dict(dest="port", default="24242",
-                                            help="TCP port to run jsbridge on.")
-    
-    debug_plugins = [os.path.join(parent, 'xpi', 'xush-0.2-fx.xpi')]
-    
-    def get_profile(self, *args, **kwargs):
-        if self.options.debug:
-            kwargs.setdefault('preferences', 
-                              {}).update({'extensions.checkCompatibility':False})
-        profile = super(CLI, self).get_profile(*args, **kwargs)
-        profile.install_plugin(extension_path)
-        if self.options.debug:
-            for p in self.debug_plugins:
-                profile.install_plugin(p)
-        return profile
-        
-    def get_runner(self, *args, **kwargs):
-        runner = super(CLI, self).get_runner(*args, **kwargs)
-        if self.options.debug:
-            runner.cmdargs.append('-jsconsole')
-        runner.cmdargs += ['-jsbridge', self.options.port]
-        return runner
-        
-    def run(self):
-        runner = self.parse_and_get_runner()
-        runner.start()
-        self.start_jsbridge_network()
-        if self.options.shell:
-            self.start_shell(runner)
-        else:
-            try:
-                runner.wait()
-            except KeyboardInterrupt:
-                runner.stop()
-                
-        runner.profile.cleanup()
-    
-    def start_shell(self, runner):
-        try:
-            import IPython
-        except:
-            IPython = None
-        jsobj = JSObject(self.bridge, window_string)
-        
-        if IPython is None or self.options.usecode:
-            import code
-            code.interact(local={"jsobj":jsobj, 
-                                 "getBrowserWindow":lambda : getBrowserWindow(self.bridge),
-                                 "back_channel":self.back_channel,
-                                 })
-        else:
-            from IPython.Shell import IPShellEmbed
-            ipshell = IPShellEmbed([])
-            ipshell(local_ns={"jsobj":jsobj, 
-                              "getBrowserWindow":lambda : getBrowserWindow(self.bridge),
-                              "back_channel":self.back_channel,
-                              })
-        runner.stop()
-        
-    def start_jsbridge_network(self, timeout=10):
-        port = int(self.options.port)
-        host = '127.0.0.1'
-        self.back_channel, self.bridge = wait_and_create_network(host, port, timeout)
-
-def cli():
-    CLI().run()
-
-def getBrowserWindow(bridge):
-    return JSObject(bridge, "Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow('')")
-    
-
-
-
-
-
-

File python-modules/jsbridge/extension/chrome.manifest

-resource jsbridge resource/
-
-content jsbridge chrome/content/
-
-overlay chrome://browser/content/browser.xul chrome://jsbridge/content/overlay.xul
-overlay chrome://messenger/content/mailWindowOverlay.xul chrome://jsbridge/content/overlay.xul
-
-overlay chrome://calendar/content/calendar.xul chrome://jsbridge/content/overlay.xul
-
-overlay windowtype:Songbird:Main chrome://jsbridge/content/overlay.xul

File python-modules/jsbridge/extension/chrome/content/overlay.js

-// ***** BEGIN LICENSE BLOCK *****
-// Version: MPL 1.1/GPL 2.0/LGPL 2.1
-// 
-// The contents of this file are subject to the Mozilla Public License Version
-// 1.1 (the "License"); you may not use this file except in compliance with
-// the License. You may obtain a copy of the License at
-// http://www.mozilla.org/MPL/
-// 
-// Software distributed under the License is distributed on an "AS IS" basis,
-// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-// for the specific language governing rights and limitations under the
-// License.
-// 
-// The Original Code is Mozilla Corporation Code.
-// 
-// The Initial Developer of the Original Code is
-// Mikeal Rogers.
-// Portions created by the Initial Developer are Copyright (C) 2008
-// the Initial Developer. All Rights Reserved.
-// 
-// Contributor(s):
-//  Mikeal Rogers <mikeal.rogers@gmail.com>
-// 
-// Alternatively, the contents of this file may be used under the terms of
-// either the GNU General Public License Version 2 or later (the "GPL"), or
-// the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-// in which case the provisions of the GPL or the LGPL are applicable instead
-// of those above. If you wish to allow use of your version of this file only
-// under the terms of either the GPL or the LGPL, and not to allow others to
-// use your version of this file under the terms of the MPL, indicate your
-// decision by deleting the provisions above and replace them with the notice
-// and other provisions required by the GPL or the LGPL. If you do not delete
-// the provisions above, a recipient may use your version of this file under
-// the terms of any one of the MPL, the GPL or the LGPL.
-// 
-// ***** END LICENSE BLOCK *****
-
-var __init = {}; Components.utils.import('resource://jsbridge/modules/init.js', __init);
-
-

File python-modules/jsbridge/extension/chrome/content/overlay.xul

-<?xml version="1.0"?>
-<overlay id="jsbridge-overlay"
-         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-  <script src="overlay.js"/>
-</overlay>

File python-modules/jsbridge/extension/components/cmdarg.js

-const nsIAppShellService    = Components.interfaces.nsIAppShellService;
-const nsISupports           = Components.interfaces.nsISupports;
-const nsICategoryManager    = Components.interfaces.nsICategoryManager;
-const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
-const nsICommandLine        = Components.interfaces.nsICommandLine;
-const nsICommandLineHandler = Components.interfaces.nsICommandLineHandler;
-const nsIFactory            = Components.interfaces.nsIFactory;
-const nsIModule             = Components.interfaces.nsIModule;
-const nsIWindowWatcher      = Components.interfaces.nsIWindowWatcher;
-
-// CHANGEME: to the chrome URI of your extension or application
-const CHROME_URI = "chrome://jsbridge/content/";
-
-// CHANGEME: change the contract id, CID, and category to be unique
-// to your application.
-const clh_contractID = "@mozilla.org/commandlinehandler/general-startup;1?type=jsbridge";
-
-// use uuidgen to generate a unique ID
-const clh_CID = Components.ID("{2872d428-14f6-11de-ac86-001f5bd9235c}");
-
-// category names are sorted alphabetically. Typical command-line handlers use a
-// category that begins with the letter "m".
-const clh_category = "jsbridge";
-
-var aConsoleService = Components.classes["@mozilla.org/consoleservice;1"].
-     getService(Components.interfaces.nsIConsoleService);
-
-/**
- * Utility functions
- */
-
-/**
- * Opens a chrome window.
- * @param aChromeURISpec a string specifying the URI of the window to open.
- * @param aArgument an argument to pass to the window (may be null)
- */
-function openWindow(aChromeURISpec, aArgument)
-{
-  var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
-    getService(Components.interfaces.nsIWindowWatcher);
-  ww.openWindow(null, aChromeURISpec, "_blank",
-                "chrome,menubar,toolbar,status,resizable,dialog=no",
-                aArgument);
-}
- 
-/**
- * The XPCOM component that implements nsICommandLineHandler.
- * It also implements nsIFactory to serve as its own singleton factory.
- */
-const jsbridgeHandler = {
-  /* nsISupports */
-  QueryInterface : function clh_QI(iid)
-  {
-    if (iid.equals(nsICommandLineHandler) ||
-        iid.equals(nsIFactory) ||
-        iid.equals(nsISupports))
-      return this;
-
-    throw Components.results.NS_ERROR_NO_INTERFACE;
-  },
-
-  /* nsICommandLineHandler */
-
-  handle : function clh_handle(cmdLine)
-  {
-    try {
-      var port = cmdLine.handleFlagWithParam("jsbridge", false);
-      if (port) {
-        var server = {}; 
-        Components.utils.import('resource://jsbridge/modules/server.js', server);
-        server.startServer(parseInt(port));
-        // dump(port);
-      } else {
-        var server = {}; 
-        Components.utils.import('resource://jsbridge/modules/server.js', server);
-        server.startServer(24242);
-      }
-    }
-    catch (e) {
-      Components.utils.reportError("incorrect parameter passed to -jsbridge on the command line.");
-    }
-
-  },
-
-  // CHANGEME: change the help info as appropriate, but
-  // follow the guidelines in nsICommandLineHandler.idl
-  // specifically, flag descriptions should start at
-  // character 24, and lines should be wrapped at
-  // 72 characters with embedded newlines,
-  // and finally, the string should end with a newline
-  helpInfo : "  -jsbridge            Port to run jsbridge on.\n",
-
-  /* nsIFactory */
-
-  createInstance : function clh_CI(outer, iid)
-  {
-    if (outer != null)
-      throw Components.results.NS_ERROR_NO_AGGREGATION;
-
-    return this.QueryInterface(iid);
-  },
-
-  lockFactory : function clh_lock(lock)
-  {
-    /* no-op */
-  }
-};
-
-/**
- * The XPCOM glue that implements nsIModule
- */
-const jsbridgeHandlerModule = {
-  /* nsISupports */
-  QueryInterface : function mod_QI(iid)
-  {
-    if (iid.equals(nsIModule) ||
-        iid.equals(nsISupports))
-      return this;
-
-    throw Components.results.NS_ERROR_NO_INTERFACE;
-  },
-
-  /* nsIModule */
-  getClassObject : function mod_gch(compMgr, cid, iid)
-  {
-    if (cid.equals(clh_CID))
-      return jsbridgeHandler.QueryInterface(iid);
-
-    throw Components.results.NS_ERROR_NOT_REGISTERED;
-  },
-
-  registerSelf : function mod_regself(compMgr, fileSpec, location, type)
-  {
-    compMgr.QueryInterface(nsIComponentRegistrar);
-
-    compMgr.registerFactoryLocation(clh_CID,
-                                    "jsbridgeHandler",
-                                    clh_contractID,
-                                    fileSpec,
-                                    location,
-                                    type);
-
-    var catMan = Components.classes["@mozilla.org/categorymanager;1"].
-      getService(nsICategoryManager);
-    catMan.addCategoryEntry("command-line-handler",
-                            clh_category,
-                            clh_contractID, true, true);
-  },
-
-  unregisterSelf : function mod_unreg(compMgr, location, type)
-  {
-    compMgr.QueryInterface(nsIComponentRegistrar);
-    compMgr.unregisterFactoryLocation(clh_CID, location);
-
-    var catMan = Components.classes["@mozilla.org/categorymanager;1"].
-      getService(nsICategoryManager);
-    catMan.deleteCategoryEntry("command-line-handler", clh_category);
-  },
-
-  canUnload : function (compMgr)
-  {
-    return true;
-  }
-};
-
-/* The NSGetModule function is the magic entry point that XPCOM uses to find what XPCOM objects
- * this component provides
- */
-function NSGetModule(comMgr, fileSpec)
-{
-  return jsbridgeHandlerModule;
-}

File python-modules/jsbridge/extension/install.rdf

-<?xml version="1.0"?>
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-     xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-   <Description about="urn:mozilla:install-manifest">
-     <em:id>jsbridge@mozilla.com</em:id>
-     <em:name>jsbridge</em:name>
-     <em:version>1.0</em:version>
-     <em:creator>Mikeal Rogers</em:creator>
-     <em:description>Python to JavaScript bridge</em:description>
-     <em:targetApplication>
-       <!-- Firefox -->
-       <Description>
-         <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
-         <em:minVersion>1.5</em:minVersion>
-         <em:maxVersion>3.6a1pre</em:maxVersion>
-       </Description>
-     </em:targetApplication>
-     <em:targetApplication>
-       <!-- Thunderbird -->
-       <Description>
-         <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id>
-         <em:minVersion>3*</em:minVersion>
-         <em:maxVersion>3.*</em:maxVersion>
-       </Description>
-     </em:targetApplication>
-     <em:targetApplication>
-       <!-- Sunbird -->
-       <Description>
-         <em:id>{718e30fb-e89b-41dd-9da7-e25a45638b28}</em:id>
-         <em:minVersion>0.6a1</em:minVersion>
-         <em:maxVersion>1.0pre</em:maxVersion>
-       </Description>
-     </em:targetApplication>
-	   <em:targetApplication>
-	      <!-- Songbird -->
-	      <Description>
-	        <em:id>songbird@songbirdnest.com</em:id>
-	        <em:minVersion>0.3pre</em:minVersion>
-	        <em:maxVersion>1.0.*</em:maxVersion>
-	      </Description>
-	   </em:targetApplication>
-	   <em:targetApplication>
-         <Description>
-          <em:id>toolkit@mozilla.org</em:id>
-          <em:minVersion>1.9</em:minVersion>
-          <em:maxVersion>1.9.*</em:maxVersion>
-         </Description>
-     </em:targetApplication>
-   </Description>
-
-
-</RDF>

File python-modules/jsbridge/extension/resource/modules/events.js

-var EXPORTED_SYMBOLS = ["backchannels", "fireEvent", "addBackChannel"];
-
-var backchannels = [];
-
-var fireEvent = function (name, obj) {
-  for each(backchannel in backchannels) {
-    backchannel.session.encodeOut({'eventType':name, 'result':obj});
-  }
-}
-
-var addBackChannel = function (backchannel) {
-    backchannels.push(backchannel);
-}

File python-modules/jsbridge/extension/resource/modules/init.js

-// ***** BEGIN LICENSE BLOCK *****
-// Version: MPL 1.1/GPL 2.0/LGPL 2.1
-// 
-// The contents of this file are subject to the Mozilla Public License Version
-// 1.1 (the "License"); you may not use this file except in compliance with
-// the License. You may obtain a copy of the License at
-// http://www.mozilla.org/MPL/
-// 
-// Software distributed under the License is distributed on an "AS IS" basis,
-// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-// for the specific language governing rights and limitations under the
-// License.
-// 
-// The Original Code is Mozilla Corporation Code.
-// 
-// The Initial Developer of the Original Code is
-// Mikeal Rogers.
-// Portions created by the Initial Developer are Copyright (C) 2008
-// the Initial Developer. All Rights Reserved.
-// 
-// Contributor(s):
-//  Mikeal Rogers <mikeal.rogers@gmail.com>
-// 
-// Alternatively, the contents of this file may be used under the terms of
-// either the GNU General Public License Version 2 or later (the "GPL"), or
-// the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-// in which case the provisions of the GPL or the LGPL are applicable instead
-// of those above. If you wish to allow use of your version of this file only
-// under the terms of either the GPL or the LGPL, and not to allow others to
-// use your version of this file under the terms of the MPL, indicate your
-// decision by deleting the provisions above and replace them with the notice
-// and other provisions required by the GPL or the LGPL. If you do not delete
-// the provisions above, a recipient may use your version of this file under
-// the terms of any one of the MPL, the GPL or the LGPL.
-// 
-// ***** END LICENSE BLOCK *****
-
-var EXPORTED_SYMBOLS = ["server"];
-
-var server = {}; Components.utils.import('resource://jsbridge/modules/server.js', server);

File python-modules/jsbridge/extension/resource/modules/json2.js

-/*
-    http://www.JSON.org/json2.js
-    2008-05-25
-
-    Public Domain.
-
-    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
-
-    See http://www.JSON.org/js.html
-
-    This file creates a global JSON object containing two methods: stringify
-    and parse.
-
-        JSON.stringify(value, replacer, space)
-            value       any JavaScript value, usually an object or array.
-
-            replacer    an optional parameter that determines how object
-                        values are stringified for objects without a toJSON
-                        method. It can be a function or an array.
-
-            space       an optional parameter that specifies the indentation
-                        of nested structures. If it is omitted, the text will
-                        be packed without extra whitespace. If it is a number,
-                        it will specify the number of spaces to indent at each
-                        level. If it is a string (such as '\t' or '&nbsp;'),
-                        it contains the characters used to indent at each level.
-
-            This method produces a JSON text from a JavaScript value.
-
-            When an object value is found, if the object contains a toJSON
-            method, its toJSON method will be called and the result will be
-            stringified. A toJSON method does not serialize: it returns the
-            value represented by the name/value pair that should be serialized,
-            or undefined if nothing should be serialized. The toJSON method
-            will be passed the key associated with the value, and this will be
-            bound to the object holding the key.
-
-            For example, this would serialize Dates as ISO strings.
-
-                Date.prototype.toJSON = function (key) {
-                    function f(n) {
-                        // Format integers to have at least two digits.
-                        return n < 10 ? '0' + n : n;
-                    }
-
-                    return this.getUTCFullYear()   + '-' +
-                         f(this.getUTCMonth() + 1) + '-' +
-                         f(this.getUTCDate())      + 'T' +
-                         f(this.getUTCHours())     + ':' +
-                         f(this.getUTCMinutes())   + ':' +
-                         f(this.getUTCSeconds())   + 'Z';
-                };
-
-            You can provide an optional replacer method. It will be passed the
-            key and value of each member, with this bound to the containing
-            object. The value that is returned from your method will be
-            serialized. If your method returns undefined, then the member will
-            be excluded from the serialization.
-
-            If the replacer parameter is an array, then it will be used to
-            select the members to be serialized. It filters the results such
-            that only members with keys listed in the replacer array are
-            stringified.
-
-            Values that do not have JSON representations, such as undefined or
-            functions, will not be serialized. Such values in objects will be
-            dropped; in arrays they will be replaced with null. You can use
-            a replacer function to replace those with JSON values.
-            JSON.stringify(undefined) returns undefined.
-
-            The optional space parameter produces a stringification of the
-            value that is filled with line breaks and indentation to make it
-            easier to read.
-
-            If the space parameter is a non-empty string, then that string will
-            be used for indentation. If the space parameter is a number, then
-            the indentation will be that many spaces.
-
-            Example:
-
-            text = JSON.stringify(['e', {pluribus: 'unum'}]);
-            // text is '["e",{"pluribus":"unum"}]'
-
-
-            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
-            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
-
-            text = JSON.stringify([new Date()], function (key, value) {
-                return this[key] instanceof Date ?
-                    'Date(' + this[key] + ')' : value;
-            });
-            // text is '["Date(---current time---)"]'
-
-
-        JSON.parse(text, reviver)
-            This method parses a JSON text to produce an object or array.
-            It can throw a SyntaxError exception.
-
-            The optional reviver parameter is a function that can filter and
-            transform the results. It receives each of the keys and values,
-            and its return value is used instead of the original value.
-            If it returns what it received, then the structure is not modified.
-            If it returns undefined then the member is deleted.
-
-            Example:
-
-            // Parse the text. Values that look like ISO date strings will
-            // be converted to Date objects.
-
-            myData = JSON.parse(text, function (key, value) {
-                var a;
-                if (typeof value === 'string') {
-                    a =
-/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
-                    if (a) {
-                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
-                            +a[5], +a[6]));
-                    }
-                }
-                return value;
-            });
-
-            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
-                var d;
-                if (typeof value === 'string' &&
-                        value.slice(0, 5) === 'Date(' &&
-                        value.slice(-1) === ')') {
-                    d = new Date(value.slice(5, -1));
-                    if (d) {
-                        return d;
-                    }
-                }
-                return value;
-            });
-
-
-    This is a reference implementation. You are free to copy, modify, or
-    redistribute.
-
-    This code should be minified before deployment.
-    See http://javascript.crockford.com/jsmin.html
-
-    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
-    NOT CONTROL.
-*/
-
-/*jslint evil: true */
-
-/*global JSON */
-
-/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", call,
-    charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
-    getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length,
-    parse, propertyIsEnumerable, prototype, push, replace, slice, stringify,
-    test, toJSON, toString
-*/
-
-var EXPORTED_SYMBOLS = ["JSON"];
-
-if (!this.JSON) {
-
-// Create a JSON object only if one does not already exist. We create the
-// object in a closure to avoid creating global variables.
-
-    JSON = function () {
-
-        function f(n) {
-            // Format integers to have at least two digits.
-            return n < 10 ? '0' + n : n;
-        }
-
-        Date.prototype.toJSON = function (key) {
-
-            return this.getUTCFullYear()   + '-' +
-                 f(this.getUTCMonth() + 1) + '-' +
-                 f(this.getUTCDate())      + 'T' +
-                 f(this.getUTCHours())     + ':' +
-                 f(this.getUTCMinutes())   + ':' +
-                 f(this.getUTCSeconds())   + 'Z';
-        };
-
-        var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
-            escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
-            gap,
-            indent,
-            meta = {    // table of character substitutions
-                '\b': '\\b',
-                '\t': '\\t',
-                '\n': '\\n',
-                '\f': '\\f',
-                '\r': '\\r',
-                '"' : '\\"',
-                '\\': '\\\\'
-            },
-            rep;
-
-
-        function quote(string) {
-
-// If the string contains no control characters, no quote characters, and no
-// backslash characters, then we can safely slap some quotes around it.
-// Otherwise we must also replace the offending characters with safe escape
-// sequences.
-
-            escapeable.lastIndex = 0;
-            return escapeable.test(string) ?
-                '"' + string.replace(escapeable, function (a) {
-                    var c = meta[a];
-                    if (typeof c === 'string') {
-                        return c;
-                    }
-                    return '\\u' + ('0000' +
-                            (+(a.charCodeAt(0))).toString(16)).slice(-4);
-                }) + '"' :
-                '"' + string + '"';
-        }
-
-
-        function str(key, holder) {
-
-// Produce a string from holder[key].
-
-            var i,          // The loop counter.
-                k,          // The member key.
-                v,          // The member value.
-                length,
-                mind = gap,
-                partial,
-                value = holder[key];
-
-// If the value has a toJSON method, call it to obtain a replacement value.
-
-            if (value && typeof value === 'object' &&
-                    typeof value.toJSON === 'function') {
-                value = value.toJSON(key);
-            }
-
-// If we were called with a replacer function, then call the replacer to
-// obtain a replacement value.
-
-            if (typeof rep === 'function') {
-                value = rep.call(holder, key, value);
-            }
-
-// What happens next depends on the value's type.
-
-            switch (typeof value) {
-            case 'string':
-                return quote(value);
-
-            case 'number':
-
-// JSON numbers must be finite. Encode non-finite numbers as null.
-
-                return isFinite(value) ? String(value) : 'null';
-
-            case 'boolean':
-            case 'null':
-
-// If the value is a boolean or null, convert it to a string. Note:
-// typeof null does not produce 'null'. The case is included here in
-// the remote chance that this gets fixed someday.
-
-                return String(value);
-
-// If the type is 'object', we might be dealing with an object or an array or
-// null.
-
-            case 'object':
-
-// Due to a specification blunder in ECMAScript, typeof null is 'object',
-// so watch out for that case.
-
-                if (!value) {
-                    return 'null';
-                }
-
-// Make an array to hold the partial results of stringifying this object value.
-
-                gap += indent;
-                partial = [];
-
-// If the object has a dontEnum length property, we'll treat it as an array.
-
-                if (typeof value.length === 'number' &&
-                        !(value.propertyIsEnumerable('length'))) {
-
-// The object is an array. Stringify every element. Use null as a placeholder
-// for non-JSON values.
-
-                    length = value.length;
-                    for (i = 0; i < length; i += 1) {
-                        partial[i] = str(i, value) || 'null';
-                    }
-
-// Join all of the elements together, separated with commas, and wrap them in
-// brackets.
-
-                    v = partial.length === 0 ? '[]' :
-                        gap ? '[\n' + gap +
-                                partial.join(',\n' + gap) + '\n' +
-                                    mind + ']' :
-                              '[' + partial.join(',') + ']';
-                    gap = mind;
-                    return v;
-                }
-
-// If the replacer is an array, use it to select the members to be stringified.
-
-                if (rep && typeof rep === 'object') {
-                    length = rep.length;
-                    for (i = 0; i < length; i += 1) {
-                        k = rep[i];
-                        if (typeof k === 'string') {
-                            v = str(k, value, rep);
-                            if (v) {
-                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
-                            }
-                        }
-                    }
-                } else {
-
-// Otherwise, iterate through all of the keys in the object.
-
-                    for (k in value) {
-                        if (Object.hasOwnProperty.call(value, k)) {
-                            v = str(k, value, rep);
-                            if (v) {
-                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
-                            }
-                        }
-                    }
-                }
-
-// Join all of the member texts together, separated with commas,
-// and wrap them in braces.
-
-                v = partial.length === 0 ? '{}' :
-                    gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
-                            mind + '}' : '{' + partial.join(',') + '}';
-                gap = mind;
-                return v;
-            }
-        }
-
-// Return the JSON object containing the stringify and parse methods.
-
-        return {
-            stringify: function (value, replacer, space) {
-
-// The stringify method takes a value and an optional replacer, and an optional
-// space parameter, and returns a JSON text. The replacer can be a function
-// that can replace values, or an array of strings that will select the keys.
-// A default replacer method can be provided. Use of the space parameter can
-// produce text that is more easily readable.
-
-                var i;
-                gap = '';
-                indent = '';
-
-// If the space parameter is a number, make an indent string containing that
-// many spaces.
-
-                if (typeof space === 'number') {
-                    for (i = 0; i < space; i += 1) {
-                        indent += ' ';
-                    }
-
-// If the space parameter is a string, it will be used as the indent string.
-
-                } else if (typeof space === 'string') {
-                    indent = space;
-                }
-
-// If there is a replacer, it must be a function or an array.
-// Otherwise, throw an error.
-
-                rep = replacer;
-                if (replacer && typeof replacer !== 'function' &&
-                        (typeof replacer !== 'object' ||
-                         typeof replacer.length !== 'number')) {
-                    throw new Error('JSON.stringify');
-                }
-
-// Make a fake root object containing our value under the key of ''.
-// Return the result of stringifying the value.
-
-                return str('', {'': value});
-            },
-
-
-            parse: function (text, reviver) {
-
-// The parse method takes a text and an optional reviver function, and returns
-// a JavaScript value if the text is a valid JSON text.
-
-                var j;
-
-                function walk(holder, key) {
-
-// The walk method is used to recursively walk the resulting structure so
-// that modifications can be made.
-
-                    var k, v, value = holder[key];
-                    if (value && typeof value === 'object') {
-                        for (k in value) {
-                            if (Object.hasOwnProperty.call(value, k)) {
-                                v = walk(value, k);
-                                if (v !== undefined) {
-                                    value[k] = v;
-                                } else {
-                                    delete value[k];
-                                }
-                            }
-                        }
-                    }
-                    return reviver.call(holder, key, value);
-                }
-
-
-// Parsing happens in four stages. In the first stage, we replace certain
-// Unicode characters with escape sequences. JavaScript handles many characters
-// incorrectly, either silently deleting them, or treating them as line endings.
-
-                cx.lastIndex = 0;
-                if (cx.test(text)) {
-                    text = text.replace(cx, function (a) {
-                        return '\\u' + ('0000' +
-                                (+(a.charCodeAt(0))).toString(16)).slice(-4);
-                    });
-                }
-
-// In the second stage, we run the text against regular expressions that look
-// for non-JSON patterns. We are especially concerned with '()' and 'new'
-// because they can cause invocation, and '=' because it can cause mutation.
-// But just to be safe, we want to reject all unexpected forms.
-
-// We split the second stage into 4 regexp operations in order to work around
-// crippling inefficiencies in IE's and Safari's regexp engines. First we
-// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
-// replace all simple value tokens with ']' characters. Third, we delete all
-// open brackets that follow a colon or comma or that begin the text. Finally,
-// we look to see that the remaining characters are only whitespace or ']' or
-// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
-
-                if (/^[\],:{}\s]*$/.
-test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
-replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
-replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
-
-// In the third stage we use the eval function to compile the text into a
-// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
-// in JavaScript: it can begin a block or an object literal. We wrap the text
-// in parens to eliminate the ambiguity.
-
-                    j = eval('(' + text + ')');
-
-// In the optional fourth stage, we recursively walk the new structure, passing
-// each name/value pair to a reviver function for possible transformation.
-
-                    return typeof reviver === 'function' ?
-                        walk({'': j}, '') : j;
-                }
-
-// If the text is not JSON parseable, then a SyntaxError is thrown.
-
-                throw new SyntaxError('JSON.parse');
-            }
-        };
-    }();
-}

File python-modules/jsbridge/extension/resource/modules/server.js

-// ***** BEGIN LICENSE BLOCK *****
-// Version: MPL 1.1/GPL 2.0/LGPL 2.1
-// 
-// The contents of this file are subject to the Mozilla Public License Version
-// 1.1 (the "License"); you may not use this file except in compliance with
-// the License. You may obtain a copy of the License at
-// http://www.mozilla.org/MPL/
-// 
-// Software distributed under the License is distributed on an "AS IS" basis,
-// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-// for the specific language governing rights and limitations under the
-// License.
-// 
-// The Original Code is Mozilla Corporation Code.
-// 
-// The Initial Developer of the Original Code is
-// based on the MozRepl project.
-// Portions created by the Initial Developer are Copyright (C) 2008
-// the Initial Developer. All Rights Reserved.
-// 
-// Contributor(s):
-//  Mikeal Rogers <mikeal.rogers@gmail.com>
-//  Massimiliano Mirra <bard@hyperstruct.net>
-//
-// Alternatively, the contents of this file may be used under the terms of
-// either the GNU General Public License Version 2 or later (the "GPL"), or
-// the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-// in which case the provisions of the GPL or the LGPL are applicable instead
-// of those above. If you wish to allow use of your version of this file only
-// under the terms of either the GPL or the LGPL, and not to allow others to
-// use your version of this file under the terms of the MPL, indicate your
-// decision by deleting the provisions above and replace them with the notice
-// and other provisions required by the GPL or the LGPL. If you do not delete
-// the provisions above, a recipient may use your version of this file under
-// the terms of any one of the MPL, the GPL or the LGPL.
-// 
-// ***** END LICENSE BLOCK *****
-
-var EXPORTED_SYMBOLS = ["Server", "server", "AsyncRead", "Session", "sessions", "globalRegistry", "startServer"];
-
-var events = {}; Components.utils.import("resource://jsbridge/modules/events.js", events);
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const loader = Cc['@mozilla.org/moz/jssubscript-loader;1']
-    .getService(Ci.mozIJSSubScriptLoader);
-
-var hwindow = Components.classes["@mozilla.org/appshell/appShellService;1"]
-    .getService(Components.interfaces.nsIAppShellService)
-    .hiddenDOMWindow;
-    
-var nativeJSON = Components.classes["@mozilla.org/dom/json;1"]
-    .createInstance(Components.interfaces.nsIJSON);
-
-var json2 = Components.utils.import("resource://jsbridge/modules/json2.js");
-
-var jsonEncode = json2.JSON.stringify;    
-
-var uuidgen = Components.classes["@mozilla.org/uuid-generator;1"]
-    .getService(Components.interfaces.nsIUUIDGenerator);
-
-function AsyncRead (session) {
-  this.session = session;
-}
-AsyncRead.prototype.onStartRequest = function (request, context) {};
-AsyncRead.prototype.onStopRequest = function (request, context, status) {
-  this.session.onQuit();
-}
-AsyncRead.prototype.onDataAvailable = function (request, context, inputStream, offset, count) {
-  var str = {};
-  this.session.instream.readString(count, str);
-  this.session.receive(str.value);
-}
-
-
-
-globalRegistry = {};
-
-function Bridge (session) {
-  this.session = session;
-  this.registry = globalRegistry;
-}
-Bridge.prototype._register = function (_type) {
-  this.bridgeType = _type;
-  if (_type == "backchannel") {
-    events.addBackChannel(this);
-  }
-}
-Bridge.prototype.register = function (uuid, _type) {
-  try {
-    this._register(_type);
-    var passed = true;
-  } catch(e) {
-    if (typeof(e) == "string") {
-      var exception = e;
-    } else {
-      var exception = {'name':e.name, 'message':e.message};
-    }
-    this.session.encodeOut({'result':false, 'exception':exception, 'uuid':uuid});
-  }
-  if (passed != undefined) {
-    this.session.encodeOut({"result":true, 'eventType':'register', 'uuid':uuid});
-  }
-  
-}
-Bridge.prototype._describe = function (obj) {
-  var response = {};
-  if (obj == null) {
-    var type = "null";
-  } else {
-    var type = typeof(obj);
-  }
-  if (type == "object") {
-    if (obj.length != undefined) {
-      var type = "array";
-    }
-    response.attributes = [];
-    for (i in obj) {
-      response.attributes = response.attributes.concat(i);
-    }
-  }
-  else if (type != "function"){
-    response.data = obj;
-  }
-  response.type = type;
-  return response;
-}
-Bridge.prototype.describe = function (uuid, obj) {
-  var response = this._describe(obj);
-  response.uuid = uuid;
-  response.result = true;
-  this.session.encodeOut(response);
-}
-Bridge.prototype._set = function (obj) {
-  var uuid = uuidgen.generateUUID().toString();
-  this.registry[uuid] = obj;
-  return uuid;
-}
-Bridge.prototype.set = function (uuid, obj) {
-  var ruuid = this._set(obj);
-  this.session.encodeOut({'result':true, 'data':'bridge.registry["'+ruuid+'"]', 'uuid':uuid});
-}
-Bridge.prototype._setAttribute = function (obj, name, value) {
-  obj[name] = value;
-  return value;
-}
-Bridge.prototype.setAttribute = function (uuid, obj, name, value) {
-  // log(uuid, String(obj), name, String(value))
-  try {
-    var result = this._setAttribute(obj, name, value);
-  } catch(e) {
-    if (typeof(e) == "string") {
-      var exception = e;
-    } else {
-      var exception = {'name':e.name, 'message':e.message};
-    }
-    this.session.encodeOut({'result':false, 'exception':exception, 'uuid':uuid});
-  }
-  if (result != undefined) {
-    this.set(uuid, obj[name]);
-  }
-}
-Bridge.prototype._execFunction = function (func, args) {
-  return func.apply(this.session.sandbox, args);
-}
-Bridge.prototype.execFunction = function (uuid, func, args) {
-  try {
-    var data = this._execFunction(func, args);
-    var result = true;
-  } catch(e) {
-    if (typeof(e) == "string") {
-      var exception = e;
-    } else {
-      var exception = {'name':e.name, 'message':e.message};
-    }
-    this.session.encodeOut({'result':false, 'exception':exception, 'uuid':uuid});
-    var result = true;
-  }  
-  if (data != undefined) {
-    this.set(uuid, data);
-  } else if ( result == true) {
-    this.session.encodeOut({'result':true, 'data':null, 'uuid':uuid});
-  } else {
-    throw 'Something very bad happened.'
-  }
-}
-
-backstage = this;
-
-function Session (transport) {
-  this.transpart = transport;
-  this.sandbox = Components.utils.Sandbox(backstage);
-  this.sandbox.bridge = new Bridge(this);
-  this.sandbox.openPreferences = hwindow.openPreferences;
-  try {
-      this.outstream = transport.openOutputStream(Ci.nsITransport.OPEN_BLOCKING , 0, 0);
-      this.stream = transport.openInputStream(0, 0, 0);
-      this.instream = Cc['@mozilla.org/intl/converter-input-stream;1']
-          .createInstance(Ci.nsIConverterInputStream);
-      this.instream.init(this.stream, 'UTF-8', 1024,
-                    Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
-  } catch(e) {
-      log('jsbridge: Error: ' + e);
-  }
-  // log('jsbridge: Accepted connection.');
-  
-  this.pump = Cc['@mozilla.org/network/input-stream-pump;1']
-      .createInstance(Ci.nsIInputStreamPump);
-  this.pump.init(this.stream, -1, -1, 0, 0, false);
-  this.pump.asyncRead(new AsyncRead(this), null);
-}
-Session.prototype.onOutput = function(string) {
-  // log('jsbridge write: '+string)
-  if (typeof(string) != "string") {
-    throw "This is not a string"
-  } 
-  try {
-    this.outstream.write(string, string.length);
-  } catch (e) {
-    throw "Why is this failing "+string
-  }
-  // this.outstream.write(string, string.length);
-};
-Session.prototype.onQuit = function() {
-  this.instream.close();
-  this.outstream.close();
-  sessions.remove(session);
-};
-Session.prototype.encodeOut = function (obj) {
-  try {
-    this.onOutput(jsonEncode(obj));
-  } catch(e) {
-    if (typeof(e) == "string") {
-      var exception = e;
-    } else {
-      var exception = {'name':e.name, 'message':e.message};
-    }
-    this.onOutput(jsonEncode({'result':false, 'exception':exception}));
-  }
-  
-}
-Session.prototype.receive = function(data) {
-  // log('jsbrige receive: '+data);
-  Components.utils.evalInSandbox(data, this.sandbox);
-}
-
-var sessions = {
-    _list: [],
-    add: function(session) {
-        this._list.push(session);
-    },
-    remove: function(session) {
-        var index = this._list.indexOf(session);
-        if(index != -1)
-            this._list.splice(index, 1);
-    },
-    get: function(index) {
-        return this._list[index];
-    },
-    quit: function() {
-        this._list.forEach(
-            function(session) { session.quit; });
-        this._list.splice(0, this._list.length);
-    }
-};
-
-function Server (port) {
-  this.port = port;
-}
-Server.prototype.start = function () {
-  try {
-    this.serv = Cc['@mozilla.org/network/server-socket;1']
-        .createInstance(Ci.nsIServerSocket);
-    this.serv.init(this.port, true, -1);
-    this.serv.asyncListen(this);
-    // log('jsbridge: Listening...');
-  } catch(e) {
-    log('jsbridge: Exception: ' + e);
-  }    
-}
-Server.prototype.stop = function () {
-    log('jsbridge: Closing...');
-    this.serv.close();
-    this.sessions.quit();
-    this.serv = undefined;
-}
-Server.prototype.onStopListening = function (serv, status) {
-// Stub function
-}
-Server.prototype.onSocketAccepted = function (serv, transport) {
-  session = new Session(transport)
-  sessions.add(session);
-}
-
-function log(msg) {
-    dump(msg + '\n');
-}
-
-function startServer(port) {
-  var server = new Server(port)
-  server.start()
-}
-
-

File python-modules/jsbridge/jsobjects.py

-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is Mozilla Corporation Code.
-#
-# The Initial Developer of the Original Code is
-# Mikeal Rogers.
-# Portions created by the Initial Developer are Copyright (C) 2008
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#  Mikeal Rogers <mikeal.rogers@gmail.com>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-def init_jsobject(cls, bridge, name, value, description=None):
-    """Initialize a js object that is a subclassed base type; int, str, unicode, float."""
-    obj = cls(value)
-    obj._bridge_ = bridge
-    obj._name_ = name
-    obj._description_ = description
-    return obj
-
-def create_jsobject(bridge, fullname, value=None, obj_type=None, override_set=False):
-    """Create a single JSObject for named object on other side of the bridge.
-    
-    Handles various initization cases for different JSObjects."""
-    description = bridge.describe(fullname)
-    obj_type = description['type']
-    value = description.get('data', None)
-    
-    if value is True or value is False:
-        return value
-
-    if js_type_cases.has_key(obj_type):
-        cls, needs_init = js_type_cases[obj_type]
-        # Objects that requires initialization are base types that have "values".
-        if needs_init:
-            obj = init_jsobject(cls, bridge, fullname, value, description=description)
-        else:
-            obj = cls(bridge, fullname, description=description, override_set=override_set)
-        return obj
-    else:
-        # Something very bad happened, we don't have a representation for the given type.
-        raise TypeError("Don't have a JSObject for javascript type "+obj_type)
-    
-class JSObject(object):
-    """Base javascript object representation."""
-    _loaded_ = False
-    
-    def __init__(self, bridge, name, override_set=False, description=None, *args, **kwargs):
-        self._bridge_ = bridge
-        if not override_set:
-            name = bridge.set(name)['data']
-        self._name_ = name
-        self._description_ = description
-    
-    def __jsget__(self, name):
-        """Abstraction for final step in get events; __getitem__ and __getattr__.
-        """
-        result = create_jsobject(self._bridge_, name, override_set=True)
-        return result
-    
-    def __getattr__(self, name):
-        """Get the object from jsbridge. 
-        
-        Handles lazy loading of all attributes of self."""
-        # A little hack so that ipython returns all the names.
-        if name == '_getAttributeNames':
-            return lambda : self._bridge_.describe(self._name_)['attributes']
-            
-        attributes = self._bridge_.describe(self._name_)['attributes']
-        if name in attributes:
-            return self.__jsget__(self._name_+'.'+name)
-        else:
-            raise AttributeError(name+" is undefined.")
-    
-    __getitem__ = __getattr__
-        
-    def __setattr__(self, name, value):
-        """Set the given JSObject as an attribute of this JSObject and make proper javascript
-        assignment on the other side of the bridge."""
-        if name.startswith('_') and name.endswith('_'):
-            return object.__setattr__(self, name, value)
-
-        response = self._bridge_.setAttribute(self._name_, name, value)
-        object.__setattr__(self, name, create_jsobject(self._bridge_, response['data'], override_set=True))
-    
-    __setitem__ = __setattr__
-
-class JSFunction(JSObject):
-    """Javascript function represenation.
-    
-    Returns a JSObject instance for the serialized js type with 
-    name set to the full javascript call for this function. 
-    """    
-    
-    def __init__(self, bridge, name, override_set=False, description=None, *args, **kwargs):
-        self._bridge_ = bridge
-        self._name_ = name
-        self._description_ = description
-    
-    def __call__(self, *args, **kwargs):
-        assert len(kwargs) is 0
-        response = self._bridge_.execFunction(self._name_, args)
-        if response['data'] is not None:
-            return create_jsobject(self._bridge_, response['data'], override_set=True)
-
-
-class JSString(JSObject, unicode):
-    "Javascript string representation."
-    __init__ = unicode.__init__
-
-class JSInt(JSObject, int): 
-    """Javascript number representation for Python int."""
-    __init__ = int.__init__
-
-class JSFloat(JSObject, float):
-    """Javascript number representation for Python float."""
-    __init__ = float.__init__
-    
-class JSUndefined(JSObject):
-    """Javascript undefined representation."""    
-    __str__ = lambda self : "undefined"
-
-    def __cmp__(self, other):
-        if isinstance(other, JSUndefined):
-            return True
-        else:
-            return False
-
-    __nonzero__ = lambda self: False
-
-js_type_cases = {'function'  :(JSFunction, False,), 
-                  'object'   :(JSObject, False,), 
-                  'array'    :(JSObject, False,),