]> git.donarmstrong.com Git - dactyl.git/blobdiff - common/content/dactyl.js
Imported Upstream version 1.1+hg7904
[dactyl.git] / common / content / dactyl.js
index 6ad9e5534ca899160a439e8b5014974c20d58f20..752b17ddd1516af998dcf30231e4c083f741bfcf 100644 (file)
@@ -1,6 +1,6 @@
 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
-// Copyright (c) 2008-2013 Kris Maglione <maglione.k@gmail.com>
+// Copyright (c) 2008-2014 Kris Maglione <maglione.k@gmail.com>
 //
 // This work is licensed for reuse under an MIT license. Details are
 // given in the LICENSE.txt file included with this file.
@@ -136,14 +136,14 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                     && !item.hidden
                     && !/rdf:http:/.test(item.getAttribute("label"))) { // FIXME
                     item.dactylPath = parent + item.getAttribute("label");
-                    if (!targetPath || targetPath.indexOf(item.dactylPath) == 0)
+                    if (!targetPath || targetPath.startsWith(item.dactylPath))
                         items.push(item);
                 }
                 else {
                     let path = parent;
                     if (item.localName == "menu")
                         path += item.getAttribute("label") + ".";
-                    if (!targetPath || targetPath.indexOf(path) == 0)
+                    if (!targetPath || targetPath.startsWith(path))
                         addChildren(item, path);
                 }
             }
