Backed out 12 changesets (bug 1685801) for causing failures on browser_fission_maxOrigins.js. CLOSED TREE

Backed out changeset 0d7153110519 (bug 1685801)
Backed out changeset 5175062925c7 (bug 1685801)
Backed out changeset 2c1250e786f0 (bug 1685801)
Backed out changeset 0ce3c773ba74 (bug 1685801)
Backed out changeset 9d51c6e24dee (bug 1685801)
Backed out changeset 3f4dc6349441 (bug 1685801)
Backed out changeset a80de9abb9f8 (bug 1685801)
Backed out changeset 30786893a5e7 (bug 1685801)
Backed out changeset 8007b12d6e32 (bug 1685801)
Backed out changeset fa814f4b7125 (bug 1685801)
Backed out changeset 14e4e47ee99f (bug 1685801)
Backed out changeset d9f1feba9454 (bug 1685801)
This commit is contained in:
Butkovits Atila 2021-01-28 07:15:59 +02:00
parent b09444da06
commit 7decdccbdc
53 changed files with 1091 additions and 1052 deletions

View File

@ -7,6 +7,11 @@ var EXPORTED_SYMBOLS = ["ClickHandlerChild"];
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(
this,
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"PrivateBrowsingUtils",
@ -97,10 +102,7 @@ class ClickHandlerChild extends JSWindowActorChild {
if (href) {
try {
Services.scriptSecurityManager.checkLoadURIStrWithPrincipal(
principal,
href
);
BrowserUtils.urlSecurityCheck(href, principal);
} catch (e) {
return;
}

View File

@ -17,11 +17,11 @@ XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]);
XPCOMUtils.defineLazyModuleGetters(this, {
E10SUtils: "resource://gre/modules/E10SUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
SpellCheckHelper: "resource://gre/modules/InlineSpellChecker.jsm",
LoginManagerChild: "resource://gre/modules/LoginManagerChild.jsm",
WebNavigationFrames: "resource://gre/modules/WebNavigationFrames.jsm",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
SelectionUtils: "resource://gre/modules/SelectionUtils.jsm",
InlineSpellCheckerContent:
"resource://gre/modules/InlineSpellCheckerContent.jsm",
ContentDOMReference: "resource://gre/modules/ContentDOMReference.jsm",
@ -237,9 +237,9 @@ class ContextMenuChild extends JSWindowActorChild {
if (!disable) {
try {
Services.scriptSecurityManager.checkLoadURIWithPrincipal(
target.ownerDocument.nodePrincipal,
target.currentURI
BrowserUtils.urlSecurityCheck(
target.currentURI.spec,
target.ownerDocument.nodePrincipal
);
let canvas = this.document.createElement("canvas");
canvas.width = target.naturalWidth;
@ -614,7 +614,7 @@ class ContextMenuChild extends JSWindowActorChild {
} catch (e) {}
}
let selectionInfo = SelectionUtils.getSelectionDetails(this.contentWindow);
let selectionInfo = BrowserUtils.getSelectionDetails(this.contentWindow);
let loadContext = this.docShell.QueryInterface(Ci.nsILoadContext);
let userContextId = loadContext.originAttributes.userContextId;

View File

@ -14,8 +14,8 @@ const { XPCOMUtils } = ChromeUtils.import(
ChromeUtils.defineModuleGetter(
this,
"BrowserUIUtils",
"resource:///modules/BrowserUIUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
@ -73,7 +73,7 @@ class EncryptedMediaParent extends JSWindowActorParent {
let link = document.createXULElement("label", { is: "text-link" });
link.setAttribute("href", baseURL + "drm-content");
link.textContent = text;
return BrowserUIUtils.getLocalizedFragment(document, mainMessage, link);
return BrowserUtils.getLocalizedFragment(document, mainMessage, link);
}
getMessageWithBrandName(aNotificationId) {

View File

@ -10,8 +10,8 @@
var EXPORTED_SYMBOLS = ["FormValidationChild"];
const { LayoutUtils } = ChromeUtils.import(
"resource://gre/modules/LayoutUtils.jsm"
const { BrowserUtils } = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
@ -154,7 +154,7 @@ class FormValidationChild extends JSWindowActorChild {
panelData.message = this._validationMessage;
panelData.screenRect = LayoutUtils.getElementBoundingScreenRect(aElement);
panelData.screenRect = BrowserUtils.getElementBoundingScreenRect(aElement);
// We want to show the popup at the middle of checkbox and radio buttons
// and where the content begin for the other elements.

View File

@ -9,6 +9,9 @@ var EXPORTED_SYMBOLS = ["PluginChild"];
const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
const { BrowserUtils } = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
@ -41,37 +44,6 @@ const OVERLAY_DISPLAY = {
// definition.
const kSubmitMsg = "PluginParent:NPAPIPluginCrashReportSubmitted";
/**
* Map the plugin's name to a filtered version more suitable for UI.
*
* N.B. This should be completely dead code at this point.
*
* @param aName The full-length name string of the plugin.
* @return the simplified name string.
*/
function makeNicePluginName(aName) {
if (aName == "Shockwave Flash") {
return "Adobe Flash";
}
// Regex checks if aName begins with "Java" + non-letter char
if (/^Java\W/.test(aName)) {
return "Java";
}
// Clean up the plugin name by stripping off parenthetical clauses,
// trailing version numbers or "plugin".
// EG, "Foo Bar (Linux) Plugin 1.23_02" --> "Foo Bar"
// Do this by first stripping the numbers, etc. off the end, and then
// removing "Plugin" (and then trimming to get rid of any whitespace).
// (Otherwise, something like "Java(TM) Plug-in 1.7.0_07" gets mangled)
let newName = aName
.replace(/\(.*?\)/g, "")
.replace(/[\s\d\.\-\_\(\)]+$/, "")
.replace(/\bplug-?in\b/i, "")
.trim();
return newName;
}
class PluginChild extends JSWindowActorChild {
constructor() {
super();
@ -167,7 +139,7 @@ class PluginChild extends JSWindowActorChild {
_getPluginInfo(pluginElement) {
if (this.isKnownPlugin(pluginElement)) {
let pluginTag = gPluginHost.getPluginTagForType(pluginElement.actualType);
let pluginName = makeNicePluginName(pluginTag.name);
let pluginName = BrowserUtils.makeNicePluginName(pluginTag.name);
let fallbackType = pluginElement.defaultFallbackType;
let permissionString = gPluginHost.getPermissionStringForType(
pluginElement.actualType
@ -197,7 +169,7 @@ class PluginChild extends JSWindowActorChild {
// nsIObjectLoadingContent to check.
let fallbackType = Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY;
if (pluginTag) {
let pluginName = makeNicePluginName(pluginTag.name);
let pluginName = BrowserUtils.makeNicePluginName(pluginTag.name);
let permissionString = gPluginHost.getPermissionStringForTag(pluginTag);
return { pluginTag, pluginName, permissionString, fallbackType };
}

View File

@ -22,6 +22,11 @@ XPCOMUtils.defineLazyServiceGetter(
"nsIPluginHost"
);
ChromeUtils.defineModuleGetter(
this,
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"CrashSubmit",
@ -42,37 +47,6 @@ const {
PLUGIN_CLICK_TO_PLAY_QUIET,
} = Ci.nsIObjectLoadingContent;
/**
* Map the plugin's name to a filtered version more suitable for UI.
*
* N.B. This should be completely dead code at this point.
*
* @param aName The full-length name string of the plugin.
* @return the simplified name string.
*/
function makeNicePluginName(aName) {
if (aName == "Shockwave Flash") {
return "Adobe Flash";
}
// Regex checks if aName begins with "Java" + non-letter char
if (/^Java\W/.test(aName)) {
return "Java";
}
// Clean up the plugin name by stripping off parenthetical clauses,
// trailing version numbers or "plugin".
// EG, "Foo Bar (Linux) Plugin 1.23_02" --> "Foo Bar"
// Do this by first stripping the numbers, etc. off the end, and then
// removing "Plugin" (and then trimming to get rid of any whitespace).
// (Otherwise, something like "Java(TM) Plug-in 1.7.0_07" gets mangled)
let newName = aName
.replace(/\(.*?\)/g, "")
.replace(/[\s\d\.\-\_\(\)]+$/, "")
.replace(/\bplug-?in\b/i, "")
.trim();
return newName;
}
const PluginManager = {
_initialized: false,
@ -155,7 +129,7 @@ const PluginManager = {
let runID = propertyBag.getPropertyAsUint32("runID");
let uglyPluginName = propertyBag.getPropertyAsAString("pluginName");
let pluginName = makeNicePluginName(uglyPluginName);
let pluginName = BrowserUtils.makeNicePluginName(uglyPluginName);
let pluginDumpID = propertyBag.getPropertyAsAString("pluginDumpID");
let state;

View File

@ -631,7 +631,7 @@ var gXPInstallObserver = {
);
let b = doc.createElementNS("http://www.w3.org/1999/xhtml", "b");
b.textContent = options.name;
let fragment = BrowserUIUtils.getLocalizedFragment(doc, text, b);
let fragment = BrowserUtils.getLocalizedFragment(doc, text, b);
message.appendChild(fragment);
} else {
message.textContent = gNavigatorBundle.getString(

View File

@ -2188,7 +2188,7 @@ var BookmarkingUI = {
) {
let isBookmarked = this._itemGuids.size > 0;
if (!isBookmarked) {
BrowserUIUtils.setToolbarButtonHeightProperty(this.star);
BrowserUtils.setToolbarButtonHeightProperty(this.star);
// there are no other animations on this element, so we can simply
// listen for animationend with the "once" option to clean up
let animatableBox = document.getElementById(

View File

@ -22,8 +22,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
NewTabPagePreloading: "resource:///modules/NewTabPagePreloading.jsm",
BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.jsm",
BrowserUsageTelemetry: "resource:///modules/BrowserUsageTelemetry.jsm",
BrowserTelemetryUtils: "resource://gre/modules/BrowserTelemetryUtils.jsm",
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
CFRPageActions: "resource://activity-stream/lib/CFRPageActions.jsm",
@ -4933,7 +4931,7 @@ var XULBrowserWindow = {
);
if (UrlbarPrefs.get("trimURLs")) {
url = BrowserUIUtils.trimURL(url);
url = BrowserUtils.trimURL(url);
}
}
@ -5122,7 +5120,7 @@ var XULBrowserWindow = {
aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT;
if (
(location == "about:blank" &&
BrowserUIUtils.checkEmptyPageOrigin(gBrowser.selectedBrowser)) ||
BrowserUtils.checkEmptyPageOrigin(gBrowser.selectedBrowser)) ||
location == ""
) {
// Second condition is for new tabs, otherwise
@ -5585,7 +5583,7 @@ var CombinedStopReload = {
this._cancelTransition();
if (shouldAnimate) {
BrowserUIUtils.setToolbarButtonHeightProperty(this.stopReloadContainer);
BrowserUtils.setToolbarButtonHeightProperty(this.stopReloadContainer);
this.stopReloadContainer.setAttribute("animate", "true");
} else {
this.stopReloadContainer.removeAttribute("animate");
@ -5608,7 +5606,7 @@ var CombinedStopReload = {
this.stopReloadContainer.closest("#nav-bar-customization-target");
if (shouldAnimate) {
BrowserUIUtils.setToolbarButtonHeightProperty(this.stopReloadContainer);
BrowserUtils.setToolbarButtonHeightProperty(this.stopReloadContainer);
this.stopReloadContainer.setAttribute("animate", "true");
} else {
this.stopReloadContainer.removeAttribute("animate");
@ -5719,7 +5717,7 @@ var TabsProgressListener = {
) {
if (recordLoadTelemetry) {
TelemetryStopwatch.finish(histogram, aBrowser);
BrowserTelemetryUtils.recordSiteOriginTelemetry(browserWindows());
BrowserUtils.recordSiteOriginTelemetry(browserWindows());
}
}
} else if (

View File

@ -255,12 +255,8 @@ class nsContextMenu {
this.selectionInfo = this.contentData.selectionInfo;
this.actor = this.contentData.actor;
} else {
const { SelectionUtils } = ChromeUtils.import(
"resource://gre/modules/SelectionUtils.jsm"
);
this.browser = this.ownerDoc.defaultView.docShell.chromeEventHandler;
this.selectionInfo = SelectionUtils.getSelectionDetails(window);
this.selectionInfo = BrowserUtils.getSelectionDetails(window);
this.actor = this.browser.browsingContext.currentWindowGlobal.getActor(
"ContextMenu"
);

View File

@ -227,7 +227,7 @@
return false;
}
if (!BrowserUIUtils.checkEmptyPageOrigin(browser)) {
if (!BrowserUtils.checkEmptyPageOrigin(browser)) {
return false;
}

View File

@ -31,7 +31,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
BookmarkJSONUtils: "resource://gre/modules/BookmarkJSONUtils.jsm",
BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.jsm",
BrowserUsageTelemetry: "resource:///modules/BrowserUsageTelemetry.jsm",
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
ContextualIdentityService:
"resource://gre/modules/ContextualIdentityService.jsm",
@ -3950,7 +3950,7 @@ BrowserGlue.prototype = {
// same way that the url bar would.
body = URIs[0].uri.replace(/([?#]).*$/, "$1");
let wasTruncated = body.length < URIs[0].uri.length;
body = BrowserUIUtils.trimURL(body);
body = BrowserUtils.trimURL(body);
if (wasTruncated) {
body = bundle.formatStringFromName(
"singleTabArrivingWithTruncatedURL.body",

View File

@ -52,8 +52,8 @@ ChromeUtils.defineModuleGetter(
);
ChromeUtils.defineModuleGetter(
this,
"BrowserUIUtils",
"resource:///modules/BrowserUIUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
@ -791,7 +791,7 @@ CustomizeMode.prototype = {
}
if (!this.window.gReduceMotion) {
let overflowButton = this.$("nav-bar-overflow-button");
BrowserUIUtils.setToolbarButtonHeightProperty(overflowButton).then(() => {
BrowserUtils.setToolbarButtonHeightProperty(overflowButton).then(() => {
overflowButton.setAttribute("animate", "true");
overflowButton.addEventListener("animationend", function onAnimationEnd(
event

View File

@ -34,8 +34,8 @@ ChromeUtils.defineModuleGetter(
);
ChromeUtils.defineModuleGetter(
this,
"BrowserUIUtils",
"resource:///modules/BrowserUIUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
@ -367,7 +367,7 @@ class ExtensionControlledPopup {
);
} else {
description.appendChild(
BrowserUIUtils.getLocalizedFragment(doc, message, addonDetails)
BrowserUtils.getLocalizedFragment(doc, message, addonDetails)
);
}

View File

@ -8,8 +8,8 @@
ChromeUtils.defineModuleGetter(
this,
"BrowserUIUtils",
"resource:///modules/BrowserUIUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
@ -64,7 +64,7 @@ XPCOMUtils.defineLazyGetter(this, "tabHidePopup", () => {
getLocalizedDescription: (doc, message, addonDetails) => {
let image = doc.createXULElement("image");
image.setAttribute("class", "extension-controlled-icon alltabs-icon");
return BrowserUIUtils.getLocalizedFragment(
return BrowserUtils.getLocalizedFragment(
doc,
message,
addonDetails,

View File

@ -42,6 +42,8 @@ const ICON_DATA =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABH0lEQVRYw2P8////f4YBBEwMAwxGHcBCUMX/91DGOSj/BpT/DkpzQChGBSjfBErLQsVZhmoI/L8LpRdD6X1QietQGhYy7FB5aAgwmkLpBKi4BZTPMThDgBGjHIDF+f9mKD0fKvGBRKNdoF7sgPL1saaJwZgGDkJ9vpZMn8PAHqg5G9FyifBgD4H/W9HyOWrU/f+DIzHhkoeZxxgzZEIAVtJ9RxX+Q6DAxCmP3byhXxkxshAs5odqbcioAY3UC1CBLyTGOTqAmsfAOWRCwBvqxV0oIUB2OQAzDy3/D+a6wB7q8mCU2vD/nw94GziYIQOtDRn9oXz+IZMGBKGMbCjNh9Ii+v8HR4uIAUeLiEEbb9twELaIRlqrmHG0bzjiHQAA1LVfww8jwM4AAAAASUVORK5CYII=";
let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
let makeURI = ChromeUtils.import("resource://gre/modules/BrowserUtils.jsm", {})
.BrowserUtils.makeURI;
function clearAllImageCaches() {
let tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"].getService(
@ -242,8 +244,8 @@ function assertIconIsData(item) {
}
async function doTest(aTestPage, aExpectedCookies, aFaviconURL) {
let firstPageURI = Services.io.newURI(TEST_SITE_ONE + aTestPage);
let secondPageURI = Services.io.newURI(TEST_SITE_TWO + aTestPage);
let firstPageURI = makeURI(TEST_SITE_ONE + aTestPage);
let secondPageURI = makeURI(TEST_SITE_TWO + aTestPage);
// Start to observe the event of that favicon has been fully loaded.
let promiseFaviconLoaded = waitOnFaviconLoaded(aFaviconURL);

View File

@ -10,8 +10,8 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(
this,
"BrowserUIUtils",
"resource:///modules/BrowserUIUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
var Pocket = {
@ -46,7 +46,7 @@ var Pocket = {
let libraryButton = document.getElementById("library-button");
if (libraryButton) {
BrowserUIUtils.setToolbarButtonHeightProperty(libraryButton);
BrowserUtils.setToolbarButtonHeightProperty(libraryButton);
}
let urlToSave = Pocket._urlToSave;

View File

@ -11,8 +11,8 @@ const { XPCOMUtils } = ChromeUtils.import(
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(
this,
"BrowserUIUtils",
"resource:///modules/BrowserUIUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
@ -76,7 +76,7 @@ var PocketPageAction = {
return;
}
BrowserUIUtils.setToolbarButtonHeightProperty(urlbarNode);
BrowserUtils.setToolbarButtonHeightProperty(urlbarNode);
PocketPageAction.urlbarNode = urlbarNode;
PocketPageAction.urlbarNode.setAttribute("open", "true");

View File

@ -15,6 +15,8 @@ const FAVICON_URI = TEST_SITE + TEST_DIRECTORY + "file_favicon.png";
const FAVICON_CACHE_URI = TEST_CACHE_SITE + TEST_DIRECTORY + "file_favicon.png";
let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
let makeURI = ChromeUtils.import("resource://gre/modules/BrowserUtils.jsm", {})
.BrowserUtils.makeURI;
function clearAllImageCaches() {
let tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"].getService(
@ -203,7 +205,7 @@ add_task(async function test_favicon_privateBrowsing() {
let privateWindow = await BrowserTestUtils.openNewBrowserWindow({
private: true,
});
let pageURI = Services.io.newURI(TEST_PAGE);
let pageURI = makeURI(TEST_PAGE);
// Generate two random cookies for non-private window and private window
// respectively.

View File

@ -396,7 +396,7 @@ function test() {
);
is(
gURLBar.value,
BrowserUIUtils.trimURL("http://example.com/"),
BrowserUtils.trimURL("http://example.com/"),
"Address bar's value set after loading URI"
);
runNextTest();

View File

@ -13,7 +13,7 @@ const { XPCOMUtils } = ChromeUtils.import(
XPCOMUtils.defineLazyModuleGetters(this, {
AppConstants: "resource://gre/modules/AppConstants.jsm",
BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.jsm",
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
ExtensionSearchHandler: "resource://gre/modules/ExtensionSearchHandler.jsm",
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
@ -330,7 +330,7 @@ class UrlbarInput {
// only if there's no opener (bug 370555).
if (
this.window.isInitialPage(uri) &&
BrowserUIUtils.checkEmptyPageOrigin(
BrowserUtils.checkEmptyPageOrigin(
this.window.gBrowser.selectedBrowser,
uri
)
@ -349,7 +349,7 @@ class UrlbarInput {
!this.window.isBlankPageURL(uri.spec) || uri.schemeIs("moz-extension");
} else if (
this.window.isInitialPage(value) &&
BrowserUIUtils.checkEmptyPageOrigin(this.window.gBrowser.selectedBrowser)
BrowserUtils.checkEmptyPageOrigin(this.window.gBrowser.selectedBrowser)
) {
value = "";
valid = true;
@ -1076,10 +1076,10 @@ class UrlbarInput {
if (
result.type == UrlbarUtils.RESULT_TYPE.URL &&
UrlbarPrefs.get("trimURLs") &&
result.payload.url.startsWith(BrowserUIUtils.trimURLProtocol)
result.payload.url.startsWith(BrowserUtils.trimURLProtocol)
) {
let fixupInfo = this._getURIFixupInfo(
BrowserUIUtils.trimURL(result.payload.url)
BrowserUtils.trimURL(result.payload.url)
);
if (fixupInfo?.keywordAsSent) {
allowTrim = false;
@ -2089,12 +2089,12 @@ class UrlbarInput {
// url. First check for a trimmed value.
if (
!selectedVal.startsWith(BrowserUIUtils.trimURLProtocol) &&
!selectedVal.startsWith(BrowserUtils.trimURLProtocol) &&
// Note _trimValue may also trim a trailing slash, thus we can't just do
// a straight string compare to tell if the protocol was trimmed.
!displaySpec.startsWith(this._trimValue(displaySpec))
) {
selectedVal = BrowserUIUtils.trimURLProtocol + selectedVal;
selectedVal = BrowserUtils.trimURLProtocol + selectedVal;
}
return selectedVal;
@ -2176,7 +2176,7 @@ class UrlbarInput {
* The trimmed string
*/
_trimValue(val) {
return UrlbarPrefs.get("trimURLs") ? BrowserUIUtils.trimURL(val) : val;
return UrlbarPrefs.get("trimURLs") ? BrowserUtils.trimURL(val) : val;
}
/**
@ -3257,11 +3257,10 @@ function getDroppableData(event) {
}
try {
// If this throws, checkLoadURStrWithPrincipal would also throw,
// as that's what it does with things that don't pass the IO
// service's newURI constructor without fixup. It's conceivable we
// may want to relax this check in the future (so e.g. www.foo.com
// gets fixed up), but not right now.
// If this throws, urlSecurityCheck would also throw, as that's what it
// does with things that don't pass the IO service's newURI constructor
// without fixup. It's conceivable we may want to relax this check in
// the future (so e.g. www.foo.com gets fixed up), but not right now.
let url = new URL(href);
// If we succeed, try to pass security checks. If this works, return the
// URL object. If the *security checks* fail, return null.
@ -3269,9 +3268,9 @@ function getDroppableData(event) {
let principal = Services.droppedLinkHandler.getTriggeringPrincipal(
event
);
Services.scriptSecurityManager.checkLoadURIStrWithPrincipal(
BrowserUtils.urlSecurityCheck(
url,
principal,
url.href,
Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL
);
return url;

View File

@ -18,7 +18,7 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
JsonSchemaValidator:
"resource://gre/modules/components-utils/JsonSchemaValidator.jsm",
Services: "resource://gre/modules/Services.jsm",
@ -226,7 +226,7 @@ class UrlbarResult {
payloadInfo.displayUrl = [...payloadInfo.url];
let url = payloadInfo.displayUrl[0];
if (url && UrlbarPrefs.get("trimURLs")) {
url = BrowserUIUtils.removeSingleTrailingSlashFromURL(url);
url = BrowserUtils.removeSingleTrailingSlashFromURL(url);
if (url.startsWith("https://")) {
url = url.substring(8);
if (url.startsWith("www.")) {

View File

@ -21,9 +21,9 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
FormHistory: "resource://gre/modules/FormHistory.jsm",
KeywordUtils: "resource://gre/modules/KeywordUtils.jsm",
Log: "resource://gre/modules/Log.jsm",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
PlacesUIUtils: "resource:///modules/PlacesUIUtils.jsm",
@ -308,7 +308,7 @@ var UrlbarUtils = {
}
try {
[url, postData] = await KeywordUtils.parseUrlAndPostData(
[url, postData] = await BrowserUtils.parseUrlAndPostData(
entry.url.href,
entry.postData,
param

View File

@ -13,7 +13,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
AddonTestUtils: "resource://testing-common/AddonTestUtils.jsm",
AppConstants: "resource://gre/modules/AppConstants.jsm",
BrowserTestUtils: "resource://testing-common/BrowserTestUtils.jsm",
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
FormHistoryTestUtils: "resource://testing-common/FormHistoryTestUtils.jsm",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
@ -113,7 +113,7 @@ var UrlbarTestUtils = {
window.gURLBar.inputField.focus();
// Using the value setter in some cases may trim and fetch unexpected
// results, then pick an alternate path.
if (UrlbarPrefs.get("trimURLs") && value != BrowserUIUtils.trimURL(value)) {
if (UrlbarPrefs.get("trimURLs") && value != BrowserUtils.trimURL(value)) {
window.gURLBar.inputField.value = value;
fireInputEvent = true;
} else {

View File

@ -102,7 +102,7 @@ function testVal(originalValue, targetValue) {
gURLBar.value = originalValue;
gURLBar.valueIsTyped = false;
let trimmedValue = UrlbarPrefs.get("trimURLs")
? BrowserUIUtils.trimURL(originalValue)
? BrowserUtils.trimURL(originalValue)
: originalValue;
Assert.equal(gURLBar.value, trimmedValue, "url bar value set");
// Now focus the urlbar and check the inputField value is properly set.

View File

@ -5,7 +5,7 @@
// modifies the selected url, or just closes the results pane, we do a visit
// rather than searching for the trimmed string.
const url = BrowserUIUtils.trimURLProtocol + "invalid.somehost/mytest";
const url = BrowserUtils.trimURLProtocol + "invalid.somehost/mytest";
add_task(async function setup() {
await SpecialPowers.pushPrefEnv({

View File

@ -16,14 +16,14 @@ add_task(async function() {
await BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
is(
gURLBar.value,
BrowserUIUtils.trimURL(goodURL),
BrowserUtils.trimURL(goodURL),
"location bar reflects loaded page"
);
await typeAndSubmitAndStop(badURL);
is(
gURLBar.value,
BrowserUIUtils.trimURL(goodURL),
BrowserUtils.trimURL(goodURL),
"location bar reflects loaded page after stop()"
);
gBrowser.removeCurrentTab();
@ -34,7 +34,7 @@ add_task(async function() {
await typeAndSubmitAndStop(badURL);
is(
gURLBar.value,
BrowserUIUtils.trimURL(badURL),
BrowserUtils.trimURL(badURL),
"location bar reflects stopped page in an empty tab"
);
gBrowser.removeCurrentTab();

View File

@ -51,7 +51,7 @@ add_task(async function() {
BrowserTestUtils.loadURI(partialURLTab.linkedBrowser, testURL);
await Promise.all([loaded1, loaded2, loaded3]);
testURL = BrowserUIUtils.trimURL(testURL);
testURL = BrowserUtils.trimURL(testURL);
testPartialURL = testURL.substr(0, testURL.length - charsToDelete);
function cleanUp() {

View File

@ -1,204 +0,0 @@
/* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* 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/. */
"use strict";
var EXPORTED_SYMBOLS = ["BrowserUIUtils"];
var BrowserUIUtils = {
/**
* Check whether a page can be considered as 'empty', that its URI
* reflects its origin, and that if it's loaded in a tab, that tab
* could be considered 'empty' (e.g. like the result of opening
* a 'blank' new tab).
*
* We have to do more than just check the URI, because especially
* for things like about:blank, it is possible that the opener or
* some other page has control over the contents of the page.
*
* @param {Browser} browser
* The browser whose page we're checking.
* @param {nsIURI} [uri]
* The URI against which we're checking (the browser's currentURI
* if omitted).
*
* @return {boolean} false if the page was opened by or is controlled by
* arbitrary web content, unless that content corresponds with the URI.
* true if the page is blank and controlled by a principal matching
* that URI (or the system principal if the principal has no URI)
*/
checkEmptyPageOrigin(browser, uri = browser.currentURI) {
// If another page opened this page with e.g. window.open, this page might
// be controlled by its opener.
if (browser.hasContentOpener) {
return false;
}
let contentPrincipal = browser.contentPrincipal;
// Not all principals have URIs...
// There are two special-cases involving about:blank. One is where
// the user has manually loaded it and it got created with a null
// principal. The other involves the case where we load
// some other empty page in a browser and the current page is the
// initial about:blank page (which has that as its principal, not
// just URI in which case it could be web-based). Especially in
// e10s, we need to tackle that case specifically to avoid race
// conditions when updating the URL bar.
//
// Note that we check the documentURI here, since the currentURI on
// the browser might have been set by SessionStore in order to
// support switch-to-tab without having actually loaded the content
// yet.
let uriToCheck = browser.documentURI || uri;
if (
(uriToCheck.spec == "about:blank" && contentPrincipal.isNullPrincipal) ||
contentPrincipal.spec == "about:blank"
) {
return true;
}
if (contentPrincipal.isContentPrincipal) {
return contentPrincipal.equalsURI(uri);
}
// ... so for those that don't have them, enforce that the page has the
// system principal (this matches e.g. on about:newtab).
return contentPrincipal.isSystemPrincipal;
},
/**
* Sets the --toolbarbutton-button-height CSS property on the closest
* toolbar to the provided element. Useful if you need to vertically
* center a position:absolute element within a toolbar that uses
* -moz-pack-align:stretch, and thus a height which is dependant on
* the font-size.
*
* @param element An element within the toolbar whose height is desired.
*/
async setToolbarButtonHeightProperty(element) {
let window = element.ownerGlobal;
let dwu = window.windowUtils;
let toolbarItem = element;
let urlBarContainer = element.closest("#urlbar-container");
if (urlBarContainer) {
// The stop-reload-button, which is contained in #urlbar-container,
// needs to use #urlbar-container to calculate the bounds.
toolbarItem = urlBarContainer;
}
if (!toolbarItem) {
return;
}
let bounds = dwu.getBoundsWithoutFlushing(toolbarItem);
if (!bounds.height) {
await window.promiseDocumentFlushed(() => {
bounds = dwu.getBoundsWithoutFlushing(toolbarItem);
});
}
if (bounds.height) {
toolbarItem.style.setProperty(
"--toolbarbutton-height",
bounds.height + "px"
);
}
},
/**
* Generate a document fragment for a localized string that has DOM
* node replacements. This avoids using getFormattedString followed
* by assigning to innerHTML. Fluent can probably replace this when
* it is in use everywhere.
*
* @param {Document} doc
* @param {String} msg
* The string to put replacements in. Fetch from
* a stringbundle using getString or GetStringFromName,
* or even an inserted dtd string.
* @param {Node|String} nodesOrStrings
* The replacement items. Can be a mix of Nodes
* and Strings. However, for correct behaviour, the
* number of items provided needs to exactly match
* the number of replacement strings in the l10n string.
* @returns {DocumentFragment}
* A document fragment. In the trivial case (no
* replacements), this will simply be a fragment with 1
* child, a text node containing the localized string.
*/
getLocalizedFragment(doc, msg, ...nodesOrStrings) {
// Ensure replacement points are indexed:
for (let i = 1; i <= nodesOrStrings.length; i++) {
if (!msg.includes("%" + i + "$S")) {
msg = msg.replace(/%S/, "%" + i + "$S");
}
}
let numberOfInsertionPoints = msg.match(/%\d+\$S/g).length;
if (numberOfInsertionPoints != nodesOrStrings.length) {
Cu.reportError(
`Message has ${numberOfInsertionPoints} insertion points, ` +
`but got ${nodesOrStrings.length} replacement parameters!`
);
}
let fragment = doc.createDocumentFragment();
let parts = [msg];
let insertionPoint = 1;
for (let replacement of nodesOrStrings) {
let insertionString = "%" + insertionPoint++ + "$S";
let partIndex = parts.findIndex(
part => typeof part == "string" && part.includes(insertionString)
);
if (partIndex == -1) {
fragment.appendChild(doc.createTextNode(msg));
return fragment;
}
if (typeof replacement == "string") {
parts[partIndex] = parts[partIndex].replace(
insertionString,
replacement
);
} else {
let [firstBit, lastBit] = parts[partIndex].split(insertionString);
parts.splice(partIndex, 1, firstBit, replacement, lastBit);
}
}
// Put everything in a document fragment:
for (let part of parts) {
if (typeof part == "string") {
if (part) {
fragment.appendChild(doc.createTextNode(part));
}
} else {
fragment.appendChild(part);
}
}
return fragment;
},
removeSingleTrailingSlashFromURL(aURL) {
// remove single trailing slash for http/https/ftp URLs
return aURL.replace(/^((?:http|https|ftp):\/\/[^/]+)\/$/, "$1");
},
/**
* Returns a URL which has been trimmed by removing 'http://' and any
* trailing slash (in http/https/ftp urls).
* Note that a trimmed url may not load the same page as the original url, so
* before loading it, it must be passed through URIFixup, to check trimming
* doesn't change its destination. We don't run the URIFixup check here,
* because trimURL is in the page load path (see onLocationChange), so it
* must be fast and simple.
*
* @param {string} aURL The URL to trim.
* @returns {string} The trimmed string.
*/
get trimURLProtocol() {
return "http://";
},
trimURL(aURL) {
let url = this.removeSingleTrailingSlashFromURL(aURL);
// Remove "http://" prefix.
return url.startsWith(this.trimURLProtocol)
? url.substring(this.trimURLProtocol.length)
: url;
},
};

View File

@ -19,7 +19,7 @@ const { XPCOMUtils } = ChromeUtils.import(
XPCOMUtils.defineLazyModuleGetters(this, {
AppConstants: "resource://gre/modules/AppConstants.jsm",
ClientID: "resource://gre/modules/ClientID.jsm",
BrowserTelemetryUtils: "resource://gre/modules/BrowserTelemetryUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
CustomizableUI: "resource:///modules/CustomizableUI.jsm",
PageActions: "resource:///modules/PageActions.jsm",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
@ -1208,7 +1208,7 @@ let BrowserUsageTelemetry = {
}
const { loadedTabCount } = getOpenTabsAndWinsCounts();
const siteOrigins = BrowserTelemetryUtils.computeSiteOriginCount(
const siteOrigins = BrowserUtils.computeSiteOriginCount(
Services.wm.getEnumerator("navigator:browser"),
false
);

View File

@ -128,7 +128,6 @@ EXTRA_JS_MODULES += [
"AboutNewTab.jsm",
"AppUpdater.jsm",
"AsyncTabSwitcher.jsm",
"BrowserUIUtils.jsm",
"BrowserUsageTelemetry.jsm",
"BrowserWindowTracker.jsm",
"ContentCrashHandlers.jsm",

View File

@ -36,7 +36,7 @@ toolbar[brighttext] {
animation-iteration-count: 1;
list-style-image: none;
/* Height must be equal to height of toolbarbutton padding-box. --toolbarbutton-height
is calculated and set during runtime by BrowserUIUtils.setToolbarButtonHeightProperty()
is calculated and set during runtime by BrowserUtils.setToolbarButtonHeightProperty()
before the animation begins. */
height: var(--toolbarbutton-height);
}

View File

@ -113,20 +113,9 @@ interface nsIScriptSecurityManager : nsISupports
* will only appear in the browser console, not window-associated
* consoles like the web console.
*/
[binaryname(CheckLoadURIWithPrincipal)]
void checkLoadURIWithPrincipalXPCOM(in nsIPrincipal aPrincipal,
in nsIURI uri,
in unsigned long flags,
[optional] in unsigned long long innerWindowID);
/**
* Same as the above, but when called from JS, raises exceptions with more
* useful messages, including both the tested URI and the principal string.
*/
[implicit_jscontext, binaryname(CheckLoadURIWithPrincipalFromJS)]
void checkLoadURIWithPrincipal(in nsIPrincipal aPrincipal,
in nsIURI uri,
[optional] in unsigned long flags,
in unsigned long flags,
[optional] in unsigned long long innerWindowID);
/**
@ -138,19 +127,9 @@ interface nsIScriptSecurityManager : nsISupports
* load as well); if any of the versions of this URI is not allowed, this
* function will return error code NS_ERROR_DOM_BAD_URI.
*/
[binaryname(CheckLoadURIStrWithPrincipal)]
void checkLoadURIStrWithPrincipalXPCOM(in nsIPrincipal aPrincipal,
in AUTF8String uri,
in unsigned long flags);
/**
* Same as the above, but when called from JS, raises exceptions with more
* useful messages, including both the tested URI and the principal string.
*/
[implicit_jscontext, binaryname(CheckLoadURIStrWithPrincipalFromJS)]
void checkLoadURIStrWithPrincipal(in nsIPrincipal aPrincipal,
in AUTF8String uri,
[optional] in unsigned long flags);
in unsigned long flags);
/**
* Returns true if the URI is from a domain that is allow-listed through

View File

@ -57,11 +57,9 @@
#include <stdint.h>
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/Exceptions.h"
#include "mozilla/dom/nsCSPContext.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/dom/WorkerCommon.h"
#include "mozilla/dom/WorkerPrivate.h"
@ -1118,49 +1116,6 @@ nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(
return rv;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckLoadURIWithPrincipalFromJS(nsIPrincipal* aPrincipal,
nsIURI* aTargetURI,
uint32_t aFlags,
uint64_t aInnerWindowID,
JSContext* aCx) {
NS_ENSURE_ARG_POINTER(aTargetURI);
nsresult rv = CheckLoadURIWithPrincipal(aPrincipal,
aTargetURI,
aFlags,
aInnerWindowID);
if (NS_FAILED(rv)) {
nsAutoCString uriStr;
Unused << aTargetURI->GetSpec(uriStr);
nsAutoCString message("Load of ");
message.Append(uriStr);
nsAutoCString principalStr;
Unused << aPrincipal->GetSpec(principalStr);
if (!principalStr.IsEmpty()) {
message.AppendPrintf(" from %s", principalStr.get());
}
message.Append(" denied");
dom::Throw(aCx, rv, message);
}
return rv;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckLoadURIStrWithPrincipalFromJS(
nsIPrincipal* aPrincipal, const nsACString& aTargetURIStr,
uint32_t aFlags, JSContext* aCx) {
nsCOMPtr<nsIURI> targetURI;
MOZ_TRY(NS_NewURI(getter_AddRefs(targetURI), aTargetURIStr));
return CheckLoadURIWithPrincipalFromJS(aPrincipal, targetURI, aFlags, 0, aCx);
}
NS_IMETHODIMP
nsScriptSecurityManager::InFileURIAllowlist(nsIURI* aUri, bool* aResult) {
MOZ_ASSERT(aUri);

View File

@ -254,7 +254,7 @@ function testURL(
let threw = false;
let targetURI;
try {
targetURI = Services.io.newURI(target);
targetURI = makeURI(target);
} catch (ex) {
ok(
!canCreate,
@ -300,7 +300,7 @@ add_task(async function() {
if (sourceString.startsWith("about:test-chrome-privs")) {
source = ssm.getSystemPrincipal();
} else {
source = ssm.createContentPrincipal(Services.io.newURI(sourceString), {});
source = ssm.createContentPrincipal(makeURI(sourceString), {});
}
for (let [
target,
@ -341,6 +341,10 @@ add_task(async function() {
// eslint-disable-next-line no-shadow
let baseFlags = ssm.STANDARD | ssm.DONT_REPORT_ERRORS;
// eslint-disable-next-line no-unused-vars
let makeURI = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm",
{}
).BrowserUtils.makeURI;
let b = new content.Blob(["I am a blob"]);
let contentBlobURI = content.URL.createObjectURL(b);
let contentPrincipal = content.document.nodePrincipal;

View File

@ -15,41 +15,46 @@
<script type="application/javascript"><![CDATA[
SimpleTest.requestCompleteLog();
let makeURI = ChromeUtils.import("resource://gre/modules/BrowserUtils.jsm", {}).BrowserUtils.makeURI;
const BASE_URI = "http://mochi.test:8888/chrome/dom/security/test/general/";
const FAVICON_URI = BASE_URI + "favicon_bug1277803.ico";
const LOADING_URI = BASE_URI + "bug1277803.html";
let testWindow; //will be used to trigger favicon load
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
let expectedPrincipal = Services.scriptSecurityManager
.createContentPrincipal(Services.io.newURI(LOADING_URI), {});
let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
let securityManager = Cc["@mozilla.org/scriptsecuritymanager;1"].
getService(Ci.nsIScriptSecurityManager);
let expectedPrincipal = securityManager.createContentPrincipal(makeURI(LOADING_URI), {});
let systemPrincipal = Cc["@mozilla.org/systemprincipal;1"].createInstance();
function runTest() {
// Register our observer to intercept favicon requests.
function observer(aSubject, aTopic, aData) {
// Make sure this is a favicon request.
let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
if (FAVICON_URI != httpChannel.URI.spec) {
return;
let os = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
let observer = {
observe: function(aSubject, aTopic, aData)
{
// Make sure this is a favicon request.
let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
if (FAVICON_URI != httpChannel.URI.spec) {
return;
}
// Ensure the topic is the one we set an observer for.
is(aTopic, "http-on-modify-request", "Expected observer topic");
// Check for the correct loadingPrincipal, triggeringPrincipal.
let triggeringPrincipal = httpChannel.loadInfo.triggeringPrincipal;
let loadingPrincipal = httpChannel.loadInfo.loadingPrincipal;
ok(loadingPrincipal.equals(expectedPrincipal), "Should be loading with the expected principal.");
ok(triggeringPrincipal.equals(expectedPrincipal), "Should be triggered with the expected principal.");
os.removeObserver(this, "http-on-modify-request");
SimpleTest.finish();
}
// Ensure the topic is the one we set an observer for.
is(aTopic, "http-on-modify-request", "Expected observer topic");
// Check for the correct loadingPrincipal, triggeringPrincipal.
let triggeringPrincipal = httpChannel.loadInfo.triggeringPrincipal;
let loadingPrincipal = httpChannel.loadInfo.loadingPrincipal;
ok(loadingPrincipal.equals(expectedPrincipal), "Should be loading with the expected principal.");
ok(triggeringPrincipal.equals(expectedPrincipal), "Should be triggered with the expected principal.");
Services.obs.removeObserver(this, "http-on-modify-request");
SimpleTest.finish();
}
Services.obs.addObserver(observer, "http-on-modify-request");
os.addObserver(observer, "http-on-modify-request");
// Now that the observer is set up, trigger a favicon load with navigation
testWindow = window.open(LOADING_URI);

View File

@ -29,7 +29,7 @@ XPCOMUtils.defineLazyServiceGetter(
);
XPCOMUtils.defineLazyModuleGetters(this, {
BrowserTelemetryUtils: "resource://gre/modules/BrowserTelemetryUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
HistogramStopwatch: "resource://gre/modules/GeckoViewTelemetry.jsm",
});
@ -435,7 +435,7 @@ class StateTracker extends Tracker {
success: aIsSuccess,
});
BrowserTelemetryUtils.recordSiteOriginTelemetry(
BrowserUtils.recordSiteOriginTelemetry(
Services.wm.getEnumerator("navigator:geckoview"),
true
);

View File

@ -11,8 +11,8 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(
this,
"LayoutUtils",
"resource://gre/modules/LayoutUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
@ -136,7 +136,7 @@ class AutoCompleteChild extends JSWindowActorChild {
return;
}
let rect = LayoutUtils.getElementBoundingScreenRect(element);
let rect = BrowserUtils.getElementBoundingScreenRect(element);
let window = element.ownerGlobal;
let dir = window.getComputedStyle(element).direction;
let results = this.getResultsFromController(input);

View File

@ -5,8 +5,8 @@
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(
this,
"LayoutUtils",
"resource://gre/modules/LayoutUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
var EXPORTED_SYMBOLS = ["DateTimePickerChild"];
@ -78,7 +78,7 @@ class DateTimePickerChild extends JSWindowActorChild {
* relative to the left/top of the content area.
*/
getBoundingContentRect(aElement) {
return LayoutUtils.getElementBoundingScreenRect(aElement);
return BrowserUtils.getElementBoundingScreenRect(aElement);
}
getTimePickerPref() {

View File

@ -12,8 +12,8 @@ const { XPCOMUtils } = ChromeUtils.import(
ChromeUtils.defineModuleGetter(
this,
"LayoutUtils",
"resource://gre/modules/LayoutUtils.jsm"
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
@ -173,7 +173,7 @@ SelectContentHelper.prototype = {
},
_getBoundingContentRect() {
return LayoutUtils.getElementBoundingScreenRect(this.element);
return BrowserUtils.getElementBoundingScreenRect(this.element);
},
_buildOptionList() {

View File

@ -142,7 +142,7 @@ XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
XPCOMUtils.defineLazyModuleGetters(this, {
AboutPagesUtils: "resource://gre/modules/AboutPagesUtils.jsm",
KeywordUtils: "resource://gre/modules/KeywordUtils.jsm",
BrowserUtils: "resource://gre/modules/BrowserUtils.jsm",
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
PlacesRemoteTabsAutocompleteProvider:
"resource://gre/modules/PlacesRemoteTabsAutocompleteProvider.jsm",
@ -1041,7 +1041,7 @@ Search.prototype = {
let url = null;
let postData = null;
try {
[url, postData] = await KeywordUtils.parseUrlAndPostData(
[url, postData] = await BrowserUtils.parseUrlAndPostData(
entry.url.href,
entry.postData,
searchString

View File

@ -8,6 +8,9 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { objectToPropBag } = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm"
).BrowserUtils;
// This is redefined below, for strange and unfortunate reasons.
var { PromptUtils } = ChromeUtils.import(
"resource://gre/modules/SharedPromptUtils.jsm"
@ -1201,7 +1204,7 @@ class ModalPrompter {
if (!(taskResult instanceof Object)) {
throw new Error("task must return object");
}
return PromptUtils.objectToPropBag(taskResult);
return objectToPropBag(taskResult);
}
/*

View File

@ -1,20 +1,8 @@
const { Cc, Ci, Cu: ChromeUtils } = SpecialPowers;
/**
* Converts a property bag to object.
* @param {nsIPropertyBag} bag - The property bag to convert
* @returns {Object} - The object representation of the nsIPropertyBag
*/
function propBagToObject(bag) {
if (!(bag instanceof Ci.nsIPropertyBag)) {
throw new TypeError("Not a property bag");
}
let result = {};
for (let { name, value } of bag.enumerator) {
result[name] = value;
}
return result;
}
const { propBagToObject } = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm"
).BrowserUtils;
var modalType;
var tabSubDialogsEnabled = SpecialPowers.Services.prefs.getBoolPref(

View File

@ -344,7 +344,7 @@ var PageThumbUtils = {
},
shouldStoreContentThumbnail(aDocument, aDocShell) {
if (BrowserUtils.isFindbarVisible(aDocShell)) {
if (BrowserUtils.isToolbarVisible(aDocShell, "findbar")) {
return false;
}

View File

@ -31,24 +31,8 @@ var ContentAreaUtils = {
},
};
function urlSecurityCheck(
aURL,
aPrincipal,
aFlags = Services.scriptSecurityManager
) {
if (aURL instanceof Ci.nsIURI) {
Services.scriptSecurityManager.checkLoadURIWithPrincipal(
aPrincipal,
aURL,
aFlags
);
} else {
Services.scriptSecurityManager.checkLoadURIStrWithPrincipal(
aPrincipal,
aURL,
aFlags
);
}
function urlSecurityCheck(aURL, aPrincipal, aFlags) {
return BrowserUtils.urlSecurityCheck(aURL, aPrincipal, aFlags);
}
// Clientele: (Make sure you don't break any of these)

View File

@ -1,199 +0,0 @@
/* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* 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/. */
"use strict";
var EXPORTED_SYMBOLS = ["BrowserTelemetryUtils"];
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
// The maximum number of concurrently-loaded origins allowed in order to
// qualify for the Fission rollout experiment.
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentMaxOrigins",
"fission.experiment.max-origins.origin-cap",
30
);
// The length of the sliding window during which a user must stay below
// the max origin cap. If the last time a user passed the max origin cap
// fell outside of this window, they will requalify for the experiment.
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentSlidingWindowMS",
"fission.experiment.max-origins.sliding-window-ms",
7 * 24 * 60 * 60 * 1000
);
// The pref holding the current qaualification state of the user. If
// true, the user is currently qualified from the experiment.
const FISSION_EXPERIMENT_PREF_QUALIFIED =
"fission.experiment.max-origins.qualified";
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentQualified",
FISSION_EXPERIMENT_PREF_QUALIFIED,
false
);
// The pref holding the timestamp of the last time we saw an origin
// count below the cap while the user was not currently marked as
// qualified.
const FISSION_EXPERIMENT_PREF_LAST_QUALIFIED =
"fission.experiment.max-origins.last-qualified";
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentLastQualified",
FISSION_EXPERIMENT_PREF_LAST_QUALIFIED,
0
);
// The pref holding the timestamp of the last time we saw an origin
// count exceeding the cap.
const FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED =
"fission.experiment.max-origins.last-disqualified";
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentLastDisqualified",
FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED,
0
);
var BrowserTelemetryUtils = {
recordSiteOriginTelemetry(aWindows, aIsGeckoView) {
Services.tm.idleDispatchToMainThread(() => {
this._recordSiteOriginTelemetry(aWindows, aIsGeckoView);
});
},
computeSiteOriginCount(aWindows, aIsGeckoView) {
// Geckoview and Desktop work differently. On desktop, aBrowser objects
// holds an array of tabs which we can use to get the <browser> objects.
// In Geckoview, it is apps' responsibility to keep track of the tabs, so
// there isn't an easy way for us to get the tabs.
let tabs = [];
if (aIsGeckoView) {
// To get all active windows; Each tab has its own window
tabs = aWindows;
} else {
for (const win of aWindows) {
tabs = tabs.concat(win.gBrowser.tabs);
}
}
let topLevelBCs = [];
for (const tab of tabs) {
let browser;
if (aIsGeckoView) {
browser = tab.browser;
} else {
browser = tab.linkedBrowser;
}
if (browser.browsingContext) {
// This is the top level browsingContext
topLevelBCs.push(browser.browsingContext);
}
}
return CanonicalBrowsingContext.countSiteOrigins(topLevelBCs);
},
_recordSiteOriginTelemetry(aWindows, aIsGeckoView) {
let currentTime = Date.now();
// default is 5 minutes
if (!this.min_interval) {
this.min_interval = Services.prefs.getIntPref(
"telemetry.number_of_site_origin.min_interval",
300000
);
}
let originCount = this.computeSiteOriginCount(aWindows, aIsGeckoView);
let histogram = Services.telemetry.getHistogramById(
"FX_NUMBER_OF_UNIQUE_SITE_ORIGINS_ALL_TABS"
);
// Discard the first load because most of the time the first load only has 1
// tab and 1 window open, so it is useless to report it.
if (!this._lastRecordSiteOrigin) {
this._lastRecordSiteOrigin = currentTime;
} else if (currentTime >= this._lastRecordSiteOrigin + this.min_interval) {
this._lastRecordSiteOrigin = currentTime;
histogram.add(originCount);
}
// Update the Fission experiment qualification state based on the
// current origin count:
// If we don't already have a last disqualification timestamp, look
// through the existing histogram values, and use the existing
// maximum value as the initial count. This will prevent us from
// enrolling users in the experiment if they have a history of
// exceeding our origin cap.
if (!this._checkedInitialExperimentQualification) {
this._checkedInitialExperimentQualification = true;
if (
!Services.prefs.prefHasUserValue(
FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED
)
) {
for (let [bucketStr, entryCount] of Object.entries(
histogram.snapshot().values
)) {
let bucket = Number(bucketStr);
if (bucket > originCount && entryCount > 0) {
originCount = bucket;
}
}
Services.prefs.setIntPref(FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED, 0);
}
}
let currentTimeSec = currentTime / 1000;
if (originCount < fissionExperimentMaxOrigins) {
let lastDisqualified = fissionExperimentLastDisqualified;
let lastQualified = fissionExperimentLastQualified;
// If the last time we saw a qualifying origin count was earlier
// than the last time we say a disqualifying count, update any
// existing last disqualified timestamp to just before now, on the
// basis that our origin count has probably just fallen below the
// cap.
if (lastDisqualified > 0 && lastQualified <= lastDisqualified) {
Services.prefs.setIntPref(
FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED,
currentTimeSec - 1
);
}
if (!fissionExperimentQualified) {
Services.prefs.setIntPref(
FISSION_EXPERIMENT_PREF_LAST_QUALIFIED,
currentTimeSec
);
// We have a qualifying origin count now. If the last time we were
// disqualified was prior to the start of our current sliding
// window, re-qualify the user.
if (
currentTimeSec - lastDisqualified >=
fissionExperimentSlidingWindowMS / 1000
) {
Services.prefs.setBoolPref(FISSION_EXPERIMENT_PREF_QUALIFIED, true);
}
}
} else {
Services.prefs.setIntPref(
FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED,
currentTimeSec
);
Services.prefs.setBoolPref(FISSION_EXPERIMENT_PREF_QUALIFIED, false);
}
},
};

View File

@ -11,8 +11,196 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm"
);
// The maximum number of concurrently-loaded origins allowed in order to
// qualify for the Fission rollout experiment.
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentMaxOrigins",
"fission.experiment.max-origins.origin-cap",
30
);
// The length of the sliding window during which a user must stay below
// the max origin cap. If the last time a user passed the max origin cap
// fell outside of this window, they will requalify for the experiment.
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentSlidingWindowMS",
"fission.experiment.max-origins.sliding-window-ms",
7 * 24 * 60 * 60 * 1000
);
// The pref holding the current qaualification state of the user. If
// true, the user is currently qualified from the experiment.
const FISSION_EXPERIMENT_PREF_QUALIFIED =
"fission.experiment.max-origins.qualified";
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentQualified",
FISSION_EXPERIMENT_PREF_QUALIFIED,
false
);
// The pref holding the timestamp of the last time we saw an origin
// count below the cap while the user was not currently marked as
// qualified.
const FISSION_EXPERIMENT_PREF_LAST_QUALIFIED =
"fission.experiment.max-origins.last-qualified";
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentLastQualified",
FISSION_EXPERIMENT_PREF_LAST_QUALIFIED,
0
);
// The pref holding the timestamp of the last time we saw an origin
// count exceeding the cap.
const FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED =
"fission.experiment.max-origins.last-disqualified";
XPCOMUtils.defineLazyPreferenceGetter(
this,
"fissionExperimentLastDisqualified",
FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED,
0
);
var BrowserUtils = {
/**
* Prints arguments separated by a space and appends a new line.
*/
dumpLn(...args) {
for (let a of args) {
dump(a + " ");
}
dump("\n");
},
/**
* restartApplication: Restarts the application, keeping it in
* safe mode if it is already in safe mode.
*/
restartApplication() {
let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance(
Ci.nsISupportsPRBool
);
Services.obs.notifyObservers(
cancelQuit,
"quit-application-requested",
"restart"
);
if (cancelQuit.data) {
// The quit request has been canceled.
return false;
}
// if already in safe mode restart in safe mode
if (Services.appinfo.inSafeMode) {
Services.startup.restartInSafeMode(
Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart
);
return undefined;
}
Services.startup.quit(
Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart
);
return undefined;
},
/**
* Check whether a page can be considered as 'empty', that its URI
* reflects its origin, and that if it's loaded in a tab, that tab
* could be considered 'empty' (e.g. like the result of opening
* a 'blank' new tab).
*
* We have to do more than just check the URI, because especially
* for things like about:blank, it is possible that the opener or
* some other page has control over the contents of the page.
*
* @param {Browser} browser
* The browser whose page we're checking.
* @param {nsIURI} [uri]
* The URI against which we're checking (the browser's currentURI
* if omitted).
*
* @return {boolean} false if the page was opened by or is controlled by
* arbitrary web content, unless that content corresponds with the URI.
* true if the page is blank and controlled by a principal matching
* that URI (or the system principal if the principal has no URI)
*/
checkEmptyPageOrigin(browser, uri = browser.currentURI) {
// If another page opened this page with e.g. window.open, this page might
// be controlled by its opener.
if (browser.hasContentOpener) {
return false;
}
let contentPrincipal = browser.contentPrincipal;
// Not all principals have URIs...
// There are two special-cases involving about:blank. One is where
// the user has manually loaded it and it got created with a null
// principal. The other involves the case where we load
// some other empty page in a browser and the current page is the
// initial about:blank page (which has that as its principal, not
// just URI in which case it could be web-based). Especially in
// e10s, we need to tackle that case specifically to avoid race
// conditions when updating the URL bar.
//
// Note that we check the documentURI here, since the currentURI on
// the browser might have been set by SessionStore in order to
// support switch-to-tab without having actually loaded the content
// yet.
let uriToCheck = browser.documentURI || uri;
if (
(uriToCheck.spec == "about:blank" && contentPrincipal.isNullPrincipal) ||
contentPrincipal.spec == "about:blank"
) {
return true;
}
if (contentPrincipal.isContentPrincipal) {
return contentPrincipal.equalsURI(uri);
}
// ... so for those that don't have them, enforce that the page has the
// system principal (this matches e.g. on about:newtab).
return contentPrincipal.isSystemPrincipal;
},
/**
* urlSecurityCheck: JavaScript wrapper for checkLoadURIWithPrincipal
* and checkLoadURIStrWithPrincipal.
* If |aPrincipal| is not allowed to link to |aURL|, this function throws with
* an error message.
*
* @param aURL
* The URL a page has linked to. This could be passed either as a string
* or as a nsIURI object.
* @param aPrincipal
* The principal of the document from which aURL came.
* @param aFlags
* Flags to be passed to checkLoadURIStr. If undefined,
* nsIScriptSecurityManager.STANDARD will be passed.
*/
urlSecurityCheck(aURL, aPrincipal, aFlags) {
var secMan = Services.scriptSecurityManager;
if (aFlags === undefined) {
aFlags = secMan.STANDARD;
}
try {
if (aURL instanceof Ci.nsIURI) {
secMan.checkLoadURIWithPrincipal(aPrincipal, aURL, aFlags);
} else {
secMan.checkLoadURIStrWithPrincipal(aPrincipal, aURL, aFlags);
}
} catch (e) {
let principalStr = "";
try {
principalStr = " from " + aPrincipal.spec;
} catch (e2) {}
throw new Error(`Load of ${aURL + principalStr} denied.`);
}
},
/**
* Return or create a principal with the content of one, and the originAttributes
* of an existing principal (e.g. on a docshell, where the originAttributes ought
@ -54,6 +242,102 @@ var BrowserUtils = {
);
},
/**
* Constructs a new URI, using nsIIOService.
* @param aURL The URI spec.
* @param aOriginCharset The charset of the URI.
* @param aBaseURI Base URI to resolve aURL, or null.
* @return an nsIURI object based on aURL.
*
* @deprecated Use Services.io.newURI directly instead.
*/
makeURI(aURL, aOriginCharset, aBaseURI) {
return Services.io.newURI(aURL, aOriginCharset, aBaseURI);
},
/**
* @deprecated Use Services.io.newFileURI directly instead.
*/
makeFileURI(aFile) {
return Services.io.newFileURI(aFile);
},
/**
* For a given DOM element, returns its position in "screen"
* coordinates. In a content process, the coordinates returned will
* be relative to the left/top of the tab. In the chrome process,
* the coordinates are relative to the user's screen.
*/
getElementBoundingScreenRect(aElement) {
return this.getElementBoundingRect(aElement, true);
},
/**
* For a given DOM element, returns its position as an offset from the topmost
* window. In a content process, the coordinates returned will be relative to
* the left/top of the topmost content area. If aInScreenCoords is true,
* screen coordinates will be returned instead.
*/
getElementBoundingRect(aElement, aInScreenCoords) {
let rect = aElement.getBoundingClientRect();
let win = aElement.ownerGlobal;
let x = rect.left;
let y = rect.top;
// We need to compensate for any iframes that might shift things
// over. We also need to compensate for zooming.
let parentFrame = win.frameElement;
while (parentFrame) {
win = parentFrame.ownerGlobal;
let cstyle = win.getComputedStyle(parentFrame);
let framerect = parentFrame.getBoundingClientRect();
x +=
framerect.left +
parseFloat(cstyle.borderLeftWidth) +
parseFloat(cstyle.paddingLeft);
y +=
framerect.top +
parseFloat(cstyle.borderTopWidth) +
parseFloat(cstyle.paddingTop);
parentFrame = win.frameElement;
}
rect = {
left: x,
top: y,
width: rect.width,
height: rect.height,
};
rect = win.windowUtils.transformRectLayoutToVisual(
rect.left,
rect.top,
rect.width,
rect.height
);
if (aInScreenCoords) {
rect = {
left: rect.left + win.mozInnerScreenX,
top: rect.top + win.mozInnerScreenY,
width: rect.width,
height: rect.height,
};
}
let fullZoom = win.windowUtils.fullZoom;
rect = {
left: rect.left * fullZoom,
top: rect.top * fullZoom,
width: rect.width * fullZoom,
height: rect.height * fullZoom,
};
return rect;
},
onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) {
// Don't modify non-default targets or targets that aren't in top-level app
// tab docshells (isAppTab will be false for app tab subframes).
@ -90,6 +374,35 @@ var BrowserUtils = {
return "_blank";
},
/**
* Map the plugin's name to a filtered version more suitable for UI.
*
* @param aName The full-length name string of the plugin.
* @return the simplified name string.
*/
makeNicePluginName(aName) {
if (aName == "Shockwave Flash") {
return "Adobe Flash";
}
// Regex checks if aName begins with "Java" + non-letter char
if (/^Java\W/.exec(aName)) {
return "Java";
}
// Clean up the plugin name by stripping off parenthetical clauses,
// trailing version numbers or "plugin".
// EG, "Foo Bar (Linux) Plugin 1.23_02" --> "Foo Bar"
// Do this by first stripping the numbers, etc. off the end, and then
// removing "Plugin" (and then trimming to get rid of any whitespace).
// (Otherwise, something like "Java(TM) Plug-in 1.7.0_07" gets mangled)
let newName = aName
.replace(/\(.*?\)/g, "")
.replace(/[\s\d\.\-\_\(\)]+$/, "")
.replace(/\bplug-?in\b/i, "")
.trim();
return newName;
},
/**
* Returns true if |mimeType| is text-based, or false otherwise.
*
@ -124,12 +437,395 @@ var BrowserUtils = {
);
},
isFindbarVisible(docShell) {
const FINDER_JSM = "resource://gre/modules/Finder.jsm";
return (
Cu.isModuleLoaded(FINDER_JSM) &&
ChromeUtils.import(FINDER_JSM).Finder.isFindbarVisible(docShell)
_visibleToolbarsMap: new WeakMap(),
/**
* Return true if any or a specific toolbar that interacts with the content
* document is visible.
*
* @param {nsIDocShell} docShell The docShell instance that a toolbar should
* be interacting with
* @param {String} which Identifier of a specific toolbar
* @return {Boolean}
*/
isToolbarVisible(docShell, which) {
let window = this.getRootWindow(docShell);
if (!this._visibleToolbarsMap.has(window)) {
return false;
}
let toolbars = this._visibleToolbarsMap.get(window);
return !!toolbars && toolbars.has(which);
},
/**
* Sets the --toolbarbutton-button-height CSS property on the closest
* toolbar to the provided element. Useful if you need to vertically
* center a position:absolute element within a toolbar that uses
* -moz-pack-align:stretch, and thus a height which is dependant on
* the font-size.
*
* @param element An element within the toolbar whose height is desired.
*/
async setToolbarButtonHeightProperty(element) {
let window = element.ownerGlobal;
let dwu = window.windowUtils;
let toolbarItem = element;
let urlBarContainer = element.closest("#urlbar-container");
if (urlBarContainer) {
// The stop-reload-button, which is contained in #urlbar-container,
// needs to use #urlbar-container to calculate the bounds.
toolbarItem = urlBarContainer;
}
if (!toolbarItem) {
return;
}
let bounds = dwu.getBoundsWithoutFlushing(toolbarItem);
if (!bounds.height) {
await window.promiseDocumentFlushed(() => {
bounds = dwu.getBoundsWithoutFlushing(toolbarItem);
});
}
if (bounds.height) {
toolbarItem.style.setProperty(
"--toolbarbutton-height",
bounds.height + "px"
);
}
},
/**
* Track whether a toolbar is visible for a given a docShell.
*
* @param {nsIDocShell} docShell The docShell instance that a toolbar should
* be interacting with
* @param {String} which Identifier of a specific toolbar
* @param {Boolean} [visible] Whether the toolbar is visible. Optional,
* defaults to `true`.
*/
trackToolbarVisibility(docShell, which, visible = true) {
// We have to get the root window object, because XPConnect WrappedNatives
// can't be used as WeakMap keys.
let window = this.getRootWindow(docShell);
let toolbars = this._visibleToolbarsMap.get(window);
if (!toolbars) {
toolbars = new Set();
this._visibleToolbarsMap.set(window, toolbars);
}
if (!visible) {
toolbars.delete(which);
} else {
toolbars.add(which);
}
},
/**
* Retrieve the root window object (i.e. the top-most content global) for a
* specific docShell object.
*
* @param {nsIDocShell} docShell
* @return {nsIDOMWindow}
*/
getRootWindow(docShell) {
return docShell.browsingContext.top.window;
},
/**
* Trim the selection text to a reasonable size and sanitize it to make it
* safe for search query input.
*
* @param aSelection
* The selection text to trim.
* @param aMaxLen
* The maximum string length, defaults to a reasonable size if undefined.
* @return The trimmed selection text.
*/
trimSelection(aSelection, aMaxLen) {
// Selections of more than 150 characters aren't useful.
const maxLen = Math.min(aMaxLen || 150, aSelection.length);
if (aSelection.length > maxLen) {
// only use the first maxLen important chars. see bug 221361
let pattern = new RegExp("^(?:\\s*.){0," + maxLen + "}");
pattern.test(aSelection);
aSelection = RegExp.lastMatch;
}
aSelection = aSelection.trim().replace(/\s+/g, " ");
if (aSelection.length > maxLen) {
aSelection = aSelection.substr(0, maxLen);
}
return aSelection;
},
/**
* Retrieve the text selection details for the given window.
*
* @param aTopWindow
* The top window of the element containing the selection.
* @param aCharLen
* The maximum string length for the selection text.
* @return The selection details containing the full and trimmed selection text
* and link details for link selections.
*/
getSelectionDetails(aTopWindow, aCharLen) {
let focusedWindow = {};
let focusedElement = Services.focus.getFocusedElementForWindow(
aTopWindow,
true,
focusedWindow
);
focusedWindow = focusedWindow.value;
let selection = focusedWindow.getSelection();
let selectionStr = selection.toString();
let fullText;
let url;
let linkText;
let isDocumentLevelSelection = true;
// try getting a selected text in text input.
if (!selectionStr && focusedElement) {
// Don't get the selection for password fields. See bug 565717.
if (
ChromeUtils.getClassName(focusedElement) === "HTMLTextAreaElement" ||
(ChromeUtils.getClassName(focusedElement) === "HTMLInputElement" &&
focusedElement.mozIsTextField(true))
) {
selection = focusedElement.editor.selection;
selectionStr = selection.toString();
isDocumentLevelSelection = false;
}
}
let collapsed = selection.isCollapsed;
if (selectionStr) {
// Have some text, let's figure out if it looks like a URL that isn't
// actually a link.
linkText = selectionStr.trim();
if (/^(?:https?|ftp):/i.test(linkText)) {
try {
url = this.makeURI(linkText);
} catch (ex) {}
} else if (/^(?:[a-z\d-]+\.)+[a-z]+$/i.test(linkText)) {
// Check if this could be a valid url, just missing the protocol.
// Now let's see if this is an intentional link selection. Our guess is
// based on whether the selection begins/ends with whitespace or is
// preceded/followed by a non-word character.
// selection.toString() trims trailing whitespace, so we look for
// that explicitly in the first and last ranges.
let beginRange = selection.getRangeAt(0);
let delimitedAtStart = /^\s/.test(beginRange);
if (!delimitedAtStart) {
let container = beginRange.startContainer;
let offset = beginRange.startOffset;
if (container.nodeType == container.TEXT_NODE && offset > 0) {
delimitedAtStart = /\W/.test(container.textContent[offset - 1]);
} else {
delimitedAtStart = true;
}
}
let delimitedAtEnd = false;
if (delimitedAtStart) {
let endRange = selection.getRangeAt(selection.rangeCount - 1);
delimitedAtEnd = /\s$/.test(endRange);
if (!delimitedAtEnd) {
let container = endRange.endContainer;
let offset = endRange.endOffset;
if (
container.nodeType == container.TEXT_NODE &&
offset < container.textContent.length
) {
delimitedAtEnd = /\W/.test(container.textContent[offset]);
} else {
delimitedAtEnd = true;
}
}
}
if (delimitedAtStart && delimitedAtEnd) {
try {
url = Services.uriFixup.getFixupURIInfo(linkText).preferredURI;
} catch (ex) {}
}
}
}
if (selectionStr) {
// Pass up to 16K through unmolested. If an add-on needs more, they will
// have to use a content script.
fullText = selectionStr.substr(0, 16384);
selectionStr = this.trimSelection(selectionStr, aCharLen);
}
if (url && !url.host) {
url = null;
}
return {
text: selectionStr,
docSelectionIsCollapsed: collapsed,
isDocumentLevelSelection,
fullText,
linkURL: url ? url.spec : null,
linkText: url ? linkText : "",
};
},
/**
* Replaces %s or %S in the provided url or postData with the given parameter,
* acccording to the best charset for the given url.
*
* @return [url, postData]
* @throws if nor url nor postData accept a param, but a param was provided.
*/
async parseUrlAndPostData(url, postData, param) {
let hasGETParam = /%s/i.test(url);
let decodedPostData = postData ? unescape(postData) : "";
let hasPOSTParam = /%s/i.test(decodedPostData);
if (!hasGETParam && !hasPOSTParam) {
if (param) {
// If nor the url, nor postData contain parameters, but a parameter was
// provided, return the original input.
throw new Error(
"A param was provided but there's nothing to bind it to"
);
}
return [url, postData];
}
let charset = "";
const re = /^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/;
let matches = url.match(re);
if (matches) {
[, url, charset] = matches;
} else {
// Try to fetch a charset from History.
try {
// Will return an empty string if character-set is not found.
let pageInfo = await PlacesUtils.history.fetch(url, {
includeAnnotations: true,
});
if (pageInfo && pageInfo.annotations.has(PlacesUtils.CHARSET_ANNO)) {
charset = pageInfo.annotations.get(PlacesUtils.CHARSET_ANNO);
}
} catch (ex) {
// makeURI() throws if url is invalid.
Cu.reportError(ex);
}
}
// encodeURIComponent produces UTF-8, and cannot be used for other charsets.
// escape() works in those cases, but it doesn't uri-encode +, @, and /.
// Therefore we need to manually replace these ASCII characters by their
// encodeURIComponent result, to match the behavior of nsEscape() with
// url_XPAlphas.
let encodedParam = "";
if (charset && charset != "UTF-8") {
try {
let converter = Cc[
"@mozilla.org/intl/scriptableunicodeconverter"
].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = charset;
encodedParam = converter.ConvertFromUnicode(param) + converter.Finish();
} catch (ex) {
encodedParam = param;
}
encodedParam = escape(encodedParam).replace(
/[+@\/]+/g,
encodeURIComponent
);
} else {
// Default charset is UTF-8
encodedParam = encodeURIComponent(param);
}
url = url.replace(/%s/g, encodedParam).replace(/%S/g, param);
if (hasPOSTParam) {
postData = decodedPostData
.replace(/%s/g, encodedParam)
.replace(/%S/g, param);
}
return [url, postData];
},
/**
* Generate a document fragment for a localized string that has DOM
* node replacements. This avoids using getFormattedString followed
* by assigning to innerHTML. Fluent can probably replace this when
* it is in use everywhere.
*
* @param {Document} doc
* @param {String} msg
* The string to put replacements in. Fetch from
* a stringbundle using getString or GetStringFromName,
* or even an inserted dtd string.
* @param {Node|String} nodesOrStrings
* The replacement items. Can be a mix of Nodes
* and Strings. However, for correct behaviour, the
* number of items provided needs to exactly match
* the number of replacement strings in the l10n string.
* @returns {DocumentFragment}
* A document fragment. In the trivial case (no
* replacements), this will simply be a fragment with 1
* child, a text node containing the localized string.
*/
getLocalizedFragment(doc, msg, ...nodesOrStrings) {
// Ensure replacement points are indexed:
for (let i = 1; i <= nodesOrStrings.length; i++) {
if (!msg.includes("%" + i + "$S")) {
msg = msg.replace(/%S/, "%" + i + "$S");
}
}
let numberOfInsertionPoints = msg.match(/%\d+\$S/g).length;
if (numberOfInsertionPoints != nodesOrStrings.length) {
Cu.reportError(
`Message has ${numberOfInsertionPoints} insertion points, ` +
`but got ${nodesOrStrings.length} replacement parameters!`
);
}
let fragment = doc.createDocumentFragment();
let parts = [msg];
let insertionPoint = 1;
for (let replacement of nodesOrStrings) {
let insertionString = "%" + insertionPoint++ + "$S";
let partIndex = parts.findIndex(
part => typeof part == "string" && part.includes(insertionString)
);
if (partIndex == -1) {
fragment.appendChild(doc.createTextNode(msg));
return fragment;
}
if (typeof replacement == "string") {
parts[partIndex] = parts[partIndex].replace(
insertionString,
replacement
);
} else {
let [firstBit, lastBit] = parts[partIndex].split(insertionString);
parts.splice(partIndex, 1, firstBit, replacement, lastBit);
}
}
// Put everything in a document fragment:
for (let part of parts) {
if (typeof part == "string") {
if (part) {
fragment.appendChild(doc.createTextNode(part));
}
} else {
fragment.appendChild(part);
}
}
return fragment;
},
/**
@ -155,6 +851,231 @@ var BrowserUtils = {
Services.obs.addObserver(observer, topic);
});
},
removeSingleTrailingSlashFromURL(aURL) {
// remove single trailing slash for http/https/ftp URLs
return aURL.replace(/^((?:http|https|ftp):\/\/[^/]+)\/$/, "$1");
},
/**
* Returns a URL which has been trimmed by removing 'http://' and any
* trailing slash (in http/https/ftp urls).
* Note that a trimmed url may not load the same page as the original url, so
* before loading it, it must be passed through URIFixup, to check trimming
* doesn't change its destination. We don't run the URIFixup check here,
* because trimURL is in the page load path (see onLocationChange), so it
* must be fast and simple.
*
* @param {string} aURL The URL to trim.
* @returns {string} The trimmed string.
*/
get trimURLProtocol() {
return "http://";
},
trimURL(aURL) {
let url = this.removeSingleTrailingSlashFromURL(aURL);
// Remove "http://" prefix.
return url.startsWith(this.trimURLProtocol)
? url.substring(this.trimURLProtocol.length)
: url;
},
recordSiteOriginTelemetry(aWindows, aIsGeckoView) {
Services.tm.idleDispatchToMainThread(() => {
this._recordSiteOriginTelemetry(aWindows, aIsGeckoView);
});
},
computeSiteOriginCount(aWindows, aIsGeckoView) {
// Geckoview and Desktop work differently. On desktop, aBrowser objects
// holds an array of tabs which we can use to get the <browser> objects.
// In Geckoview, it is apps' responsibility to keep track of the tabs, so
// there isn't an easy way for us to get the tabs.
let tabs = [];
if (aIsGeckoView) {
// To get all active windows; Each tab has its own window
tabs = aWindows;
} else {
for (const win of aWindows) {
tabs = tabs.concat(win.gBrowser.tabs);
}
}
let topLevelBCs = [];
for (const tab of tabs) {
let browser;
if (aIsGeckoView) {
browser = tab.browser;
} else {
browser = tab.linkedBrowser;
}
if (browser.browsingContext) {
// This is the top level browsingContext
topLevelBCs.push(browser.browsingContext);
}
}
return CanonicalBrowsingContext.countSiteOrigins(topLevelBCs);
},
_recordSiteOriginTelemetry(aWindows, aIsGeckoView) {
let currentTime = Date.now();
// default is 5 minutes
if (!this.min_interval) {
this.min_interval = Services.prefs.getIntPref(
"telemetry.number_of_site_origin.min_interval",
300000
);
}
let originCount = this.computeSiteOriginCount(aWindows, aIsGeckoView);
let histogram = Services.telemetry.getHistogramById(
"FX_NUMBER_OF_UNIQUE_SITE_ORIGINS_ALL_TABS"
);
// Discard the first load because most of the time the first load only has 1
// tab and 1 window open, so it is useless to report it.
if (!this._lastRecordSiteOrigin) {
this._lastRecordSiteOrigin = currentTime;
} else if (currentTime >= this._lastRecordSiteOrigin + this.min_interval) {
this._lastRecordSiteOrigin = currentTime;
histogram.add(originCount);
}
// Update the Fission experiment qualification state based on the
// current origin count:
// If we don't already have a last disqualification timestamp, look
// through the existing histogram values, and use the existing
// maximum value as the initial count. This will prevent us from
// enrolling users in the experiment if they have a history of
// exceeding our origin cap.
if (!this._checkedInitialExperimentQualification) {
this._checkedInitialExperimentQualification = true;
if (
!Services.prefs.prefHasUserValue(
FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED
)
) {
for (let [bucketStr, entryCount] of Object.entries(
histogram.snapshot().values
)) {
let bucket = Number(bucketStr);
if (bucket > originCount && entryCount > 0) {
originCount = bucket;
}
}
Services.prefs.setIntPref(FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED, 0);
}
}
let currentTimeSec = currentTime / 1000;
if (originCount < fissionExperimentMaxOrigins) {
let lastDisqualified = fissionExperimentLastDisqualified;
let lastQualified = fissionExperimentLastQualified;
// If the last time we saw a qualifying origin count was earlier
// than the last time we say a disqualifying count, update any
// existing last disqualified timestamp to just before now, on the
// basis that our origin count has probably just fallen below the
// cap.
if (lastDisqualified > 0 && lastQualified <= lastDisqualified) {
Services.prefs.setIntPref(
FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED,
currentTimeSec - 1
);
}
if (!fissionExperimentQualified) {
Services.prefs.setIntPref(
FISSION_EXPERIMENT_PREF_LAST_QUALIFIED,
currentTimeSec
);
// We have a qualifying origin count now. If the last time we were
// disqualified was prior to the start of our current sliding
// window, re-qualify the user.
if (
currentTimeSec - lastDisqualified >=
fissionExperimentSlidingWindowMS / 1000
) {
Services.prefs.setBoolPref(FISSION_EXPERIMENT_PREF_QUALIFIED, true);
}
}
} else {
Services.prefs.setIntPref(
FISSION_EXPERIMENT_PREF_LAST_DISQUALIFIED,
currentTimeSec
);
Services.prefs.setBoolPref(FISSION_EXPERIMENT_PREF_QUALIFIED, false);
}
},
/**
* Converts a property bag to object.
* @param {nsIPropertyBag} bag - The property bag to convert
* @returns {Object} - The object representation of the nsIPropertyBag
*/
propBagToObject(bag) {
function toValue(property) {
if (typeof property != "object") {
return property;
}
if (Array.isArray(property)) {
return property.map(this.toValue, this);
}
if (property && property instanceof Ci.nsIPropertyBag) {
return this.propBagToObject(property);
}
return property;
}
if (!(bag instanceof Ci.nsIPropertyBag)) {
throw new TypeError("Not a property bag");
}
let result = {};
for (let { name, value: property } of bag.enumerator) {
let value = toValue(property);
result[name] = value;
}
return result;
},
/**
* Converts an object to a property bag.
* @param {Object} obj - The object to convert.
* @returns {nsIPropertyBag} - The property bag representation of the object.
*/
objectToPropBag(obj) {
function fromValue(value) {
if (typeof value == "function") {
return null; // Emulating the behavior of JSON.stringify with functions
}
if (Array.isArray(value)) {
return value.map(this.fromValue, this);
}
if (value == null || typeof value != "object") {
// Auto-converted to nsIVariant
return value;
}
return this.objectToPropBag(value);
}
if (obj == null || typeof obj != "object") {
throw new TypeError("Invalid object: " + obj);
}
let bag = Cc["@mozilla.org/hash-property-bag;1"].createInstance(
Ci.nsIWritablePropertyBag
);
for (let k of Object.keys(obj)) {
let value = fromValue(obj[k]);
bag.setProperty(k, value);
}
return bag;
},
};
XPCOMUtils.defineLazyPreferenceGetter(

View File

@ -15,6 +15,11 @@ const { XPCOMUtils } = ChromeUtils.import(
const { Rect } = ChromeUtils.import("resource://gre/modules/Geometry.jsm");
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(
this,
"BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"FinderIterator",
@ -37,8 +42,6 @@ XPCOMUtils.defineLazyServiceGetter(
const kSelectionMaxLen = 150;
const kMatchesCountLimitPref = "accessibility.typeaheadfind.matchesCountLimit";
const activeFinderRoots = new WeakSet();
function Finder(docShell) {
this._fastFind = Cc["@mozilla.org/typeaheadfind;1"].createInstance(
Ci.nsITypeAheadFind
@ -489,15 +492,11 @@ Finder.prototype = {
this.enableSelection();
this.highlighter.highlight(false);
this.iterator.reset();
activeFinderRoots.delete(this._docShell.browsingContext.top);
BrowserUtils.trackToolbarVisibility(this._docShell, "findbar", false);
},
onFindbarOpen() {
activeFinderRoots.add(this._docShell.browsingContext.top);
},
isFindbarVisible(docShell) {
return activeFinderRoots.has(docShell.browsingContext.top);
BrowserUtils.trackToolbarVisibility(this._docShell, "findbar", true);
},
onModalHighlightChange(useModalHighlight) {

View File

@ -1,94 +0,0 @@
/* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* 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/. */
"use strict";
var EXPORTED_SYMBOLS = ["KeywordUtils"];
ChromeUtils.defineModuleGetter(
this,
"PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm"
);
var KeywordUtils = {
/**
* Replaces %s or %S in the provided url or postData with the given parameter,
* acccording to the best charset for the given url.
*
* @return [url, postData]
* @throws if nor url nor postData accept a param, but a param was provided.
*/
async parseUrlAndPostData(url, postData, param) {
let hasGETParam = /%s/i.test(url);
let decodedPostData = postData ? unescape(postData) : "";
let hasPOSTParam = /%s/i.test(decodedPostData);
if (!hasGETParam && !hasPOSTParam) {
if (param) {
// If nor the url, nor postData contain parameters, but a parameter was
// provided, return the original input.
throw new Error(
"A param was provided but there's nothing to bind it to"
);
}
return [url, postData];
}
let charset = "";
const re = /^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/;
let matches = url.match(re);
if (matches) {
[, url, charset] = matches;
} else {
// Try to fetch a charset from History.
try {
// Will return an empty string if character-set is not found.
let pageInfo = await PlacesUtils.history.fetch(url, {
includeAnnotations: true,
});
if (pageInfo && pageInfo.annotations.has(PlacesUtils.CHARSET_ANNO)) {
charset = pageInfo.annotations.get(PlacesUtils.CHARSET_ANNO);
}
} catch (ex) {
// makeURI() throws if url is invalid.
Cu.reportError(ex);
}
}
// encodeURIComponent produces UTF-8, and cannot be used for other charsets.
// escape() works in those cases, but it doesn't uri-encode +, @, and /.
// Therefore we need to manually replace these ASCII characters by their
// encodeURIComponent result, to match the behavior of nsEscape() with
// url_XPAlphas.
let encodedParam = "";
if (charset && charset != "UTF-8") {
try {
let converter = Cc[
"@mozilla.org/intl/scriptableunicodeconverter"
].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = charset;
encodedParam = converter.ConvertFromUnicode(param) + converter.Finish();
} catch (ex) {
encodedParam = param;
}
encodedParam = escape(encodedParam).replace(
/[+@\/]+/g,
encodeURIComponent
);
} else {
// Default charset is UTF-8
encodedParam = encodeURIComponent(param);
}
url = url.replace(/%s/g, encodedParam).replace(/%S/g, param);
if (hasPOSTParam) {
postData = decodedPostData
.replace(/%s/g, encodedParam)
.replace(/%S/g, param);
}
return [url, postData];
},
};

View File

@ -1,86 +0,0 @@
/* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* 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/. */
"use strict";
var EXPORTED_SYMBOLS = ["LayoutUtils"];
var LayoutUtils = {
/**
* For a given DOM element, returns its position in "screen"
* coordinates. In a content process, the coordinates returned will
* be relative to the left/top of the tab. In the chrome process,
* the coordinates are relative to the user's screen.
*/
getElementBoundingScreenRect(aElement) {
return this.getElementBoundingRect(aElement, true);
},
/**
* For a given DOM element, returns its position as an offset from the topmost
* window. In a content process, the coordinates returned will be relative to
* the left/top of the topmost content area. If aInScreenCoords is true,
* screen coordinates will be returned instead.
*/
getElementBoundingRect(aElement, aInScreenCoords) {
let rect = aElement.getBoundingClientRect();
let win = aElement.ownerGlobal;
let x = rect.left;
let y = rect.top;
// We need to compensate for any iframes that might shift things
// over. We also need to compensate for zooming.
let parentFrame = win.frameElement;
while (parentFrame) {
win = parentFrame.ownerGlobal;
let cstyle = win.getComputedStyle(parentFrame);
let framerect = parentFrame.getBoundingClientRect();
x +=
framerect.left +
parseFloat(cstyle.borderLeftWidth) +
parseFloat(cstyle.paddingLeft);
y +=
framerect.top +
parseFloat(cstyle.borderTopWidth) +
parseFloat(cstyle.paddingTop);
parentFrame = win.frameElement;
}
rect = {
left: x,
top: y,
width: rect.width,
height: rect.height,
};
rect = win.windowUtils.transformRectLayoutToVisual(
rect.left,
rect.top,
rect.width,
rect.height
);
if (aInScreenCoords) {
rect = {
left: rect.left + win.mozInnerScreenX,
top: rect.top + win.mozInnerScreenY,
width: rect.width,
height: rect.height,
};
}
let fullZoom = win.windowUtils.fullZoom;
rect = {
left: rect.left * fullZoom,
top: rect.top * fullZoom,
width: rect.width * fullZoom,
height: rect.height * fullZoom,
};
return rect;
},
};

View File

@ -1,160 +0,0 @@
/* -*- mode: js; indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* 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/. */
"use strict";
var EXPORTED_SYMBOLS = ["SelectionUtils"];
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var SelectionUtils = {
/**
* Trim the selection text to a reasonable size and sanitize it to make it
* safe for search query input.
*
* @param aSelection
* The selection text to trim.
* @param aMaxLen
* The maximum string length, defaults to a reasonable size if undefined.
* @return The trimmed selection text.
*/
trimSelection(aSelection, aMaxLen) {
// Selections of more than 150 characters aren't useful.
const maxLen = Math.min(aMaxLen || 150, aSelection.length);
if (aSelection.length > maxLen) {
// only use the first maxLen important chars. see bug 221361
let pattern = new RegExp("^(?:\\s*.){0," + maxLen + "}");
pattern.test(aSelection);
aSelection = RegExp.lastMatch;
}
aSelection = aSelection.trim().replace(/\s+/g, " ");
if (aSelection.length > maxLen) {
aSelection = aSelection.substr(0, maxLen);
}
return aSelection;
},
/**
* Retrieve the text selection details for the given window.
*
* @param aTopWindow
* The top window of the element containing the selection.
* @param aCharLen
* The maximum string length for the selection text.
* @return The selection details containing the full and trimmed selection text
* and link details for link selections.
*/
getSelectionDetails(aTopWindow, aCharLen) {
let focusedWindow = {};
let focusedElement = Services.focus.getFocusedElementForWindow(
aTopWindow,
true,
focusedWindow
);
focusedWindow = focusedWindow.value;
let selection = focusedWindow.getSelection();
let selectionStr = selection.toString();
let fullText;
let url;
let linkText;
let isDocumentLevelSelection = true;
// try getting a selected text in text input.
if (!selectionStr && focusedElement) {
// Don't get the selection for password fields. See bug 565717.
if (
ChromeUtils.getClassName(focusedElement) === "HTMLTextAreaElement" ||
(ChromeUtils.getClassName(focusedElement) === "HTMLInputElement" &&
focusedElement.mozIsTextField(true))
) {
selection = focusedElement.editor.selection;
selectionStr = selection.toString();
isDocumentLevelSelection = false;
}
}
let collapsed = selection.isCollapsed;
if (selectionStr) {
// Have some text, let's figure out if it looks like a URL that isn't
// actually a link.
linkText = selectionStr.trim();
if (/^(?:https?|ftp):/i.test(linkText)) {
try {
url = Services.io.newURI(linkText);
} catch (ex) {}
} else if (/^(?:[a-z\d-]+\.)+[a-z]+$/i.test(linkText)) {
// Check if this could be a valid url, just missing the protocol.
// Now let's see if this is an intentional link selection. Our guess is
// based on whether the selection begins/ends with whitespace or is
// preceded/followed by a non-word character.
// selection.toString() trims trailing whitespace, so we look for
// that explicitly in the first and last ranges.
let beginRange = selection.getRangeAt(0);
let delimitedAtStart = /^\s/.test(beginRange);
if (!delimitedAtStart) {
let container = beginRange.startContainer;
let offset = beginRange.startOffset;
if (container.nodeType == container.TEXT_NODE && offset > 0) {
delimitedAtStart = /\W/.test(container.textContent[offset - 1]);
} else {
delimitedAtStart = true;
}
}
let delimitedAtEnd = false;
if (delimitedAtStart) {
let endRange = selection.getRangeAt(selection.rangeCount - 1);
delimitedAtEnd = /\s$/.test(endRange);
if (!delimitedAtEnd) {
let container = endRange.endContainer;
let offset = endRange.endOffset;
if (
container.nodeType == container.TEXT_NODE &&
offset < container.textContent.length
) {
delimitedAtEnd = /\W/.test(container.textContent[offset]);
} else {
delimitedAtEnd = true;
}
}
}
if (delimitedAtStart && delimitedAtEnd) {
try {
url = Services.uriFixup.getFixupURIInfo(linkText).preferredURI;
} catch (ex) {}
}
}
}
if (selectionStr) {
// Pass up to 16K through unmolested. If an add-on needs more, they will
// have to use a content script.
fullText = selectionStr.substr(0, 16384);
selectionStr = this.trimSelection(selectionStr, aCharLen);
}
if (url && !url.host) {
url = null;
}
return {
text: selectionStr,
docSelectionIsCollapsed: collapsed,
isDocumentLevelSelection,
fullText,
linkURL: url ? url.spec : null,
linkText: url ? linkText : "",
};
},
};

View File

@ -160,7 +160,6 @@ EXTRA_JS_MODULES += [
"AppMenuNotifications.jsm",
"AsyncPrefs.jsm",
"BinarySearch.jsm",
"BrowserTelemetryUtils.jsm",
"BrowserUtils.jsm",
"CanonicalJSON.jsm",
"CertUtils.jsm",
@ -191,8 +190,6 @@ EXTRA_JS_MODULES += [
"InlineSpellCheckerContent.jsm",
"Integration.jsm",
"JSONFile.jsm",
"KeywordUtils.jsm",
"LayoutUtils.jsm",
"Log.jsm",
"NewTabUtils.jsm",
"NLP.jsm",
@ -213,7 +210,6 @@ EXTRA_JS_MODULES += [
"RemotePageAccessManager.jsm",
"ResetProfile.jsm",
"ResponsivenessMonitor.jsm",
"SelectionUtils.jsm",
"ServiceRequest.jsm",
"Services.jsm",
"ShortcutUtils.jsm",

View File

@ -2,14 +2,18 @@
* 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/. */
const { BrowserUtils } = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm"
);
add_task(async function test_getSelectionDetails_input() {
// Mostly a regression test for bug 1420560
const url = kFixtureBaseURL + "file_getSelectionDetails_inputs.html";
await BrowserTestUtils.withNewTab({ gBrowser, url }, async browser => {
await SpecialPowers.spawn(browser, [], () => {
function checkSelection({ id, text, linkURL }) {
const { SelectionUtils } = ChromeUtils.import(
"resource://gre/modules/SelectionUtils.jsm"
const { BrowserUtils } = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm"
);
content.document.getElementById(id).select();
// It seems that when running as a test, the previous line will set
@ -19,7 +23,7 @@ add_task(async function test_getSelectionDetails_input() {
// ensure we're doing the right thing in the case that only the input's
// selection is present.
content.getSelection().removeAllRanges();
let info = SelectionUtils.getSelectionDetails(content);
let info = BrowserUtils.getSelectionDetails(content);
Assert.equal(text, info.text);
Assert.ok(!info.collapsed);
Assert.equal(linkURL, info.linkURL);