home *** CD-ROM | disk | FTP | other *** search
- var misc = {
- dump: function misc_dump(what, depth) {
- function _dump(what, depth, stack) {
- stack.push(what);
-
- var res = "";
- for (let prop in what) {
- let val = what[prop];
- let valStr;
- if ((depth > stack.length) &&
- (val instanceof Object || typeof val == "object") &&
- (stack.indexOf(val) == -1))
- valStr = _dump(val, depth, stack);
- else
- valStr = String(val);
-
- res += (prop + ": " + valStr + "\r\n");
- }
-
- stack.pop();
-
- return res;
- }
-
- return _dump(what, depth, []);
- },
-
- formatError: function misc_formatError(e) {
- if (!(e instanceof this._Ci.nsIException))
- return ("" + e);
-
- let text = e.name + ": " + e.message;
- if (e.fileName)
- text += "\nin " + e.fileName + "\nat line " + e.lineNumber;
-
- return text;
- },
-
- getNavigatorWindows: function misc_getNavigatorWindows() {
- let windows = [],
- wndEnum = this._Cc["@mozilla.org/appshell/window-mediator;1"]
- .getService(this._Ci.nsIWindowMediator)
- .getEnumerator("navigator:browser");
- while (wndEnum.hasMoreElements())
- windows.push(wndEnum.getNext());
-
- return windows;
- },
-
- getTopNavigatorWindow: function() {
- return this.getTopWindowOfType("navigator:browser");
- },
-
- getTopWindowOfType: function(windowType) {
- let mediator = this._Cc["@mozilla.org/appshell/window-mediator;1"].getService(this._Ci.nsIWindowMediator);
- return mediator.getMostRecentWindow(windowType);
- },
-
- openWindow: function(parameters) {
- let window;
-
- if ("name" in parameters && parameters.name) {
- const WM = this._Cc["@mozilla.org/appshell/window-mediator;1"].getService(this._Ci.nsIWindowMediator);
- if ((window = WM.getMostRecentWindow(parameters.name))) {
- window.focus();
- return window;
- }
- }
-
- let parent;
- let features = parameters.features || "";
-
- if (features.indexOf("__popup__") != -1) {
- let featuresHash = { __proto__: null };
-
- features.replace(/(^|,)__popup__($|,)/, "").split(",")
- .forEach(function(aFeatureString) {
- if (aFeatureString) {
- let [name, value] = aFeatureString.split("=");
- if (name)
- featuresHash[name] = value;
- }
- });
-
- function addFeature(aFeatureString) {
- let [name, value] = aFeatureString.split("=");
- if (!(name in featuresHash))
- featuresHash[name] = value;
- }
-
- addFeature("chrome");
- addFeature("dependent=yes");
-
- if (!Ci.nsIDOMGeoPositionAddress)
- addFeature("titlebar=no");
-
- const AppInfo = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).QueryInterface(Ci.nsIXULRuntime);
- if (!/^win/i.test(AppInfo.OS))
- addFeature("popup=yes");
-
- let featuresMod = [];
- for (let [name, value] in Iterator(featuresHash))
- featuresMod.push(name + (value ? "=" + value : ""));
-
- features = featuresMod.join(",");
-
- if (!("parent" in parameters))
- parent = this.getTopNavigatorWindow();
- }
-
- parent = parent || parameters.parent || null;
-
- const WW = this._Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(this._Ci.nsIWindowWatcher);
- window = WW.openWindow(
- parent,
- parameters.url,
- parameters.name || "_blank",
- features,
- parameters.arguments
- );
-
- window.parameters = parameters;
-
- return window;
- },
-
- stringMD5: function misc_stringMD5(str) {
- var converter = this._Cc["@mozilla.org/intl/scriptableunicodeconverter"]
- .createInstance(this._Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
-
- var result = {};
- var data = converter.convertToByteArray(str, result);
- var ch = this._Cc["@mozilla.org/security/hash;1"].createInstance(this._Ci.nsICryptoHash);
- ch.init(ch.MD5);
- ch.update(data, data.length);
- var hash = ch.finish(false);
-
- function toHexString(charCode)
- {
- return ("0" + charCode.toString(16)).slice(-2);
- }
-
- return [toHexString(hash.charCodeAt(i)) for (i in hash)].join("");
- },
-
- camelize: function(string) {
- function camelizeFunction(item, i) {
- if (i != 0)
- return item.charAt(0).toUpperCase() + item.substr(1).toLowerCase();
- return item;
- }
- return string.split("-").map(camelizeFunction).join("");
- },
-
- parseLocale: function misc_parseLocale(localeString) {
- var components = localeString.match(this._localePattern);
- if (components)
- return {
- language: components[1],
- country: components[3],
- region: components[5]
- };
- return null;
- },
-
- get StringBundle() {
- function StringBundle(aURL) {
- this._url = this._createURL(aURL);
- }
-
- StringBundle.prototype = {
- get: function StringBundle_get(key, args) {
- if (args)
- return this._stringBundle.formatStringFromName(key, args, args.length);
-
- return this._stringBundle.GetStringFromName(key);
- },
-
- getPlural: function StringBundle_getPlural(key, pluralData, args) {
- if (typeof pluralData == "number")
- return this._getPluralString(key, pluralData);
-
- let str = this.get(key, args);
-
- pluralData.forEach(function(aData, aIndex) {
- let purIndex = aIndex + 1;
-
- let plurStringKey = (typeof aData == "number" || !("key" in aData))
- ? [key, purIndex, "Plur"].join("")
- : aData.key;
-
- let plurNumber = (typeof aData == "number" ? aData : aData.number) || 0;
- let plurString = this._getPluralString(plurStringKey, plurNumber);
-
- str = str.replace("#" + purIndex, plurString);
- }, this);
-
- return str;
- },
-
- tryGet: function StringBundle_tryGet(key, args, default_) {
- try {
- return this.get(key, args);
- }
- catch (e) {
- return default_;
- }
- },
-
- _defaultPrefixForURL: "chrome://" + APP_NAME + "/locale/",
-
- _createURL: function StringBundle__createURL(aURL) {
- return (/^chrome:\/\//.test(aURL) ? "" : this._defaultPrefixForURL) + aURL;
- },
-
- get _stringBundle() {
- let stringBundle = Cc["@mozilla.org/intl/stringbundle;1"]
- .getService(Ci.nsIStringBundleService)
- .createBundle(this._url);
-
- this.__defineGetter__("_stringBundle", function() stringBundle);
- return this._stringBundle;
- },
-
- _getPluralString: function StringBundle__getPluralString(aStringKey, aNumber) {
- let plurStrings = this.get(aStringKey).split(";");
- let plurStringNone = pluralForm.numForms() < plurStrings.length ? plurStrings.shift() : null;
-
- return (aNumber === 0 && plurStringNone !== null)
- ? plurStringNone
- : pluralForm.get(aNumber, plurStrings.join(";"));
- }
- };
-
- const pluralRule = parseInt(new StringBundle("global.properties").get("pluralRule"), 10);
- const pluralForm = {};
-
- Cu.import("resource://gre/modules/PluralForm.jsm", pluralForm);
- [pluralForm.get, pluralForm.numForms] = pluralForm.PluralForm.makeGetter(pluralRule);
-
- delete this.StringBundle;
- return this.StringBundle = StringBundle;
- },
-
- removeFileSafe: function(file) {
- if (!file.exists())
- return;
- file = file.clone();
-
- try {
- file.remove(true);
- if (!file.exists())
- return;
- }
- catch(e) {
- }
-
- var trash = Components.classes["@mozilla.org/file/directory_service;1"].
- getService(Components.interfaces.nsIProperties).
- get("TmpD", Components.interfaces.nsIFile);
-
- trash.append("trash");
- trash.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0755);
- try {
- file.moveTo(trash, file.leafName);
- }
- catch (e) {
- try {
- file.remove(true);
- }
- catch (e) {
- }
- }
- try {
- trash.remove(true);
- }
- catch (e) {
- }
- },
-
- get DownloadQueue() {
- function DownloadQueue(queue, callback, progressmeter) {
- this.queue = queue;
- this.callback = callback;
- this.progressmeter = progressmeter;
- if (this.progressmeter)
- this.progressmeter.value = 0;
-
- if (this.queue.length == 0) {
- this.checkDefer();
- return;
- }
-
- this.start();
- }
-
- DownloadQueue.prototype = {
- start: function() {
- var failed = false;
- for each (let item in this.queue) {
- try {
- item.uri = item.uri || item.url;
- let uri = Components.classes["@mozilla.org/network/io-service;1"]
- .getService(Components.interfaces.nsIIOService)
- .newURI(item.uri, null, null);
-
- if (!item.file)
- item.file = this.tempFile(item.uri);
-
- let persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
- persist.persistFlags = persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES | persist.PERSIST_FLAGS_BYPASS_CACHE | persist.PERSIST_FLAGS_IGNORE_REDIRECTED_DATA;
- persist.progressListener = {
- item: item,
- owner: this,
- onLocationChange: this.onLocationChange,
- onSecurityChange: this.onSecurityChange,
- onStatusChange: this.onStatusChange,
- onStateChange: this.onStateChange,
- onProgressChange: this.onProgressChange
- };
- persist.saveURI(uri, null, null, null, "", item.file);
- item.persist = persist;
- }
- catch(e) {
- item.done = true;
- item.status = Components.results.NS_ERROR_UNEXPECTED;
- failed = true;
- }
- }
-
- if (failed)
- this.checkDefer();
- },
-
- tempFile: function(uri) {
- if (!this.tempDirectory) {
- this.tempDirectory = Components.classes["@mozilla.org/file/directory_service;1"].
- getService(Components.interfaces.nsIProperties).
- get("TmpD", Components.interfaces.nsIFile);
- }
-
- let file = this.tempDirectory.clone();
- file.append(misc.stringMD5(uri));
- file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);
- return file;
- },
-
- destroy: function() {
- this.clean();
- },
-
- clean: function() {
- for each (let item in this.queue) {
- try {
- if (item.persist)
- item.persist.cancelSave();
- }
- catch(e) {}
- try {
- if (item.file)
- misc.removeFileSafe(item.file);
- }
- catch(e) {}
- }
- },
-
- checkDefer: function() {
- var context = this;
- (this._timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer))
- .initWithCallback({notify: function() { context.check(); }}, 1, Ci.nsITimer.TYPE_ONE_SHOT);
- },
-
- check: function() {
- var done = true;
- for each (item in this.queue)
- if (!item.done) {
- done = false;
- break;
- }
-
- if (done)
- this.callback(this.queue);
- },
-
- onLocationChange: function(webProgress, request, location) {
- },
-
- onSecurityChange: function(webProgress, request, state) {
- },
-
- onStatusChange: function(webProgress, request, status, message) {
- },
-
- onStateChange: function(webProgress, request, state, message) {
- if (state & Components.interfaces.nsIWebProgressListener.STATE_STOP) {
- var item = this.item,
- owner = this.owner,
- queue = owner.queue;
-
- var httpStatus = 400; // 400: Bad Request
- try {
- httpStatus = request.QueryInterface(Components.interfaces.nsIHttpChannel).responseStatus;
- }
- catch (e) {
- // no problem
- }
- item.httpStatus = httpStatus;
- item.status = request.status;
- if (item.httpStatus >= 400)
- item.status = Components.results.NS_ERROR_UNEXPECTED;
- item.done = true;
-
- owner.check();
- }
- },
-
- onProgressChange: function(webProgress, request, currentSelfProgress, maxSelfProgress, currentTotalProgress, maxTotalProgress) {
- var item = this.item,
- owner = this.owner,
- queue = owner.queue;
- if (!item || !owner || queue.length <= 0)
- return;
- item.percent = (maxTotalProgress <= 0 ? 1 : (currentTotalProgress / maxTotalProgress)) * 100;
- var total = 0;
- for each (item in queue)
- total += item.percent;
-
- if (this.owner.progressmeter)
- this.owner.progressmeter.value = total / queue.length;
- }
- };
-
- delete this.DownloadQueue;
- return this.DownloadQueue = DownloadQueue;
- },
-
- _Cc: Components.classes,
- _Ci: Components.interfaces,
- _Cu: Components.utils,
- _Cr: Components.results,
-
- _localePattern: /^([a-z]{2})(-([A-Z]{2})(-(\w{2,5}))?)?$/
- };
-