@@ -206,7 +206,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
 
     registerObservers: function registerObservers(obj, prop) {
         for (let [signal, func] in Iterator(obj[prop || "signals"]))
-            this.registerObserver(signal, obj.closure(func), false);
+            this.registerObserver(signal, func.bind(obj), false);
     },
 
     unregisterObserver: function unregisterObserver(type, callback) {
@@ -216,20 +216,11 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
 
     applyTriggerObserver: function triggerObserver(type, args) {
         if (type in this._observers)
-            this._observers[type] = this._observers[type].filter(function (callback) {
-                if (callback.get()) {
-                    try {
-                        try {
-                            callback.get().apply(null, args);
-                        }
-                        catch (e if e.message == "can't wrap XML objects") {
-                            // Horrible kludge.
-                            callback.get().apply(null, [String(args[0])].concat(args.slice(1)));
-                        }
-                    }
-                    catch (e) {
-                        dactyl.reportError(e);
-                    }
+            this._observers[type] = this._observers[type]
+                                        .filter(callback => {
+                callback = callback.get();
+                if (callback) {
+                    util.trapErrors(() => callback.apply(null, args));
                     return true;
                 }
             });
@@ -250,7 +241,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                 let filters = args.map(arg => let (re = util.regexp.escape(arg))
                                         util.regexp("\\b" + re + "\\b|(?:^|[()\\s])" + re + "(?:$|[()\\s])", "i"));
                 if (filters.length)
-                    results = results.filter(item => filters.every(re => keys(item).some(re.closure.test)));
+                    results = results.filter(item => filters.every(re => keys(item).some(re.bound.test)));
 
                 commandline.commandOutput(
                     template.usage(results, params.format));
@@ -278,10 +269,9 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                 let results = array((params.iterateIndex || params.iterate).call(params, commands.get(name).newArgs()))
                         .array.sort((a, b) => String.localeCompare(a.name, b.name));
 
-                let haveTag = Set.has(help.tags);
                 for (let obj in values(results)) {
                     let res = dactyl.generateHelp(obj, null, null, true);
-                    if (!haveTag(obj.helpTag))
+                    if (!hasOwnProperty(help.tags, obj.helpTag))
                         res[0][1].tag = obj.helpTag;
 
                     yield res;
@@ -387,9 +377,9 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
     },
 
     dump: deprecated("util.dump",
-                     { get: function dump() util.closure.dump }),
+                     { get: function dump() util.bound.dump }),
     dumpStack: deprecated("util.dumpStack",
-                          { get: function dumpStack() util.closure.dumpStack }),
+                          { get: function dumpStack() util.bound.dumpStack }),
 
     /**
      * Outputs a plain message to the command line.
@@ -468,16 +458,16 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
      *     should be loaded.
      */
     loadScript: function loadScript(uri, context) {
+        let prefix = "literal:" + uri + ":";
+        cache.flush(s => s.startsWith(prefix));
+        delete literal.files[uri];
         JSMLoader.loadSubScript(uri, context, File.defaultEncoding);
     },
 
     userEval: function userEval(str, context, fileName, lineNumber) {
-        let ctxt;
-        if (jsmodules.__proto__ != window && jsmodules.__proto__ != XPCNativeWrapper(window) &&
-                jsmodules.isPrototypeOf(context))
-            str = "with (window) { with (modules) { (this.eval || eval)(" + str.quote() + ") } }";
+        let ctxt,
+            info = contexts.context;
 
-        let info = contexts.context;
         if (fileName == null)
             if (info)
                 ({ file: fileName, line: lineNumber, context: ctxt }) = info;
@@ -485,14 +475,14 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
         if (fileName && fileName[0] == "[")
             fileName = "dactyl://command-line/";
         else if (!context)
-            context = ctxt || _userContext;
-
-        if (isinstance(context, ["Sandbox"]))
-            return Cu.evalInSandbox(str, context, "1.8", fileName, lineNumber);
+            context = ctxt || userContext;
 
         if (!context)
             context = userContext || ctxt;
 
+        if (isinstance(context, ["Sandbox"]))
+            return Cu.evalInSandbox(str, context, "1.8", fileName, lineNumber);
+
         if (services.has("dactyl") && services.dactyl.evalInContext)
             return services.dactyl.evalInContext(str, context, fileName, lineNumber);
 
@@ -538,7 +528,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
      * @param {boolean} silent Whether the command should be echoed on the
      *     command line.
      */
-    execute: function execute(str, modifiers = {}, silent = false) {
+    execute: function execute(str, modifiers={}, silent=false) {
         // skip comments and blank lines
         if (/^\s*("|$)/.test(str))
             return;
@@ -620,7 +610,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
      * @param {string} feature The feature name.
      * @returns {boolean}
      */
-    has: function has(feature) Set.has(config.features, feature),
+    has: function has(feature) config.has(feature),
 
     /**
      * @private
@@ -637,8 +627,8 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
         }
     },
 
-    help: deprecated("help.help", { get: function help() modules.help.closure.help }),
-    findHelp: deprecated("help.findHelp", { get: function findHelp() help.closure.findHelp }),
+    help: deprecated("help.help", { get: function help() modules.help.bound.help }),
+    findHelp: deprecated("help.findHelp", { get: function findHelp() help.bound.findHelp }),
 
     /**
      * @private
@@ -734,7 +724,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
         }
 
         if (obj.completer && false)
-            add(completion._runCompleter(obj.closure.completer, "", null, args).items
+            add(completion._runCompleter(obj.bound.completer, "", null, args).items
                           .map(i => [i.text, i.description]));
 
         if (obj.options && obj.options.some(o => o.description) && false)
@@ -832,6 +822,20 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
     },
 
     events: {
+        beforecustomization: function onbeforecustomization(event) {
+            // Show navigation bar on Australis, where it's not supposed
+            // to be collapsible, and is therefore not handled by
+            // builtin code.
+            if ("CustomizableUI" in window)
+                this.setNodeVisible(document.getElementById("nav-bar"),
+                                    true);
+        },
+
+        aftercustomization: function onaftercustomization(event) {
+            // Restore toolbar states.
+            options["guioptions"] = options["guioptions"];
+        },
+
         click: function onClick(event) {
             let elem = event.originalTarget;
 
@@ -890,13 +894,13 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
      *     tabs.
      * @returns {boolean}
      */
-    open: function open(urls, params = {}, force = false) {
+    open: function open(urls, params={}, force=false) {
         if (typeof urls == "string")
             urls = dactyl.parseURLs(urls);
 
         if (urls.length > prefs.get("browser.tabs.maxOpenBeforeWarn", 20) && !force)
-            return commandline.input(_("dactyl.prompt.openMany", urls.length) + " ",
-                function (resp) {
+            return commandline.input(_("dactyl.prompt.openMany", urls.length) + " ")
+                .then(function (resp) {
                     if (resp && resp.match(/^y(es)?$/i))
                         dactyl.open(urls, params, true);
                 });
@@ -1143,7 +1147,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
         if (error instanceof FailedAssertion && error.noTrace || error.message === "Interrupted") {
             let context = contexts.context;
             let prefix = context ? context.file + ":" + context.line + ": " : "";
-            if (error.message && error.message.indexOf(prefix) !== 0 &&
+            if (error.message && !error.message.startsWith(prefix) &&
                     prefix != "[Command Line]:1: ")
                 error.message = prefix + error.message;
 
@@ -1184,7 +1188,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
             return [];
         }
     },
-    wrapCallback: function wrapCallback(callback, self = this) {
+    wrapCallback: function wrapCallback(callback, self=this) {
         let save = ["forceOpen"];
         let saved = save.map(p => dactyl[p]);
         return function wrappedCallback() {
@@ -1205,10 +1209,11 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
      * @property {[Window]} Returns an array of all the host application's
      *     open windows.
      */
-    get windows() [win for (win in iter(services.windowMediator.getEnumerator("navigator:browser"))) if (win.dactyl)],
+    get windows() [w for (w of overlay.windows)]
 
 }, {
-    toolbarHidden: function hidden(elem) (elem.getAttribute("autohide") || elem.getAttribute("collapsed")) == "true"
+    toolbarHidden: function toolbarHidden(elem) "true" == (elem.getAttribute("autohide") ||
+                                                           elem.getAttribute("collapsed"))
 }, {
     cache: function initCache() {
         cache.register("help/plugins.xml", function () {
@@ -1219,19 +1224,23 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                 try {
                     let info = contexts.getDocs(context);
                     if (DOM.isJSONXML(info)) {
-                        let langs = info.slice(2).filter(e => isArray(e) && isObject(e[1]) && e[1].lang);
+                        let langs = info.slice(2)
+                                        .filter(e => isArray(e) && isObject(e[1]) && e[1].lang);
                         if (langs) {
-                            let lang = config.bestLocale(l[1].lang for each (l in langs));
+                            let lang = config.bestLocale(langs.map(l => l[1].lang));
 
                             info = info.slice(0, 2).concat(
                                 info.slice(2).filter(e => !isArray(e)
                                                        || !isObject(e[1])
                                                        || e[1].lang == lang));
 
-                            for each (let elem in info.slice(2).filter(e => isArray(e) && e[0] == "info" && isObject(e[1])))
-                                for (let attr in values(["name", "summary", "href"]))
+                            info.slice(2)
+                                .filter(e => isArray(e) && e[0] == "info" && isObject(e[1]))
+                                .forEach(elem => {
+                                for (let attr of ["name", "summary", "href"])
                                     if (attr in elem[1])
                                         info[attr] = elem[1][attr];
+                            });
                         }
                         body.push(["h2", { xmlns: "dactyl", tag: info[1].name + '-plugin' },
                                        String(info[1].summary)]);
@@ -1251,7 +1260,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                            ["toc", { start: "2" }],
 
                            body]);
-        });
+        }, true);
 
         cache.register("help/index.xml", function () {
             return '<?xml version="1.0"?>\n' +
@@ -1260,7 +1269,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                            ["dl", { insertafter: name + "-index" },
                                template.map(iter(), util.identity)],
                            "\n\n")]);
-        });
+        }, true);
 
         cache.register("help/gui.xml", function () {
             return '<?xml version="1.0"?>\n' +
@@ -1272,7 +1281,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                                       ["dd", {}, val[0]]]
                                    : undefined,
                                "\n")]]);
-        });
+        }, true);
 
         cache.register("help/privacy.xml", function () {
             return '<?xml version="1.0"?>\n' +
@@ -1285,7 +1294,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                                [["dt", {}, name],
                                 ["dd", {}, template.linkifyHelp(description, true)]],
                                "\n")]]);
