]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/storage.jsm
28ad0e8dd0715d0b7b3ad2946c907806d8f7050f
[dactyl.git] / common / modules / storage.jsm
1 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k at Gmail>
2 //
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
5 "use strict";
6
7 Components.utils.import("resource://dactyl/bootstrap.jsm");
8 defineModule("storage", {
9     exports: ["File", "Storage", "storage"],
10     require: ["services", "util"]
11 }, this);
12
13 var win32 = /^win(32|nt)$/i.test(services.runtime.OS);
14 var myObject = JSON.parse("{}").constructor;
15
16 function loadData(name, store, type) {
17     try {
18         let data = storage.infoPath.child(name).read();
19         let result = JSON.parse(data);
20         if (result instanceof type)
21             return result;
22     }
23     catch (e) {}
24 }
25
26 function saveData(obj) {
27     if (obj.privateData && storage.privateMode)
28         return;
29     if (obj.store && storage.infoPath)
30         storage.infoPath.child(obj.name).write(obj.serial);
31 }
32
33 var StoreBase = Class("StoreBase", {
34     OPTIONS: ["privateData", "replacer"],
35
36     fireEvent: function (event, arg) { storage.fireEvent(this.name, event, arg); },
37
38     get serial() JSON.stringify(this._object, this.replacer),
39
40     init: function (name, store, load, options) {
41         this._load = load;
42
43         this.__defineGetter__("store", function () store);
44         this.__defineGetter__("name", function () name);
45         for (let [k, v] in Iterator(options))
46             if (this.OPTIONS.indexOf(k) >= 0)
47                 this[k] = v;
48         this.reload();
49     },
50
51     changed: function () { this.timer.tell(); },
52
53     reload: function reload() {
54         this._object = this._load() || this._constructor();
55         this.fireEvent("change", null);
56     },
57
58     delete: function delete_() {
59         delete storage.keys[this.name];
60         delete storage[this.name];
61         storage.infoPath.child(this.name).remove(false);
62     },
63
64     save: function () { saveData(this); },
65
66     __iterator__: function () Iterator(this._object)
67 });
68
69 var ArrayStore = Class("ArrayStore", StoreBase, {
70     _constructor: Array,
71
72     get length() this._object.length,
73
74     set: function set(index, value) {
75         var orig = this._object[index];
76         this._object[index] = value;
77         this.fireEvent("change", index);
78     },
79
80     push: function push(value) {
81         this._object.push(value);
82         this.fireEvent("push", this._object.length);
83     },
84
85     pop: function pop(value) {
86         var res = this._object.pop();
87         this.fireEvent("pop", this._object.length);
88         return res;
89     },
90
91     truncate: function truncate(length, fromEnd) {
92         var res = this._object.length;
93         if (this._object.length > length) {
94             if (fromEnd)
95                 this._object.splice(0, this._object.length - length);
96             this._object.length = length;
97             this.fireEvent("truncate", length);
98         }
99         return res;
100     },
101
102     // XXX: Awkward.
103     mutate: function mutate(funcName) {
104         var _funcName = funcName;
105         arguments[0] = this._object;
106         this._object = Array[_funcName].apply(Array, arguments);
107         this.fireEvent("change", null);
108     },
109
110     get: function get(index) index >= 0 ? this._object[index] : this._object[this._object.length + index]
111 });
112
113 var ObjectStore = Class("ObjectStore", StoreBase, {
114     _constructor: myObject,
115
116     clear: function () {
117         this._object = {};
118         this.fireEvent("clear");
119     },
120
121     get: function get(key, default_) {
122         return key in this._object  ? this._object[key] :
123                arguments.length > 1 ? this.set(key, default_) :
124                                       undefined;
125     },
126
127     keys: function keys() Object.keys(this._object),
128
129     remove: function remove(key) {
130         var res = this._object[key];
131         delete this._object[key];
132         this.fireEvent("remove", key);
133         return res;
134     },
135
136     set: function set(key, val) {
137         var defined = key in this._object;
138         var orig = this._object[key];
139         this._object[key] = val;
140         if (!defined)
141             this.fireEvent("add", key);
142         else if (orig != val)
143             this.fireEvent("change", key);
144         return val;
145     }
146 });
147
148 var Storage = Module("Storage", {
149     alwaysReload: {},
150
151     init: function () {
152         this.cleanup();
153     },
154
155     cleanup: function () {
156         this.saveAll();
157
158         for (let key in keys(this.keys)) {
159             if (this[key].timer)
160                 this[key].timer.flush();
161             delete this[key];
162         }
163         for (let ary in values(this.observers))
164             for (let obj in values(ary))
165                 if (obj.ref && obj.ref.get())
166                     delete obj.ref.get().dactylStorageRefs;
167
168         this.keys = {};
169         this.observers = {};
170     },
171
172     exists: function exists(name) this.infoPath.child(name).exists(),
173
174     newObject: function newObject(key, constructor, params) {
175         if (params == null || !isObject(params))
176             throw Error("Invalid argument type");
177
178         if (!(key in this.keys) || params.reload || this.alwaysReload[key]) {
179             if (key in this && !(params.reload || this.alwaysReload[key]))
180                 throw Error();
181             let load = function () loadData(key, params.store, params.type || myObject);
182
183             this.keys[key] = new constructor(key, params.store, load, params);
184             this.keys[key].timer = new Timer(1000, 10000, function () storage.save(key));
185             this.__defineGetter__(key, function () this.keys[key]);
186         }
187         return this.keys[key];
188     },
189
190     newMap: function newMap(key, options) {
191         return this.newObject(key, ObjectStore, options);
192     },
193
194     newArray: function newArray(key, options) {
195         return this.newObject(key, ArrayStore, update({ type: Array }, options));
196     },
197
198     addObserver: function addObserver(key, callback, ref) {
199         if (ref) {
200             if (!ref.dactylStorageRefs)
201                 ref.dactylStorageRefs = [];
202             ref.dactylStorageRefs.push(callback);
203             var callbackRef = Cu.getWeakReference(callback);
204         }
205         else {
206             callbackRef = { get: function () callback };
207         }
208         this.removeDeadObservers();
209         if (!(key in this.observers))
210             this.observers[key] = [];
211         if (!this.observers[key].some(function (o) o.callback.get() == callback))
212             this.observers[key].push({ ref: ref && Cu.getWeakReference(ref), callback: callbackRef });
213     },
214
215     removeObserver: function (key, callback) {
216         this.removeDeadObservers();
217         if (!(key in this.observers))
218             return;
219         this.observers[key] = this.observers[key].filter(function (elem) elem.callback.get() != callback);
220         if (this.observers[key].length == 0)
221             delete obsevers[key];
222     },
223
224     removeDeadObservers: function () {
225         for (let [key, ary] in Iterator(this.observers)) {
226             this.observers[key] = ary = ary.filter(function (o) o.callback.get() && (!o.ref || o.ref.get() && o.ref.get().dactylStorageRefs));
227             if (!ary.length)
228                 delete this.observers[key];
229         }
230     },
231
232     fireEvent: function fireEvent(key, event, arg) {
233         this.removeDeadObservers();
234         if (key in this.observers)
235             // Safe, since we have our own Array object here.
236             for each (let observer in this.observers[key])
237                 observer.callback.get()(key, event, arg);
238         if (key in this.keys)
239             this[key].timer.tell();
240     },
241
242     load: function load(key) {
243         if (this[key].store && this[key].reload)
244             this[key].reload();
245     },
246
247     save: function save(key) {
248         if (this[key])
249             saveData(this.keys[key]);
250     },
251
252     saveAll: function storeAll() {
253         for each (let obj in this.keys)
254             saveData(obj);
255     },
256
257     _privateMode: false,
258     get privateMode() this._privateMode,
259     set privateMode(val) {
260         if (val && !this._privateMode)
261             this.saveAll();
262         if (!val && this._privateMode)
263             for (let key in this.keys)
264                 this.load(key);
265         return this._privateMode = Boolean(val);
266     }
267 }, {
268     Replacer: {
269         skipXpcom: function skipXpcom(key, val) val instanceof Ci.nsISupports ? null : val
270     }
271 }, {
272     init: function init(dactyl, modules) {
273         init.superapply(this, arguments);
274         storage.infoPath = File(modules.IO.runtimePath.replace(/,.*/, ""))
275                              .child("info").child(dactyl.profileName);
276     },
277
278     cleanup: function (dactyl, modules, window) {
279         delete window.dactylStorageRefs;
280         this.removeDeadObservers();
281     }
282 });
283
284 /**
285  * @class File A class to wrap nsIFile objects and simplify operations
286  * thereon.
287  *
288  * @param {nsIFile|string} path Expanded according to {@link IO#expandPath}
289  * @param {boolean} checkPWD Whether to allow expansion relative to the
290  *          current directory. @default true
291  */
292 var File = Class("File", {
293     init: function (path, checkPWD) {
294         let file = services.File();
295
296         if (path instanceof Ci.nsIFile)
297             file = path.QueryInterface(Ci.nsIFile).clone();
298         else if (/file:\/\//.test(path))
299             file = services["file:"]().getFileFromURLSpec(path);
300         else {
301             try {
302                 let expandedPath = File.expandPath(path);
303
304                 if (!File.isAbsolutePath(expandedPath) && checkPWD)
305                     file = checkPWD.child(expandedPath);
306                 else
307                     file.initWithPath(expandedPath);
308             }
309             catch (e) {
310                 util.reportError(e);
311                 return File.DoesNotExist(path, e);
312             }
313         }
314         let self = XPCSafeJSObjectWrapper(file.QueryInterface(Ci.nsILocalFile));
315         self.__proto__ = this;
316         return self;
317     },
318
319     /**
320      * Iterates over the objects in this directory.
321      */
322     iterDirectory: function () {
323         if (!this.exists())
324             throw Error("File does not exist");
325         if (!this.isDirectory())
326             throw Error("Not a directory");
327         for (let file in iter(this.directoryEntries))
328             yield File(file);
329     },
330
331     /**
332      * Returns a new file for the given child of this directory entry.
333      */
334     child: function (name) {
335         let f = this.constructor(this);
336         for each (let elem in name.split(File.pathSplit))
337             f.append(elem);
338         return f;
339     },
340
341     /**
342      * Reads this file's entire contents in "text" mode and returns the
343      * content as a string.
344      *
345      * @param {string} encoding The encoding from which to decode the file.
346      *          @default options["fileencoding"]
347      * @returns {string}
348      */
349     read: function (encoding) {
350         let ifstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
351         ifstream.init(this, -1, 0, 0);
352
353         return File.readStream(ifstream, encoding);
354     },
355
356     /**
357      * Returns the list of files in this directory.
358      *
359      * @param {boolean} sort Whether to sort the returned directory
360      *     entries.
361      * @returns {nsIFile[]}
362      */
363     readDirectory: function (sort) {
364         if (!this.isDirectory())
365             throw Error("Not a directory");
366
367         let array = [e for (e in this.iterDirectory())];
368         if (sort)
369             array.sort(function (a, b) b.isDirectory() - a.isDirectory() || String.localeCompare(a.path, b.path));
370         return array;
371     },
372
373     /**
374      * Returns a new nsIFileURL object for this file.
375      *
376      * @returns {nsIFileURL}
377      */
378     toURI: function toURI() services.io.newFileURI(this),
379
380     /**
381      * Writes the string *buf* to this file.
382      *
383      * @param {string} buf The file content.
384      * @param {string|number} mode The file access mode, a bitwise OR of
385      *     the following flags:
386      *       {@link #MODE_RDONLY}:   0x01
387      *       {@link #MODE_WRONLY}:   0x02
388      *       {@link #MODE_RDWR}:     0x04
389      *       {@link #MODE_CREATE}:   0x08
390      *       {@link #MODE_APPEND}:   0x10
391      *       {@link #MODE_TRUNCATE}: 0x20
392      *       {@link #MODE_SYNC}:     0x40
393      *     Alternatively, the following abbreviations may be used:
394      *       ">"  is equivalent to {@link #MODE_WRONLY} | {@link #MODE_CREATE} | {@link #MODE_TRUNCATE}
395      *       ">>" is equivalent to {@link #MODE_WRONLY} | {@link #MODE_CREATE} | {@link #MODE_APPEND}
396      * @default ">"
397      * @param {number} perms The file mode bits of the created file. This
398      *     is only used when creating a new file and does not change
399      *     permissions if the file exists.
400      * @default 0644
401      * @param {string} encoding The encoding to used to write the file.
402      * @default options["fileencoding"]
403      */
404     write: function (buf, mode, perms, encoding) {
405         let ofstream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
406         function getStream(defaultChar) {
407             let stream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
408             stream.init(ofstream, encoding, 0, defaultChar);
409             return stream;
410         }
411         if (buf instanceof File)
412             buf = buf.read();
413
414         if (!encoding)
415             encoding = File.defaultEncoding;
416
417         if (mode == ">>")
418             mode = File.MODE_WRONLY | File.MODE_CREATE | File.MODE_APPEND;
419         else if (!mode || mode == ">")
420             mode = File.MODE_WRONLY | File.MODE_CREATE | File.MODE_TRUNCATE;
421
422         if (!perms)
423             perms = octal(644);
424         if (!this.exists()) // OCREAT won't create the directory
425             this.create(this.NORMAL_FILE_TYPE, perms);
426
427         ofstream.init(this, mode, perms, 0);
428         try {
429             if (callable(buf))
430                 buf(ofstream.QueryInterface(Ci.nsIOutputStream));
431             else {
432                 var ocstream = getStream(0);
433                 ocstream.writeString(buf);
434             }
435         }
436         catch (e if callable(buf) && e.result == Cr.NS_ERROR_LOSS_OF_SIGNIFICANT_DATA) {
437             ocstream = getStream("?".charCodeAt(0));
438             ocstream.writeString(buf);
439             return false;
440         }
441         finally {
442             try {
443                 ocstream.close();
444             }
445             catch (e) {}
446             ofstream.close();
447         }
448         return true;
449     }
450 }, {
451     /**
452      * @property {number} Open for reading only.
453      * @final
454      */
455     MODE_RDONLY: 0x01,
456
457     /**
458      * @property {number} Open for writing only.
459      * @final
460      */
461     MODE_WRONLY: 0x02,
462
463     /**
464      * @property {number} Open for reading and writing.
465      * @final
466      */
467     MODE_RDWR: 0x04,
468
469     /**
470      * @property {number} If the file does not exist, the file is created.
471      *     If the file exists, this flag has no effect.
472      * @final
473      */
474     MODE_CREATE: 0x08,
475
476     /**
477      * @property {number} The file pointer is set to the end of the file
478      *     prior to each write.
479      * @final
480      */
481     MODE_APPEND: 0x10,
482
483     /**
484      * @property {number} If the file exists, its length is truncated to 0.
485      * @final
486      */
487     MODE_TRUNCATE: 0x20,
488
489     /**
490      * @property {number} If set, each write will wait for both the file
491      *     data and file status to be physically updated.
492      * @final
493      */
494     MODE_SYNC: 0x40,
495
496     /**
497      * @property {number} With MODE_CREATE, if the file does not exist, the
498      *     file is created. If the file already exists, no action and NULL
499      *     is returned.
500      * @final
501      */
502     MODE_EXCL: 0x80,
503
504     /**
505      * @property {string} The current platform's path separator.
506      */
507     PATH_SEP: Class.memoize(function () {
508         let f = services.directory.get("CurProcD", Ci.nsIFile);
509         f.append("foo");
510         return f.path.substr(f.parent.path.length, 1);
511     }),
512
513     pathSplit: Class.memoize(function () util.regexp("(?:/|" + util.regexp.escape(this.PATH_SEP) + ")", "g")),
514
515     DoesNotExist: function (path, error) ({
516         path: path,
517         exists: function () false,
518         __noSuchMethod__: function () { throw error || Error("Does not exist"); }
519     }),
520
521     defaultEncoding: "UTF-8",
522
523     /**
524      * Expands "~" and environment variables in *path*.
525      *
526      * "~" is expanded to to the value of $HOME. On Windows if this is not
527      * set then the following are tried in order:
528      *   $USERPROFILE
529      *   ${HOMDRIVE}$HOMEPATH
530      *
531      * The variable notation is $VAR (terminated by a non-word character)
532      * or ${VAR}. %VAR% is also supported on Windows.
533      *
534      * @param {string} path The unexpanded path string.
535      * @param {boolean} relative Whether the path is relative or absolute.
536      * @returns {string}
537      */
538     expandPath: function (path, relative) {
539         function getenv(name) services.environment.get(name);
540
541         // expand any $ENV vars - this is naive but so is Vim and we like to be compatible
542         // TODO: Vim does not expand variables set to an empty string (and documents it).
543         // Kris reckons we shouldn't replicate this 'bug'. --djk
544         // TODO: should we be doing this for all paths?
545         function expand(path) path.replace(
546             !win32 ? /\$(\w+)\b|\${(\w+)}/g
547                    : /\$(\w+)\b|\${(\w+)}|%(\w+)%/g,
548             function (m, n1, n2, n3) getenv(n1 || n2 || n3) || m
549         );
550         path = expand(path);
551
552         // expand ~
553         // Yuck.
554         if (!relative && RegExp("~(?:$|[/" + util.regexp.escape(File.PATH_SEP) + "])").test(path)) {
555             // Try $HOME first, on all systems
556             let home = getenv("HOME");
557
558             // Windows has its own idiosyncratic $HOME variables.
559             if (win32 && (!home || !File(home).exists()))
560                 home = getenv("USERPROFILE") ||
561                        getenv("HOMEDRIVE") + getenv("HOMEPATH");
562
563             path = home + path.substr(1);
564         }
565
566         // TODO: Vim expands paths twice, once before checking for ~, once
567         // after, but doesn't document it. Is this just a bug? --Kris
568         path = expand(path);
569         return path.replace("/", File.PATH_SEP, "g");
570     },
571
572     expandPathList: function (list) list.map(this.expandPath),
573
574     readStream: function (ifstream, encoding) {
575         try {
576             var icstream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream);
577             icstream.init(ifstream, encoding || File.defaultEncoding, 4096, // 4096 bytes buffering
578                           Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
579             let buffer = [];
580             let str = {};
581             while (icstream.readString(4096, str) != 0)
582                 buffer.push(str.value);
583             return buffer.join("");
584         }
585         finally {
586             icstream.close();
587             ifstream.close();
588         }
589     },
590
591     isAbsolutePath: function (path) {
592         try {
593             services.File().initWithPath(path);
594             return true;
595         }
596         catch (e) {
597             return false;
598         }
599     },
600
601     joinPaths: function (head, tail, cwd) {
602         let path = this(head, cwd);
603         try {
604             // FIXME: should only expand environment vars and normalize path separators
605             path.appendRelativePath(this.expandPath(tail, true));
606         }
607         catch (e) {
608             return File.DoesNotExist(e);
609         }
610         return path;
611     },
612
613     replacePathSep: function (path) path.replace("/", File.PATH_SEP, "g")
614 });
615
616 endModule();
617
618 // catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
619
620 // vim: set fdm=marker sw=4 sts=4 et ft=javascript: