]> git.donarmstrong.com Git - dactyl.git/blobdiff - common/modules/addons.jsm
Import 1.0 supporting Firefox up to 14.*
[dactyl.git] / common / modules / addons.jsm
index 03c4e0fb9bf18ff2a4920dac0cdd5706b69fd975..8ea7f8a4a6414a0016ffd0c77f13a9dd9c398d17 100644 (file)
@@ -3,15 +3,14 @@
 //
 // This work is licensed for reuse under an MIT license. Details are
 // given in the LICENSE.txt file included with this file.
-"use strict";
+/* use strict */
 
 try {
 
 Components.utils.import("resource://dactyl/bootstrap.jsm");
 defineModule("addons", {
     exports: ["AddonManager", "Addons", "Addon", "addons"],
-    require: ["services"],
-    use: ["completion", "config", "io", "messages", "prefs", "template", "util"]
+    require: ["services"]
 }, this);
 
 var callResult = function callResult(method) {
@@ -22,8 +21,8 @@ var callResult = function callResult(method) {
 var listener = function listener(action, event)
     function addonListener(install) {
         this.dactyl[install.error ? "echoerr" : "echomsg"](
-            "Add-on " + action + " " + event + ": " + (install.name || install.sourceURI.spec) +
-            (install.error ? ": " + addonErrors[install.error] : ""));
+            _("addon.error", action, event, (install.name || install.sourceURI.spec) +
+                (install.error ? ": " + addons.errors[install.error] : "")));
     }
 
 var AddonListener = Class("AddonListener", {
@@ -64,18 +63,18 @@ var updateAddons = Class("UpgradeListener", AddonListener, {
         install.install();
     },
     onUpdateFinished: function (addon, error) {
-        this.remaining = this.remaining.filter(function (a) a != addon);
+        this.remaining = this.remaining.filter(function (a) a.type != addon.type || a.id != addon.id);
         if (!this.remaining.length)
             this.dactyl.echomsg(
                 this.upgrade.length
-                    ? "Installing updates for addons: " + this.upgrade.map(function (i) i.name).join(", ")
-                    : "No addon updates found");
+                    ? _("addon.installingUpdates", this.upgrade.map(function (i) i.name).join(", "))
+                    : _("addon.noUpdates"));
     }
 });
 
 var actions = {
     delete: {
-        name: "extde[lete]",
+        name: ["extde[lete]", "extrm"],
         description: "Uninstall an extension",
         action: callResult("uninstall"),
         perm: "uninstall"
@@ -84,14 +83,14 @@ var actions = {
         name: "exte[nable]",
         description: "Enable an extension",
         action: function (addon) { addon.userDisabled = false; },
-        filter: function ({ item }) item.userDisabled,
+        filter: function (addon) addon.userDisabled,
         perm: "enable"
     },
     disable: {
         name: "extd[isable]",
         description: "Disable an extension",
         action: function (addon) { addon.userDisabled = true; },
-        filter: function ({ item }) !item.userDisabled,
+        filter: function (addon) !addon.userDisabled,
         perm: "disable"
     },
     options: {
@@ -104,21 +103,22 @@ var actions = {
             else
                 this.dactyl.open(addon.optionsURL, { from: "extoptions" });
         },
-        filter: function ({ item }) item.isActive && item.optionsURL
+        filter: function (addon) addon.isActive && addon.optionsURL
     },
     rehash: {
         name: "extr[ehash]",
         description: "Reload an extension",
         action: function (addon) {
-            util.assert(util.haveGecko("2b"), _("error.notUseful", config.host));
+            util.assert(config.haveGecko("2b"), _("command.notUseful", config.host));
+            util.flushCache();
             util.timeout(function () {
                 addon.userDisabled = true;
                 addon.userDisabled = false;
             });
         },
         get filter() {
-            let ids = set(keys(JSON.parse(prefs.get("extensions.bootstrappedAddons", "{}"))));
-            return function ({ item }) !item.userDisabled && set.has(ids, item.id);
+            return function (addon) !addon.userDisabled &&
+                !(addon.operationsRequiringRestart & (AddonManager.OP_NEEDS_RESTART_ENABLE | AddonManager.OP_NEEDS_RESTART_DISABLE))
         },
         perm: "disable"
     },
@@ -149,14 +149,14 @@ var Addon = Class("Addon", {
             <tr highlight="Addon" key="row" xmlns:dactyl={NS} xmlns={XHTML}>
                 <td highlight="AddonName" key="name"/>
                 <td highlight="AddonVersion" key="version"/>
-                <td highlight="AddonStatus" key="status"/>
                 <td highlight="AddonButtons Buttons">
-                    <a highlight="Button" key="enable">On&#xa0;</a>
-                    <a highlight="Button" key="disable">Off</a>
-                    <a highlight="Button" key="delete">Del</a>
-                    <a highlight="Button" key="update">Upd</a>
-                    <a highlight="Button" key="options">Opt</a>
+                    <a highlight="Button" href="javascript:0" key="enable">{_("addon.action.On")}</a>
+                    <a highlight="Button" href="javascript:0" key="disable">{_("addon.action.Off")}</a>
+                    <a highlight="Button" href="javascript:0" key="delete">{_("addon.action.Delete")}</a>
+                    <a highlight="Button" href="javascript:0" key="update">{_("addon.action.Update")}</a>
+                    <a highlight="Button" href="javascript:0" key="options">{_("addon.action.Options")}</a>
                 </td>
+                <td highlight="AddonStatus" key="status"/>
                 <td highlight="AddonDescription" key="description"/>
             </tr>,
             this.list.document, this.nodes);
@@ -165,18 +165,18 @@ var Addon = Class("Addon", {
     },
 
     commandAllowed: function commandAllowed(cmd) {
-        util.assert(set.has(actions, cmd), "Unknown command");
+        util.assert(Set.has(actions, cmd), _("addon.unknownCommand"));
 
         let action = actions[cmd];
         if ("perm" in action && !(this.permissions & AddonManager["PERM_CAN_" + action.perm.toUpperCase()]))
             return false;
-        if ("filter" in action && !action.filter({ item: this }))
+        if ("filter" in action && !action.filter(this))
             return false;
         return true;
     },
 
     command: function command(cmd) {
-        util.assert(this.commandAllowed(cmd), "Command not allowed");
+        util.assert(this.commandAllowed(cmd), _("addon.commandNotAllowed"));
 
         let action = actions[cmd];
         if (action.action)
@@ -224,6 +224,7 @@ var Addon = Class("Addon", {
         this.nodes.version.textContent = this.version;
         update("status", this.statusInfo);
         this.nodes.description.textContent = this.description;
+        DOM(this.nodes.row).attr("active", this.isActive || null);
 
         for (let node in values(this.nodes))
             if (node.update && node.update !== callee)
@@ -277,16 +278,16 @@ var AddonList = Class("AddonList", {
         this.update();
     },
 
-    message: Class.memoize(function () {
+    message: Class.Memoize(function () {
 
         XML.ignoreWhitespace = true;
         util.xmlToDom(<table highlight="Addons" key="list" xmlns={XHTML}>
                         <tr highlight="AddonHead">
-                            <td>Name</td>
-                            <td>Version</td>
-                            <td>Status</td>
+                            <td>{_("title.Name")}</td>
+                            <td>{_("title.Version")}</td>
                             <td/>
-                            <td>Description</td>
+                            <td>{_("title.Status")}</td>
+                            <td>{_("title.Description")}</td>
                         </tr>
                       </table>, this.document, this.nodes);
 
@@ -347,10 +348,15 @@ var AddonList = Class("AddonList", {
 });
 
 var Addons = Module("addons", {
+    errors: Class.Memoize(function ()
+            array(["ERROR_NETWORK_FAILURE", "ERROR_INCORRECT_HASH",
+                   "ERROR_CORRUPT_FILE", "ERROR_FILE_ACCESS"])
+                .map(function (e) [AddonManager[e], _("AddonManager." + e)])
+                .toObject())
 }, {
 }, {
     commands: function (dactyl, modules, window) {
-        const { CommandOption, commands, completion } = modules;
+        const { CommandOption, commands, completion, io } = modules;
 
         commands.add(["addo[ns]", "ao"],
             "List installed extensions",
@@ -393,7 +399,7 @@ var Addons = Module("addons", {
                 else if (file.isDirectory())
                     dactyl.echoerr(_("addon.cantInstallDir", file.path.quote()));
                 else
-                    dactyl.echoerr(_("io.notReadable-1", file.path));
+                    dactyl.echoerr(_("io.notReadable", file.path));
             }, {
                 argCount: "1",
                 completer: function (context) {
@@ -406,25 +412,25 @@ var Addons = Module("addons", {
         // TODO: handle extension dependencies
         values(actions).forEach(function (command) {
             let perm = command.perm && AddonManager["PERM_CAN_" + command.perm.toUpperCase()];
-            function ok(addon) !perm || addon.permissions & perm;
+            function ok(addon) (!perm || addon.permissions & perm) && (!command.filter || command.filter(addon));
 
             commands.add(Array.concat(command.name),
                 command.description,
                 function (args) {
                     let name = args[0];
                     if (args.bang && !command.bang)
-                        dactyl.assert(!name, _("error.trailing"));
+                        dactyl.assert(!name, _("error.trailingCharacters"));
                     else
                         dactyl.assert(name, _("error.argumentRequired"));
 
-                    AddonManager.getAddonsByTypes(["extension"], dactyl.wrapCallback(function (list) {
+                    AddonManager.getAddonsByTypes(args["-types"], dactyl.wrapCallback(function (list) {
                         if (!args.bang || command.bang) {
-                            list = list.filter(function (extension) extension.name == name);
-                            if (list.length == 0)
-                                return void dactyl.echoerr(_("error.invalidArgument", name));
-                            if (!list.every(ok))
-                                return void dactyl.echoerr(_("error.invalidOperation"));
+                            list = list.filter(function (addon) addon.id == name || addon.name == name);
+                            dactyl.assert(list.length, _("error.invalidArgument", name));
+                            dactyl.assert(list.some(ok), _("error.invalidOperation"));
+                            list = list.filter(ok);
                         }
+                        dactyl.assert(list.every(ok));
                         if (command.actions)
                             command.actions(list, this.modules);
                         else
@@ -433,13 +439,20 @@ var Addons = Module("addons", {
                 }, {
                     argCount: "?", // FIXME: should be "1"
                     bang: true,
-                    completer: function (context) {
-                        completion.extension(context);
+                    completer: function (context, args) {
+                        completion.addon(context, args["-types"]);
                         context.filters.push(function ({ item }) ok(item));
-                        if (command.filter)
-                            context.filters.push(command.filter);
                     },
-                    literal: 0
+                    literal: 0,
+                    options: [
+                        {
+                            names: ["-types", "-type", "-t"],
+                            description: "The add-on types to operate on",
+                            default: ["extension"],
+                            completer: function (context, args) completion.addonType(context),
+                            type: CommandOption.LIST
+                        }
+                    ]
                 });
         });
     },
@@ -460,13 +473,17 @@ var Addons = Module("addons", {
                                           true));
                     });
                 }
-            }
-        }
+            };
+        };
 
-        completion.extension = function extension(context, types) {
-            context.title = ["Extension"];
+        completion.addon = function addon(context, types) {
+            context.title = ["Add-on"];
             context.anchored = false;
-            context.keys = { text: "name", description: "description", icon: "iconURL" },
+            context.keys = {
+                text: function (addon) [addon.name, addon.id],
+                description: "description",
+                icon: "iconURL"
+            };
             context.generate = function () {
                 context.incomplete = true;
                 AddonManager.getAddonsByTypes(types || ["extension"], function (addons) {
@@ -494,27 +511,14 @@ else
                 addon = this.wrapAddon(addon);
             return callback(addon);
         },
+
         wrapAddon: function wrapAddon(addon) {
             addon = Object.create(addon.QueryInterface(Ci.nsIUpdateItem));
 
-            function getRdfProperty(item, property) {
-                let resource = services.rdf.GetResource("urn:mozilla:item:" + item.id);
-                let value = "";
-
-                if (resource) {
-                    let target = services.extensionManager.datasource.GetTarget(resource,
-                        services.rdf.GetResource("http://www.mozilla.org/2004/em-rdf#" + property), true);
-                    if (target && target instanceof Ci.nsIRDFLiteral)
-                        value = target.Value;
-                }
-
-                return value;
-            }
-
             ["aboutURL", "creator", "description", "developers",
              "homepageURL", "installDate", "optionsURL",
              "releaseNotesURI", "updateDate"].forEach(function (item) {
-                memoize(addon, item, function (item) getRdfProperty(this, item));
+                memoize(addon, item, function (item) this.getProperty(item));
             });
 
             update(addon, {
@@ -523,19 +527,33 @@ else
 
                 appDisabled: false,
 
-                installLocation: Class.memoize(function () services.extensionManager.getInstallLocation(this.id)),
+                getProperty: function getProperty(property) {
+                    let resource = services.rdf.GetResource("urn:mozilla:item:" + this.id);
+
+                    if (resource) {
+                        let target = services.extensionManager.datasource.GetTarget(resource,
+                            services.rdf.GetResource("http://www.mozilla.org/2004/em-rdf#" + property), true);
+
+                        if (target && target instanceof Ci.nsIRDFLiteral)
+                            return target.Value;
+                    }
+
+                    return "";
+                },
+
+                installLocation: Class.Memoize(function () services.extensionManager.getInstallLocation(this.id)),
                 getResourceURI: function getResourceURI(path) {
                     let file = this.installLocation.getItemFile(this.id, path);
                     return services.io.newFileURI(file);
                 },
 
-                isActive: getRdfProperty(addon, "isDisabled") != "true",
+                get isActive() this.getProperty("isDisabled") != "true",
 
                 uninstall: function uninstall() {
                     services.extensionManager.uninstallItem(this.id);
                 },
 
-                get userDisabled() getRdfProperty(addon, "userDisabled") === "true",
+                get userDisabled() this.getProperty("userDisabled") === "true",
                 set userDisabled(val) {
                     services.extensionManager[val ? "disableItem" : "enableItem"](this.id);
                 }
@@ -543,6 +561,7 @@ else
 
             return addon;
         },
+
         getAddonsByTypes: function (types, callback) {
             let res = [];
             for (let [, type] in Iterator(types))
@@ -554,6 +573,7 @@ else
                 util.timeout(function () { callback(res); });
             return res;
         },
+
         getInstallForFile: function (file, callback, mimetype) {
             callback({
                 addListener: function () {},
@@ -562,9 +582,11 @@ else
                 }
             });
         },
+
         getInstallForURL: function (url, callback, mimetype) {
             util.assert(false, _("error.unavailable", config.host, services.runtime.version));
         },
+
         observers: [],
         addAddonListener: function (listener) {
             observer.listener = listener;
@@ -595,12 +617,6 @@ else
         }
     };
 
-var addonErrors = array.toObject([
-    [AddonManager.ERROR_NETWORK_FAILURE, "A network error occurred"],
-    [AddonManager.ERROR_INCORRECT_HASH,  "The downloaded file did not match the expected hash"],
-    [AddonManager.ERROR_CORRUPT_FILE,    "The file appears to be corrupt"],
-    [AddonManager.ERROR_FILE_ACCESS,     "There was an error accessing the filesystem"]]);
-
 endModule();
 
 } catch(e){ if (isString(e)) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }