1 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k at Gmail>
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
7 Components.utils.import("resource://dactyl/bootstrap.jsm");
8 defineModule("storage", {
9 exports: ["File", "Storage", "storage"],
10 require: ["services", "util"]
13 var win32 = /^win(32|nt)$/i.test(services.runtime.OS);
14 var myObject = JSON.parse("{}").constructor;
16 function loadData(name, store, type) {
18 let data = storage.infoPath.child(name).read();
19 let result = JSON.parse(data);
20 if (result instanceof type)
26 function saveData(obj) {
27 if (obj.privateData && storage.privateMode)
29 if (obj.store && storage.infoPath)
30 storage.infoPath.child(obj.name).write(obj.serial);
33 var StoreBase = Class("StoreBase", {
34 OPTIONS: ["privateData", "replacer"],
36 fireEvent: function (event, arg) { storage.fireEvent(this.name, event, arg); },
38 get serial() JSON.stringify(this._object, this.replacer),
40 init: function (name, store, load, options) {
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)
51 changed: function () { this.timer.tell(); },
53 reload: function reload() {
54 this._object = this._load() || this._constructor();
55 this.fireEvent("change", null);
58 delete: function delete_() {
59 delete storage.keys[this.name];
60 delete storage[this.name];
61 storage.infoPath.child(this.name).remove(false);
64 save: function () { saveData(this); },
66 __iterator__: function () Iterator(this._object)
69 var ArrayStore = Class("ArrayStore", StoreBase, {
72 get length() this._object.length,
74 set: function set(index, value) {
75 var orig = this._object[index];
76 this._object[index] = value;
77 this.fireEvent("change", index);
80 push: function push(value) {
81 this._object.push(value);
82 this.fireEvent("push", this._object.length);
85 pop: function pop(value) {
86 var res = this._object.pop();
87 this.fireEvent("pop", this._object.length);
91 truncate: function truncate(length, fromEnd) {
92 var res = this._object.length;
93 if (this._object.length > length) {
95 this._object.splice(0, this._object.length - length);
96 this._object.length = length;
97 this.fireEvent("truncate", length);
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);
110 get: function get(index) index >= 0 ? this._object[index] : this._object[this._object.length + index]
113 var ObjectStore = Class("ObjectStore", StoreBase, {
114 _constructor: myObject,
118 this.fireEvent("clear");
121 get: function get(key, default_) {
122 return key in this._object ? this._object[key] :
123 arguments.length > 1 ? this.set(key, default_) :
127 keys: function keys() Object.keys(this._object),
129 remove: function remove(key) {
130 var res = this._object[key];
131 delete this._object[key];
132 this.fireEvent("remove", key);
136 set: function set(key, val) {
137 var defined = key in this._object;
138 var orig = this._object[key];
139 this._object[key] = val;
141 this.fireEvent("add", key);
142 else if (orig != val)
143 this.fireEvent("change", key);
148 var Storage = Module("Storage", {
155 cleanup: function () {
158 for (let key in keys(this.keys)) {
160 this[key].timer.flush();
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;
172 exists: function exists(name) this.infoPath.child(name).exists(),
174 newObject: function newObject(key, constructor, params) {
175 if (params == null || !isObject(params))
176 throw Error("Invalid argument type");
178 if (!(key in this.keys) || params.reload || this.alwaysReload[key]) {
179 if (key in this && !(params.reload || this.alwaysReload[key]))
181 let load = function () loadData(key, params.store, params.type || myObject);
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]);
187 return this.keys[key];
190 newMap: function newMap(key, options) {
191 return this.newObject(key, ObjectStore, options);
194 newArray: function newArray(key, options) {
195 return this.newObject(key, ArrayStore, update({ type: Array }, options));
198 addObserver: function addObserver(key, callback, ref) {
200 if (!ref.dactylStorageRefs)
201 ref.dactylStorageRefs = [];
202 ref.dactylStorageRefs.push(callback);
203 var callbackRef = Cu.getWeakReference(callback);
206 callbackRef = { get: function () callback };
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 });
215 removeObserver: function (key, callback) {
216 this.removeDeadObservers();
217 if (!(key in this.observers))
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];
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));
228 delete this.observers[key];
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();
242 load: function load(key) {
243 if (this[key].store && this[key].reload)
247 save: function save(key) {
249 saveData(this.keys[key]);
252 saveAll: function storeAll() {
253 for each (let obj in this.keys)
258 get privateMode() this._privateMode,
259 set privateMode(val) {
260 if (val && !this._privateMode)
262 if (!val && this._privateMode)
263 for (let key in this.keys)
265 return this._privateMode = Boolean(val);
269 skipXpcom: function skipXpcom(key, val) val instanceof Ci.nsISupports ? null : val
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);
278 cleanup: function (dactyl, modules, window) {
279 delete window.dactylStorageRefs;
280 this.removeDeadObservers();
285 * @class File A class to wrap nsIFile objects and simplify operations
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
292 var File = Class("File", {
293 init: function (path, checkPWD) {
294 let file = services.File();
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);
302 let expandedPath = File.expandPath(path);
304 if (!File.isAbsolutePath(expandedPath) && checkPWD)
305 file = checkPWD.child(expandedPath);
307 file.initWithPath(expandedPath);
311 return File.DoesNotExist(path, e);
314 let self = XPCSafeJSObjectWrapper(file.QueryInterface(Ci.nsILocalFile));
315 self.__proto__ = this;
320 * Iterates over the objects in this directory.
322 iterDirectory: function () {
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))
332 * Returns a new file for the given child of this directory entry.
334 child: function (name) {
335 let f = this.constructor(this);
336 for each (let elem in name.split(File.pathSplit))
342 * Reads this file's entire contents in "text" mode and returns the
343 * content as a string.
345 * @param {string} encoding The encoding from which to decode the file.
346 * @default options["fileencoding"]
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);
353 return File.readStream(ifstream, encoding);
357 * Returns the list of files in this directory.
359 * @param {boolean} sort Whether to sort the returned directory
361 * @returns {nsIFile[]}
363 readDirectory: function (sort) {
364 if (!this.isDirectory())
365 throw Error("Not a directory");
367 let array = [e for (e in this.iterDirectory())];
369 array.sort(function (a, b) b.isDirectory() - a.isDirectory() || String.localeCompare(a.path, b.path));
374 * Returns a new nsIFileURL object for this file.
376 * @returns {nsIFileURL}
378 toURI: function toURI() services.io.newFileURI(this),
381 * Writes the string *buf* to this file.
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}
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.
401 * @param {string} encoding The encoding to used to write the file.
402 * @default options["fileencoding"]
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);
411 if (buf instanceof File)
415 encoding = File.defaultEncoding;
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;
424 if (!this.exists()) // OCREAT won't create the directory
425 this.create(this.NORMAL_FILE_TYPE, perms);
427 ofstream.init(this, mode, perms, 0);
430 buf(ofstream.QueryInterface(Ci.nsIOutputStream));
432 var ocstream = getStream(0);
433 ocstream.writeString(buf);
436 catch (e if callable(buf) && e.result == Cr.NS_ERROR_LOSS_OF_SIGNIFICANT_DATA) {
437 ocstream = getStream("?".charCodeAt(0));
438 ocstream.writeString(buf);
452 * @property {number} Open for reading only.
458 * @property {number} Open for writing only.
464 * @property {number} Open for reading and writing.
470 * @property {number} If the file does not exist, the file is created.
471 * If the file exists, this flag has no effect.
477 * @property {number} The file pointer is set to the end of the file
478 * prior to each write.
484 * @property {number} If the file exists, its length is truncated to 0.
490 * @property {number} If set, each write will wait for both the file
491 * data and file status to be physically updated.
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
505 * @property {string} The current platform's path separator.
507 PATH_SEP: Class.memoize(function () {
508 let f = services.directory.get("CurProcD", Ci.nsIFile);
510 return f.path.substr(f.parent.path.length, 1);
513 pathSplit: Class.memoize(function () util.regexp("(?:/|" + util.regexp.escape(this.PATH_SEP) + ")", "g")),
515 DoesNotExist: function (path, error) ({
517 exists: function () false,
518 __noSuchMethod__: function () { throw error || Error("Does not exist"); }
521 defaultEncoding: "UTF-8",
524 * Expands "~" and environment variables in *path*.
526 * "~" is expanded to to the value of $HOME. On Windows if this is not
527 * set then the following are tried in order:
529 * ${HOMDRIVE}$HOMEPATH
531 * The variable notation is $VAR (terminated by a non-word character)
532 * or ${VAR}. %VAR% is also supported on Windows.
534 * @param {string} path The unexpanded path string.
535 * @param {boolean} relative Whether the path is relative or absolute.
538 expandPath: function (path, relative) {
539 function getenv(name) services.environment.get(name);
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
554 if (!relative && RegExp("~(?:$|[/" + util.regexp.escape(File.PATH_SEP) + "])").test(path)) {
555 // Try $HOME first, on all systems
556 let home = getenv("HOME");
558 // Windows has its own idiosyncratic $HOME variables.
559 if (win32 && (!home || !File(home).exists()))
560 home = getenv("USERPROFILE") ||
561 getenv("HOMEDRIVE") + getenv("HOMEPATH");
563 path = home + path.substr(1);
566 // TODO: Vim expands paths twice, once before checking for ~, once
567 // after, but doesn't document it. Is this just a bug? --Kris
569 return path.replace("/", File.PATH_SEP, "g");
572 expandPathList: function (list) list.map(this.expandPath),
574 readStream: function (ifstream, encoding) {
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);
581 while (icstream.readString(4096, str) != 0)
582 buffer.push(str.value);
583 return buffer.join("");
591 isAbsolutePath: function (path) {
593 services.File().initWithPath(path);
601 joinPaths: function (head, tail, cwd) {
602 let path = this(head, cwd);
604 // FIXME: should only expand environment vars and normalize path separators
605 path.appendRelativePath(this.expandPath(tail, true));
608 return File.DoesNotExist(e);
613 replacePathSep: function (path) path.replace("/", File.PATH_SEP, "g")
618 // catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
620 // vim: set fdm=marker sw=4 sts=4 et ft=javascript: