]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/services.jsm
finalize changelog for 7904
[dactyl.git] / common / modules / services.jsm
1 // Copyright (c) 2008-2014 Kris Maglione <maglione.k at Gmail>
2 //
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
5 "use strict";
6
7 try {
8
9 var global = this;
10 defineModule("services", {
11     exports: ["PrivateBrowsingUtils", "services"]
12 });
13
14 try {
15     var { PrivateBrowsingUtils } = Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
16 }
17 catch (e) {}
18
19 /**
20  * A lazily-instantiated XPCOM class and service cache.
21  */
22 var Services = Module("Services", {
23     ABOUT: "@mozilla.org/network/protocol/about;1?what=",
24     AUTOCOMPLETE: "@mozilla.org/autocomplete/search;1?name=",
25     PROTOCOL: "@mozilla.org/network/protocol;1?name=",
26
27     init: function () {
28         this.services = {};
29
30         this.add("annotation",          "@mozilla.org/browser/annotation-service;1",        "nsIAnnotationService");
31         this.add("appShell",            "@mozilla.org/appshell/appShellService;1",          "nsIAppShellService");
32         this.add("appStartup",          "@mozilla.org/toolkit/app-startup;1",               "nsIAppStartup");
33         this.add("bookmarks",           "@mozilla.org/browser/nav-bookmarks-service;1",     "nsINavBookmarksService");
34         this.add("browserSearch",       "@mozilla.org/browser/search-service;1",            "nsIBrowserSearchService");
35         this.add("cache",               "@mozilla.org/network/cache-service;1",             "nsICacheService");
36         this.add("charset",             "@mozilla.org/charset-converter-manager;1",         "nsICharsetConverterManager");
37         this.add("chromeRegistry",      "@mozilla.org/chrome/chrome-registry;1",            "nsIXULChromeRegistry");
38         this.add("clipboard",           "@mozilla.org/widget/clipboard;1",                  "nsIClipboard");
39         this.add("clipboardHelper",     "@mozilla.org/widget/clipboardhelper;1",            "nsIClipboardHelper");
40         this.add("commandLineHandler",  "@mozilla.org/commandlinehandler/general-startup;1?type=dactyl");
41         this.add("console",             "@mozilla.org/consoleservice;1",                    "nsIConsoleService");
42         this.add("contentPrefs",        "@mozilla.org/content-pref/service;1",              ["nsIContentPrefService",
43                                                                                              "nsIContentPrefService2"]);
44         this.add("dactyl",              "@dactyl.googlecode.com/extra/utils",               "dactylIUtils");
45         this.add("dactyl:",             this.PROTOCOL + "dactyl");
46         this.add("debugger",            "@mozilla.org/js/jsd/debugger-service;1",           "jsdIDebuggerService");
47         this.add("directory",           "@mozilla.org/file/directory_service;1",            "nsIProperties");
48         this.add("downloadManager",     "@mozilla.org/download-manager;1",                  "nsIDownloadManager");
49         this.add("environment",         "@mozilla.org/process/environment;1",               "nsIEnvironment");
50         this.add("extensionManager",    "@mozilla.org/extensions/manager;1",                "nsIExtensionManager");
51         this.add("externalApp",         "@mozilla.org/uriloader/external-helper-app-service;1", "nsPIExternalAppLauncher");
52         this.add("externalProtocol",    "@mozilla.org/uriloader/external-protocol-service;1", "nsIExternalProtocolService");
53         this.add("favicon",             "@mozilla.org/browser/favicon-service;1",           "nsIFaviconService");
54         this.add("file:",               this.PROTOCOL + "file",                             "nsIFileProtocolHandler");
55         this.add("focus",               "@mozilla.org/focus-manager;1",                     "nsIFocusManager");
56         this.add("history",             "@mozilla.org/browser/nav-history-service;1",
57                  ["nsIBrowserHistory", "nsINavHistoryService", "nsPIPlacesDatabase"]);
58         this.add("io",                  "@mozilla.org/network/io-service;1",                "nsIIOService");
59         this.add("json",                "@mozilla.org/dom/json;1",                          "nsIJSON", "createInstance");
60         this.add("listeners",           "@mozilla.org/eventlistenerservice;1",              "nsIEventListenerService");
61         this.add("livemark",            "@mozilla.org/browser/livemark-service;2",          "nsILivemarkService");
62         this.add("messages",            "@mozilla.org/globalmessagemanager;1",              "nsIChromeFrameMessageManager");
63         this.add("mime",                "@mozilla.org/mime;1",                              "nsIMIMEService");
64         this.add("observer",            "@mozilla.org/observer-service;1",                  "nsIObserverService");
65         this.add("pref",                "@mozilla.org/preferences-service;1",               ["nsIPrefBranch2", "nsIPrefService"]);
66         this.add("printSettings",       "@mozilla.org/gfx/printsettings-service;1",         "nsIPrintSettingsService");
67         this.add("privateBrowsing",     "@mozilla.org/privatebrowsing;1",                   "nsIPrivateBrowsingService");
68         this.add("profile",             "@mozilla.org/toolkit/profile-service;1",           "nsIToolkitProfileService");
69         this.add("resource:",           this.PROTOCOL + "resource",                         ["nsIProtocolHandler", "nsIResProtocolHandler"]);
70         this.add("runtime",             "@mozilla.org/xre/runtime;1",                       ["nsIXULAppInfo", "nsIXULRuntime"]);
71         this.add("rdf",                 "@mozilla.org/rdf/rdf-service;1",                   "nsIRDFService");
72         this.add("security",            "@mozilla.org/scriptsecuritymanager;1",             "nsIScriptSecurityManager");
73         this.add("sessionStore",        "@mozilla.org/browser/sessionstore;1",              "nsISessionStore");
74         this.add("spell",               "@mozilla.org/spellchecker/engine;1",               "mozISpellCheckingEngine");
75         this.add("stringBundle",        "@mozilla.org/intl/stringbundle;1",                 "nsIStringBundleService");
76         this.add("stylesheet",          "@mozilla.org/content/style-sheet-service;1",       "nsIStyleSheetService");
77         this.add("subscriptLoader",     "@mozilla.org/moz/jssubscript-loader;1",            "mozIJSSubScriptLoader");
78         this.add("tagging",             "@mozilla.org/browser/tagging-service;1",           "nsITaggingService");
79         this.add("tld",                 "@mozilla.org/network/effective-tld-service;1",     "nsIEffectiveTLDService");
80         this.add("threading",           "@mozilla.org/thread-manager;1",                    "nsIThreadManager");
81         this.add("urifixup",            "@mozilla.org/docshell/urifixup;1",                 "nsIURIFixup");
82         this.add("versionCompare",      "@mozilla.org/xpcom/version-comparator;1",          "nsIVersionComparator");
83         this.add("windowMediator",      "@mozilla.org/appshell/window-mediator;1",          "nsIWindowMediator");
84         this.add("windowWatcher",       "@mozilla.org/embedcomp/window-watcher;1",          "nsIWindowWatcher");
85         this.add("zipReader",           "@mozilla.org/libjar/zip-reader-cache;1",           "nsIZipReaderCache");
86
87         this.addClass("CharsetConv",  "@mozilla.org/intl/scriptableunicodeconverter", "nsIScriptableUnicodeConverter", "charset");
88         this.addClass("CharsetStream","@mozilla.org/intl/converter-input-stream;1",   ["nsIConverterInputStream",
89                                                                                        "nsIUnicharLineInputStream"], "init");
90         this.addClass("ConvOutStream","@mozilla.org/intl/converter-output-stream;1", "nsIConverterOutputStream", "init", false);
91         this.addClass("File",         "@mozilla.org/file/local;1",                 "nsILocalFile");
92         this.addClass("FileInStream", "@mozilla.org/network/file-input-stream;1",  "nsIFileInputStream", "init", false);
93         this.addClass("FileOutStream","@mozilla.org/network/file-output-stream;1", "nsIFileOutputStream", "init", false);
94         this.addClass("Find",         "@mozilla.org/embedcomp/rangefind;1",        "nsIFind");
95         this.addClass("FormData",     "@mozilla.org/files/formdata;1",             "nsIDOMFormData");
96         this.addClass("HtmlConverter","@mozilla.org/widget/htmlformatconverter;1", "nsIFormatConverter");
97         this.addClass("HtmlEncoder",  "@mozilla.org/layout/htmlCopyEncoder;1",     "nsIDocumentEncoder");
98         this.addClass("InterfacePointer", "@mozilla.org/supports-interface-pointer;1", "nsISupportsInterfacePointer", "data");
99         this.addClass("InputStream",  "@mozilla.org/scriptableinputstream;1",      "nsIScriptableInputStream", "init");
100         this.addClass("MIMEStream",   "@mozilla.org/network/mime-input-stream;1",  "nsIMIMEInputStream", "setData");
101         this.addClass("Persist",      "@mozilla.org/embedding/browser/nsWebBrowserPersist;1", "nsIWebBrowserPersist");
102         this.addClass("Pipe",         "@mozilla.org/pipe;1",                       "nsIPipe", "init");
103         this.addClass("Process",      "@mozilla.org/process/util;1",               "nsIProcess", "init");
104         this.addClass("Pump",         "@mozilla.org/network/input-stream-pump;1",  "nsIInputStreamPump", "init");
105         this.addClass("StreamChannel","@mozilla.org/network/input-stream-channel;1",
106                       ["nsIInputStreamChannel", "nsIChannel"], "setURI");
107         this.addClass("StreamCopier", "@mozilla.org/network/async-stream-copier;1","nsIAsyncStreamCopier", "init");
108         this.addClass("String",       "@mozilla.org/supports-string;1",            "nsISupportsString", "data");
109         this.addClass("StringStream", "@mozilla.org/io/string-input-stream;1",     "nsIStringInputStream", "data");
110         this.addClass("Transfer",     "@mozilla.org/transfer;1",                   "nsITransfer", "init");
111         this.addClass("Transferable", "@mozilla.org/widget/transferable;1",        "nsITransferable");
112         this.addClass("Timer",        "@mozilla.org/timer;1",                      "nsITimer", "initWithCallback");
113         this.addClass("URL",          "@mozilla.org/network/standard-url;1",       ["nsIStandardURL", "nsIURL"], "init");
114         this.addClass("Xmlhttp",      "@mozilla.org/xmlextras/xmlhttprequest;1",   [], "open");
115         this.addClass("XPathEvaluator", "@mozilla.org/dom/xpath-evaluator;1",      "nsIDOMXPathEvaluator");
116         this.addClass("XMLDocument",  "@mozilla.org/xml/xml-document;1",           "nsIDOMXMLDocument");
117         this.addClass("XMLSerializer","@mozilla.org/xmlextras/xmlserializer;1",    ["nsIDOMSerializer"]);
118         this.addClass("ZipReader",    "@mozilla.org/libjar/zip-reader;1",          "nsIZipReader", "open", false);
119         this.addClass("ZipWriter",    "@mozilla.org/zipwriter;1",                  "nsIZipWriter", "open", false);
120     },
121     reinit: function () {},
122
123     _create: function _create(name, args) {
124         try {
125             var service = this.services[name];
126
127             let res = Cc[service.class][service.method || "getService"]();
128             if (!service.interfaces.length)
129                 return res.wrappedJSObject || res;
130
131             service.interfaces.forEach(iface => { res instanceof Ci[iface]; });
132
133             if (service.init && args.length) {
134                 if (service.callable)
135                     res[service.init].apply(res, args);
136                 else
137                     res[service.init] = args[0];
138             }
139             return res;
140         }
141         catch (e) {
142             if (service.quiet === false)
143                 throw e.stack ? e : Error(e);
144
145             if (typeof util !== "undefined" && util != null)
146                 util.reportError(e);
147             else
148                 dump("dactyl: Service creation failed for '" + service.class + "': " + e + "\n" + (e.stack || Error(e).stack));
149             return null;
150         }
151     },
152
153     /**
154      * Adds a new XPCOM service to the cache.
155      *
156      * @param {string} name The service's cache key.
157      * @param {string} class The class's contract ID.
158      * @param {string|[string]} ifaces The interface or array of
159      *     interfaces implemented by this service.
160      * @param {string} meth The name of the function used to instantiate
161      *     the service.
162      */
163     add: function add(name, class_, ifaces, meth) {
164         const self = this;
165         this.services[name] = { method: meth, class: class_, interfaces: Array.concat(ifaces || []) };
166         if (name in this && ifaces && !this.__lookupGetter__(name) && !(this[name] instanceof Ci.nsISupports))
167             throw TypeError();
168         memoize(this, name, () => self._create(name));
169     },
170
171     /**
172      * Adds a new XPCOM class to the cache.
173      *
174      * @param {string} name The class's cache key.
175      * @param {string} class_ The class's contract ID.
176      * @param {string|[string]} ifaces The interface or array of
177      *     interfaces implemented by this class.
178      * @param {string} init Name of a property or method used to initialize the
179      *     class.
180      */
181     addClass: function addClass(name, class_, ifaces, init, quiet) {
182         this.services[name] = { class: class_, interfaces: Array.concat(ifaces || []), method: "createInstance", init: init, quiet: quiet };
183         if (init)
184             memoize(this.services[name], "callable",
185                     function () callable(XPCOMShim(this.interfaces)[this.init]));
186
187         this[name] = (function Create() this._create(name, arguments)).bind(this);
188         update.apply(null, [this[name]].concat([Ci[i] for (i of Array.concat(ifaces))]));
189         return this[name];
190     },
191
192     /**
193      * Returns a new instance of the cached class with the specified name.
194      *
195      * @param {string} name The class's cache key.
196      */
197     create: deprecated("services.*name*()", function create(name) this[util.capitalize(name)]()),
198
199     /**
200      * Returns the cached service with the specified name.
201      *
202      * @param {string} name The service's cache key.
203      */
204     get: deprecated("services.*name*", function get(name) this[name]),
205
206     /**
207      * Returns true if the given service is available.
208      *
209      * @param {string} name The service's cache key.
210      */
211     has: function has(name) hasOwnProperty(this.services, name) && this.services[name].class in Cc &&
212         this.services[name].interfaces.every(iface => iface in Ci)
213 });
214
215 endModule();
216
217 } catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
218
219 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: