]> git.donarmstrong.com Git - dactyl.git/blobdiff - common/modules/io.jsm
Imported Upstream version 1.1+hg7904
[dactyl.git] / common / modules / io.jsm
index 8a3a06b2994c4f7a7e40a39c28c361f9b0b71bdd..9de045500a4f2a7b9202335847ed0bce541faa35 100644 (file)
@@ -1,7 +1,6 @@
 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
 // Copyright (c) 2007-2012 by Doug Kearns <dougkearns@gmail.com>
-// Copyright (c) 2008-2012 Kris Maglione <maglione.k@gmail.com>
-// Some code based on Venkman
+// 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.
@@ -16,6 +15,7 @@ defineModule("io", {
 
 lazyRequire("config", ["config"]);
 lazyRequire("contexts", ["Contexts", "contexts"]);
+lazyRequire("promises", ["Promise"]);
 lazyRequire("storage", ["File", "storage"]);
 lazyRequire("styles", ["styles"]);
 lazyRequire("template", ["template"]);
@@ -42,7 +42,7 @@ var IO = Module("io", {
             this._oldcwd = null;
 
             this._lastRunCommand = ""; // updated whenever the users runs a command with :!
-            this._scriptNames = [];
+            this._scriptNames = RealSet();
         },
 
         CommandFileMode: Class("CommandFileMode", modules.CommandMode, {
@@ -74,8 +74,8 @@ var IO = Module("io", {
          */
         getRuntimeDirectories: function getRuntimeDirectories(name) {
             return modules.options.get("runtimepath").files
-                .map(function (dir) dir.child(name))
-                .filter(function (dir) dir.exists() && dir.isDirectory() && dir.isReadable());
+                .map(dir => dir.child(name))
+                .filter(dir => (dir.exists() && dir.isDirectory() && dir.isReadable()));
         },
 
         // FIXME: multiple paths?
@@ -156,7 +156,7 @@ var IO = Module("io", {
                     else if (/\.js$/.test(filename)) {
                         try {
                             var context = contexts.Script(file, params.group);
-                            if (Set.has(this._scriptNames, file.path))
+                            if (this._scriptNames.has(file.path))
                                 util.flushCache();
 
                             dactyl.loadScript(uri.spec, context);
@@ -196,7 +196,7 @@ var IO = Module("io", {
                         dactyl.triggerObserver("io.source", context, file, file.lastModifiedTime);
                     }
 
-                    Set.add(this._scriptNames, file.path);
+                    this._scriptNames.add(file.path);
 
                     dactyl.echomsg(_("io.sourcingEnd", filename.quote()), 2);
                     dactyl.log(_("dactyl.sourced", filename), 3);
@@ -241,11 +241,13 @@ var IO = Module("io", {
     /**
      * Sets the current working directory.
      *
-     * @param {string} newDir The new CWD. This may be a relative or
+     * @param {File|string} newDir The new CWD. This may be a relative or
      *     absolute path and is expanded by {@link #expandPath}.
+     *     @optional
+     *     @default = "~"
      */
-    set cwd(newDir) {
-        newDir = newDir && newDir.path || newDir || "~";
+    set cwd(newDir = "~") {
+        newDir = newDir.path || newDir;
 
         if (newDir == "-") {
             util.assert(this._oldcwd != null, _("io.noPrevDir"));
@@ -266,8 +268,8 @@ var IO = Module("io", {
      */
     File: Class.Memoize(function () let (io = this)
         Class("File", File, {
-            init: function init(path, checkCWD)
-                init.supercall(this, path, (arguments.length < 2 || checkCWD) && io.cwd)
+            init: function init(path, checkCWD=true)
+                init.supercall(this, path, checkCWD && io.cwd)
         })),
 
     /**
@@ -317,7 +319,7 @@ var IO = Module("io", {
      *     @default ""
      * @returns {File}
      */
-    createTempFile: function createTempFile(ext = "txt", label = "") {
+    createTempFile: function createTempFile(ext="txt", label="") {
         let file = services.directory.get("TmpD", Ci.nsIFile);
         file.append(config.name + label + "." + ext);
         file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, octal(666));
@@ -445,26 +447,29 @@ var IO = Module("io", {
 
         let process = services.Process(file.file);
         process.run(false, args.map(String), args.length);
-        try {
-            if (callable(blocking))
-                var timer = services.Timer(
-                    function () {
-                        if (!process.isRunning) {
-                            timer.cancel();
-                            util.trapErrors(blocking, self, process.exitValue);
-                        }
-                    },
-                    100, services.Timer.TYPE_REPEATING_SLACK);
-            else if (blocking)
-                while (process.isRunning)
-                    util.threadYield(false, true);
-        }
-        catch (e) {
-            process.kill();
-            throw e;
+
+        let deferred = Promise.defer();
+
+        if (callable(blocking))
+            // Deprecated.
+            deferred.promise.then(blocking);
+        else if (blocking) {
+            // Deprecated?
+            while (process.isRunning)
+                util.threadYield(false, true);
+            return process.exitValue;
         }
 
-        return process.exitValue;
+        let timer = services.Timer(
+            function () {
+                if (!process.isRunning) {
+                    timer.cancel();
+                    deferred.resolve(process.exitValue);
+                }
+            },
+            100, services.Timer.TYPE_REPEATING_SLACK);
+
+        return deferred.promise;
     },
 
     // TODO: when https://bugzilla.mozilla.org/show_bug.cgi?id=68702 is
@@ -484,7 +489,7 @@ var IO = Module("io", {
     system: function system(command, input, callback) {
         util.dactyl.echomsg(_("io.callingShell", command), 4);
 
-        let { shellEscape } = util.closure;
+        let { shellEscape } = util.bound;
 
         return this.withTempFiles(function (stdin, stdout, cmd) {
             if (input instanceof File)
@@ -502,7 +507,9 @@ var IO = Module("io", {
 
             function async(status) {
                 let output = stdout.read();
-                [stdin, stdout, cmd].forEach(function (f) f.exists() && f.remove(false));
+                for (let f of [stdin, stdout, cmd])
+                    if (f.exists())
+                        f.remove(false);
                 callback(result(status, output));
             }
 
@@ -550,7 +557,7 @@ var IO = Module("io", {
         }
         finally {
             if (!checked || res !== true)
-                args.forEach(function (f) f.remove(false));
+                args.forEach(f => { f.remove(false); });
         }
         return res;
     }
@@ -806,7 +813,9 @@ unlet s:cpo_save
                         lines.last.push(item, sep);
                     }
                     lines.last.pop();
-                    return lines.map(function (l) l.join("")).join("\n").replace(/\s+\n/gm, "\n");
+                    return lines.map(l => l.join(""))
+                                .join("\n")
+                                .replace(/\s+\n/gm, "\n");
                 }//}}}
 
                 let params = { //{{{
@@ -859,7 +868,7 @@ unlet s:cpo_save
         commands.add(["scrip[tnames]"],
             "List all sourced script names",
             function () {
-                let names = Object.keys(io._scriptNames);
+                let names = [k for (k of io._scriptNames)];
                 if (!names.length)
                     dactyl.echomsg(_("command.scriptnames.none"));
                 else
@@ -904,8 +913,8 @@ unlet s:cpo_save
                         _("command.run.noPrevious"));
 
                     arg = arg.replace(/(\\)*!/g,
-                        function (m) /^\\(\\\\)*!$/.test(m) ? m.replace("\\!", "!") : m.replace("!", io._lastRunCommand)
-                    );
+                                      m => (/^\\(\\\\)*!$/.test(m) ? m.replace("\\!", "!")
+                                                                   : m.replace("!", io._lastRunCommand)));
                 }
 
                 io._lastRunCommand = arg;
@@ -942,21 +951,21 @@ unlet s:cpo_save
                     }
                 }
             };
-            context.generate = function () iter(services.charset.getDecoderList());
+            context.generate = () => iter(services.charset.getDecoderList());
         };
 
         completion.directory = function directory(context, full) {
             this.file(context, full);
-            context.filters.push(function (item) item.isdir);
+            context.filters.push(item => item.isdir);
         };
 
         completion.environment = function environment(context) {
             context.title = ["Environment Variable", "Value"];
-            context.generate = function ()
+            context.generate = () =>
                 io.system(config.OS.isWindows ? "set" : "env")
                   .output.split("\n")
-                  .filter(function (line) line.indexOf("=") > 0)
-                  .map(function (line) line.match(/([^=]+)=(.*)/).slice(1));
+                  .filter(line => line.indexOf("=") > 0)
+                  .map(line => line.match(/([^=]+)=(.*)/).slice(1));
         };
 
         completion.file = function file(context, full, dir) {
@@ -983,10 +992,10 @@ unlet s:cpo_save
                 icon: function (f) this.isdir ? "resource://gre/res/html/folder.png"
                                               : "moz-icon://" + f.leafName
             };
-            context.compare = function (a, b) b.isdir - a.isdir || String.localeCompare(a.text, b.text);
+            context.compare = (a, b) => b.isdir - a.isdir || String.localeCompare(a.text, b.text);
 
             if (modules.options["wildignore"])
-                context.filters.push(function (item) !modules.options.get("wildignore").getKey(item.path));
+                context.filters.push(item => !modules.options.get("wildignore").getKey(item.path));
 
             // context.background = true;
             context.key = dir;
@@ -1054,7 +1063,7 @@ unlet s:cpo_save
                 if (!match.path) {
                     context.key = match.proto;
                     context.advance(match.proto.length);
-                    context.generate = function () config.chromePackages.map(function (p) [p, match.proto + p + "/"]);
+                    context.generate = () => config.chromePackages.map(p => [p, match.proto + p + "/"]);
                 }
                 else if (match.scheme === "chrome") {
                     context.key = match.prefix;
@@ -1121,8 +1130,8 @@ unlet s:cpo_save
             "List of directories searched when executing :cd",
             "stringlist", ["."].concat(services.environment.get("CDPATH").split(/[:;]/).filter(util.identity)).join(","),
             {
-                get files() this.value.map(function (path) File(path, modules.io.cwd))
-                                .filter(function (dir) dir.exists()),
+                get files() this.value.map(path => File(path, modules.io.cwd))
+                                .filter(dir => dir.exists()),
                 setter: function (value) File.expandPathList(value)
             });
 
@@ -1130,8 +1139,8 @@ unlet s:cpo_save
             "List of directories searched for runtime files",
             "stringlist", IO.runtimePath,
             {
-                get files() this.value.map(function (path) File(path, modules.io.cwd))
-                                .filter(function (dir) dir.exists())
+                get files() this.value.map(path => File(path, modules.io.cwd))
+                                .filter(dir => dir.exists())
             });
 
         options.add(["shell", "sh"],