1
0
mirror of https://github.com/gryf/pentadactyl-pm.git synced 2025-12-20 08:27:59 +01:00

Do away with services.(get|create), and move the prefs module to its own file.

This commit is contained in:
Kris Maglione
2010-12-01 21:57:51 -05:00
parent 0bf9cfb0bc
commit 5d51fd491a
26 changed files with 540 additions and 516 deletions

View File

@@ -61,7 +61,7 @@ const Bookmarks = Module("bookmarks", {
if (bmark.url == uri.spec) { if (bmark.url == uri.spec) {
var id = bmark.id; var id = bmark.id;
if (title) if (title)
services.get("bookmarks").setItemTitle(id, title); services.bookmarks.setItemTitle(id, title);
break; break;
} }
@@ -70,8 +70,8 @@ const Bookmarks = Module("bookmarks", {
PlacesUtils.tagging.tagURI(uri, tags); PlacesUtils.tagging.tagURI(uri, tags);
} }
if (id == undefined) if (id == undefined)
id = services.get("bookmarks").insertBookmark( id = services.bookmarks.insertBookmark(
services.get("bookmarks")[unfiled ? "unfiledBookmarksFolder" : "bookmarksMenuFolder"], services.bookmarks[unfiled ? "unfiledBookmarksFolder" : "bookmarksMenuFolder"],
uri, -1, title || url); uri, -1, title || url);
if (!id) if (!id)
return false; return false;
@@ -79,7 +79,7 @@ const Bookmarks = Module("bookmarks", {
if (post !== undefined) if (post !== undefined)
PlacesUtils.setPostDataForBookmark(id, post); PlacesUtils.setPostDataForBookmark(id, post);
if (keyword) if (keyword)
services.get("bookmarks").setKeywordForBookmark(id, keyword); services.bookmarks.setKeywordForBookmark(id, keyword);
} }
catch (e) { catch (e) {
dactyl.log(e, 0); dactyl.log(e, 0);
@@ -141,7 +141,7 @@ const Bookmarks = Module("bookmarks", {
*/ */
isBookmarked: function isBookmarked(url) { isBookmarked: function isBookmarked(url) {
try { try {
return services.get("bookmarks") return services.bookmarks
.getBookmarkIdsForURI(makeURI(url), {}) .getBookmarkIdsForURI(makeURI(url), {})
.some(bookmarkcache.closure.isRegularBookmark); .some(bookmarkcache.closure.isRegularBookmark);
} }
@@ -163,7 +163,7 @@ const Bookmarks = Module("bookmarks", {
try { try {
if (!isArray(ids)) { if (!isArray(ids)) {
let uri = util.newURI(ids); let uri = util.newURI(ids);
ids = services.get("bookmarks") ids = services.bookmarks
.getBookmarkIdsForURI(uri, {}) .getBookmarkIdsForURI(uri, {})
.filter(bookmarkcache.closure.isRegularBookmark); .filter(bookmarkcache.closure.isRegularBookmark);
} }
@@ -171,7 +171,7 @@ const Bookmarks = Module("bookmarks", {
let bmark = bookmarkcache.bookmarks[id]; let bmark = bookmarkcache.bookmarks[id];
if (bmark) if (bmark)
PlacesUtils.tagging.untagURI(util.newURI(bmark.url), null); PlacesUtils.tagging.untagURI(util.newURI(bmark.url), null);
services.get("bookmarks").removeItem(id); services.bookmarks.removeItem(id);
}); });
return ids.length; return ids.length;
} }
@@ -199,7 +199,7 @@ const Bookmarks = Module("bookmarks", {
get searchEngines() { get searchEngines() {
let searchEngines = []; let searchEngines = [];
let aliases = {}; let aliases = {};
return services.get("browserSearch").getVisibleEngines({}).map(function (engine) { return services.browserSearch.getVisibleEngines({}).map(function (engine) {
let alias = engine.alias; let alias = engine.alias;
if (!alias || !/^[a-z_-]+$/.test(alias)) if (!alias || !/^[a-z_-]+$/.test(alias))
alias = engine.name.replace(/^\W*([a-zA-Z_-]+).*/, "$1").toLowerCase(); alias = engine.name.replace(/^\W*([a-zA-Z_-]+).*/, "$1").toLowerCase();
@@ -290,7 +290,7 @@ const Bookmarks = Module("bookmarks", {
param = url.substr(offset + 1); param = url.substr(offset + 1);
} }
var engine = services.get("browserSearch").getEngineByAlias(keyword); var engine = services.browserSearch.getEngineByAlias(keyword);
if (engine) { if (engine) {
var submission = engine.getSubmission(param, null); var submission = engine.getSubmission(param, null);
return [submission.uri.spec, submission.postData]; return [submission.uri.spec, submission.postData];
@@ -308,7 +308,7 @@ const Bookmarks = Module("bookmarks", {
[, shortcutURL, charset] = matches; [, shortcutURL, charset] = matches;
else { else {
try { try {
charset = services.get("history").getCharsetForURI(window.makeURI(shortcutURL)); charset = services.history.getCharsetForURI(window.makeURI(shortcutURL));
} }
catch (e) {} catch (e) {}
} }
@@ -499,7 +499,7 @@ const Bookmarks = Module("bookmarks", {
commandline.input("This will delete all bookmarks. Would you like to continue? (yes/[no]) ", commandline.input("This will delete all bookmarks. Would you like to continue? (yes/[no]) ",
function (resp) { function (resp) {
if (resp && resp.match(/^y(es)?$/i)) { if (resp && resp.match(/^y(es)?$/i)) {
Object.keys(bookmarkcache.bookmarks).forEach(function (id) { services.get("bookmarks").removeItem(id); }); Object.keys(bookmarkcache.bookmarks).forEach(function (id) { services.bookmarks.removeItem(id); });
dactyl.echomsg("All bookmarks deleted", 1, commandline.FORCE_SINGLELINE); dactyl.echomsg("All bookmarks deleted", 1, commandline.FORCE_SINGLELINE);
} }
}); });
@@ -632,7 +632,7 @@ const Bookmarks = Module("bookmarks", {
}; };
completion.searchEngine = function searchEngine(context, suggest) { completion.searchEngine = function searchEngine(context, suggest) {
let engines = services.get("browserSearch").getEngines({}); let engines = services.browserSearch.getEngines({});
if (suggest) if (suggest)
engines = engines.filter(function (e) e.supportsResponseType("application/x-suggestions+json")); engines = engines.filter(function (e) e.supportsResponseType("application/x-suggestions+json"));
@@ -647,7 +647,7 @@ const Bookmarks = Module("bookmarks", {
let engineList = (engineAliases || options["suggestengines"].join(",") || "google").split(","); let engineList = (engineAliases || options["suggestengines"].join(",") || "google").split(",");
engineList.forEach(function (name) { engineList.forEach(function (name) {
let engine = services.get("browserSearch").getEngineByAlias(name); let engine = services.browserSearch.getEngineByAlias(name);
if (!engine) if (!engine)
return; return;
let [, word] = /^\s*(\S+)/.exec(context.filter) || []; let [, word] = /^\s*(\S+)/.exec(context.filter) || [];

View File

@@ -89,7 +89,7 @@ const Buffer = Module("buffer", {
for (let proto in array.iterValues(["HTTP", "FTP"])) { for (let proto in array.iterValues(["HTTP", "FTP"])) {
try { try {
var cacheEntryDescriptor = services.get("cache").createSession(proto, 0, true) var cacheEntryDescriptor = services.cache.createSession(proto, 0, true)
.openCacheEntry(cacheKey, ACCESS_READ, false); .openCacheEntry(cacheKey, ACCESS_READ, false);
break; break;
} }
@@ -977,7 +977,7 @@ const Buffer = Module("buffer", {
if (!isString(doc)) if (!isString(doc))
return io.withTempFiles(function (temp) { return io.withTempFiles(function (temp) {
let encoder = services.create("htmlEncoder"); let encoder = services.HtmlEncoder();
encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted); encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted);
temp.write(encoder.encodeToString(), ">"); temp.write(encoder.encodeToString(), ">");
this.callback(temp); this.callback(temp);

View File

@@ -666,8 +666,8 @@ const CommandLine = Module("commandline", {
} }
if ((flags & this.ACTIVE_WINDOW) && if ((flags & this.ACTIVE_WINDOW) &&
window != services.get("windowWatcher").activeWindow && window != services.windowWatcher.activeWindow &&
services.get("windowWatcher").activeWindow.dactyl) services.windowWatcher.activeWindow.dactyl)
return; return;
if ((flags & this.DISALLOW_MULTILINE) && !this.widgets.mowContainer.collapsed) if ((flags & this.DISALLOW_MULTILINE) && !this.widgets.mowContainer.collapsed)

View File

@@ -12,10 +12,10 @@ const ConfigBase = Class(ModuleBase, {
* initialization code. Must call superclass's init function. * initialization code. Must call superclass's init function.
*/ */
init: function () { init: function () {
this.name = services.get("dactyl:").name; this.name = services["dactyl:"].name;
this.idName = services.get("dactyl:").idName; this.idName = services["dactyl:"].idName;
this.appName = services.get("dactyl:").appName; this.appName = services["dactyl:"].appName;
this.host = services.get("dactyl:").host; this.host = services["dactyl:"].host;
highlight.styleableChrome = this.styleableChrome; highlight.styleableChrome = this.styleableChrome;
highlight.loadCSS(this.CSS); highlight.loadCSS(this.CSS);

View File

@@ -53,10 +53,11 @@
let prefix = [BASE]; let prefix = [BASE];
modules.load("services"); modules.load("services");
prefix.unshift("chrome://" + modules.services.get("dactyl:").name + "/content/"); prefix.unshift("chrome://" + modules.services["dactyl:"].name + "/content/");
["base", ["base",
"modules", "modules",
"prefs",
"storage", "storage",
"util", "util",
"dactyl", "dactyl",

View File

@@ -52,14 +52,14 @@ const Dactyl = Module("dactyl", {
/** @property {string} The name of the current user profile. */ /** @property {string} The name of the current user profile. */
profileName: Class.memoize(function () { profileName: Class.memoize(function () {
// NOTE: services.get("profile").selectedProfile.name doesn't return // NOTE: services.profile.selectedProfile.name doesn't return
// what you might expect. It returns the last _actively_ selected // what you might expect. It returns the last _actively_ selected
// profile (i.e. via the Profile Manager or -P option) rather than the // profile (i.e. via the Profile Manager or -P option) rather than the
// current profile. These will differ if the current process was run // current profile. These will differ if the current process was run
// without explicitly selecting a profile. // without explicitly selecting a profile.
let dir = services.get("directory").get("ProfD", Ci.nsIFile); let dir = services.directory.get("ProfD", Ci.nsIFile);
for (let prof in iter(services.get("profile").profiles)) for (let prof in iter(services.profile.profiles))
if (prof.QueryInterface(Ci.nsIToolkitProfile).localDir.path === dir.path) if (prof.QueryInterface(Ci.nsIToolkitProfile).localDir.path === dir.path)
return prof.name; return prof.name;
return "unknown"; return "unknown";
@@ -297,7 +297,7 @@ const Dactyl = Module("dactyl", {
* should be loaded. * should be loaded.
*/ */
loadScript: function (uri, context) { loadScript: function (uri, context) {
services.get("subscriptLoader").loadSubScript(uri, context, File.defaultEncoding); services.subscriptLoader.loadSubScript(uri, context, File.defaultEncoding);
}, },
userEval: function (str, context, fileName, lineNumber) { userEval: function (str, context, fileName, lineNumber) {
@@ -359,7 +359,7 @@ const Dactyl = Module("dactyl", {
* element. * element.
*/ */
focusContent: function (clearFocusedElement) { focusContent: function (clearFocusedElement) {
if (window != services.get("windowWatcher").activeWindow) if (window != services.windowWatcher.activeWindow)
return; return;
let win = document.commandDispatcher.focusedWindow; let win = document.commandDispatcher.focusedWindow;
@@ -412,7 +412,7 @@ const Dactyl = Module("dactyl", {
* @returns {string} * @returns {string}
*/ */
findHelp: function (topic, unchunked) { findHelp: function (topic, unchunked) {
if (!unchunked && topic in services.get("dactyl:").FILE_MAP) if (!unchunked && topic in services["dactyl:"].FILE_MAP)
return topic; return topic;
unchunked = !!unchunked; unchunked = !!unchunked;
let items = completion._runCompleter("help", topic, null, unchunked).items; let items = completion._runCompleter("help", topic, null, unchunked).items;
@@ -444,11 +444,11 @@ const Dactyl = Module("dactyl", {
} }
let namespaces = [config.name, "dactyl"]; let namespaces = [config.name, "dactyl"];
services.get("dactyl:").init({}); services["dactyl:"].init({});
let tagMap = services.get("dactyl:").HELP_TAGS; let tagMap = services["dactyl:"].HELP_TAGS;
let fileMap = services.get("dactyl:").FILE_MAP; let fileMap = services["dactyl:"].FILE_MAP;
let overlayMap = services.get("dactyl:").OVERLAY_MAP; let overlayMap = services["dactyl:"].OVERLAY_MAP;
// Find help and overlay files with the given name. // Find help and overlay files with the given name.
function findHelpFile(file) { function findHelpFile(file) {
@@ -544,11 +544,11 @@ const Dactyl = Module("dactyl", {
const TIME = Date.now(); const TIME = Date.now();
dactyl.initHelp(); dactyl.initHelp();
let zip = services.create("zipWriter"); let zip = services.ZipWriter();
zip.open(FILE, File.MODE_CREATE | File.MODE_WRONLY | File.MODE_TRUNCATE); zip.open(FILE, File.MODE_CREATE | File.MODE_WRONLY | File.MODE_TRUNCATE);
function addURIEntry(file, uri) function addURIEntry(file, uri)
zip.addEntryChannel(PATH + file, TIME, 9, zip.addEntryChannel(PATH + file, TIME, 9,
services.get("io").newChannel(uri, null, null), false); services.io.newChannel(uri, null, null), false);
function addDataEntry(file, data) // Unideal to an extreme. function addDataEntry(file, data) // Unideal to an extreme.
addURIEntry(file, "data:text/plain;charset=UTF-8," + encodeURI(data)); addURIEntry(file, "data:text/plain;charset=UTF-8," + encodeURI(data));
@@ -557,7 +557,7 @@ const Dactyl = Module("dactyl", {
let chrome = {}; let chrome = {};
let styles = {}; let styles = {};
for (let [file, ] in Iterator(services.get("dactyl:").FILE_MAP)) { for (let [file, ] in Iterator(services["dactyl:"].FILE_MAP)) {
dactyl.open("dactyl://help/" + file); dactyl.open("dactyl://help/" + file);
dactyl.modules.events.waitForPageLoad(); dactyl.modules.events.waitForPageLoad();
let data = [ let data = [
@@ -584,7 +584,7 @@ const Dactyl = Module("dactyl", {
if (name == "href") { if (name == "href") {
value = node.href; value = node.href;
if (value.indexOf("dactyl://help-tag/") == 0) { if (value.indexOf("dactyl://help-tag/") == 0) {
let uri = services.get("io").newChannel(value, null, null).originalURI; let uri = services.io.newChannel(value, null, null).originalURI;
value = uri.spec == value ? "javascript:;" : uri.path.substr(1); value = uri.spec == value ? "javascript:;" : uri.path.substr(1);
} }
if (!/^#|[\/](#|$)|^[a-z]+:/.test(value)) if (!/^#|[\/](#|$)|^[a-z]+:/.test(value))
@@ -725,7 +725,7 @@ const Dactyl = Module("dactyl", {
if (!topic) { if (!topic) {
let helpFile = unchunked ? "all" : options["helpfile"]; let helpFile = unchunked ? "all" : options["helpfile"];
if (helpFile in services.get("dactyl:").FILE_MAP) if (helpFile in services["dactyl:"].FILE_MAP)
dactyl.open("dactyl://help/" + helpFile, { from: "help" }); dactyl.open("dactyl://help/" + helpFile, { from: "help" });
else else
dactyl.echomsg("Sorry, help file " + helpFile.quote() + " not found"); dactyl.echomsg("Sorry, help file " + helpFile.quote() + " not found");
@@ -803,7 +803,7 @@ const Dactyl = Module("dactyl", {
if (isObject(msg)) if (isObject(msg))
msg = util.objectToString(msg, false); msg = util.objectToString(msg, false);
services.get("console").logStringMessage(config.name + ": " + msg); services.console.logStringMessage(config.name + ": " + msg);
} }
}, },
@@ -891,7 +891,7 @@ const Dactyl = Module("dactyl", {
case dactyl.NEW_WINDOW: case dactyl.NEW_WINDOW:
window.open(); window.open();
let win = services.get("windowMediator").getMostRecentWindow("navigator:browser"); let win = services.windowMediator.getMostRecentWindow("navigator:browser");
win.loadURI(url, null, postdata); win.loadURI(url, null, postdata);
browser = win.getBrowser(); browser = win.getBrowser();
break; break;
@@ -944,7 +944,7 @@ const Dactyl = Module("dactyl", {
if (!saveSession && prefs.get(pref) >= 2) if (!saveSession && prefs.get(pref) >= 2)
prefs.safeSet(pref, 1); prefs.safeSet(pref, 1);
services.get("appStartup").quit(Ci.nsIAppStartup[force ? "eForceQuit" : "eAttemptQuit"]); services.appStartup.quit(Ci.nsIAppStartup[force ? "eForceQuit" : "eAttemptQuit"]);
}, },
/** /**
@@ -971,7 +971,7 @@ const Dactyl = Module("dactyl", {
// Try to find a matching file. // Try to find a matching file.
let file = io.File(url); let file = io.File(url);
if (file.exists() && file.isReadable()) if (file.exists() && file.isReadable())
return services.get("io").newFileURI(file).spec; return services.io.newFileURI(file).spec;
} }
catch (e) {} catch (e) {}
} }
@@ -1052,7 +1052,7 @@ const Dactyl = Module("dactyl", {
if (!canQuitApplication()) if (!canQuitApplication())
return; return;
services.get("appStartup").quit(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart); services.appStartup.quit(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart);
}, },
/** /**
@@ -1103,7 +1103,7 @@ const Dactyl = Module("dactyl", {
* @property {Window[]} Returns an array of all the host application's * @property {Window[]} Returns an array of all the host application's
* open windows. * open windows.
*/ */
get windows() [win for (win in iter(services.get("windowMediator").getEnumerator("navigator:browser")))], get windows() [win for (win in iter(services.windowMediator.getEnumerator("navigator:browser")))],
}, { }, {
// initially hide all GUI elements, they are later restored unless the user // initially hide all GUI elements, they are later restored unless the user
@@ -1269,14 +1269,14 @@ const Dactyl = Module("dactyl", {
// TODO: remove this FF3.5 test when we no longer support 3.0 // TODO: remove this FF3.5 test when we no longer support 3.0
// : make this a config feature // : make this a config feature
if (services.get("privateBrowsing")) { if (services.privateBrowsing) {
let oldValue = win.getAttribute("titlemodifier_normal"); let oldValue = win.getAttribute("titlemodifier_normal");
let suffix = win.getAttribute("titlemodifier_privatebrowsing").substr(oldValue.length); let suffix = win.getAttribute("titlemodifier_privatebrowsing").substr(oldValue.length);
win.setAttribute("titlemodifier_normal", value); win.setAttribute("titlemodifier_normal", value);
win.setAttribute("titlemodifier_privatebrowsing", value + suffix); win.setAttribute("titlemodifier_privatebrowsing", value + suffix);
if (services.get("privateBrowsing").privateBrowsingEnabled) { if (services.privateBrowsing.privateBrowsingEnabled) {
updateTitle(oldValue + suffix, value + suffix); updateTitle(oldValue + suffix, value + suffix);
return value; return value;
} }
@@ -1399,18 +1399,18 @@ const Dactyl = Module("dactyl", {
callback = callback || util.identity; callback = callback || util.identity;
let addon = id; let addon = id;
if (!isObject(addon)) if (!isObject(addon))
addon = services.get("extensionManager").getItemForID(id); addon = services.extensionManager.getItemForID(id);
if (!addon) if (!addon)
return callback(null); return callback(null);
addon = Object.create(addon); addon = Object.create(addon);
function getRdfProperty(item, property) { function getRdfProperty(item, property) {
let resource = services.get("rdf").GetResource("urn:mozilla:item:" + item.id); let resource = services.rdf.GetResource("urn:mozilla:item:" + item.id);
let value = ""; let value = "";
if (resource) { if (resource) {
let target = services.get("extensionManager").datasource.GetTarget(resource, let target = services.extensionManager.datasource.GetTarget(resource,
services.get("rdf").GetResource("http://www.mozilla.org/2004/em-rdf#" + property), true); services.rdf.GetResource("http://www.mozilla.org/2004/em-rdf#" + property), true);
if (target && target instanceof Ci.nsIRDFLiteral) if (target && target instanceof Ci.nsIRDFLiteral)
value = target.Value; value = target.Value;
} }
@@ -1426,12 +1426,12 @@ const Dactyl = Module("dactyl", {
addon.isActive = getRdfProperty(addon, "isDisabled") != "true"; addon.isActive = getRdfProperty(addon, "isDisabled") != "true";
addon.uninstall = function () { addon.uninstall = function () {
services.get("extensionManager").uninstallItem(this.id); services.extensionManager.uninstallItem(this.id);
}; };
addon.appDisabled = false; addon.appDisabled = false;
addon.__defineGetter__("userDisabled", function () getRdfProperty(addon, "userDisabled") === "true"); addon.__defineGetter__("userDisabled", function () getRdfProperty(addon, "userDisabled") === "true");
addon.__defineSetter__("userDisabled", function (val) { addon.__defineSetter__("userDisabled", function (val) {
services.get("extensionManager")[val ? "disableItem" : "enableItem"](this.id); services.extensionManager[val ? "disableItem" : "enableItem"](this.id);
}); });
return callback(addon); return callback(addon);
@@ -1439,7 +1439,7 @@ const Dactyl = Module("dactyl", {
getAddonsByTypes: function (types, callback) { getAddonsByTypes: function (types, callback) {
let res = []; let res = [];
for (let [, type] in Iterator(types)) for (let [, type] in Iterator(types))
for (let [, item] in Iterator(services.get("extensionManager") for (let [, item] in Iterator(services.extensionManager
.getItemList(Ci.nsIUpdateItem["TYPE_" + type.toUpperCase()], {}))) .getItemList(Ci.nsIUpdateItem["TYPE_" + type.toUpperCase()], {})))
res.push(this.getAddonByID(item)); res.push(this.getAddonByID(item));
callback(res); callback(res);
@@ -1448,7 +1448,7 @@ const Dactyl = Module("dactyl", {
callback({ callback({
addListener: function () {}, addListener: function () {},
install: function () { install: function () {
services.get("extensionManager").installItemFromFile(file, "app-profile"); services.extensionManager.installItemFromFile(file, "app-profile");
} }
}); });
}, },
@@ -1486,7 +1486,7 @@ const Dactyl = Module("dactyl", {
const updateAddons = Class("UpgradeListener", { const updateAddons = Class("UpgradeListener", {
init: function init(addons) { init: function init(addons) {
dactyl.assert(!addons.length || addons[0].findUpdates, dactyl.assert(!addons.length || addons[0].findUpdates,
"Not available on " + config.host + " " + services.get("runtime").version); "Not available on " + config.host + " " + services.runtime.version);
this.remaining = addons; this.remaining = addons;
this.upgrade = []; this.upgrade = [];
dactyl.echomsg("Checking updates for addons: " + addons.map(function (a) a.name).join(", ")); dactyl.echomsg("Checking updates for addons: " + addons.map(function (a) a.name).join(", "));
@@ -1953,7 +1953,7 @@ const Dactyl = Module("dactyl", {
dactyl.initHelp(); dactyl.initHelp();
context.title = ["Help"]; context.title = ["Help"];
context.anchored = false; context.anchored = false;
context.completions = services.get("dactyl:").HELP_TAGS; context.completions = services["dactyl:"].HELP_TAGS;
if (unchunked) if (unchunked)
context.keys = { text: 0, description: function () "all" }; context.keys = { text: 0, description: function () "all" };
}; };
@@ -1983,17 +1983,17 @@ const Dactyl = Module("dactyl", {
dactyl.log("All modules loaded", 3); dactyl.log("All modules loaded", 3);
AddonManager.getAddonByID(services.get("dactyl:").addonID, function (addon) { AddonManager.getAddonByID(services["dactyl:"].addonID, function (addon) {
// @DATE@ token replaced by the Makefile // @DATE@ token replaced by the Makefile
// TODO: Find it automatically // TODO: Find it automatically
prefs.set("extensions.dactyl.version", addon.version); prefs.set("extensions.dactyl.version", addon.version);
dactyl.version = addon.version + " (created: @DATE@)"; dactyl.version = addon.version + " (created: @DATE@)";
}); });
if (!services.get("commandLineHandler")) if (!services.commandLineHandler)
services.add("commandLineHandler", "@mozilla.org/commandlinehandler/general-startup;1?type=" + config.name); services.add("commandLineHandler", "@mozilla.org/commandlinehandler/general-startup;1?type=" + config.name);
let commandline = services.get("commandLineHandler").optionValue; let commandline = services.commandLineHandler.optionValue;
if (commandline) { if (commandline) {
let args = dactyl.parseCommandLine(commandline); let args = dactyl.parseCommandLine(commandline);
dactyl.commandLineOptions.rcFile = args["+u"]; dactyl.commandLineOptions.rcFile = args["+u"];
@@ -2028,7 +2028,7 @@ const Dactyl = Module("dactyl", {
// finally, read the RC file and source plugins // finally, read the RC file and source plugins
// make sourcing asynchronous, otherwise commands that open new tabs won't work // make sourcing asynchronous, otherwise commands that open new tabs won't work
util.timeout(function () { util.timeout(function () {
let init = services.get("environment").get(config.idName + "_INIT"); let init = services.environment.get(config.idName + "_INIT");
let rcFile = io.getRCFile("~"); let rcFile = io.getRCFile("~");
if (dactyl.userEval('typeof document') === "undefined") if (dactyl.userEval('typeof document') === "undefined")
@@ -2046,7 +2046,7 @@ const Dactyl = Module("dactyl", {
else { else {
if (rcFile) { if (rcFile) {
io.source(rcFile.path, false); io.source(rcFile.path, false);
services.get("environment").set("MY_" + config.idName + "RC", rcFile.path); services.environment.set("MY_" + config.idName + "RC", rcFile.path);
} }
else else
dactyl.log("No user RC file found", 3); dactyl.log("No user RC file found", 3);

View File

@@ -306,7 +306,7 @@ const Editor = Module("editor", {
} }
} }
let timer = services.create("timer"); let timer = services.Timer();
timer.initWithCallback({ notify: update }, 100, timer.TYPE_REPEATING_SLACK); timer.initWithCallback({ notify: update }, 100, timer.TYPE_REPEATING_SLACK);
try { try {

View File

@@ -264,7 +264,7 @@ const RangeFind = Class("RangeFind", {
this.elementPath = elementPath || null; this.elementPath = elementPath || null;
this.reverse = Boolean(backward); this.reverse = Boolean(backward);
this.finder = services.create("find"); this.finder = services.Find();
this.matchCase = Boolean(matchCase); this.matchCase = Boolean(matchCase);
this.regexp = Boolean(regexp); this.regexp = Boolean(regexp);

View File

@@ -9,12 +9,12 @@
const History = Module("history", { const History = Module("history", {
get format() bookmarks.format, get format() bookmarks.format,
get service() services.get("history"), get service() services.history,
get: function get(filter, maxItems) { get: function get(filter, maxItems) {
// no query parameters will get all history // no query parameters will get all history
let query = services.get("history").getNewQuery(); let query = services.history.getNewQuery();
let options = services.get("history").getNewQueryOptions(); let options = services.history.getNewQueryOptions();
if (typeof filter == "string") if (typeof filter == "string")
filter = { searchTerms: filter }; filter = { searchTerms: filter };
@@ -26,7 +26,7 @@ const History = Module("history", {
options.maxResults = maxItems; options.maxResults = maxItems;
// execute the query // execute the query
let root = services.get("history").executeQuery(query, options).root; let root = services.history.executeQuery(query, options).root;
root.containerOpen = true; root.containerOpen = true;
let items = util.map(util.range(0, root.childCount), function (i) { let items = util.map(util.range(0, root.childCount), function (i) {
let node = root.getChild(i); let node = root.getChild(i);
@@ -50,7 +50,7 @@ const History = Module("history", {
obj[i] = update(Object.create(sh.getEntryAtIndex(i, false)), obj[i] = update(Object.create(sh.getEntryAtIndex(i, false)),
{ index: i }); { index: i });
memoize(obj[i], "icon", memoize(obj[i], "icon",
function () services.get("favicon").getFaviconImageForPage(this.URI).spec); function () services.favicon.getFaviconImageForPage(this.URI).spec);
} }
return obj; return obj;
}, },
@@ -213,7 +213,7 @@ const History = Module("history", {
// FIXME: Schema-specific // FIXME: Schema-specific
context.generate = function () [ context.generate = function () [
Array.slice(row.rev_host).reverse().join("").slice(1) Array.slice(row.rev_host).reverse().join("").slice(1)
for (row in iter(services.get("history").DBConnection for (row in iter(services.history.DBConnection
.createStatement("SELECT DISTINCT rev_host FROM moz_places;"))) .createStatement("SELECT DISTINCT rev_host FROM moz_places;")))
].slice(2); ].slice(2);
}; };

View File

@@ -39,7 +39,7 @@ function Script(file) {
*/ */
const IO = Module("io", { const IO = Module("io", {
init: function () { init: function () {
this._processDir = services.get("directory").get("CurWorkD", Ci.nsIFile); this._processDir = services.directory.get("CurWorkD", Ci.nsIFile);
this._cwd = this._processDir.path; this._cwd = this._processDir.path;
this._oldcwd = null; this._oldcwd = null;
@@ -48,7 +48,7 @@ const IO = Module("io", {
this.downloadListener = { this.downloadListener = {
onDownloadStateChange: function (state, download) { onDownloadStateChange: function (state, download) {
if (download.state == services.get("downloadManager").DOWNLOAD_FINISHED) { if (download.state == services.downloadManager.DOWNLOAD_FINISHED) {
let url = download.source.spec; let url = download.source.spec;
let title = download.displayName; let title = download.displayName;
let file = download.targetFile.path; let file = download.targetFile.path;
@@ -64,7 +64,7 @@ const IO = Module("io", {
onSecurityChange: function () {} onSecurityChange: function () {}
}; };
services.get("downloadManager").addListener(this.downloadListener); services.downloadManager.addListener(this.downloadListener);
}, },
// TODO: there seems to be no way, short of a new component, to change // TODO: there seems to be no way, short of a new component, to change
@@ -112,7 +112,7 @@ const IO = Module("io", {
}, },
destroy: function () { destroy: function () {
services.get("downloadManager").removeListener(this.downloadListener); services.downloadManager.removeListener(this.downloadListener);
for (let [, plugin] in Iterator(plugins.contexts)) for (let [, plugin] in Iterator(plugins.contexts))
if (plugin.onUnload) if (plugin.onUnload)
plugin.onUnload(); plugin.onUnload();
@@ -199,7 +199,7 @@ const IO = Module("io", {
* @returns {File} * @returns {File}
*/ */
createTempFile: function () { createTempFile: function () {
let file = services.get("directory").get("TmpD", Ci.nsIFile); let file = services.directory.get("TmpD", Ci.nsIFile);
file.append(config.tempFile); file.append(config.tempFile);
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt('0600', 8)); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt('0600', 8));
@@ -230,7 +230,7 @@ const IO = Module("io", {
if (File.isAbsolutePath(program)) if (File.isAbsolutePath(program))
file = io.File(program, true); file = io.File(program, true);
else { else {
let dirs = services.get("environment").get("PATH").split(util.OS.isWindows ? ";" : ":"); let dirs = services.environment.get("PATH").split(util.OS.isWindows ? ";" : ":");
// Windows tries the CWD first TODO: desirable? // Windows tries the CWD first TODO: desirable?
if (util.OS.isWindows) if (util.OS.isWindows)
dirs = [io.cwd].concat(dirs); dirs = [io.cwd].concat(dirs);
@@ -245,7 +245,7 @@ lookup:
// TODO: couldn't we just palm this off to the start command? // TODO: couldn't we just palm this off to the start command?
// automatically try to add the executable path extensions on windows // automatically try to add the executable path extensions on windows
if (util.OS.isWindows) { if (util.OS.isWindows) {
let extensions = services.get("environment").get("PATHEXT").split(";"); let extensions = services.environment.get("PATHEXT").split(";");
for (let [, extension] in Iterator(extensions)) { for (let [, extension] in Iterator(extensions)) {
file = File.joinPaths(dir, program + extension, io.cwd); file = File.joinPaths(dir, program + extension, io.cwd);
if (file.exists()) if (file.exists())
@@ -262,7 +262,7 @@ lookup:
return -1; return -1;
} }
let process = services.create("process"); let process = services.Process();
process.init(file); process.init(file);
process.run(false, args.map(String), args.length); process.run(false, args.map(String), args.length);
@@ -338,7 +338,7 @@ lookup:
dactyl.echomsg("sourcing " + filename.quote(), 2); dactyl.echomsg("sourcing " + filename.quote(), 2);
let uri = services.get("io").newFileURI(file); let uri = services.io.newFileURI(file);
// handle pure JavaScript files specially // handle pure JavaScript files specially
if (/\.js$/.test(filename)) { if (/\.js$/.test(filename)) {
@@ -455,10 +455,10 @@ lookup:
*/ */
get runtimePath() { get runtimePath() {
const rtpvar = config.idName + "_RUNTIME"; const rtpvar = config.idName + "_RUNTIME";
let rtp = services.get("environment").get(rtpvar); let rtp = services.environment.get(rtpvar);
if (!rtp) { if (!rtp) {
rtp = "~/" + (util.OS.isWindows ? "" : ".") + config.name; rtp = "~/" + (util.OS.isWindows ? "" : ".") + config.name;
services.get("environment").set(rtpvar, rtp); services.environment.set(rtpvar, rtp);
} }
return rtp; return rtp;
}, },
@@ -629,9 +629,9 @@ lookup:
context.anchored = false; context.anchored = false;
context.keys = { context.keys = {
text: util.identity, text: util.identity,
description: services.get("charset").getCharsetTitle description: services.charset.getCharsetTitle
}; };
context.generate = function () iter(services.get("charset").getDecoderList()); context.generate = function () iter(services.charset.getDecoderList());
}; };
completion.directory = function directory(context, full) { completion.directory = function directory(context, full) {
@@ -695,7 +695,7 @@ lookup:
completion.shellCommand = function shellCommand(context) { completion.shellCommand = function shellCommand(context) {
context.title = ["Shell Command", "Path"]; context.title = ["Shell Command", "Path"];
context.generate = function () { context.generate = function () {
let dirNames = services.get("environment").get("PATH").split(util.OS.isWindows ? ";" : ":"); let dirNames = services.environment.get("PATH").split(util.OS.isWindows ? ";" : ":");
let commands = []; let commands = [];
for (let [, dirName] in Iterator(dirNames)) { for (let [, dirName] in Iterator(dirNames)) {
@@ -730,7 +730,7 @@ lookup:
shellcmdflag = "/c"; shellcmdflag = "/c";
} }
else { else {
shell = services.get("environment").get("SHELL") || "sh"; shell = services.environment.get("SHELL") || "sh";
shellcmdflag = "-c"; shellcmdflag = "-c";
} }
@@ -747,7 +747,7 @@ lookup:
}); });
options.add(["cdpath", "cd"], options.add(["cdpath", "cd"],
"List of directories searched when executing :cd", "List of directories searched when executing :cd",
"stringlist", ["."].concat(services.get("environment").get("CDPATH").split(/[:;]/).filter(util.identity)).join(","), "stringlist", ["."].concat(services.environment.get("CDPATH").split(/[:;]/).filter(util.identity)).join(","),
{ setter: function (value) File.expandPathList(value) }); { setter: function (value) File.expandPathList(value) });
options.add(["runtimepath", "rtp"], options.add(["runtimepath", "rtp"],

View File

@@ -666,10 +666,10 @@ const JavaScript = Module("javascript", {
"Use the JavaScript debugger service for JavaScript completion", "Use the JavaScript debugger service for JavaScript completion",
"boolean", false, { "boolean", false, {
setter: function (value) { setter: function (value) {
if (services.get("debugger").isOn != value) if (services.debugger.isOn != value)
services.get("debugger")[value ? "on" : "off"](); services.debugger[value ? "on" : "off"]();
}, },
getter: function () services.get("debugger").isOn getter: function () services.debugger.isOn
}); });
} }
}); });

View File

@@ -120,7 +120,7 @@ const Tabs = Module("tabs", {
* @property {Object[]} The array of closed tabs for the current * @property {Object[]} The array of closed tabs for the current
* session. * session.
*/ */
get closedTabs() services.get("json").decode(services.get("sessionStore").getClosedTabData(window)), get closedTabs() services.json.decode(services.sessionStore.getClosedTabData(window)),
/** /**
* Clones the specified *tab* and append it to the tab list. * Clones the specified *tab* and append it to the tab list.
@@ -148,7 +148,7 @@ const Tabs = Module("tabs", {
if (!tab) if (!tab)
tab = config.tabbrowser.mTabContainer.selectedItem; tab = config.tabbrowser.mTabContainer.selectedItem;
services.get("windowWatcher") services.windowWatcher
.openWindow(window, window.getBrowserURL(), null, "chrome,dialog=no,all", tab); .openWindow(window, window.getBrowserURL(), null, "chrome,dialog=no,all", tab);
}, },
@@ -490,8 +490,8 @@ const Tabs = Module("tabs", {
if (!from) if (!from)
from = config.tabbrowser.mTabContainer.selectedItem; from = config.tabbrowser.mTabContainer.selectedItem;
let tabState = services.get("sessionStore").getTabState(from); let tabState = services.sessionStore.getTabState(from);
services.get("sessionStore").setTabState(to, tabState); services.sessionStore.setTabState(to, tabState);
} }
}, { }, {
commands: function () { commands: function () {

View File

@@ -124,7 +124,7 @@ defineModule.dump = function dump_() {
msg = util.objectToString(msg); msg = util.objectToString(msg);
return msg; return msg;
}).join(", "); }).join(", ");
let name = loaded.services ? services.get("dactyl:").name : "dactyl"; let name = loaded.services ? services["dactyl:"].name : "dactyl";
dump(String.replace(msg, /\n?$/, "\n") dump(String.replace(msg, /\n?$/, "\n")
.replace(/^./gm, name + ": $&")); .replace(/^./gm, name + ": $&"));
} }
@@ -199,9 +199,9 @@ Runnable.prototype.QueryInterface = XPCOMUtils.generateQI([Ci.nsIRunnable]);
* @returns [jsdIProperty] * @returns [jsdIProperty]
*/ */
function debuggerProperties(obj) { function debuggerProperties(obj) {
if (loaded.services && services.get("debugger").isOn) { if (loaded.services && services.debugger.isOn) {
let ret = {}; let ret = {};
services.get("debugger").wrapValue(obj).getProperties(ret, {}); services.debugger.wrapValue(obj).getProperties(ret, {});
return ret.value; return ret.value;
} }
} }
@@ -227,7 +227,7 @@ function properties(obj, prototypes, debugger_) {
for (; obj; obj = prototypes && prototype(obj)) { for (; obj; obj = prototypes && prototype(obj)) {
try { try {
if (sandbox.Object.getOwnPropertyNames || !debugger_ || !services.get("debugger").isOn) if (sandbox.Object.getOwnPropertyNames || !debugger_ || !services.debugger.isOn)
var iter = values(Object.getOwnPropertyNames(obj)); var iter = values(Object.getOwnPropertyNames(obj));
} }
catch (e) {} catch (e) {}
@@ -798,7 +798,7 @@ Class.prototype = {
timeout: function (callback, timeout) { timeout: function (callback, timeout) {
const self = this; const self = this;
let notify = { notify: function notify(timer) { try { callback.apply(self); } catch (e) { util.reportError(e); } } }; let notify = { notify: function notify(timer) { try { callback.apply(self); } catch (e) { util.reportError(e); } } };
let timer = services.create("timer"); let timer = services.Timer();
timer.initWithCallback(notify, timeout || 0, timer.TYPE_ONE_SHOT); timer.initWithCallback(notify, timeout || 0, timer.TYPE_ONE_SHOT);
return timer; return timer;
} }
@@ -939,7 +939,7 @@ let StructBase = Class("StructBase", Array, {
const Timer = Class("Timer", { const Timer = Class("Timer", {
init: function (minInterval, maxInterval, callback) { init: function (minInterval, maxInterval, callback) {
this._timer = services.create("timer"); this._timer = services.Timer();
this.callback = callback; this.callback = callback;
this.minInterval = minInterval; this.minInterval = minInterval;
this.maxInterval = maxInterval; this.maxInterval = maxInterval;

View File

@@ -18,10 +18,10 @@ Bookmark.prototype.__defineGetter__("extra", function () [
["tags", this.tags.join(", "), "Tag"] ["tags", this.tags.join(", "), "Tag"]
].filter(function (item) item[1])); ].filter(function (item) item[1]));
const annotation = services.get("annotation"); const annotation = services.annotation;
const bookmarks = services.get("bookmarks"); const bookmarks = services.bookmarks;
const history = services.get("history"); const history = services.history;
const tagging = services.get("tagging"); const tagging = services.tagging;
const name = "bookmark-cache"; const name = "bookmark-cache";
const BookmarkCache = Module("BookmarkCache", XPCOM(Ci.nsINavBookmarkObserver), { const BookmarkCache = Module("BookmarkCache", XPCOM(Ci.nsINavBookmarkObserver), {
@@ -85,7 +85,7 @@ const BookmarkCache = Module("BookmarkCache", XPCOM(Ci.nsINavBookmarkObserver),
isRegularBookmark: function isRegularBookmark(id) { isRegularBookmark: function isRegularBookmark(id) {
do { do {
var root = id; var root = id;
if (services.get("livemark") && services.get("livemark").isLivemark(id)) if (services.livemark && services.livemark.isLivemark(id))
return false; return false;
id = bookmarks.getFolderIdForItem(id); id = bookmarks.getFolderIdForItem(id);
} while (id != bookmarks.placesRoot && id != root); } while (id != bookmarks.placesRoot && id != root);

346
common/modules/prefs.jsm Normal file
View File

@@ -0,0 +1,346 @@
// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2010 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2010 by 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.
"use strict";
Components.utils.import("resource://dactyl/base.jsm");
defineModule("prefs", {
exports: ["Prefs", "prefs"],
require: ["services", "util"],
use: ["template"]
});
const Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]), {
SAVED: "extensions.dactyl.saved.",
RESTORE: "extensions.dactyl.restore.",
init: function () {
this._prefContexts = [];
util.addObserver(this);
this._branch = services.pref.getBranch("").QueryInterface(Ci.nsIPrefBranch2);
this._branch.addObserver("", this, false);
this._observers = {};
this.restore();
},
observe: {
"nsPref:changed": function (subject, data) {
let observers = this._observers[data];
if (observers) {
let value = this.get(data, false);
this._observers[data] = observers.filter(function (callback) {
if (!callback.get())
return false;
util.trapErrors(callback.get(), null, value);
return true;
});
}
}
},
/**
* Adds a new preference observer for the given preference.
*
* @param {string} pref The preference to observe.
* @param {function(object)} callback The callback, called with the
* new value of the preference whenever it changes.
*/
watch: function (pref, callback, strong) {
if (!this._observers[pref])
this._observers[pref] = [];
this._observers[pref].push(!strong ? Cu.getWeakReference(callback) : { get: function () callback });
},
/**
* Lists all preferences matching *filter* or only those with changed
* values if *onlyNonDefault* is specified.
*
* @param {boolean} onlyNonDefault Limit the list to prefs with a
* non-default value.
* @param {string} filter The list filter. A null filter lists all
* prefs.
* @optional
*/
list: function list(onlyNonDefault, filter) {
if (!filter)
filter = "";
let prefArray = this.getNames();
prefArray.sort();
function prefs() {
for (let [, pref] in Iterator(prefArray)) {
let userValue = services.pref.prefHasUserValue(pref);
if (onlyNonDefault && !userValue || pref.indexOf(filter) == -1)
continue;
let value = this.get(pref);
let option = {
isDefault: !userValue,
default: this._load(pref, null, true),
value: <>={template.highlight(value, true, 100)}</>,
name: pref,
pre: "\u00a0\u00a0" // Unicode nonbreaking space.
};
yield option;
}
};
return template.options(services["dactyl:"].host + " Preferences", prefs.call(this));
},
/**
* Returns the value of a preference.
*
* @param {string} name The preference name.
* @param {value} defaultValue The value to return if the preference
* is unset.
*/
get: function (name, defaultValue) this._load(name, defaultValue),
/**
* Returns the default value of a preference
*
* @param {string} name The preference name.
* @param {value} defaultValue The value to return if the preference
* has no default value.
*/
getDefault: function (name, defaultValue) this._load(name, defaultValue, true),
/**
* Returns the names of all preferences.
*
* @param {string} branch The branch in which to search preferences.
* @default ""
*/
getNames: function (branch) services.pref.getChildList(branch || "", { value: 0 }),
_checkSafe: function (name, message, value) {
let curval = this._load(name, null, false);
if (arguments.length > 2 && curval === value)
return;
let defval = this._load(name, null, true);
let saved = this._load(this.SAVED + name);
if (saved == null && curval != defval || curval != saved) {
let msg = "Warning: setting preference " + name + ", but it's changed from its default value.";
if (message)
msg += " " + message;
util.dactyl.echomsg(msg);
}
},
/**
* Resets the preference *name* to *value* but warns the user if the value
* is changed from its default.
*
* @param {string} name The preference name.
* @param {value} value The new preference value.
*/
safeReset: function (name, message) {
this._checkSafe(name, message);
this.reset(name);
this.reset(this.SAVED + name);
},
/**
* Sets the preference *name* to *value* but warns the user if the value is
* changed from its default.
*
* @param {string} name The preference name.
* @param {value} value The new preference value.
*/
safeSet: function (name, value, message, skipSave) {
this._checkSafe(name, message, value);
this._store(name, value);
this[skipSave ? "reset" : "_store"](this.SAVED + name, value);
},
/**
* Sets the preference *name* to *value*.
*
* @param {string} name The preference name.
* @param {value} value The new preference value.
*/
set: function (name, value) {
this._store(name, value);
},
/**
* Saves the current value of a preference to be restored at next
* startup.
*
* @param {string} name The preference to save.
*/
save: function (name) {
let val = this.get(name);
this.set(this.RESTORE + name, val);
this.safeSet(name, val);
},
/**
* Restores saved preferences in the given branch.
*
* @param {string} branch The branch from which to restore
* preferences. @optional
*/
restore: function (branch) {
this.getNames(this.RESTORE + (branch || "")).forEach(function (pref) {
this.safeSet(pref.substr(this.RESTORE.length), this.get(pref), null, true)
this.reset(pref);
}, this);
},
/**
* Resets the preference *name* to its default value.
*
* @param {string} name The preference name.
*/
reset: function (name) {
try {
services.pref.clearUserPref(name);
}
catch (e) {} // ignore - thrown if not a user set value
},
/**
* Toggles the value of the boolean preference *name*.
*
* @param {string} name The preference name.
*/
toggle: function (name) {
util.assert(services.pref.getPrefType(name) === Ci.nsIPrefBranch.PREF_BOOL,
"E488: Trailing characters: " + name + "!");
this.set(name, !this.get(name));
},
/**
* Pushes a new preference context onto the context stack.
*
* @see #withContext
*/
pushContext: function () {
this._prefContexts.push({});
},
/**
* Pops the top preference context from the stack.
*
* @see #withContext
*/
popContext: function () {
for (let [k, v] in Iterator(this._prefContexts.pop()))
this._store(k, v);
},
/**
* Executes *func* with a new preference context. When *func* returns, the
* context is popped and any preferences set via {@link #setPref} or
* {@link #invertPref} are restored to their previous values.
*
* @param {function} func The function to call.
* @param {Object} func The 'this' object with which to call *func*
* @see #pushContext
* @see #popContext
*/
withContext: function (func, self) {
try {
this.pushContext();
return func.call(self);
}
finally {
this.popContext();
}
},
_store: function (name, value) {
if (this._prefContexts.length) {
let val = this._load(name, null);
if (val != null)
this._prefContexts[this._prefContexts.length - 1][name] = val;
}
function assertType(needType)
util.assert(type === Ci.nsIPrefBranch.PREF_INVALID || type === needType,
type === Ci.nsIPrefBranch.PREF_INT
? "E521: Number required after =: " + name + "=" + value
: "E474: Invalid argument: " + name + "=" + value);
let type = services.pref.getPrefType(name);
switch (typeof value) {
case "string":
assertType(Ci.nsIPrefBranch.PREF_STRING);
let supportString = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
supportString.data = value;
services.pref.setComplexValue(name, Ci.nsISupportsString, supportString);
break;
case "number":
assertType(Ci.nsIPrefBranch.PREF_INT);
services.pref.setIntPref(name, value);
break;
case "boolean":
assertType(Ci.nsIPrefBranch.PREF_BOOL);
services.pref.setBoolPref(name, value);
break;
default:
throw FailedAssertion("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")");
}
},
_load: function (name, defaultValue, defaultBranch) {
if (defaultValue == null)
defaultValue = null;
let branch = defaultBranch ? services.pref.getDefaultBranch("") : services.pref;
let type = services.pref.getPrefType(name);
try {
switch (type) {
case Ci.nsIPrefBranch.PREF_STRING:
let value = branch.getComplexValue(name, Ci.nsISupportsString).data;
// try in case it's a localized string (will throw an exception if not)
if (!services.pref.prefIsLocked(name) && !services.pref.prefHasUserValue(name) &&
RegExp("chrome://.+/locale/.+\\.properties").test(value))
value = branch.getComplexValue(name, Ci.nsIPrefLocalizedString).data;
return value;
case Ci.nsIPrefBranch.PREF_INT:
return branch.getIntPref(name);
case Ci.nsIPrefBranch.PREF_BOOL:
return branch.getBoolPref(name);
default:
return defaultValue;
}
}
catch (e) {
return defaultValue;
}
}
}, {
}, {
completion: function (dactyl, modules) {
modules.completion.preference = function preference(context) {
context.anchored = false;
context.title = [services["dactyl:"].host + " Preference", "Value"];
context.keys = { text: function (item) item, description: function (item) prefs.get(item) };
context.completions = prefs.getNames();
};
},
javascript: function (dactyl, modules) {
modules.JavaScript.setCompleter([this.get, this.safeSet, this.set, this.reset, this.toggle],
[function (context) (context.anchored=false, prefs.getNames().map(function (pref) [pref, ""]))]);
}
});
endModule();
// catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
// vim: set fdm=marker sw=4 ts=4 et ft=javascript:

View File

@@ -15,11 +15,11 @@
Components.utils.import("resource://dactyl/base.jsm"); Components.utils.import("resource://dactyl/base.jsm");
defineModule("sanitizer", { defineModule("sanitizer", {
exports: ["Range", "Sanitizer", "sanitizer"], exports: ["Range", "Sanitizer", "sanitizer"],
require: ["services", "storage", "template", "util"] require: ["prefs", "services", "storage", "template", "util"]
}); });
let tmp = {}; let tmp = {};
services.get("subscriptLoader").loadSubScript("chrome://browser/content/sanitize.js", tmp); services.subscriptLoader.loadSubScript("chrome://browser/content/sanitize.js", tmp);
tmp.Sanitizer.prototype.__proto__ = Class.prototype; tmp.Sanitizer.prototype.__proto__ = Class.prototype;
const Range = Struct("min", "max"); const Range = Struct("min", "max");
@@ -92,7 +92,7 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
action: function (range, host) { action: function (range, host) {
for (let c in Sanitizer.iterCookies(host)) for (let c in Sanitizer.iterCookies(host))
if (range.contains(c.creationTime) || timespan.isSession && c.isSession) if (range.contains(c.creationTime) || timespan.isSession && c.isSession)
services.get("cookies").remove(c.host, c.name, c.path, false); services.cookies.remove(c.host, c.name, c.path, false);
}, },
override: true override: true
}); });
@@ -105,23 +105,23 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
return; return;
if (host) { if (host) {
for (let p in Sanitizer.iterPermissions(host)) { for (let p in Sanitizer.iterPermissions(host)) {
services.get("permissions").remove(util.createURI(p.host), p.type); services.permissions.remove(util.createURI(p.host), p.type);
services.get("permissions").add(util.createURI(p.host), p.type, 0); services.permissions.add(util.createURI(p.host), p.type, 0);
} }
for (let p in iter(services.get("contentprefs").getPrefs(util.createURI(host)))) for (let p in iter(services.contentprefs.getPrefs(util.createURI(host))))
services.get("contentprefs").removePref(util.createURI(host), p.QueryInterface(Ci.nsIProperty).name); services.contentprefs.removePref(util.createURI(host), p.QueryInterface(Ci.nsIProperty).name);
} }
else { else {
// "Allow this site to open popups" ... // "Allow this site to open popups" ...
services.get("permissions").removeAll(); services.permissions.removeAll();
// Zoom level, ... // Zoom level, ...
services.get("contentprefs").removeGroupedPrefs(); services.contentprefs.removeGroupedPrefs();
} }
// "Never remember passwords" ... // "Never remember passwords" ...
for each (let domain in services.get("loginmanager").getAllDisabledHosts()) for each (let domain in services.loginmanager.getAllDisabledHosts())
if (!host || util.isSubdomain(domain, host)) if (!host || util.isSubdomain(domain, host))
services.get("loginmanager").setLoginSavingEnabled(host, true); services.loginmanager.setLoginSavingEnabled(host, true);
}, },
override: true override: true
}); });
@@ -153,7 +153,7 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
append: { append: {
SanitizeDialogPane: SanitizeDialogPane:
<groupbox orient="horizontal" xmlns={XUL}> <groupbox orient="horizontal" xmlns={XUL}>
<caption label={services.get("dactyl:").appName + " (see :help privacy)"}/> <caption label={services["dactyl:"].appName + " (see :help privacy)"}/>
<grid flex="1"> <grid flex="1">
<columns><column flex="1"/><column flex="1"/></columns> <columns><column flex="1"/><column flex="1"/></columns>
<rows>{ <rows>{
@@ -178,7 +178,7 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
{ {
template.map(ourItems(), function ([item, desc]) template.map(ourItems(), function ([item, desc])
<listitem xmlns={XUL} type="checkbox" <listitem xmlns={XUL} type="checkbox"
label={services.get("dactyl:").appName + " " + desc} label={services["dactyl:"].appName + " " + desc}
preference={branch + item} preference={branch + item}
onsyncfrompreference="return gSanitizePromptDialog.onReadGeneric();"/>) onsyncfrompreference="return gSanitizePromptDialog.onReadGeneric();"/>)
} }
@@ -328,14 +328,14 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
prefToArg: function (pref) pref.replace(/.*\./, "").toLowerCase(), prefToArg: function (pref) pref.replace(/.*\./, "").toLowerCase(),
iterCookies: function iterCookies(host) { iterCookies: function iterCookies(host) {
for (let c in iter(services.get("cookies"))) { for (let c in iter(services.cookies)) {
c.QueryInterface(Ci.nsICookie2); c.QueryInterface(Ci.nsICookie2);
if (!host || util.isSubdomain(c.rawHost, host)) if (!host || util.isSubdomain(c.rawHost, host))
yield c; yield c;
} }
}, },
iterPermissions: function iterPermissions(host) { iterPermissions: function iterPermissions(host) {
for (let p in iter(services.get("permissions"))) { for (let p in iter(services.permissions)) {
p.QueryInterface(Ci.nsIPermission); p.QueryInterface(Ci.nsIPermission);
if (!host || util.isSubdomain(p.host, host)) if (!host || util.isSubdomain(p.host, host))
yield p; yield p;
@@ -393,7 +393,7 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
args["-host"].forEach(function (host) { args["-host"].forEach(function (host) {
sanitizer.sanitizing = true; sanitizer.sanitizing = true;
if (items.indexOf("history") > -1) if (items.indexOf("history") > -1)
services.get("privateBrowsing").removeDataFromDomain(host); services.privateBrowsing.removeDataFromDomain(host);
sanitizer.sanitizeItems(items, range, host) sanitizer.sanitizeItems(items, range, host)
}); });
} }
@@ -438,13 +438,13 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
function getPerms(host) { function getPerms(host) {
let uri = util.createURI(host); let uri = util.createURI(host);
if (uri) if (uri)
return Sanitizer.UNPERMS[services.get("permissions").testPermission(uri, "cookie")]; return Sanitizer.UNPERMS[services.permissions.testPermission(uri, "cookie")];
return "unset"; return "unset";
} }
function setPerms(host, perm) { function setPerms(host, perm) {
let uri = util.createURI(host); let uri = util.createURI(host);
services.get("permissions").remove(uri, "cookie"); services.permissions.remove(uri, "cookie");
services.get("permissions").add(uri, "cookie", Sanitizer.PERMS[perm]); services.permissions.add(uri, "cookie", Sanitizer.PERMS[perm]);
} }
commands.add(["cookies", "ck"], commands.add(["cookies", "ck"],
"Change cookie permissions for sites", "Change cookie permissions for sites",
@@ -458,14 +458,14 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
switch (cmd) { switch (cmd) {
case "clear": case "clear":
for (let c in Sanitizer.iterCookies(host)) for (let c in Sanitizer.iterCookies(host))
services.get("cookies").remove(c.host, c.name, c.path, false); services.cookies.remove(c.host, c.name, c.path, false);
break; break;
case "clear-persistent": case "clear-persistent":
session = false; session = false;
case "clear-session": case "clear-session":
for (let c in Sanitizer.iterCookies(host)) for (let c in Sanitizer.iterCookies(host))
if (c.isSession == session) if (c.isSession == session)
services.get("cookies").remove(c.host, c.name, c.path, false); services.cookies.remove(c.host, c.name, c.path, false);
return; return;
case "list": case "list":
@@ -524,16 +524,16 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
}, },
options: function (dactyl, modules) { options: function (dactyl, modules) {
const options = modules.options; const options = modules.options;
if (services.get("privateBrowsing")) if (services.privateBrowsing)
options.add(["private", "pornmode"], options.add(["private", "pornmode"],
"Set the 'private browsing' option", "Set the 'private browsing' option",
"boolean", false, "boolean", false,
{ {
initialValue: true, initialValue: true,
getter: function () services.get("privateBrowsing").privateBrowsingEnabled, getter: function () services.privateBrowsing.privateBrowsingEnabled,
setter: function (value) { setter: function (value) {
if (services.get("privateBrowsing").privateBrowsingEnabled != value) if (services.privateBrowsing.privateBrowsingEnabled != value)
services.get("privateBrowsing").privateBrowsingEnabled = value services.privateBrowsing.privateBrowsingEnabled = value
}, },
persist: false persist: false
}); });

View File

@@ -56,16 +56,16 @@ const Services = Module("Services", {
this.add("windowMediator", "@mozilla.org/appshell/window-mediator;1", Ci.nsIWindowMediator); this.add("windowMediator", "@mozilla.org/appshell/window-mediator;1", Ci.nsIWindowMediator);
this.add("windowWatcher", "@mozilla.org/embedcomp/window-watcher;1", Ci.nsIWindowWatcher); this.add("windowWatcher", "@mozilla.org/embedcomp/window-watcher;1", Ci.nsIWindowWatcher);
this.addClass("file", "@mozilla.org/file/local;1", Ci.nsILocalFile); this.addClass("File", "@mozilla.org/file/local;1", Ci.nsILocalFile);
this.addClass("file:", "@mozilla.org/network/protocol;1?name=file", Ci.nsIFileProtocolHandler); this.addClass("File:", "@mozilla.org/network/protocol;1?name=file", Ci.nsIFileProtocolHandler);
this.addClass("find", "@mozilla.org/embedcomp/rangefind;1", Ci.nsIFind); this.addClass("Find", "@mozilla.org/embedcomp/rangefind;1", Ci.nsIFind);
this.addClass("htmlConverter","@mozilla.org/widget/htmlformatconverter;1", Ci.nsIFormatConverter); this.addClass("HtmlConverter","@mozilla.org/widget/htmlformatconverter;1", Ci.nsIFormatConverter);
this.addClass("htmlEncoder", "@mozilla.org/layout/htmlCopyEncoder;1", Ci.nsIDocumentEncoder); this.addClass("HtmlEncoder", "@mozilla.org/layout/htmlCopyEncoder;1", Ci.nsIDocumentEncoder);
this.addClass("process", "@mozilla.org/process/util;1", Ci.nsIProcess); this.addClass("Process", "@mozilla.org/process/util;1", Ci.nsIProcess);
this.addClass("string", "@mozilla.org/supports-string;1", Ci.nsISupportsString); this.addClass("String", "@mozilla.org/supports-string;1", Ci.nsISupportsString);
this.addClass("timer", "@mozilla.org/timer;1", Ci.nsITimer); this.addClass("Timer", "@mozilla.org/timer;1", Ci.nsITimer);
this.addClass("xmlhttp", "@mozilla.org/xmlextras/xmlhttprequest;1", Ci.nsIXMLHttpRequest); this.addClass("Xmlhttp", "@mozilla.org/xmlextras/xmlhttprequest;1", Ci.nsIXMLHttpRequest);
this.addClass("zipWriter", "@mozilla.org/zipwriter;1", Ci.nsIZipWriter); this.addClass("ZipWriter", "@mozilla.org/zipwriter;1", Ci.nsIZipWriter);
}, },
_create: function (classes, ifaces, meth) { _create: function (classes, ifaces, meth) {
@@ -102,7 +102,9 @@ const Services = Module("Services", {
*/ */
add: function (name, class_, ifaces, meth) { add: function (name, class_, ifaces, meth) {
const self = this; const self = this;
this.services.__defineGetter__(name, function () { if (name in this && !this.__lookupGetter__(name) && !(this[name] instanceof Ci.nsISupports))
throw TypeError();
this.__defineGetter__(name, function () {
delete this[name]; delete this[name];
return this[name] = self._create(class_, ifaces, meth); return this[name] = self._create(class_, ifaces, meth);
}); });
@@ -118,7 +120,7 @@ const Services = Module("Services", {
*/ */
addClass: function (name, class_, ifaces) { addClass: function (name, class_, ifaces) {
const self = this; const self = this;
return this.classes[name] = function () self._create(class_, ifaces, "createInstance"); return this[name] = function () self._create(class_, ifaces, "createInstance");
}, },
/** /**
@@ -126,14 +128,14 @@ const Services = Module("Services", {
* *
* @param {string} name The class's cache key. * @param {string} name The class's cache key.
*/ */
create: function (name) this.classes[name](), create: function (name) this[name[0].toUpperCase() + name.substr(1)],
/** /**
* Returns the cached service with the specified name. * Returns the cached service with the specified name.
* *
* @param {string} name The service's cache key. * @param {string} name The service's cache key.
*/ */
get: function (name) this.services[name], get: function (name) this[name],
}, { }, {
}, { }, {
init: function (dactyl, modules) { init: function (dactyl, modules) {

View File

@@ -14,7 +14,7 @@ defineModule("storage", {
require: ["services", "util"] require: ["services", "util"]
}); });
const win32 = /^win(32|nt)$/i.test(services.get("runtime").OS); const win32 = /^win(32|nt)$/i.test(services.runtime.OS);
function getFile(name) { function getFile(name) {
let file = storage.infoPath.clone(); let file = storage.infoPath.clone();
@@ -27,7 +27,7 @@ function loadData(name, store, type) {
if (storage.infoPath) if (storage.infoPath)
var file = getFile(name).read(); var file = getFile(name).read();
if (file) if (file)
var result = services.get("json").decode(file); var result = services.json.decode(file);
if (result instanceof type) if (result instanceof type)
return result; return result;
} }
@@ -265,12 +265,12 @@ const Storage = Module("Storage", {
*/ */
const File = Class("File", { const File = Class("File", {
init: function (path, checkPWD) { init: function (path, checkPWD) {
let file = services.create("file"); let file = services.File();
if (path instanceof Ci.nsIFile) if (path instanceof Ci.nsIFile)
file = path.QueryInterface(Ci.nsIFile); file = path.QueryInterface(Ci.nsIFile);
else if (/file:\/\//.test(path)) else if (/file:\/\//.test(path))
file = services.create("file:").getFileFromURLSpec(path); file = services["File:"]().getFileFromURLSpec(path);
else { else {
try { try {
let expandedPath = File.expandPath(path); let expandedPath = File.expandPath(path);
@@ -484,7 +484,7 @@ const File = Class("File", {
*/ */
get PATH_SEP() { get PATH_SEP() {
delete this.PATH_SEP; delete this.PATH_SEP;
let f = services.get("directory").get("CurProcD", Ci.nsIFile); let f = services.directory.get("CurProcD", Ci.nsIFile);
f.append("foo"); f.append("foo");
return this.PATH_SEP = f.path.substr(f.parent.path.length, 1); return this.PATH_SEP = f.path.substr(f.parent.path.length, 1);
}, },
@@ -497,6 +497,7 @@ const File = Class("File", {
defaultEncoding: "UTF-8", defaultEncoding: "UTF-8",
expandPath: function (path, relative) { expandPath: function (path, relative) {
function getenv(name) services.environment.get(name);
// expand any $ENV vars - this is naive but so is Vim and we like to be compatible // expand any $ENV vars - this is naive but so is Vim and we like to be compatible
// TODO: Vim does not expand variables set to an empty string (and documents it). // TODO: Vim does not expand variables set to an empty string (and documents it).
@@ -505,7 +506,7 @@ const File = Class("File", {
function expand(path) path.replace( function expand(path) path.replace(
!win32 ? /\$(\w+)\b|\${(\w+)}/g !win32 ? /\$(\w+)\b|\${(\w+)}/g
: /\$(\w+)\b|\${(\w+)}|%(\w+)%/g, : /\$(\w+)\b|\${(\w+)}|%(\w+)%/g,
function (m, n1, n2, n3) services.get("environment").get(n1 || n2 || n3) || m function (m, n1, n2, n3) getenv(n1 || n2 || n3) || m
); );
path = expand(path); path = expand(path);
@@ -513,12 +514,12 @@ const File = Class("File", {
// Yuck. // Yuck.
if (!relative && RegExp("~(?:$|[/" + util.escapeRegexp(File.PATH_SEP) + "])").test(path)) { if (!relative && RegExp("~(?:$|[/" + util.escapeRegexp(File.PATH_SEP) + "])").test(path)) {
// Try $HOME first, on all systems // Try $HOME first, on all systems
let home = services.get("environment").get("HOME"); let home = getenv("HOME");
// Windows has its own idiosyncratic $HOME variables. // Windows has its own idiosyncratic $HOME variables.
if (win32 && (!home || !File(home) || !File(home).exists())) if (win32 && (!home || !File(home).exists()))
home = services.get("environment").get("USERPROFILE") || home = getenv("USERPROFILE") ||
services.get("environment").get("HOMEDRIVE") + services.get("environment").get("HOMEPATH"); getenv("HOMEDRIVE") + getenv("HOMEPATH");
path = home + path.substr(1); path = home + path.substr(1);
} }
@@ -533,7 +534,7 @@ const File = Class("File", {
isAbsolutePath: function (path) { isAbsolutePath: function (path) {
try { try {
services.create("file").initWithPath(path); services.File().initWithPath(path);
return true; return true;
} }
catch (e) { catch (e) {

View File

@@ -11,7 +11,7 @@ defineModule("styles", {
use: ["template"] use: ["template"]
}); });
const sss = services.get("stylesheet"); const sss = services.stylesheet;
function cssUri(css) "chrome-data:text/css," + encodeURI(css); function cssUri(css) "chrome-data:text/css," + encodeURI(css);
const namespace = "@namespace html " + XHTML.uri.quote() + ";\n" + const namespace = "@namespace html " + XHTML.uri.quote() + ";\n" +
"@namespace xul " + XUL.uri.quote() + ";\n" + "@namespace xul " + XUL.uri.quote() + ";\n" +
@@ -219,7 +219,7 @@ const Styles = Module("Styles", {
* already registered. * already registered.
*/ */
registerSheet: function registerSheet(url, agent, reload) { registerSheet: function registerSheet(url, agent, reload) {
let uri = services.get("io").newURI(url, null, null); let uri = services.io.newURI(url, null, null);
if (reload) if (reload)
this.unregisterSheet(url, agent); this.unregisterSheet(url, agent);
if (reload || !sss.sheetRegistered(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET)) if (reload || !sss.sheetRegistered(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET))
@@ -233,7 +233,7 @@ const Styles = Module("Styles", {
* @param {boolean} agent If true, sheet is registered as an agent sheet. * @param {boolean} agent If true, sheet is registered as an agent sheet.
*/ */
unregisterSheet: function unregisterSheet(url, agent) { unregisterSheet: function unregisterSheet(url, agent) {
let uri = services.get("io").newURI(url, null, null); let uri = services.io.newURI(url, null, null);
if (sss.sheetRegistered(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET)) if (sss.sheetRegistered(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET))
sss.unregisterSheet(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET); sss.unregisterSheet(uri, agent ? sss.AGENT_SHEET : sss.USER_SHEET);
}, },

View File

@@ -1,5 +1,5 @@
// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org> // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2009 by Doug Kearns <dougkearns@gmail.com> // Copyright (c) 2007-2010 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2010 by Kris Maglione <maglione.k@gmail.com> // Copyright (c) 2008-2010 by Kris Maglione <maglione.k@gmail.com>
// //
// This work is licensed for reuse under an MIT license. Details are // This work is licensed for reuse under an MIT license. Details are
@@ -10,7 +10,7 @@ try {
Components.utils.import("resource://dactyl/base.jsm"); Components.utils.import("resource://dactyl/base.jsm");
defineModule("util", { defineModule("util", {
exports: ["FailedAssertion", "Math", "NS", "Prefs", "Util", "XHTML", "XUL", "prefs", "util"], exports: ["FailedAssertion", "Math", "NS", "Util", "XHTML", "XUL", "util"],
require: ["services"], require: ["services"],
use: ["highlight", "template"] use: ["highlight", "template"]
}); });
@@ -46,7 +46,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
}, },
// FIXME: Only works for Pentadactyl // FIXME: Only works for Pentadactyl
get activeWindow() services.get("windowMediator").getMostRecentWindow("navigator:browser"), get activeWindow() services.windowMediator.getMostRecentWindow("navigator:browser"),
dactyl: { dactyl: {
__noSuchMethod__: function (meth, args) { __noSuchMethod__: function (meth, args) {
let win = util.activeWindow; let win = util.activeWindow;
@@ -69,9 +69,9 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
addObserver: function (obj) { addObserver: function (obj) {
let observers = obj.observe; let observers = obj.observe;
function register(meth) { function register(meth) {
services.get("observer")[meth](obj, "quit-application", true); services.observer[meth](obj, "quit-application", true);
for (let target in keys(observers)) for (let target in keys(observers))
services.get("observer")[meth](obj, target, true); services.observer[meth](obj, target, true);
} }
Class.replaceProperty(obj, "observe", Class.replaceProperty(obj, "observe",
function (subject, target, data) { function (subject, target, data) {
@@ -155,7 +155,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
*/ */
createURI: function createURI(str) { createURI: function createURI(str) {
try { try {
return services.get("urifixup").createFixupURI(str, services.get("urifixup").FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP); return services.urifixup.createFixupURI(str, services.urifixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP);
} }
catch (e) { catch (e) {
return null; return null;
@@ -225,20 +225,20 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
} }
let doc = (node.getRangeAt ? node.getRangeAt(0) : node).startContainer.ownerDocument; let doc = (node.getRangeAt ? node.getRangeAt(0) : node).startContainer.ownerDocument;
let encoder = services.create("htmlEncoder"); let encoder = services.HtmlEncoder();
encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted); encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted);
if (node instanceof Ci.nsISelection) if (node instanceof Ci.nsISelection)
encoder.setSelection(node); encoder.setSelection(node);
else if (node instanceof Ci.nsIDOMRange) else if (node instanceof Ci.nsIDOMRange)
encoder.setRange(node); encoder.setRange(node);
let str = services.create("string"); let str = services.String();
str.data = encoder.encodeToString(); str.data = encoder.encodeToString();
if (html) if (html)
return str.data; return str.data;
let [result, length] = [{}, {}]; let [result, length] = [{}, {}];
services.create("htmlConverter").convert("text/html", str, str.data.length*2, "text/unicode", result, length); services.HtmlConverter().convert("text/html", str, str.data.length*2, "text/unicode", result, length);
return result.value.QueryInterface(Ci.nsISupportsString).data; return result.value.QueryInterface(Ci.nsISupportsString).data;
}, },
@@ -424,7 +424,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
* *
* @param {string} ver The required version. * @param {string} ver The required version.
*/ */
haveGecko: function (ver) services.get("versionCompare").compare(services.get("runtime").platformVersion, ver) >= 0, haveGecko: function (ver) services.versionCompare.compare(services.runtime.platformVersion, ver) >= 0,
/** /**
* Sends a synchronous or asynchronous HTTP request to *url* and returns * Sends a synchronous or asynchronous HTTP request to *url* and returns
@@ -438,7 +438,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
*/ */
httpGet: function httpGet(url, callback) { httpGet: function httpGet(url, callback) {
try { try {
let xmlhttp = services.create("xmlhttp"); let xmlhttp = services.Xmlhttp();
xmlhttp.mozBackgroundRequest = true; xmlhttp.mozBackgroundRequest = true;
if (callback) if (callback)
xmlhttp.onreadystatechange = function () { xmlhttp.onreadystatechange = function () {
@@ -490,7 +490,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
/** Dactyl's notion of the current operating system platform. */ /** Dactyl's notion of the current operating system platform. */
OS: { OS: {
_arch: services.get("runtime").OS, _arch: services.runtime.OS,
/** /**
* @property {string} The normalised name of the OS. This is one of * @property {string} The normalised name of the OS. This is one of
* "Windows", "Mac OS X" or "Unix". * "Windows", "Mac OS X" or "Unix".
@@ -564,7 +564,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
* @returns {nsIURI} * @returns {nsIURI}
*/ */
// FIXME: createURI needed too? // FIXME: createURI needed too?
newURI: function (uri, charset, base) services.get("io").newURI(uri, charset, base), newURI: function (uri, charset, base) services.io.newURI(uri, charset, base),
/** /**
* Pretty print a JavaScript object. Use HTML markup to color certain items * Pretty print a JavaScript object. Use HTML markup to color certain items
@@ -873,7 +873,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
let base = host.replace(/.*\.(.+?\..+?)$/, "$1"); let base = host.replace(/.*\.(.+?\..+?)$/, "$1");
try { try {
base = services.get("tld").getBaseDomainFromHost(host); base = services.tld.getBaseDomainFromHost(host);
} }
catch (e) {} catch (e) {}
@@ -915,7 +915,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
* @param {number} delay The time period for which to sleep in milliseconds. * @param {number} delay The time period for which to sleep in milliseconds.
*/ */
sleep: function (delay) { sleep: function (delay) {
let mainThread = services.get("threading").mainThread; let mainThread = services.threading.mainThread;
let end = Date.now() + delay; let end = Date.now() + delay;
while (Date.now() < end) while (Date.now() < end)
@@ -994,7 +994,7 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
}, },
threadYield: function (flush, interruptable) { threadYield: function (flush, interruptable) {
let mainThread = services.get("threading").mainThread; let mainThread = services.threading.mainThread;
/* FIXME */ /* FIXME */
util.interrupted = false; util.interrupted = false;
do { do {
@@ -1067,332 +1067,6 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
Array: array Array: array
}); });
const Prefs = Module("prefs", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]), {
SAVED: "extensions.dactyl.saved.",
RESTORE: "extensions.dactyl.restore.",
init: function () {
this._prefContexts = [];
util.addObserver(this);
this._branch = services.get("pref").getBranch("").QueryInterface(Ci.nsIPrefBranch2);
this._branch.addObserver("", this, false);
this._observers = {};
this.restore();
},
observe: {
"nsPref:changed": function (subject, data) {
let observers = this._observers[data];
if (observers) {
let value = this.get(data, false);
this._observers[data] = observers.filter(function (callback) {
if (!callback.get())
return false;
util.trapErrors(callback.get(), null, value);
return true;
});
}
}
},
/**
* Adds a new preference observer for the given preference.
*
* @param {string} pref The preference to observe.
* @param {function(object)} callback The callback, called with the
* new value of the preference whenever it changes.
*/
watch: function (pref, callback, strong) {
if (!this._observers[pref])
this._observers[pref] = [];
this._observers[pref].push(!strong ? Cu.getWeakReference(callback) : { get: function () callback });
},
/**
* Lists all preferences matching *filter* or only those with changed
* values if *onlyNonDefault* is specified.
*
* @param {boolean} onlyNonDefault Limit the list to prefs with a
* non-default value.
* @param {string} filter The list filter. A null filter lists all
* prefs.
* @optional
*/
list: function list(onlyNonDefault, filter) {
if (!filter)
filter = "";
let prefArray = this.getNames();
prefArray.sort();
function prefs() {
for (let [, pref] in Iterator(prefArray)) {
let userValue = services.get("pref").prefHasUserValue(pref);
if (onlyNonDefault && !userValue || pref.indexOf(filter) == -1)
continue;
let value = this.get(pref);
let option = {
isDefault: !userValue,
default: this._load(pref, null, true),
value: <>={template.highlight(value, true, 100)}</>,
name: pref,
pre: "\u00a0\u00a0" // Unicode nonbreaking space.
};
yield option;
}
};
return template.options(services.get("dactyl:").host + " Preferences", prefs.call(this));
},
/**
* Returns the value of a preference.
*
* @param {string} name The preference name.
* @param {value} defaultValue The value to return if the preference
* is unset.
*/
get: function (name, defaultValue) this._load(name, defaultValue),
/**
* Returns the default value of a preference
*
* @param {string} name The preference name.
* @param {value} defaultValue The value to return if the preference
* has no default value.
*/
getDefault: function (name, defaultValue) this._load(name, defaultValue, true),
/**
* Returns the names of all preferences.
*
* @param {string} branch The branch in which to search preferences.
* @default ""
*/
getNames: function (branch) services.get("pref").getChildList(branch || "", { value: 0 }),
_checkSafe: function (name, message, value) {
let curval = this._load(name, null, false);
if (arguments.length > 2 && curval === value)
return;
let defval = this._load(name, null, true);
let saved = this._load(this.SAVED + name);
if (saved == null && curval != defval || curval != saved) {
let msg = "Warning: setting preference " + name + ", but it's changed from its default value.";
if (message)
msg += " " + message;
util.dactyl.echomsg(msg);
}
},
/**
* Resets the preference *name* to *value* but warns the user if the value
* is changed from its default.
*
* @param {string} name The preference name.
* @param {value} value The new preference value.
*/
safeReset: function (name, message) {
this._checkSafe(name, message);
this.reset(name);
this.reset(this.SAVED + name);
},
/**
* Sets the preference *name* to *value* but warns the user if the value is
* changed from its default.
*
* @param {string} name The preference name.
* @param {value} value The new preference value.
*/
safeSet: function (name, value, message, skipSave) {
this._checkSafe(name, message, value);
this._store(name, value);
this[skipSave ? "reset" : "_store"](this.SAVED + name, value);
},
/**
* Sets the preference *name* to *value*.
*
* @param {string} name The preference name.
* @param {value} value The new preference value.
*/
set: function (name, value) {
this._store(name, value);
},
/**
* Saves the current value of a preference to be restored at next
* startup.
*
* @param {string} name The preference to save.
*/
save: function (name) {
let val = this.get(name);
this.set(this.RESTORE + name, val);
this.safeSet(name, val);
},
/**
* Restores saved preferences in the given branch.
*
* @param {string} branch The branch from which to restore
* preferences. @optional
*/
restore: function (branch) {
this.getNames(this.RESTORE + (branch || "")).forEach(function (pref) {
this.safeSet(pref.substr(this.RESTORE.length), this.get(pref), null, true)
this.reset(pref);
}, this);
},
/**
* Resets the preference *name* to its default value.
*
* @param {string} name The preference name.
*/
reset: function (name) {
try {
services.get("pref").clearUserPref(name);
}
catch (e) {} // ignore - thrown if not a user set value
},
/**
* Toggles the value of the boolean preference *name*.
*
* @param {string} name The preference name.
*/
toggle: function (name) {
util.assert(services.get("pref").getPrefType(name) === Ci.nsIPrefBranch.PREF_BOOL,
"E488: Trailing characters: " + name + "!");
this.set(name, !this.get(name));
},
/**
* Pushes a new preference context onto the context stack.
*
* @see #withContext
*/
pushContext: function () {
this._prefContexts.push({});
},
/**
* Pops the top preference context from the stack.
*
* @see #withContext
*/
popContext: function () {
for (let [k, v] in Iterator(this._prefContexts.pop()))
this._store(k, v);
},
/**
* Executes *func* with a new preference context. When *func* returns, the
* context is popped and any preferences set via {@link #setPref} or
* {@link #invertPref} are restored to their previous values.
*
* @param {function} func The function to call.
* @param {Object} func The 'this' object with which to call *func*
* @see #pushContext
* @see #popContext
*/
withContext: function (func, self) {
try {
this.pushContext();
return func.call(self);
}
finally {
this.popContext();
}
},
_store: function (name, value) {
if (this._prefContexts.length) {
let val = this._load(name, null);
if (val != null)
this._prefContexts[this._prefContexts.length - 1][name] = val;
}
function assertType(needType)
util.assert(type === Ci.nsIPrefBranch.PREF_INVALID || type === needType,
type === Ci.nsIPrefBranch.PREF_INT
? "E521: Number required after =: " + name + "=" + value
: "E474: Invalid argument: " + name + "=" + value);
let type = services.get("pref").getPrefType(name);
switch (typeof value) {
case "string":
assertType(Ci.nsIPrefBranch.PREF_STRING);
let supportString = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
supportString.data = value;
services.get("pref").setComplexValue(name, Ci.nsISupportsString, supportString);
break;
case "number":
assertType(Ci.nsIPrefBranch.PREF_INT);
services.get("pref").setIntPref(name, value);
break;
case "boolean":
assertType(Ci.nsIPrefBranch.PREF_BOOL);
services.get("pref").setBoolPref(name, value);
break;
default:
throw FailedAssertion("Unknown preference type: " + typeof value + " (" + name + "=" + value + ")");
}
},
_load: function (name, defaultValue, defaultBranch) {
if (defaultValue == null)
defaultValue = null;
let branch = defaultBranch ? services.get("pref").getDefaultBranch("") : services.get("pref");
let type = services.get("pref").getPrefType(name);
try {
switch (type) {
case Ci.nsIPrefBranch.PREF_STRING:
let value = branch.getComplexValue(name, Ci.nsISupportsString).data;
// try in case it's a localized string (will throw an exception if not)
if (!services.get("pref").prefIsLocked(name) && !services.get("pref").prefHasUserValue(name) &&
RegExp("chrome://.+/locale/.+\\.properties").test(value))
value = branch.getComplexValue(name, Ci.nsIPrefLocalizedString).data;
return value;
case Ci.nsIPrefBranch.PREF_INT:
return branch.getIntPref(name);
case Ci.nsIPrefBranch.PREF_BOOL:
return branch.getBoolPref(name);
default:
return defaultValue;
}
}
catch (e) {
return defaultValue;
}
}
}, {
}, {
completion: function (dactyl, modules) {
modules.completion.preference = function preference(context) {
context.anchored = false;
context.title = [services.get("dactyl:").host + " Preference", "Value"];
context.keys = { text: function (item) item, description: function (item) prefs.get(item) };
context.completions = prefs.getNames();
};
},
javascript: function (dactyl, modules) {
modules.JavaScript.setCompleter([this.get, this.safeSet, this.set, this.reset, this.toggle],
[function (context) (context.anchored=false, prefs.getNames().map(function (pref) [pref, ""]))]);
}
});
/** /**
* Math utility methods. * Math utility methods.

View File

@@ -172,7 +172,7 @@ const Config = Module("config", ConfigBase, {
this.showServicePane(true); this.showServicePane(true);
else { else {
let pane = document.getElementById(id); let pane = document.getElementById(id);
let manager = services.get("displayPaneManager"); let manager = services.displayPaneManager;
let paneinfo = manager.getPaneInfo(pane._lastURL.stringValue); let paneinfo = manager.getPaneInfo(pane._lastURL.stringValue);
if (!paneinfo) if (!paneinfo)
@@ -272,12 +272,12 @@ const Config = Module("config", ConfigBase, {
"boolean", true, "boolean", true,
{ {
setter: function (value) { setter: function (value) {
const ioService = services.get("io"); const ioService = services.io;
ioService.offline = !value; ioService.offline = !value;
prefs.set("browser.offline", ioService.offline); prefs.set("browser.offline", ioService.offline);
return value; return value;
}, },
getter: function () !services.get("io").offline getter: function () !services.io.offline
}); });
}, },
services: function () { services: function () {

View File

@@ -49,7 +49,7 @@ const Library = Module("library", {
* @returns {string[]} * @returns {string[]}
*/ */
getTracks: function getTracks(artist, album) { getTracks: function getTracks(artist, album) {
let properties = services.create("mutablePropertyArray"); let properties = services.MutablePropertyArray();
properties.appendProperty(SBProperties.artistName, artist); properties.appendProperty(SBProperties.artistName, artist);
properties.appendProperty(SBProperties.albumName, album); properties.appendProperty(SBProperties.albumName, album);

View File

@@ -370,7 +370,7 @@ const Player = Module("player", {
*/ */
getMediaPages: function getMediaPages() { getMediaPages: function getMediaPages() {
let list = SBGetBrowser().currentMediaPage.mediaListView.mediaList; let list = SBGetBrowser().currentMediaPage.mediaListView.mediaList;
let pages = services.get("mediaPageManager").getAvailablePages(list); let pages = services.mediaPageManager.getAvailablePages(list);
return ArrayConverter.JSArray(pages).map(function (page) page.QueryInterface(Ci.sbIMediaPageInfo)); return ArrayConverter.JSArray(pages).map(function (page) page.QueryInterface(Ci.sbIMediaPageInfo));
}, },
@@ -383,7 +383,7 @@ const Player = Module("player", {
* @param {sbIMediaView} view * @param {sbIMediaView} view
*/ */
loadMediaPage: function loadMediaPage(page, list, view) { loadMediaPage: function loadMediaPage(page, list, view) {
services.get("mediaPageManager").setPage(list, page); services.mediaPageManager.setPage(list, page);
SBGetBrowser().loadMediaList(list, null, null, view, null); SBGetBrowser().loadMediaList(list, null, null, view, null);
}, },
@@ -409,7 +409,7 @@ const Player = Module("player", {
*/ */
sortBy: function sortBy(field, ascending) { sortBy: function sortBy(field, ascending) {
let order = ascending ? "a" : "d"; let order = ascending ? "a" : "d";
let properties = services.create("mutablePropertyArray"); let properties = services.MutablePropertyArray();
properties.strict = false; properties.strict = false;
switch (field) { switch (field) {
@@ -594,7 +594,7 @@ const Player = Module("player", {
commands.add(["qu[eue]"], commands.add(["qu[eue]"],
"Queue tracks by artist/album/track", "Queue tracks by artist/album/track",
function (args) { function (args) {
let properties = services.create("mutablePropertyArray"); let properties = services.MutablePropertyArray();
// args // args
switch (args.length) { switch (args.length) {

View File

@@ -247,7 +247,7 @@ const Config = Module("config", ConfigBase, {
completion: function () { completion: function () {
var searchRunning = false; // only until Firefox fixes https://bugzilla.mozilla.org/show_bug.cgi?id=510589 var searchRunning = false; // only until Firefox fixes https://bugzilla.mozilla.org/show_bug.cgi?id=510589
completion.location = function location(context) { completion.location = function location(context) {
if (!services.get("autoCompleteSearch")) if (!services.autoCompleteSearch)
return; return;
context.anchored = false; context.anchored = false;
@@ -262,12 +262,12 @@ const Config = Module("config", ConfigBase, {
context.cancel = function () { context.cancel = function () {
if (searchRunning) { if (searchRunning) {
services.get("autoCompleteSearch").stopSearch(); services.autoCompleteSearch.stopSearch();
searchRunning = false; searchRunning = false;
} }
}; };
if (searchRunning) if (searchRunning)
services.get("autoCompleteSearch").stopSearch(); services.autoCompleteSearch.stopSearch();
let timer = new Timer(50, 100, function (result) { let timer = new Timer(50, 100, function (result) {
context.incomplete = result.searchResult >= result.RESULT_NOMATCH_ONGOING; context.incomplete = result.searchResult >= result.RESULT_NOMATCH_ONGOING;
context.completions = [ context.completions = [
@@ -275,7 +275,7 @@ const Config = Module("config", ConfigBase, {
for (i in util.range(0, result.matchCount)) for (i in util.range(0, result.matchCount))
]; ];
}); });
services.get("autoCompleteSearch").startSearch(context.filter, "", context.result, { services.autoCompleteSearch.startSearch(context.filter, "", context.result, {
onSearchResult: function onSearchResult(search, result) { onSearchResult: function onSearchResult(search, result) {
timer.tell(result); timer.tell(result);
if (result.searchResult <= result.RESULT_SUCCESS) { if (result.searchResult <= result.RESULT_SUCCESS) {
@@ -312,12 +312,12 @@ const Config = Module("config", ConfigBase, {
"boolean", true, "boolean", true,
{ {
setter: function (value) { setter: function (value) {
const ioService = services.get("io"); const ioService = services.io;
if (ioService.offline == value) if (ioService.offline == value)
BrowserOffline.toggleOfflineStatus(); BrowserOffline.toggleOfflineStatus();
return value; return value;
}, },
getter: function () !services.get("io").offline getter: function () !services.io.offline
}); });
} }
}); });

View File

@@ -21,7 +21,7 @@ const Addressbook = Module("addressbook", {
return ""; return "";
}, },
getDirectoryFromURI: function (uri) services.get("rdf").GetResource(uri).QueryInterface(Ci.nsIAbDirectory), getDirectoryFromURI: function (uri) services.rdf.GetResource(uri).QueryInterface(Ci.nsIAbDirectory),
add: function (address, firstName, lastName, displayName) { add: function (address, firstName, lastName, displayName) {
const personalAddressbookURI = "moz-abmdbdirectory://abook.mab"; const personalAddressbookURI = "moz-abmdbdirectory://abook.mab";

View File

@@ -133,7 +133,7 @@ const Mail = Module("mail", {
/** @property {nsISmtpServer[]} The list of configured SMTP servers. */ /** @property {nsISmtpServer[]} The list of configured SMTP servers. */
get smtpServers() { get smtpServers() {
let servers = services.get("smtpService").smtpServers; let servers = services.smtpService.smtpServers;
let ret = []; let ret = [];
while (servers.hasMoreElements()) { while (servers.hasMoreElements()) {
@@ -914,12 +914,12 @@ const Mail = Module("mail", {
options.add(["smtpserver", "smtp"], options.add(["smtpserver", "smtp"],
"Set the default SMTP server", "Set the default SMTP server",
"string", services.get("smtpService").defaultServer.key, // TODO: how should we handle these persistent external defaults - "inherit" or null? "string", services.smtpService.defaultServer.key, // TODO: how should we handle these persistent external defaults - "inherit" or null?
{ {
getter: function () services.get("smtpService").defaultServer.key, getter: function () services.smtpService.defaultServer.key,
setter: function (value) { setter: function (value) {
let server = mail.smtpServers.filter(function (s) s.key == value)[0]; let server = mail.smtpServers.filter(function (s) s.key == value)[0];
services.get("smtpService").defaultServer = server; services.smtpService.defaultServer = server;
return value; return value;
}, },
completer: function (context) [[s.key, s.serverURI] for ([, s] in Iterator(mail.smtpServers))] completer: function (context) [[s.key, s.serverURI] for ([, s] in Iterator(mail.smtpServers))]