Bug 1561435 - Format uriloader/, a=automatic-formatting

# ignore-this-changeset

Differential Revision: https://phabricator.services.mozilla.com/D35942

--HG--
extra : source : 5dea4c57938db29579b142d06cec98f03eb5397d
This commit is contained in:
Victor Porof 2019-07-05 11:18:48 +02:00
parent 472d3c137a
commit afb5dbbfbb
20 changed files with 869 additions and 521 deletions

View file

@ -45,7 +45,6 @@ module.exports = {
"overrides": [{ "overrides": [{
"files": [ "files": [
"devtools/**", "devtools/**",
"uriloader/**",
"view/**", "view/**",
"widget/**", "widget/**",
"xpcom/**", "xpcom/**",

View file

@ -40,7 +40,6 @@ toolkit/components/telemetry/datareporting-prefs.js
toolkit/components/telemetry/healthreport-prefs.js toolkit/components/telemetry/healthreport-prefs.js
# Ignore all top-level directories for now. # Ignore all top-level directories for now.
uriloader/**
view/** view/**
widget/** widget/**
xpcom/** xpcom/**

View file

@ -2,21 +2,35 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm"); const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm");
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); const { XPCOMUtils } = ChromeUtils.import(
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); "resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(this, "FileUtils", ChromeUtils.defineModuleGetter(
"resource://gre/modules/FileUtils.jsm"); this,
ChromeUtils.defineModuleGetter(this, "JSONFile", "FileUtils",
"resource://gre/modules/JSONFile.jsm"); "resource://gre/modules/FileUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"JSONFile",
"resource://gre/modules/JSONFile.jsm"
);
XPCOMUtils.defineLazyServiceGetter(this, "gExternalProtocolService", XPCOMUtils.defineLazyServiceGetter(
this,
"gExternalProtocolService",
"@mozilla.org/uriloader/external-protocol-service;1", "@mozilla.org/uriloader/external-protocol-service;1",
"nsIExternalProtocolService"); "nsIExternalProtocolService"
XPCOMUtils.defineLazyServiceGetter(this, "gMIMEService", );
XPCOMUtils.defineLazyServiceGetter(
this,
"gMIMEService",
"@mozilla.org/mime;1", "@mozilla.org/mime;1",
"nsIMIMEService"); "nsIMIMEService"
);
function HandlerService() { function HandlerService() {
// Observe handlersvc-json-replace so we can switch to the datasource // Observe handlersvc-json-replace so we can switch to the datasource
@ -24,7 +38,6 @@ function HandlerService() {
} }
HandlerService.prototype = { HandlerService.prototype = {
classID: Components.ID("{220cc253-b60f-41f6-b9cf-fdcb325f970f}"), classID: Components.ID("{220cc253-b60f-41f6-b9cf-fdcb325f970f}"),
QueryInterface: ChromeUtils.generateQI([ QueryInterface: ChromeUtils.generateQI([
Ci.nsISupportsWeakReference, Ci.nsISupportsWeakReference,
@ -61,7 +74,9 @@ HandlerService.prototype = {
}, },
_dataPostProcessor(data) { _dataPostProcessor(data) {
return data.defaultHandlersVersion ? data : { return data.defaultHandlersVersion
? data
: {
defaultHandlersVersion: {}, defaultHandlersVersion: {},
mimeTypes: {}, mimeTypes: {},
schemes: {}, schemes: {},
@ -77,10 +92,13 @@ HandlerService.prototype = {
try { try {
prefsDefaultHandlersVersion = Services.prefs.getComplexValue( prefsDefaultHandlersVersion = Services.prefs.getComplexValue(
"gecko.handlerService.defaultHandlersVersion", "gecko.handlerService.defaultHandlersVersion",
Ci.nsIPrefLocalizedString); Ci.nsIPrefLocalizedString
);
} catch (ex) { } catch (ex) {
if (ex instanceof Components.Exception && if (
ex.result == Cr.NS_ERROR_UNEXPECTED) { ex instanceof Components.Exception &&
ex.result == Cr.NS_ERROR_UNEXPECTED
) {
// This platform does not have any default protocol handlers configured. // This platform does not have any default protocol handlers configured.
return; return;
} }
@ -95,8 +113,9 @@ HandlerService.prototype = {
this._store.data.defaultHandlersVersion[locale] || 0; this._store.data.defaultHandlersVersion[locale] || 0;
if (defaultHandlersVersion < prefsDefaultHandlersVersion) { if (defaultHandlersVersion < prefsDefaultHandlersVersion) {
this._injectDefaultProtocolHandlers(); this._injectDefaultProtocolHandlers();
this._store.data.defaultHandlersVersion[locale] = this._store.data.defaultHandlersVersion[
prefsDefaultHandlersVersion; locale
] = prefsDefaultHandlersVersion;
} }
} catch (ex) { } catch (ex) {
Cu.reportError(ex); Cu.reportError(ex);
@ -104,7 +123,9 @@ HandlerService.prototype = {
}, },
_injectDefaultProtocolHandlers() { _injectDefaultProtocolHandlers() {
let schemesPrefBranch = Services.prefs.getBranch("gecko.handlerService.schemes."); let schemesPrefBranch = Services.prefs.getBranch(
"gecko.handlerService.schemes."
);
let schemePrefList = schemesPrefBranch.getChildList(""); let schemePrefList = schemesPrefBranch.getChildList("");
let schemes = {}; let schemes = {};
@ -114,9 +135,10 @@ HandlerService.prototype = {
let [scheme, handlerNumber, attribute] = schemePrefName.split("."); let [scheme, handlerNumber, attribute] = schemePrefName.split(".");
try { try {
let attrData = let attrData = schemesPrefBranch.getComplexValue(
schemesPrefBranch.getComplexValue(schemePrefName, schemePrefName,
Ci.nsIPrefLocalizedString).data; Ci.nsIPrefLocalizedString
).data;
if (!(scheme in schemes)) { if (!(scheme in schemes)) {
schemes[scheme] = {}; schemes[scheme] = {};
} }
@ -136,7 +158,9 @@ HandlerService.prototype = {
let possibleHandlers = protoInfo.possibleApplicationHandlers; let possibleHandlers = protoInfo.possibleApplicationHandlers;
for (let handlerNumber of Object.keys(schemes[scheme])) { for (let handlerNumber of Object.keys(schemes[scheme])) {
let handlerApp = this.handlerAppFromSerializable(schemes[scheme][handlerNumber]); let handlerApp = this.handlerAppFromSerializable(
schemes[scheme][handlerNumber]
);
// If there is already a handler registered with the same template // If there is already a handler registered with the same template
// URL, the newly added one will be ignored when saving. // URL, the newly added one will be ignored when saving.
possibleHandlers.appendElement(handlerApp); possibleHandlers.appendElement(handlerApp);
@ -160,7 +184,9 @@ HandlerService.prototype = {
const kMigrations = { const kMigrations = {
"30boxes": () => { "30boxes": () => {
const k30BoxesRegex = /^https?:\/\/(?:www\.)?30boxes.com\/external\/widget/i; const k30BoxesRegex = /^https?:\/\/(?:www\.)?30boxes.com\/external\/widget/i;
let webcalHandler = gExternalProtocolService.getProtocolHandlerInfo("webcal"); let webcalHandler = gExternalProtocolService.getProtocolHandlerInfo(
"webcal"
);
if (this.exists(webcalHandler)) { if (this.exists(webcalHandler)) {
this.fillHandlerInfo(webcalHandler, ""); this.fillHandlerInfo(webcalHandler, "");
let shouldStore = false; let shouldStore = false;
@ -168,8 +194,10 @@ HandlerService.prototype = {
let handlers = webcalHandler.possibleApplicationHandlers; let handlers = webcalHandler.possibleApplicationHandlers;
for (let i = handlers.length - 1; i >= 0; i--) { for (let i = handlers.length - 1; i >= 0; i--) {
let app = handlers.queryElementAt(i, Ci.nsIHandlerApp); let app = handlers.queryElementAt(i, Ci.nsIHandlerApp);
if (app instanceof Ci.nsIWebHandlerApp && if (
k30BoxesRegex.test(app.uriTemplate)) { app instanceof Ci.nsIWebHandlerApp &&
k30BoxesRegex.test(app.uriTemplate)
) {
shouldStore = true; shouldStore = true;
handlers.removeElementAt(i); handlers.removeElementAt(i);
} }
@ -177,8 +205,10 @@ HandlerService.prototype = {
// Then remove as a preferred handler. // Then remove as a preferred handler.
if (webcalHandler.preferredApplicationHandler) { if (webcalHandler.preferredApplicationHandler) {
let app = webcalHandler.preferredApplicationHandler; let app = webcalHandler.preferredApplicationHandler;
if (app instanceof Ci.nsIWebHandlerApp && if (
k30BoxesRegex.test(app.uriTemplate)) { app instanceof Ci.nsIWebHandlerApp &&
k30BoxesRegex.test(app.uriTemplate)
) {
webcalHandler.preferredApplicationHandler = null; webcalHandler.preferredApplicationHandler = null;
shouldStore = true; shouldStore = true;
} }
@ -190,7 +220,10 @@ HandlerService.prototype = {
} }
}, },
}; };
let migrationsToRun = Services.prefs.getCharPref("browser.handlers.migrations", ""); let migrationsToRun = Services.prefs.getCharPref(
"browser.handlers.migrations",
""
);
migrationsToRun = migrationsToRun ? migrationsToRun.split(",") : []; migrationsToRun = migrationsToRun ? migrationsToRun.split(",") : [];
for (let migration of migrationsToRun) { for (let migration of migrationsToRun) {
migration.trim(); migration.trim();
@ -234,19 +267,23 @@ HandlerService.prototype = {
path: OS.Path.join(OS.Constants.Path.profileDir, "handlers.json"), path: OS.Path.join(OS.Constants.Path.profileDir, "handlers.json"),
dataPostProcessor: this._dataPostProcessor.bind(this), dataPostProcessor: this._dataPostProcessor.bind(this),
}); });
this.__store.load().then(() => { this.__store
.load()
.then(() => {
// __store can be null if we called _onDBChange in the mean time. // __store can be null if we called _onDBChange in the mean time.
if (this.__store) { if (this.__store) {
this._ensureStoreInitialized(); this._ensureStoreInitialized();
} }
}).catch(Cu.reportError); })
.catch(Cu.reportError);
} }
}, },
// nsIHandlerService // nsIHandlerService
enumerate() { enumerate() {
let handlers = Cc["@mozilla.org/array;1"] let handlers = Cc["@mozilla.org/array;1"].createInstance(
.createInstance(Ci.nsIMutableArray); Ci.nsIMutableArray
);
for (let type of Object.keys(this._store.data.mimeTypes)) { for (let type of Object.keys(this._store.data.mimeTypes)) {
let handler = gMIMEService.getFromTypeAndExtension(type, null); let handler = gMIMEService.getFromTypeAndExtension(type, null);
handlers.appendElement(handler); handlers.appendElement(handler);
@ -266,7 +303,9 @@ HandlerService.prototype = {
type, type,
get _handlerInfo() { get _handlerInfo() {
delete this._handlerInfo; delete this._handlerInfo;
return this._handlerInfo = gExternalProtocolService.getProtocolHandlerInfo(type); return (this._handlerInfo = gExternalProtocolService.getProtocolHandlerInfo(
type
));
}, },
}, },
{ {
@ -276,7 +315,7 @@ HandlerService.prototype = {
set(target, name, value) { set(target, name, value) {
target._handlerInfo[name] = value; target._handlerInfo[name] = value;
}, },
}, }
); );
handlers.appendElement(handler); handlers.appendElement(handler);
} }
@ -296,9 +335,11 @@ HandlerService.prototype = {
} }
// Only a limited number of preferredAction values is allowed. // Only a limited number of preferredAction values is allowed.
if (handlerInfo.preferredAction == Ci.nsIHandlerInfo.saveToDisk || if (
handlerInfo.preferredAction == Ci.nsIHandlerInfo.saveToDisk ||
handlerInfo.preferredAction == Ci.nsIHandlerInfo.useSystemDefault || handlerInfo.preferredAction == Ci.nsIHandlerInfo.useSystemDefault ||
handlerInfo.preferredAction == Ci.nsIHandlerInfo.handleInternally) { handlerInfo.preferredAction == Ci.nsIHandlerInfo.handleInternally
) {
storedHandlerInfo.action = handlerInfo.preferredAction; storedHandlerInfo.action = handlerInfo.preferredAction;
} else { } else {
storedHandlerInfo.action = Ci.nsIHandlerInfo.useHelperApp; storedHandlerInfo.action = Ci.nsIHandlerInfo.useHelperApp;
@ -315,7 +356,9 @@ HandlerService.prototype = {
if (handlerInfo.preferredApplicationHandler) { if (handlerInfo.preferredApplicationHandler) {
handlers.push(handlerInfo.preferredApplicationHandler); handlers.push(handlerInfo.preferredApplicationHandler);
} }
for (let handler of handlerInfo.possibleApplicationHandlers.enumerate(Ci.nsIHandlerApp)) { for (let handler of handlerInfo.possibleApplicationHandlers.enumerate(
Ci.nsIHandlerApp
)) {
// If the caller stored duplicate handlers, we save them only once. // If the caller stored duplicate handlers, we save them only once.
if (!handlers.some(h => h.equals(handler))) { if (!handlers.some(h => h.equals(handler))) {
handlers.push(handler); handlers.push(handler);
@ -325,8 +368,9 @@ HandlerService.prototype = {
// If any of the nsIHandlerInfo instances cannot be serialized, it is not // If any of the nsIHandlerInfo instances cannot be serialized, it is not
// included in the final list. The first element is always the preferred // included in the final list. The first element is always the preferred
// handler, or null if there is none. // handler, or null if there is none.
let serializableHandlers = let serializableHandlers = handlers
handlers.map(h => this.handlerAppToSerializable(h)).filter(h => h); .map(h => this.handlerAppToSerializable(h))
.filter(h => h);
if (serializableHandlers.length) { if (serializableHandlers.length) {
if (!handlerInfo.preferredApplicationHandler) { if (!handlerInfo.preferredApplicationHandler) {
serializableHandlers.unshift(null); serializableHandlers.unshift(null);
@ -358,10 +402,14 @@ HandlerService.prototype = {
// nsIHandlerService // nsIHandlerService
fillHandlerInfo(handlerInfo, overrideType) { fillHandlerInfo(handlerInfo, overrideType) {
let type = overrideType || handlerInfo.type; let type = overrideType || handlerInfo.type;
let storedHandlerInfo = this._getHandlerListByHandlerInfoType(handlerInfo)[type]; let storedHandlerInfo = this._getHandlerListByHandlerInfoType(handlerInfo)[
type
];
if (!storedHandlerInfo) { if (!storedHandlerInfo) {
throw new Components.Exception("handlerSvc fillHandlerInfo: don't know this type", throw new Components.Exception(
Cr.NS_ERROR_NOT_AVAILABLE); "handlerSvc fillHandlerInfo: don't know this type",
Cr.NS_ERROR_NOT_AVAILABLE
);
} }
handlerInfo.preferredAction = storedHandlerInfo.action; handlerInfo.preferredAction = storedHandlerInfo.action;
@ -436,25 +484,27 @@ HandlerService.prototype = {
if (!file.exists()) { if (!file.exists()) {
return null; return null;
} }
handlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"] handlerApp = Cc[
.createInstance(Ci.nsILocalHandlerApp); "@mozilla.org/uriloader/local-handler-app;1"
].createInstance(Ci.nsILocalHandlerApp);
handlerApp.executable = file; handlerApp.executable = file;
} catch (ex) { } catch (ex) {
return null; return null;
} }
} else if ("uriTemplate" in handlerObj) { } else if ("uriTemplate" in handlerObj) {
handlerApp = Cc["@mozilla.org/uriloader/web-handler-app;1"] handlerApp = Cc[
.createInstance(Ci.nsIWebHandlerApp); "@mozilla.org/uriloader/web-handler-app;1"
].createInstance(Ci.nsIWebHandlerApp);
handlerApp.uriTemplate = handlerObj.uriTemplate; handlerApp.uriTemplate = handlerObj.uriTemplate;
} else if ("service" in handlerObj) { } else if ("service" in handlerObj) {
handlerApp = Cc["@mozilla.org/uriloader/dbus-handler-app;1"] handlerApp = Cc[
.createInstance(Ci.nsIDBusHandlerApp); "@mozilla.org/uriloader/dbus-handler-app;1"
].createInstance(Ci.nsIDBusHandlerApp);
handlerApp.service = handlerObj.service; handlerApp.service = handlerObj.service;
handlerApp.method = handlerObj.method; handlerApp.method = handlerObj.method;
handlerApp.objectPath = handlerObj.objectPath; handlerApp.objectPath = handlerObj.objectPath;
handlerApp.dBusInterface = handlerObj.dBusInterface; handlerApp.dBusInterface = handlerObj.dBusInterface;
} else if ("command" in handlerObj && } else if ("command" in handlerObj && "@mozilla.org/gio-service;1" in Cc) {
"@mozilla.org/gio-service;1" in Cc) {
try { try {
handlerApp = Cc["@mozilla.org/gio-service;1"] handlerApp = Cc["@mozilla.org/gio-service;1"]
.getService(Ci.nsIGIOService) .getService(Ci.nsIGIOService)
@ -475,7 +525,8 @@ HandlerService.prototype = {
* based on which type of handlerInfo is provided. * based on which type of handlerInfo is provided.
*/ */
_getHandlerListByHandlerInfoType(handlerInfo) { _getHandlerListByHandlerInfoType(handlerInfo) {
return this._isMIMEInfo(handlerInfo) ? this._store.data.mimeTypes return this._isMIMEInfo(handlerInfo)
? this._store.data.mimeTypes
: this._store.data.schemes; : this._store.data.schemes;
}, },
@ -486,13 +537,16 @@ HandlerService.prototype = {
// We cannot rely only on the instanceof check because on Android both MIME // We cannot rely only on the instanceof check because on Android both MIME
// types and protocols are instances of nsIMIMEInfo. We still do the check // types and protocols are instances of nsIMIMEInfo. We still do the check
// so that properties of nsIMIMEInfo become available to the callers. // so that properties of nsIMIMEInfo become available to the callers.
return handlerInfo instanceof Ci.nsIMIMEInfo && return (
handlerInfo.type.includes("/"); handlerInfo instanceof Ci.nsIMIMEInfo && handlerInfo.type.includes("/")
);
}, },
// nsIHandlerService // nsIHandlerService
exists(handlerInfo) { exists(handlerInfo) {
return handlerInfo.type in this._getHandlerListByHandlerInfoType(handlerInfo); return (
handlerInfo.type in this._getHandlerListByHandlerInfoType(handlerInfo)
);
}, },
// nsIHandlerService // nsIHandlerService
@ -506,8 +560,10 @@ HandlerService.prototype = {
let extension = fileExtension.toLowerCase(); let extension = fileExtension.toLowerCase();
let mimeTypes = this._store.data.mimeTypes; let mimeTypes = this._store.data.mimeTypes;
for (let type of Object.keys(mimeTypes)) { for (let type of Object.keys(mimeTypes)) {
if (mimeTypes[type].extensions && if (
mimeTypes[type].extensions.includes(extension)) { mimeTypes[type].extensions &&
mimeTypes[type].extensions.includes(extension)
) {
return type; return type;
} }
} }

View file

@ -2,10 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(this, "PrivateBrowsingUtils", "resource://gre/modules/PrivateBrowsingUtils.jsm"); ChromeUtils.defineModuleGetter(
this,
"PrivateBrowsingUtils",
"resource://gre/modules/PrivateBrowsingUtils.jsm"
);
function nsWebHandlerApp() {} function nsWebHandlerApp() {}
@ -13,7 +17,10 @@ nsWebHandlerApp.prototype = {
classDescription: "A web handler for protocols and content", classDescription: "A web handler for protocols and content",
classID: Components.ID("8b1ae382-51a9-4972-b930-56977a57919d"), classID: Components.ID("8b1ae382-51a9-4972-b930-56977a57919d"),
contractID: "@mozilla.org/uriloader/web-handler-app;1", contractID: "@mozilla.org/uriloader/web-handler-app;1",
QueryInterface: ChromeUtils.generateQI([Ci.nsIWebHandlerApp, Ci.nsIHandlerApp]), QueryInterface: ChromeUtils.generateQI([
Ci.nsIWebHandlerApp,
Ci.nsIHandlerApp,
]),
_name: null, _name: null,
_detailedDescription: null, _detailedDescription: null,
@ -42,10 +49,12 @@ nsWebHandlerApp.prototype = {
throw Cr.NS_ERROR_NULL_POINTER; throw Cr.NS_ERROR_NULL_POINTER;
} }
if (aHandlerApp instanceof Ci.nsIWebHandlerApp && if (
aHandlerApp instanceof Ci.nsIWebHandlerApp &&
aHandlerApp.uriTemplate && aHandlerApp.uriTemplate &&
this.uriTemplate && this.uriTemplate &&
aHandlerApp.uriTemplate == this.uriTemplate) { aHandlerApp.uriTemplate == this.uriTemplate
) {
return true; return true;
} }
return false; return false;
@ -70,10 +79,14 @@ nsWebHandlerApp.prototype = {
// if we have a window context, use the URI loader to load there // if we have a window context, use the URI loader to load there
if (aWindowContext) { if (aWindowContext) {
try { try {
let remoteWindow = aWindowContext.getInterface(Ci.nsIRemoteWindowContext); let remoteWindow = aWindowContext.getInterface(
Ci.nsIRemoteWindowContext
);
if (remoteWindow.usePrivateBrowsing && !privateAllowed) { if (remoteWindow.usePrivateBrowsing && !privateAllowed) {
throw Components.Exception("Extension not allowed in private windows.", throw Components.Exception(
Cr.NS_ERROR_FILE_NOT_FOUND); "Extension not allowed in private windows.",
Cr.NS_ERROR_FILE_NOT_FOUND
);
} }
// getInterface throws if the object doesn't implement the given // getInterface throws if the object doesn't implement the given
// interface, so this try/catch statement is more of an if. // interface, so this try/catch statement is more of an if.
@ -88,12 +101,14 @@ nsWebHandlerApp.prototype = {
} }
try { try {
let isPrivate = aWindowContext.getInterface(Ci.nsIDocShell) let isPrivate = aWindowContext
.QueryInterface(Ci.nsILoadContext) .getInterface(Ci.nsIDocShell)
.usePrivateBrowsing; .QueryInterface(Ci.nsILoadContext).usePrivateBrowsing;
if (isPrivate && !privateAllowed) { if (isPrivate && !privateAllowed) {
throw Components.Exception("Extension not allowed in private windows.", throw Components.Exception(
Cr.NS_ERROR_FILE_NOT_FOUND); "Extension not allowed in private windows.",
Cr.NS_ERROR_FILE_NOT_FOUND
);
} }
} catch (e) { } catch (e) {
if (e.result != Cr.NS_NOINTERFACE) { if (e.result != Cr.NS_NOINTERFACE) {
@ -109,25 +124,31 @@ nsWebHandlerApp.prototype = {
channel.loadFlags = Ci.nsIChannel.LOAD_DOCUMENT_URI; channel.loadFlags = Ci.nsIChannel.LOAD_DOCUMENT_URI;
// load the channel // load the channel
var uriLoader = Cc["@mozilla.org/uriloader;1"].getService(Ci.nsIURILoader); var uriLoader = Cc["@mozilla.org/uriloader;1"].getService(
Ci.nsIURILoader
);
// XXX ideally, whether to pass the IS_CONTENT_PREFERRED flag should be // XXX ideally, whether to pass the IS_CONTENT_PREFERRED flag should be
// passed in from above. Practically, the flag is probably a reasonable // passed in from above. Practically, the flag is probably a reasonable
// default since browsers don't care much, and link click is likely to be // default since browsers don't care much, and link click is likely to be
// the more interesting case for non-browser apps. See // the more interesting case for non-browser apps. See
// <https://bugzilla.mozilla.org/show_bug.cgi?id=392957#c9> for details. // <https://bugzilla.mozilla.org/show_bug.cgi?id=392957#c9> for details.
uriLoader.openURI(channel, Ci.nsIURILoader.IS_CONTENT_PREFERRED, uriLoader.openURI(
aWindowContext); channel,
Ci.nsIURILoader.IS_CONTENT_PREFERRED,
aWindowContext
);
return; return;
} }
let win = Services.wm.getMostRecentWindow("navigator:browser"); let win = Services.wm.getMostRecentWindow("navigator:browser");
// If this is an extension handler, check private browsing access. // If this is an extension handler, check private browsing access.
if (!privateAllowed && if (!privateAllowed && PrivateBrowsingUtils.isContentWindowPrivate(win)) {
PrivateBrowsingUtils.isContentWindowPrivate(win)) { throw Components.Exception(
throw Components.Exception("Extension not allowed in private windows.", "Extension not allowed in private windows.",
Cr.NS_ERROR_FILE_NOT_FOUND); Cr.NS_ERROR_FILE_NOT_FOUND
);
} }
// If we get an exception, there are several possible reasons why: // If we get an exception, there are several possible reasons why:
@ -147,11 +168,13 @@ nsWebHandlerApp.prototype = {
// above, so for now we don't catch the exception. // above, so for now we don't catch the exception.
// openURI // openURI
win.browserDOMWindow.openURI(uriToSend, win.browserDOMWindow.openURI(
uriToSend,
null, // no window.opener null, // no window.opener
Ci.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW, Ci.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW,
Ci.nsIBrowserDOMWindow.OPEN_NEW, Ci.nsIBrowserDOMWindow.OPEN_NEW,
Services.scriptSecurityManager.getSystemPrincipal()); Services.scriptSecurityManager.getSystemPrincipal()
);
}, },
// nsIWebHandlerApp // nsIWebHandlerApp

View file

@ -7,23 +7,34 @@
"use strict"; "use strict";
var EXPORTED_SYMBOLS = [ var EXPORTED_SYMBOLS = ["HandlerServiceTestUtils"];
"HandlerServiceTestUtils",
];
const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); const { AppConstants } = ChromeUtils.import(
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); "resource://gre/modules/AppConstants.jsm"
const {Assert} = ChromeUtils.import("resource://testing-common/Assert.jsm"); );
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Assert } = ChromeUtils.import("resource://testing-common/Assert.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "gExternalProtocolService", XPCOMUtils.defineLazyServiceGetter(
this,
"gExternalProtocolService",
"@mozilla.org/uriloader/external-protocol-service;1", "@mozilla.org/uriloader/external-protocol-service;1",
"nsIExternalProtocolService"); "nsIExternalProtocolService"
XPCOMUtils.defineLazyServiceGetter(this, "gMIMEService", );
XPCOMUtils.defineLazyServiceGetter(
this,
"gMIMEService",
"@mozilla.org/mime;1", "@mozilla.org/mime;1",
"nsIMIMEService"); "nsIMIMEService"
XPCOMUtils.defineLazyServiceGetter(this, "gHandlerService", );
XPCOMUtils.defineLazyServiceGetter(
this,
"gHandlerService",
"@mozilla.org/uriloader/handler-service;1", "@mozilla.org/uriloader/handler-service;1",
"nsIHandlerService"); "nsIHandlerService"
);
var HandlerServiceTestUtils = { var HandlerServiceTestUtils = {
/** /**
@ -34,9 +45,7 @@ var HandlerServiceTestUtils = {
* alphabetically regardless of category. * alphabetically regardless of category.
*/ */
getAllHandlerInfoTypes() { getAllHandlerInfoTypes() {
return Array.from(gHandlerService.enumerate(), return Array.from(gHandlerService.enumerate(), info => info.type).sort();
info => info.type)
.sort();
}, },
/** /**
@ -97,12 +106,16 @@ var HandlerServiceTestUtils = {
// method does on the default nsIHandlerService instance. // method does on the default nsIHandlerService instance.
let osDefaultHandlerFound = {}; let osDefaultHandlerFound = {};
let handlerInfo = gExternalProtocolService.getProtocolHandlerInfoFromOS( let handlerInfo = gExternalProtocolService.getProtocolHandlerInfoFromOS(
type, osDefaultHandlerFound); type,
osDefaultHandlerFound
);
if (gHandlerService.exists(handlerInfo)) { if (gHandlerService.exists(handlerInfo)) {
gHandlerService.fillHandlerInfo(handlerInfo, ""); gHandlerService.fillHandlerInfo(handlerInfo, "");
} else { } else {
gExternalProtocolService.setProtocolHandlerDefaults( gExternalProtocolService.setProtocolHandlerDefaults(
handlerInfo, osDefaultHandlerFound.value); handlerInfo,
osDefaultHandlerFound.value
);
} }
return handlerInfo; return handlerInfo;
}, },
@ -158,15 +171,18 @@ var HandlerServiceTestUtils = {
* Checks whether an nsIHandlerInfo instance matches the provided object. * Checks whether an nsIHandlerInfo instance matches the provided object.
*/ */
assertHandlerInfoMatches(handlerInfo, expected) { assertHandlerInfoMatches(handlerInfo, expected) {
let expectedInterface = expected.type.includes("/") ? Ci.nsIMIMEInfo let expectedInterface = expected.type.includes("/")
? Ci.nsIMIMEInfo
: Ci.nsIHandlerInfo; : Ci.nsIHandlerInfo;
Assert.ok(handlerInfo instanceof expectedInterface); Assert.ok(handlerInfo instanceof expectedInterface);
Assert.equal(handlerInfo.type, expected.type); Assert.equal(handlerInfo.type, expected.type);
if (!expected.preferredActionOSDependent) { if (!expected.preferredActionOSDependent) {
Assert.equal(handlerInfo.preferredAction, expected.preferredAction); Assert.equal(handlerInfo.preferredAction, expected.preferredAction);
Assert.equal(handlerInfo.alwaysAskBeforeHandling, Assert.equal(
expected.alwaysAskBeforeHandling); handlerInfo.alwaysAskBeforeHandling,
expected.alwaysAskBeforeHandling
);
} }
if (expectedInterface == Ci.nsIMIMEInfo) { if (expectedInterface == Ci.nsIMIMEInfo) {
@ -178,14 +194,15 @@ var HandlerServiceTestUtils = {
} }
if (expected.preferredApplicationHandler) { if (expected.preferredApplicationHandler) {
this.assertHandlerAppMatches(handlerInfo.preferredApplicationHandler, this.assertHandlerAppMatches(
expected.preferredApplicationHandler); handlerInfo.preferredApplicationHandler,
expected.preferredApplicationHandler
);
} else { } else {
Assert.equal(handlerInfo.preferredApplicationHandler, null); Assert.equal(handlerInfo.preferredApplicationHandler, null);
} }
let handlerAppsArrayEnumerator = let handlerAppsArrayEnumerator = handlerInfo.possibleApplicationHandlers.enumerate();
handlerInfo.possibleApplicationHandlers.enumerate();
if (AppConstants.platform == "android") { if (AppConstants.platform == "android") {
// On Android, the first handler application is always the internal one. // On Android, the first handler application is always the internal one.
this.assertHandlerAppMatches(handlerAppsArrayEnumerator.getNext(), { this.assertHandlerAppMatches(handlerAppsArrayEnumerator.getNext(), {
@ -193,8 +210,10 @@ var HandlerServiceTestUtils = {
}); });
} }
for (let expectedHandlerApp of expected.possibleApplicationHandlers || []) { for (let expectedHandlerApp of expected.possibleApplicationHandlers || []) {
this.assertHandlerAppMatches(handlerAppsArrayEnumerator.getNext(), this.assertHandlerAppMatches(
expectedHandlerApp); handlerAppsArrayEnumerator.getNext(),
expectedHandlerApp
);
} }
Assert.ok(!handlerAppsArrayEnumerator.hasMoreElements()); Assert.ok(!handlerAppsArrayEnumerator.hasMoreElements());
}, },

View file

@ -1,35 +1,39 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */ * http://creativecommons.org/publicdomain/zero/1.0/ */
const ROOT = getRootDirectory(gTestPath).replace("chrome://mochitests/content", const ROOT = getRootDirectory(gTestPath).replace(
"https://example.com"); "chrome://mochitests/content",
"https://example.com"
);
const PAGE_URL = ROOT + "download_page.html"; const PAGE_URL = ROOT + "download_page.html";
const SJS_URL = ROOT + "download.sjs"; const SJS_URL = ROOT + "download.sjs";
const HELPERAPP_DIALOG_CONTRACT_ID = "@mozilla.org/helperapplauncherdialog;1"; const HELPERAPP_DIALOG_CONTRACT_ID = "@mozilla.org/helperapplauncherdialog;1";
const HELPERAPP_DIALOG_CID = const HELPERAPP_DIALOG_CID = Components.ID(
Components.ID(Cc[HELPERAPP_DIALOG_CONTRACT_ID].number); Cc[HELPERAPP_DIALOG_CONTRACT_ID].number
const MOCK_HELPERAPP_DIALOG_CID = );
Components.ID("{2f372b6f-56c9-46d5-af0d-9f09bb69860c}"); const MOCK_HELPERAPP_DIALOG_CID = Components.ID(
"{2f372b6f-56c9-46d5-af0d-9f09bb69860c}"
);
let registrar = Components.manager let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
.QueryInterface(Ci.nsIComponentRegistrar);
let curDialogResolve = null; let curDialogResolve = null;
function HelperAppLauncherDialog() { function HelperAppLauncherDialog() {}
}
HelperAppLauncherDialog.prototype = { HelperAppLauncherDialog.prototype = {
show(aLauncher, aWindowContext, aReason) { show(aLauncher, aWindowContext, aReason) {
ok(true, "Showing the helper app dialog"); ok(true, "Showing the helper app dialog");
curDialogResolve(aWindowContext); curDialogResolve(aWindowContext);
executeSoon(() => { aLauncher.cancel(Cr.NS_ERROR_ABORT); }); executeSoon(() => {
aLauncher.cancel(Cr.NS_ERROR_ABORT);
});
}, },
QueryInterface: ChromeUtils.generateQI([Ci.nsIHelperAppLauncherDialog]), QueryInterface: ChromeUtils.generateQI([Ci.nsIHelperAppLauncherDialog]),
}; };
function promiseHelperAppDialog() { function promiseHelperAppDialog() {
return new Promise((resolve) => { return new Promise(resolve => {
curDialogResolve = resolve; curDialogResolve = resolve;
}); });
} }
@ -39,17 +43,26 @@ let mockHelperAppService;
add_task(async function setup() { add_task(async function setup() {
// Replace the real helper app dialog with our own. // Replace the real helper app dialog with our own.
mockHelperAppService = XPCOMUtils._getFactory(HelperAppLauncherDialog); mockHelperAppService = XPCOMUtils._getFactory(HelperAppLauncherDialog);
registrar.registerFactory(MOCK_HELPERAPP_DIALOG_CID, "", registrar.registerFactory(
MOCK_HELPERAPP_DIALOG_CID,
"",
HELPERAPP_DIALOG_CONTRACT_ID, HELPERAPP_DIALOG_CONTRACT_ID,
mockHelperAppService); mockHelperAppService
);
}); });
add_task(async function simple_navigation() { add_task(async function simple_navigation() {
// Tests that simple navigation gives us the right windowContext (that is, // Tests that simple navigation gives us the right windowContext (that is,
// the window that we're using). // the window that we're using).
await BrowserTestUtils.withNewTab({ gBrowser, url: PAGE_URL }, async function(browser) { await BrowserTestUtils.withNewTab({ gBrowser, url: PAGE_URL }, async function(
browser
) {
let dialogAppeared = promiseHelperAppDialog(); let dialogAppeared = promiseHelperAppDialog();
await BrowserTestUtils.synthesizeMouseAtCenter("#regular_load", {}, browser); await BrowserTestUtils.synthesizeMouseAtCenter(
"#regular_load",
{},
browser
);
let windowContext = await dialogAppeared; let windowContext = await dialogAppeared;
is(windowContext, browser.ownerGlobal, "got the right windowContext"); is(windowContext, browser.ownerGlobal, "got the right windowContext");
@ -61,15 +74,18 @@ add_task(async function simple_navigation() {
// automatically open and close that tab. // automatically open and close that tab.
async function testNewTab(browser) { async function testNewTab(browser) {
let dialogAppeared = promiseHelperAppDialog(); let dialogAppeared = promiseHelperAppDialog();
let tabOpened = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen").then((event) => { let tabOpened = BrowserTestUtils.waitForEvent(
return [ event.target, BrowserTestUtils.waitForTabClosing(event.target) ]; gBrowser.tabContainer,
"TabOpen"
).then(event => {
return [event.target, BrowserTestUtils.waitForTabClosing(event.target)];
}); });
await BrowserTestUtils.synthesizeMouseAtCenter("#target_blank", {}, browser); await BrowserTestUtils.synthesizeMouseAtCenter("#target_blank", {}, browser);
let windowContext = await dialogAppeared; let windowContext = await dialogAppeared;
is(windowContext, browser.ownerGlobal, "got the right windowContext"); is(windowContext, browser.ownerGlobal, "got the right windowContext");
let [ tab, closingPromise ] = await tabOpened; let [tab, closingPromise] = await tabOpened;
await closingPromise; await closingPromise;
is(tab.linkedBrowser, null, "tab was opened and closed"); is(tab.linkedBrowser, null, "tab was opened and closed");
} }
@ -77,7 +93,9 @@ async function testNewTab(browser) {
add_task(async function target_blank() { add_task(async function target_blank() {
// Tests that a link with target=_blank opens a new tab and closes it, // Tests that a link with target=_blank opens a new tab and closes it,
// returning the window that we're using for navigation. // returning the window that we're using for navigation.
await BrowserTestUtils.withNewTab({ gBrowser, url: PAGE_URL }, async function(browser) { await BrowserTestUtils.withNewTab({ gBrowser, url: PAGE_URL }, async function(
browser
) {
await testNewTab(browser); await testNewTab(browser);
}); });
}); });
@ -87,7 +105,9 @@ add_task(async function new_window() {
// width and a height in window.open) opens a new window for the load, // width and a height in window.open) opens a new window for the load,
// realizes that we need to close that window and returns the *original* // realizes that we need to close that window and returns the *original*
// window as the window context. // window as the window context.
await BrowserTestUtils.withNewTab({ gBrowser, url: PAGE_URL }, async function(browser) { await BrowserTestUtils.withNewTab({ gBrowser, url: PAGE_URL }, async function(
browser
) {
let dialogAppeared = promiseHelperAppDialog(); let dialogAppeared = promiseHelperAppDialog();
let windowOpened = BrowserTestUtils.waitForNewWindow(); let windowOpened = BrowserTestUtils.waitForNewWindow();
@ -96,7 +116,6 @@ add_task(async function new_window() {
// Now allow request to complete: // Now allow request to complete:
fetch(SJS_URL + "?finish"); fetch(SJS_URL + "?finish");
let windowContext = await dialogAppeared; let windowContext = await dialogAppeared;
is(windowContext, browser.ownerGlobal, "got the right windowContext"); is(windowContext, browser.ownerGlobal, "got the right windowContext");
@ -109,9 +128,19 @@ add_task(async function new_window() {
add_task(async function nested_window_opens() { add_task(async function nested_window_opens() {
// Tests that the window auto-closing feature works if the download is // Tests that the window auto-closing feature works if the download is
// initiated by a window that, itself, has an opener (see bug 1373109). // initiated by a window that, itself, has an opener (see bug 1373109).
await BrowserTestUtils.withNewTab({ gBrowser, url: PAGE_URL }, async function(outerBrowser) { await BrowserTestUtils.withNewTab({ gBrowser, url: PAGE_URL }, async function(
let secondTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, `${PAGE_URL}?newwin`, true); outerBrowser
BrowserTestUtils.synthesizeMouseAtCenter("#open_in_new_tab", {}, outerBrowser); ) {
let secondTabPromise = BrowserTestUtils.waitForNewTab(
gBrowser,
`${PAGE_URL}?newwin`,
true
);
BrowserTestUtils.synthesizeMouseAtCenter(
"#open_in_new_tab",
{},
outerBrowser
);
let secondTab = await secondTabPromise; let secondTab = await secondTabPromise;
let nestedBrowser = secondTab.linkedBrowser; let nestedBrowser = secondTab.linkedBrowser;
@ -121,7 +150,11 @@ add_task(async function nested_window_opens() {
await testNewTab(nestedBrowser); await testNewTab(nestedBrowser);
isnot(secondTab.linkedBrowser, null, "the page that triggered the download is still open"); isnot(
secondTab.linkedBrowser,
null,
"the page that triggered the download is still open"
);
BrowserTestUtils.removeTab(secondTab); BrowserTestUtils.removeTab(secondTab);
}); });
}); });
@ -129,6 +162,10 @@ add_task(async function nested_window_opens() {
add_task(async function cleanup() { add_task(async function cleanup() {
// Unregister our factory from XPCOM and restore the original CID. // Unregister our factory from XPCOM and restore the original CID.
registrar.unregisterFactory(MOCK_HELPERAPP_DIALOG_CID, mockHelperAppService); registrar.unregisterFactory(MOCK_HELPERAPP_DIALOG_CID, mockHelperAppService);
registrar.registerFactory(HELPERAPP_DIALOG_CID, "", registrar.registerFactory(
HELPERAPP_DIALOG_CONTRACT_ID, null); HELPERAPP_DIALOG_CID,
"",
HELPERAPP_DIALOG_CONTRACT_ID,
null
);
}); });

View file

@ -10,9 +10,15 @@ add_task(async function() {
info("Waiting for dialog to be populated."); info("Waiting for dialog to be populated.");
await BrowserTestUtils.waitForAttribute("value", location, expectedValue); await BrowserTestUtils.waitForAttribute("value", location, expectedValue);
} }
is(doc.getElementById("mode").selectedItem.id, "open", "Should be opening the file."); is(
ok(!dlg.document.getElementById("openHandler").selectedItem.hidden, doc.getElementById("mode").selectedItem.id,
"Should not have selected a hidden item."); "open",
"Should be opening the file."
);
ok(
!dlg.document.getElementById("openHandler").selectedItem.hidden,
"Should not have selected a hidden item."
);
let helperAppDialogHiddenPromise = BrowserTestUtils.windowClosed(dlg); let helperAppDialogHiddenPromise = BrowserTestUtils.windowClosed(dlg);
doc.documentElement.cancelDialog(); doc.documentElement.cancelDialog();
await helperAppDialogHiddenPromise; await helperAppDialogHiddenPromise;

View file

@ -38,8 +38,10 @@ add_task(async function test_download_privatebrowsing() {
let win = await BrowserTestUtils.openNewBrowserWindow({ private: true }); let win = await BrowserTestUtils.openNewBrowserWindow({ private: true });
try { try {
let tab = await BrowserTestUtils.openNewForegroundTab(win.gBrowser, let tab = await BrowserTestUtils.openNewForegroundTab(
`data:text/html,<a download href="data:text/plain,">download</a>`); win.gBrowser,
`data:text/html,<a download href="data:text/plain,">download</a>`
);
let promiseNextPrivateDownload = new Promise(resolve => { let promiseNextPrivateDownload = new Promise(resolve => {
privateList.addView({ privateList.addView({

View file

@ -8,12 +8,17 @@ add_task(async function() {
let doc = dlg.document; let doc = dlg.document;
// Set remember choice // Set remember choice
ok(!doc.getElementById("rememberChoice").checked, ok(
"Remember choice checkbox should be not checked."); !doc.getElementById("rememberChoice").checked,
"Remember choice checkbox should be not checked."
);
doc.getElementById("rememberChoice").checked = true; doc.getElementById("rememberChoice").checked = true;
// Make sure the mock handler information is not in nsIHandlerService // Make sure the mock handler information is not in nsIHandlerService
ok(!gHandlerSvc.exists(launcher.MIMEInfo), "Should not be in nsIHandlerService."); ok(
!gHandlerSvc.exists(launcher.MIMEInfo),
"Should not be in nsIHandlerService."
);
// close the dialog by pushing the ok button. // close the dialog by pushing the ok button.
let dialogClosedPromise = BrowserTestUtils.windowClosed(dlg); let dialogClosedPromise = BrowserTestUtils.windowClosed(dlg);
@ -32,15 +37,23 @@ add_task(async function() {
for (let handlerInfo of gHandlerSvc.enumerate()) { for (let handlerInfo of gHandlerSvc.enumerate()) {
if (handlerInfo.type == launcher.MIMEInfo.type) { if (handlerInfo.type == launcher.MIMEInfo.type) {
// check the alwaysAskBeforeHandling // check the alwaysAskBeforeHandling
ok(!handlerInfo.alwaysAskBeforeHandling, ok(
"Should turn off the always ask."); !handlerInfo.alwaysAskBeforeHandling,
"Should turn off the always ask."
);
// check the preferredApplicationHandler // check the preferredApplicationHandler
ok(handlerInfo.preferredApplicationHandler.equals( ok(
launcher.MIMEInfo.preferredApplicationHandler), handlerInfo.preferredApplicationHandler.equals(
"Should be equal to the mockedHandlerApp."); launcher.MIMEInfo.preferredApplicationHandler
),
"Should be equal to the mockedHandlerApp."
);
// check the perferredAction // check the perferredAction
is(handlerInfo.preferredAction, launcher.MIMEInfo.preferredAction, is(
"Should be equal to Ci.nsIHandlerInfo.useHelperApp."); handlerInfo.preferredAction,
launcher.MIMEInfo.preferredAction,
"Should be equal to Ci.nsIHandlerInfo.useHelperApp."
);
break; break;
} }
} }

View file

@ -1,4 +1,5 @@
let testURL = "https://example.com/browser/" + let testURL =
"https://example.com/browser/" +
"uriloader/exthandler/tests/mochitest/protocolHandler.html"; "uriloader/exthandler/tests/mochitest/protocolHandler.html";
add_task(async function() { add_task(async function() {
@ -18,45 +19,66 @@ add_task(async function() {
button.click(); button.click();
// Set the new handler as default. // Set the new handler as default.
const protoSvc = Cc["@mozilla.org/uriloader/external-protocol-service;1"]. const protoSvc = Cc[
getService(Ci.nsIExternalProtocolService); "@mozilla.org/uriloader/external-protocol-service;1"
].getService(Ci.nsIExternalProtocolService);
let protoInfo = protoSvc.getProtocolHandlerInfo("web+testprotocol"); let protoInfo = protoSvc.getProtocolHandlerInfo("web+testprotocol");
is(protoInfo.preferredAction, protoInfo.useHelperApp, is(
"using a helper application is the preferred action"); protoInfo.preferredAction,
protoInfo.useHelperApp,
"using a helper application is the preferred action"
);
ok(!protoInfo.preferredApplicationHandler, "no preferred handler is set"); ok(!protoInfo.preferredApplicationHandler, "no preferred handler is set");
let handlers = protoInfo.possibleApplicationHandlers; let handlers = protoInfo.possibleApplicationHandlers;
is(1, handlers.length, "only one handler registered for web+testprotocol"); is(1, handlers.length, "only one handler registered for web+testprotocol");
let handler = handlers.queryElementAt(0, Ci.nsIHandlerApp); let handler = handlers.queryElementAt(0, Ci.nsIHandlerApp);
ok(handler instanceof Ci.nsIWebHandlerApp, "the handler is a web handler"); ok(handler instanceof Ci.nsIWebHandlerApp, "the handler is a web handler");
is(handler.uriTemplate, "https://example.com/foobar?uri=%s", is(
"correct url template"); handler.uriTemplate,
"https://example.com/foobar?uri=%s",
"correct url template"
);
protoInfo.preferredApplicationHandler = handler; protoInfo.preferredApplicationHandler = handler;
protoInfo.alwaysAskBeforeHandling = false; protoInfo.alwaysAskBeforeHandling = false;
const handlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"]. const handlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
getService(Ci.nsIHandlerService); Ci.nsIHandlerService
);
handlerSvc.store(protoInfo); handlerSvc.store(protoInfo);
// Middle-click a testprotocol link and check the new tab is correct // Middle-click a testprotocol link and check the new tab is correct
let link = "#link"; let link = "#link";
const expectedURL = "https://example.com/foobar?uri=web%2Btestprotocol%3Atest"; const expectedURL =
"https://example.com/foobar?uri=web%2Btestprotocol%3Atest";
let promiseTabOpened = let promiseTabOpened = BrowserTestUtils.waitForNewTab(gBrowser, expectedURL);
BrowserTestUtils.waitForNewTab(gBrowser, expectedURL); await BrowserTestUtils.synthesizeMouseAtCenter(link, { button: 1 }, browser);
await BrowserTestUtils.synthesizeMouseAtCenter(link, {button: 1}, browser);
let tab = await promiseTabOpened; let tab = await promiseTabOpened;
gBrowser.selectedTab = tab; gBrowser.selectedTab = tab;
is(gURLBar.value, expectedURL, is(
"the expected URL is displayed in the location bar"); gURLBar.value,
expectedURL,
"the expected URL is displayed in the location bar"
);
BrowserTestUtils.removeTab(tab); BrowserTestUtils.removeTab(tab);
// Shift-click the testprotocol link and check the new window. // Shift-click the testprotocol link and check the new window.
let newWindowPromise = BrowserTestUtils.waitForNewWindow({url: expectedURL}); let newWindowPromise = BrowserTestUtils.waitForNewWindow({
await BrowserTestUtils.synthesizeMouseAtCenter(link, {shiftKey: true}, url: expectedURL,
browser); });
await BrowserTestUtils.synthesizeMouseAtCenter(
link,
{ shiftKey: true },
browser
);
let win = await newWindowPromise; let win = await newWindowPromise;
await BrowserTestUtils.waitForCondition(() => win.gBrowser.currentURI.spec == expectedURL); await BrowserTestUtils.waitForCondition(
is(win.gURLBar.value, expectedURL, () => win.gBrowser.currentURI.spec == expectedURL
"the expected URL is displayed in the location bar"); );
is(
win.gURLBar.value,
expectedURL,
"the expected URL is displayed in the location bar"
);
await BrowserTestUtils.closeWindow(win); await BrowserTestUtils.closeWindow(win);
// Click the testprotocol link and check the url in the current tab. // Click the testprotocol link and check the url in the current tab.
@ -64,8 +86,11 @@ add_task(async function() {
await BrowserTestUtils.synthesizeMouseAtCenter(link, {}, browser); await BrowserTestUtils.synthesizeMouseAtCenter(link, {}, browser);
await loadPromise; await loadPromise;
await BrowserTestUtils.waitForCondition(() => gURLBar.value != testURL); await BrowserTestUtils.waitForCondition(() => gURLBar.value != testURL);
is(gURLBar.value, expectedURL, is(
"the expected URL is displayed in the location bar"); gURLBar.value,
expectedURL,
"the expected URL is displayed in the location bar"
);
// Cleanup. // Cleanup.
protoInfo.preferredApplicationHandler = null; protoInfo.preferredApplicationHandler = null;

View file

@ -9,8 +9,9 @@ const Cc = SpecialPowers.Cc;
function test() { function test() {
// set up the web handler object // set up the web handler object
var webHandler = Cc["@mozilla.org/uriloader/web-handler-app;1"]. var webHandler = Cc[
createInstance(SpecialPowers.Ci.nsIWebHandlerApp); "@mozilla.org/uriloader/web-handler-app;1"
].createInstance(SpecialPowers.Ci.nsIWebHandlerApp);
webHandler.name = "Test Web Handler App"; webHandler.name = "Test Web Handler App";
webHandler.uriTemplate = webHandler.uriTemplate =
"https://example.com/tests/uriloader/exthandler/tests/mochitest/" + "https://example.com/tests/uriloader/exthandler/tests/mochitest/" +
@ -19,8 +20,9 @@ function test() {
// set up the uri to test with // set up the uri to test with
/* eslint-disable mozilla/use-services */ /* eslint-disable mozilla/use-services */
var ioService = Cc["@mozilla.org/network/io-service;1"]. var ioService = Cc["@mozilla.org/network/io-service;1"].getService(
getService(SpecialPowers.Ci.nsIIOService); SpecialPowers.Ci.nsIIOService
);
var uri = ioService.newURI(testURI); var uri = ioService.newURI(testURI);
@ -41,18 +43,21 @@ function test() {
ok(true, "webHandler launchWithURI (new window/tab) test started"); ok(true, "webHandler launchWithURI (new window/tab) test started");
// set up the local handler object // set up the local handler object
var localHandler = Cc["@mozilla.org/uriloader/local-handler-app;1"]. var localHandler = Cc[
createInstance(SpecialPowers.Ci.nsILocalHandlerApp); "@mozilla.org/uriloader/local-handler-app;1"
].createInstance(SpecialPowers.Ci.nsILocalHandlerApp);
localHandler.name = "Test Local Handler App"; localHandler.name = "Test Local Handler App";
// get a local app that we know will be there and do something sane // get a local app that we know will be there and do something sane
/* eslint-disable mozilla/use-services */ /* eslint-disable mozilla/use-services */
var osString = Cc["@mozilla.org/xre/app-info;1"]. var osString = Cc["@mozilla.org/xre/app-info;1"].getService(
getService(SpecialPowers.Ci.nsIXULRuntime).OS; SpecialPowers.Ci.nsIXULRuntime
).OS;
var dirSvc = Cc["@mozilla.org/file/directory_service;1"]. var dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(
getService(SpecialPowers.Ci.nsIDirectoryServiceProvider); SpecialPowers.Ci.nsIDirectoryServiceProvider
);
if (osString == "WINNT") { if (osString == "WINNT") {
var windowsDir = dirSvc.getFile("WinD", {}); var windowsDir = dirSvc.getFile("WinD", {});
var exe = windowsDir.clone().QueryInterface(SpecialPowers.Ci.nsIFile); var exe = windowsDir.clone().QueryInterface(SpecialPowers.Ci.nsIFile);
@ -71,14 +76,16 @@ function test() {
todo(false, "On SeaMonkey, testing OS X as generic Unix. (Bug 749872)"); todo(false, "On SeaMonkey, testing OS X as generic Unix. (Bug 749872)");
// assume a generic UNIX variant // assume a generic UNIX variant
exe = Cc["@mozilla.org/file/local;1"]. exe = Cc["@mozilla.org/file/local;1"].createInstance(
createInstance(SpecialPowers.Ci.nsIFile); SpecialPowers.Ci.nsIFile
);
exe.initWithPath("/bin/echo"); exe.initWithPath("/bin/echo");
} }
} else { } else {
// assume a generic UNIX variant // assume a generic UNIX variant
exe = Cc["@mozilla.org/file/local;1"]. exe = Cc["@mozilla.org/file/local;1"].createInstance(
createInstance(SpecialPowers.Ci.nsIFile); SpecialPowers.Ci.nsIFile
);
exe.initWithPath("/bin/echo"); exe.initWithPath("/bin/echo");
} }
@ -91,12 +98,14 @@ function test() {
// if we ever decide that killing iCal is the right thing to do, change // if we ever decide that killing iCal is the right thing to do, change
// the if statement below from "NOTDarwin" to "Darwin" // the if statement below from "NOTDarwin" to "Darwin"
if (osString == "NOTDarwin") { if (osString == "NOTDarwin") {
var killall = Cc["@mozilla.org/file/local;1"]. var killall = Cc["@mozilla.org/file/local;1"].createInstance(
createInstance(SpecialPowers.Ci.nsIFile); SpecialPowers.Ci.nsIFile
);
killall.initWithPath("/usr/bin/killall"); killall.initWithPath("/usr/bin/killall");
var process = Cc["@mozilla.org/process/util;1"]. var process = Cc["@mozilla.org/process/util;1"].createInstance(
createInstance(SpecialPowers.Ci.nsIProcess); SpecialPowers.Ci.nsIProcess
);
process.init(killall); process.init(killall);
var args = ["iCal"]; var args = ["iCal"];

View file

@ -1,7 +1,9 @@
var {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm"); var { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm");
var gMimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService); var gMimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
var gHandlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService); var gHandlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
Ci.nsIHandlerService
);
function createMockedHandlerApp() { function createMockedHandlerApp() {
// Mock the executable // Mock the executable
@ -11,8 +13,9 @@ function createMockedHandlerApp() {
} }
// Mock the handler app // Mock the handler app
let mockedHandlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"] let mockedHandlerApp = Cc[
.createInstance(Ci.nsILocalHandlerApp); "@mozilla.org/uriloader/local-handler-app;1"
].createInstance(Ci.nsILocalHandlerApp);
mockedHandlerApp.executable = mockedExecutable; mockedHandlerApp.executable = mockedExecutable;
mockedHandlerApp.detailedDescription = "Mocked handler app"; mockedHandlerApp.detailedDescription = "Mocked handler app";
@ -28,14 +31,19 @@ function createMockedHandlerApp() {
function createMockedObjects(createHandlerApp) { function createMockedObjects(createHandlerApp) {
// Mock the mime info // Mock the mime info
let internalMockedMIME = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null); let internalMockedMIME = gMimeSvc.getFromTypeAndExtension(
"text/x-test-handler",
null
);
internalMockedMIME.alwaysAskBeforeHandling = true; internalMockedMIME.alwaysAskBeforeHandling = true;
internalMockedMIME.preferredAction = Ci.nsIHandlerInfo.useHelperApp; internalMockedMIME.preferredAction = Ci.nsIHandlerInfo.useHelperApp;
internalMockedMIME.appendExtension("abc"); internalMockedMIME.appendExtension("abc");
if (createHandlerApp) { if (createHandlerApp) {
let mockedHandlerApp = createMockedHandlerApp(); let mockedHandlerApp = createMockedHandlerApp();
internalMockedMIME.description = mockedHandlerApp.detailedDescription; internalMockedMIME.description = mockedHandlerApp.detailedDescription;
internalMockedMIME.possibleApplicationHandlers.appendElement(mockedHandlerApp); internalMockedMIME.possibleApplicationHandlers.appendElement(
mockedHandlerApp
);
internalMockedMIME.preferredApplicationHandler = mockedHandlerApp; internalMockedMIME.preferredApplicationHandler = mockedHandlerApp;
} }
@ -68,12 +76,18 @@ function createMockedObjects(createHandlerApp) {
targetFile: null, // never read targetFile: null, // never read
// PRTime is microseconds since epoch, Date.now() returns milliseconds: // PRTime is microseconds since epoch, Date.now() returns milliseconds:
timeDownloadStarted: Date.now() * 1000, timeDownloadStarted: Date.now() * 1000,
QueryInterface: ChromeUtils.generateQI([Ci.nsICancelable, Ci.nsIHelperAppLauncher]), QueryInterface: ChromeUtils.generateQI([
Ci.nsICancelable,
Ci.nsIHelperAppLauncher,
]),
}; };
registerCleanupFunction(function() { registerCleanupFunction(function() {
// remove the mocked mime info from database. // remove the mocked mime info from database.
let mockHandlerInfo = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null); let mockHandlerInfo = gMimeSvc.getFromTypeAndExtension(
"text/x-test-handler",
null
);
if (gHandlerSvc.exists(mockHandlerInfo)) { if (gHandlerSvc.exists(mockHandlerInfo)) {
gHandlerSvc.remove(mockHandlerInfo); gHandlerSvc.remove(mockHandlerInfo);
} }
@ -83,22 +97,29 @@ function createMockedObjects(createHandlerApp) {
} }
async function openHelperAppDialog(launcher) { async function openHelperAppDialog(launcher) {
let helperAppDialog = Cc["@mozilla.org/helperapplauncherdialog;1"]. let helperAppDialog = Cc[
createInstance(Ci.nsIHelperAppLauncherDialog); "@mozilla.org/helperapplauncherdialog;1"
].createInstance(Ci.nsIHelperAppLauncherDialog);
let helperAppDialogShownPromise = BrowserTestUtils.domWindowOpened(); let helperAppDialogShownPromise = BrowserTestUtils.domWindowOpened();
try { try {
helperAppDialog.show(launcher, window, "foopy"); helperAppDialog.show(launcher, window, "foopy");
} catch (ex) { } catch (ex) {
ok(false, "Trying to show unknownContentType.xul failed with exception: " + ex); ok(
false,
"Trying to show unknownContentType.xul failed with exception: " + ex
);
Cu.reportError(ex); Cu.reportError(ex);
} }
let dlg = await helperAppDialogShownPromise; let dlg = await helperAppDialogShownPromise;
await BrowserTestUtils.waitForEvent(dlg, "load", false); await BrowserTestUtils.waitForEvent(dlg, "load", false);
is(dlg.location.href, "chrome://mozapps/content/downloads/unknownContentType.xul", is(
"Got correct dialog"); dlg.location.href,
"chrome://mozapps/content/downloads/unknownContentType.xul",
"Got correct dialog"
);
return dlg; return dlg;
} }

View file

@ -1,11 +1,15 @@
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const HELPERAPP_DIALOG_CONTRACT = "@mozilla.org/helperapplauncherdialog;1"; const HELPERAPP_DIALOG_CONTRACT = "@mozilla.org/helperapplauncherdialog;1";
const HELPERAPP_DIALOG_CID = const HELPERAPP_DIALOG_CID = Components.ID(
Components.ID(Cc[HELPERAPP_DIALOG_CONTRACT].number); Cc[HELPERAPP_DIALOG_CONTRACT].number
);
const FAKE_CID = Cc["@mozilla.org/uuid-generator;1"]. const FAKE_CID = Cc["@mozilla.org/uuid-generator;1"]
getService(Ci.nsIUUIDGenerator).generateUUID(); .getService(Ci.nsIUUIDGenerator)
.generateUUID();
/* eslint-env mozilla/frame-script */ /* eslint-env mozilla/frame-script */
function HelperAppLauncherDialog() {} function HelperAppLauncherDialog() {}
HelperAppLauncherDialog.prototype = { HelperAppLauncherDialog.prototype = {
@ -16,11 +20,19 @@ HelperAppLauncherDialog.prototype = {
}; };
var registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); var registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
registrar.registerFactory(FAKE_CID, "", HELPERAPP_DIALOG_CONTRACT, registrar.registerFactory(
XPCOMUtils._getFactory(HelperAppLauncherDialog)); FAKE_CID,
"",
HELPERAPP_DIALOG_CONTRACT,
XPCOMUtils._getFactory(HelperAppLauncherDialog)
);
addMessageListener("unregister", function() { addMessageListener("unregister", function() {
registrar.registerFactory(HELPERAPP_DIALOG_CID, "", registrar.registerFactory(
HELPERAPP_DIALOG_CONTRACT, null); HELPERAPP_DIALOG_CID,
"",
HELPERAPP_DIALOG_CONTRACT,
null
);
sendAsyncMessage("unregistered"); sendAsyncMessage("unregistered");
}); });

View file

@ -8,19 +8,31 @@
"use strict"; "use strict";
var {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); var { AppConstants } = ChromeUtils.import(
var {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm"); "resource://gre/modules/AppConstants.jsm"
var {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); );
var {OS, require} = ChromeUtils.import("resource://gre/modules/osfile.jsm"); var { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm");
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); var { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); var { OS, require } = ChromeUtils.import("resource://gre/modules/osfile.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
ChromeUtils.import("resource://testing-common/HandlerServiceTestUtils.jsm", this); ChromeUtils.import(
var {TestUtils} = ChromeUtils.import("resource://testing-common/TestUtils.jsm"); "resource://testing-common/HandlerServiceTestUtils.jsm",
this
);
var { TestUtils } = ChromeUtils.import(
"resource://testing-common/TestUtils.jsm"
);
XPCOMUtils.defineLazyServiceGetter(this, "gHandlerService", XPCOMUtils.defineLazyServiceGetter(
this,
"gHandlerService",
"@mozilla.org/uriloader/handler-service;1", "@mozilla.org/uriloader/handler-service;1",
"nsIHandlerService"); "nsIHandlerService"
);
do_get_profile(); do_get_profile();

View file

@ -12,12 +12,14 @@ function run_test() {
var badMimeType = "text/plainÿ"; var badMimeType = "text/plainÿ";
Assert.equal(badMimeType.length, 11); Assert.equal(badMimeType.length, 11);
try { try {
Cc["@mozilla.org/mime;1"]. Cc["@mozilla.org/mime;1"]
getService(Ci.nsIMIMEService). .getService(Ci.nsIMIMEService)
getFromTypeAndExtension(badMimeType, "txt"); .getFromTypeAndExtension(badMimeType, "txt");
} catch (e) { } catch (e) {
if (!(e instanceof Ci.nsIException) || if (
e.result != Cr.NS_ERROR_NOT_AVAILABLE) { !(e instanceof Ci.nsIException) ||
e.result != Cr.NS_ERROR_NOT_AVAILABLE
) {
throw e; throw e;
} }
// This is an expected exception, thrown if the type can't be determined // This is an expected exception, thrown if the type can't be determined

View file

@ -11,8 +11,7 @@
function run_test() { function run_test() {
// --- Common services --- // --- Common services ---
const mimeService = Cc["@mozilla.org/mime;1"]. const mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
getService(Ci.nsIMIMEService);
const categoryManager = Services.catMan; const categoryManager = Services.catMan;
@ -30,8 +29,10 @@ function run_test() {
// The line above should have thrown an exception. // The line above should have thrown an exception.
do_throw("nsIMIMEService.getTypeFromExtension succeeded unexpectedly"); do_throw("nsIMIMEService.getTypeFromExtension succeeded unexpectedly");
} catch (e) { } catch (e) {
if (!(e instanceof Ci.nsIException) || if (
e.result != Cr.NS_ERROR_NOT_AVAILABLE) { !(e instanceof Ci.nsIException) ||
e.result != Cr.NS_ERROR_NOT_AVAILABLE
) {
throw e; throw e;
} }
// This is an expected exception, thrown if the type can't be determined. // This is an expected exception, thrown if the type can't be determined.
@ -39,8 +40,13 @@ function run_test() {
} }
// Add a temporary category entry mapping the extension to the MIME type. // Add a temporary category entry mapping the extension to the MIME type.
categoryManager.addCategoryEntry("ext-to-type-mapping", kTestExtension, categoryManager.addCategoryEntry(
kTestMimeType, false, true); "ext-to-type-mapping",
kTestExtension,
kTestMimeType,
false,
true
);
// Check that the mapping is recognized in the simple case. // Check that the mapping is recognized in the simple case.
var type = mimeService.getTypeFromExtension(kTestExtension); var type = mimeService.getTypeFromExtension(kTestExtension);
@ -51,5 +57,9 @@ function run_test() {
Assert.equal(type, kTestMimeType); Assert.equal(type, kTestMimeType);
// Clean up after ourselves. // Clean up after ourselves.
categoryManager.deleteCategoryEntry("ext-to-type-mapping", kTestExtension, false); categoryManager.deleteCategoryEntry(
"ext-to-type-mapping",
kTestExtension,
false
);
} }

View file

@ -21,21 +21,33 @@ function run_test() {
registerMockWindowsRegKeyFactory(); registerMockWindowsRegKeyFactory();
// Check the mock has been properly activated. // Check the mock has been properly activated.
let regKey = Cc["@mozilla.org/windows-registry-key;1"] let regKey = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
.createInstance(Ci.nsIWindowsRegKey); Ci.nsIWindowsRegKey
regKey.open(Ci.nsIWindowsRegKey.ROOT_KEY_CLASSES_ROOT, FILE_EXTENSION, );
Ci.nsIWindowsRegKey.ACCESS_QUERY_VALUE); regKey.open(
Assert.equal(regKey.readStringValue("content type"), "", Ci.nsIWindowsRegKey.ROOT_KEY_CLASSES_ROOT,
"Check the mock replied as expected."); FILE_EXTENSION,
Ci.nsIWindowsRegKey.ACCESS_QUERY_VALUE
);
Assert.equal(
regKey.readStringValue("content type"),
"",
"Check the mock replied as expected."
);
Assert.ok(gTestUsedOurMock, "The test properly used the mock registry"); Assert.ok(gTestUsedOurMock, "The test properly used the mock registry");
// Reset gTestUsedOurMock, because we just used it. // Reset gTestUsedOurMock, because we just used it.
gTestUsedOurMock = false; gTestUsedOurMock = false;
// Try and get the MIME type associated with the extension. If this // Try and get the MIME type associated with the extension. If this
// operation does not throw an unexpected exception, the test succeeds. // operation does not throw an unexpected exception, the test succeeds.
Assert.throws(() => { Assert.throws(
Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService) () => {
Cc["@mozilla.org/mime;1"]
.getService(Ci.nsIMIMEService)
.getTypeFromExtension(FILE_EXTENSION); .getTypeFromExtension(FILE_EXTENSION);
}, /NS_ERROR_NOT_AVAILABLE/, "Should throw a NOT_AVAILABLE exception"); },
/NS_ERROR_NOT_AVAILABLE/,
"Should throw a NOT_AVAILABLE exception"
);
Assert.ok(gTestUsedOurMock, "The test properly used the mock registry"); Assert.ok(gTestUsedOurMock, "The test properly used the mock registry");
} }
@ -122,9 +134,11 @@ MockWindowsRegKey.prototype = {
readStringValue(aName) { readStringValue(aName) {
// If this is the key under test, return a fake value // If this is the key under test, return a fake value
if (this._rootKey == Ci.nsIWindowsRegKey.ROOT_KEY_CLASSES_ROOT && if (
this._rootKey == Ci.nsIWindowsRegKey.ROOT_KEY_CLASSES_ROOT &&
this._relPath.toLowerCase() == FILE_EXTENSION && this._relPath.toLowerCase() == FILE_EXTENSION &&
aName.toLowerCase() == "content type") { aName.toLowerCase() == "content type"
) {
gTestUsedOurMock = true; gTestUsedOurMock = true;
return ""; return "";
} }
@ -140,8 +154,9 @@ function registerMockWindowsRegKeyFactory() {
let originalWindowsRegKeyCID = Cc[kWindowsRegKeyContractID].number; let originalWindowsRegKeyCID = Cc[kWindowsRegKeyContractID].number;
info("Create a mock RegKey factory"); info("Create a mock RegKey factory");
let originalRegKey = Cc["@mozilla.org/windows-registry-key;1"] let originalRegKey = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
.createInstance(Ci.nsIWindowsRegKey); Ci.nsIWindowsRegKey
);
let mockWindowsRegKeyFactory = { let mockWindowsRegKeyFactory = {
createInstance(outer, iid) { createInstance(outer, iid) {
if (outer != null) { if (outer != null) {
@ -163,10 +178,7 @@ function registerMockWindowsRegKeyFactory() {
registerCleanupFunction(() => { registerCleanupFunction(() => {
// Free references to the mock factory // Free references to the mock factory
registrar.unregisterFactory( registrar.unregisterFactory(kMockCID, mockWindowsRegKeyFactory);
kMockCID,
mockWindowsRegKeyFactory
);
// Restore the original factory // Restore the original factory
registrar.registerFactory( registrar.registerFactory(
Components.ID(originalWindowsRegKeyCID), Components.ID(originalWindowsRegKeyCID),

View file

@ -6,19 +6,21 @@ function run_test() {
//* *************************************************************************// //* *************************************************************************//
// Constants // Constants
const handlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"]. const handlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(
getService(Ci.nsIHandlerService); Ci.nsIHandlerService
);
const mimeSvc = Cc["@mozilla.org/mime;1"]. const mimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
getService(Ci.nsIMIMEService);
const protoSvc = Cc["@mozilla.org/uriloader/external-protocol-service;1"]. const protoSvc = Cc[
getService(Ci.nsIExternalProtocolService); "@mozilla.org/uriloader/external-protocol-service;1"
].getService(Ci.nsIExternalProtocolService);
const prefSvc = Services.prefs; const prefSvc = Services.prefs;
const env = Cc["@mozilla.org/process/environment;1"]. const env = Cc["@mozilla.org/process/environment;1"].getService(
getService(Ci.nsIEnvironment); Ci.nsIEnvironment
);
const rootPrefBranch = prefSvc.getBranch(""); const rootPrefBranch = prefSvc.getBranch("");
@ -26,12 +28,11 @@ function run_test() {
if (mozinfo.os == "win") { if (mozinfo.os == "win") {
// Check mailto handler from registry. // Check mailto handler from registry.
// If registry entry is nothing, no mailto handler // If registry entry is nothing, no mailto handler
let regSvc = Cc["@mozilla.org/windows-registry-key;1"]. let regSvc = Cc["@mozilla.org/windows-registry-key;1"].createInstance(
createInstance(Ci.nsIWindowsRegKey); Ci.nsIWindowsRegKey
);
try { try {
regSvc.open(regSvc.ROOT_KEY_CLASSES_ROOT, regSvc.open(regSvc.ROOT_KEY_CLASSES_ROOT, "mailto", regSvc.ACCESS_READ);
"mailto",
regSvc.ACCESS_READ);
noMailto = false; noMailto = false;
} catch (ex) { } catch (ex) {
noMailto = true; noMailto = true;
@ -42,8 +43,9 @@ function run_test() {
if (mozinfo.os == "linux") { if (mozinfo.os == "linux") {
// Check mailto handler from GIO // Check mailto handler from GIO
// If there isn't one, then we have no mailto handler // If there isn't one, then we have no mailto handler
let gIOSvc = Cc["@mozilla.org/gio-service;1"]. let gIOSvc = Cc["@mozilla.org/gio-service;1"].createInstance(
createInstance(Ci.nsIGIOService); Ci.nsIGIOService
);
try { try {
gIOSvc.getAppForURIScheme("mailto"); gIOSvc.getAppForURIScheme("mailto");
noMailto = false; noMailto = false;
@ -66,13 +68,15 @@ function run_test() {
// if (!executable.exists()) // if (!executable.exists())
// executable.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0o755); // executable.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0o755);
var localHandler = Cc["@mozilla.org/uriloader/local-handler-app;1"]. var localHandler = Cc[
createInstance(Ci.nsILocalHandlerApp); "@mozilla.org/uriloader/local-handler-app;1"
].createInstance(Ci.nsILocalHandlerApp);
localHandler.name = "Local Handler"; localHandler.name = "Local Handler";
localHandler.executable = executable; localHandler.executable = executable;
var webHandler = Cc["@mozilla.org/uriloader/web-handler-app;1"]. var webHandler = Cc[
createInstance(Ci.nsIWebHandlerApp); "@mozilla.org/uriloader/web-handler-app;1"
].createInstance(Ci.nsIWebHandlerApp);
webHandler.name = "Web Handler"; webHandler.name = "Web Handler";
webHandler.uriTemplate = "http://www.example.com/?%s"; webHandler.uriTemplate = "http://www.example.com/?%s";
@ -80,7 +84,6 @@ function run_test() {
// make sense to move each test into its own scope so we don't run the risk // make sense to move each test into its own scope so we don't run the risk
// of one test stomping on another's data. // of one test stomping on another's data.
//* *************************************************************************// //* *************************************************************************//
// Test Default Properties // Test Default Properties
@ -154,16 +157,18 @@ function run_test() {
// OS default exists, injected default exists, explicit warning pref: false // OS default exists, injected default exists, explicit warning pref: false
prefSvc.setBoolPref(kExternalWarningPrefPrefix + "mailto", false); prefSvc.setBoolPref(kExternalWarningPrefPrefix + "mailto", false);
protoInfo = protoSvc.getProtocolHandlerInfo("mailto"); protoInfo = protoSvc.getProtocolHandlerInfo("mailto");
if (haveDefaultHandlersVersion) if (haveDefaultHandlersVersion) {
Assert.equal(2, protoInfo.possibleApplicationHandlers.length); Assert.equal(2, protoInfo.possibleApplicationHandlers.length);
else } else {
Assert.equal(0, protoInfo.possibleApplicationHandlers.length); Assert.equal(0, protoInfo.possibleApplicationHandlers.length);
}
// Win7+ or Linux's GIO might not have a default mailto: handler // Win7+ or Linux's GIO might not have a default mailto: handler
if (noMailto) if (noMailto) {
Assert.ok(protoInfo.alwaysAskBeforeHandling); Assert.ok(protoInfo.alwaysAskBeforeHandling);
else } else {
Assert.ok(!protoInfo.alwaysAskBeforeHandling); Assert.ok(!protoInfo.alwaysAskBeforeHandling);
}
// OS default exists, injected default exists, explicit warning pref: true // OS default exists, injected default exists, explicit warning pref: true
prefSvc.setBoolPref(kExternalWarningPrefPrefix + "mailto", true); prefSvc.setBoolPref(kExternalWarningPrefPrefix + "mailto", true);
@ -175,10 +180,11 @@ function run_test() {
// the pref is true, the value in RDF is false. The injected mailto handler // the pref is true, the value in RDF is false. The injected mailto handler
// carried over the default pref value, and so when we set the pref above // carried over the default pref value, and so when we set the pref above
// to true it's ignored. // to true it's ignored.
if (noMailto) if (noMailto) {
Assert.ok(protoInfo.alwaysAskBeforeHandling); Assert.ok(protoInfo.alwaysAskBeforeHandling);
else } else {
Assert.ok(!protoInfo.alwaysAskBeforeHandling); Assert.ok(!protoInfo.alwaysAskBeforeHandling);
}
} else { } else {
Assert.equal(0, protoInfo.possibleApplicationHandlers.length); Assert.equal(0, protoInfo.possibleApplicationHandlers.length);
Assert.ok(protoInfo.alwaysAskBeforeHandling); Assert.ok(protoInfo.alwaysAskBeforeHandling);
@ -196,7 +202,6 @@ function run_test() {
Assert.ok(protoInfo.alwaysAskBeforeHandling); Assert.ok(protoInfo.alwaysAskBeforeHandling);
} }
//* *************************************************************************// //* *************************************************************************//
// Test Round-Trip Data Integrity // Test Round-Trip Data Integrity
@ -242,46 +247,63 @@ function run_test() {
// Make sure the handler service's remove method removes a handler record. // Make sure the handler service's remove method removes a handler record.
handlerSvc.remove(handlerInfo2); handlerSvc.remove(handlerInfo2);
let handlers = handlerSvc.enumerate(); let handlers = handlerSvc.enumerate();
while (handlers.hasMoreElements()) while (handlers.hasMoreElements()) {
Assert.notEqual(handlers.getNext().QueryInterface(Ci.nsIHandlerInfo).type, Assert.notEqual(
handlerInfo2.type); handlers.getNext().QueryInterface(Ci.nsIHandlerInfo).type,
handlerInfo2.type
);
}
// Make sure we can store and retrieve a handler info object with no preferred // Make sure we can store and retrieve a handler info object with no preferred
// handler. // handler.
var noPreferredHandlerInfo = var noPreferredHandlerInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/no-preferred-handler", null); "nonexistent/no-preferred-handler",
null
);
handlerSvc.store(noPreferredHandlerInfo); handlerSvc.store(noPreferredHandlerInfo);
noPreferredHandlerInfo = noPreferredHandlerInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/no-preferred-handler", null); "nonexistent/no-preferred-handler",
null
);
Assert.equal(noPreferredHandlerInfo.preferredApplicationHandler, null); Assert.equal(noPreferredHandlerInfo.preferredApplicationHandler, null);
// Make sure that the handler service removes an existing handler record // Make sure that the handler service removes an existing handler record
// if we store a handler info object with no preferred handler. // if we store a handler info object with no preferred handler.
var removePreferredHandlerInfo = var removePreferredHandlerInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/rem-preferred-handler", null); "nonexistent/rem-preferred-handler",
null
);
removePreferredHandlerInfo.preferredApplicationHandler = localHandler; removePreferredHandlerInfo.preferredApplicationHandler = localHandler;
handlerSvc.store(removePreferredHandlerInfo); handlerSvc.store(removePreferredHandlerInfo);
removePreferredHandlerInfo = removePreferredHandlerInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/rem-preferred-handler", null); "nonexistent/rem-preferred-handler",
null
);
removePreferredHandlerInfo.preferredApplicationHandler = null; removePreferredHandlerInfo.preferredApplicationHandler = null;
handlerSvc.store(removePreferredHandlerInfo); handlerSvc.store(removePreferredHandlerInfo);
removePreferredHandlerInfo = removePreferredHandlerInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/rem-preferred-handler", null); "nonexistent/rem-preferred-handler",
null
);
Assert.equal(removePreferredHandlerInfo.preferredApplicationHandler, null); Assert.equal(removePreferredHandlerInfo.preferredApplicationHandler, null);
// Make sure we can store and retrieve a handler info object with possible // Make sure we can store and retrieve a handler info object with possible
// handlers. We test both adding and removing handlers. // handlers. We test both adding and removing handlers.
// Get a handler info and make sure it has no possible handlers. // Get a handler info and make sure it has no possible handlers.
var possibleHandlersInfo = var possibleHandlersInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/possible-handlers", null); "nonexistent/possible-handlers",
null
);
Assert.equal(possibleHandlersInfo.possibleApplicationHandlers.length, 0); Assert.equal(possibleHandlersInfo.possibleApplicationHandlers.length, 0);
// Store and re-retrieve the handler and make sure it still has no possible // Store and re-retrieve the handler and make sure it still has no possible
// handlers. // handlers.
handlerSvc.store(possibleHandlersInfo); handlerSvc.store(possibleHandlersInfo);
possibleHandlersInfo = possibleHandlersInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/possible-handlers", null); "nonexistent/possible-handlers",
null
);
Assert.equal(possibleHandlersInfo.possibleApplicationHandlers.length, 0); Assert.equal(possibleHandlersInfo.possibleApplicationHandlers.length, 0);
// Add two handlers, store the object, re-retrieve it, and make sure it has // Add two handlers, store the object, re-retrieve it, and make sure it has
@ -289,26 +311,37 @@ function run_test() {
possibleHandlersInfo.possibleApplicationHandlers.appendElement(localHandler); possibleHandlersInfo.possibleApplicationHandlers.appendElement(localHandler);
possibleHandlersInfo.possibleApplicationHandlers.appendElement(webHandler); possibleHandlersInfo.possibleApplicationHandlers.appendElement(webHandler);
handlerSvc.store(possibleHandlersInfo); handlerSvc.store(possibleHandlersInfo);
possibleHandlersInfo = possibleHandlersInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/possible-handlers", null); "nonexistent/possible-handlers",
null
);
Assert.equal(possibleHandlersInfo.possibleApplicationHandlers.length, 2); Assert.equal(possibleHandlersInfo.possibleApplicationHandlers.length, 2);
// Figure out which is the local and which is the web handler and the index // Figure out which is the local and which is the web handler and the index
// in the array of the local handler, which is the one we're going to remove // in the array of the local handler, which is the one we're going to remove
// to test removal of a handler. // to test removal of a handler.
var handler1 = possibleHandlersInfo.possibleApplicationHandlers. var handler1 = possibleHandlersInfo.possibleApplicationHandlers.queryElementAt(
queryElementAt(0, Ci.nsIHandlerApp); 0,
var handler2 = possibleHandlersInfo.possibleApplicationHandlers. Ci.nsIHandlerApp
queryElementAt(1, Ci.nsIHandlerApp); );
var handler2 = possibleHandlersInfo.possibleApplicationHandlers.queryElementAt(
1,
Ci.nsIHandlerApp
);
var localPossibleHandler, webPossibleHandler, localIndex; var localPossibleHandler, webPossibleHandler, localIndex;
if (handler1 instanceof Ci.nsILocalHandlerApp) if (handler1 instanceof Ci.nsILocalHandlerApp) {
[localPossibleHandler, webPossibleHandler, localIndex] = [handler1, [localPossibleHandler, webPossibleHandler, localIndex] = [
handler2,
0];
else
[localPossibleHandler, webPossibleHandler, localIndex] = [handler2,
handler1, handler1,
1]; handler2,
0,
];
} else {
[localPossibleHandler, webPossibleHandler, localIndex] = [
handler2,
handler1,
1,
];
}
localPossibleHandler.QueryInterface(Ci.nsILocalHandlerApp); localPossibleHandler.QueryInterface(Ci.nsILocalHandlerApp);
webPossibleHandler.QueryInterface(Ci.nsIWebHandlerApp); webPossibleHandler.QueryInterface(Ci.nsIWebHandlerApp);
@ -322,20 +355,25 @@ function run_test() {
// it only has one handler. // it only has one handler.
possibleHandlersInfo.possibleApplicationHandlers.removeElementAt(localIndex); possibleHandlersInfo.possibleApplicationHandlers.removeElementAt(localIndex);
handlerSvc.store(possibleHandlersInfo); handlerSvc.store(possibleHandlersInfo);
possibleHandlersInfo = possibleHandlersInfo = mimeSvc.getFromTypeAndExtension(
mimeSvc.getFromTypeAndExtension("nonexistent/possible-handlers", null); "nonexistent/possible-handlers",
null
);
Assert.equal(possibleHandlersInfo.possibleApplicationHandlers.length, 1); Assert.equal(possibleHandlersInfo.possibleApplicationHandlers.length, 1);
// Make sure the handler is the one we didn't remove. // Make sure the handler is the one we didn't remove.
webPossibleHandler = possibleHandlersInfo.possibleApplicationHandlers. webPossibleHandler = possibleHandlersInfo.possibleApplicationHandlers.queryElementAt(
queryElementAt(0, Ci.nsIWebHandlerApp); 0,
Ci.nsIWebHandlerApp
);
Assert.equal(webPossibleHandler.name, webHandler.name); Assert.equal(webPossibleHandler.name, webHandler.name);
Assert.ok(webPossibleHandler.equals(webHandler)); Assert.ok(webPossibleHandler.equals(webHandler));
// //////////////////////////////////////////////////// // ////////////////////////////////////////////////////
// handler info command line parameters and equality // handler info command line parameters and equality
var localApp = Cc["@mozilla.org/uriloader/local-handler-app;1"]. var localApp = Cc[
createInstance(Ci.nsILocalHandlerApp); "@mozilla.org/uriloader/local-handler-app;1"
].createInstance(Ci.nsILocalHandlerApp);
var handlerApp = localApp.QueryInterface(Ci.nsIHandlerApp); var handlerApp = localApp.QueryInterface(Ci.nsIHandlerApp);
Assert.ok(handlerApp.equals(localApp)); Assert.ok(handlerApp.equals(localApp));
@ -353,8 +391,9 @@ function run_test() {
localApp.clearParameters(); localApp.clearParameters();
Assert.equal(0, localApp.parameterCount); Assert.equal(0, localApp.parameterCount);
var localApp2 = Cc["@mozilla.org/uriloader/local-handler-app;1"]. var localApp2 = Cc[
createInstance(Ci.nsILocalHandlerApp); "@mozilla.org/uriloader/local-handler-app;1"
].createInstance(Ci.nsILocalHandlerApp);
localApp2.executable = executable; localApp2.executable = executable;
@ -406,7 +445,6 @@ function run_test() {
var lolType = handlerSvc.getTypeFromExtension("lolcat"); var lolType = handlerSvc.getTypeFromExtension("lolcat");
Assert.equal(lolType, ""); Assert.equal(lolType, "");
// add a handler for the extension // add a handler for the extension
var lolHandler = mimeSvc.getFromTypeAndExtension("application/lolcat", null); var lolHandler = mimeSvc.getFromTypeAndExtension("application/lolcat", null);
@ -429,7 +467,10 @@ function run_test() {
if (mozinfo.os != "win" && mozinfo.os != "mac") { if (mozinfo.os != "win" && mozinfo.os != "mac") {
env.set("PERSONAL_MAILCAP", do_get_file("mailcap").path); env.set("PERSONAL_MAILCAP", do_get_file("mailcap").path);
handlerInfo = mimeSvc.getFromTypeAndExtension("text/plain", null); handlerInfo = mimeSvc.getFromTypeAndExtension("text/plain", null);
Assert.equal(handlerInfo.preferredAction, Ci.nsIHandlerInfo.useSystemDefault); Assert.equal(
handlerInfo.preferredAction,
Ci.nsIHandlerInfo.useSystemDefault
);
Assert.equal(handlerInfo.defaultDescription, "sed"); Assert.equal(handlerInfo.defaultDescription, "sed");
} }
} }

View file

@ -6,8 +6,9 @@
*/ */
// Set up an nsIWebHandlerApp instance that can be used in multiple tests. // Set up an nsIWebHandlerApp instance that can be used in multiple tests.
let webHandlerApp = Cc["@mozilla.org/uriloader/web-handler-app;1"] let webHandlerApp = Cc[
.createInstance(Ci.nsIWebHandlerApp); "@mozilla.org/uriloader/web-handler-app;1"
].createInstance(Ci.nsIWebHandlerApp);
webHandlerApp.name = "Web Handler"; webHandlerApp.name = "Web Handler";
webHandlerApp.uriTemplate = "https://www.example.com/?url=%s"; webHandlerApp.uriTemplate = "https://www.example.com/?url=%s";
let expectedWebHandlerApp = { let expectedWebHandlerApp = {
@ -18,8 +19,9 @@ let expectedWebHandlerApp = {
// Set up an nsILocalHandlerApp instance that can be used in multiple tests. The // Set up an nsILocalHandlerApp instance that can be used in multiple tests. The
// executable should exist, but it doesn't need to point to an actual file, so // executable should exist, but it doesn't need to point to an actual file, so
// we simply initialize it to the path of an existing directory. // we simply initialize it to the path of an existing directory.
let localHandlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"] let localHandlerApp = Cc[
.createInstance(Ci.nsILocalHandlerApp); "@mozilla.org/uriloader/local-handler-app;1"
].createInstance(Ci.nsILocalHandlerApp);
localHandlerApp.name = "Local Handler"; localHandlerApp.name = "Local Handler";
localHandlerApp.executable = FileUtils.getFile("TmpD", []); localHandlerApp.executable = FileUtils.getFile("TmpD", []);
let expectedLocalHandlerApp = { let expectedLocalHandlerApp = {
@ -58,9 +60,7 @@ function assertAllHandlerInfosMatchTestData() {
type: "example/type.handleinternally", type: "example/type.handleinternally",
preferredAction: Ci.nsIHandlerInfo.handleInternally, preferredAction: Ci.nsIHandlerInfo.handleInternally,
alwaysAskBeforeHandling: false, alwaysAskBeforeHandling: false,
fileExtensions: [ fileExtensions: ["example_one"],
"example_one",
],
}); });
HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), { HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), {
@ -71,14 +71,13 @@ function assertAllHandlerInfosMatchTestData() {
name: "Example Default Handler", name: "Example Default Handler",
uriTemplate: "https://www.example.com/?url=%s", uriTemplate: "https://www.example.com/?url=%s",
}, },
possibleApplicationHandlers: [{ possibleApplicationHandlers: [
{
name: "Example Default Handler", name: "Example Default Handler",
uriTemplate: "https://www.example.com/?url=%s", uriTemplate: "https://www.example.com/?url=%s",
}], },
fileExtensions: [
"example_two",
"example_three",
], ],
fileExtensions: ["example_two", "example_three"],
}); });
HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), { HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), {
@ -89,30 +88,33 @@ function assertAllHandlerInfosMatchTestData() {
name: "Example Default Handler", name: "Example Default Handler",
uriTemplate: "https://www.example.com/?url=%s", uriTemplate: "https://www.example.com/?url=%s",
}, },
possibleApplicationHandlers: [{ possibleApplicationHandlers: [
{
name: "Example Default Handler", name: "Example Default Handler",
uriTemplate: "https://www.example.com/?url=%s", uriTemplate: "https://www.example.com/?url=%s",
}, { },
{
name: "Example Possible Handler One", name: "Example Possible Handler One",
uriTemplate: "http://www.example.com/?id=1&url=%s", uriTemplate: "http://www.example.com/?id=1&url=%s",
}, { },
{
name: "Example Possible Handler Two", name: "Example Possible Handler Two",
uriTemplate: "http://www.example.com/?id=2&url=%s", uriTemplate: "http://www.example.com/?id=2&url=%s",
}], },
fileExtensions: [
"example_two",
"example_three",
], ],
fileExtensions: ["example_two", "example_three"],
}); });
HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), { HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), {
type: "example/type.usesystemdefault", type: "example/type.usesystemdefault",
preferredAction: Ci.nsIHandlerInfo.useSystemDefault, preferredAction: Ci.nsIHandlerInfo.useSystemDefault,
alwaysAskBeforeHandling: false, alwaysAskBeforeHandling: false,
possibleApplicationHandlers: [{ possibleApplicationHandlers: [
{
name: "Example Possible Handler", name: "Example Possible Handler",
uriTemplate: "http://www.example.com/?url=%s", uriTemplate: "http://www.example.com/?url=%s",
}], },
],
}); });
HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), { HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), {
@ -123,26 +125,32 @@ function assertAllHandlerInfosMatchTestData() {
name: "Example Default Handler", name: "Example Default Handler",
uriTemplate: "https://www.example.com/?url=%s", uriTemplate: "https://www.example.com/?url=%s",
}, },
possibleApplicationHandlers: [{ possibleApplicationHandlers: [
{
name: "Example Default Handler", name: "Example Default Handler",
uriTemplate: "https://www.example.com/?url=%s", uriTemplate: "https://www.example.com/?url=%s",
}, { },
{
name: "Example Possible Handler One", name: "Example Possible Handler One",
uriTemplate: "http://www.example.com/?id=1&url=%s", uriTemplate: "http://www.example.com/?id=1&url=%s",
}, { },
{
name: "Example Possible Handler Two", name: "Example Possible Handler Two",
uriTemplate: "http://www.example.com/?id=2&url=%s", uriTemplate: "http://www.example.com/?id=2&url=%s",
}], },
],
}); });
HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), { HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), {
type: "examplescheme.usesystemdefault", type: "examplescheme.usesystemdefault",
preferredAction: Ci.nsIHandlerInfo.useSystemDefault, preferredAction: Ci.nsIHandlerInfo.useSystemDefault,
alwaysAskBeforeHandling: false, alwaysAskBeforeHandling: false,
possibleApplicationHandlers: [{ possibleApplicationHandlers: [
{
name: "Example Possible Handler", name: "Example Possible Handler",
uriTemplate: "http://www.example.com/?url=%s", uriTemplate: "http://www.example.com/?url=%s",
}], },
],
}); });
Assert.equal(handlerInfos.length, 0); Assert.equal(handlerInfos.length, 0);
@ -181,8 +189,10 @@ add_task(async function test_store_fillHandlerInfo_predefined() {
*/ */
add_task(async function test_store_remove_exists() { add_task(async function test_store_remove_exists() {
// Test both MIME types and protocols. // Test both MIME types and protocols.
for (let type of ["example/type.usehelperapp", for (let type of [
"examplescheme.usehelperapp"]) { "example/type.usehelperapp",
"examplescheme.usehelperapp",
]) {
// Create new nsIHandlerInfo instances before loading the test data. // Create new nsIHandlerInfo instances before loading the test data.
await deleteHandlerStore(); await deleteHandlerStore();
let handlerInfoPresent = HandlerServiceTestUtils.getHandlerInfo(type); let handlerInfoPresent = HandlerServiceTestUtils.getHandlerInfo(type);
@ -207,7 +217,8 @@ add_task(async function test_store_remove_exists() {
Assert.throws( Assert.throws(
() => gHandlerService.fillHandlerInfo(handlerInfoPresent, ""), () => gHandlerService.fillHandlerInfo(handlerInfoPresent, ""),
ex => ex.result == Cr.NS_ERROR_NOT_AVAILABLE); ex => ex.result == Cr.NS_ERROR_NOT_AVAILABLE
);
let actualHandlerInfo = HandlerServiceTestUtils.getHandlerInfo(type + "2"); let actualHandlerInfo = HandlerServiceTestUtils.getHandlerInfo(type + "2");
HandlerServiceTestUtils.assertHandlerInfoMatches(actualHandlerInfo, { HandlerServiceTestUtils.assertHandlerInfoMatches(actualHandlerInfo, {
@ -247,8 +258,9 @@ add_task(async function test_store_localHandlerApp_missing() {
return; return;
} }
let missingHandlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"] let missingHandlerApp = Cc[
.createInstance(Ci.nsILocalHandlerApp); "@mozilla.org/uriloader/local-handler-app;1"
].createInstance(Ci.nsILocalHandlerApp);
missingHandlerApp.name = "Non-existing Handler"; missingHandlerApp.name = "Non-existing Handler";
missingHandlerApp.executable = FileUtils.getFile("TmpD", ["nonexisting"]); missingHandlerApp.executable = FileUtils.getFile("TmpD", ["nonexisting"]);
@ -281,8 +293,9 @@ add_task(async function test_store_dBusHandlerApp() {
} }
// Set up an nsIDBusHandlerApp instance for testing. // Set up an nsIDBusHandlerApp instance for testing.
let dBusHandlerApp = Cc["@mozilla.org/uriloader/dbus-handler-app;1"] let dBusHandlerApp = Cc[
.createInstance(Ci.nsIDBusHandlerApp); "@mozilla.org/uriloader/dbus-handler-app;1"
].createInstance(Ci.nsIDBusHandlerApp);
dBusHandlerApp.name = "DBus Handler"; dBusHandlerApp.name = "DBus Handler";
dBusHandlerApp.service = "test.method.server"; dBusHandlerApp.service = "test.method.server";
dBusHandlerApp.method = "Method"; dBusHandlerApp.method = "Method";
@ -320,7 +333,8 @@ add_task(async function test_store_dBusHandlerApp() {
* "preferredApplicationHandler" and no "possibleApplicationHandlers", but the * "preferredApplicationHandler" and no "possibleApplicationHandlers", but the
* former is always included in the latter list when reloading. * former is always included in the latter list when reloading.
*/ */
add_task(async function test_store_possibleApplicationHandlers_includes_preferred() { add_task(
async function test_store_possibleApplicationHandlers_includes_preferred() {
await deleteHandlerStore(); await deleteHandlerStore();
let handlerInfo = getKnownHandlerInfo("example/new"); let handlerInfo = getKnownHandlerInfo("example/new");
@ -329,7 +343,9 @@ add_task(async function test_store_possibleApplicationHandlers_includes_preferre
await unloadHandlerStore(); await unloadHandlerStore();
let actualHandlerInfo = HandlerServiceTestUtils.getHandlerInfo("example/new"); let actualHandlerInfo = HandlerServiceTestUtils.getHandlerInfo(
"example/new"
);
HandlerServiceTestUtils.assertHandlerInfoMatches(actualHandlerInfo, { HandlerServiceTestUtils.assertHandlerInfoMatches(actualHandlerInfo, {
type: "example/new", type: "example/new",
preferredAction: Ci.nsIHandlerInfo.saveToDisk, preferredAction: Ci.nsIHandlerInfo.saveToDisk,
@ -337,7 +353,8 @@ add_task(async function test_store_possibleApplicationHandlers_includes_preferre
preferredApplicationHandler: expectedLocalHandlerApp, preferredApplicationHandler: expectedLocalHandlerApp,
possibleApplicationHandlers: [expectedLocalHandlerApp], possibleApplicationHandlers: [expectedLocalHandlerApp],
}); });
}); }
);
/** /**
* Tests that it is possible to save an nsIHandlerInfo instance with a * Tests that it is possible to save an nsIHandlerInfo instance with a
@ -345,7 +362,8 @@ add_task(async function test_store_possibleApplicationHandlers_includes_preferre
* "possibleApplicationHandlers", but the former is always included as the first * "possibleApplicationHandlers", but the former is always included as the first
* element of the latter list when reloading. * element of the latter list when reloading.
*/ */
add_task(async function test_store_possibleApplicationHandlers_preferred_first() { add_task(
async function test_store_possibleApplicationHandlers_preferred_first() {
await deleteHandlerStore(); await deleteHandlerStore();
let handlerInfo = getKnownHandlerInfo("example/new"); let handlerInfo = getKnownHandlerInfo("example/new");
@ -357,7 +375,9 @@ add_task(async function test_store_possibleApplicationHandlers_preferred_first()
await unloadHandlerStore(); await unloadHandlerStore();
let actualHandlerInfo = HandlerServiceTestUtils.getHandlerInfo("example/new"); let actualHandlerInfo = HandlerServiceTestUtils.getHandlerInfo(
"example/new"
);
HandlerServiceTestUtils.assertHandlerInfoMatches(actualHandlerInfo, { HandlerServiceTestUtils.assertHandlerInfoMatches(actualHandlerInfo, {
type: "example/new", type: "example/new",
preferredAction: Ci.nsIHandlerInfo.saveToDisk, preferredAction: Ci.nsIHandlerInfo.saveToDisk,
@ -368,7 +388,8 @@ add_task(async function test_store_possibleApplicationHandlers_preferred_first()
expectedLocalHandlerApp, expectedLocalHandlerApp,
], ],
}); });
}); }
);
/** /**
* Tests that it is possible to save an nsIHandlerInfo instance with an * Tests that it is possible to save an nsIHandlerInfo instance with an
@ -389,10 +410,7 @@ add_task(async function test_store_fileExtensions_lowercase() {
type: "example/new", type: "example/new",
preferredAction: Ci.nsIHandlerInfo.saveToDisk, preferredAction: Ci.nsIHandlerInfo.saveToDisk,
alwaysAskBeforeHandling: false, alwaysAskBeforeHandling: false,
fileExtensions: [ fileExtensions: ["extension_test1", "extension_test2"],
"extension_test1",
"extension_test2",
],
}); });
}); });
@ -427,10 +445,7 @@ add_task(async function test_store_no_duplicates() {
expectedWebHandlerApp, expectedWebHandlerApp,
expectedLocalHandlerApp, expectedLocalHandlerApp,
], ],
fileExtensions: [ fileExtensions: ["extension_test1", "extension_test2"],
"extension_test1",
"extension_test2",
],
}); });
}); });
@ -446,8 +461,9 @@ add_task(async function test_store_deletes_properties_except_extensions() {
// Prepare an nsIHandlerInfo instance with all the properties set to values // Prepare an nsIHandlerInfo instance with all the properties set to values
// that will result in deletions. The preferredAction is also set to a defined // that will result in deletions. The preferredAction is also set to a defined
// value so we can more easily verify it later. // value so we can more easily verify it later.
let handlerInfo = let handlerInfo = HandlerServiceTestUtils.getBlankHandlerInfo(
HandlerServiceTestUtils.getBlankHandlerInfo("example/type.savetodisk"); "example/type.savetodisk"
);
handlerInfo.preferredAction = Ci.nsIHandlerInfo.saveToDisk; handlerInfo.preferredAction = Ci.nsIHandlerInfo.saveToDisk;
handlerInfo.alwaysAskBeforeHandling = false; handlerInfo.alwaysAskBeforeHandling = false;
@ -458,16 +474,14 @@ add_task(async function test_store_deletes_properties_except_extensions() {
// Now we can reload the data and verify that no extra values have been kept. // Now we can reload the data and verify that no extra values have been kept.
await unloadHandlerStore(); await unloadHandlerStore();
let actualHandlerInfo = let actualHandlerInfo = HandlerServiceTestUtils.getHandlerInfo(
HandlerServiceTestUtils.getHandlerInfo("example/type.savetodisk"); "example/type.savetodisk"
);
HandlerServiceTestUtils.assertHandlerInfoMatches(actualHandlerInfo, { HandlerServiceTestUtils.assertHandlerInfoMatches(actualHandlerInfo, {
type: "example/type.savetodisk", type: "example/type.savetodisk",
preferredAction: Ci.nsIHandlerInfo.saveToDisk, preferredAction: Ci.nsIHandlerInfo.saveToDisk,
alwaysAskBeforeHandling: false, alwaysAskBeforeHandling: false,
fileExtensions: [ fileExtensions: ["example_two", "example_three"],
"example_two",
"example_three",
],
}); });
}); });
@ -476,8 +490,10 @@ add_task(async function test_store_deletes_properties_except_extensions() {
*/ */
add_task(async function test_fillHandlerInfo_overrideType() { add_task(async function test_fillHandlerInfo_overrideType() {
// Test both MIME types and protocols. // Test both MIME types and protocols.
for (let type of ["example/type.usesystemdefault", for (let type of [
"examplescheme.usesystemdefault"]) { "example/type.usesystemdefault",
"examplescheme.usesystemdefault",
]) {
await deleteHandlerStore(); await deleteHandlerStore();
// Create new nsIHandlerInfo instances before loading the test data. // Create new nsIHandlerInfo instances before loading the test data.
@ -491,10 +507,12 @@ add_task(async function test_fillHandlerInfo_overrideType() {
type: type + "2", type: type + "2",
preferredAction: Ci.nsIHandlerInfo.useSystemDefault, preferredAction: Ci.nsIHandlerInfo.useSystemDefault,
alwaysAskBeforeHandling: false, alwaysAskBeforeHandling: false,
possibleApplicationHandlers: [{ possibleApplicationHandlers: [
{
name: "Example Possible Handler", name: "Example Possible Handler",
uriTemplate: "http://www.example.com/?url=%s", uriTemplate: "http://www.example.com/?url=%s",
}], },
],
}); });
} }
}); });
@ -507,10 +525,14 @@ add_task(async function test_getTypeFromExtension() {
Assert.equal(gHandlerService.getTypeFromExtension(""), ""); Assert.equal(gHandlerService.getTypeFromExtension(""), "");
Assert.equal(gHandlerService.getTypeFromExtension("example_unknown"), ""); Assert.equal(gHandlerService.getTypeFromExtension("example_unknown"), "");
Assert.equal(gHandlerService.getTypeFromExtension("example_one"), Assert.equal(
"example/type.handleinternally"); gHandlerService.getTypeFromExtension("example_one"),
Assert.equal(gHandlerService.getTypeFromExtension("EXAMPLE_one"), "example/type.handleinternally"
"example/type.handleinternally"); );
Assert.equal(
gHandlerService.getTypeFromExtension("EXAMPLE_one"),
"example/type.handleinternally"
);
}); });
/** /**
@ -524,23 +546,28 @@ function assertAllHandlerInfosMatchDefaultHandlers() {
HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), { HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), {
type, type,
preferredActionOSDependent: true, preferredActionOSDependent: true,
possibleApplicationHandlers: [{ possibleApplicationHandlers: [
{
name: "Mibbit", name: "Mibbit",
uriTemplate: "https://www.mibbit.com/?url=%s", uriTemplate: "https://www.mibbit.com/?url=%s",
}], },
],
}); });
} }
HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), { HandlerServiceTestUtils.assertHandlerInfoMatches(handlerInfos.shift(), {
type: "mailto", type: "mailto",
preferredActionOSDependent: true, preferredActionOSDependent: true,
possibleApplicationHandlers: [{ possibleApplicationHandlers: [
{
name: "Yahoo! Mail", name: "Yahoo! Mail",
uriTemplate: "https://compose.mail.yahoo.com/?To=%s", uriTemplate: "https://compose.mail.yahoo.com/?To=%s",
}, { },
{
name: "Gmail", name: "Gmail",
uriTemplate: "https://mail.google.com/mail/?extsrc=mailto&url=%s", uriTemplate: "https://mail.google.com/mail/?extsrc=mailto&url=%s",
}], },
],
}); });
Assert.equal(handlerInfos.length, 0); Assert.equal(handlerInfos.length, 0);
@ -550,7 +577,9 @@ function assertAllHandlerInfosMatchDefaultHandlers() {
* Tests the default protocol handlers imported from the locale-specific data. * Tests the default protocol handlers imported from the locale-specific data.
*/ */
add_task(async function test_default_protocol_handlers() { add_task(async function test_default_protocol_handlers() {
if (!Services.prefs.getPrefType("gecko.handlerService.defaultHandlersVersion")) { if (
!Services.prefs.getPrefType("gecko.handlerService.defaultHandlersVersion")
) {
info("This platform or locale does not have default handlers."); info("This platform or locale does not have default handlers.");
return; return;
} }
@ -566,7 +595,9 @@ add_task(async function test_default_protocol_handlers() {
* locale-specific data if they already exist. * locale-specific data if they already exist.
*/ */
add_task(async function test_default_protocol_handlers_no_duplicates() { add_task(async function test_default_protocol_handlers_no_duplicates() {
if (!Services.prefs.getPrefType("gecko.handlerService.defaultHandlersVersion")) { if (
!Services.prefs.getPrefType("gecko.handlerService.defaultHandlersVersion")
) {
info("This platform or locale does not have default handlers."); info("This platform or locale does not have default handlers.");
return; return;
} }
@ -579,11 +610,15 @@ add_task(async function test_default_protocol_handlers_no_duplicates() {
gHandlerService.remove(ircHandlerInfo); gHandlerService.remove(ircHandlerInfo);
let originalDefaultHandlersVersion = Services.prefs.getComplexValue( let originalDefaultHandlersVersion = Services.prefs.getComplexValue(
"gecko.handlerService.defaultHandlersVersion", Ci.nsIPrefLocalizedString); "gecko.handlerService.defaultHandlersVersion",
Ci.nsIPrefLocalizedString
);
// Set the preference to an arbitrarily high number to force injecting again. // Set the preference to an arbitrarily high number to force injecting again.
Services.prefs.setStringPref("gecko.handlerService.defaultHandlersVersion", Services.prefs.setStringPref(
"999"); "gecko.handlerService.defaultHandlersVersion",
"999"
);
await unloadHandlerStore(); await unloadHandlerStore();
@ -593,8 +628,10 @@ add_task(async function test_default_protocol_handlers_no_duplicates() {
// There should be no duplicate handlers in the protocols. // There should be no duplicate handlers in the protocols.
await assertAllHandlerInfosMatchDefaultHandlers(); await assertAllHandlerInfosMatchDefaultHandlers();
Services.prefs.setStringPref("gecko.handlerService.defaultHandlersVersion", Services.prefs.setStringPref(
originalDefaultHandlersVersion); "gecko.handlerService.defaultHandlersVersion",
originalDefaultHandlersVersion
);
}); });
/** /**
@ -604,16 +641,19 @@ add_task(async function test_default_protocol_handlers_no_duplicates() {
add_task(async function test_store_keeps_unknown_properties() { add_task(async function test_store_keeps_unknown_properties() {
// Create a new nsIHandlerInfo instance before loading the test data. // Create a new nsIHandlerInfo instance before loading the test data.
await deleteHandlerStore(); await deleteHandlerStore();
let handlerInfo = let handlerInfo = HandlerServiceTestUtils.getHandlerInfo(
HandlerServiceTestUtils.getHandlerInfo("example/type.handleinternally"); "example/type.handleinternally"
);
await copyTestDataToHandlerStore(); await copyTestDataToHandlerStore();
gHandlerService.store(handlerInfo); gHandlerService.store(handlerInfo);
await unloadHandlerStore(); await unloadHandlerStore();
let data = JSON.parse(new TextDecoder().decode(await OS.File.read(jsonPath))); let data = JSON.parse(new TextDecoder().decode(await OS.File.read(jsonPath)));
Assert.equal(data.mimeTypes["example/type.handleinternally"].unknownProperty, Assert.equal(
"preserved"); data.mimeTypes["example/type.handleinternally"].unknownProperty,
"preserved"
);
}); });
/** /**
@ -665,7 +705,10 @@ add_task(async function test_store_gioHandlerApp() {
// Create dummy exec file that following won't fail because file not found error // Create dummy exec file that following won't fail because file not found error
let dummyHandlerFile = FileUtils.getFile("TmpD", ["dummyHandler"]); let dummyHandlerFile = FileUtils.getFile("TmpD", ["dummyHandler"]);
dummyHandlerFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("777", 8)); dummyHandlerFile.createUnique(
Ci.nsIFile.NORMAL_FILE_TYPE,
parseInt("777", 8)
);
// Set up an nsIGIOMimeApp instance for testing. // Set up an nsIGIOMimeApp instance for testing.
let handlerApp = Cc["@mozilla.org/gio-service;1"] let handlerApp = Cc["@mozilla.org/gio-service;1"]

View file

@ -20,8 +20,13 @@ function checkFile() {
if (!tempFile.exists()) { if (!tempFile.exists()) {
if (gCheckExistsAttempts >= kMaxCheckExistAttempts) { if (gCheckExistsAttempts >= kMaxCheckExistAttempts) {
do_throw("Expected File " + tempFile.path + " does not exist after " + do_throw(
kMaxCheckExistAttempts + " seconds"); "Expected File " +
tempFile.path +
" does not exist after " +
kMaxCheckExistAttempts +
" seconds"
);
} else { } else {
++gCheckExistsAttempts; ++gCheckExistsAttempts;
// Wait a bit longer then try again // Wait a bit longer then try again
@ -31,12 +36,12 @@ function checkFile() {
} }
// Now read it // Now read it
var fstream = var fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
Cc["@mozilla.org/network/file-input-stream;1"] Ci.nsIFileInputStream
.createInstance(Ci.nsIFileInputStream); );
var sstream = var sstream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(
Cc["@mozilla.org/scriptableinputstream;1"] Ci.nsIScriptableInputStream
.createInstance(Ci.nsIScriptableInputStream); );
fstream.init(tempFile, -1, 0, 0); fstream.init(tempFile, -1, 0, 0);
sstream.init(fstream); sstream.init(fstream);
@ -55,8 +60,9 @@ function checkFile() {
// find a way around it. // find a way around it.
// Additionally the lack of OS detection in xpcshell tests sucks, so we'll // Additionally the lack of OS detection in xpcshell tests sucks, so we'll
// have to check for the argument mac gives us. // have to check for the argument mac gives us.
if (data.substring(0, 7) != "-psn_0_") if (data.substring(0, 7) != "-psn_0_") {
Assert.equal(data, kExpectedURI); Assert.equal(data, kExpectedURI);
}
do_test_finished(); do_test_finished();
} }
@ -71,9 +77,9 @@ function run_test() {
var ioService = Services.io; var ioService = Services.io;
// set up the local handler object // set up the local handler object
var localHandler = var localHandler = Cc[
Cc["@mozilla.org/uriloader/local-handler-app;1"] "@mozilla.org/uriloader/local-handler-app;1"
.createInstance(Ci.nsILocalHandlerApp); ].createInstance(Ci.nsILocalHandlerApp);
localHandler.name = "Test Local Handler App"; localHandler.name = "Test Local Handler App";
// WriteArgument will just dump its arguments to a file for us. // WriteArgument will just dump its arguments to a file for us.
@ -84,17 +90,18 @@ function run_test() {
if (!exe.exists()) { if (!exe.exists()) {
// Maybe we are on windows // Maybe we are on windows
exe.leafName = "WriteArgument.exe"; exe.leafName = "WriteArgument.exe";
if (!exe.exists()) if (!exe.exists()) {
do_throw("Could not locate the WriteArgument tests executable\n"); do_throw("Could not locate the WriteArgument tests executable\n");
} }
}
var outFile = tempDir.clone(); var outFile = tempDir.clone();
outFile.append(kOutputFile); outFile.append(kOutputFile);
// Set an environment variable for WriteArgument to pick up // Set an environment variable for WriteArgument to pick up
var envSvc = var envSvc = Cc["@mozilla.org/process/environment;1"].getService(
Cc["@mozilla.org/process/environment;1"] Ci.nsIEnvironment
.getService(Ci.nsIEnvironment); );
// The Write Argument file needs to know where its libraries are, so // The Write Argument file needs to know where its libraries are, so
// just force the path variable // just force the path variable