[Pale-Moon] Issue #1737 - Part 3: Clean up base/content p.3

This commit is contained in:
Pale Moon 2020-03-10 17:19:36 +01:00 • committed by Roy Tam
commit 6c51c7704a
9 changed files with 833 additions and 836 deletions

View file

@ -43,7 +43,7 @@ addMessageListener("Browser:HideSessionRestoreButton", function (message) {
let doc = content.document; let doc = content.document;
let container; let container;
if (doc.documentURI.toLowerCase() == "about:home" && if (doc.documentURI.toLowerCase() == "about:home" &&
(container = doc.getElementById("sessionRestoreContainer"))){ (container = doc.getElementById("sessionRestoreContainer"))) {
container.hidden = true; container.hidden = true;
} }
}); });
@ -67,7 +67,8 @@ var handleContentContextMenu = function (event) {
let plugin = null; let plugin = null;
try { try {
plugin = event.target.QueryInterface(Ci.nsIObjectLoadingContent); plugin = event.target.QueryInterface(Ci.nsIObjectLoadingContent);
} catch (e) {} } catch(e) {
}
if (plugin && plugin.displayedType == Ci.nsIObjectLoadingContent.TYPE_PLUGIN) { if (plugin && plugin.displayedType == Ci.nsIObjectLoadingContent.TYPE_PLUGIN) {
// Don't open a context menu for plugins. // Don't open a context menu for plugins.
return; return;
@ -76,10 +77,11 @@ var handleContentContextMenu = function (event) {
defaultPrevented = false; defaultPrevented = false;
} }
if (defaultPrevented) if (defaultPrevented) {
return; return;
}
let addonInfo = {}; let addonInfo = { };
let subject = { let subject = {
event: event, event: event,
addonInfo: addonInfo, addonInfo: addonInfo,
@ -106,8 +108,8 @@ var handleContentContextMenu = function (event) {
// if per element referrer is enabled, the element referrer overrules // if per element referrer is enabled, the element referrer overrules
// the document wide referrer // the document wide referrer
if (Services.prefs.getBoolPref("network.http.enablePerElementReferrer")) { if (Services.prefs.getBoolPref("network.http.enablePerElementReferrer")) {
let referrerAttrValue = Services.netUtils.parseAttributePolicyString(event.target. let referrerAttrValue = Services.netUtils.parseAttributePolicyString(
getAttribute("referrerpolicy")); event.target.getAttribute("referrerpolicy"));
if (referrerAttrValue !== Ci.nsIHttpChannel.REFERRER_POLICY_UNSET) { if (referrerAttrValue !== Ci.nsIHttpChannel.REFERRER_POLICY_UNSET) {
referrerPolicy = referrerAttrValue; referrerPolicy = referrerAttrValue;
} }
@ -128,12 +130,15 @@ var handleContentContextMenu = function (event) {
imageCache.findEntryProperties(event.target.currentURI, doc); imageCache.findEntryProperties(event.target.currentURI, doc);
try { try {
contentType = props.get("type", Ci.nsISupportsCString).data; contentType = props.get("type", Ci.nsISupportsCString).data;
} catch (e) {} } catch(e) {
}
try { try {
contentDisposition = contentDisposition =
props.get("content-disposition", Ci.nsISupportsCString).data; props.get("content-disposition", Ci.nsISupportsCString).data;
} catch (e) {} } catch(e) {
} catch (e) {} }
} catch(e) {
}
} }
let selectionInfo = BrowserUtils.getSelectionDetails(content); let selectionInfo = BrowserUtils.getSelectionDetails(content);
@ -158,7 +163,7 @@ var handleContentContextMenu = function (event) {
contentDisposition: contentDisposition, contentDisposition: contentDisposition,
selectionInfo: selectionInfo, selectionInfo: selectionInfo,
loginFillInfo, loginFillInfo,
parentAllowsMixedContent, parentAllowsMixedContent
}; };
} }
@ -167,11 +172,11 @@ Cc["@mozilla.org/eventlistenerservice;1"]
.addSystemEventListener(global, "contextmenu", handleContentContextMenu, false); .addSystemEventListener(global, "contextmenu", handleContentContextMenu, false);
// Lazily load the finder code // Lazily load the finder code
addMessageListener("Finder:Initialize", function () { addMessageListener("Finder:Initialize", function() {
let {RemoteFinderListener} = Cu.import("resource://gre/modules/RemoteFinder.jsm", {}); let {RemoteFinderListener} = Cu.import("resource://gre/modules/RemoteFinder.jsm", {});
new RemoteFinderListener(global); new RemoteFinderListener(global);
}); });
addEventListener("DOMWebNotificationClicked", function(event) { addEventListener("DOMWebNotificationClicked", function(event) {
sendAsyncMessage("DOMWebNotificationClicked", {}); sendAsyncMessage("DOMWebNotificationClicked", { });
}, false); }, false);

View file

@ -17,21 +17,21 @@ nsContextMenu.prototype = {
// Get contextual info. // Get contextual info.
this.setTarget(document.popupNode, document.popupRangeParent, this.setTarget(document.popupNode, document.popupRangeParent,
document.popupRangeOffset); document.popupRangeOffset);
if (!this.shouldDisplay) if (!this.shouldDisplay) {
return; return;
}
this.hasPageMenu = false; this.hasPageMenu = false;
if (!aIsShift) { if (!aIsShift) {
this.hasPageMenu = PageMenu.maybeBuildAndAttachMenu(this.target, this.hasPageMenu = PageMenu.maybeBuildAndAttachMenu(this.target, aXulMenu);
aXulMenu);
} }
this.isFrameImage = document.getElementById("isFrameImage"); this.isFrameImage = document.getElementById("isFrameImage");
this.ellipsis = "\u2026"; this.ellipsis = "\u2026";
try { try {
this.ellipsis = gPrefService.getComplexValue("intl.ellipsis", this.ellipsis = gPrefService.getComplexValue("intl.ellipsis", Ci.nsIPrefLocalizedString).data;
Ci.nsIPrefLocalizedString).data; } catch(e) {
} catch (e) { } }
this.isContentSelected = this.isContentSelection(); this.isContentSelected = this.isContentSelection();
this.onPlainTextLink = false; this.onPlainTextLink = false;
@ -68,9 +68,9 @@ nsContextMenu.prototype = {
initOpenItems: function() { initOpenItems: function() {
var isMailtoInternal = false; var isMailtoInternal = false;
if (this.onMailtoLink) { if (this.onMailtoLink) {
var mailtoHandler = Cc["@mozilla.org/uriloader/external-protocol-service;1"]. var mailtoHandler = Cc["@mozilla.org/uriloader/external-protocol-service;1"]
getService(Ci.nsIExternalProtocolService). .getService(Ci.nsIExternalProtocolService)
getProtocolHandlerInfo("mailto"); .getProtocolHandlerInfo("mailto");
isMailtoInternal = (!mailtoHandler.alwaysAskBeforeHandling && isMailtoInternal = (!mailtoHandler.alwaysAskBeforeHandling &&
mailtoHandler.preferredAction == Ci.nsIHandlerInfo.useHelperApp && mailtoHandler.preferredAction == Ci.nsIHandlerInfo.useHelperApp &&
(mailtoHandler.preferredApplicationHandler instanceof Ci.nsIWebHandlerApp)); (mailtoHandler.preferredApplicationHandler instanceof Ci.nsIWebHandlerApp));
@ -87,15 +87,16 @@ nsContextMenu.prototype = {
if (/^(?:https?|ftp):/i.test(linkText)) { if (/^(?:https?|ftp):/i.test(linkText)) {
try { try {
uri = makeURI(linkText); uri = makeURI(linkText);
} catch (ex) {} } catch(ex) {
} }
// Check if this could be a valid url, just missing the protocol. } else if (/^[-a-z\d\.]+\.[-a-z\d]{2,}[-_=~:#%&\?\w\/\.]*$/i.test(linkText)) {
else if (/^[-a-z\d\.]+\.[-a-z\d]{2,}[-_=~:#%&\?\w\/\.]*$/i.test(linkText)) { // Check if this could be a valid url, just missing the protocol.
let uriFixup = Cc["@mozilla.org/docshell/urifixup;1"] let uriFixup = Cc["@mozilla.org/docshell/urifixup;1"]
.getService(Ci.nsIURIFixup); .getService(Ci.nsIURIFixup);
try { try {
uri = uriFixup.createFixupURI(linkText, uriFixup.FIXUP_FLAG_NONE); uri = uriFixup.createFixupURI(linkText, uriFixup.FIXUP_FLAG_NONE);
} catch (ex) {} } catch(ex) {
}
} }
if (uri && uri.host) { if (uri && uri.host) {
@ -142,8 +143,9 @@ nsContextMenu.prototype = {
this.showItem("context-leave-dom-fullscreen", shouldShow); this.showItem("context-leave-dom-fullscreen", shouldShow);
// Explicitly show if in DOM fullscreen, but do not hide it has already been shown // Explicitly show if in DOM fullscreen, but do not hide it has already been shown
if (shouldShow) if (shouldShow) {
this.showItem("context-media-sep-commands", true); this.showItem("context-media-sep-commands", true);
}
}, },
initSaveItems: function() { initSaveItems: function() {
@ -199,8 +201,9 @@ nsContextMenu.prototype = {
#ifdef HAVE_SHELL_SERVICE #ifdef HAVE_SHELL_SERVICE
// Only enable Set as Desktop Background if we can get the shell service. // Only enable Set as Desktop Background if we can get the shell service.
var shell = getShellService(); var shell = getShellService();
if (shell) if (shell) {
haveSetDesktopBackground = shell.canSetDesktopBackground; haveSetDesktopBackground = shell.canSetDesktopBackground;
}
#endif #endif
this.showItem("context-setDesktopBackground", this.showItem("context-setDesktopBackground",
haveSetDesktopBackground && this.onLoadedImage); haveSetDesktopBackground && this.onLoadedImage);
@ -268,10 +271,11 @@ nsContextMenu.prototype = {
// Hide menu entries for images, show otherwise // Hide menu entries for images, show otherwise
if (this.inFrame) { if (this.inFrame) {
if (BrowserUtils.mimeTypeIsTextBased(this.target.ownerDocument.contentType)) if (BrowserUtils.mimeTypeIsTextBased(this.target.ownerDocument.contentType)) {
this.isFrameImage.removeAttribute('hidden'); this.isFrameImage.removeAttribute('hidden');
else } else {
this.isFrameImage.setAttribute('hidden', 'true'); this.isFrameImage.setAttribute('hidden', 'true');
}
} }
// BiDi UI // BiDi UI
@ -297,15 +301,14 @@ nsContextMenu.prototype = {
// suggestion list // suggestion list
this.showItem("spell-suggestions-separator", onMisspelling || showUndo); this.showItem("spell-suggestions-separator", onMisspelling || showUndo);
if (onMisspelling) { if (onMisspelling) {
var suggestionsSeparator = var suggestionsSeparator = document.getElementById("spell-add-to-dictionary");
document.getElementById("spell-add-to-dictionary");
var numsug = var numsug =
InlineSpellCheckerUI.addSuggestionsToMenu(suggestionsSeparator.parentNode, InlineSpellCheckerUI.addSuggestionsToMenu(suggestionsSeparator.parentNode,
suggestionsSeparator, 5); suggestionsSeparator, 5);
this.showItem("spell-no-suggestions", numsug == 0); this.showItem("spell-no-suggestions", numsug == 0);
} } else {
else
this.showItem("spell-no-suggestions", false); this.showItem("spell-no-suggestions", false);
}
// dictionary list // dictionary list
this.showItem("spell-dictionaries", canSpell && InlineSpellCheckerUI.enabled); this.showItem("spell-dictionaries", canSpell && InlineSpellCheckerUI.enabled);
@ -314,15 +317,14 @@ nsContextMenu.prototype = {
var dictSep = document.getElementById("spell-language-separator"); var dictSep = document.getElementById("spell-language-separator");
InlineSpellCheckerUI.addDictionaryListToMenu(dictMenu, dictSep); InlineSpellCheckerUI.addDictionaryListToMenu(dictMenu, dictSep);
this.showItem("spell-add-dictionaries-main", false); this.showItem("spell-add-dictionaries-main", false);
} } else if (this.onEditableArea) {
else if (this.onEditableArea) {
// when there is no spellchecker but we might be able to spellcheck // when there is no spellchecker but we might be able to spellcheck
// add the add to dictionaries item. This will ensure that people // add the add to dictionaries item. This will ensure that people
// with no dictionaries will be able to download them // with no dictionaries will be able to download them
this.showItem("spell-add-dictionaries-main", true); this.showItem("spell-add-dictionaries-main", true);
} } else {
else
this.showItem("spell-add-dictionaries-main", false); this.showItem("spell-add-dictionaries-main", false);
}
}, },
initClipboardItems: function() { initClipboardItems: function() {
@ -335,8 +337,7 @@ nsContextMenu.prototype = {
this.showItem("context-undo", this.onTextInput); this.showItem("context-undo", this.onTextInput);
this.showItem("context-sep-undo", this.onTextInput); this.showItem("context-sep-undo", this.onTextInput);
this.showItem("context-cut", this.onTextInput); this.showItem("context-cut", this.onTextInput);
this.showItem("context-copy", this.showItem("context-copy", this.isContentSelected || this.onTextInput);
this.isContentSelected || this.onTextInput);
this.showItem("context-paste", this.onTextInput); this.showItem("context-paste", this.onTextInput);
this.showItem("context-delete", this.onTextInput); this.showItem("context-delete", this.onTextInput);
this.showItem("context-sep-paste", this.onTextInput); this.showItem("context-sep-paste", this.onTextInput);
@ -370,7 +371,8 @@ nsContextMenu.prototype = {
this.setItemAttr("context-copyvideourl", "disabled", !this.mediaURL); this.setItemAttr("context-copyvideourl", "disabled", !this.mediaURL);
this.setItemAttr("context-copyaudiourl", "disabled", !this.mediaURL); this.setItemAttr("context-copyaudiourl", "disabled", !this.mediaURL);
this.showItem("context-sep-copyimage", this.onImage || this.showItem("context-sep-copyimage", this.onImage ||
this.onVideo || this.onAudio); this.onVideo ||
this.onAudio);
}, },
initMediaPlayerItems: function() { initMediaPlayerItems: function() {
@ -436,7 +438,7 @@ nsContextMenu.prototype = {
return gDevTools.showToolbox(target, "inspector").then(function(toolbox) { return gDevTools.showToolbox(target, "inspector").then(function(toolbox) {
let inspector = toolbox.getCurrentPanel(); let inspector = toolbox.getCurrentPanel();
this.browser.messageManager.sendAsyncMessage("debug:inspect", {}, {node: this.target}); this.browser.messageManager.sendAsyncMessage("debug:inspect", { }, { node: this.target });
inspector.walker.findInspectingNode().then(nodeFront => { inspector.walker.findInspectingNode().then(nodeFront => {
inspector.selection.setNodeFront(nodeFront, "browser-context-menu"); inspector.selection.setNodeFront(nodeFront, "browser-context-menu");
}); });
@ -488,13 +490,13 @@ nsContextMenu.prototype = {
this.target = aNode; this.target = aNode;
this.browser = this.target.ownerDocument.defaultView this.browser = this.target.ownerDocument.defaultView
.QueryInterface(Ci.nsIInterfaceRequestor) .QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation) .getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell) .QueryInterface(Ci.nsIDocShell)
.chromeEventHandler; .chromeEventHandler;
// Check if we are in a synthetic document (stand alone image, video, etc.). // Check if we are in a synthetic document (stand alone image, video, etc.).
this.inSyntheticDoc = this.target.ownerDocument.mozSyntheticDocument; this.inSyntheticDoc = this.target.ownerDocument.mozSyntheticDocument;
// First, do checks for nodes that never have children. // First, do checks for nodes that never have children.
if (this.target.nodeType == Node.ELEMENT_NODE) { if (this.target.nodeType == Node.ELEMENT_NODE) {
// See if the user clicked on an image. // See if the user clicked on an image.
@ -504,19 +506,19 @@ nsContextMenu.prototype = {
var request = var request =
this.target.getRequest(Ci.nsIImageLoadingContent.CURRENT_REQUEST); this.target.getRequest(Ci.nsIImageLoadingContent.CURRENT_REQUEST);
if (request && (request.imageStatus & request.STATUS_SIZE_AVAILABLE)) if (request && (request.imageStatus & request.STATUS_SIZE_AVAILABLE)) {
this.onLoadedImage = true; this.onLoadedImage = true;
if (request && (request.imageStatus & request.STATUS_LOAD_COMPLETE)) }
if (request && (request.imageStatus & request.STATUS_LOAD_COMPLETE)) {
this.onCompletedImage = true; this.onCompletedImage = true;
}
this.mediaURL = this.target.currentURI.spec; this.mediaURL = this.target.currentURI.spec;
} } else if (this.target instanceof HTMLCanvasElement) {
else if (this.target instanceof HTMLCanvasElement) {
this.onCanvas = true; this.onCanvas = true;
} } else if (this.target instanceof HTMLVideoElement) {
else if (this.target instanceof HTMLVideoElement) {
this.mediaURL = this.target.currentSrc || this.target.src; this.mediaURL = this.target.currentSrc || this.target.src;
// Firefox always creates a HTMLVideoElement when loading an ogg file // Pale Moon always creates a HTMLVideoElement when loading an ogg file
// directly. If the media is actually audio, be smarter and provide a // directly. If the media is actually audio, be smarter and provide a
// context menu with audio operations. // context menu with audio operations.
if (this.target.readyState >= this.target.HAVE_METADATA && if (this.target.readyState >= this.target.HAVE_METADATA &&
@ -525,12 +527,10 @@ nsContextMenu.prototype = {
} else { } else {
this.onVideo = true; this.onVideo = true;
} }
} } else if (this.target instanceof HTMLAudioElement) {
else if (this.target instanceof HTMLAudioElement) {
this.onAudio = true; this.onAudio = true;
this.mediaURL = this.target.currentSrc || this.target.src; this.mediaURL = this.target.currentSrc || this.target.src;
} } else if (this.target instanceof HTMLInputElement ) {
else if (this.target instanceof HTMLInputElement ) {
this.onTextInput = this.isTargetATextBox(this.target); this.onTextInput = this.isTargetATextBox(this.target);
// Allow spellchecking UI on all text and search inputs. // Allow spellchecking UI on all text and search inputs.
if (this.onTextInput && ! this.target.readOnly && if (this.onTextInput && ! this.target.readOnly &&
@ -540,16 +540,14 @@ nsContextMenu.prototype = {
InlineSpellCheckerUI.initFromEvent(aRangeParent, aRangeOffset); InlineSpellCheckerUI.initFromEvent(aRangeParent, aRangeOffset);
} }
this.onKeywordField = this.isTargetAKeywordField(this.target); this.onKeywordField = this.isTargetAKeywordField(this.target);
} } else if (this.target instanceof HTMLTextAreaElement) {
else if (this.target instanceof HTMLTextAreaElement) {
this.onTextInput = true; this.onTextInput = true;
if (!this.target.readOnly) { if (!this.target.readOnly) {
this.onEditableArea = true; this.onEditableArea = true;
InlineSpellCheckerUI.init(this.target.QueryInterface(Ci.nsIDOMNSEditableElement).editor); InlineSpellCheckerUI.init(this.target.QueryInterface(Ci.nsIDOMNSEditableElement).editor);
InlineSpellCheckerUI.initFromEvent(aRangeParent, aRangeOffset); InlineSpellCheckerUI.initFromEvent(aRangeParent, aRangeOffset);
} }
} } else if (this.target instanceof HTMLHtmlElement) {
else if (this.target instanceof HTMLHtmlElement) {
var bodyElt = this.target.ownerDocument.body; var bodyElt = this.target.ownerDocument.body;
if (bodyElt) { if (bodyElt) {
let computedURL; let computedURL;
@ -565,8 +563,7 @@ nsContextMenu.prototype = {
computedURL); computedURL);
} }
} }
} } else if ((this.target instanceof HTMLEmbedElement ||
else if ((this.target instanceof HTMLEmbedElement ||
this.target instanceof HTMLObjectElement || this.target instanceof HTMLObjectElement ||
this.target instanceof HTMLAppletElement) && this.target instanceof HTMLAppletElement) &&
this.target.displayedType == HTMLObjectElement.TYPE_NULL && this.target.displayedType == HTMLObjectElement.TYPE_NULL &&
@ -575,8 +572,7 @@ nsContextMenu.prototype = {
} }
this.canSpellCheck = this._isSpellCheckEnabled(this.target); this.canSpellCheck = this._isSpellCheckEnabled(this.target);
} } else if (this.target.nodeType == Node.TEXT_NODE) {
else if (this.target.nodeType == Node.TEXT_NODE) {
// For text nodes, look at the parent node to determine the spellcheck attribute. // For text nodes, look at the parent node to determine the spellcheck attribute.
this.canSpellCheck = this.target.parentNode && this.canSpellCheck = this.target.parentNode &&
this._isSpellCheckEnabled(this.target); this._isSpellCheckEnabled(this.target);
@ -617,26 +613,24 @@ nsContextMenu.prototype = {
// this.principal.checkMayLoad(this.linkURI, false, true); // this.principal.checkMayLoad(this.linkURI, false, true);
this.linkDownload = elem.download; this.linkDownload = elem.download;
} }
} catch(ex) {
} }
catch (ex) {}
} }
// Background image? Don't bother if we've already found a // Background image? Don't bother if we've already found a
// background image further down the hierarchy. Otherwise, // background image further down the hierarchy. Otherwise,
// we look for the computed background-image style. // we look for the computed background-image style.
if (!this.hasBGImage && if (!this.hasBGImage && !this._hasMultipleBGImages) {
!this._hasMultipleBGImages) {
let bgImgUrl; let bgImgUrl;
try { try {
bgImgUrl = this.getComputedURL(elem, "background-image"); bgImgUrl = this.getComputedURL(elem, "background-image");
this._hasMultipleBGImages = false; this._hasMultipleBGImages = false;
} catch (e) { } catch(e) {
this._hasMultipleBGImages = true; this._hasMultipleBGImages = true;
} }
if (bgImgUrl) { if (bgImgUrl) {
this.hasBGImage = true; this.hasBGImage = true;
this.bgImageURL = makeURLAbsolute(elem.baseURI, this.bgImageURL = makeURLAbsolute(elem.baseURI, bgImgUrl);
bgImgUrl);
} }
} }
} }
@ -648,8 +642,9 @@ nsContextMenu.prototype = {
const NS_MathML = "http://www.w3.org/1998/Math/MathML"; const NS_MathML = "http://www.w3.org/1998/Math/MathML";
if ((this.target.nodeType == Node.TEXT_NODE && if ((this.target.nodeType == Node.TEXT_NODE &&
this.target.parentNode.namespaceURI == NS_MathML) this.target.parentNode.namespaceURI == NS_MathML)
|| (this.target.namespaceURI == NS_MathML)) || (this.target.namespaceURI == NS_MathML)) {
this.onMathML = true; this.onMathML = true;
}
// See if the user clicked in a frame. // See if the user clicked in a frame.
var docDefaultView = this.target.ownerDocument.defaultView; var docDefaultView = this.target.ownerDocument.defaultView;
@ -675,8 +670,7 @@ nsContextMenu.prototype = {
this.getComputedStyle(this.target, "-moz-user-modify") == "read-write") { this.getComputedStyle(this.target, "-moz-user-modify") == "read-write") {
isEditable = true; isEditable = true;
} }
} } catch(ex) {
catch(ex) {
// If someone built with composer disabled, we can't get an editing session. // If someone built with composer disabled, we can't get an editing session.
} }
@ -691,7 +685,7 @@ nsContextMenu.prototype = {
this.inSrcdocFrame = false; this.inSrcdocFrame = false;
this.hasBGImage = false; this.hasBGImage = false;
this.isDesignMode = true; this.isDesignMode = true;
this.onEditableArea = true; this.onEditableArea = true;
InlineSpellCheckerUI.init(editingSession.getEditorForWindow(win)); InlineSpellCheckerUI.init(editingSession.getEditorForWindow(win));
var canSpell = InlineSpellCheckerUI.canSpellCheck && this.canSpellCheck; var canSpell = InlineSpellCheckerUI.canSpellCheck && this.canSpellCheck;
InlineSpellCheckerUI.initFromEvent(aRangeParent, aRangeOffset); InlineSpellCheckerUI.initFromEvent(aRangeParent, aRangeOffset);
@ -706,21 +700,23 @@ nsContextMenu.prototype = {
getComputedStyle: function(aElem, aProp) { getComputedStyle: function(aElem, aProp) {
return aElem.ownerDocument return aElem.ownerDocument
.defaultView .defaultView
.getComputedStyle(aElem, "").getPropertyValue(aProp); .getComputedStyle(aElem, "")
.getPropertyValue(aProp);
}, },
// Returns a "url"-type computed style attribute value, with the url() stripped. // Returns a "url"-type computed style attribute value, with the url() stripped.
getComputedURL: function(aElem, aProp) { getComputedURL: function(aElem, aProp) {
var url = aElem.ownerDocument var url = aElem.ownerDocument
.defaultView.getComputedStyle(aElem, "") .defaultView
.getComputedStyle(aElem, "")
.getPropertyCSSValue(aProp); .getPropertyCSSValue(aProp);
if (url instanceof CSSValueList) { if (url instanceof CSSValueList) {
if (url.length != 1) if (url.length != 1) {
throw "found multiple URLs"; throw "found multiple URLs";
}
url = url[0]; url = url[0];
} }
return url.primitiveType == CSSPrimitiveValue.CSS_URI ? return url.primitiveType == CSSPrimitiveValue.CSS_URI ? url.getStringValue() : null;
url.getStringValue() : null;
}, },
// Returns true if clicked-on link targets a resource that can be saved. // Returns true if clicked-on link targets a resource that can be saved.
@ -728,10 +724,10 @@ nsContextMenu.prototype = {
// We don't do the Right Thing for news/snews yet, so turn them off // We don't do the Right Thing for news/snews yet, so turn them off
// until we do. // until we do.
return this.linkProtocol && !( return this.linkProtocol && !(
this.linkProtocol == "mailto" || this.linkProtocol == "mailto" ||
this.linkProtocol == "javascript" || this.linkProtocol == "javascript" ||
this.linkProtocol == "news" || this.linkProtocol == "news" ||
this.linkProtocol == "snews" ); this.linkProtocol == "snews");
}, },
_isSpellCheckEnabled: function(aNode) { _isSpellCheckEnabled: function(aNode) {
@ -869,8 +865,9 @@ nsContextMenu.prototype = {
this.browser.contentPrincipal, this.browser.contentPrincipal,
Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT); Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT);
if (this.target instanceof Ci.nsIImageLoadingContent) if (this.target instanceof Ci.nsIImageLoadingContent) {
this.target.forceReload(); this.target.forceReload();
}
}, },
// Change current window to the URL of the image, video, or audio. // Change current window to the URL of the image, video, or audio.
@ -886,7 +883,8 @@ nsContextMenu.prototype = {
"This feature cannot be used, because it hasn't found " + "This feature cannot be used, because it hasn't found " +
"an appropriate window."); "an appropriate window.");
} else { } else {
new Promise.resolve({then: function(resolve) { // TODO: This is unreadable. Rewrite it to something more sane.
new Promise.resolve({ then: function(resolve) {
target.toBlob((blob) => { target.toBlob((blob) => {
resolve(win.URL.createObjectURL(blob)); resolve(win.URL.createObjectURL(blob));
}) })
@ -919,9 +917,11 @@ nsContextMenu.prototype = {
let url = uri.QueryInterface(Ci.nsIURL); let url = uri.QueryInterface(Ci.nsIURL);
if (url.fileBaseName) if (url.fileBaseName)
name = decodeURI(url.fileBaseName) + ".jpg"; name = decodeURI(url.fileBaseName) + ".jpg";
} catch (e) { } } catch (e) {
if (!name) }
if (!name) {
name = "snapshot.jpg"; name = "snapshot.jpg";
}
var video = this.target; var video = this.target;
var canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); var canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
canvas.width = video.videoWidth; canvas.width = video.videoWidth;
@ -935,8 +935,9 @@ nsContextMenu.prototype = {
fullScreenVideo: function() { fullScreenVideo: function() {
let video = this.target; let video = this.target;
if (document.mozFullScreenEnabled) if (document.mozFullScreenEnabled) {
video.mozRequestFullScreen(); video.mozRequestFullScreen();
}
}, },
leaveDOMFullScreen: function() { leaveDOMFullScreen: function() {
@ -956,20 +957,24 @@ nsContextMenu.prototype = {
disableSetDesktopBackground: function() { disableSetDesktopBackground: function() {
// Disable the Set as Desktop Background menu item if we're still trying // Disable the Set as Desktop Background menu item if we're still trying
// to load the image or the load failed. // to load the image or the load failed.
if (!(this.target instanceof Ci.nsIImageLoadingContent)) if (!(this.target instanceof Ci.nsIImageLoadingContent)) {
return true; return true;
}
if (("complete" in this.target) && !this.target.complete) if (("complete" in this.target) && !this.target.complete) {
return true; return true;
}
if (this.target.currentURI.schemeIs("javascript")) if (this.target.currentURI.schemeIs("javascript")) {
return true; return true;
}
var request = this.target var request = this.target
.QueryInterface(Ci.nsIImageLoadingContent) .QueryInterface(Ci.nsIImageLoadingContent)
.getRequest(Ci.nsIImageLoadingContent.CURRENT_REQUEST); .getRequest(Ci.nsIImageLoadingContent.CURRENT_REQUEST);
if (!request) if (!request) {
return true; return true;
}
return false; return false;
}, },
@ -977,15 +982,15 @@ nsContextMenu.prototype = {
setDesktopBackground: function() { setDesktopBackground: function() {
// Paranoia: check disableSetDesktopBackground again, in case the // Paranoia: check disableSetDesktopBackground again, in case the
// image changed since the context menu was initiated. // image changed since the context menu was initiated.
if (this.disableSetDesktopBackground()) if (this.disableSetDesktopBackground()) {
return; return;
}
urlSecurityCheck(this.target.currentURI.spec, urlSecurityCheck(this.target.currentURI.spec,
this.target.ownerDocument.nodePrincipal); this.target.ownerDocument.nodePrincipal);
// Confirm since it's annoying if you hit this accidentally. // Confirm since it's annoying if you hit this accidentally.
const kDesktopBackgroundURL = const kDesktopBackgroundURL = "chrome://browser/content/setDesktopBackground.xul";
"chrome://browser/content/setDesktopBackground.xul";
#ifdef XP_MACOSX #ifdef XP_MACOSX
// On Mac, the Set Desktop Background window is not modal. // On Mac, the Set Desktop Background window is not modal.
// Don't open more than one Set Desktop Background window. // Don't open more than one Set Desktop Background window.
@ -995,8 +1000,7 @@ nsContextMenu.prototype = {
if (dbWin) { if (dbWin) {
dbWin.gSetBackground.init(this.target); dbWin.gSetBackground.init(this.target);
dbWin.focus(); dbWin.focus();
} } else {
else {
openDialog(kDesktopBackgroundURL, "", openDialog(kDesktopBackgroundURL, "",
"centerscreen,chrome,dialog=no,dependent,resizable=no", "centerscreen,chrome,dialog=no,dependent,resizable=no",
this.target); this.target);
@ -1025,7 +1029,8 @@ nsContextMenu.prototype = {
// nsIExternalHelperAppService.doContent, which will wait for the // nsIExternalHelperAppService.doContent, which will wait for the
// appropriate MIME-type headers and then prompt the user with a // appropriate MIME-type headers and then prompt the user with a
// file picker // file picker
function saveAsListener() {} function saveAsListener() { }
saveAsListener.prototype = { saveAsListener.prototype = {
extListener: null, extListener: null,
@ -1034,8 +1039,9 @@ nsContextMenu.prototype = {
// if the timer fired, the error status will have been caused by that, // if the timer fired, the error status will have been caused by that,
// and we'll be restarting in onStopRequest, so no reason to notify // and we'll be restarting in onStopRequest, so no reason to notify
// the user // the user
if (aRequest.status == NS_ERROR_SAVE_LINK_AS_TIMEOUT) if (aRequest.status == NS_ERROR_SAVE_LINK_AS_TIMEOUT) {
return; return;
}
timer.cancel(); timer.cancel();
@ -1053,7 +1059,8 @@ nsContextMenu.prototype = {
const promptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"]. const promptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"].
getService(Ci.nsIPromptService); getService(Ci.nsIPromptService);
promptSvc.alert(doc.defaultView, title, msg); promptSvc.alert(doc.defaultView, title, msg);
} catch (ex) {} } catch (ex) {
}
return; return;
} }
@ -1067,26 +1074,25 @@ nsContextMenu.prototype = {
this.extListener.onStartRequest(aRequest, aContext); this.extListener.onStartRequest(aRequest, aContext);
}, },
onStopRequest: function(aRequest, aContext, onStopRequest: function(aRequest, aContext, aStatusCode) {
aStatusCode) {
if (aStatusCode == NS_ERROR_SAVE_LINK_AS_TIMEOUT) { if (aStatusCode == NS_ERROR_SAVE_LINK_AS_TIMEOUT) {
// do it the old fashioned way, which will pick the best filename // do it the old fashioned way, which will pick the best filename
// it can without waiting. // it can without waiting.
saveURL(linkURL, linkText, dialogTitle, bypassCache, false, doc.documentURIObject, doc); saveURL(linkURL, linkText, dialogTitle, bypassCache, false, doc.documentURIObject, doc);
} }
if (this.extListener) if (this.extListener) {
this.extListener.onStopRequest(aRequest, aContext, aStatusCode); this.extListener.onStopRequest(aRequest, aContext, aStatusCode);
}
}, },
onDataAvailable: function(aRequest, aContext, onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount) {
aInputStream,
aOffset, aCount) {
this.extListener.onDataAvailable(aRequest, aContext, aInputStream, this.extListener.onDataAvailable(aRequest, aContext, aInputStream,
aOffset, aCount); aOffset, aCount);
} }
} }
function callbacks() {} function callbacks() { }
callbacks.prototype = { callbacks.prototype = {
getInterface: function(aIID) { getInterface: function(aIID) {
if (aIID.equals(Ci.nsIAuthPrompt) || aIID.equals(Ci.nsIAuthPrompt2)) { if (aIID.equals(Ci.nsIAuthPrompt) || aIID.equals(Ci.nsIAuthPrompt2)) {
@ -1105,7 +1111,8 @@ nsContextMenu.prototype = {
// if it we don't have the headers after a short time, the user // if it we don't have the headers after a short time, the user
// won't have received any feedback from their click. that's bad. so // won't have received any feedback from their click. that's bad. so
// we give up waiting for the filename. // we give up waiting for the filename.
function timerCallback() {} function timerCallback() { }
timerCallback.prototype = { timerCallback.prototype = {
notify: function(aTimer) { notify: function(aTimer) {
channel.cancel(NS_ERROR_SAVE_LINK_AS_TIMEOUT); channel.cancel(NS_ERROR_SAVE_LINK_AS_TIMEOUT);
@ -1114,15 +1121,15 @@ nsContextMenu.prototype = {
} }
// setting up a new channel for 'right click - save link as ...' // setting up a new channel for 'right click - save link as ...'
var channel = NetUtil.newChannel({ var channel = NetUtil.newChannel(
uri: makeURI(linkURL), { uri: makeURI(linkURL),
loadingPrincipal: this.target.ownerDocument.nodePrincipal, loadingPrincipal: this.target.ownerDocument.nodePrincipal,
contentPolicyType: Ci.nsIContentPolicy.TYPE_SAVEAS_DOWNLOAD, contentPolicyType: Ci.nsIContentPolicy.TYPE_SAVEAS_DOWNLOAD,
securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS, securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS });
});
if (linkDownload) if (linkDownload) {
channel.contentDispositionFilename = linkDownload; channel.contentDispositionFilename = linkDownload;
}
if (channel instanceof Ci.nsIPrivateBrowsingChannel) { if (channel instanceof Ci.nsIPrivateBrowsingChannel) {
let docIsPrivate = PrivateBrowsingUtils.isWindowPrivate(doc.defaultView); let docIsPrivate = PrivateBrowsingUtils.isWindowPrivate(doc.defaultView);
channel.setPrivate(docIsPrivate); channel.setPrivate(docIsPrivate);
@ -1131,26 +1138,27 @@ nsContextMenu.prototype = {
let flags = Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS; let flags = Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS;
if (bypassCache) if (bypassCache) {
flags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; flags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
}
if (channel instanceof Ci.nsICachingChannel) if (channel instanceof Ci.nsICachingChannel) {
flags |= Ci.nsICachingChannel.LOAD_BYPASS_LOCAL_CACHE_IF_BUSY; flags |= Ci.nsICachingChannel.LOAD_BYPASS_LOCAL_CACHE_IF_BUSY;
}
channel.loadFlags |= flags; channel.loadFlags |= flags;
if (channel instanceof Ci.nsIHttpChannel) { if (channel instanceof Ci.nsIHttpChannel) {
channel.referrer = doc.documentURIObject; channel.referrer = doc.documentURIObject;
if (channel instanceof Ci.nsIHttpChannelInternal) if (channel instanceof Ci.nsIHttpChannelInternal) {
channel.forceAllowThirdPartyCookie = true; channel.forceAllowThirdPartyCookie = true;
}
} }
// fallback to the old way if we don't see the headers quickly // fallback to the old way if we don't see the headers quickly
var timeToWait = var timeToWait = gPrefService.getIntPref("browser.download.saveLinkAsFilenameTimeout");
gPrefService.getIntPref("browser.download.saveLinkAsFilenameTimeout");
var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.initWithCallback(new timerCallback(), timeToWait, timer.initWithCallback(new timerCallback(), timeToWait, timer.TYPE_ONE_SHOT);
timer.TYPE_ONE_SHOT);
// kick off the channel with our proxy object as the listener // kick off the channel with our proxy object as the listener
channel.asyncOpen2(new saveAsListener()); channel.asyncOpen2(new saveAsListener());
@ -1161,10 +1169,11 @@ nsContextMenu.prototype = {
var doc = this.target.ownerDocument; var doc = this.target.ownerDocument;
var linkText; var linkText;
// If selected text is found to match valid URL pattern. // If selected text is found to match valid URL pattern.
if (this.onPlainTextLink) if (this.onPlainTextLink) {
linkText = document.commandDispatcher.focusedWindow.getSelection().toString().trim(); linkText = document.commandDispatcher.focusedWindow.getSelection().toString().trim();
else } else {
linkText = this.linkText(); linkText = this.linkText();
}
urlSecurityCheck(this.linkURL, doc.nodePrincipal); urlSecurityCheck(this.linkURL, doc.nodePrincipal);
this.saveHelper(this.linkURL, linkText, null, true, doc, this.saveHelper(this.linkURL, linkText, null, true, doc,
@ -1178,8 +1187,9 @@ nsContextMenu.prototype = {
// Backwards-compatibility wrapper // Backwards-compatibility wrapper
saveImage : function() { saveImage : function() {
if (this.onCanvas || this.onImage) if (this.onCanvas || this.onImage) {
this.saveMedia(); this.saveMedia();
}
}, },
// Save URL of the clicked upon image, video, or audio. // Save URL of the clicked upon image, video, or audio.
@ -1197,7 +1207,8 @@ nsContextMenu.prototype = {
"This feature cannot be used, because it hasn't found " + "This feature cannot be used, because it hasn't found " +
"an appropriate window."); "an appropriate window.");
} else { } else {
new Promise.resolve({then: function(resolve) { // TODO: This is unreadable. Rewrite it to something more sane.
new Promise.resolve({ then: function(resolve) {
target.toBlob((blob) => { target.toBlob((blob) => {
resolve(win.URL.createObjectURL(blob)); resolve(win.URL.createObjectURL(blob));
}) })
@ -1253,16 +1264,15 @@ nsContextMenu.prototype = {
// in case the address is not ASCII. // in case the address is not ASCII.
try { try {
var characterSet = this.target.ownerDocument.characterSet; var characterSet = this.target.ownerDocument.characterSet;
const textToSubURI = Cc["@mozilla.org/intl/texttosuburi;1"]. const textToSubURI = Cc["@mozilla.org/intl/texttosuburi;1"]
getService(Ci.nsITextToSubURI); .getService(Ci.nsITextToSubURI);
addresses = textToSubURI.unEscapeURIForUI(characterSet, addresses); addresses = textToSubURI.unEscapeURIForUI(characterSet, addresses);
} } catch(ex) {
catch(ex) {
// Do nothing. // Do nothing.
} }
var clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"]. var clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"]
getService(Ci.nsIClipboardHelper); .getService(Ci.nsIClipboardHelper);
clipboard.copyString(addresses, document); clipboard.copyString(addresses, document);
}, },
@ -1273,9 +1283,11 @@ nsContextMenu.prototype = {
// Show/hide one item (specified via name or the item element itself). // Show/hide one item (specified via name or the item element itself).
showItem: function(aItemOrId, aShow) { showItem: function(aItemOrId, aShow) {
var item = aItemOrId.constructor == String ? var item = aItemOrId.constructor == String ?
document.getElementById(aItemOrId) : aItemOrId; document.getElementById(aItemOrId) :
if (item) aItemOrId;
if (item) {
item.hidden = !aShow; item.hidden = !aShow;
}
}, },
// Set given attribute of specified context-menu item. If the // Set given attribute of specified context-menu item. If the
@ -1287,8 +1299,7 @@ nsContextMenu.prototype = {
if (aVal == null) { if (aVal == null) {
// null indicates attr should be removed. // null indicates attr should be removed.
elem.removeAttribute(aAttr); elem.removeAttribute(aAttr);
} } else {
else {
// Set attr=val. // Set attr=val.
elem.setAttribute(aAttr, aVal); elem.setAttribute(aAttr, aVal);
} }
@ -1299,10 +1310,11 @@ nsContextMenu.prototype = {
// (such as a broadcaster). // (such as a broadcaster).
setItemAttrFromNode: function(aItem_id, aAttr, aOther_id) { setItemAttrFromNode: function(aItem_id, aAttr, aOther_id) {
var elem = document.getElementById(aOther_id); var elem = document.getElementById(aOther_id);
if (elem && elem.getAttribute(aAttr) == "true") if (elem && elem.getAttribute(aAttr) == "true") {
this.setItemAttr(aItem_id, aAttr, "true"); this.setItemAttr(aItem_id, aAttr, "true");
else } else {
this.setItemAttr(aItem_id, aAttr, null); this.setItemAttr(aItem_id, aAttr, null);
}
}, },
// Temporary workaround for DOM api not yet implemented by XUL nodes. // Temporary workaround for DOM api not yet implemented by XUL nodes.
@ -1342,8 +1354,7 @@ nsContextMenu.prototype = {
getLinkURI: function() { getLinkURI: function() {
try { try {
return makeURI(this.linkURL); return makeURI(this.linkURL);
} } catch(ex) {
catch (ex) {
// e.g. empty URL string // e.g. empty URL string
} }
@ -1351,8 +1362,10 @@ nsContextMenu.prototype = {
}, },
getLinkProtocol: function() { getLinkProtocol: function() {
if (this.linkURI) if (this.linkURI) {
return this.linkURI.scheme; // can be |undefined| // can be |undefined|
return this.linkURI.scheme;
}
return null; return null;
}, },
@ -1364,8 +1377,9 @@ nsContextMenu.prototype = {
text = this.link.getAttribute("title"); text = this.link.getAttribute("title");
if (!text || !text.match(/\S/)) { if (!text || !text.match(/\S/)) {
text = this.link.getAttribute("alt"); text = this.link.getAttribute("alt");
if (!text || !text.match(/\S/)) if (!text || !text.match(/\S/)) {
text = this.linkURL; text = this.linkURL;
}
} }
} }
@ -1390,25 +1404,28 @@ nsContextMenu.prototype = {
let ownerDoc = aNode.ownerDocument; let ownerDoc = aNode.ownerDocument;
return ownerDoc.defaultView && return ownerDoc.defaultView &&
ownerDoc.defaultView ownerDoc.defaultView
.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindowUtils) .getInterface(Components.interfaces.nsIDOMWindowUtils)
.isNodeDisabledForEvents(aNode); .isNodeDisabledForEvents(aNode);
}, },
isTargetATextBox: function(node) { isTargetATextBox: function(node) {
if (node instanceof HTMLInputElement) if (node instanceof HTMLInputElement) {
return node.mozIsTextField(false); return node.mozIsTextField(false);
}
return (node instanceof HTMLTextAreaElement); return (node instanceof HTMLTextAreaElement);
}, },
isTargetAKeywordField: function(aNode) { isTargetAKeywordField: function(aNode) {
if (!(aNode instanceof HTMLInputElement)) if (!(aNode instanceof HTMLInputElement)) {
return false; return false;
}
var form = aNode.form; var form = aNode.form;
if (!form || aNode.type == "password") if (!form || aNode.type == "password") {
return false; return false;
}
var method = form.method.toUpperCase(); var method = form.method.toUpperCase();
@ -1423,7 +1440,8 @@ nsContextMenu.prototype = {
// POST multipart/form-data NO // POST multipart/form-data NO
// POST everything else YES // POST everything else YES
return (method == "GET" || method == "") || return (method == "GET" || method == "") ||
(form.enctype != "text/plain") && (form.enctype != "multipart/form-data"); ((form.enctype != "text/plain") &&
(form.enctype != "multipart/form-data"));
}, },
// Determines whether or not the separator with the specified ID should be // Determines whether or not the separator with the specified ID should be
@ -1434,8 +1452,9 @@ nsContextMenu.prototype = {
if (separator) { if (separator) {
var sibling = separator.previousSibling; var sibling = separator.previousSibling;
while (sibling && sibling.localName != "menuseparator") { while (sibling && sibling.localName != "menuseparator") {
if (!sibling.hidden) if (!sibling.hidden) {
return true; return true;
}
sibling = sibling.previousSibling; sibling = sibling.previousSibling;
} }
} }
@ -1449,15 +1468,15 @@ nsContextMenu.prototype = {
try { try {
locale = gPrefService.getComplexValue("intl.accept_languages", locale = gPrefService.getComplexValue("intl.accept_languages",
Ci.nsIPrefLocalizedString).data; Ci.nsIPrefLocalizedString).data;
} catch(e) {
} }
catch (e) { }
var version = "-"; var version = "-";
try { try {
version = Cc["@mozilla.org/xre/app-info;1"]. version = Cc["@mozilla.org/xre/app-info;1"].
getService(Ci.nsIXULAppInfo).version; getService(Ci.nsIXULAppInfo).version;
} catch(e) {
} }
catch (e) { }
uri = uri.replace(/%LOCALE%/, escape(locale)).replace(/%VERSION%/, version); uri = uri.replace(/%LOCALE%/, escape(locale)).replace(/%VERSION%/, version);
@ -1474,12 +1493,12 @@ nsContextMenu.prototype = {
bookmarkLink: function() { bookmarkLink: function() {
var linkText; var linkText;
// If selected text is found to match valid URL pattern. // If selected text is found to match valid URL pattern.
if (this.onPlainTextLink) if (this.onPlainTextLink) {
linkText = document.commandDispatcher.focusedWindow.getSelection().toString().trim(); linkText = document.commandDispatcher.focusedWindow.getSelection().toString().trim();
else } else {
linkText = this.linkText(); linkText = this.linkText();
window.top.PlacesCommandHook.bookmarkLink(PlacesUtils.bookmarksMenuFolderId, this.linkURL, }
linkText); window.top.PlacesCommandHook.bookmarkLink(PlacesUtils.bookmarksMenuFolderId, this.linkURL, linkText);
}, },
addBookmarkForFrame: function() { addBookmarkForFrame: function() {
@ -1490,21 +1509,20 @@ nsContextMenu.prototype = {
if (itemId == -1) { if (itemId == -1) {
var title = doc.title; var title = doc.title;
var description = PlacesUIUtils.getDescriptionFromDocument(doc); var description = PlacesUIUtils.getDescriptionFromDocument(doc);
PlacesUIUtils.showBookmarkDialog({ action: "add" PlacesUIUtils.showBookmarkDialog({ action: "add",
, type: "bookmark" type: "bookmark",
, uri: uri uri: uri,
, title: title title: title,
, description: description description: description,
, hiddenRows: [ "description" hiddenRows: [ "description"
, "location" , "location"
, "loadInSidebar" , "loadInSidebar"
, "keyword" ] , "keyword" ]
}, window.top); }, window.top);
} } else {
else { PlacesUIUtils.showBookmarkDialog({ action: "edit",
PlacesUIUtils.showBookmarkDialog({ action: "edit" type: "bookmark",
, type: "bookmark" itemId: itemId
, itemId: itemId
}, window.top); }, window.top);
} }
}, },
@ -1563,14 +1581,15 @@ nsContextMenu.prototype = {
}, },
copyMediaLocation : function() { copyMediaLocation : function() {
var clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"]. var clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"]
getService(Ci.nsIClipboardHelper); .getService(Ci.nsIClipboardHelper);
clipboard.copyString(this.mediaURL, document); clipboard.copyString(this.mediaURL, document);
}, },
get imageURL() { get imageURL() {
if (this.onImage) if (this.onImage) {
return this.mediaURL; return this.mediaURL;
}
return ""; return "";
}, },
@ -1582,18 +1601,20 @@ nsContextMenu.prototype = {
// Store searchTerms in context menu item so we know what to search onclick // Store searchTerms in context menu item so we know what to search onclick
menuItem.searchTerms = selectedText; menuItem.searchTerms = selectedText;
if (selectedText.length > 15) if (selectedText.length > 15) {
selectedText = selectedText.substr(0,15) + this.ellipsis; selectedText = selectedText.substr(0,15) + this.ellipsis;
}
// Use the current engine if the search bar is visible, the default // Use the current engine if the search bar is visible, the default
// engine otherwise. // engine otherwise.
var engineName = ""; var engineName = "";
var ss = Cc["@mozilla.org/browser/search-service;1"]. var ss = Cc["@mozilla.org/browser/search-service;1"]
getService(Ci.nsIBrowserSearchService); .getService(Ci.nsIBrowserSearchService);
if (isElementVisible(BrowserSearch.searchBar)) if (isElementVisible(BrowserSearch.searchBar)) {
engineName = ss.currentEngine.name; engineName = ss.currentEngine.name;
else } else {
engineName = ss.defaultEngine.name; engineName = ss.defaultEngine.name;
}
// format "Search <engine> for <selection>" string to show in menu // format "Search <engine> for <selection>" string to show in menu
var menuLabel = gNavigatorBundle.getFormattedString("contextMenuSearch", var menuLabel = gNavigatorBundle.getFormattedString("contextMenuSearch",

View file

@ -5,62 +5,65 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var browser; var browser;
var dialog = {}; var dialog = { };
var pref = null; var pref = null;
var openLocationModule = {}; var openLocationModule = { };
try { try {
pref = Components.classes["@mozilla.org/preferences-service;1"] pref = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch); .getService(Components.interfaces.nsIPrefBranch);
} catch (ex) { } catch(ex) {
// not critical, remain silent // not critical, remain silent
} }
Components.utils.import("resource:///modules/openLocationLastURL.jsm", openLocationModule); Components.utils.import("resource:///modules/openLocationLastURL.jsm", openLocationModule);
var gOpenLocationLastURL = new openLocationModule.OpenLocationLastURL(window.opener); var gOpenLocationLastURL = new openLocationModule.OpenLocationLastURL(window.opener);
function onLoad() function onLoad() {
{
dialog.input = document.getElementById("dialog.input"); dialog.input = document.getElementById("dialog.input");
dialog.open = document.documentElement.getButton("accept"); dialog.open = document.documentElement.getButton("accept");
dialog.openWhereList = document.getElementById("openWhereList"); dialog.openWhereList = document.getElementById("openWhereList");
dialog.openTopWindow = document.getElementById("currentWindow"); dialog.openTopWindow = document.getElementById("currentWindow");
dialog.bundle = document.getElementById("openLocationBundle"); dialog.bundle = document.getElementById("openLocationBundle");
if ("arguments" in window && window.arguments.length >= 1) if ("arguments" in window && window.arguments.length >= 1) {
browser = window.arguments[0]; browser = window.arguments[0];
}
dialog.openWhereList.selectedItem = dialog.openTopWindow; dialog.openWhereList.selectedItem = dialog.openTopWindow;
if (pref) { if (pref) {
try { try {
var useAutoFill = pref.getBoolPref("browser.urlbar.autoFill"); var useAutoFill = pref.getBoolPref("browser.urlbar.autoFill");
if (useAutoFill) if (useAutoFill) {
dialog.input.setAttribute("completedefaultindex", "true"); dialog.input.setAttribute("completedefaultindex", "true");
} catch (ex) {} }
} catch(ex) {
}
try { try {
var value = pref.getIntPref("general.open_location.last_window_choice"); var value = pref.getIntPref("general.open_location.last_window_choice");
var element = dialog.openWhereList.getElementsByAttribute("value", value)[0]; var element = dialog.openWhereList.getElementsByAttribute("value", value)[0];
if (element) if (element) {
dialog.openWhereList.selectedItem = element; dialog.openWhereList.selectedItem = element;
}
dialog.input.value = gOpenLocationLastURL.value; dialog.input.value = gOpenLocationLastURL.value;
} catch(ex) {
} }
catch(ex) {
if (dialog.input.value) {
// XXX should probably be done automatically
dialog.input.select();
} }
if (dialog.input.value)
dialog.input.select(); // XXX should probably be done automatically
} }
doEnabling(); doEnabling();
} }
function doEnabling() function doEnabling() {
{
dialog.open.disabled = !dialog.input.value; dialog.open.disabled = !dialog.input.value;
} }
function open() function open() {
{
var openData = { var openData = {
"url": null, "url": null,
"postData": null, "postData": null,
@ -83,8 +86,7 @@ function open()
return false; return false;
} }
function openLocation(openData) function openLocation(openData) {
{
try { try {
// Whichever target we use for the load, we allow third-party services to // Whichever target we use for the load, we allow third-party services to
// fix up the URI // fix up the URI
@ -93,10 +95,10 @@ function openLocation(openData)
var webNav = Components.interfaces.nsIWebNavigation; var webNav = Components.interfaces.nsIWebNavigation;
var flags = webNav.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP | var flags = webNav.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
webNav.LOAD_FLAGS_FIXUP_SCHEME_TYPOS; webNav.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
if (!openData.mayInheritPrincipal) if (!openData.mayInheritPrincipal) {
flags |= webNav.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL; flags |= webNav.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL;
browser.gBrowser.loadURIWithFlags( }
openData.url, flags, null, null, openData.postData); browser.gBrowser.loadURIWithFlags(openData.url, flags, null, null, openData.postData);
break; break;
case "1": case "1":
window.opener.delayedOpenWindow(getBrowserURL(), "all,dialog=no", window.opener.delayedOpenWindow(getBrowserURL(), "all,dialog=no",
@ -104,16 +106,15 @@ function openLocation(openData)
null, null, true); null, null, true);
break; break;
case "3": case "3":
browser.delayedOpenTab( browser.delayedOpenTab(openData.url, null, null, openData.postData, true);
openData.url, null, null, openData.postData, true);
break; break;
} }
} catch (ex) {} } catch(ex) {
}
if (pref) { if (pref) {
gOpenLocationLastURL.value = dialog.input.value; gOpenLocationLastURL.value = dialog.input.value;
pref.setIntPref( pref.setIntPref("general.open_location.last_window_choice", dialog.openWhereList.value);
"general.open_location.last_window_choice", dialog.openWhereList.value);
} }
window.close(); window.close();
@ -129,10 +130,11 @@ const nsIFilePicker = Components.interfaces.nsIFilePicker;
function onChooseFile() function onChooseFile()
{ {
try { try {
let fp = Components.classes["@mozilla.org/filepicker;1"]. let fp = Components.classes["@mozilla.org/filepicker;1"]
createInstance(nsIFilePicker); .createInstance(nsIFilePicker);
let fpCallback = function fpCallback_done(aResult) { let fpCallback = function fpCallback_done(aResult) {
if (aResult == nsIFilePicker.returnOK && fp.fileURL.spec && if (aResult == nsIFilePicker.returnOK &&
fp.fileURL.spec &&
fp.fileURL.spec.length > 0) { fp.fileURL.spec.length > 0) {
dialog.input.value = fp.fileURL.spec; dialog.input.value = fp.fileURL.spec;
} }
@ -145,6 +147,6 @@ function onChooseFile()
nsIFilePicker.filterImages | nsIFilePicker.filterXML | nsIFilePicker.filterImages | nsIFilePicker.filterXML |
nsIFilePicker.filterHTML); nsIFilePicker.filterHTML);
fp.open(fpCallback); fp.open(fpCallback);
} catch (ex) { } catch(ex) {
} }
} }

View file

@ -5,88 +5,92 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var padlock_PadLock = var padlock_PadLock =
{ {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener, QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
Ci.nsISupportsWeakReference]), Ci.nsISupportsWeakReference]),
onButtonClick: function(event) { onButtonClick: function(event) {
event.stopPropagation(); event.stopPropagation();
gIdentityHandler.handleMoreInfoClick(event); gIdentityHandler.handleMoreInfoClick(event);
}, },
onStateChange: function() {}, onStateChange: function() { },
onProgressChange: function() {}, onProgressChange: function() { },
onLocationChange: function() {}, onLocationChange: function() { },
onStatusChange: function() {}, onStatusChange: function() { },
onSecurityChange: function(aCallerWebProgress, aRequestWithState, aState) { onSecurityChange: function(aCallerWebProgress, aRequestWithState, aState) {
// aState is defined as a bitmask that may be extended in the future. // aState is defined as a bitmask that may be extended in the future.
// We filter out any unknown bits before testing for known values. // We filter out any unknown bits before testing for known values.
const wpl = Ci.nsIWebProgressListener; const wpl = Ci.nsIWebProgressListener;
const wpl_security_bits = wpl.STATE_IS_SECURE | const wpl_security_bits = wpl.STATE_IS_SECURE |
wpl.STATE_IS_BROKEN | wpl.STATE_IS_BROKEN |
wpl.STATE_IS_INSECURE | wpl.STATE_IS_INSECURE |
wpl.STATE_IDENTITY_EV_TOPLEVEL | wpl.STATE_IDENTITY_EV_TOPLEVEL |
wpl.STATE_SECURE_HIGH | wpl.STATE_SECURE_HIGH |
wpl.STATE_SECURE_MED | wpl.STATE_SECURE_MED |
wpl.STATE_SECURE_LOW; wpl.STATE_SECURE_LOW;
var level; var level;
var is_insecure; var is_insecure;
var highlight_urlbar = false; var highlight_urlbar = false;
switch (aState & wpl_security_bits) { switch (aState & wpl_security_bits) {
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH | wpl.STATE_IDENTITY_EV_TOPLEVEL: case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH | wpl.STATE_IDENTITY_EV_TOPLEVEL:
level = "ev"; level = "ev";
is_insecure = ""; is_insecure = "";
highlight_urlbar = true; highlight_urlbar = true;
break; break;
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH: case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH:
level = "high"; level = "high";
is_insecure = ""; is_insecure = "";
highlight_urlbar = true; highlight_urlbar = true;
break; break;
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_MED: case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_MED:
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW: case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW:
level = "low"; level = "low";
is_insecure = "insecure"; is_insecure = "insecure";
break; break;
case wpl.STATE_IS_BROKEN | wpl.STATE_SECURE_LOW: case wpl.STATE_IS_BROKEN | wpl.STATE_SECURE_LOW:
level = "mixed"; level = "mixed";
is_insecure = "insecure"; is_insecure = "insecure";
highlight_urlbar = true; highlight_urlbar = true;
break; break;
case wpl.STATE_IS_BROKEN: case wpl.STATE_IS_BROKEN:
level = "broken"; level = "broken";
is_insecure = "insecure"; is_insecure = "insecure";
highlight_urlbar = true; highlight_urlbar = true;
break; break;
default: // should not be reached default: // should not be reached
level = null; level = null;
is_insecure = "insecure"; is_insecure = "insecure";
} }
try { try {
var proto = gBrowser.contentWindow.location.protocol; var proto = gBrowser.contentWindow.location.protocol;
if (proto == "about:" || proto == "chrome:" || proto == "file:" ) { if (proto == "about:" || proto == "chrome:" || proto == "file:" ) {
// do not warn when using local protocols // do not warn when using local protocols
is_insecure = false; is_insecure = false;
} }
} } catch(ex) {
catch (ex) {} }
let ub = document.getElementById("urlbar"); let ub = document.getElementById("urlbar");
if (ub) { // Only call if URL bar is present. if (ub) {
if (highlight_urlbar) { // Only call if URL bar is present.
ub.setAttribute("security_level", level); if (highlight_urlbar) {
} else { ub.setAttribute("security_level", level);
ub.removeAttribute("security_level"); } else {
} ub.removeAttribute("security_level");
} }
}
try { // URL bar may be hidden try { // URL bar may be hidden
padlock_PadLock.setPadlockLevel("padlock-ib", level); padlock_PadLock.setPadlockLevel("padlock-ib", level);
padlock_PadLock.setPadlockLevel("padlock-ib-left", level); padlock_PadLock.setPadlockLevel("padlock-ib-left", level);
padlock_PadLock.setPadlockLevel("padlock-ub-right", level); padlock_PadLock.setPadlockLevel("padlock-ub-right", level);
} catch(e) {} } catch(e) {
padlock_PadLock.setPadlockLevel("padlock-sb", level); }
padlock_PadLock.setPadlockLevel("padlock-tab", level);
}, padlock_PadLock.setPadlockLevel("padlock-sb", level);
padlock_PadLock.setPadlockLevel("padlock-tab", level);
},
setPadlockLevel: function(item, level) { setPadlockLevel: function(item, level) {
let secbut = document.getElementById(item); let secbut = document.getElementById(item);
var sectooltip = ""; var sectooltip = "";
@ -120,7 +124,9 @@ var padlock_PadLock =
} }
secbut.setAttribute("tooltiptext", sectooltip); secbut.setAttribute("tooltiptext", sectooltip);
}, },
prefbranch : null, prefbranch : null,
onLoad: function() { onLoad: function() {
gBrowser.addProgressListener(padlock_PadLock); gBrowser.addProgressListener(padlock_PadLock);
@ -148,40 +154,32 @@ var padlock_PadLock =
if (prefval == 2) { if (prefval == 2) {
position = "ib-left"; position = "ib-left";
padstyle = "modern"; padstyle = "modern";
} } else if (prefval == 3) {
else if (prefval == 3) {
position = "ub-right"; position = "ub-right";
padstyle = "modern"; padstyle = "modern";
} } else if (prefval == 4) {
else if (prefval == 4) {
position = "statbar"; position = "statbar";
padstyle = "modern"; padstyle = "modern";
} } else if (prefval == 5) {
else if (prefval == 5) {
position = "tabs-bar"; position = "tabs-bar";
padstyle = "modern"; padstyle = "modern";
} } else if (prefval == 6) {
else if (prefval == 6) {
position = "ib-trans-bg"; position = "ib-trans-bg";
padstyle = "classic"; padstyle = "classic";
} } else if (prefval == 7) {
else if (prefval == 7) {
position = "ib-left"; position = "ib-left";
padstyle = "classic"; padstyle = "classic";
} } else if (prefval == 8) {
else if (prefval == 8) {
position = "ub-right"; position = "ub-right";
padstyle = "classic"; padstyle = "classic";
} } else if (prefval == 9) {
else if (prefval == 9) {
position = "statbar"; position = "statbar";
padstyle = "classic"; padstyle = "classic";
} } else if (prefval == 10) {
else if (prefval == 10) {
position = "tabs-bar"; position = "tabs-bar";
padstyle = "classic"; padstyle = "classic";
} } else {
else { // 1 or anything else_ default // 1 or anything else_ default
position = "ib-trans-bg"; position = "ib-trans-bg";
padstyle = "modern"; padstyle = "modern";
} }
@ -198,12 +196,15 @@ var padlock_PadLock =
case 1: case 1:
colshow = "secure-only"; colshow = "secure-only";
break; break;
default: default:
colshow = ""; // 0 or anything else: no shading // 0 or anything else: no shading
colshow = "";
} }
try { // URL bar may be hidden try {
// XXX should probably be done automatically
document.getElementById("urlbar").setAttribute("https_color", colshow); document.getElementById("urlbar").setAttribute("https_color", colshow);
} catch(e) {} } catch(e) {
}
var lockenabled = padlock_PadLock.prefbranch.getBoolPref("shown"); var lockenabled = padlock_PadLock.prefbranch.getBoolPref("shown");
var padshow = ""; var padshow = "";
@ -215,7 +216,9 @@ var padlock_PadLock =
document.getElementById("padlock-ib").setAttribute("padshow", padshow); document.getElementById("padlock-ib").setAttribute("padshow", padshow);
document.getElementById("padlock-ib-left").setAttribute("padshow", padshow); document.getElementById("padlock-ib-left").setAttribute("padshow", padshow);
document.getElementById("padlock-ub-right").setAttribute("padshow", padshow); document.getElementById("padlock-ub-right").setAttribute("padshow", padshow);
} catch(e) {} } catch(e) {
}
document.getElementById("padlock-sb").setAttribute("padshow", padshow); document.getElementById("padlock-sb").setAttribute("padshow", padshow);
document.getElementById("padlock-tab").setAttribute("padshow", padshow); document.getElementById("padlock-tab").setAttribute("padshow", padshow);
@ -223,7 +226,9 @@ var padlock_PadLock =
document.getElementById("padlock-ib").setAttribute("padstyle", padstyle); document.getElementById("padlock-ib").setAttribute("padstyle", padstyle);
document.getElementById("padlock-ib-left").setAttribute("padstyle", padstyle); document.getElementById("padlock-ib-left").setAttribute("padstyle", padstyle);
document.getElementById("padlock-ub-right").setAttribute("padstyle", padstyle); document.getElementById("padlock-ub-right").setAttribute("padstyle", padstyle);
} catch(e) {} } catch(e) {
}
document.getElementById("padlock-sb").setAttribute("padstyle", padstyle); document.getElementById("padlock-sb").setAttribute("padstyle", padstyle);
document.getElementById("padlock-tab").setAttribute("padstyle", padstyle); document.getElementById("padlock-tab").setAttribute("padstyle", padstyle);

View file

@ -10,31 +10,30 @@ Cu.import("resource://gre/modules/AddonManager.jsm");
function restartApp() { function restartApp() {
let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"] let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
.getService(Ci.nsIAppStartup); .getService(Ci.nsIAppStartup);
appStartup.quit(Ci.nsIAppStartup.eForceQuit | Ci.nsIAppStartup.eRestart); appStartup.quit(Ci.nsIAppStartup.eForceQuit | Ci.nsIAppStartup.eRestart);
} }
function clearAllPrefs() { function clearAllPrefs() {
var prefService = Cc["@mozilla.org/preferences-service;1"] var prefService = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService); .getService(Ci.nsIPrefService);
prefService.resetUserPrefs(); prefService.resetUserPrefs();
// Remove the pref-overrides dir, if it exists // Remove the pref-overrides dir, if it exists
try { try {
var fileLocator = Cc["@mozilla.org/file/directory_service;1"] var fileLocator = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties); .getService(Ci.nsIProperties);
const NS_APP_PREFS_OVERRIDE_DIR = "PrefDOverride"; const NS_APP_PREFS_OVERRIDE_DIR = "PrefDOverride";
var prefOverridesDir = fileLocator.get(NS_APP_PREFS_OVERRIDE_DIR, var prefOverridesDir = fileLocator.get(NS_APP_PREFS_OVERRIDE_DIR, Ci.nsIFile);
Ci.nsIFile);
prefOverridesDir.remove(true); prefOverridesDir.remove(true);
} catch (ex) { } catch(ex) {
Components.utils.reportError(ex); Components.utils.reportError(ex);
} }
} }
function restoreDefaultBookmarks() { function restoreDefaultBookmarks() {
var prefBranch = Cc["@mozilla.org/preferences-service;1"] var prefBranch = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefBranch); .getService(Ci.nsIPrefBranch);
prefBranch.setBoolPref("browser.bookmarks.restore_default_bookmarks", true); prefBranch.setBoolPref("browser.bookmarks.restore_default_bookmarks", true);
} }
@ -42,7 +41,7 @@ function deleteLocalstore() {
const nsIDirectoryServiceContractID = "@mozilla.org/file/directory_service;1"; const nsIDirectoryServiceContractID = "@mozilla.org/file/directory_service;1";
const nsIProperties = Ci.nsIProperties; const nsIProperties = Ci.nsIProperties;
var directoryService = Cc[nsIDirectoryServiceContractID] var directoryService = Cc[nsIDirectoryServiceContractID]
.getService(nsIProperties); .getService(nsIProperties);
// Local store file // Local store file
var localstoreFile = directoryService.get("LStoreS", Components.interfaces.nsIFile); var localstoreFile = directoryService.get("LStoreS", Components.interfaces.nsIFile);
// XUL store file // XUL store file
@ -68,8 +67,7 @@ function disableAddons() {
const DEFAULT_THEME_ID = "{972ce4c6-7e08-4474-a285-3208198ce6fd}"; const DEFAULT_THEME_ID = "{972ce4c6-7e08-4474-a285-3208198ce6fd}";
if (aAddon.id == DEFAULT_THEME_ID) if (aAddon.id == DEFAULT_THEME_ID)
aAddon.userDisabled = false; aAddon.userDisabled = false;
} } else {
else {
aAddon.userDisabled = true; aAddon.userDisabled = true;
} }
}); });
@ -80,21 +78,25 @@ function disableAddons() {
function restoreDefaultSearchEngines() { function restoreDefaultSearchEngines() {
var searchService = Cc["@mozilla.org/browser/search-service;1"] var searchService = Cc["@mozilla.org/browser/search-service;1"]
.getService(Ci.nsIBrowserSearchService); .getService(Ci.nsIBrowserSearchService);
searchService.restoreDefaultEngines(); searchService.restoreDefaultEngines();
} }
function onOK() { function onOK() {
try { try {
if (document.getElementById("resetUserPrefs").checked) if (document.getElementById("resetUserPrefs").checked) {
clearAllPrefs(); clearAllPrefs();
if (document.getElementById("deleteBookmarks").checked) }
if (document.getElementById("deleteBookmarks").checked) {
restoreDefaultBookmarks(); restoreDefaultBookmarks();
if (document.getElementById("resetToolbars").checked) }
if (document.getElementById("resetToolbars").checked) {
deleteLocalstore(); deleteLocalstore();
if (document.getElementById("restoreSearch").checked) }
if (document.getElementById("restoreSearch").checked) {
restoreDefaultSearchEngines(); restoreDefaultSearchEngines();
}
if (document.getElementById("disableAddons").checked) { if (document.getElementById("disableAddons").checked) {
disableAddons(); disableAddons();
// disableAddons will asynchronously restart the application // disableAddons will asynchronously restart the application
@ -109,7 +111,7 @@ function onOK() {
function onCancel() { function onCancel() {
let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"] let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
.getService(Ci.nsIAppStartup); .getService(Ci.nsIAppStartup);
appStartup.quit(Ci.nsIAppStartup.eForceQuit); appStartup.quit(Ci.nsIAppStartup.eForceQuit);
} }

View file

@ -17,17 +17,17 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task",
XPCOMUtils.defineLazyModuleGetter(this, "console", XPCOMUtils.defineLazyModuleGetter(this, "console",
"resource://gre/modules/Console.jsm"); "resource://gre/modules/Console.jsm");
function Sanitizer() {} function Sanitizer() { }
Sanitizer.prototype = { Sanitizer.prototype = {
// warning to the caller: this one may raise an exception (e.g. bug #265028) // warning to the caller: this one may raise an exception (e.g. bug #265028)
clearItem: function (aItemName) clearItem: function (aItemName) {
{ if (this.items[aItemName].canClear) {
if (this.items[aItemName].canClear)
this.items[aItemName].clear(); this.items[aItemName].clear();
}
}, },
canClearItem: function (aItemName, aCallback, aArg) canClearItem: function (aItemName, aCallback, aArg) {
{
let canClear = this.items[aItemName].canClear; let canClear = this.items[aItemName].canClear;
if (typeof canClear == "function") { if (typeof canClear == "function") {
canClear(aCallback, aArg); canClear(aCallback, aArg);
@ -41,8 +41,7 @@ Sanitizer.prototype = {
prefDomain: "", prefDomain: "",
isShutDown: false, isShutDown: false,
getNameFromPreference: function (aPreferenceName) getNameFromPreference: function (aPreferenceName) {
{
return aPreferenceName.substr(this.prefDomain.length); return aPreferenceName.substr(this.prefDomain.length);
}, },
@ -52,8 +51,7 @@ Sanitizer.prototype = {
* occurs, a message is reported to the console and all other items are still * occurs, a message is reported to the console and all other items are still
* cleared before the promise is finally rejected. * cleared before the promise is finally rejected.
*/ */
sanitize: function () sanitize: function () {
{
var deferred = Promise.defer(); var deferred = Promise.defer();
var psvc = Components.classes["@mozilla.org/preferences-service;1"] var psvc = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService); .getService(Components.interfaces.nsIPrefService);
@ -61,10 +59,12 @@ Sanitizer.prototype = {
var seenError = false; var seenError = false;
// Cache the range of times to clear // Cache the range of times to clear
if (this.ignoreTimespan) if (this.ignoreTimespan) {
var range = null; // If we ignore timespan, clear everything // If we ignore timespan, clear everything
else var range = null;
} else {
range = this.range || Sanitizer.getClearRange(); range = this.range || Sanitizer.getClearRange();
}
let itemCount = Object.keys(this.items).length; let itemCount = Object.keys(this.items).length;
let onItemComplete = function() { let onItemComplete = function() {
@ -112,32 +112,31 @@ Sanitizer.prototype = {
items: { items: {
cache: { cache: {
clear: function () clear: function() {
{ var cache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
var cache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]. .getService(Ci.nsICacheStorageService);
getService(Ci.nsICacheStorageService);
try { try {
// Cache doesn't consult timespan, nor does it have the // Cache doesn't consult timespan, nor does it have the
// facility for timespan-based eviction. Wipe it. // facility for timespan-based eviction. Wipe it.
cache.clear(); cache.clear();
} catch(er) {} } catch(er) {
}
var imageCache = Cc["@mozilla.org/image/tools;1"]. var imageCache = Cc["@mozilla.org/image/tools;1"].
getService(Ci.imgITools).getImgCacheForDocument(null); getService(Ci.imgITools).getImgCacheForDocument(null);
try { try {
imageCache.clearCache(false); // true=chrome, false=content imageCache.clearCache(false); // true=chrome, false=content
} catch(er) {} } catch(er) {
}
}, },
get canClear() get canClear() {
{
return true; return true;
} }
}, },
cookies: { cookies: {
clear: function () clear: function () {
{
var cookieMgr = Components.classes["@mozilla.org/cookiemanager;1"] var cookieMgr = Components.classes["@mozilla.org/cookiemanager;1"]
.getService(Ci.nsICookieManager); .getService(Ci.nsICookieManager);
if (this.range) { if (this.range) {
@ -146,13 +145,13 @@ Sanitizer.prototype = {
while (cookiesEnum.hasMoreElements()) { while (cookiesEnum.hasMoreElements()) {
var cookie = cookiesEnum.getNext().QueryInterface(Ci.nsICookie2); var cookie = cookiesEnum.getNext().QueryInterface(Ci.nsICookie2);
if (cookie.creationTime > this.range[0]) if (cookie.creationTime > this.range[0]) {
// This cookie was created after our cutoff, clear it // This cookie was created after our cutoff, clear it
cookieMgr.remove(cookie.host, cookie.name, cookie.path, cookieMgr.remove(cookie.host, cookie.name, cookie.path,
false, cookie.originAttributes); false, cookie.originAttributes);
}
} }
} } else {
else {
// Remove everything // Remove everything
cookieMgr.removeAll(); cookieMgr.removeAll();
} }
@ -166,20 +165,20 @@ Sanitizer.prototype = {
// that this.range[1] is actually now, so we compute age range based // that this.range[1] is actually now, so we compute age range based
// on the lower bound. If this.range results in a negative age, do // on the lower bound. If this.range results in a negative age, do
// nothing. // nothing.
let age = this.range ? (Date.now() / 1000 - this.range[0] / 1000000) let age = this.range ?
: -1; (Date.now() / 1000 - this.range[0] / 1000000) :
-1;
if (!this.range || age >= 0) { if (!this.range || age >= 0) {
let tags = ph.getPluginTags(); let tags = ph.getPluginTags();
for (let i = 0; i < tags.length; i++) { for (let i = 0; i < tags.length; i++) {
try { try {
ph.clearSiteData(tags[i], null, FLAG_CLEAR_ALL, age); ph.clearSiteData(tags[i], null, FLAG_CLEAR_ALL, age);
} catch (e) { } catch(e) {
// If the plugin doesn't support clearing by age, clear everything. // If the plugin doesn't support clearing by age, clear everything.
if (e.result == Components.results. if (e.result == Components.results.NS_ERROR_PLUGIN_TIME_RANGE_NOT_SUPPORTED) {
NS_ERROR_PLUGIN_TIME_RANGE_NOT_SUPPORTED) {
try { try {
ph.clearSiteData(tags[i], null, FLAG_CLEAR_ALL, -1); ph.clearSiteData(tags[i], null, FLAG_CLEAR_ALL, -1);
} catch (e) { } catch(e) {
// Ignore errors from the plugin // Ignore errors from the plugin
} }
} }
@ -188,15 +187,13 @@ Sanitizer.prototype = {
} }
}, },
get canClear() get canClear() {
{
return true; return true;
} }
}, },
offlineApps: { offlineApps: {
clear: function () clear: function () {
{
Components.utils.import("resource:///modules/offlineAppCache.jsm"); Components.utils.import("resource:///modules/offlineAppCache.jsm");
OfflineAppCacheHelper.clear(); OfflineAppCacheHelper.clear();
if (!this.range || this.isShutDown) { if (!this.range || this.isShutDown) {
@ -205,15 +202,13 @@ Sanitizer.prototype = {
} }
}, },
get canClear() get canClear() {
{
return true; return true;
} }
}, },
history: { history: {
clear: function () clear: function () {
{
if (this.range) { if (this.range) {
PlacesUtils.history.removeVisitsByFilter({ PlacesUtils.history.removeVisitsByFilter({
beginDate: new Date(this.range[0] / 1000), beginDate: new Date(this.range[0] / 1000),
@ -222,23 +217,23 @@ Sanitizer.prototype = {
} else { } else {
// Remove everything. // Remove everything.
PlacesUtils.history.clear() PlacesUtils.history.clear()
.catch(Components.utils.reportError); .catch(Components.utils.reportError);
} }
try { try {
var os = Components.classes["@mozilla.org/observer-service;1"] var os = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService); .getService(Components.interfaces.nsIObserverService);
os.notifyObservers(null, "browser:purge-session-history", ""); os.notifyObservers(null, "browser:purge-session-history", "");
} catch(e) {
} }
catch (e) { }
// Clear last URL of the Open Web Location dialog // Clear last URL of the Open Web Location dialog
var prefs = Components.classes["@mozilla.org/preferences-service;1"] var prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch); .getService(Components.interfaces.nsIPrefBranch);
try { try {
prefs.clearUserPref("general.open_location.last_url"); prefs.clearUserPref("general.open_location.last_url");
} catch(e) {
} }
catch (e) { }
}, },
get canClear() get canClear()
@ -250,8 +245,7 @@ Sanitizer.prototype = {
}, },
formdata: { formdata: {
clear: function () clear: function () {
{
// Clear undo history of all searchBars // Clear undo history of all searchBars
var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'] var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1']
.getService(Components.interfaces.nsIWindowMediator); .getService(Components.interfaces.nsIWindowMediator);
@ -259,11 +253,13 @@ Sanitizer.prototype = {
while (windows.hasMoreElements()) { while (windows.hasMoreElements()) {
let currentDocument = windows.getNext().document; let currentDocument = windows.getNext().document;
let searchBar = currentDocument.getElementById("searchbar"); let searchBar = currentDocument.getElementById("searchbar");
if (searchBar) if (searchBar) {
searchBar.textbox.reset(); searchBar.textbox.reset();
}
let findBar = currentDocument.getElementById("FindToolbar"); let findBar = currentDocument.getElementById("FindToolbar");
if (findBar) if (findBar) {
findBar.clear(); findBar.clear();
}
} }
let change = { op: "remove" }; let change = { op: "remove" };
@ -273,8 +269,7 @@ Sanitizer.prototype = {
FormHistory.update(change); FormHistory.update(change);
}, },
canClear : function(aCallback, aArg) canClear: function(aCallback, aArg) {
{
var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'] var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1']
.getService(Components.interfaces.nsIWindowMediator); .getService(Components.interfaces.nsIWindowMediator);
var windows = windowManager.getEnumerator("navigator:browser"); var windows = windowManager.getEnumerator("navigator:browser");
@ -299,27 +294,34 @@ Sanitizer.prototype = {
let count = 0; let count = 0;
let countDone = { let countDone = {
handleResult : function(aResult) count = aResult, handleResult: function(aResult) {
handleError : function(aError) Components.utils.reportError(aError), count = aResult;
handleCompletion : },
function(aReason) { aCallback("formdata", aReason == 0 && count > 0, aArg); } handleError: function(aError) {
Components.utils.reportError(aError);
},
handleCompletion: function(aReason) {
aCallback("formdata", aReason == 0 && count > 0, aArg);
}
}; };
FormHistory.count({}, countDone); FormHistory.count({ }, countDone);
return false; return false;
} }
}, },
downloads: { downloads: {
clear: Task.async(function* (range) { clear: Task.async(function* (range) {
let refObj = {}; let refObj = { };
try { try {
let filterByTime = null; let filterByTime = null;
if (range) { if (range) {
// Convert microseconds back to milliseconds for date comparisons. // Convert microseconds back to milliseconds for date comparisons.
let rangeBeginMs = range[0] / 1000; let rangeBeginMs = range[0] / 1000;
let rangeEndMs = range[1] / 1000; let rangeEndMs = range[1] / 1000;
filterByTime = download => download.startTime >= rangeBeginMs && filterByTime = download => {
download.startTime <= rangeEndMs; return download.startTime >= rangeBeginMs &&
download.startTime <= rangeEndMs;
}
} }
// Clear all completed/cancelled downloads // Clear all completed/cancelled downloads
@ -328,34 +330,31 @@ Sanitizer.prototype = {
} finally {} } finally {}
}), }),
get canClear() get canClear() {
{
//Clearing is always possible with JSTransfers //Clearing is always possible with JSTransfers
return true; return true;
} }
}, },
passwords: { passwords: {
clear: function () clear: function () {
{
var pwmgr = Components.classes["@mozilla.org/login-manager;1"] var pwmgr = Components.classes["@mozilla.org/login-manager;1"]
.getService(Components.interfaces.nsILoginManager); .getService(Components.interfaces.nsILoginManager);
// Passwords are timeless, and don't respect the timeSpan setting // Passwords are timeless, and don't respect the timeSpan setting
pwmgr.removeAllLogins(); pwmgr.removeAllLogins();
}, },
get canClear() get canClear() {
{
var pwmgr = Components.classes["@mozilla.org/login-manager;1"] var pwmgr = Components.classes["@mozilla.org/login-manager;1"]
.getService(Components.interfaces.nsILoginManager); .getService(Components.interfaces.nsILoginManager);
var count = pwmgr.countLogins("", "", ""); // count all logins // count all logins
var count = pwmgr.countLogins("", "", "");
return (count > 0); return (count > 0);
} }
}, },
sessions: { sessions: {
clear: function () clear: function () {
{
// clear all auth tokens // clear all auth tokens
var sdr = Components.classes["@mozilla.org/security/sdr;1"] var sdr = Components.classes["@mozilla.org/security/sdr;1"]
.getService(Components.interfaces.nsISecretDecoderRing); .getService(Components.interfaces.nsISecretDecoderRing);
@ -367,15 +366,13 @@ Sanitizer.prototype = {
os.notifyObservers(null, "net:clear-active-logins", null); os.notifyObservers(null, "net:clear-active-logins", null);
}, },
get canClear() get canClear() {
{
return true; return true;
} }
}, },
siteSettings: { siteSettings: {
clear: function () clear: function () {
{
// Clear site-specific permissions like "Allow this site to open popups" // Clear site-specific permissions like "Allow this site to open popups"
var pm = Components.classes["@mozilla.org/permissionmanager;1"] var pm = Components.classes["@mozilla.org/permissionmanager;1"]
.getService(Components.interfaces.nsIPermissionManager); .getService(Components.interfaces.nsIPermissionManager);
@ -396,23 +393,20 @@ Sanitizer.prototype = {
} }
}, },
get canClear() get canClear() {
{
return true; return true;
} }
}, },
connectivityData: { connectivityData: {
clear: function () clear: function () {
{
// Clear site security settings // Clear site security settings
var sss = Components.classes["@mozilla.org/ssservice;1"] var sss = Components.classes["@mozilla.org/ssservice;1"]
.getService(Components.interfaces.nsISiteSecurityService); .getService(Components.interfaces.nsISiteSecurityService);
sss.clearAll(); sss.clearAll();
}, },
get canClear() get canClear() {
{
return true; return true;
} }
} }
@ -440,11 +434,13 @@ Sanitizer.IS_SHUTDOWN = true;
// in the uSec-since-epoch format that PRTime likes. If we should // in the uSec-since-epoch format that PRTime likes. If we should
// clear everything, return null. Use ts if it is defined; otherwise // clear everything, return null. Use ts if it is defined; otherwise
// use the timeSpan pref. // use the timeSpan pref.
Sanitizer.getClearRange = function (ts) { Sanitizer.getClearRange = function(ts) {
if (ts === undefined) if (ts === undefined) {
ts = Sanitizer.prefs.getIntPref("timeSpan"); ts = Sanitizer.prefs.getIntPref("timeSpan");
if (ts === Sanitizer.TIMESPAN_EVERYTHING) }
if (ts === Sanitizer.TIMESPAN_EVERYTHING) {
return null; return null;
}
// PRTime is microseconds while JS time is milliseconds // PRTime is microseconds while JS time is milliseconds
var endDate = Date.now() * 1000; var endDate = Date.now() * 1000;
@ -472,17 +468,16 @@ Sanitizer.getClearRange = function (ts) {
}; };
Sanitizer._prefs = null; Sanitizer._prefs = null;
Sanitizer.__defineGetter__("prefs", function() Sanitizer.__defineGetter__("prefs", function() {
{ return Sanitizer._prefs ?
return Sanitizer._prefs ? Sanitizer._prefs Sanitizer._prefs :
: Sanitizer._prefs = Components.classes["@mozilla.org/preferences-service;1"] Sanitizer._prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService) .getService(Components.interfaces.nsIPrefService)
.getBranch(Sanitizer.prefDomain); .getBranch(Sanitizer.prefDomain);
}); });
// Shows sanitization UI // Shows sanitization UI
Sanitizer.showUI = function(aParentWindow) Sanitizer.showUI = function(aParentWindow) {
{
var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
.getService(Components.interfaces.nsIWindowWatcher); .getService(Components.interfaces.nsIWindowWatcher);
#ifdef XP_MACOSX #ifdef XP_MACOSX
@ -500,26 +495,22 @@ Sanitizer.showUI = function(aParentWindow)
* Deletes privacy sensitive data in a batch, optionally showing the * Deletes privacy sensitive data in a batch, optionally showing the
* sanitize UI, according to user preferences * sanitize UI, according to user preferences
*/ */
Sanitizer.sanitize = function(aParentWindow) Sanitizer.sanitize = function(aParentWindow) {
{
Sanitizer.showUI(aParentWindow); Sanitizer.showUI(aParentWindow);
}; };
Sanitizer.onStartup = function() Sanitizer.onStartup = function() {
{
// we check for unclean exit with pending sanitization // we check for unclean exit with pending sanitization
Sanitizer._checkAndSanitize(); Sanitizer._checkAndSanitize();
}; };
Sanitizer.onShutdown = function() Sanitizer.onShutdown = function() {
{
// we check if sanitization is needed and perform it // we check if sanitization is needed and perform it
Sanitizer._checkAndSanitize(Sanitizer.IS_SHUTDOWN); Sanitizer._checkAndSanitize(Sanitizer.IS_SHUTDOWN);
}; };
// this is called on startup and shutdown, to perform pending sanitizations // this is called on startup and shutdown, to perform pending sanitizations
Sanitizer._checkAndSanitize = function(isShutDown) Sanitizer._checkAndSanitize = function(isShutDown) {
{
const prefs = Sanitizer.prefs; const prefs = Sanitizer.prefs;
if (prefs.getBoolPref(Sanitizer.prefShutdown) && if (prefs.getBoolPref(Sanitizer.prefShutdown) &&
!prefs.prefHasUserValue(Sanitizer.prefDidShutdown)) { !prefs.prefHasUserValue(Sanitizer.prefDidShutdown)) {

View file

@ -8,35 +8,30 @@ var Ci = Components.interfaces;
var gSanitizePromptDialog = { var gSanitizePromptDialog = {
get bundleBrowser() get bundleBrowser() {
{ if (!this._bundleBrowser) {
if (!this._bundleBrowser)
this._bundleBrowser = document.getElementById("bundleBrowser"); this._bundleBrowser = document.getElementById("bundleBrowser");
}
return this._bundleBrowser; return this._bundleBrowser;
}, },
get selectedTimespan() get selectedTimespan() {
{
var durList = document.getElementById("sanitizeDurationChoice"); var durList = document.getElementById("sanitizeDurationChoice");
return parseInt(durList.value); return parseInt(durList.value);
}, },
get sanitizePreferences() get sanitizePreferences() {
{
if (!this._sanitizePreferences) { if (!this._sanitizePreferences) {
this._sanitizePreferences = this._sanitizePreferences = document.getElementById("sanitizePreferences");
document.getElementById("sanitizePreferences");
} }
return this._sanitizePreferences; return this._sanitizePreferences;
}, },
get warningBox() get warningBox() {
{
return document.getElementById("sanitizeEverythingWarningBox"); return document.getElementById("sanitizeEverythingWarningBox");
}, },
init: function() init: function() {
{
// This is used by selectByTimespan() to determine if the window has loaded. // This is used by selectByTimespan() to determine if the window has loaded.
this._inited = true; this._inited = true;
@ -62,19 +57,18 @@ var gSanitizePromptDialog = {
if (this.selectedTimespan === Sanitizer.TIMESPAN_EVERYTHING) { if (this.selectedTimespan === Sanitizer.TIMESPAN_EVERYTHING) {
this.prepareWarning(); this.prepareWarning();
this.warningBox.hidden = false; this.warningBox.hidden = false;
document.title = document.title = this.bundleBrowser.getString("sanitizeDialog2.everything.title");
this.bundleBrowser.getString("sanitizeDialog2.everything.title"); } else {
}
else
this.warningBox.hidden = true; this.warningBox.hidden = true;
}
}, },
selectByTimespan: function() selectByTimespan: function() {
{
// This method is the onselect handler for the duration dropdown. As a // This method is the onselect handler for the duration dropdown. As a
// result it's called a couple of times before onload calls init(). // result it's called a couple of times before onload calls init().
if (!this._inited) if (!this._inited) {
return; return;
}
var warningBox = this.warningBox; var warningBox = this.warningBox;
@ -85,8 +79,7 @@ var gSanitizePromptDialog = {
warningBox.hidden = false; warningBox.hidden = false;
window.resizeBy(0, warningBox.boxObject.height); window.resizeBy(0, warningBox.boxObject.height);
} }
window.document.title = window.document.title = this.bundleBrowser.getString("sanitizeDialog2.everything.title");
this.bundleBrowser.getString("sanitizeDialog2.everything.title");
return; return;
} }
@ -95,12 +88,10 @@ var gSanitizePromptDialog = {
window.resizeBy(0, -warningBox.boxObject.height); window.resizeBy(0, -warningBox.boxObject.height);
warningBox.hidden = true; warningBox.hidden = true;
} }
window.document.title = window.document.title = window.document.documentElement.getAttribute("noneverythingtitle");
window.document.documentElement.getAttribute("noneverythingtitle");
}, },
sanitize: function() sanitize: function() {
{
// Update pref values before handing off to the sanitizer (bug 453440) // Update pref values before handing off to the sanitizer (bug 453440)
this.updatePrefs(); this.updatePrefs();
var s = new Sanitizer(); var s = new Sanitizer();
@ -116,8 +107,7 @@ var gSanitizePromptDialog = {
let docElt = document.documentElement; let docElt = document.documentElement;
let acceptButton = docElt.getButton("accept"); let acceptButton = docElt.getButton("accept");
acceptButton.disabled = true; acceptButton.disabled = true;
acceptButton.setAttribute("label", acceptButton.setAttribute("label", this.bundleBrowser.getString("sanitizeButtonClearing"));
this.bundleBrowser.getString("sanitizeButtonClearing"));
docElt.getButton("cancel").disabled = true; docElt.getButton("cancel").disabled = true;
try { try {
s.sanitize().then(window.close, window.close); s.sanitize().then(window.close, window.close);
@ -144,24 +134,22 @@ var gSanitizePromptDialog = {
var warningStringID; var warningStringID;
if (this.hasNonSelectedItems()) { if (this.hasNonSelectedItems()) {
warningStringID = "sanitizeSelectedWarning"; warningStringID = "sanitizeSelectedWarning";
if (!aDontShowItemList) if (!aDontShowItemList) {
this.showItemList(); this.showItemList();
} }
else { } else {
warningStringID = "sanitizeEverythingWarning2"; warningStringID = "sanitizeEverythingWarning2";
} }
var warningDesc = document.getElementById("sanitizeEverythingWarning"); var warningDesc = document.getElementById("sanitizeEverythingWarning");
warningDesc.textContent = warningDesc.textContent = this.bundleBrowser.getString(warningStringID);
this.bundleBrowser.getString(warningStringID);
}, },
/** /**
* Called when the value of a preference element is synced from the actual * Called when the value of a preference element is synced from the actual
* pref. Enables or disables the OK button appropriately. * pref. Enables or disables the OK button appropriately.
*/ */
onReadGeneric: function() onReadGeneric: function() {
{
var found = false; var found = false;
// Find any other pref that's checked and enabled. // Find any other pref that's checked and enabled.
@ -176,8 +164,8 @@ var gSanitizePromptDialog = {
try { try {
document.documentElement.getButton("accept").disabled = !found; document.documentElement.getButton("accept").disabled = !found;
} catch(e) {
} }
catch (e) { }
// Update the warning prompt if needed // Update the warning prompt if needed
this.prepareWarning(true); this.prepareWarning(true);
@ -218,8 +206,9 @@ var gSanitizePromptDialog = {
let checkboxes = document.querySelectorAll("#itemList > [preference]"); let checkboxes = document.querySelectorAll("#itemList > [preference]");
for (let i = 0; i < checkboxes.length; ++i) { for (let i = 0; i < checkboxes.length; ++i) {
let pref = document.getElementById(checkboxes[i].getAttribute("preference")); let pref = document.getElementById(checkboxes[i].getAttribute("preference"));
if (!pref.value) if (!pref.value) {
return true; return true;
}
} }
return false; return false;
}, },
@ -234,8 +223,9 @@ var gSanitizePromptDialog = {
if (itemList.collapsed) { if (itemList.collapsed) {
expanderButton.className = "expander-up"; expanderButton.className = "expander-up";
itemList.setAttribute("collapsed", "false"); itemList.setAttribute("collapsed", "false");
if (document.documentElement.boxObject.height) if (document.documentElement.boxObject.height) {
window.resizeBy(0, itemList.boxObject.height); window.resizeBy(0, itemList.boxObject.height);
}
} }
}, },
@ -256,34 +246,32 @@ var gSanitizePromptDialog = {
/** /**
* Called by the item list expander button to toggle the list's visibility. * Called by the item list expander button to toggle the list's visibility.
*/ */
toggleItemList: function() toggleItemList: function() {
{
var itemList = document.getElementById("itemList"); var itemList = document.getElementById("itemList");
if (itemList.collapsed) if (itemList.collapsed) {
this.showItemList(); this.showItemList();
else } else {
this.hideItemList(); this.hideItemList();
}
} }
#ifdef CRH_DIALOG_TREE_VIEW #ifdef CRH_DIALOG_TREE_VIEW
// A duration value; used in the same context as Sanitizer.TIMESPAN_HOUR, // A duration value; used in the same context as Sanitizer.TIMESPAN_HOUR,
// Sanitizer.TIMESPAN_2HOURS, et al. This should match the value attribute // Sanitizer.TIMESPAN_2HOURS, et al. This should match the value attribute
// of the sanitizeDurationCustom menuitem. // of the sanitizeDurationCustom menuitem.
get TIMESPAN_CUSTOM() get TIMESPAN_CUSTOM() {
{
return -1; return -1;
}, },
get placesTree() get placesTree() {
{ if (!this._placesTree) {
if (!this._placesTree)
this._placesTree = document.getElementById("placesTree"); this._placesTree = document.getElementById("placesTree");
}
return this._placesTree; return this._placesTree;
}, },
init: function() init: function() {
{
// This is used by selectByTimespan() to determine if the window has loaded. // This is used by selectByTimespan() to determine if the window has loaded.
this._inited = true; this._inited = true;
@ -315,8 +303,7 @@ var gSanitizePromptDialog = {
* the tree to duration values, and this.durationStartTimes, which maps * the tree to duration values, and this.durationStartTimes, which maps
* duration values to their corresponding start times. * duration values to their corresponding start times.
*/ */
initDurationDropdown: function() initDurationDropdown: function() {
{
// First, calculate the start times for each duration. // First, calculate the start times for each duration.
this.durationStartTimes = {}; this.durationStartTimes = {};
var durVals = []; var durVals = [];
@ -342,14 +329,14 @@ var gSanitizePromptDialog = {
// Now calculate the rows in the tree of the durations' start times. For // Now calculate the rows in the tree of the durations' start times. For
// each duration, we are looking for the node in the tree whose time is the // each duration, we are looking for the node in the tree whose time is the
// smallest time greater than or equal to the duration's start time. // smallest time greater than or equal to the duration's start time.
this.durationRowsToVals = {}; this.durationRowsToVals = { };
this.durationValsToRows = {}; this.durationValsToRows = { };
var view = this.placesTree.view; var view = this.placesTree.view;
// For all rows in the tree except the grippy row... // For all rows in the tree except the grippy row...
for (let i = 0; i < view.rowCount - 1; i++) { for (let i = 0; i < view.rowCount - 1; i++) {
let unfoundDurVals = []; let unfoundDurVals = [];
let nodeTime = view.QueryInterface(Ci.nsINavHistoryResultTreeViewer). let nodeTime = view.QueryInterface(Ci.nsINavHistoryResultTreeViewer)
nodeForTreeIndex(i).time; .nodeForTreeIndex(i).time;
// For all durations whose rows have not yet been found in the tree, see // For all durations whose rows have not yet been found in the tree, see
// if index i is their index. An index may map to more than one duration, // if index i is their index. An index may map to more than one duration,
// in which case the final duration (the largest) wins. // in which case the final duration (the largest) wins.
@ -359,9 +346,9 @@ var gSanitizePromptDialog = {
if (nodeTime < durStartTime) { if (nodeTime < durStartTime) {
this.durationValsToRows[durVal] = i - 1; this.durationValsToRows[durVal] = i - 1;
this.durationRowsToVals[i - 1] = durVal; this.durationRowsToVals[i - 1] = durVal;
} } else {
else
unfoundDurVals.push(durVal); unfoundDurVals.push(durVal);
}
} }
durVals = unfoundDurVals; durVals = unfoundDurVals;
} }
@ -379,10 +366,10 @@ var gSanitizePromptDialog = {
/** /**
* If the Places tree is not set up, sets it up. Otherwise does nothing. * If the Places tree is not set up, sets it up. Otherwise does nothing.
*/ */
ensurePlacesTreeIsInited: function() ensurePlacesTreeIsInited: function() {
{ if (this._placesTreeIsInited) {
if (this._placesTreeIsInited)
return; return;
}
this._placesTreeIsInited = true; this._placesTreeIsInited = true;
@ -396,8 +383,8 @@ var gSanitizePromptDialog = {
times = Sanitizer.getClearRange(Sanitizer.TIMESPAN_4HOURS); times = Sanitizer.getClearRange(Sanitizer.TIMESPAN_4HOURS);
} }
var histServ = Cc["@mozilla.org/browser/nav-history-service;1"]. var histServ = Cc["@mozilla.org/browser/nav-history-service;1"]
getService(Ci.nsINavHistoryService); .getService(Ci.nsINavHistoryService);
var query = histServ.getNewQuery(); var query = histServ.getNewQuery();
query.beginTimeReference = query.TIME_RELATIVE_EPOCH; query.beginTimeReference = query.TIME_RELATIVE_EPOCH;
query.beginTime = times[0]; query.beginTime = times[0];
@ -420,12 +407,12 @@ var gSanitizePromptDialog = {
* the tree that are contained in the selected duration. If clearing * the tree that are contained in the selected duration. If clearing
* everything, the warning panel is shown instead. * everything, the warning panel is shown instead.
*/ */
selectByTimespan: function() selectByTimespan: function() {
{
// This method is the onselect handler for the duration dropdown. As a // This method is the onselect handler for the duration dropdown. As a
// result it's called a couple of times before onload calls init(). // result it's called a couple of times before onload calls init().
if (!this._inited) if (!this._inited) {
return; return;
}
var durDeck = document.getElementById("durationDeck"); var durDeck = document.getElementById("durationDeck");
var durList = document.getElementById("sanitizeDurationChoice"); var durList = document.getElementById("sanitizeDurationChoice");
@ -446,29 +433,24 @@ var gSanitizePromptDialog = {
if (durVal === Sanitizer.TIMESPAN_EVERYTHING) { if (durVal === Sanitizer.TIMESPAN_EVERYTHING) {
this.prepareWarning(); this.prepareWarning();
durDeck.selectedIndex = 1; durDeck.selectedIndex = 1;
window.document.title = window.document.title = this.bundleBrowser.getString("sanitizeDialog2.everything.title");
this.bundleBrowser.getString("sanitizeDialog2.everything.title");
document.documentElement.getButton("accept").disabled = false; document.documentElement.getButton("accept").disabled = false;
return; return;
} }
// Otherwise -- if clearing a specific time range -- select that time range // Otherwise -- if clearing a specific time range -- select that time range in the tree.
// in the tree.
this.ensurePlacesTreeIsInited(); this.ensurePlacesTreeIsInited();
durDeck.selectedIndex = 0; durDeck.selectedIndex = 0;
window.document.title = window.document.title = window.document.documentElement.getAttribute("noneverythingtitle");
window.document.documentElement.getAttribute("noneverythingtitle");
var durRow = this.durationValsToRows[durVal]; var durRow = this.durationValsToRows[durVal];
gContiguousSelectionTreeHelper.rangedSelect(durRow); gContiguousSelectionTreeHelper.rangedSelect(durRow);
gContiguousSelectionTreeHelper.scrollToGrippy(); gContiguousSelectionTreeHelper.scrollToGrippy();
// If duration is empty (there are no selected rows), disable the dialog's // If duration is empty (there are no selected rows), disable the dialog's OK button.
// OK button.
document.documentElement.getButton("accept").disabled = durRow < 0; document.documentElement.getButton("accept").disabled = durRow < 0;
}, },
sanitize: function() sanitize: function() {
{
// Update pref values before handing off to the sanitizer (bug 453440) // Update pref values before handing off to the sanitizer (bug 453440)
this.updatePrefs(); this.updatePrefs();
var s = new Sanitizer(); var s = new Sanitizer();
@ -486,9 +468,9 @@ var gSanitizePromptDialog = {
var now = Date.now() * 1000; var now = Date.now() * 1000;
// We disable the dialog's OK button if there's no selection, but we'll // We disable the dialog's OK button if there's no selection, but we'll
// handle that case just in... case. // handle that case just in... case.
if (view.selection.getRangeCount() === 0) if (view.selection.getRangeCount() === 0) {
s.range = [now, now]; s.range = [now, now];
else { } else {
var startIndexRef = {}; var startIndexRef = {};
// Tree sorted by visit date DEscending, so start time time comes last. // Tree sorted by visit date DEscending, so start time time comes last.
view.selection.getRangeAt(0, {}, startIndexRef); view.selection.getRangeAt(0, {}, startIndexRef);
@ -496,10 +478,10 @@ var gSanitizePromptDialog = {
var startNode = view.nodeForTreeIndex(startIndexRef.value); var startNode = view.nodeForTreeIndex(startIndexRef.value);
s.range = [startNode.time, now]; s.range = [startNode.time, now];
} }
} } else {
// Otherwise use the predetermined range. // Use the predetermined range.
else
s.range = [this.durationStartTimes[durValue], Date.now() * 1000]; s.range = [this.durationStartTimes[durValue], Date.now() * 1000];
}
} }
try { try {
@ -515,8 +497,7 @@ var gSanitizePromptDialog = {
* for garbage collection, we need to break the reference cycle between the * for garbage collection, we need to break the reference cycle between the
* two. * two.
*/ */
unload: function() unload: function() {
{
let result = this.placesTree.getResult(); let result = this.placesTree.getResult();
result.removeObserver(this.placesTree.view); result.removeObserver(this.placesTree.view);
this.placesTree.view = null; this.placesTree.view = null;
@ -533,8 +514,7 @@ var gSanitizePromptDialog = {
* @param aEvent * @param aEvent
* The event captured in the event handler. * The event captured in the event handler.
*/ */
grippyMoved: function(aEventName, aEvent) grippyMoved: function(aEventName, aEvent) {
{
gContiguousSelectionTreeHelper[aEventName](aEvent); gContiguousSelectionTreeHelper[aEventName](aEvent);
var lastSelRow = gContiguousSelectionTreeHelper.getGrippyRow() - 1; var lastSelRow = gContiguousSelectionTreeHelper.getGrippyRow() - 1;
var durList = document.getElementById("sanitizeDurationChoice"); var durList = document.getElementById("sanitizeDurationChoice");
@ -548,10 +528,11 @@ var gSanitizePromptDialog = {
this.durationValsToRows[durValue] !== lastSelRow)) { this.durationValsToRows[durValue] !== lastSelRow)) {
// Setting durList.value causes its onselect handler to fire, which calls // Setting durList.value causes its onselect handler to fire, which calls
// selectByTimespan(). // selectByTimespan().
if (lastSelRow in this.durationRowsToVals) if (lastSelRow in this.durationRowsToVals) {
durList.value = this.durationRowsToVals[lastSelRow]; durList.value = this.durationRowsToVals[lastSelRow];
else } else {
durList.value = this.TIMESPAN_CUSTOM; durList.value = this.TIMESPAN_CUSTOM;
}
} }
// If there are no selected rows, disable the dialog's OK button. // If there are no selected rows, disable the dialog's OK button.
@ -561,7 +542,6 @@ var gSanitizePromptDialog = {
}; };
#ifdef CRH_DIALOG_TREE_VIEW #ifdef CRH_DIALOG_TREE_VIEW
/** /**
* A helper for handling contiguous selection in the tree. * A helper for handling contiguous selection in the tree.
@ -571,8 +551,7 @@ var gContiguousSelectionTreeHelper = {
/** /**
* Gets the tree associated with this helper. * Gets the tree associated with this helper.
*/ */
get tree() get tree() {
{
return this._tree; return this._tree;
}, },
@ -589,8 +568,7 @@ var gContiguousSelectionTreeHelper = {
* view * view
* @return The new view * @return The new view
*/ */
setTree: function(aTreeElement, aProtoTreeView) setTree: function(aTreeElement, aProtoTreeView) {
{
this._tree = aTreeElement; this._tree = aTreeElement;
var newView = this._makeTreeView(aProtoTreeView || aTreeElement.view); var newView = this._makeTreeView(aProtoTreeView || aTreeElement.view);
aTreeElement.view = newView; aTreeElement.view = newView;
@ -604,18 +582,18 @@ var gContiguousSelectionTreeHelper = {
* *
* @return The row index of the grippy * @return The row index of the grippy
*/ */
getGrippyRow: function() getGrippyRow: function() {
{
var sel = this.tree.view.selection; var sel = this.tree.view.selection;
var rangeCount = sel.getRangeCount(); var rangeCount = sel.getRangeCount();
if (rangeCount === 0) if (rangeCount === 0) {
return 0; return 0;
}
if (rangeCount !== 1) { if (rangeCount !== 1) {
throw "contiguous selection tree helper: getGrippyRow called with " + throw "contiguous selection tree helper: getGrippyRow called with " +
"multiple selection ranges"; "multiple selection ranges";
} }
var max = {}; var max = { };
sel.getRangeAt(0, {}, max); sel.getRangeAt(0, { }, max);
return max.value + 1; return max.value + 1;
}, },
@ -626,13 +604,12 @@ var gContiguousSelectionTreeHelper = {
* @param aEvent * @param aEvent
* The observed dragover event * The observed dragover event
*/ */
ondragover: function(aEvent) ondragover: function(aEvent) {
{
// Without this when dragging on Windows the mouse cursor is a "no" sign. // Without this when dragging on Windows the mouse cursor is a "no" sign.
// This makes it a drop symbol. // This makes it a drop symbol.
var ds = Cc["@mozilla.org/widget/dragservice;1"]. var ds = Cc["@mozilla.org/widget/dragservice;1"]
getService(Ci.nsIDragService). .getService(Ci.nsIDragService)
getCurrentSession(); .getCurrentSession();
ds.canDrop = true; ds.canDrop = true;
ds.dragAction = 0; ds.dragAction = 0;
@ -640,8 +617,9 @@ var gContiguousSelectionTreeHelper = {
aEvent.QueryInterface(Ci.nsIDOMMouseEvent); aEvent.QueryInterface(Ci.nsIDOMMouseEvent);
var hoverRow = tbo.getRowAt(aEvent.clientX, aEvent.clientY); var hoverRow = tbo.getRowAt(aEvent.clientX, aEvent.clientY);
if (hoverRow < 0) if (hoverRow < 0) {
return; return;
}
this.rangedSelect(hoverRow - 1); this.rangedSelect(hoverRow - 1);
}, },
@ -653,30 +631,30 @@ var gContiguousSelectionTreeHelper = {
* @param aEvent * @param aEvent
* The observed dragstart event * The observed dragstart event
*/ */
ondragstart: function(aEvent) ondragstart: function(aEvent) {
{
var tbo = this.tree.treeBoxObject; var tbo = this.tree.treeBoxObject;
var clickedRow = tbo.getRowAt(aEvent.clientX, aEvent.clientY); var clickedRow = tbo.getRowAt(aEvent.clientX, aEvent.clientY);
if (clickedRow !== this.getGrippyRow()) if (clickedRow !== this.getGrippyRow()) {
return; return;
}
// This part is a hack. What we really want is a grab and slide, not // This part is a hack. What we really want is a grab and slide, not
// drag and drop. Start a move drag session with dummy data and a // drag and drop. Start a move drag session with dummy data and a
// dummy region. Set the region's coordinates to (Infinity, Infinity) // dummy region. Set the region's coordinates to (Infinity, Infinity)
// so it's drawn offscreen and its size to (1, 1). // so it's drawn offscreen and its size to (1, 1).
var arr = Cc["@mozilla.org/supports-array;1"]. var arr = Cc["@mozilla.org/supports-array;1"]
createInstance(Ci.nsISupportsArray); .createInstance(Ci.nsISupportsArray);
var trans = Cc["@mozilla.org/widget/transferable;1"]. var trans = Cc["@mozilla.org/widget/transferable;1"]
createInstance(Ci.nsITransferable); .createInstance(Ci.nsITransferable);
trans.init(null); trans.init(null);
trans.setTransferData('dummy-flavor', null, 0); trans.setTransferData('dummy-flavor', null, 0);
arr.AppendElement(trans); arr.AppendElement(trans);
var reg = Cc["@mozilla.org/gfx/region;1"]. var reg = Cc["@mozilla.org/gfx/region;1"]
createInstance(Ci.nsIScriptableRegion); .createInstance(Ci.nsIScriptableRegion);
reg.setToRect(Infinity, Infinity, 1, 1); reg.setToRect(Infinity, Infinity, 1, 1);
var ds = Cc["@mozilla.org/widget/dragservice;1"]. var ds = Cc["@mozilla.org/widget/dragservice;1"]
getService(Ci.nsIDragService); .getService(Ci.nsIDragService);
ds.invokeDragSession(aEvent.target, arr, reg, ds.DRAGDROP_ACTION_MOVE); ds.invokeDragSession(aEvent.target, arr, reg, ds.DRAGDROP_ACTION_MOVE);
}, },
@ -688,56 +666,59 @@ var gContiguousSelectionTreeHelper = {
* @param aEvent * @param aEvent
* The observed keypress event * The observed keypress event
*/ */
onkeypress: function(aEvent) onkeypress: function(aEvent) {
{
var grippyRow = this.getGrippyRow(); var grippyRow = this.getGrippyRow();
var tbo = this.tree.treeBoxObject; var tbo = this.tree.treeBoxObject;
var rangeEnd; var rangeEnd;
switch (aEvent.keyCode) { switch (aEvent.keyCode) {
case aEvent.DOM_VK_HOME: case aEvent.DOM_VK_HOME:
rangeEnd = 0; rangeEnd = 0;
break; break;
case aEvent.DOM_VK_PAGE_UP: case aEvent.DOM_VK_PAGE_UP:
rangeEnd = grippyRow - tbo.getPageLength(); rangeEnd = grippyRow - tbo.getPageLength();
break; break;
case aEvent.DOM_VK_UP: case aEvent.DOM_VK_UP:
rangeEnd = grippyRow - 2; rangeEnd = grippyRow - 2;
break; break;
case aEvent.DOM_VK_DOWN: case aEvent.DOM_VK_DOWN:
rangeEnd = grippyRow; rangeEnd = grippyRow;
break; break;
case aEvent.DOM_VK_PAGE_DOWN: case aEvent.DOM_VK_PAGE_DOWN:
rangeEnd = grippyRow + tbo.getPageLength(); rangeEnd = grippyRow + tbo.getPageLength();
break; break;
case aEvent.DOM_VK_END: case aEvent.DOM_VK_END:
rangeEnd = this.tree.view.rowCount - 2; rangeEnd = this.tree.view.rowCount - 2;
break; break;
default: default:
return; return;
break; break;
} }
aEvent.stopPropagation(); aEvent.stopPropagation();
// First, clip rangeEnd. this.rangedSelect() doesn't clip the range if we // First, clip rangeEnd. this.rangedSelect() doesn't clip the range if we
// select past the ends of the tree. // select past the ends of the tree.
if (rangeEnd < 0) if (rangeEnd < 0) {
rangeEnd = -1; rangeEnd = -1;
else if (this.tree.view.rowCount - 2 < rangeEnd) } else if (this.tree.view.rowCount - 2 < rangeEnd) {
rangeEnd = this.tree.view.rowCount - 2; rangeEnd = this.tree.view.rowCount - 2;
}
// Next, (de)select. // Next, (de)select.
this.rangedSelect(rangeEnd); this.rangedSelect(rangeEnd);
// Finally, scroll the tree. We always want one row above and below the // Finally, scroll the tree. We always want one row above and below the
// grippy row to be visible if possible. // grippy row to be visible if possible.
if (rangeEnd < grippyRow) // moved up if (rangeEnd < grippyRow) {
// moved up
tbo.ensureRowIsVisible(rangeEnd < 0 ? 0 : rangeEnd); tbo.ensureRowIsVisible(rangeEnd < 0 ? 0 : rangeEnd);
else { // moved down } else {
if (rangeEnd + 2 < this.tree.view.rowCount) // moved down
if (rangeEnd + 2 < this.tree.view.rowCount) {
tbo.ensureRowIsVisible(rangeEnd + 2); tbo.ensureRowIsVisible(rangeEnd + 2);
else if (rangeEnd + 1 < this.tree.view.rowCount) } else if (rangeEnd + 1 < this.tree.view.rowCount) {
tbo.ensureRowIsVisible(rangeEnd + 1); tbo.ensureRowIsVisible(rangeEnd + 1);
}
} }
}, },
@ -749,18 +730,19 @@ var gContiguousSelectionTreeHelper = {
* @param aEvent * @param aEvent
* The observed mousedown event * The observed mousedown event
*/ */
onmousedown: function(aEvent) onmousedown: function(aEvent) {
{
var tbo = this.tree.treeBoxObject; var tbo = this.tree.treeBoxObject;
var clickedRow = tbo.getRowAt(aEvent.clientX, aEvent.clientY); var clickedRow = tbo.getRowAt(aEvent.clientX, aEvent.clientY);
if (clickedRow < 0 || clickedRow >= this.tree.view.rowCount) if (clickedRow < 0 || clickedRow >= this.tree.view.rowCount) {
return; return;
}
if (clickedRow < this.getGrippyRow()) if (clickedRow < this.getGrippyRow()) {
this.rangedSelect(clickedRow); this.rangedSelect(clickedRow);
else if (clickedRow > this.getGrippyRow()) } else if (clickedRow > this.getGrippyRow()) {
this.rangedSelect(clickedRow - 1); this.rangedSelect(clickedRow - 1);
}
}, },
/** /**
@ -771,40 +753,40 @@ var gContiguousSelectionTreeHelper = {
* @param aEndRow * @param aEndRow
* The range [0, aEndRow] will be selected. * The range [0, aEndRow] will be selected.
*/ */
rangedSelect: function(aEndRow) rangedSelect: function(aEndRow) {
{
var tbo = this.tree.treeBoxObject; var tbo = this.tree.treeBoxObject;
if (aEndRow < 0) if (aEndRow < 0) {
this.tree.view.selection.clearSelection(); this.tree.view.selection.clearSelection();
else } else {
this.tree.view.selection.rangedSelect(0, aEndRow, false); this.tree.view.selection.rangedSelect(0, aEndRow, false);
}
tbo.invalidateRange(tbo.getFirstVisibleRow(), tbo.getLastVisibleRow()); tbo.invalidateRange(tbo.getFirstVisibleRow(), tbo.getLastVisibleRow());
}, },
/** /**
* Scrolls the tree so that the grippy row is in the center of the view. * Scrolls the tree so that the grippy row is in the center of the view.
*/ */
scrollToGrippy: function() scrollToGrippy: function() {
{
var rowCount = this.tree.view.rowCount; var rowCount = this.tree.view.rowCount;
var tbo = this.tree.treeBoxObject; var tbo = this.tree.treeBoxObject;
var pageLen = tbo.getPageLength() || var pageLen = tbo.getPageLength() ||
parseInt(this.tree.getAttribute("rows")) || parseInt(this.tree.getAttribute("rows")) ||
10; 10;
// All rows fit on a single page. if (rowCount <= pageLen) {
if (rowCount <= pageLen) // All rows fit on a single page.
return; return;
}
var scrollToRow = this.getGrippyRow() - Math.ceil(pageLen / 2.0); var scrollToRow = this.getGrippyRow() - Math.ceil(pageLen / 2.0);
// Grippy row is in first half of first page. if (scrollToRow < 0) {
if (scrollToRow < 0) // Grippy row is in first half of first page.
scrollToRow = 0; scrollToRow = 0;
} else if (rowCount < scrollToRow + pageLen) {
// Grippy row is in last half of last page. // Grippy row is in last half of last page.
else if (rowCount < scrollToRow + pageLen)
scrollToRow = rowCount - pageLen; scrollToRow = rowCount - pageLen;
}
tbo.scrollToRow(scrollToRow); tbo.scrollToRow(scrollToRow);
}, },
@ -817,92 +799,87 @@ var gContiguousSelectionTreeHelper = {
* @param aProtoTreeView * @param aProtoTreeView
* Used as the new view's prototype if specified * Used as the new view's prototype if specified
*/ */
_makeTreeView: function(aProtoTreeView) _makeTreeView: function(aProtoTreeView) {
{
var view = aProtoTreeView; var view = aProtoTreeView;
var that = this; var that = this;
//XXXadw: When Alex gets the grippy icon done, this may or may not change, //XXXadw: When Alex gets the grippy icon done, this may or may not change,
// depending on how we style it. // depending on how we style it.
view.isSeparator = function(aRow) view.isSeparator = function(aRow) {
{
return aRow === that.getGrippyRow(); return aRow === that.getGrippyRow();
}; };
// rowCount includes the grippy row. // rowCount includes the grippy row.
view.__defineGetter__("_rowCount", view.__lookupGetter__("rowCount")); view.__defineGetter__("_rowCount", view.__lookupGetter__("rowCount"));
view.__defineGetter__("rowCount", view.__defineGetter__("rowCount", function() {
function()
{
return this._rowCount + 1; return this._rowCount + 1;
}); });
// This has to do with visual feedback in the view itself, e.g., drawing // This has to do with visual feedback in the view itself, e.g., drawing
// a small line underneath the dropzone. Not what we want. // a small line underneath the dropzone. Not what we want.
view.canDrop = function CSTH_View_canDrop() { return false; }; view.canDrop = function() {
return false;
};
// No clicking headers to sort the tree or sort feedback on columns. // No clicking headers to sort the tree or sort feedback on columns.
view.cycleHeader = function CSTH_View_cycleHeader() {}; view.cycleHeader = function() { };
view.sortingChanged = function CSTH_View_sortingChanged() {}; view.sortingChanged = function() { };
// Override a bunch of methods to account for the grippy row. // Override a bunch of methods to account for the grippy row.
view._getCellProperties = view.getCellProperties; view._getCellProperties = view.getCellProperties;
view.getCellProperties = view.getCellProperties = function (aRow, aCol) {
function CSTH_View_getCellProperties(aRow, aCol)
{
var grippyRow = that.getGrippyRow(); var grippyRow = that.getGrippyRow();
if (aRow === grippyRow) if (aRow === grippyRow) {
return "grippyRow"; return "grippyRow";
if (aRow < grippyRow) }
if (aRow < grippyRow) {
return this._getCellProperties(aRow, aCol); return this._getCellProperties(aRow, aCol);
}
return this._getCellProperties(aRow - 1, aCol); return this._getCellProperties(aRow - 1, aCol);
}; };
view._getRowProperties = view.getRowProperties; view._getRowProperties = view.getRowProperties;
view.getRowProperties = view.getRowProperties = function (aRow) {
function CSTH_View_getRowProperties(aRow)
{
var grippyRow = that.getGrippyRow(); var grippyRow = that.getGrippyRow();
if (aRow === grippyRow) if (aRow === grippyRow) {
return "grippyRow"; return "grippyRow";
}
if (aRow < grippyRow) if (aRow < grippyRow) {
return this._getRowProperties(aRow); return this._getRowProperties(aRow);
}
return this._getRowProperties(aRow - 1); return this._getRowProperties(aRow - 1);
}; };
view._getCellText = view.getCellText; view._getCellText = view.getCellText;
view.getCellText = view.getCellText = function (aRow, aCol) {
function CSTH_View_getCellText(aRow, aCol)
{
var grippyRow = that.getGrippyRow(); var grippyRow = that.getGrippyRow();
if (aRow === grippyRow) if (aRow === grippyRow) {
return ""; return "";
}
aRow = aRow < grippyRow ? aRow : aRow - 1; aRow = aRow < grippyRow ? aRow : aRow - 1;
return this._getCellText(aRow, aCol); return this._getCellText(aRow, aCol);
}; };
view._getImageSrc = view.getImageSrc; view._getImageSrc = view.getImageSrc;
view.getImageSrc = view.getImageSrc = function(aRow, aCol) {
function CSTH_View_getImageSrc(aRow, aCol)
{
var grippyRow = that.getGrippyRow(); var grippyRow = that.getGrippyRow();
if (aRow === grippyRow) if (aRow === grippyRow) {
return ""; return "";
}
aRow = aRow < grippyRow ? aRow : aRow - 1; aRow = aRow < grippyRow ? aRow : aRow - 1;
return this._getImageSrc(aRow, aCol); return this._getImageSrc(aRow, aCol);
}; };
view.isContainer = function CSTH_View_isContainer(aRow) { return false; }; view.isContainer = function(aRow) { return false; };
view.getParentIndex = function CSTH_View_getParentIndex(aRow) { return -1; }; view.getParentIndex = function(aRow) { return -1; };
view.getLevel = function CSTH_View_getLevel(aRow) { return 0; }; view.getLevel = function(aRow) { return 0; };
view.hasNextSibling = function CSTH_View_hasNextSibling(aRow, aAfterIndex) view.hasNextSibling = function(aRow, aAfterIndex) {
{ return aRow < this.rowCount - 1;
return aRow < this.rowCount - 1; };
};
return view; return view;
} }

View file

@ -15,14 +15,15 @@ XPCOMUtils.defineLazyModuleGetter(this, "ShellService",
XPCOMUtils.defineLazyModuleGetter(this, "Deprecated", XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
"resource://gre/modules/Deprecated.jsm"); "resource://gre/modules/Deprecated.jsm");
XPCOMUtils.defineLazyGetter(this, "BROWSER_NEW_TAB_URL", function () { XPCOMUtils.defineLazyGetter(this, "BROWSER_NEW_TAB_URL", function() {
const PREF = "browser.newtab.url"; const PREF = "browser.newtab.url";
function getNewTabPageURL() { function getNewTabPageURL() {
if (!Services.prefs.prefHasUserValue(PREF)) { if (!Services.prefs.prefHasUserValue(PREF)) {
if (PrivateBrowsingUtils.isWindowPrivate(window) && if (PrivateBrowsingUtils.isWindowPrivate(window) &&
!PrivateBrowsingUtils.permanentPrivateBrowsing) !PrivateBrowsingUtils.permanentPrivateBrowsing) {
return "about:privatebrowsing"; return "about:privatebrowsing";
}
} }
return Services.prefs.getCharPref(PREF) || "about:blank"; return Services.prefs.getCharPref(PREF) || "about:blank";
} }
@ -49,14 +50,13 @@ var gBidiUI = false;
* Determines whether the given url is considered a special URL for new tabs. * Determines whether the given url is considered a special URL for new tabs.
*/ */
function isBlankPageURL(aURL) { function isBlankPageURL(aURL) {
// Pale Moon: Only make "about:blank", the logopage, or "about:newtab" be // Only make "about:blank", the logopage, or "about:newtab" be
// a "blank page" to fix focus issues. // a "blank page" to fix focus issues.
// Original code: return aURL == "about:blank" || aURL == BROWSER_NEW_TAB_URL; // Original code: return aURL == "about:blank" || aURL == BROWSER_NEW_TAB_URL;
return aURL == "about:blank" || aURL == "about:newtab" || aURL == "about:logopage"; return aURL == "about:blank" || aURL == "about:newtab" || aURL == "about:logopage";
} }
function getBrowserURL() function getBrowserURL() {
{
return "chrome://browser/content/browser.xul"; return "chrome://browser/content/browser.xul";
} }
@ -73,12 +73,13 @@ function getTopWin(skipPopups) {
// whether it's the frontmost window, since commands can be executed in // whether it's the frontmost window, since commands can be executed in
// background windows (bug 626148). // background windows (bug 626148).
if (top.document.documentElement.getAttribute("windowtype") == "navigator:browser" && if (top.document.documentElement.getAttribute("windowtype") == "navigator:browser" &&
(!skipPopups || top.toolbar.visible)) (!skipPopups || top.toolbar.visible)) {
return top; return top;
}
let isPrivate = PrivateBrowsingUtils.isWindowPrivate(window); let isPrivate = PrivateBrowsingUtils.isWindowPrivate(window);
return RecentWindow.getMostRecentBrowserWindow({private: isPrivate, return RecentWindow.getMostRecentBrowserWindow({ private: isPrivate,
allowPopups: !skipPopups}); allowPopups: !skipPopups });
} }
function openTopWin(url) { function openTopWin(url) {
@ -137,13 +138,13 @@ function openUILink(url, event, aIgnoreButton, aIgnoreAlt, aAllowThirdPartyFixup
* - Alt can't be used on the bookmarks toolbar because Alt is used for "treat this as something draggable". * - Alt can't be used on the bookmarks toolbar because Alt is used for "treat this as something draggable".
* - The button is ignored for the middle-click-paste-URL feature, since it's always a middle-click. * - The button is ignored for the middle-click-paste-URL feature, since it's always a middle-click.
*/ */
function whereToOpenLink( e, ignoreButton, ignoreAlt ) function whereToOpenLink(e, ignoreButton, ignoreAlt) {
{
// This method must treat a null event like a left click without modifier keys (i.e. // This method must treat a null event like a left click without modifier keys (i.e.
// e = { shiftKey:false, ctrlKey:false, metaKey:false, altKey:false, button:0 }) // e = { shiftKey:false, ctrlKey:false, metaKey:false, altKey:false, button:0 })
// for compatibility purposes. // for compatibility purposes.
if (!e) if (!e) {
return "current"; return "current";
}
var shift = e.shiftKey; var shift = e.shiftKey;
var ctrl = e.ctrlKey; var ctrl = e.ctrlKey;
@ -157,17 +158,20 @@ function whereToOpenLink( e, ignoreButton, ignoreAlt )
// Don't do anything special with right-mouse clicks. They're probably clicks on context menu items. // Don't do anything special with right-mouse clicks. They're probably clicks on context menu items.
#ifdef XP_MACOSX #ifdef XP_MACOSX
if (meta || (middle && middleUsesTabs)) if (meta || (middle && middleUsesTabs)) {
#else #else
if (ctrl || (middle && middleUsesTabs)) if (ctrl || (middle && middleUsesTabs)) {
#endif #endif
return shift ? "tabshifted" : "tab"; return shift ? "tabshifted" : "tab";
}
if (alt && Services.prefs.getBoolPref("browser.altClickSave", false)) if (alt && Services.prefs.getBoolPref("browser.altClickSave", false)) {
return "save"; return "save";
}
if (shift || (middle && !middleUsesTabs)) if (shift || (middle && !middleUsesTabs)) {
return "window"; return "window";
}
return "current"; return "current";
} }
@ -213,8 +217,9 @@ function openUILinkIn(url, where, aAllowThirdPartyFixup, aPostData, aReferrerURI
/* eslint-disable complexity */ /* eslint-disable complexity */
function openLinkIn(url, where, params) { function openLinkIn(url, where, params) {
if (!where || !url) if (!where || !url) {
return; return;
}
const Cc = Components.classes; const Cc = Components.classes;
const Ci = Components.interfaces; const Ci = Components.interfaces;
@ -224,7 +229,8 @@ function openLinkIn(url, where, params) {
var aCharset = params.charset; var aCharset = params.charset;
var aReferrerURI = params.referrerURI; var aReferrerURI = params.referrerURI;
var aReferrerPolicy = ('referrerPolicy' in params ? var aReferrerPolicy = ('referrerPolicy' in params ?
params.referrerPolicy : Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT); params.referrerPolicy :
Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT);
var aRelatedToCurrent = params.relatedToCurrent; var aRelatedToCurrent = params.relatedToCurrent;
var aForceAllowDataURI = params.forceAllowDataURI; var aForceAllowDataURI = params.forceAllowDataURI;
var aInBackground = params.inBackground; var aInBackground = params.inBackground;
@ -233,8 +239,7 @@ function openLinkIn(url, where, params) {
var aIsPrivate = params.private; var aIsPrivate = params.private;
var aPrincipal = params.originPrincipal; var aPrincipal = params.originPrincipal;
var aTriggeringPrincipal = params.triggeringPrincipal; var aTriggeringPrincipal = params.triggeringPrincipal;
var aForceAboutBlankViewerInCurrent = var aForceAboutBlankViewerInCurrent = params.forceAboutBlankViewerInCurrent;
params.forceAboutBlankViewerInCurrent;
var sendReferrerURI = true; var sendReferrerURI = true;
if (where == "save") { if (where == "save") {
@ -284,33 +289,30 @@ function openLinkIn(url, where, params) {
sendReferrerURI = false; sendReferrerURI = false;
} }
var sa = Cc["@mozilla.org/supports-array;1"]. var sa = Cc["@mozilla.org/supports-array;1"].createInstance(Ci.nsISupportsArray);
createInstance(Ci.nsISupportsArray);
var wuri = Cc["@mozilla.org/supports-string;1"]. var wuri = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
createInstance(Ci.nsISupportsString);
wuri.data = url; wuri.data = url;
let charset = null; let charset = null;
if (aCharset) { if (aCharset) {
charset = Cc["@mozilla.org/supports-string;1"] charset = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
.createInstance(Ci.nsISupportsString);
charset.data = "charset=" + aCharset; charset.data = "charset=" + aCharset;
} }
var allowThirdPartyFixupSupports = Cc["@mozilla.org/supports-PRBool;1"]. var allowThirdPartyFixupSupports = Cc["@mozilla.org/supports-PRBool;1"]
createInstance(Ci.nsISupportsPRBool); .createInstance(Ci.nsISupportsPRBool);
allowThirdPartyFixupSupports.data = aAllowThirdPartyFixup; allowThirdPartyFixupSupports.data = aAllowThirdPartyFixup;
var referrerURISupports = null; var referrerURISupports = null;
if (aReferrerURI && sendReferrerURI) { if (aReferrerURI && sendReferrerURI) {
referrerURISupports = Cc["@mozilla.org/supports-string;1"]. referrerURISupports = Cc["@mozilla.org/supports-string;1"]
createInstance(Ci.nsISupportsString); .createInstance(Ci.nsISupportsString);
referrerURISupports.data = aReferrerURI.spec; referrerURISupports.data = aReferrerURI.spec;
} }
var referrerPolicySupports = Cc["@mozilla.org/supports-PRUint32;1"]. var referrerPolicySupports = Cc["@mozilla.org/supports-PRUint32;1"]
createInstance(Ci.nsISupportsPRUint32); .createInstance(Ci.nsISupportsPRUint32);
referrerPolicySupports.data = aReferrerPolicy; referrerPolicySupports.data = aReferrerPolicy;
sa.AppendElement(wuri); sa.AppendElement(wuri);
@ -334,15 +336,16 @@ function openLinkIn(url, where, params) {
let loadInBackground = where == "current" ? false : aInBackground; let loadInBackground = where == "current" ? false : aInBackground;
if (loadInBackground == null) { if (loadInBackground == null) {
loadInBackground = aFromChrome ? loadInBackground = aFromChrome ?
false : false :
Services.prefs.getBoolPref("browser.tabs.loadInBackground"); Services.prefs.getBoolPref("browser.tabs.loadInBackground");
} }
let uriObj; let uriObj;
if (where == "current") { if (where == "current") {
try { try {
uriObj = Services.io.newURI(url, null, null); uriObj = Services.io.newURI(url, null, null);
} catch (e) {} } catch(e) {
}
} }
if (where == "current" && w.gBrowser.selectedTab.pinned) { if (where == "current" && w.gBrowser.selectedTab.pinned) {
@ -353,7 +356,7 @@ function openLinkIn(url, where, params) {
where = "tab"; where = "tab";
loadInBackground = false; loadInBackground = false;
} }
} catch (err) { } catch(err) {
where = "tab"; where = "tab";
loadInBackground = false; loadInBackground = false;
} }
@ -365,53 +368,51 @@ function openLinkIn(url, where, params) {
let browserUsedForLoad = null; let browserUsedForLoad = null;
switch (where) { switch (where) {
case "current": case "current":
let flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE; let flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
if (aAllowThirdPartyFixup) { if (aAllowThirdPartyFixup) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP; flags |= Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FIXUP_SCHEME_TYPOS; flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
} }
if (aDisallowInheritPrincipal) if (aDisallowInheritPrincipal) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL; flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL;
if (aForceAllowDataURI) { }
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FORCE_ALLOW_DATA_URI; if (aForceAllowDataURI) {
} flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FORCE_ALLOW_DATA_URI;
let {URI_INHERITS_SECURITY_CONTEXT} = Ci.nsIProtocolHandler; }
if (aForceAboutBlankViewerInCurrent && let {URI_INHERITS_SECURITY_CONTEXT} = Ci.nsIProtocolHandler;
(!uriObj || if (aForceAboutBlankViewerInCurrent &&
(Services.io.getProtocolFlags(uriObj.scheme) & URI_INHERITS_SECURITY_CONTEXT))) { (!uriObj ||
// Unless we know for sure we're not inheriting principals, (Services.io.getProtocolFlags(uriObj.scheme) & URI_INHERITS_SECURITY_CONTEXT))) {
// force the about:blank viewer to have the right principal: // Unless we know for sure we're not inheriting principals,
w.gBrowser.selectedBrowser.createAboutBlankContentViewer(aPrincipal); // force the about:blank viewer to have the right principal:
} w.gBrowser.selectedBrowser.createAboutBlankContentViewer(aPrincipal);
}
w.gBrowser.loadURIWithFlags(url, { w.gBrowser.loadURIWithFlags(url, { flags: flags,
flags: flags, triggeringPrincipal: aTriggeringPrincipal,
triggeringPrincipal: aTriggeringPrincipal, referrerURI: aReferrerURI,
referrerURI: aReferrerURI, referrerPolicy: aReferrerPolicy,
referrerPolicy: aReferrerPolicy, postData: aPostData,
postData: aPostData, originPrincipal: aPrincipal });
originPrincipal: aPrincipal, browserUsedForLoad = aCurrentBrowser;
}); break;
browserUsedForLoad = aCurrentBrowser; case "tabshifted":
break; loadInBackground = !loadInBackground;
case "tabshifted": // fall through
loadInBackground = !loadInBackground; case "tab":
// fall through let browser = w.gBrowser;
case "tab": let tabUsedForLoad = browser.loadOneTab(url, { referrerURI: aReferrerURI,
let browser = w.gBrowser; referrerPolicy: aReferrerPolicy,
let tabUsedForLoad = browser.loadOneTab(url, { charset: aCharset,
referrerURI: aReferrerURI, postData: aPostData,
referrerPolicy: aReferrerPolicy, inBackground: loadInBackground,
charset: aCharset, allowThirdPartyFixup: aAllowThirdPartyFixup,
postData: aPostData, relatedToCurrent: aRelatedToCurrent,
inBackground: loadInBackground, originPrincipal: aPrincipal,
allowThirdPartyFixup: aAllowThirdPartyFixup, triggeringPrincipal: aTriggeringPrincipal });
relatedToCurrent: aRelatedToCurrent, browserUsedForLoad = tabUsedForLoad.linkedBrowser;
originPrincipal: aPrincipal, break;
triggeringPrincipal: aTriggeringPrincipal });
browserUsedForLoad = tabUsedForLoad.linkedBrowser;
break;
} }
// Focus the content, but only if the browser used for the load is selected. // Focus the content, but only if the browser used for the load is selected.
@ -420,10 +421,11 @@ function openLinkIn(url, where, params) {
browserUsedForLoad.focus(); browserUsedForLoad.focus();
} }
if (!loadInBackground && w.isBlankPageURL(url)) if (!loadInBackground && w.isBlankPageURL(url)) {
if (!w.focusAndSelectUrlBar()) { if (!w.focusAndSelectUrlBar()) {
console.error("Unable to focus and select address bar.") console.error("Unable to focus and select address bar.")
} }
}
} }
// Used as an onclick handler for UI elements with link-like behavior. // Used as an onclick handler for UI elements with link-like behavior.
@ -432,15 +434,18 @@ function checkForMiddleClick(node, event) {
// We should be using the disabled property here instead of the attribute, // We should be using the disabled property here instead of the attribute,
// but some elements that this function is used with don't support it (e.g. // but some elements that this function is used with don't support it (e.g.
// menuitem). // menuitem).
if (node.getAttribute("disabled") == "true") if (node.getAttribute("disabled") == "true") {
return; // Do nothing // Do nothing
return;
}
if (event.button == 1) { if (event.button == 1) {
/* Execute the node's oncommand or command. /* Execute the node's oncommand or command.
* *
* XXX: we should use node.oncommand(event) once bug 246720 is fixed. * XXX: we should use node.oncommand(event) once bug 246720 is fixed.
*/ */
var target = node.hasAttribute("oncommand") ? node : var target = node.hasAttribute("oncommand") ?
node :
node.ownerDocument.getElementById(node.getAttribute("command")); node.ownerDocument.getElementById(node.getAttribute("command"));
var fn = new Function("event", target.getAttribute("oncommand")); var fn = new Function("event", target.getAttribute("oncommand"));
fn.call(target, event); fn.call(target, event);
@ -455,17 +460,17 @@ function checkForMiddleClick(node, event) {
function closeMenus(node) function closeMenus(node)
{ {
if ("tagName" in node) { if ("tagName" in node) {
if (node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" if (node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" &&
&& (node.tagName == "menupopup" || node.tagName == "popup")) (node.tagName == "menupopup" || node.tagName == "popup")) {
node.hidePopup(); node.hidePopup();
}
closeMenus(node.parentNode); closeMenus(node.parentNode);
} }
} }
// Gather all descendent text under given document node. // Gather all descendant text under given document node.
function gatherTextUnder ( root ) function gatherTextUnder(root) {
{
var text = ""; var text = "";
var node = root.firstChild; var node = root.firstChild;
var depth = 1; var depth = 1;
@ -509,15 +514,15 @@ function gatherTextUnder ( root )
} }
// This function exists for legacy reasons. // This function exists for legacy reasons.
function getShellService() function getShellService() {
{
return ShellService; return ShellService;
} }
function isBidiEnabled() { function isBidiEnabled() {
// first check the pref. // first check the pref.
if (Services.prefs.getBoolPref("bidi.browser.ui", false)) if (Services.prefs.getBoolPref("bidi.browser.ui", false)) {
return true; return true;
}
// if the pref isn't set, check for an RTL locale and force the pref to true // if the pref isn't set, check for an RTL locale and force the pref to true
// if we find one. // if we find one.
@ -537,7 +542,8 @@ function isBidiEnabled() {
rv = true; rv = true;
Services.prefs.setBoolPref("bidi.browser.ui", true); Services.prefs.setBoolPref("bidi.browser.ui", true);
} }
} catch (e) {} } catch (e) {
}
return rv; return rv;
} }
@ -546,22 +552,20 @@ function isBidiEnabled() {
/** /**
* Opens the update manager and checks for updates to the application. * Opens the update manager and checks for updates to the application.
*/ */
function checkForUpdates() function checkForUpdates() {
{ var um = Components.classes["@mozilla.org/updates/update-manager;1"]
var um = .getService(Components.interfaces.nsIUpdateManager);
Components.classes["@mozilla.org/updates/update-manager;1"]. var prompter = Components.classes["@mozilla.org/updates/update-prompt;1"]
getService(Components.interfaces.nsIUpdateManager); .createInstance(Components.interfaces.nsIUpdatePrompt);
var prompter =
Components.classes["@mozilla.org/updates/update-prompt;1"].
createInstance(Components.interfaces.nsIUpdatePrompt);
// If there's an update ready to be applied, show the "Update Downloaded" // If there's an update ready to be applied, show the "Update Downloaded"
// UI instead and let the user know they have to restart the application for // UI instead and let the user know they have to restart the application for
// the changes to be applied. // the changes to be applied.
if (um.activeUpdate && ["pending", "pending-elevate", "applied"].includes(um.activeUpdate.state)) if (um.activeUpdate && ["pending", "pending-elevate", "applied"].includes(um.activeUpdate.state)) {
prompter.showUpdateDownloaded(um.activeUpdate); prompter.showUpdateDownloaded(um.activeUpdate);
else } else {
prompter.checkForUpdates(); prompter.checkForUpdates();
}
} }
#endif #endif
@ -569,15 +573,12 @@ function checkForUpdates()
* Set up the help menu software update items to show proper status, * Set up the help menu software update items to show proper status,
* also disabling the items if update is disabled. * also disabling the items if update is disabled.
*/ */
function buildHelpMenu() function buildHelpMenu() {
{
#ifdef MOZ_UPDATER #ifdef MOZ_UPDATER
var updates = var updates = Components.classes["@mozilla.org/updates/update-service;1"]
Components.classes["@mozilla.org/updates/update-service;1"]. .getService(Components.interfaces.nsIApplicationUpdateService);
getService(Components.interfaces.nsIApplicationUpdateService); var um = Components.classes["@mozilla.org/updates/update-manager;1"]
var um = .getService(Components.interfaces.nsIUpdateManager);
Components.classes["@mozilla.org/updates/update-manager;1"].
getService(Components.interfaces.nsIUpdateManager);
// Disable the UI if the update enabled pref has been locked by the // Disable the UI if the update enabled pref has been locked by the
// administrator or if we cannot update for some other reason. // administrator or if we cannot update for some other reason.
@ -601,8 +602,9 @@ function buildHelpMenu()
// If there's an active update, substitute its name into the label // If there's an active update, substitute its name into the label
// we show for this item, otherwise display a generic label. // we show for this item, otherwise display a generic label.
function getStringWithUpdateName(key) { function getStringWithUpdateName(key) {
if (activeUpdate && activeUpdate.name) if (activeUpdate && activeUpdate.name) {
return strings.getFormattedString(key, [activeUpdate.name]); return strings.getFormattedString(key, [activeUpdate.name]);
}
return strings.getString(key + "Fallback"); return strings.getString(key + "Fallback");
} }
@ -611,20 +613,20 @@ function buildHelpMenu()
var key = "default"; var key = "default";
if (activeUpdate) { if (activeUpdate) {
switch (activeUpdate.state) { switch (activeUpdate.state) {
case "downloading": case "downloading":
// If we're downloading an update at present, show the text: // If we're downloading an update at present, show the text:
// "Downloading Thunderbird x.x..." from updatesItem_downloading or // "Downloading Thunderbird x.x..." from updatesItem_downloading or
// updatesItem_downloadingFallback, otherwise we're paused, and show // updatesItem_downloadingFallback, otherwise we're paused, and show
// "Resume Downloading Thunderbird x.x..." from updatesItem_resume or // "Resume Downloading Thunderbird x.x..." from updatesItem_resume or
// updatesItem_resumeFallback // updatesItem_resumeFallback
key = updates.isDownloading ? "downloading" : "resume"; key = updates.isDownloading ? "downloading" : "resume";
break; break;
case "pending": case "pending":
// If we're waiting for the user to restart, show: "Apply Downloaded // If we're waiting for the user to restart, show: "Apply Downloaded
// Updates Now..." from updatesItem_pending or // Updates Now..." from updatesItem_pending or
// updatesItem_pendingFallback // updatesItem_pendingFallback
key = "pending"; key = "pending";
break; break;
} }
} }
@ -636,12 +638,10 @@ function buildHelpMenu()
// updatesItem_default.accesskey, updatesItem_downloading.accesskey, // updatesItem_default.accesskey, updatesItem_downloading.accesskey,
// updatesItem_resume.accesskey or updatesItem_pending.accesskey // updatesItem_resume.accesskey or updatesItem_pending.accesskey
checkForUpdates.accessKey = strings.getString("updatesItem_" + key + checkForUpdates.accessKey = strings.getString("updatesItem_" + key + ".accesskey");
".accesskey");
if (appMenuCheckForUpdates) { if (appMenuCheckForUpdates) {
appMenuCheckForUpdates.accessKey = strings.getString("updatesItem_" + key + appMenuCheckForUpdates.accessKey = strings.getString("updatesItem_" + key + ".accesskey");
".accesskey");
} }
if (um.activeUpdate && updates.isDownloading) { if (um.activeUpdate && updates.isDownloading) {
@ -664,8 +664,9 @@ function buildHelpMenu()
var aboutSeparator = document.getElementById("aboutSeparator"); var aboutSeparator = document.getElementById("aboutSeparator");
var checkForUpdates = document.getElementById("checkForUpdates"); var checkForUpdates = document.getElementById("checkForUpdates");
if (updatesSeparator.nextSibling === checkForUpdates && if (updatesSeparator.nextSibling === checkForUpdates &&
checkForUpdates.nextSibling === aboutSeparator) checkForUpdates.nextSibling === aboutSeparator) {
updatesSeparator.hidden = true; updatesSeparator.hidden = true;
}
#endif #endif
#endif #endif
} }
@ -690,8 +691,7 @@ function openAboutDialog() {
window.openDialog("chrome://browser/content/aboutDialog.xul", "", features); window.openDialog("chrome://browser/content/aboutDialog.xul", "", features);
} }
function openPreferences(paneID, extraArgs) function openPreferences(paneID, extraArgs) {
{
var instantApply = Services.prefs.getBoolPref("browser.preferences.instantApply", false); var instantApply = Services.prefs.getBoolPref("browser.preferences.instantApply", false);
var features = "chrome,titlebar,toolbar,centerscreen" + (instantApply ? ",dialog=no" : ",modal"); var features = "chrome,titlebar,toolbar,centerscreen" + (instantApply ? ",dialog=no" : ",modal");
@ -715,16 +715,14 @@ function openPreferences(paneID, extraArgs)
"Preferences", features, paneID, extraArgs); "Preferences", features, paneID, extraArgs);
} }
function openAdvancedPreferences(tabID) function openAdvancedPreferences(tabID) {
{
openPreferences("paneAdvanced", { "advancedTab" : tabID }); openPreferences("paneAdvanced", { "advancedTab" : tabID });
} }
/** /**
* Opens the release notes page for this version of the application. * Opens the release notes page for this version of the application.
*/ */
function openReleaseNotes() function openReleaseNotes() {
{
var relnotesURL = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"] var relnotesURL = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
.getService(Components.interfaces.nsIURLFormatter) .getService(Components.interfaces.nsIURLFormatter)
.formatURLPref("app.releaseNotesURL"); .formatURLPref("app.releaseNotesURL");
@ -736,23 +734,21 @@ function openReleaseNotes()
* Opens the troubleshooting information (about:support) page for this version * Opens the troubleshooting information (about:support) page for this version
* of the application. * of the application.
*/ */
function openTroubleshootingPage() function openTroubleshootingPage() {
{
openUILinkIn("about:support", "tab"); openUILinkIn("about:support", "tab");
} }
/** /**
* Opens the feedback page for this version of the application. * Opens the feedback page for this version of the application.
*/ */
function openFeedbackPage() function openFeedbackPage() {
{
openUILinkIn(Services.prefs.getCharPref("browser.feedback.url"), "tab"); openUILinkIn(Services.prefs.getCharPref("browser.feedback.url"), "tab");
} }
function isElementVisible(aElement) function isElementVisible(aElement) {
{ if (!aElement) {
if (!aElement)
return false; return false;
}
// If aElement or a direct or indirect parent is hidden or collapsed, // If aElement or a direct or indirect parent is hidden or collapsed,
// height, width or both will be 0. // height, width or both will be 0.
@ -794,15 +790,17 @@ function makeURLAbsolute(aBase, aUrl)
*/ */
function openNewTabWith(aURL, aDocument, aPostData, aEvent, function openNewTabWith(aURL, aDocument, aPostData, aEvent,
aAllowThirdPartyFixup, aReferrer, aReferrerPolicy) { aAllowThirdPartyFixup, aReferrer, aReferrerPolicy) {
if (aDocument) if (aDocument) {
urlSecurityCheck(aURL, aDocument.nodePrincipal); urlSecurityCheck(aURL, aDocument.nodePrincipal);
}
// As in openNewWindowWith(), we want to pass the charset of the // As in openNewWindowWith(), we want to pass the charset of the
// current document over to a new tab. // current document over to a new tab.
var originCharset = aDocument && aDocument.characterSet; var originCharset = aDocument && aDocument.characterSet;
if (!originCharset && if (!originCharset &&
document.documentElement.getAttribute("windowtype") == "navigator:browser") document.documentElement.getAttribute("windowtype") == "navigator:browser") {
originCharset = window.content.document.characterSet; originCharset = window.content.document.characterSet;
}
openLinkIn(aURL, aEvent && aEvent.shiftKey ? "tabshifted" : "tab", openLinkIn(aURL, aEvent && aEvent.shiftKey ? "tabshifted" : "tab",
{ charset: originCharset, { charset: originCharset,
@ -815,8 +813,9 @@ function openNewTabWith(aURL, aDocument, aPostData, aEvent,
function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup, function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup,
aReferrer, aReferrerPolicy) { aReferrer, aReferrerPolicy) {
if (aDocument) if (aDocument) {
urlSecurityCheck(aURL, aDocument.nodePrincipal); urlSecurityCheck(aURL, aDocument.nodePrincipal);
}
// if and only if the current window is a browser window and it has a // if and only if the current window is a browser window and it has a
// document with a character set, then extract the current charset menu // document with a character set, then extract the current charset menu
@ -824,8 +823,9 @@ function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup,
// window... // window...
var originCharset = aDocument && aDocument.characterSet; var originCharset = aDocument && aDocument.characterSet;
if (!originCharset && if (!originCharset &&
document.documentElement.getAttribute("windowtype") == "navigator:browser") document.documentElement.getAttribute("windowtype") == "navigator:browser") {
originCharset = window.content.document.characterSet; originCharset = window.content.document.characterSet;
}
openLinkIn(aURL, "window", openLinkIn(aURL, "window",
{ charset: originCharset, { charset: originCharset,
@ -847,10 +847,10 @@ function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup,
* Whether this is already a known feed or not, if true only a security * Whether this is already a known feed or not, if true only a security
* check will be performed. * check will be performed.
*/ */
function isValidFeed(aLink, aPrincipal, aIsFeed) function isValidFeed(aLink, aPrincipal, aIsFeed) {
{ if (!aLink || !aPrincipal) {
if (!aLink || !aPrincipal)
return false; return false;
}
var type = aLink.type.toLowerCase().replace(/^\s+|\s*(?:;.*)?$/g, ""); var type = aLink.type.toLowerCase().replace(/^\s+|\s*(?:;.*)?$/g, "");
if (!aIsFeed) { if (!aIsFeed) {
@ -863,8 +863,7 @@ function isValidFeed(aLink, aPrincipal, aIsFeed)
urlSecurityCheck(aLink.href, aPrincipal, urlSecurityCheck(aLink.href, aPrincipal,
Components.interfaces.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL); Components.interfaces.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
return type || "application/rss+xml"; return type || "application/rss+xml";
} } catch(ex) {
catch(ex) {
} }
} }

View file

@ -7,96 +7,91 @@ const NS_ERROR_MODULE_NETWORK = 2152398848;
const NS_NET_STATUS_READ_FROM = NS_ERROR_MODULE_NETWORK + 8; const NS_NET_STATUS_READ_FROM = NS_ERROR_MODULE_NETWORK + 8;
const NS_NET_STATUS_WROTE_TO = NS_ERROR_MODULE_NETWORK + 9; const NS_NET_STATUS_WROTE_TO = NS_ERROR_MODULE_NETWORK + 9;
function getPanelBrowser() function getPanelBrowser() {
{ return document.getElementById("web-panels-browser");
return document.getElementById("web-panels-browser");
} }
var panelProgressListener = { var panelProgressListener = {
onProgressChange : function (aWebProgress, aRequest, onProgressChange: function (aWebProgress, aRequest,
aCurSelfProgress, aMaxSelfProgress, aCurSelfProgress, aMaxSelfProgress,
aCurTotalProgress, aMaxTotalProgress) { aCurTotalProgress, aMaxTotalProgress) {
}, },
onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus) onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
{ if (!aRequest) {
if (!aRequest) return;
return;
//ignore local/resource:/chrome: files
if (aStatus == NS_NET_STATUS_READ_FROM || aStatus == NS_NET_STATUS_WROTE_TO)
return;
if (aStateFlags & Ci.nsIWebProgressListener.STATE_START &&
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
window.parent.document.getElementById('sidebar-throbber').setAttribute("loading", "true");
}
else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
window.parent.document.getElementById('sidebar-throbber').removeAttribute("loading");
}
},
onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags) {
UpdateBackForwardCommands(getPanelBrowser().webNavigation);
},
onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) {
},
onSecurityChange : function(aWebProgress, aRequest, aState) {
},
QueryInterface : function(aIID)
{
if (aIID.equals(Ci.nsIWebProgressListener) ||
aIID.equals(Ci.nsISupportsWeakReference) ||
aIID.equals(Ci.nsISupports))
return this;
throw Cr.NS_NOINTERFACE;
} }
//ignore local/resource:/chrome: files
if (aStatus == NS_NET_STATUS_READ_FROM || aStatus == NS_NET_STATUS_WROTE_TO) {
return;
}
if (aStateFlags & Ci.nsIWebProgressListener.STATE_START &&
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
window.parent.document.getElementById('sidebar-throbber').setAttribute("loading", "true");
} else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
window.parent.document.getElementById('sidebar-throbber').removeAttribute("loading");
}
},
onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) {
UpdateBackForwardCommands(getPanelBrowser().webNavigation);
},
onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) {
},
onSecurityChange: function(aWebProgress, aRequest, aState) {
},
QueryInterface: function(aIID) {
if (aIID.equals(Ci.nsIWebProgressListener) ||
aIID.equals(Ci.nsISupportsWeakReference) ||
aIID.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_NOINTERFACE;
}
}; };
var gLoadFired = false; var gLoadFired = false;
function loadWebPanel(aURI) { function loadWebPanel(aURI) {
var panelBrowser = getPanelBrowser(); var panelBrowser = getPanelBrowser();
if (gLoadFired) { if (gLoadFired) {
panelBrowser.webNavigation panelBrowser.webNavigation
.loadURI(aURI, nsIWebNavigation.LOAD_FLAGS_NONE, .loadURI(aURI, nsIWebNavigation.LOAD_FLAGS_NONE,
null, null, null); null, null, null);
} }
panelBrowser.setAttribute("cachedurl", aURI); panelBrowser.setAttribute("cachedurl", aURI);
} }
function load() function load() {
{ var panelBrowser = getPanelBrowser();
var panelBrowser = getPanelBrowser(); panelBrowser.webProgress.addProgressListener(panelProgressListener,
panelBrowser.webProgress.addProgressListener(panelProgressListener, Ci.nsIWebProgress.NOTIFY_ALL);
Ci.nsIWebProgress.NOTIFY_ALL); var cachedurl = panelBrowser.getAttribute("cachedurl")
var cachedurl = panelBrowser.getAttribute("cachedurl") if (cachedurl) {
if (cachedurl) { panelBrowser.webNavigation
panelBrowser.webNavigation .loadURI(cachedurl, nsIWebNavigation.LOAD_FLAGS_NONE, null,
.loadURI(cachedurl, nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null);
null, null); }
}
gLoadFired = true; gLoadFired = true;
} }
function unload() function unload() {
{ getPanelBrowser().webProgress.removeProgressListener(panelProgressListener);
getPanelBrowser().webProgress.removeProgressListener(panelProgressListener);
} }
function PanelBrowserStop() function PanelBrowserStop() {
{ getPanelBrowser().webNavigation.stop(nsIWebNavigation.STOP_ALL)
getPanelBrowser().webNavigation.stop(nsIWebNavigation.STOP_ALL)
} }
function PanelBrowserReload() function PanelBrowserReload() {
{ getPanelBrowser().webNavigation
getPanelBrowser().webNavigation .sessionHistory
.sessionHistory .QueryInterface(nsIWebNavigation)
.QueryInterface(nsIWebNavigation) .reload(nsIWebNavigation.LOAD_FLAGS_NONE);
.reload(nsIWebNavigation.LOAD_FLAGS_NONE);
} }