-        });
+        }, true);
     },
     events: function initEvents() {
         events.listen(window, dactyl, "events", true);
@@ -1315,7 +1324,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                     M: ["Always show messages outside of the status line"]
                 },
                 setter: function (opts) {
-                    if (loaded.commandline || ~opts.indexOf("c"))
+                    if (loaded.has("commandline") || ~opts.indexOf("c"))
                         commandline.widgets.updateVisibility();
                 }
             },
@@ -1367,10 +1376,6 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                     styles.system.add("taboptions", "chrome://*",
                                       classes.length ? classes.join(",") + "{ display: none; }" : "");
 
-                    if (!dactyl.has("Gecko2")) {
-                        tabs.tabBinding.enabled = Array.some(opts, k => k in this.opts);
-                        tabs.updateTabCount();
-                    }
                     if (config.tabbrowser.tabContainer._positionPinnedTabs)
                         config.tabbrowser.tabContainer._positionPinnedTabs();
                 },
@@ -1639,7 +1644,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
                 if (args["+purgecaches"])
                     cache.flush();
 
-                util.delay(function () { util.rehash(args) });
+                util.delay(() => { util.rehash(args) });
             },
             {
                 argCount: "0", // FIXME
@@ -1889,6 +1894,12 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
             });
         }
 
+        if (config.has("default-theme") && "CustomizableUI" in window)
+            overlay.overlayWindow(window, {
+                append: [
+                    ["window", { id: document.documentElement.id, "dactyl-australis": "true", xmlns: "xul" }]]
+            });
+
         dactyl.timeout(function () {
             try {
                 var args = config.prefs.get("commandline-args")
@@ -1927,7 +1938,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
             // dactyl.hideGUI();
 
             if (dactyl.userEval("typeof document", null, "test.js") === "undefined")
-                jsmodules.__proto__ = XPCSafeJSObjectWrapper(window);
+                jsmodules.__proto__ = window;
 
             if (dactyl.commandLineOptions.preCommands)
                 dactyl.commandLineOptions.preCommands.forEach(function (cmd) {