[Mypal] Begin clean up and format all js/jsm.

master
Fedor 2020-09-17 09:18:10 +03:00
parent e95b7edc02
commit 26374cae84
28 changed files with 3322 additions and 2928 deletions

View File

@ -7,8 +7,9 @@ Components.utils.import("resource://gre/modules/Services.jsm");
function init(aEvent)
{
if (aEvent.target != document)
if (aEvent.target != document) {
return;
}
try {
var distroId = Services.prefs.getCharPref("distribution.id");
@ -22,18 +23,16 @@ function init(aEvent)
try {
// This is in its own try catch due to bug 895473 and bug 900925.
var distroAbout = Services.prefs.getComplexValue("distribution.about",
Components.interfaces.nsISupportsString);
Components.interfaces.nsISupportsString);
var distroField = document.getElementById("distribution");
distroField.value = distroAbout;
distroField.style.display = "block";
}
catch (ex) {
} catch (ex) {
// Pref is unset
Components.utils.reportError(ex);
}
}
}
catch (e) {
} catch(e) {
// Pref is unset
}

View File

@ -17,10 +17,8 @@ var Cu = Components.utils;
// Services = object with smart getters for common XPCOM services
Cu.import("resource://gre/modules/Services.jsm");
var browser_autoRecovery =
{
var browser_autoRecovery = {
onLoad: function() {
var nsIAS = Ci.nsIAppStartup; // Application startup interface
if (typeof gBrowser === "undefined") {
@ -35,9 +33,9 @@ var browser_autoRecovery =
// gBrowser isn't defined, and we're not using a custom locale. Most likely
// a user-installed add-on causes issues here, so we restart in Safe Mode.
let RISM = Services.prompt.confirm(null, "Error",
"The Browser didn't start properly!\n"+
"This is usually caused by an add-on or misconfiguration.\n\n"+
"Restart in Safe Mode?");
"The Browser didn't start properly!\n"+
"This is usually caused by an add-on or misconfiguration.\n\n"+
"Restart in Safe Mode?");
if (RISM) {
Cc["@mozilla.org/toolkit/app-startup;1"].getService(nsIAS).restartInSafeMode(nsIAS.eRestart | nsIAS.eAttemptQuit);
} else {

View File

@ -30,39 +30,40 @@ function removeNotificationOnEnd(notification, installs) {
}
const gXPInstallObserver = {
_findChildShell: function (aDocShell, aSoughtShell)
{
if (aDocShell == aSoughtShell)
_findChildShell: function (aDocShell, aSoughtShell) {
if (aDocShell == aSoughtShell) {
return aDocShell;
}
var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeItem);
for (var i = 0; i < node.childCount; ++i) {
var docShell = node.getChildAt(i);
docShell = this._findChildShell(docShell, aSoughtShell);
if (docShell == aSoughtShell)
if (docShell == aSoughtShell) {
return docShell;
}
}
return null;
},
_getBrowser: function (aDocShell)
{
_getBrowser: function (aDocShell) {
for (let browser of gBrowser.browsers) {
if (this._findChildShell(browser.docShell, aDocShell))
if (this._findChildShell(browser.docShell, aDocShell)) {
return browser;
}
}
return null;
},
observe: function (aSubject, aTopic, aData)
{
observe: function (aSubject, aTopic, aData) {
var brandBundle = document.getElementById("bundle_brand");
var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo);
var browser = installInfo.browser;
// Make sure the browser is still alive.
if (!browser || gBrowser.browsers.indexOf(browser) == -1)
if (!browser || gBrowser.browsers.indexOf(browser) == -1) {
return;
}
const anchorID = "addons-notification-icon";
var messageString, action;
@ -70,152 +71,159 @@ const gXPInstallObserver = {
var notificationID = aTopic;
// Make notifications persist a minimum of 30 seconds
var options = {
timeout: Date.now() + 30000
};
var options = { timeout: Date.now() + 30000 };
switch (aTopic) {
case "addon-install-disabled":
notificationID = "xpinstall-disabled"
case "addon-install-disabled": {
notificationID = "xpinstall-disabled"
if (gPrefService.prefIsLocked("xpinstall.enabled")) {
messageString = gNavigatorBundle.getString("xpinstallDisabledMessageLocked");
buttons = [];
}
else {
messageString = gNavigatorBundle.getString("xpinstallDisabledMessage");
if (gPrefService.prefIsLocked("xpinstall.enabled")) {
messageString = gNavigatorBundle.getString("xpinstallDisabledMessageLocked");
buttons = [];
} else {
messageString = gNavigatorBundle.getString("xpinstallDisabledMessage");
action = {
label: gNavigatorBundle.getString("xpinstallDisabledButton"),
accessKey: gNavigatorBundle.getString("xpinstallDisabledButton.accesskey"),
callback: function editPrefs() {
gPrefService.setBoolPref("xpinstall.enabled", true);
}
};
}
PopupNotifications.show(browser, notificationID, messageString, anchorID,
action, null, options);
break;
case "addon-install-origin-blocked": {
messageString = gNavigatorBundle.getFormattedString("xpinstallPromptWarningOrigin",
[brandShortName]);
let popup = PopupNotifications.show(browser, notificationID,
messageString, anchorID,
null, null, options);
removeNotificationOnEnd(popup, installInfo.installs);
break; }
case "addon-install-blocked":
let originatingHost;
try {
originatingHost = installInfo.originatingURI.host;
} catch (ex) {
// Need to deal with missing originatingURI and with about:/data: URIs more gracefully,
// see bug 1063418 - but for now, bail:
return;
}
messageString = gNavigatorBundle.getFormattedString("xpinstallPromptWarning",
[brandShortName, originatingHost]);
action = {
label: gNavigatorBundle.getString("xpinstallPromptAllowButton"),
accessKey: gNavigatorBundle.getString("xpinstallPromptAllowButton.accesskey"),
callback: function() {
installInfo.install();
action = {
label: gNavigatorBundle.getString("xpinstallDisabledButton"),
accessKey: gNavigatorBundle.getString("xpinstallDisabledButton.accesskey"),
callback: function editPrefs() {
gPrefService.setBoolPref("xpinstall.enabled", true);
}
};
}
};
let popup = PopupNotifications.show(browser, notificationID, messageString,
anchorID, action, null, options);
removeNotificationOnEnd(popup, installInfo.installs);
break;
case "addon-install-started":
var needsDownload = function needsDownload(aInstall) {
return aInstall.state != AddonManager.STATE_DOWNLOADED;
}
// If all installs have already been downloaded then there is no need to
// show the download progress
if (!installInfo.installs.some(needsDownload))
return;
notificationID = "addon-progress";
messageString = gNavigatorBundle.getString("addonDownloading");
messageString = PluralForm.get(installInfo.installs.length, messageString);
options.installs = installInfo.installs;
options.contentWindow = browser.contentWindow;
options.sourceURI = browser.currentURI;
options.eventCallback = function(aEvent) {
if (aEvent != "removed")
return;
options.contentWindow = null;
options.sourceURI = null;
};
PopupNotifications.show(browser, notificationID, messageString, anchorID,
null, null, options);
break;
case "addon-install-failed":
// TODO This isn't terribly ideal for the multiple failure case
for (let install of installInfo.installs) {
let host = (installInfo.originatingURI instanceof Ci.nsIStandardURL) &&
installInfo.originatingURI.host;
if (!host)
host = (install.sourceURI instanceof Ci.nsIStandardURL) &&
install.sourceURI.host;
let error = (host || install.error == 0) ? "addonError" : "addonLocalError";
if (install.error != 0)
error += install.error;
else if (install.addon.jetsdk)
error += "JetSDK";
else if (install.addon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED)
error += "Blocklisted";
else
error += "Incompatible";
messageString = gNavigatorBundle.getString(error);
messageString = messageString.replace("#1", install.name);
if (host)
messageString = messageString.replace("#2", host);
messageString = messageString.replace("#3", brandShortName);
messageString = messageString.replace("#4", Services.appinfo.version);
PopupNotifications.show(browser, notificationID, messageString, anchorID,
action, null, options);
break;
}
break;
case "addon-install-complete":
var needsRestart = installInfo.installs.some(function(i) {
return i.addon.pendingOperations != AddonManager.PENDING_NONE;
});
case "addon-install-origin-blocked": {
messageString = gNavigatorBundle.getFormattedString("xpinstallPromptWarningOrigin",
[brandShortName]);
let popup = PopupNotifications.show(browser, notificationID,
messageString, anchorID,
null, null, options);
removeNotificationOnEnd(popup, installInfo.installs);
break;
}
case "addon-install-blocked": {
let originatingHost;
try {
originatingHost = installInfo.originatingURI.host;
} catch(ex) {
// Need to deal with missing originatingURI and with about:/data: URIs more gracefully,
// see bug 1063418 - but for now, bail:
return;
}
messageString = gNavigatorBundle.getFormattedString("xpinstallPromptWarning",
[brandShortName, originatingHost]);
if (needsRestart) {
messageString = gNavigatorBundle.getString("addonsInstalledNeedsRestart");
action = {
label: gNavigatorBundle.getString("addonInstallRestartButton"),
accessKey: gNavigatorBundle.getString("addonInstallRestartButton.accesskey"),
label: gNavigatorBundle.getString("xpinstallPromptAllowButton"),
accessKey: gNavigatorBundle.getString("xpinstallPromptAllowButton.accesskey"),
callback: function() {
Application.restart();
installInfo.install();
}
};
let popup = PopupNotifications.show(browser, notificationID, messageString,
anchorID, action, null, options);
removeNotificationOnEnd(popup, installInfo.installs);
break;
}
else {
messageString = gNavigatorBundle.getString("addonsInstalled");
action = null;
case "addon-install-started": {
var needsDownload = function needsDownload(aInstall) {
return aInstall.state != AddonManager.STATE_DOWNLOADED;
}
// If all installs have already been downloaded then there is no need to
// show the download progress
if (!installInfo.installs.some(needsDownload)) {
return;
}
notificationID = "addon-progress";
messageString = gNavigatorBundle.getString("addonDownloading");
messageString = PluralForm.get(installInfo.installs.length, messageString);
options.installs = installInfo.installs;
options.contentWindow = browser.contentWindow;
options.sourceURI = browser.currentURI;
options.eventCallback = function(aEvent) {
if (aEvent != "removed") {
return;
}
options.contentWindow = null;
options.sourceURI = null;
};
PopupNotifications.show(browser, notificationID, messageString, anchorID,
null, null, options);
break;
}
case "addon-install-failed": {
// TODO This isn't terribly ideal for the multiple failure case
for (let install of installInfo.installs) {
let host = (installInfo.originatingURI instanceof Ci.nsIStandardURL) &&
installInfo.originatingURI.host;
if (!host) {
host = (install.sourceURI instanceof Ci.nsIStandardURL) &&
install.sourceURI.host;
}
messageString = PluralForm.get(installInfo.installs.length, messageString);
messageString = messageString.replace("#1", installInfo.installs[0].name);
messageString = messageString.replace("#2", installInfo.installs.length);
messageString = messageString.replace("#3", brandShortName);
let error = (host || install.error == 0) ? "addonError" : "addonLocalError";
if (install.error != 0) {
error += install.error;
} else if (install.addon.jetsdk) {
error += "JetSDK";
} else if (install.addon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED) {
error += "Blocklisted";
} else {
error += "Incompatible";
}
// Remove notificaion on dismissal, since it's possible to cancel the
// install through the addons manager UI, making the "restart" prompt
// irrelevant.
options.removeOnDismissal = true;
messageString = gNavigatorBundle.getString(error);
messageString = messageString.replace("#1", install.name);
if (host) {
messageString = messageString.replace("#2", host);
}
messageString = messageString.replace("#3", brandShortName);
messageString = messageString.replace("#4", Services.appinfo.version);
PopupNotifications.show(browser, notificationID, messageString, anchorID,
action, null, options);
break;
PopupNotifications.show(browser, notificationID, messageString, anchorID,
action, null, options);
}
break;
}
case "addon-install-complete": {
var needsRestart = installInfo.installs.some(function(i) {
return i.addon.pendingOperations != AddonManager.PENDING_NONE;
});
if (needsRestart) {
messageString = gNavigatorBundle.getString("addonsInstalledNeedsRestart");
action = {
label: gNavigatorBundle.getString("addonInstallRestartButton"),
accessKey: gNavigatorBundle.getString("addonInstallRestartButton.accesskey"),
callback: function() {
Application.restart();
}
};
} else {
messageString = gNavigatorBundle.getString("addonsInstalled");
action = null;
}
messageString = PluralForm.get(installInfo.installs.length, messageString);
messageString = messageString.replace("#1", installInfo.installs[0].name);
messageString = messageString.replace("#2", installInfo.installs.length);
messageString = messageString.replace("#3", brandShortName);
// Remove notificaion on dismissal, since it's possible to cancel the
// install through the addons manager UI, making the "restart" prompt
// irrelevant.
options.removeOnDismissal = true;
PopupNotifications.show(browser, notificationID, messageString, anchorID,
action, null, options);
break;
}
}
}
};
@ -237,8 +245,9 @@ var AddonsMgrListener = {
.split(",")
.concat(["separator", "spacer", "spring"]);
for (let item of this.addonBar.currentSet.split(",")) {
if (defaultOrNoninteractive.indexOf(item) == -1)
if (defaultOrNoninteractive.indexOf(item) == -1) {
itemCount++;
}
}
return itemCount;
@ -247,20 +256,30 @@ var AddonsMgrListener = {
this.lastAddonBarCount = this.getAddonBarItemCount();
},
onInstalled: function(aAddon) {
if (this.getAddonBarItemCount() > this.lastAddonBarCount)
if (this.getAddonBarItemCount() > this.lastAddonBarCount) {
setToolbarVisibility(this.addonBar, true);
}
},
onUninstalling: function(aAddon) {
this.lastAddonBarCount = this.getAddonBarItemCount();
},
onUninstalled: function(aAddon) {
if (this.getAddonBarItemCount() == 0)
if (this.getAddonBarItemCount() == 0) {
setToolbarVisibility(this.addonBar, false);
}
},
onEnabling: function(aAddon) this.onInstalling(),
onEnabled: function(aAddon) this.onInstalled(),
onDisabling: function(aAddon) this.onUninstalling(),
onDisabled: function(aAddon) this.onUninstalled(),
onEnabling: function(aAddon) {
return this.onInstalling();
},
onEnabled: function(aAddon) {
return this.onInstalled();
},
onDisabling: function(aAddon) {
return this.onUninstalling();
},
onDisabled: function(aAddon) {
return this.onUninstalled();
}
};
#ifdef MOZ_PERSONAS
@ -271,8 +290,9 @@ var LightWeightThemeWebInstaller = {
case "PreviewBrowserTheme":
case "ResetBrowserThemePreview":
// ignore requests from background tabs
if (event.target.ownerDocument.defaultView.top != content)
if (event.target.ownerDocument.defaultView.top != content) {
return;
}
}
switch (event.type) {
case "InstallBrowserTheme":
@ -301,21 +321,19 @@ var LightWeightThemeWebInstaller = {
_installRequest: function (event) {
var node = event.target;
var data = this._getThemeFromNode(node);
if (!data)
if (!data) {
return;
}
if (this._isAllowed(node)) {
this._install(data);
return;
}
var allowButtonText =
gNavigatorBundle.getString("lwthemeInstallRequest.allowButton");
var allowButtonAccesskey =
gNavigatorBundle.getString("lwthemeInstallRequest.allowButton.accesskey");
var message =
gNavigatorBundle.getFormattedString("lwthemeInstallRequest.message",
[node.ownerDocument.location.host]);
var allowButtonText = gNavigatorBundle.getString("lwthemeInstallRequest.allowButton");
var allowButtonAccesskey = gNavigatorBundle.getString("lwthemeInstallRequest.allowButton.accesskey");
var message = gNavigatorBundle.getFormattedString("lwthemeInstallRequest.message",
[node.ownerDocument.location.host]);
var buttons = [{
label: allowButtonText,
accessKey: allowButtonAccesskey,
@ -339,11 +357,12 @@ var LightWeightThemeWebInstaller = {
var listener = {
onEnabling: function(aAddon, aRequiresRestart) {
if (!aRequiresRestart)
if (!aRequiresRestart) {
return;
}
let messageString = gNavigatorBundle.getFormattedString("lwthemeNeedsRestart.message",
[aAddon.name], 1);
[aAddon.name], 1);
let action = {
label: gNavigatorBundle.getString("lwthemeNeedsRestart.button"),
@ -353,9 +372,7 @@ var LightWeightThemeWebInstaller = {
}
};
let options = {
timeout: Date.now() + 30000
};
let options = { timeout: Date.now() + 30000 };
PopupNotifications.show(gBrowser.selectedBrowser, "addon-theme-change",
messageString, "addons-notification-icon",
@ -417,12 +434,14 @@ var LightWeightThemeWebInstaller = {
_previewWindow: null,
_preview: function (event) {
if (!this._isAllowed(event.target))
if (!this._isAllowed(event.target)) {
return;
}
var data = this._getThemeFromNode(event.target);
if (!data)
if (!data) {
return;
}
this._resetPreview();
@ -435,8 +454,9 @@ var LightWeightThemeWebInstaller = {
_resetPreview: function (event) {
if (!this._previewWindow ||
event && !this._isAllowed(event.target))
(event && !this._isAllowed(event.target))) {
return;
}
this._previewWindow.removeEventListener("pagehide", this, true);
this._previewWindow = null;
@ -475,8 +495,9 @@ var LightweightThemeListener = {
Services.obs.addObserver(this, "lightweight-theme-styling-update", false);
Services.obs.addObserver(this, "lightweight-theme-optimized", false);
if (document.documentElement.hasAttribute("lwtheme"))
if (document.documentElement.hasAttribute("lwtheme")) {
this.updateStyleSheet(document.documentElement.style.backgroundImage);
}
},
uninit: function () {
@ -491,8 +512,9 @@ var LightweightThemeListener = {
* @param headerImage - a string containing a CSS image for the lightweight theme header.
*/
updateStyleSheet: function(headerImage) {
if (!this.styleSheet)
if (!this.styleSheet) {
return;
}
this.substituteRules(this.styleSheet.cssRules, headerImage);
},
@ -504,11 +526,13 @@ var LightweightThemeListener = {
// Add the number of modified sub-rules to the modified count
styleRulesModified += this.substituteRules(rule.cssRules, headerImage, existingStyleRulesModified + styleRulesModified);
} else if (rule instanceof Ci.nsIDOMCSSStyleRule) {
if (!rule.style.backgroundImage)
if (!rule.style.backgroundImage) {
continue;
}
let modifiedIndex = existingStyleRulesModified + styleRulesModified;
if (!this._modifiedStyles[modifiedIndex])
if (!this._modifiedStyles[modifiedIndex]) {
this._modifiedStyles[modifiedIndex] = { backgroundImage: rule.style.backgroundImage };
}
rule.style.backgroundImage = this._modifiedStyles[modifiedIndex].backgroundImage + ", " + headerImage;
styleRulesModified++;
@ -522,15 +546,18 @@ var LightweightThemeListener = {
// nsIObserver
observe: function (aSubject, aTopic, aData) {
if ((aTopic != "lightweight-theme-styling-update" && aTopic != "lightweight-theme-optimized") ||
!this.styleSheet)
!this.styleSheet) {
return;
}
if (aTopic == "lightweight-theme-optimized" && aSubject != window)
if (aTopic == "lightweight-theme-optimized" && aSubject != window) {
return;
}
let themeData = JSON.parse(aData);
if (!themeData)
if (!themeData) {
return;
}
this.updateStyleSheet("url(" + themeData.headerURL + ")");
},
};

View File

@ -37,8 +37,9 @@ var FeedHandler = {
let feeds = gBrowser.selectedBrowser.feeds || [];
// If there are multiple feeds, the menu will open, so no need to do
// anything. If there are no feeds, nothing to do either.
if (feeds.length != 1)
if (feeds.length != 1) {
return;
}
if (event.eventPhase == Event.AT_TARGET &&
(event.button == 0 || event.button == 1)) {
@ -68,18 +69,21 @@ var FeedHandler = {
return false;
}
while (menuPopup.firstChild)
while (menuPopup.firstChild) {
menuPopup.removeChild(menuPopup.firstChild);
}
if (feeds.length == 1) {
var feedButtonPM = document.getElementById("ub-feed-button");
if (feedButtonPM)
if (feedButtonPM) {
feedButtonPM.setAttribute("feed", feeds[0].href);
}
return false;
}
if (feeds.length <= 1)
if (feeds.length <= 1) {
return false;
}
// Build the menu showing the available feed choices for viewing.
for (let feedInfo of feeds) {
@ -112,15 +116,17 @@ var FeedHandler = {
subscribeToFeed: function(href, event) {
// Just load the feed in the content area to either subscribe or show the
// preview UI
if (!href)
if (!href) {
href = event.target.getAttribute("feed");
}
urlSecurityCheck(href, gBrowser.contentPrincipal,
Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
var feedURI = makeURI(href, document.characterSet);
// Use the feed scheme so X-Moz-Is-Feed will be set
// The value doesn't matter
if (/^https?$/.test(feedURI.scheme))
if (/^https?$/.test(feedURI.scheme)) {
href = "feed:" + href;
}
this.loadFeed(href, event);
},
@ -128,8 +134,7 @@ var FeedHandler = {
var feeds = gBrowser.selectedBrowser.feeds;
try {
openUILink(href, event, { ignoreAlt: true });
}
finally {
} finally {
// We might default to a livebookmarks modal dialog,
// so reset that if the user happens to click it again
gBrowser.selectedBrowser.feeds = feeds;
@ -151,8 +156,9 @@ var FeedHandler = {
* a page is loaded or the user switches tabs to a page that has feeds.
*/
updateFeeds: function() {
if (this._updateFeedTimeout)
if (this._updateFeedTimeout) {
clearTimeout(this._updateFeedTimeout);
}
var feeds = gBrowser.selectedBrowser.feeds;
var haveFeeds = feeds && feeds.length > 0;
@ -161,8 +167,9 @@ var FeedHandler = {
var feedButton = document.getElementById("feed-button");
if (feedButton)
if (feedButton) {
feedButton.disabled = !haveFeeds;
}
if (feedButtonPM) {
if (!haveFeeds) {
@ -181,13 +188,15 @@ var FeedHandler = {
}
if (feeds.length > 1) {
if (feedButtonPM)
if (feedButtonPM) {
feedButtonPM.removeAttribute("feed");
}
this._feedMenuitem.setAttribute("hidden", "true");
this._feedMenupopup.removeAttribute("hidden");
} else {
if (feedButtonPM)
if (feedButtonPM) {
feedButtonPM.setAttribute("feed", feeds[0].href);
}
this._feedMenuitem.setAttribute("feed", feeds[0].href);
this._feedMenuitem.removeAttribute("disabled");
this._feedMenuitem.removeAttribute("hidden");
@ -203,8 +212,9 @@ var FeedHandler = {
return;
}
if (!browserForLink.feeds)
if (!browserForLink.feeds) {
browserForLink.feeds = [];
}
browserForLink.feeds.push({ href: link.href, title: link.title });
@ -212,12 +222,14 @@ var FeedHandler = {
// background browsers, we'll update on tab switch.
if (browserForLink == gBrowser.selectedBrowser) {
var feedButtonPM = document.getElementById("ub-feed-button");
if (feedButtonPM)
if (feedButtonPM) {
feedButtonPM.collapsed = !gPrefService.getBoolPref("browser.urlbar.rss");
}
// Batch updates to avoid updating the UI for multiple onLinkAdded events
// fired within 100ms of each other.
if (this._updateFeedTimeout)
if (this._updateFeedTimeout) {
clearTimeout(this._updateFeedTimeout);
}
this._updateFeedTimeout = setTimeout(this.updateFeeds.bind(this), 100);
}
}

View File

@ -37,8 +37,7 @@ var FullScreen = {
if (enterFS && this.useLionFullScreen) {
if (document.mozFullScreen) {
this.showXULChrome("toolbar", false);
}
else {
} else {
gNavToolbox.setAttribute("inFullscreen", true);
document.documentElement.setAttribute("inFullscreen", true);
}
@ -61,8 +60,7 @@ var FullScreen = {
// as the size of the content area would still be changing after the
// mozfullscreenchange event fired, which could confuse content script.
this.hideNavToolbox(document.mozFullScreen);
}
else {
} else {
this.showNavToolbox(false);
// This is needed if they use the context menu to quit fullscreen
this._isPopupOpen = false;
@ -85,15 +83,17 @@ var FullScreen = {
}
break;
case "transitionend":
if (event.propertyName == "opacity")
if (event.propertyName == "opacity") {
this.cancelWarning();
}
break;
}
},
enterDomFullscreen : function(event) {
if (!document.mozFullScreen)
if (!document.mozFullScreen) {
return;
}
// However, if we receive a "MozDOMFullscreen:NewOrigin" event for a document
// which is not a subdocument of a currently active (ie. visible) browser
@ -117,8 +117,9 @@ var FullScreen = {
document.documentElement.setAttribute("inDOMFullscreen", true);
if (gFindBarInitialized)
if (gFindBarInitialized) {
gFindBar.close();
}
this.showWarning(event.target);
@ -151,54 +152,54 @@ var FullScreen = {
gBrowser.tabContainer.removeEventListener("TabOpen", this.exitDomFullScreen);
gBrowser.tabContainer.removeEventListener("TabClose", this.exitDomFullScreen);
gBrowser.tabContainer.removeEventListener("TabSelect", this.exitDomFullScreen);
if (!this.useLionFullScreen)
if (!this.useLionFullScreen) {
window.removeEventListener("activate", this);
}
this.fullscreenDoc = null;
}
},
// Event callbacks
_expandCallback: function()
{
_expandCallback: function() {
FullScreen.showNavToolbox();
},
_collapseCallback: function()
{
_collapseCallback: function() {
FullScreen.hideNavToolbox();
},
_keyToggleCallback: function(aEvent)
{
_keyToggleCallback: function(aEvent) {
// if we can use the keyboard (eg Ctrl+L or Ctrl+E) to open the toolbars, we
// should provide a way to collapse them too.
if (aEvent.keyCode == aEvent.DOM_VK_ESCAPE) {
FullScreen.hideNavToolbox(true);
}
// F6 is another shortcut to the address bar, but its not covered in OpenLocation()
else if (aEvent.keyCode == aEvent.DOM_VK_F6)
} else if (aEvent.keyCode == aEvent.DOM_VK_F6) {
// F6 is another shortcut to the address bar, but its not covered in OpenLocation()
FullScreen.showNavToolbox();
}
},
// Checks whether we are allowed to collapse the chrome
_isPopupOpen: false,
_isChromeCollapsed: false,
_safeToCollapse: function(forceHide)
{
if (!gPrefService.getBoolPref("browser.fullscreen.autohide"))
_safeToCollapse: function(forceHide) {
if (!gPrefService.getBoolPref("browser.fullscreen.autohide")) {
return false;
}
// a popup menu is open in chrome: don't collapse chrome
if (!forceHide && this._isPopupOpen)
if (!forceHide && this._isPopupOpen) {
return false;
}
// a textbox in chrome is focused (location bar anyone?): don't collapse chrome
if (document.commandDispatcher.focusedElement &&
document.commandDispatcher.focusedElement.ownerDocument == document &&
document.commandDispatcher.focusedElement.localName == "input") {
if (forceHide)
if (forceHide) {
// hidden textboxes that still have focus are bad bad bad
document.commandDispatcher.focusedElement.blur();
else
} else {
return false;
}
}
return true;
},
@ -210,20 +211,19 @@ var FullScreen = {
// e.g. we wouldn't want the autoscroll icon firing this event, so when the user
// toggles chrome when moving mouse to the top, it doesn't go away again.
if (aEvent.type == "popupshown" && !FullScreen._isChromeCollapsed &&
aEvent.target.localName != "tooltip" && aEvent.target.localName != "window")
aEvent.target.localName != "tooltip" && aEvent.target.localName != "window") {
FullScreen._isPopupOpen = true;
else if (aEvent.type == "popuphidden" && aEvent.target.localName != "tooltip" &&
aEvent.target.localName != "window")
} else if (aEvent.type == "popuphidden" && aEvent.target.localName != "tooltip" &&
aEvent.target.localName != "window") {
FullScreen._isPopupOpen = false;
}
},
// Autohide helpers for the context menu item
getAutohide: function(aItem)
{
getAutohide: function(aItem) {
aItem.setAttribute("checked", gPrefService.getBoolPref("browser.fullscreen.autohide"));
},
setAutohide: function()
{
setAutohide: function() {
gPrefService.setBoolPref("browser.fullscreen.autohide", !gPrefService.getBoolPref("browser.fullscreen.autohide"));
},
@ -231,8 +231,9 @@ var FullScreen = {
_shouldAnimate: true,
cancelWarning: function(event) {
if (!this.warningBox)
if (!this.warningBox) {
return;
}
this.warningBox.removeEventListener("transitionend", this);
if (this.warningFadeOutTimeout) {
clearTimeout(this.warningFadeOutTimeout);
@ -257,8 +258,9 @@ var FullScreen = {
// Shows a warning that the site has entered fullscreen for a short duration.
showWarning: function(targetDoc) {
let timeout = gPrefService.getIntPref("full-screen-api.warning.timeout");
if (!document.mozFullScreen || timeout <= 0)
if (!document.mozFullScreen || timeout <= 0) {
return;
}
// Set the strings on the fullscreen warning UI.
this.fullscreenDoc = targetDoc;
@ -266,7 +268,7 @@ var FullScreen = {
let host = null;
try {
host = uri.host;
} catch (e) { }
} catch(e) {}
let hostLabel = document.getElementById("full-screen-domain-text");
if (host) {
// Document's principal's URI has a host. Display a warning including the hostname.
@ -384,16 +386,16 @@ var FullScreen = {
// Give the main nav bar and the tab bar the fullscreen context menu,
// otherwise remove context menu to prevent breakage
el.setAttribute("saved-context", el.getAttribute("context"));
if (el.id == "nav-bar" || el.id == "TabsToolbar")
if (el.id == "nav-bar" || el.id == "TabsToolbar") {
el.setAttribute("context", "autohide-context");
else
} else {
el.removeAttribute("context");
}
// Set the inFullscreen attribute to allow specific styling
// in fullscreen mode
el.setAttribute("inFullscreen", true);
}
else {
} else {
var restoreAttr = function restoreAttr(attrName) {
var savedAttr = "saved-" + attrName;
if (el.hasAttribute(savedAttr)) {
@ -411,10 +413,11 @@ var FullScreen = {
} else {
// use moz-collapsed so it doesn't persist hidden/collapsed,
// so that new windows don't have missing toolbars
if (aShow)
if (aShow) {
el.removeAttribute("moz-collapsed");
else
} else {
el.setAttribute("moz-collapsed", "true");
}
}
}
@ -433,13 +436,13 @@ var FullScreen = {
var fullscreenctls = document.getElementById("window-controls");
var navbar = document.getElementById("nav-bar");
var ctlsOnTabbar = window.toolbar.visible &&
(navbar.collapsed || (TabsOnTop.enabled &&
!gPrefService.getBoolPref("browser.tabs.autoHide")));
(navbar.collapsed ||
(TabsOnTop.enabled &&
!gPrefService.getBoolPref("browser.tabs.autoHide")));
if (fullscreenctls.parentNode == navbar && ctlsOnTabbar) {
fullscreenctls.removeAttribute("flex");
document.getElementById("TabsToolbar").appendChild(fullscreenctls);
}
else if (fullscreenctls.parentNode.id == "TabsToolbar" && !ctlsOnTabbar) {
} else if (fullscreenctls.parentNode.id == "TabsToolbar" && !ctlsOnTabbar) {
fullscreenctls.setAttribute("flex", "1");
navbar.appendChild(fullscreenctls);
}

View File

@ -134,19 +134,22 @@ var FullZoom = {
}
let browser = gBrowser.selectedBrowser;
if (!browser.currentURI)
if (!browser.currentURI) {
return;
}
let ctxt = this._loadContextFromBrowser(browser);
let domain = this._cps2.extractDomain(browser.currentURI.spec);
if (aGroup) {
if (aGroup == domain && ctxt.usePrivateBrowsing == aIsPrivate)
if (aGroup == domain && ctxt.usePrivateBrowsing == aIsPrivate) {
this._applyPrefToZoom(aValue, browser);
}
return;
}
this._globalValue = aValue === undefined ? aValue :
this._ensureValid(aValue);
this._globalValue = aValue === undefined ?
aValue :
this._ensureValid(aValue);
// If the current page doesn't have a site-specific preference, then its
// zoom should be set to the new global preference now that the global
@ -156,8 +159,9 @@ var FullZoom = {
this._cps2.getByDomainAndName(browser.currentURI.spec, this.name, ctxt, {
handleResult: function() { hasPref = true; },
handleCompletion: function() {
if (!hasPref && token.isCurrent)
if (!hasPref && token.isCurrent) {
this._applyPrefToZoom(undefined, browser);
}
}.bind(this)
});
},
@ -358,8 +362,9 @@ var FullZoom = {
Services.obs.notifyObservers(browser, "browser-fullZoom:zoomChange", "");
if (!this.siteSpecific ||
gInPrintPreviewMode ||
browser.isSyntheticDocument)
browser.isSyntheticDocument) {
return;
}
this._cps2.set(browser.currentURI.spec, this.name,
ZoomManager.getZoomForBrowser(browser),
@ -377,8 +382,9 @@ var FullZoom = {
*/
_removePref: function(browser) {
Services.obs.notifyObservers(browser, "browser-fullZoom:zoomReset", "");
if (browser.isSyntheticDocument)
if (browser.isSyntheticDocument) {
return;
}
let ctxt = this._loadContextFromBrowser(browser);
this._cps2.removeByDomainAndName(browser.currentURI.spec, this.name, ctxt, {
handleCompletion: function() {
@ -403,8 +409,9 @@ var FullZoom = {
*/
_getBrowserToken: function(browser) {
let map = this._browserTokenMap;
if (!map.has(browser))
if (!map.has(browser)) {
map.set(browser, 0);
}
return {
token: map.get(browser),
get isCurrent() {
@ -431,13 +438,15 @@ var FullZoom = {
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
if (target instanceof window.XULElement &&
target.localName == "browser" &&
target.namespaceURI == XUL_NS)
target.namespaceURI == XUL_NS) {
return target;
}
// With in-process content browsers, the event's target is the content
// document.
if (target.nodeType == Node.DOCUMENT_NODE)
if (target.nodeType == Node.DOCUMENT_NODE) {
return gBrowser.getBrowserForDocument(target);
}
throw new Error("Unexpected ZoomChangeUsingMouseWheel event source");
},
@ -457,14 +466,17 @@ var FullZoom = {
_ensureValid: function(aValue) {
// Note that undefined is a valid value for aValue that indicates a known-
// not-to-exist value.
if (isNaN(aValue))
if (isNaN(aValue)) {
return 1;
}
if (aValue < ZoomManager.MIN)
if (aValue < ZoomManager.MIN) {
return ZoomManager.MIN;
}
if (aValue > ZoomManager.MAX)
if (aValue > ZoomManager.MAX) {
return ZoomManager.MAX;
}
return aValue;
},
@ -519,8 +531,9 @@ var FullZoom = {
},
_executeSoon: function(callback) {
if (!callback)
if (!callback) {
return;
}
Services.tm.mainThread.dispatch(callback, Ci.nsIThread.DISPATCH_NORMAL);
},
};

View File

@ -126,8 +126,9 @@ var gGestureSupport = {
*/
_setupGesture: function(aEvent, aGesture, aPref, aInc, aDec) {
// Try to load user-set values from preferences
for (let [pref, def] in Iterator(aPref))
for (let [pref, def] in Iterator(aPref)) {
aPref[pref] = this._getPref(aGesture + "." + pref, def);
}
// Keep track of the total deltas and latching behavior
let offset = 0;
@ -170,10 +171,8 @@ var gGestureSupport = {
* @return true if the swipe event may navigate the history, false othwerwise.
*/
_swipeNavigatesHistory: function(aEvent) {
return this._getCommand(aEvent, ["swipe", "left"])
== "Browser:BackOrBackDuplicate" &&
this._getCommand(aEvent, ["swipe", "right"])
== "Browser:ForwardOrForwardDuplicate";
return this._getCommand(aEvent, ["swipe", "left"]) == "Browser:BackOrBackDuplicate" &&
this._getCommand(aEvent, ["swipe", "right"]) == "Browser:ForwardOrForwardDuplicate";
},
/**
@ -186,19 +185,24 @@ var gGestureSupport = {
* otherwise.
*/
_shouldDoSwipeGesture: function(aEvent) {
if (!this._swipeNavigatesHistory(aEvent))
if (!this._swipeNavigatesHistory(aEvent)) {
return false;
}
let canGoBack = gHistorySwipeAnimation.canGoBack();
let canGoForward = gHistorySwipeAnimation.canGoForward();
let isLTR = gHistorySwipeAnimation.isLTR;
if (canGoBack)
aEvent.allowedDirections |= isLTR ? aEvent.DIRECTION_LEFT :
aEvent.DIRECTION_RIGHT;
if (canGoForward)
aEvent.allowedDirections |= isLTR ? aEvent.DIRECTION_RIGHT :
aEvent.DIRECTION_LEFT;
if (canGoBack) {
aEvent.allowedDirections |= isLTR ?
aEvent.DIRECTION_LEFT :
aEvent.DIRECTION_RIGHT;
}
if (canGoForward) {
aEvent.allowedDirections |= isLTR ?
aEvent.DIRECTION_RIGHT :
aEvent.DIRECTION_LEFT;
}
return true;
},
@ -222,8 +226,8 @@ var gGestureSupport = {
this._doEnd = function(aEvent) {
gHistorySwipeAnimation.swipeEndEventReceived();
this._doUpdate = function(aEvent) {};
this._doEnd = function(aEvent) {};
this._doUpdate = function(aEvent) { };
this._doEnd = function(aEvent) { };
}
},
@ -241,8 +245,9 @@ var gGestureSupport = {
while (--num >= 0) {
// Only select array elements where the current bit is set
yield aArray.reduce(function(aPrev, aCurr, aIndex) {
if (num & 1 << aIndex)
if (num & 1 << aIndex) {
aPrev.push(aCurr);
}
return aPrev;
}, []);
}
@ -279,8 +284,9 @@ var gGestureSupport = {
// command for both don't exist)
let keyCombos = [];
["shift", "alt", "ctrl", "meta"].forEach(function(key) {
if (aEvent[key + "Key"])
if (aEvent[key + "Key"]) {
keyCombos.push(key);
}
});
// Try each combination of key presses in decreasing order for commands
@ -291,10 +297,11 @@ var gGestureSupport = {
let command;
try {
command = this._getPref(aGesture.concat(subCombo).join("."));
} catch (e) {}
} catch(e) {}
if (command)
if (command) {
return command;
}
}
return null;
},
@ -318,8 +325,7 @@ var gGestureSupport = {
node.dispatchEvent(cmdEvent);
}
}
else {
} else {
goDoCommand(aCommand);
}
},
@ -331,7 +337,7 @@ var gGestureSupport = {
* @param aEvent
* The continual motion update event to handle
*/
_doUpdate: function(aEvent) {},
_doUpdate: function(aEvent) { },
/**
* Handle gesture end events. This function will be set by _setupSwipe.
@ -339,7 +345,7 @@ var gGestureSupport = {
* @param aEvent
* The gesture end event to handle
*/
_doEnd: function(aEvent) {},
_doEnd: function(aEvent) { },
/**
* Convert the swipe gesture into a browser action based on the direction.
@ -380,13 +386,11 @@ var gGestureSupport = {
* @param aDir
* The direction for the swipe event
*/
_coordinateSwipeEventWithAnimation:
function(aEvent, aDir) {
_coordinateSwipeEventWithAnimation: function(aEvent, aDir) {
if ((gHistorySwipeAnimation.isAnimationRunning()) &&
(aDir == "RIGHT" || aDir == "LEFT")) {
gHistorySwipeAnimation.processSwipeEvent(aEvent, aDir);
}
else {
} else {
this.processSwipeEvent(aEvent, aDir);
}
},
@ -406,11 +410,13 @@ var gGestureSupport = {
try {
// Determine what type of data to load based on default value's type
let type = typeof aDef;
let getFunc = "get" + (type == "boolean" ? "Bool" :
type == "number" ? "Int" : "Char") + "Pref";
let getFunc = "get" + (type == "boolean" ?
"Bool" :
type == "number" ?
"Int" :
"Char") + "Pref";
return gPrefService[getFunc](branch + aPref);
}
catch (e) {
} catch(e) {
return aDef;
}
},
@ -422,15 +428,18 @@ var gGestureSupport = {
* The MozRotateGestureUpdate event triggering this call
*/
rotate: function(aEvent) {
if (!(content.document instanceof ImageDocument))
if (!(content.document instanceof ImageDocument)) {
return;
}
let contentElement = content.document.body.firstElementChild;
if (!contentElement)
if (!contentElement) {
return;
}
// If we're currently snapping, cancel that snap
if (contentElement.classList.contains("completeRotation"))
if (contentElement.classList.contains("completeRotation")) {
this._clearCompleteRotation();
}
this.rotation = Math.round(this.rotation + aEvent.delta);
contentElement.style.transform = "rotate(" + this.rotation + "deg)";
@ -441,37 +450,41 @@ var gGestureSupport = {
* Perform a rotation end for ImageDocuments
*/
rotateEnd: function() {
if (!(content.document instanceof ImageDocument))
if (!(content.document instanceof ImageDocument)) {
return;
}
let contentElement = content.document.body.firstElementChild;
if (!contentElement)
if (!contentElement) {
return;
}
let transitionRotation = 0;
// The reason that 360 is allowed here is because when rotating between
// 315 and 360, setting rotate(0deg) will cause it to rotate the wrong
// direction around--spinning wildly.
if (this.rotation <= 45)
if (this.rotation <= 45) {
transitionRotation = 0;
else if (this.rotation > 45 && this.rotation <= 135)
} else if (this.rotation > 45 && this.rotation <= 135) {
transitionRotation = 90;
else if (this.rotation > 135 && this.rotation <= 225)
} else if (this.rotation > 135 && this.rotation <= 225) {
transitionRotation = 180;
else if (this.rotation > 225 && this.rotation <= 315)
} else if (this.rotation > 225 && this.rotation <= 315) {
transitionRotation = 270;
else
} else {
transitionRotation = 360;
}
// If we're going fast enough, and we didn't already snap ahead of rotation,
// then snap ahead of rotation to simulate momentum
if (this._lastRotateDelta > this._rotateMomentumThreshold &&
this.rotation > transitionRotation)
this.rotation > transitionRotation) {
transitionRotation += 90;
else if (this._lastRotateDelta < -1 * this._rotateMomentumThreshold &&
this.rotation < transitionRotation)
} else if (this._lastRotateDelta < -1 * this._rotateMomentumThreshold &&
this.rotation < transitionRotation) {
transitionRotation -= 90;
}
// Only add the completeRotation class if it is is necessary
if (transitionRotation != this.rotation) {
@ -499,8 +512,9 @@ var gGestureSupport = {
*/
set rotation(aVal) {
this._currentRotation = aVal % 360;
if (this._currentRotation < 0)
if (this._currentRotation < 0) {
this._currentRotation += 360;
}
return this._currentRotation;
},
@ -509,8 +523,9 @@ var gGestureSupport = {
* image
*/
restoreRotationState: function() {
if (!(content.document instanceof ImageDocument))
if (!(content.document instanceof ImageDocument)) {
return;
}
let contentElement = content.document.body.firstElementChild;
let transformValue = content.window.getComputedStyle(contentElement, null)
@ -538,8 +553,9 @@ var gGestureSupport = {
content.document instanceof ImageDocument &&
content.document.body &&
content.document.body.firstElementChild;
if (!contentElement)
if (!contentElement) {
return;
}
contentElement.classList.remove("completeRotation");
contentElement.removeEventListener("transitionend", this._clearCompleteRotation);
},
@ -556,8 +572,9 @@ var gHistorySwipeAnimation = {
* by the platform/configuration.
*/
init: function() {
if (!this._isSupported())
if (!this._isSupported()) {
return;
}
this.active = false;
this.isLTR = document.documentElement.matches(":-moz-locale-dir(ltr)");
@ -604,8 +621,7 @@ var gHistorySwipeAnimation = {
this._canGoBack = this.canGoBack();
this._canGoForward = this.canGoForward();
this._handleFastSwiping();
}
else {
} else {
this._historyIndex = gBrowser.webNavigation.sessionHistory.index;
this._canGoBack = this.canGoBack();
this._canGoForward = this.canGoForward();
@ -635,18 +651,22 @@ var gHistorySwipeAnimation = {
* swipe gesture.
*/
updateAnimation: function(aVal) {
if (!this.isAnimationRunning())
if (!this.isAnimationRunning()) {
return;
}
if ((aVal >= 0 && this.isLTR) ||
(aVal <= 0 && !this.isLTR)) {
if (aVal > 1)
aVal = 1; // Cap value to avoid sliding the page further than allowed.
if (aVal > 1) {
// Cap value to avoid sliding the page further than allowed.
aVal = 1;
}
if (this._canGoBack)
if (this._canGoBack) {
this._prevBox.collapsed = false;
else
} else {
this._prevBox.collapsed = true;
}
// The current page is pushed to the right (LTR) or left (RTL),
// the intention is to go back.
@ -655,10 +675,11 @@ var gHistorySwipeAnimation = {
// The forward page should be pushed offscreen all the way to the right.
this._positionBox(this._nextBox, 1);
}
else {
if (aVal < -1)
aVal = -1; // Cap value to avoid sliding the page further than allowed.
} else {
if (aVal < -1) {
// Cap value to avoid sliding the page further than allowed.
aVal = -1;
}
// The intention is to go forward. If there is a page to go forward to,
// it should slide in from the right (LTR) or left (RTL).
// Otherwise, the current page should slide to the left (LTR) or
@ -670,8 +691,7 @@ var gHistorySwipeAnimation = {
let offset = this.isLTR ? 1 : -1;
this._positionBox(this._curBox, 0);
this._positionBox(this._nextBox, offset + aVal); // aval is negative
}
else {
} else {
this._prevBox.collapsed = true;
this._positionBox(this._curBox, aVal);
}
@ -736,12 +756,13 @@ var gHistorySwipeAnimation = {
* The direction for the swipe event
*/
processSwipeEvent: function(aEvent, aDir) {
if (aDir == "RIGHT")
if (aDir == "RIGHT") {
this._historyIndex += this.isLTR ? 1 : -1;
else if (aDir == "LEFT")
} else if (aDir == "LEFT") {
this._historyIndex += this.isLTR ? -1 : 1;
else
} else {
return;
}
this._lastSwipeDir = aDir;
},
@ -751,8 +772,9 @@ var gHistorySwipeAnimation = {
* @return true if there is a previous page in history, false otherwise.
*/
canGoBack: function() {
if (this.isAnimationRunning())
if (this.isAnimationRunning()) {
return this._doesIndexExistInHistory(this._historyIndex - 1);
}
return gBrowser.webNavigation.canGoBack;
},
@ -762,8 +784,9 @@ var gHistorySwipeAnimation = {
* @return true if there is a next page in history, false otherwise.
*/
canGoForward: function() {
if (this.isAnimationRunning())
if (this.isAnimationRunning()) {
return this._doesIndexExistInHistory(this._historyIndex + 1);
}
return gBrowser.webNavigation.canGoForward;
},
@ -773,10 +796,11 @@ var gHistorySwipeAnimation = {
* any. This will also result in the animation overlay to be torn down.
*/
swipeEndEventReceived: function() {
if (this._lastSwipeDir != "")
if (this._lastSwipeDir != "") {
this._navigateToHistoryIndex();
else
} else {
this.stopAnimation();
}
},
/**
@ -789,8 +813,7 @@ var gHistorySwipeAnimation = {
_doesIndexExistInHistory: function(aIndex) {
try {
gBrowser.webNavigation.sessionHistory.getEntryAtIndex(aIndex, false);
}
catch(ex) {
} catch(ex) {
return false;
}
return true;
@ -801,10 +824,11 @@ var gHistorySwipeAnimation = {
* |this|.
*/
_navigateToHistoryIndex: function() {
if (this._doesIndexExistInHistory(this._historyIndex))
if (this._doesIndexExistInHistory(this._historyIndex)) {
gBrowser.webNavigation.gotoIndex(this._historyIndex);
else
} else {
this.stopAnimation();
}
},
/**
@ -860,8 +884,9 @@ var gHistorySwipeAnimation = {
this._curBox = null;
this._prevBox = null;
this._nextBox = null;
if (this._container)
if (this._container) {
this._container.parentNode.removeChild(this._container);
}
this._container = null;
this._boxWidth = -1;
},
@ -958,16 +983,16 @@ var gHistorySwipeAnimation = {
* @param aCanvas
* The snapshot to add to the list and compress.
*/
_assignSnapshotToCurrentBrowser:
function(aCanvas) {
_assignSnapshotToCurrentBrowser: function(aCanvas) {
let browser = gBrowser.selectedBrowser;
let currIndex = browser.webNavigation.sessionHistory.index;
this._removeTrackedSnapshot(currIndex, browser);
this._addSnapshotRefToArray(currIndex, browser);
if (!("snapshots" in browser))
if (!("snapshots" in browser)) {
browser.snapshots = [];
}
let snapshots = browser.snapshots;
// Temporarily store the canvas as the compressed snapshot.
// This avoids a blank page if the user swipes quickly
@ -1024,10 +1049,13 @@ var gHistorySwipeAnimation = {
(aIndex < 0 || aIndex == arr[i].index)) {
delete aBrowser.snapshots[arr[i].index];
arr.splice(i, 1);
if (requiresExactIndexMatch)
return; // Found and removed the only element.
i--; // Make sure to revisit the index that we just removed an
// element at.
if (requiresExactIndexMatch) {
// Found and removed the only element.
return;
}
// Make sure to revisit the index that we just removed an
// element at.
i--;
}
}
},
@ -1041,8 +1069,7 @@ var gHistorySwipeAnimation = {
* @param aBrowser
* The browser the new snapshot was taken in.
*/
_addSnapshotRefToArray:
function(aIndex, aBrowser) {
_addSnapshotRefToArray: function(aIndex, aBrowser) {
let id = { index: aIndex,
browser: aBrowser };
let arr = this._trackedSnapshots;
@ -1067,12 +1094,14 @@ var gHistorySwipeAnimation = {
* @return A new Image object representing the converted blob.
*/
_convertToImg: function(aBlob) {
if (!aBlob)
if (!aBlob) {
return null;
}
// Return aBlob if it's still a canvas and not a compressed blob yet.
if (aBlob instanceof HTMLCanvasElement)
if (aBlob instanceof HTMLCanvasElement) {
return aBlob;
}
let img = new Image();
let url = "";
@ -1081,8 +1110,7 @@ var gHistorySwipeAnimation = {
img.onload = function() {
URL.revokeObjectURL(url);
};
}
finally {
} finally {
img.src = url;
return img;
}
@ -1122,50 +1150,42 @@ var gHistorySwipeAnimation = {
* The snapshot to set the current page to. If this parameter is null,
* the previously stored snapshot for this index (if any) will be used.
*/
_installCurrentPageSnapshot:
function(aCanvas) {
_installCurrentPageSnapshot: function(aCanvas) {
let currSnapshot = aCanvas;
let scale = window.devicePixelRatio;
if (!currSnapshot) {
let snapshots = gBrowser.selectedBrowser.snapshots || {};
let snapshots = gBrowser.selectedBrowser.snapshots || { };
let currIndex = this._historyIndex;
if (currIndex in snapshots) {
currSnapshot = this._convertToImg(snapshots[currIndex].image);
scale = snapshots[currIndex].scale;
}
}
this._scaleSnapshot(currSnapshot, scale, this._curBox ? this._curBox :
null);
document.mozSetImageElement("historySwipeAnimationCurrentPageSnapshot",
currSnapshot);
this._scaleSnapshot(currSnapshot, scale, this._curBox ? this._curBox : null);
document.mozSetImageElement("historySwipeAnimationCurrentPageSnapshot", currSnapshot);
},
/**
* Sets the snapshots of the previous and next pages to the snapshots
* previously stored for their respective indeces.
*/
_installPrevAndNextSnapshots:
function() {
_installPrevAndNextSnapshots: function() {
let snapshots = gBrowser.selectedBrowser.snapshots || [];
let currIndex = this._historyIndex;
let prevIndex = currIndex - 1;
let prevSnapshot = null;
if (prevIndex in snapshots) {
prevSnapshot = this._convertToImg(snapshots[prevIndex].image);
this._scaleSnapshot(prevSnapshot, snapshots[prevIndex].scale,
this._prevBox);
this._scaleSnapshot(prevSnapshot, snapshots[prevIndex].scale, this._prevBox);
}
document.mozSetImageElement("historySwipeAnimationPreviousPageSnapshot",
prevSnapshot);
document.mozSetImageElement("historySwipeAnimationPreviousPageSnapshot", prevSnapshot);
let nextIndex = currIndex + 1;
let nextSnapshot = null;
if (nextIndex in snapshots) {
nextSnapshot = this._convertToImg(snapshots[nextIndex].image);
this._scaleSnapshot(nextSnapshot, snapshots[nextIndex].scale,
this._nextBox);
this._scaleSnapshot(nextSnapshot, snapshots[nextIndex].scale, this._nextBox);
}
document.mozSetImageElement("historySwipeAnimationNextPageSnapshot",
nextSnapshot);
document.mozSetImageElement("historySwipeAnimationNextPageSnapshot", nextSnapshot);
},
};

View File

@ -23,7 +23,7 @@ var browserMenuDragging = {
count:[],
init: function(){
init: function() {
window.removeEventListener('load', this, false);
window.addEventListener('unload', this, false);
this.addPrefListener(this.PrefListener);
@ -34,7 +34,7 @@ var browserMenuDragging = {
this.delayedStartup();
},
uninit: function(){
uninit: function() {
window.removeEventListener('unload', this, false);
this.removePrefListener(this.PrefListener);
@ -50,7 +50,7 @@ var browserMenuDragging = {
},
initPref: function(){
initPref: function() {
this.STAY_OPEN_ONDRAGEXIT =
Services.prefs.getBoolPref('browser.menu.dragging.stayOpen', false);
this.DEBUG =
@ -58,12 +58,12 @@ var browserMenuDragging = {
},
//delayed startup
delayedStartup: function(){
delayedStartup: function() {
//wait until construction of bookmarksBarContent is completed.
for (var i = 0; i < this.menupopup.length; i++){
for (var i = 0; i < this.menupopup.length; i++) {
this.count[i] = 0;
this.timer[i] = setInterval(function(self, i){
if(++self.count[i] > 50 || document.getElementById(self.menupopup[i])){
this.timer[i] = setInterval(function(self, i) {
if(++self.count[i] > 50 || document.getElementById(self.menupopup[i])) {
clearInterval(self.timer[i]);
var menupopup = document.getElementById(self.menupopup[i]);
if (menupopup) {
@ -75,7 +75,7 @@ var browserMenuDragging = {
}
},
handleEvent: function(event){
handleEvent: function(event) {
switch (event.type) {
case 'popupshowing':
this.popupshowing(event);
@ -105,12 +105,14 @@ var browserMenuDragging = {
// leaves button depressed/sunken when hovered
menupopup.parentNode.parentNode._openedMenuButton = null;
if (!PlacesControllerDragHelper.getSession())
// Clear the dragover attribute if present, if we are dragging into a
// folder in the hierachy of current opened popup we don't clear
// this attribute on clearOverFolder. See Notify for closeTimer.
if (menupopup.parentNode.hasAttribute('dragover'))
menupopup.parentNode.removeAttribute('dragover');
if (!PlacesControllerDragHelper.getSession()) {
// Clear the dragover attribute if present, if we are dragging into a
// folder in the hierachy of current opened popup we don't clear
// this attribute on clearOverFolder. See Notify for closeTimer.
if (menupopup.parentNode.hasAttribute('dragover')) {
menupopup.parentNode.removeAttribute('dragover');
}
}
}
},
@ -120,10 +122,10 @@ var browserMenuDragging = {
var parentPopup = menupopup.parentNode.parentNode;
if (!!parentPopup.openNode){
if (!!parentPopup.openNode) {
try {
parentPopup.openNode.hidePopup();
} catch(e){}
} catch(e) {}
}
parentPopup.openNode = menupopup;
@ -138,12 +140,16 @@ var browserMenuDragging = {
var target = event.originalTarget;
while (target) {
if (/menupopup/.test(target.localName))
if (/menupopup/.test(target.localName)) {
break;
}
target = target.parentNode;
}
if (this != target)
if (this != target) {
return;
}
event.stopPropagation();
browserMenuDragging.debug("onDragOver " + "\n" + this.parentNode.getAttribute('label'));
@ -201,13 +207,13 @@ var browserMenuDragging = {
if (scrollDir == 0) {
let elt = this.firstChild;
while (elt && event.screenY > elt.boxObject.screenY +
elt.boxObject.height / 2)
elt.boxObject.height / 2) {
elt = elt.nextSibling;
newMarginTop = elt ? elt.boxObject.screenY - sbo.screenY :
sbo.height;
}
else if (scrollDir == 1)
}
newMarginTop = elt ? elt.boxObject.screenY - sbo.screenY : sbo.height;
} else if (scrollDir == 1) {
newMarginTop = sbo.height;
}
// Set the new marginTop based on arrowscrollbox.
newMarginTop += sbo.y - this._scrollBox.boxObject.y;
@ -221,12 +227,16 @@ var browserMenuDragging = {
menupopup.onDragExit = function (event) {
var target = event.originalTarget;
while (target) {
if (/menupopup/.test(target.localName))
if (/menupopup/.test(target.localName)) {
break;
}
target = target.parentNode;
}
if (this != target)
if (this != target) {
return;
}
event.stopPropagation();
browserMenuDragging.debug("onDragExit " + browserMenuDragging.STAY_OPEN_ONDRAGEXIT);
@ -236,13 +246,13 @@ var browserMenuDragging = {
// If we have not moved to a valid new target clear the drop indicator
// this happens when moving out of the popup.
target = event.relatedTarget;
if (!target)
if (!target) {
this._indicatorBar.hidden = true;
}
// Close any folder being hovered over
if (this._overFolder.elt) {
this._overFolder.closeTimer = this._overFolder
.setTimer(this._overFolder.hoverTime);
this._overFolder.closeTimer = this._overFolder.setTimer(this._overFolder.hoverTime);
}
// The auto-opened attribute is set when this folder was automatically
@ -268,12 +278,13 @@ var browserMenuDragging = {
hideTooltip: function() {
['bhTooltip', 'btTooltip2'].forEach(function(id) {
var tooltip = document.getElementById(id);
if (tooltip)
if (tooltip) {
tooltip.hidePopup();
}
});
},
get getVer(){
get getVer() {
const Cc = Components.classes;
const Ci = Components.interfaces;
var info = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo);
@ -281,17 +292,18 @@ var browserMenuDragging = {
return ver;
},
debug: function(aMsg){
if (!browserMenuDragging.DEBUG)
debug: function(aMsg) {
if (!browserMenuDragging.DEBUG) {
return;
}
Components.classes["@mozilla.org/consoleservice;1"]
.getService(Components.interfaces.nsIConsoleService)
.logStringMessage(aMsg);
.getService(Components.interfaces.nsIConsoleService)
.logStringMessage(aMsg);
},
setPref: function(aPrefString, aPrefType, aValue){
setPref: function(aPrefString, aPrefType, aValue) {
var xpPref = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
.getService(Components.interfaces.nsIPrefService);
try{
switch (aPrefType){
case 'complex':
@ -305,8 +317,7 @@ var browserMenuDragging = {
default:
return xpPref.setBoolPref(aPrefString, aValue); break;
}
}catch(e){
}
} catch(e) {}
return null;
},

View File

@ -36,8 +36,9 @@ var StarUI = {
_blockCommands: function() {
this._blockedCommands.forEach(function(elt) {
// make sure not to permanently disable this item (see bug 409155)
if (elt.hasAttribute("wasDisabled"))
if (elt.hasAttribute("wasDisabled")) {
return;
}
if (elt.getAttribute("disabled") == "true") {
elt.setAttribute("wasDisabled", "true");
} else {
@ -49,8 +50,9 @@ var StarUI = {
_restoreCommandsState: function() {
this._blockedCommands.forEach(function(elt) {
if (elt.getAttribute("wasDisabled") != "true")
if (elt.getAttribute("wasDisabled") != "true") {
elt.removeAttribute("disabled");
}
elt.removeAttribute("wasDisabled");
});
},
@ -60,8 +62,9 @@ var StarUI = {
switch (aEvent.type) {
case "popuphidden":
if (aEvent.originalTarget == this.panel) {
if (!this._element("editBookmarkPanelContent").hidden)
if (!this._element("editBookmarkPanelContent").hidden) {
this.quitEditMode();
}
this._restoreCommandsState();
this._itemId = -1;
@ -98,8 +101,9 @@ var StarUI = {
}
switch (aEvent.keyCode) {
case KeyEvent.DOM_VK_ESCAPE:
if (!this._element("editBookmarkPanelContent").hidden)
if (!this._element("editBookmarkPanelContent").hidden) {
this.cancelButtonOnCommand();
}
break;
case KeyEvent.DOM_VK_RETURN:
if (aEvent.target.className == "expander-up" ||
@ -122,8 +126,9 @@ var StarUI = {
function(aItemId, aAnchorElement, aPosition) {
// Performance: load the overlay the first time the panel is opened
// (see bug 392443).
if (this._overlayLoading)
if (this._overlayLoading) {
return;
}
if (this._overlayLoaded) {
this._doShowEditBookmarkPanel(aItemId, aAnchorElement, aPosition);
@ -153,8 +158,9 @@ var StarUI = {
_doShowEditBookmarkPanel:
function(aItemId, aAnchorElement, aPosition) {
if (this.panel.state != "closed")
if (this.panel.state != "closed") {
return;
}
this._blockCommands(); // un-done in the popuphiding handler
@ -164,8 +170,8 @@ var StarUI = {
// we are about editing it, then use Edit This Bookmark.
this._element("editBookmarkPanelTitle").value =
this._batching ?
gNavigatorBundle.getString("editBookmarkPanel.pageBookmarkedTitle") :
gNavigatorBundle.getString("editBookmarkPanel.editBookmarkTitle");
gNavigatorBundle.getString("editBookmarkPanel.pageBookmarkedTitle") :
gNavigatorBundle.getString("editBookmarkPanel.editBookmarkTitle");
// No description; show the Done, Cancel;
this._element("editBookmarkPanelDescription").textContent = "";
@ -218,8 +224,7 @@ var StarUI = {
var elt = this._element(fieldToFocus);
elt.focus();
elt.select();
}
else {
} else {
// Note this isn't actually used anymore, we should remove this
// once we decide not to bring back the page bookmarked notification
this.panel.focus();
@ -290,8 +295,7 @@ var PlacesCommandHook = {
title = title || url.spec;
description = PlacesUIUtils.getDescriptionFromDocument(webNav.document);
charset = webNav.document.characterSet;
}
catch (e) { }
} catch(e) {}
if (aShowEditUI) {
// If we bookmark the page here (i.e. page was not "starred" already)
@ -301,7 +305,8 @@ var PlacesCommandHook = {
}
var parent = aParent != undefined ?
aParent : PlacesUtils.unfiledBookmarksFolderId;
aParent :
PlacesUtils.unfiledBookmarksFolderId;
var descAnno = { name: PlacesUIUtils.DESCRIPTION_ANNO, value: description };
var txn = new PlacesCreateBookmarkTransaction(uri, parent,
PlacesUtils.bookmarks.DEFAULT_INDEX,
@ -309,17 +314,20 @@ var PlacesCommandHook = {
PlacesUtils.transactionManager.doTransaction(txn);
itemId = txn.item.id;
// Set the character-set
if (charset && !PrivateBrowsingUtils.isWindowPrivate(aBrowser.contentWindow))
if (charset && !PrivateBrowsingUtils.isWindowPrivate(aBrowser.contentWindow)) {
PlacesUtils.setCharsetForURI(uri, charset);
}
}
// Revert the contents of the location bar
if (gURLBar)
if (gURLBar) {
gURLBar.handleRevert();
}
// If it was not requested to open directly in "edit" mode, we are done.
if (!aShowEditUI)
if (!aShowEditUI) {
return;
}
// Try to dock the panel to:
// 1. the bookmarks menu button
@ -361,20 +369,19 @@ var PlacesCommandHook = {
var linkURI = makeURI(aURL);
var itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
if (itemId == -1) {
PlacesUIUtils.showBookmarkDialog({ action: "add"
, type: "bookmark"
, uri: linkURI
, title: aTitle
, hiddenRows: [ "description"
, "location"
, "loadInSidebar"
, "keyword" ]
PlacesUIUtils.showBookmarkDialog({ action: "add",
type: "bookmark",
uri: linkURI,
title: aTitle,
hiddenRows: [ "description",
"location",
"loadInSidebar",
"keyword" ]
}, window);
}
else {
PlacesUIUtils.showBookmarkDialog({ action: "edit"
, type: "bookmark"
, itemId: itemId
} else {
PlacesUIUtils.showBookmarkDialog({ action: "edit",
type: "bookmark",
itemId: itemId
}, window);
}
},
@ -408,10 +415,10 @@ var PlacesCommandHook = {
bookmarkCurrentPages: function() {
let pages = this.uniqueCurrentPages;
if (pages.length > 1) {
PlacesUIUtils.showBookmarkDialog({ action: "add"
, type: "folder"
, URIList: pages
, hiddenRows: [ "description" ]
PlacesUIUtils.showBookmarkDialog({ action: "add",
type: "folder",
URIList: pages,
hiddenRows: [ "description" ]
}, window);
}
},
@ -419,11 +426,11 @@ var PlacesCommandHook = {
/**
* Updates disabled state for the "Bookmark All Tabs" command.
*/
updateBookmarkAllTabsCommand:
function() {
updateBookmarkAllTabsCommand: function() {
// There's nothing to do in non-browser windows.
if (window.location.href != getBrowserURL())
if (window.location.href != getBrowserURL()) {
return;
}
// Disable "Bookmark All Tabs" if there are less than two
// "unique current pages".
@ -450,16 +457,16 @@ var PlacesCommandHook = {
description = PlacesUIUtils.getDescriptionFromDocument(gBrowser.contentDocument);
}
PlacesUIUtils.showBookmarkDialog({ action: "add"
, type: "livemark"
, feedURI: feedURI
, siteURI: gBrowser.currentURI
, title: title
, description: description
, defaultInsertionPoint: toolbarIP
, hiddenRows: [ "feedLocation"
, "siteLocation"
, "description" ]
PlacesUIUtils.showBookmarkDialog({ action: "add",
type: "livemark",
feedURI: feedURI,
siteURI: gBrowser.currentURI,
title: title,
description: description,
defaultInsertionPoint: toolbarIP,
hiddenRows: [ "feedLocation",
"siteLocation",
"description" ]
}, window);
},
@ -477,8 +484,7 @@ var PlacesCommandHook = {
// No currently open places window, so open one with the specified mode.
openDialog("chrome://browser/content/places/places.xul",
"", "chrome,toolbar=yes,dialog=no,resizable", aLeftPaneRoot);
}
else {
} else {
organizer.PlacesOrganizer.selectLeftPaneQuery(aLeftPaneRoot);
organizer.focus();
}
@ -507,10 +513,11 @@ HistoryMenu.prototype = {
let restoreItem = this._rootElt.ownerDocument.getElementById("Browser:RestoreLastSession");
if (this._ss.canRestoreLastSession &&
!PrivateBrowsingUtils.isWindowPrivate(window))
!PrivateBrowsingUtils.isWindowPrivate(window)) {
restoreItem.removeAttribute("disabled");
else
} else {
restoreItem.setAttribute("disabled", true);
}
},
toggleRecentlyClosedTabs: function() {
@ -518,10 +525,11 @@ HistoryMenu.prototype = {
var undoMenu = this._rootElt.getElementsByClassName("recentlyClosedTabsMenu")[0];
// no restorable tabs, so disable menu
if (this._ss.getClosedTabCount(window) == 0)
if (this._ss.getClosedTabCount(window) == 0) {
undoMenu.setAttribute("disabled", true);
else
} else {
undoMenu.removeAttribute("disabled");
}
},
/**
@ -531,8 +539,9 @@ HistoryMenu.prototype = {
* The event when the user clicks the menu item
*/
_undoCloseMiddleClick: function(aEvent) {
if (aEvent.button != 1)
if (aEvent.button != 1) {
return;
}
undoCloseTab(aEvent.originalTarget.value);
gBrowser.moveTabToEnd();
@ -546,8 +555,9 @@ HistoryMenu.prototype = {
var undoPopup = undoMenu.firstChild;
// remove existing menu items
while (undoPopup.hasChildNodes())
while (undoPopup.hasChildNodes()) {
undoPopup.removeChild(undoPopup.firstChild);
}
// no restorable tabs, so make sure menu is disabled, and return
if (this._ss.getClosedTabCount(window) == 0) {
@ -566,8 +576,9 @@ HistoryMenu.prototype = {
if (undoItems[i].image) {
let iconURL = undoItems[i].image;
// don't initiate a connection just to fetch a favicon (see bug 467828)
if (/^https?:/.test(iconURL))
if (/^https?:/.test(iconURL)) {
iconURL = "moz-anno:favicon:" + iconURL;
}
m.setAttribute("image", iconURL);
}
m.setAttribute("class", "menuitem-iconic bookmark-item menuitem-with-favicon");
@ -579,12 +590,14 @@ HistoryMenu.prototype = {
// normalize them.
let tabData = undoItems[i].state;
let activeIndex = (tabData.index || tabData.entries.length) - 1;
if (activeIndex >= 0 && tabData.entries[activeIndex])
if (activeIndex >= 0 && tabData.entries[activeIndex]) {
m.setAttribute("targetURI", tabData.entries[activeIndex].url);
}
m.addEventListener("click", this._undoCloseMiddleClick, false);
if (i == 0)
if (i == 0) {
m.setAttribute("key", "key_undoCloseTab");
}
undoPopup.appendChild(m);
}
@ -595,8 +608,9 @@ HistoryMenu.prototype = {
m.id = "menu_restoreAllTabs";
m.setAttribute("label", strings.getString("menuRestoreAllTabs.label"));
m.addEventListener("command", function() {
for (var i = 0; i < undoItems.length; i++)
for (var i = 0; i < undoItems.length; i++) {
undoCloseTab();
}
}, false);
},
@ -605,10 +619,11 @@ HistoryMenu.prototype = {
var undoMenu = this._rootElt.getElementsByClassName("recentlyClosedWindowsMenu")[0];
// no restorable windows, so disable menu
if (this._ss.getClosedWindowCount() == 0)
if (this._ss.getClosedWindowCount() == 0) {
undoMenu.setAttribute("disabled", true);
else
} else {
undoMenu.removeAttribute("disabled");
}
},
/**
@ -618,12 +633,12 @@ HistoryMenu.prototype = {
let undoMenu = this._rootElt.getElementsByClassName("recentlyClosedWindowsMenu")[0];
let undoPopup = undoMenu.firstChild;
let menuLabelString = gNavigatorBundle.getString("menuUndoCloseWindowLabel");
let menuLabelStringSingleTab =
gNavigatorBundle.getString("menuUndoCloseWindowSingleTabLabel");
let menuLabelStringSingleTab = gNavigatorBundle.getString("menuUndoCloseWindowSingleTabLabel");
// remove existing menu items
while (undoPopup.hasChildNodes())
while (undoPopup.hasChildNodes()) {
undoPopup.removeChild(undoPopup.firstChild);
}
// no restorable windows, so make sure menu is disabled, and return
if (this._ss.getClosedWindowCount() == 0) {
@ -649,8 +664,9 @@ HistoryMenu.prototype = {
if (selectedTab.image) {
let iconURL = selectedTab.image;
// don't initiate a connection just to fetch a favicon (see bug 467828)
if (/^https?:/.test(iconURL))
if (/^https?:/.test(iconURL)) {
iconURL = "moz-anno:favicon:" + iconURL;
}
m.setAttribute("image", iconURL);
}
m.setAttribute("class", "menuitem-iconic bookmark-item menuitem-with-favicon");
@ -659,11 +675,13 @@ HistoryMenu.prototype = {
// Set the targetURI attribute so it will be shown in tooltip.
// SessionStore uses one-based indexes, so we need to normalize them.
let activeIndex = (selectedTab.index || selectedTab.entries.length) - 1;
if (activeIndex >= 0 && selectedTab.entries[activeIndex])
if (activeIndex >= 0 && selectedTab.entries[activeIndex]) {
m.setAttribute("targetURI", selectedTab.entries[activeIndex].url);
}
if (i == 0)
if (i == 0) {
m.setAttribute("key", "key_undoCloseWindow");
}
undoPopup.appendChild(m);
}
@ -682,8 +700,9 @@ HistoryMenu.prototype = {
// Enable/disable the Tabs From Other Computers menu. Some of the menus handled
// by HistoryMenu do not have this menuitem.
let menuitem = this._rootElt.getElementsByClassName("syncTabsMenuItem")[0];
if (!menuitem)
if (!menuitem) {
return;
}
// If Sync isn't configured yet, then don't show the menuitem.
if (Weave.Status.checkSetup() == Weave.CLIENT_NOT_CONFIGURED ||
@ -706,8 +725,9 @@ HistoryMenu.prototype = {
PlacesMenu.prototype._onPopupShowing.apply(this, arguments);
// Don't handle events for submenus.
if (aEvent.target != aEvent.currentTarget)
if (aEvent.target != aEvent.currentTarget) {
return;
}
this.toggleRestoreLastSession();
this.toggleRecentlyClosedTabs();
@ -718,8 +738,9 @@ HistoryMenu.prototype = {
_onCommand: function(aEvent) {
let placesNode = aEvent.target._placesNode;
if (placesNode) {
if (!PrivateBrowsingUtils.isWindowPrivate(window))
if (!PrivateBrowsingUtils.isWindowPrivate(window)) {
PlacesUIUtils.markPageAsTyped(placesNode.uri);
}
openUILink(placesNode.uri, aEvent, { ignoreAlt: true });
}
}
@ -750,21 +771,23 @@ var BookmarksEventHandler = {
#else
var modifKey = aEvent.ctrlKey || aEvent.shiftKey;
#endif
if (aEvent.button == 2 || (aEvent.button == 0 && !modifKey))
if (aEvent.button == 2 || (aEvent.button == 0 && !modifKey)) {
return;
}
var target = aEvent.originalTarget;
// If this event bubbled up from a menu or menuitem, close the menus.
// Do this before opening tabs, to avoid hiding the open tabs confirm-dialog.
if (target.localName == "menu" || target.localName == "menuitem") {
for (node = target.parentNode; node; node = node.parentNode) {
if (node.localName == "menupopup")
if (node.localName == "menupopup") {
node.hidePopup();
else if (node.localName != "menu" &&
node.localName != "splitmenu" &&
node.localName != "hbox" &&
node.localName != "vbox" )
} else if (node.localName != "menu" &&
node.localName != "splitmenu" &&
node.localName != "hbox" &&
node.localName != "vbox" ) {
break;
}
}
}
@ -772,10 +795,10 @@ var BookmarksEventHandler = {
// Don't open the root folder in tabs when the empty area on the toolbar
// is middle-clicked or when a non-bookmark item except for Open in Tabs)
// in a bookmarks menupopup is middle-clicked.
if (target.localName == "menu" || target.localName == "toolbarbutton")
if (target.localName == "menu" || target.localName == "toolbarbutton") {
PlacesUIUtils.openContainerNodeInTabs(target._placesNode, aEvent, aView);
}
else if (aEvent.button == 1) {
}
} else if (aEvent.button == 1) {
// left-clicks with modifier are already served by onCommand
this.onCommand(aEvent, aView);
}
@ -792,8 +815,9 @@ var BookmarksEventHandler = {
*/
onCommand: function(aEvent, aView) {
var target = aEvent.originalTarget;
if (target._placesNode)
if (target._placesNode) {
PlacesUIUtils.openNodeWithEvent(target._placesNode, aEvent, aView);
}
},
fillInBHTooltip: function(aDocument, aEvent) {
@ -805,47 +829,52 @@ var BookmarksEventHandler = {
var tree = aDocument.tooltipNode.parentNode;
var tbo = tree.treeBoxObject;
var cell = tbo.getCellAt(aEvent.clientX, aEvent.clientY);
if (cell.row == -1)
if (cell.row == -1) {
return false;
}
node = tree.view.nodeForTreeIndex(cell.row);
cropped = tbo.isCellCropped(cell.row, cell.col);
}
else {
} else {
// Check whether the tooltipNode is a Places node.
// In such a case use it, otherwise check for targetURI attribute.
var tooltipNode = aDocument.tooltipNode;
if (tooltipNode._placesNode)
if (tooltipNode._placesNode) {
node = tooltipNode._placesNode;
else {
} else {
// This is a static non-Places node.
targetURI = tooltipNode.getAttribute("targetURI");
}
}
if (!node && !targetURI)
if (!node && !targetURI) {
return false;
}
// Show node.label as tooltip's title for non-Places nodes.
var title = node ? node.title : tooltipNode.label;
// Show URL only for Places URI-nodes or nodes with a targetURI attribute.
var url;
if (targetURI || PlacesUtils.nodeIsURI(node))
if (targetURI || PlacesUtils.nodeIsURI(node)) {
url = targetURI || node.uri;
}
// Show tooltip for containers only if their title is cropped.
if (!cropped && !url)
if (!cropped && !url) {
return false;
}
var tooltipTitle = aDocument.getElementById("bhtTitleText");
tooltipTitle.hidden = (!title || (title == url));
if (!tooltipTitle.hidden)
if (!tooltipTitle.hidden) {
tooltipTitle.textContent = title;
}
var tooltipUrl = aDocument.getElementById("bhtUrlText");
tooltipUrl.hidden = !url;
if (!tooltipUrl.hidden)
if (!tooltipUrl.hidden) {
tooltipUrl.value = url;
}
// Show tooltip.
return true;
@ -869,12 +898,14 @@ var PlacesMenuDNDHandler = {
*/
onDragEnter: function(event) {
// Opening menus in a Places popup is handled by the view itself.
if (!this._isStaticContainer(event.target))
if (!this._isStaticContainer(event.target)) {
return;
}
let popup = event.target.lastChild;
if (this._loadTimer || popup.state === "showing" || popup.state === "open")
if (this._loadTimer || popup.state === "showing" || popup.state === "open") {
return;
}
this._loadTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this._loadTimer.initWithCallback(() => {
@ -894,12 +925,14 @@ var PlacesMenuDNDHandler = {
onDragLeave: function(event) {
// Handle menu-button separate targets.
if (event.relatedTarget === event.currentTarget ||
event.relatedTarget.parentNode === event.currentTarget)
event.relatedTarget.parentNode === event.currentTarget) {
return;
}
// Closing menus in a Places popup is handled by the view itself.
if (!this._isStaticContainer(event.target))
if (!this._isStaticContainer(event.target)) {
return;
}
let popup = event.target.lastChild;
@ -933,7 +966,8 @@ var PlacesMenuDNDHandler = {
(node.localName == "toolbarbutton" &&
(node.getAttribute("type") == "menu" ||
node.getAttribute("type") == "menu-button"));
let isStatic = !("_placesNode" in node) && node.lastChild &&
let isStatic = !("_placesNode" in node) &&
node.lastChild &&
node.lastChild.hasAttribute("placespopup") &&
!node.parentNode.hasAttribute("placespopup");
return isMenu && isStatic;
@ -948,8 +982,9 @@ var PlacesMenuDNDHandler = {
let ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId,
PlacesUtils.bookmarks.DEFAULT_INDEX,
Ci.nsITreeView.DROP_ON);
if (ip && PlacesControllerDragHelper.canDrop(ip, event.dataTransfer))
if (ip && PlacesControllerDragHelper.canDrop(ip, event.dataTransfer)) {
event.preventDefault();
}
event.stopPropagation();
},
@ -985,8 +1020,9 @@ var PlacesToolbarHelper = {
init: function() {
let viewElt = this._viewElt;
if (!viewElt || viewElt._placesView)
if (!viewElt || viewElt._placesView) {
return;
}
// If the bookmarks toolbar item is hidden because the parent toolbar is
// collapsed or hidden (i.e. in a popup), spare the initialization. Also,
@ -995,16 +1031,18 @@ var PlacesToolbarHelper = {
let toolbar = viewElt.parentNode.parentNode;
if (toolbar.collapsed ||
getComputedStyle(toolbar, "").display == "none" ||
this._isCustomizing)
this._isCustomizing) {
return;
}
new PlacesToolbar(this._place);
},
customizeStart: function() {
let viewElt = this._viewElt;
if (viewElt && viewElt._placesView)
if (viewElt && viewElt._placesView) {
viewElt._placesView.uninit();
}
this._isCustomizing = true;
},
@ -1050,25 +1088,23 @@ var BookmarkingUI = {
STATUS_UNSTARRED: 0,
STATUS_STARRED: 1,
get status() {
if (this._pendingStmt)
if (this._pendingStmt) {
return this.STATUS_UPDATING;
}
return this.star &&
this.star.hasAttribute("starred") ? this.STATUS_STARRED
: this.STATUS_UNSTARRED;
this.star.hasAttribute("starred") ? this.STATUS_STARRED : this.STATUS_UNSTARRED;
},
get _starredTooltip()
{
delete this._starredTooltip;
return this._starredTooltip =
gNavigatorBundle.getString("starButtonOn.tooltip");
return this._starredTooltip = gNavigatorBundle.getString("starButtonOn.tooltip");
},
get _unstarredTooltip()
{
delete this._unstarredTooltip;
return this._unstarredTooltip =
gNavigatorBundle.getString("starButtonOff.tooltip");
return this._unstarredTooltip = gNavigatorBundle.getString("starButtonOff.tooltip");
},
/**
@ -1084,11 +1120,14 @@ var BookmarkingUI = {
onPopupShowing: function(event) {
// Don't handle events for submenus.
if (event.target != event.currentTarget)
if (event.target != event.currentTarget) {
return;
}
if (!this._popupNeedsUpdate)
if (!this._popupNeedsUpdate) {
return;
}
this._popupNeedsUpdate = false;
let popup = event.target;
@ -1124,8 +1163,7 @@ var BookmarkingUI = {
if (aState == "invalid") {
this.star.setAttribute("disabled", "true");
this.star.removeAttribute("starred");
}
else {
} else {
this.star.removeAttribute("disabled");
}
},
@ -1142,8 +1180,7 @@ var BookmarkingUI = {
if (onPersonalToolbar) {
this.button.classList.add("bookmark-item");
this.button.classList.remove("toolbarbutton-1");
}
else {
} else {
this.button.classList.remove("bookmark-item");
this.button.classList.add("toolbarbutton-1");
}
@ -1252,8 +1289,7 @@ var BookmarkingUI = {
if (this._itemIds.length > 0) {
this.star.setAttribute("starred", "true");
this.star.setAttribute("tooltiptext", this._starredTooltip);
}
else {
} else {
this.star.removeAttribute("starred");
this.star.setAttribute("tooltiptext", this._unstarredTooltip);
}
@ -1299,9 +1335,8 @@ var BookmarkingUI = {
if (index != -1 && aNewValue != this._uri.spec) {
this._itemIds.splice(index, 1);
this._updateStar();
}
// If another bookmark is now pointing to the tracked uri, register it.
else if (index == -1 && aNewValue == this._uri.spec) {
} else if (index == -1 && aNewValue == this._uri.spec) {
// If another bookmark is now pointing to the tracked uri, register it.
this._itemIds.push(aItemId);
this._updateStar();
}

View File

@ -64,8 +64,9 @@ var gPluginHandler = {
// Map the plugin's name to a filtered version more suitable for user UI.
makeNicePluginName : function(aName) {
if (aName == "Shockwave Flash")
if (aName == "Shockwave Flash") {
return "Adobe Flash";
}
// Clean up the plugin name by stripping off any trailing version numbers
// or "plugin". EG, "Foo Bar Plugin 1.23_02" --> "Foo Bar"
@ -94,34 +95,37 @@ var gPluginHandler = {
let callbackArgs = Array.prototype.slice.call(arguments).slice(2);
linkNode.addEventListener("click",
function(evt) {
if (!evt.isTrusted)
if (!evt.isTrusted) {
return;
}
evt.preventDefault();
if (callbackArgs.length == 0)
if (callbackArgs.length == 0) {
callbackArgs = [ evt ];
}
(self[callbackName]).apply(self, callbackArgs);
},
true);
}, true);
linkNode.addEventListener("keydown",
function(evt) {
if (!evt.isTrusted)
if (!evt.isTrusted) {
return;
}
if (evt.keyCode == evt.DOM_VK_RETURN) {
evt.preventDefault();
if (callbackArgs.length == 0)
if (callbackArgs.length == 0) {
callbackArgs = [ evt ];
}
evt.preventDefault();
(self[callbackName]).apply(self, callbackArgs);
}
},
true);
}, true);
},
// Helper to get the binding handler type from a plugin object
_getBindingType : function(plugin) {
if (!(plugin instanceof Ci.nsIObjectLoadingContent))
if (!(plugin instanceof Ci.nsIObjectLoadingContent)) {
return null;
}
switch (plugin.pluginFallbackType) {
case Ci.nsIObjectLoadingContent.PLUGIN_UNSUPPORTED:
@ -153,13 +157,13 @@ var gPluginHandler = {
let eventType = event.type;
if (eventType === "PluginRemoved") {
doc = event.target;
}
else {
} else {
plugin = event.target;
doc = plugin.ownerDocument;
if (!(plugin instanceof Ci.nsIObjectLoadingContent))
if (!(plugin instanceof Ci.nsIObjectLoadingContent)) {
return;
}
}
if (eventType == "PluginBindingAttached") {
@ -182,8 +186,9 @@ var gPluginHandler = {
let shouldShowNotification = false;
let browser = gBrowser.getBrowserForDocument(doc.defaultView.top.document);
if (!browser)
if (!browser) {
return;
}
switch (eventType) {
case "PluginCrashed":
@ -278,8 +283,9 @@ var gPluginHandler = {
// if this isn't a known plugin, we can't activate it
// (this also guards pluginHost.getPermissionStringForType against
// unexpected input)
if (!gPluginHandler.isKnownPlugin(objLoadingContent))
if (!gPluginHandler.isKnownPlugin(objLoadingContent)) {
return false;
}
let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
let permissionString = pluginHost.getPermissionStringForType(objLoadingContent.actualType);
@ -303,19 +309,22 @@ var gPluginHandler = {
hideClickToPlayOverlay: function(aPlugin) {
let overlay = this.getPluginUI(aPlugin, "main");
if (overlay)
if (overlay) {
overlay.style.visibility = "hidden";
}
},
stopPlayPreview: function(aPlugin, aPlayPlugin) {
let objLoadingContent = aPlugin.QueryInterface(Ci.nsIObjectLoadingContent);
if (objLoadingContent.activated)
if (objLoadingContent.activated) {
return;
}
if (aPlayPlugin)
if (aPlayPlugin) {
objLoadingContent.playPlugin();
else
} else {
objLoadingContent.cancelPlayPreview();
}
},
// Callback for user clicking on a disabled plugin
@ -341,8 +350,9 @@ var gPluginHandler = {
let objLoadingContent = aPlugin.QueryInterface(Ci.nsIObjectLoadingContent);
// guard against giving pluginHost.getPermissionStringForType a type
// not associated with any known plugin
if (!gPluginHandler.isKnownPlugin(objLoadingContent))
if (!gPluginHandler.isKnownPlugin(objLoadingContent)) {
return;
}
let permissionString = pluginHost.getPermissionStringForType(objLoadingContent.actualType);
let principal = doc.defaultView.top.document.nodePrincipal;
let pluginPermission = Services.perms.testPermissionFromPrincipal(principal, permissionString);
@ -350,8 +360,9 @@ var gPluginHandler = {
let overlay = this.getPluginUI(aPlugin, "main");
if (pluginPermission == Ci.nsIPermissionManager.DENY_ACTION) {
if (overlay)
if (overlay) {
overlay.style.visibility = "hidden";
}
return;
}
@ -359,8 +370,9 @@ var gPluginHandler = {
overlay.addEventListener("click", gPluginHandler._overlayClickListener, true);
let closeIcon = gPluginHandler.getPluginUI(aPlugin, "closeIcon");
closeIcon.addEventListener("click", function(aEvent) {
if (aEvent.button == 0 && aEvent.isTrusted)
if (aEvent.button == 0 && aEvent.isTrusted) {
gPluginHandler.hideClickToPlayOverlay(aPlugin);
}
}, true);
}
},
@ -373,8 +385,8 @@ var gPluginHandler = {
// drag-and-dropped a tab from a window containing only that tab. In
// that case, the window gets destroyed.
let browser = gBrowser.getBrowserForDocument ?
gBrowser.getBrowserForDocument(contentWindow.document) :
null;
gBrowser.getBrowserForDocument(contentWindow.document) :
null;
// If browser is null here, we've been drag-and-dropped from another
// window, and this is the wrong click handler.
if (!browser) {
@ -416,8 +428,9 @@ var gPluginHandler = {
// MozPlayPlugin event can be dispatched from the extension chrome
// code to replace the preview content with the native plugin
previewContent.addEventListener("MozPlayPlugin", function playPluginHandler(aEvent) {
if (!aEvent.isTrusted)
if (!aEvent.isTrusted) {
return;
}
previewContent.removeEventListener("MozPlayPlugin", playPluginHandler, true);
@ -426,8 +439,9 @@ var gPluginHandler = {
// cleaning up: removes overlay iframe from the DOM
let iframe = previewContent.getElementsByClassName("previewPluginContentFrame")[0];
if (iframe)
if (iframe) {
previewContent.removeChild(iframe);
}
}, true);
if (!playPreviewInfo.ignoreCTP) {
@ -444,11 +458,13 @@ var gPluginHandler = {
let plugins = cwu.plugins;
for (let plugin of plugins) {
let overlay = doc.getAnonymousElementByAttribute(plugin, "anonid", "main");
if (overlay)
if (overlay) {
overlay.removeEventListener("click", gPluginHandler._overlayClickListener, true);
}
let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
if (gPluginHandler.canActivatePlugin(objLoadingContent))
if (gPluginHandler.canActivatePlugin(objLoadingContent)) {
gPluginHandler._handleClickToPlayEvent(plugin);
}
}
gPluginHandler._showClickToPlayNotification(browser);
},
@ -456,8 +472,7 @@ var gPluginHandler = {
_clickToPlayNotificationEventCallback: function(event) {
if (event == "showing") {
gPluginHandler._makeCenterActions(this);
}
else if (event == "dismissed") {
} else if (event == "dismissed") {
// Once the popup is dismissed, clicking the icon should show the full
// list again
this.options.primaryPlugin = null;
@ -497,8 +512,7 @@ var gPluginHandler = {
if (permissionObj) {
pluginInfo.pluginPermissionPrePath = permissionObj.principal.originNoSuffix;
pluginInfo.pluginPermissionType = permissionObj.expireType;
}
else {
} else {
pluginInfo.pluginPermissionPrePath = principal.originNoSuffix;
pluginInfo.pluginPermissionType = undefined;
}
@ -625,8 +639,9 @@ var gPluginHandler = {
}
let dismissed = notification ? notification.dismissed : true;
if (aPrimaryPlugin)
if (aPrimaryPlugin) {
dismissed = false;
}
let primaryPluginPermission = null;
if (aPrimaryPlugin) {
@ -639,8 +654,7 @@ var gPluginHandler = {
primaryPlugin: primaryPluginPermission
};
PopupNotifications.show(aBrowser, "click-to-play-plugins",
"", icon,
null, null, options);
"", icon, null, null, options);
},
// Crashed-plugin observer. Notified once per plugin crash, before events
@ -648,16 +662,18 @@ var gPluginHandler = {
pluginCrashed : function(subject, topic, data) {
let propertyBag = subject;
if (!(propertyBag instanceof Ci.nsIPropertyBag2) ||
!(propertyBag instanceof Ci.nsIWritablePropertyBag2))
return;
!(propertyBag instanceof Ci.nsIWritablePropertyBag2)) {
return;
}
},
// Crashed-plugin event listener. Called for every instance of a
// plugin in content.
pluginInstanceCrashed: function(plugin, aEvent) {
// Ensure the plugin and event are of the right type.
if (!(aEvent instanceof Ci.nsIDOMDataContainerEvent))
if (!(aEvent instanceof Ci.nsIDOMDataContainerEvent)) {
return;
}
let submittedReport = aEvent.getData("submittedCrashReport");
let doPrompt = true; // XXX followup for .getData("doPrompt");
@ -721,15 +737,17 @@ var gPluginHandler = {
function hideNotificationBar() {
let notification = notificationBox.getNotificationWithValue("plugin-crashed");
if (notification)
if (notification) {
notificationBox.removeNotification(notification, true);
}
}
function showNotificationBar(pluginDumpID, browserDumpID) {
// If there's already an existing notification bar, don't do anything.
let notification = notificationBox.getNotificationWithValue("plugin-crashed");
if (notification)
if (notification) {
return;
}
// Configure the notification bar
let priority = notificationBox.PRIORITY_WARNING_MEDIUM;
@ -747,7 +765,7 @@ var gPluginHandler = {
}];
notification = notificationBox.appendNotification(messageString, "plugin-crashed",
iconURL, priority, buttons);
iconURL, priority, buttons);
// Add the "learn more" link.
let XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

View File

@ -117,12 +117,14 @@ var gSyncUI = {
// Functions called by observers
onActivityStart: function() {
if (!gBrowser)
if (!gBrowser) {
return;
}
let button = document.getElementById("sync-button");
if (!button)
if (!button) {
return;
}
button.setAttribute("status", "active");
button.setAttribute("label", this._stringBundle.GetStringFromName("syncing2.label"));
@ -182,7 +184,10 @@ var gSyncUI = {
buttons.push(new Weave.NotificationButton(
this._stringBundle.GetStringFromName("error.login.prefs.label"),
this._stringBundle.GetStringFromName("error.login.prefs.accesskey"),
function() { gSyncUI.openPrefs(); return true; }
function() {
gSyncUI.openPrefs();
return true;
}
));
let notification = new Weave.Notification(title, description, null,
@ -206,7 +211,10 @@ var gSyncUI = {
buttons.push(new Weave.NotificationButton(
this._stringBundle.GetStringFromName("error.sync.viewQuotaButton.label"),
this._stringBundle.GetStringFromName("error.sync.viewQuotaButton.accesskey"),
function() { gSyncUI.openQuotaDialog(); return true; }
function() {
gSyncUI.openQuotaDialog();
return true;
}
));
let notification = new Weave.Notification(
@ -225,10 +233,11 @@ var gSyncUI = {
},
handleToolbarButton: function() {
if (this._needsSetup())
if (this._needsSetup()) {
this.openSetup();
else
} else {
this.doSync();
}
},
//XXXzpao should be part of syncCommon.js - which we might want to make a module...
@ -246,9 +255,9 @@ var gSyncUI = {
openSetup: function(wizardType) {
let win = Services.wm.getMostRecentWindow("Weave:AccountSetup");
if (win)
if (win) {
win.focus();
else {
} else {
window.openDialog("chrome://browser/content/sync/setup.xul",
"weaveSetup", "centerscreen,chrome,resizable=no",
wizardType);
@ -256,25 +265,28 @@ var gSyncUI = {
},
openAddDevice: function() {
if (!Weave.Utils.ensureMPUnlocked())
if (!Weave.Utils.ensureMPUnlocked()) {
return;
}
let win = Services.wm.getMostRecentWindow("Sync:AddDevice");
if (win)
if (win) {
win.focus();
else
} else {
window.openDialog("chrome://browser/content/sync/addDevice.xul",
"syncAddDevice", "centerscreen,chrome,resizable=no");
}
},
openQuotaDialog: function() {
let win = Services.wm.getMostRecentWindow("Sync:ViewQuota");
if (win)
if (win) {
win.focus();
else
} else {
Services.ww.activeWindow.openDialog(
"chrome://browser/content/sync/quota.xul", "",
"centerscreen,chrome,dialog,modal");
}
},
openPrefs: function() {
@ -284,12 +296,14 @@ var gSyncUI = {
// Helpers
_updateLastSyncTime: function() {
if (!gBrowser)
if (!gBrowser) {
return;
}
let syncButton = document.getElementById("sync-button");
if (!syncButton)
if (!syncButton) {
return;
}
let lastSync = Services.prefs.getCharPref("services.sync.lastSync", "");
if (!lastSync || this._needsSetup()) {
@ -348,8 +362,9 @@ var gSyncUI = {
// Check if the client is outdated in some way
let outdated = Weave.Status.sync == Weave.VERSION_OUT_OF_DATE;
for (let [engine, reason] in Iterator(Weave.Status.engines))
for (let [engine, reason] in Iterator(Weave.Status.engines)) {
outdated = outdated || reason == Weave.VERSION_OUT_OF_DATE;
}
if (outdated) {
description = this._stringBundle.GetStringFromName(
@ -362,8 +377,7 @@ var gSyncUI = {
return true;
}
));
}
else if (Weave.Status.sync == Weave.OVER_QUOTA) {
} else if (Weave.Status.sync == Weave.OVER_QUOTA) {
description = this._stringBundle.GetStringFromName(
"error.sync.quota.description");
buttons.push(new Weave.NotificationButton(
@ -371,23 +385,30 @@ var gSyncUI = {
"error.sync.viewQuotaButton.label"),
this._stringBundle.GetStringFromName(
"error.sync.viewQuotaButton.accesskey"),
function() { gSyncUI.openQuotaDialog(); return true; } )
);
}
else if (Weave.Status.enforceBackoff) {
function() {
gSyncUI.openQuotaDialog();
return true;
}
));
} else if (Weave.Status.enforceBackoff) {
priority = Weave.Notifications.PRIORITY_INFO;
buttons.push(new Weave.NotificationButton(
this._stringBundle.GetStringFromName("error.sync.serverStatusButton.label"),
this._stringBundle.GetStringFromName("error.sync.serverStatusButton.accesskey"),
function() { gSyncUI.openServerStatus(); return true; }
function() {
gSyncUI.openServerStatus();
return true;
}
));
}
else {
} else {
priority = Weave.Notifications.PRIORITY_INFO;
buttons.push(new Weave.NotificationButton(
this._stringBundle.GetStringFromName("error.sync.tryAgainButton.label"),
this._stringBundle.GetStringFromName("error.sync.tryAgainButton.accesskey"),
function() { gSyncUI.doSync(); return true; }
function() {
gSyncUI.doSync();
return true;
}
));
}

View File

@ -23,8 +23,9 @@ var tabPreviews = {
},
init: function() {
if (this._selectedTab)
if (this._selectedTab) {
return;
}
this._selectedTab = gBrowser.selectedTab;
gBrowser.tabContainer.addEventListener("TabSelect", this, false);
@ -40,8 +41,9 @@ var tabPreviews = {
aTab.__thumbnail_lastURI = null;
}
if (aTab.__thumbnail)
if (aTab.__thumbnail) {
return aTab.__thumbnail;
}
if (aTab.getAttribute("pending") == "true") {
let img = new Image;
@ -90,8 +92,9 @@ var tabPreviews = {
self._pendingUpdate = false;
if (aTab.parentNode &&
!aTab.hasAttribute("busy") &&
!aTab.hasAttribute("pending"))
!aTab.hasAttribute("pending")) {
self.capture(aTab, true);
}
}, 2000, this, this._selectedTab);
}
this._selectedTab = event.target;
@ -123,20 +126,23 @@ var tabPreviewPanelHelper = {
};
},
_popupshown: function(host) {
if ("setupGUI" in host)
if ("setupGUI" in host) {
host.setupGUI();
}
},
_popuphiding: function(host) {
if ("suspendGUI" in host)
if ("suspendGUI" in host) {
host.suspendGUI();
}
if (host._prevFocus) {
Cc["@mozilla.org/focus-manager;1"]
.getService(Ci.nsIFocusManager)
.setFocus(host._prevFocus, Ci.nsIFocusManager.FLAG_NOSCROLL);
host._prevFocus = null;
} else
} else {
gBrowser.selectedBrowser.focus();
}
if (host.tabToSelect) {
gBrowser.selectedTab = host.tabToSelect;
@ -149,23 +155,23 @@ var tabPreviewPanelHelper = {
* Ctrl-Tab panel
*/
var ctrlTab = {
get panel () {
get panel() {
delete this.panel;
return this.panel = document.getElementById("ctrlTab-panel");
},
get showAllButton () {
get showAllButton() {
delete this.showAllButton;
return this.showAllButton = document.getElementById("ctrlTab-showAll");
},
get previews () {
get previews() {
delete this.previews;
return this.previews = this.panel.getElementsByClassName("ctrlTab-preview");
},
get recentlyUsedLimit () {
get recentlyUsedLimit() {
delete this.recentlyUsedLimit;
return this.recentlyUsedLimit = gPrefService.getIntPref("browser.ctrlTab.recentlyUsedLimit");
},
get keys () {
get keys() {
var keys = {};
["close", "find", "selectAll"].forEach(function(key) {
keys[key] = document.getElementById("key_" + key)
@ -176,17 +182,26 @@ var ctrlTab = {
return this.keys = keys;
},
_selectedIndex: 0,
get selected () this._selectedIndex < 0 ?
document.activeElement :
this.previews.item(this._selectedIndex),
get isOpen () this.panel.state == "open" || this.panel.state == "showing" || this._timer,
get tabCount () this.tabList.length,
get tabPreviewCount () Math.min(this.previews.length - 1, this.tabCount),
get canvasWidth () Math.min(tabPreviews.width,
Math.ceil(screen.availWidth * .85 / this.tabPreviewCount)),
get canvasHeight () Math.round(this.canvasWidth * tabPreviews.aspectRatio),
get selected() {
return this._selectedIndex < 0 ? document.activeElement : this.previews.item(this._selectedIndex);
},
get isOpen() {
return this.panel.state == "open" || this.panel.state == "showing" || this._timer;
},
get tabCount() {
return this.tabList.length;
},
get tabPreviewCount() {
return Math.min(this.previews.length - 1, this.tabCount);
},
get canvasWidth() {
return Math.min(tabPreviews.width, Math.ceil(screen.availWidth * .85 / this.tabPreviewCount));
},
get canvasHeight() {
return Math.round(this.canvasWidth * tabPreviews.aspectRatio);
},
get tabList () {
get tabList() {
if (this._tabList)
return this._tabList;
@ -196,8 +211,9 @@ var ctrlTab = {
let list = Array.filter(gBrowser.tabs, function(tab) !tab.hidden);
// Rotate the list until the selected tab is first
while (!list[0].selected)
while (!list[0].selected) {
list.push(list.shift());
}
list = list.filter(function(tab) !tab.closing);
@ -206,8 +222,9 @@ var ctrlTab = {
for (let tab of this._recentlyUsedTabs) {
if (!tab.hidden && !tab.closing) {
recentlyUsedTabs.push(tab);
if (this.recentlyUsedLimit > 0 && recentlyUsedTabs.length >= this.recentlyUsedLimit)
if (this.recentlyUsedLimit > 0 && recentlyUsedTabs.length >= this.recentlyUsedLimit) {
break;
}
}
}
for (let i = recentlyUsedTabs.length - 1; i >= 0; i--) {
@ -249,18 +266,20 @@ var ctrlTab = {
(!gPrefService.prefHasUserValue("browser.ctrlTab.disallowForScreenReaders") ||
!gPrefService.getBoolPref("browser.ctrlTab.disallowForScreenReaders"));
if (enable)
if (enable) {
this.init();
else
} else {
this.uninit();
}
},
observe: function(aSubject, aTopic, aPrefName) {
this.readPref();
},
updatePreviews: function() {
for (let i = 0; i < this.previews.length; i++)
for (let i = 0; i < this.previews.length; i++) {
this.updatePreview(this.previews[i], this.tabList[i]);
}
var showAllLabel = gNavigatorBundle.getString("ctrlTab.showAll.label");
this.showAllButton.label =
@ -268,13 +287,15 @@ var ctrlTab = {
},
updatePreview: function(aPreview, aTab) {
if (aPreview == this.showAllButton)
if (aPreview == this.showAllButton) {
return;
}
aPreview._tab = aTab;
if (aPreview.firstChild)
if (aPreview.firstChild) {
aPreview.removeChild(aPreview.firstChild);
}
if (aTab) {
let canvasWidth = this.canvasWidth;
let canvasHeight = this.canvasHeight;
@ -305,10 +326,11 @@ var ctrlTab = {
let selectedIndex = Array.indexOf(this.previews, this.selected);
do {
selectedIndex += aForward ? 1 : -1;
if (selectedIndex < 0)
if (selectedIndex < 0) {
selectedIndex = this.previews.length - 1;
else if (selectedIndex >= this.previews.length)
} else if (selectedIndex >= this.previews.length) {
selectedIndex = 0;
}
} while (this.previews[selectedIndex].hidden);
if (this._selectedIndex == -1) {
@ -331,15 +353,17 @@ var ctrlTab = {
},
pick: function(aPreview) {
if (!this.tabCount)
if (!this.tabCount) {
return;
}
var select = (aPreview || this.selected);
if (select == this.showAllButton)
if (select == this.showAllButton) {
this.showAllTabs();
else
} else {
this.close(select._tab);
}
},
showAllTabs: function(aPreview) {
@ -348,27 +372,31 @@ var ctrlTab = {
},
remove: function(aPreview) {
if (aPreview._tab)
if (aPreview._tab) {
gBrowser.removeTab(aPreview._tab);
}
},
attachTab: function(aTab, aPos) {
if (aPos == 0)
if (aPos == 0) {
this._recentlyUsedTabs.unshift(aTab);
else if (aPos)
} else if (aPos) {
this._recentlyUsedTabs.splice(aPos, 0, aTab);
else
} else {
this._recentlyUsedTabs.push(aTab);
}
},
detachTab: function(aTab) {
var i = this._recentlyUsedTabs.indexOf(aTab);
if (i >= 0)
if (i >= 0) {
this._recentlyUsedTabs.splice(i, 1);
}
},
open: function() {
if (this.isOpen)
if (this.isOpen) {
return;
}
allTabs.close();
@ -397,15 +425,17 @@ var ctrlTab = {
},
close: function(aTabToSelect) {
if (!this.isOpen)
if (!this.isOpen) {
return;
}
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
this.suspendGUI();
if (aTabToSelect)
if (aTabToSelect) {
gBrowser.selectedTab = aTabToSelect;
}
return;
}
@ -421,8 +451,9 @@ var ctrlTab = {
// to be under the mouse pointer initially won't be selected unintentionally.
this._trackMouseOver = false;
setTimeout(function(self) {
if (self.isOpen)
if (self.isOpen) {
self._trackMouseOver = true;
}
}, 0, this);
},
@ -490,10 +521,12 @@ var ctrlTab = {
this._tabList = null;
this.updatePreviews();
if (this.selected.hidden)
if (this.selected.hidden) {
this.advanceFocus(false);
if (this.selected == this.showAllButton)
}
if (this.selected == this.showAllButton) {
this.advanceFocus(false);
}
// If the current tab is removed, another tab can steal our focus.
if (aTab.selected && this.panel.state == "open") {
@ -523,15 +556,17 @@ var ctrlTab = {
break;
case "TabClose":
this.detachTab(event.target);
if (this.isOpen)
if (this.isOpen) {
this.removeClosingTabFromUI(event.target);
}
break;
case "keypress":
this.onKeyPress(event);
break;
case "keyup":
if (event.keyCode == event.DOM_VK_CONTROL)
if (event.keyCode == event.DOM_VK_CONTROL) {
this.pick();
}
break;
}
},
@ -555,10 +590,11 @@ var ctrlTab = {
// Also disable the <key> to ensure Shift+Ctrl+Tab never triggers
// Show All Tabs.
var key_showAllTabs = document.getElementById("key_showAllTabs");
if (enable)
if (enable) {
key_showAllTabs.removeAttribute("disabled");
else
} else {
key_showAllTabs.setAttribute("disabled", "true");
}
}
};
@ -567,29 +603,36 @@ var ctrlTab = {
* All Tabs panel
*/
var allTabs = {
get panel () {
get panel() {
delete this.panel;
return this.panel = document.getElementById("allTabs-panel");
},
get filterField () {
get filterField() {
delete this.filterField;
return this.filterField = document.getElementById("allTabs-filter");
},
get container () {
get container() {
delete this.container;
return this.container = document.getElementById("allTabs-container");
},
get tabCloseButton () {
get tabCloseButton() {
delete this.tabCloseButton;
return this.tabCloseButton = document.getElementById("allTabs-tab-close-button");
},
get toolbarButton() document.getElementById("alltabs-button"),
get previews () this.container.getElementsByClassName("allTabs-preview"),
get isOpen () this.panel.state == "open" || this.panel.state == "showing",
get toolbarButton() {
return document.getElementById("alltabs-button");
},
get previews() {
return this.container.getElementsByClassName("allTabs-preview");
},
get isOpen() {
return this.panel.state == "open" || this.panel.state == "showing";
},
init: function() {
if (this._initiated)
if (this._initiated) {
return;
}
this._initiated = true;
tabPreviews.init();
@ -605,16 +648,18 @@ var allTabs = {
},
uninit: function() {
if (!this._initiated)
if (!this._initiated) {
return;
}
gBrowser.tabContainer.removeEventListener("TabOpen", this, false);
gBrowser.tabContainer.removeEventListener("TabAttrModified", this, false);
gBrowser.tabContainer.removeEventListener("TabMove", this, false);
gBrowser.tabContainer.removeEventListener("TabClose", this, false);
while (this.container.hasChildNodes())
while (this.container.hasChildNodes()) {
this.container.removeChild(this.container.firstChild);
}
this._initiated = false;
},
@ -622,8 +667,9 @@ var allTabs = {
prefName: "browser.allTabs.previews",
readPref: function() {
var allTabsButton = this.toolbarButton;
if (!allTabsButton)
if (!allTabsButton) {
return;
}
if (gPrefService.getBoolPref(this.prefName)) {
allTabsButton.removeAttribute("type");
@ -639,10 +685,12 @@ var allTabs = {
},
pick: function(aPreview) {
if (!aPreview)
if (!aPreview) {
aPreview = this._firstVisiblePreview;
if (aPreview)
}
if (aPreview) {
this.tabToSelect = aPreview._tab;
}
this.close();
},
@ -653,8 +701,9 @@ var allTabs = {
},
filter: function() {
if (this._currentFilter == this.filterField.value)
if (this._currentFilter == this.filterField.value) {
return;
}
this._currentFilter = this.filterField.value;
@ -676,15 +725,15 @@ var allTabs = {
let tabstring = tab.linkedBrowser.currentURI.spec;
try {
tabstring = decodeURI(tabstring);
} catch (e) {}
} catch(e) {}
tabstring = tab.label + " " + tab.label.toLocaleLowerCase() + " " + tabstring;
for (let i = 0; i < filter.length; i++)
for (let i = 0; i < filter.length; i++) {
matches += tabstring.includes(filter[i]);
}
}
if (matches < filter.length || tab.hidden || (hidePinnedTabs && tab.pinned)) {
preview.hidden = true;
}
else {
} else {
this._visible++;
this._updatePreview(preview);
preview.hidden = false;
@ -708,8 +757,9 @@ var allTabs = {
this.init();
if (this.isOpen)
if (this.isOpen) {
return;
}
this._maxPanelHeight = Math.max(gBrowser.clientHeight, screen.availHeight / 2);
this._maxPanelWidth = Math.max(gBrowser.clientWidth, screen.availWidth / 2);
@ -758,27 +808,31 @@ var allTabs = {
handleEvent: function(event) {
if (event.type.startsWith("Tab")) {
var tab = event.target;
if (event.type != "TabOpen")
if (event.type != "TabOpen") {
var preview = this._getPreview(tab);
}
}
switch (event.type) {
case "TabAttrModified":
// tab attribute modified (e.g. label, crop, busy, image)
if (!preview.hidden)
if (!preview.hidden) {
this._updatePreview(preview);
}
break;
case "TabOpen":
if (this.isOpen)
if (this.isOpen) {
this.close();
}
this._addPreview(tab);
break;
case "TabMove":
let siblingPreview = tab.nextSibling &&
this._getPreview(tab.nextSibling);
if (siblingPreview)
if (siblingPreview) {
siblingPreview.parentNode.insertBefore(preview, siblingPreview);
else
} else {
this.container.lastChild.appendChild(preview);
}
if (this.isOpen && !preview.hidden) {
this._reflow();
preview.focus();
@ -801,23 +855,23 @@ var allTabs = {
_visible: 0,
_currentFilter: null,
get _stack () {
get _stack() {
delete this._stack;
return this._stack = document.getElementById("allTabs-stack");
},
get _browserCommandSet () {
get _browserCommandSet() {
delete this._browserCommandSet;
return this._browserCommandSet = document.getElementById("mainCommandSet");
},
get _previewLabelHeight () {
get _previewLabelHeight() {
delete this._previewLabelHeight;
return this._previewLabelHeight = parseInt(getComputedStyle(this.previews[0], "").lineHeight);
},
get _visiblePreviews ()
get _visiblePreviews()
Array.filter(this.previews, function(preview) !preview.hidden),
get _firstVisiblePreview () {
get _firstVisiblePreview() {
if (this._visible == 0)
return null;
var previews = this.previews;
@ -860,10 +914,12 @@ var allTabs = {
var previews = Array.slice(this.previews);
while (this.container.hasChildNodes())
while (this.container.hasChildNodes()) {
this.container.removeChild(this.container.firstChild);
for (let i = rows || 1; i > 0; i--)
}
for (let i = rows || 1; i > 0; i--) {
this.container.appendChild(document.createElement("hbox"));
}
var row = this.container.firstChild;
var colCount = 0;
@ -907,19 +963,23 @@ var allTabs = {
_getPreview: function(aTab) {
var previews = this.previews;
for (let i = 0; i < previews.length; i++)
if (previews[i]._tab == aTab)
for (let i = 0; i < previews.length; i++) {
if (previews[i]._tab == aTab) {
return previews[i];
}
}
return null;
},
_updateTabCloseButton: function(event) {
if (event && event.target == this.tabCloseButton)
if (event && event.target == this.tabCloseButton) {
return;
}
if (this.tabCloseButton._targetPreview) {
if (event && event.target == this.tabCloseButton._targetPreview)
if (event && event.target == this.tabCloseButton._targetPreview) {
return;
}
this.tabCloseButton._targetPreview.removeAttribute("closebuttonhover");
}
@ -954,22 +1014,25 @@ var allTabs = {
aPreview.setAttribute("label", aPreview._tab.label);
aPreview.setAttribute("tooltiptext", aPreview._tab.label);
aPreview.setAttribute("crop", aPreview._tab.crop);
if (aPreview._tab.image)
if (aPreview._tab.image) {
aPreview.setAttribute("image", aPreview._tab.image);
else
} else {
aPreview.removeAttribute("image");
}
aPreview.removeAttribute("soundplaying");
aPreview.removeAttribute("muted");
if (aPreview._tab.hasAttribute("muted"))
if (aPreview._tab.hasAttribute("muted")) {
aPreview.setAttribute("muted", "true");
else if (aPreview._tab.hasAttribute("soundplaying"))
} else if (aPreview._tab.hasAttribute("soundplaying")) {
aPreview.setAttribute("soundplaying", "true");
}
var thumbnail = tabPreviews.get(aPreview._tab);
if (aPreview.firstChild) {
if (aPreview.firstChild == thumbnail)
if (aPreview.firstChild == thumbnail) {
return;
}
aPreview.removeChild(aPreview.firstChild);
}
aPreview.appendChild(thumbnail);
@ -1014,8 +1077,9 @@ var allTabs = {
switch (event.keyCode) {
case event.DOM_VK_UP:
case event.DOM_VK_DOWN:
if (event.target != this.filterField)
if (event.target != this.filterField) {
this._advanceFocusVertically(event);
}
break;
case event.DOM_VK_RETURN:
if (event.target == this.filterField) {
@ -1030,8 +1094,9 @@ var allTabs = {
_advanceFocusVertically: function(event) {
var preview = document.activeElement;
if (!preview || preview.parentNode.parentNode != this.container)
if (!preview || preview.parentNode.parentNode != this.container) {
return;
}
event.stopPropagation();
@ -1057,8 +1122,9 @@ var allTabs = {
let rows = Math.ceil(previews.length / columns);
row = rows - 1;
column--;
if (outOfBounds())
if (outOfBounds()) {
row--;
}
}
} else {
row++;

View File

@ -32,13 +32,14 @@ var gBrowserThumbnails = {
init: function() {
// Bug 863512 - Make page thumbnails work in electrolysis
if (gMultiProcessBrowser)
if (gMultiProcessBrowser) {
return;
}
try {
if (Services.prefs.getBoolPref("browser.pagethumbnails.capturing_disabled"))
return;
} catch (e) {}
} catch(e) {}
PageThumbs.addExpirationFilter(this);
gBrowser.addTabsProgressListener(this);
@ -56,8 +57,9 @@ var gBrowserThumbnails = {
uninit: function() {
// Bug 863512 - Make page thumbnails work in electrolysis
if (gMultiProcessBrowser)
if (gMultiProcessBrowser) {
return;
}
PageThumbs.removeExpirationFilter(this);
gBrowser.removeTabsProgressListener(this);
@ -72,8 +74,9 @@ var gBrowserThumbnails = {
switch (aEvent.type) {
case "scroll":
let browser = aEvent.currentTarget;
if (this._timeouts.has(browser))
if (this._timeouts.has(browser)) {
this._delayedCapture(browser);
}
break;
case "TabSelect":
this._delayedCapture(aEvent.target.linkedBrowser);
@ -106,20 +109,23 @@ var gBrowserThumbnails = {
onStateChange: function(aBrowser, aWebProgress,
aRequest, aStateFlags, aStatus) {
if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK)
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
this._delayedCapture(aBrowser);
}
},
_capture: function(aBrowser) {
if (this._shouldCapture(aBrowser))
if (this._shouldCapture(aBrowser)) {
PageThumbs.captureAndStore(aBrowser);
}
},
_delayedCapture: function(aBrowser) {
if (this._timeouts.has(aBrowser))
if (this._timeouts.has(aBrowser)) {
clearTimeout(this._timeouts.get(aBrowser));
else
} else {
aBrowser.addEventListener("scroll", this, true);
}
let timeout = setTimeout(function() {
this._clearTimeout(aBrowser);
@ -131,63 +137,75 @@ var gBrowserThumbnails = {
_shouldCapture: function(aBrowser) {
// Capture only if it's the currently selected tab.
if (aBrowser != gBrowser.selectedBrowser)
if (aBrowser != gBrowser.selectedBrowser) {
return false;
}
// Don't capture in per-window private browsing mode.
if (PrivateBrowsingUtils.isWindowPrivate(window))
if (PrivateBrowsingUtils.isWindowPrivate(window)) {
return false;
}
let doc = aBrowser.contentDocument;
// FIXME Bug 720575 - Don't capture thumbnails for SVG or XML documents as
// that currently regresses Talos SVG tests.
if (doc instanceof XMLDocument)
if (doc instanceof XMLDocument) {
return false;
}
// There's no point in taking screenshot of loading pages.
if (aBrowser.docShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE)
if (aBrowser.docShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE) {
return false;
}
// Don't take screenshots of about: pages.
if (aBrowser.currentURI.schemeIs("about"))
if (aBrowser.currentURI.schemeIs("about")) {
return false;
}
let channel = aBrowser.docShell.currentDocumentChannel;
// No valid document channel. We shouldn't take a screenshot.
if (!channel)
if (!channel) {
return false;
}
// Don't take screenshots of internally redirecting about: pages.
// This includes error pages.
let uri = channel.originalURI;
if (uri.schemeIs("about"))
if (uri.schemeIs("about")) {
return false;
}
let httpChannel;
try {
httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);
} catch (e) { /* Not an HTTP channel. */ }
} catch(e) {
// Not an HTTP channel.
}
if (httpChannel) {
// Continue only if we have a 2xx status code.
try {
if (Math.floor(httpChannel.responseStatus / 100) != 2)
if (Math.floor(httpChannel.responseStatus / 100) != 2) {
return false;
} catch (e) {
}
} catch(e) {
// Can't get response information from the httpChannel
// because mResponseHead is not available.
return false;
}
// Cache-Control: no-store.
if (httpChannel.isNoStoreResponse())
if (httpChannel.isNoStoreResponse()) {
return false;
}
// Don't capture HTTPS pages unless the user explicitly enabled it.
if (uri.schemeIs("https") && !this._sslDiskCacheEnabled)
if (uri.schemeIs("https") && !this._sslDiskCacheEnabled) {
return false;
}
}
return true;

View File

@ -5,7 +5,7 @@
var WebrtcIndicator = {
init: function () {
let temp = {};
let temp = { };
Cu.import("resource:///modules/webrtcUI.jsm", temp);
this.UIModule = temp.webrtcUI;
@ -35,14 +35,16 @@ var WebrtcIndicator = {
},
clearPopup: function (aPopup) {
while (aPopup.lastChild)
while (aPopup.lastChild) {
aPopup.removeChild(aPopup.lastChild);
}
},
menuCommand: function (aMenuitem) {
let streamData = this._menuitemData.get(aMenuitem);
if (!streamData)
if (!streamData) {
return;
}
let browserWindow = streamData.browser.ownerDocument.defaultView;
if (streamData.tab) {

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -11,56 +11,57 @@ var openLocationModule = {};
try {
pref = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
} catch (ex) {
} catch(ex) {
// not critical, remain silent
}
Components.utils.import("resource:///modules/openLocationLastURL.jsm", openLocationModule);
var gOpenLocationLastURL = new openLocationModule.OpenLocationLastURL(window.opener);
function onLoad()
{
function onLoad() {
dialog.input = document.getElementById("dialog.input");
dialog.open = document.documentElement.getButton("accept");
dialog.openWhereList = document.getElementById("openWhereList");
dialog.openTopWindow = document.getElementById("currentWindow");
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];
}
dialog.openWhereList.selectedItem = dialog.openTopWindow;
if (pref) {
try {
var useAutoFill = pref.getBoolPref("browser.urlbar.autoFill");
if (useAutoFill)
if (useAutoFill) {
dialog.input.setAttribute("completedefaultindex", "true");
} catch (ex) {}
}
} catch(ex) {}
try {
var value = pref.getIntPref("general.open_location.last_window_choice");
var element = dialog.openWhereList.getElementsByAttribute("value", value)[0];
if (element)
if (element) {
dialog.openWhereList.selectedItem = element;
}
dialog.input.value = gOpenLocationLastURL.value;
} catch(ex) {}
if (dialog.input.value) {
// XXX should probably be done automatically
dialog.input.select();
}
catch(ex) {
}
if (dialog.input.value)
dialog.input.select(); // XXX should probably be done automatically
}
doEnabling();
}
function doEnabling()
{
function doEnabling() {
dialog.open.disabled = !dialog.input.value;
}
function open()
{
function open() {
var openData = {
"url": null,
"postData": null,
@ -83,8 +84,7 @@ function open()
return false;
}
function openLocation(openData)
{
function openLocation(openData) {
try {
// Whichever target we use for the load, we allow third-party services to
// fix up the URI
@ -93,10 +93,10 @@ function openLocation(openData)
var webNav = Components.interfaces.nsIWebNavigation;
var flags = webNav.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
webNav.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
if (!openData.mayInheritPrincipal)
if (!openData.mayInheritPrincipal) {
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;
case "1":
window.opener.delayedOpenWindow(getBrowserURL(), "all,dialog=no",
@ -104,16 +104,14 @@ function openLocation(openData)
null, null, true);
break;
case "3":
browser.delayedOpenTab(
openData.url, null, null, openData.postData, true);
browser.delayedOpenTab(openData.url, null, null, openData.postData, true);
break;
}
} catch (ex) {}
} catch(ex) {}
if (pref) {
gOpenLocationLastURL.value = dialog.input.value;
pref.setIntPref(
"general.open_location.last_window_choice", dialog.openWhereList.value);
pref.setIntPref("general.open_location.last_window_choice", dialog.openWhereList.value);
}
window.close();
@ -129,10 +127,11 @@ const nsIFilePicker = Components.interfaces.nsIFilePicker;
function onChooseFile()
{
try {
let fp = Components.classes["@mozilla.org/filepicker;1"].
createInstance(nsIFilePicker);
let fp = Components.classes["@mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
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) {
dialog.input.value = fp.fileURL.spec;
}
@ -145,6 +144,5 @@ function onChooseFile()
nsIFilePicker.filterImages | nsIFilePicker.filterXML |
nsIFilePicker.filterHTML);
fp.open(fpCallback);
} catch (ex) {
}
} catch(ex) {}
}

View File

@ -5,88 +5,90 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var padlock_PadLock =
{
QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
Ci.nsISupportsWeakReference]),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
Ci.nsISupportsWeakReference]),
onButtonClick: function(event) {
event.stopPropagation();
gIdentityHandler.handleMoreInfoClick(event);
},
onStateChange: function() {},
onProgressChange: function() {},
onLocationChange: function() {},
onStatusChange: function() {},
onSecurityChange: function(aCallerWebProgress, aRequestWithState, aState) {
// aState is defined as a bitmask that may be extended in the future.
// We filter out any unknown bits before testing for known values.
const wpl = Ci.nsIWebProgressListener;
const wpl_security_bits = wpl.STATE_IS_SECURE |
wpl.STATE_IS_BROKEN |
wpl.STATE_IS_INSECURE |
wpl.STATE_IDENTITY_EV_TOPLEVEL |
wpl.STATE_SECURE_HIGH |
wpl.STATE_SECURE_MED |
wpl.STATE_SECURE_LOW;
var level;
var is_insecure;
var highlight_urlbar = false;
onStateChange: function() {},
onProgressChange: function() {},
onLocationChange: function() {},
onStatusChange: function() {},
onSecurityChange: function(aCallerWebProgress, aRequestWithState, aState) {
// aState is defined as a bitmask that may be extended in the future.
// We filter out any unknown bits before testing for known values.
const wpl = Ci.nsIWebProgressListener;
const wpl_security_bits = wpl.STATE_IS_SECURE |
wpl.STATE_IS_BROKEN |
wpl.STATE_IS_INSECURE |
wpl.STATE_IDENTITY_EV_TOPLEVEL |
wpl.STATE_SECURE_HIGH |
wpl.STATE_SECURE_MED |
wpl.STATE_SECURE_LOW;
var level;
var is_insecure;
var highlight_urlbar = false;
switch (aState & wpl_security_bits) {
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH | wpl.STATE_IDENTITY_EV_TOPLEVEL:
level = "ev";
is_insecure = "";
highlight_urlbar = true;
break;
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH:
level = "high";
is_insecure = "";
highlight_urlbar = true;
break;
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_MED:
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW:
level = "low";
is_insecure = "insecure";
break;
case wpl.STATE_IS_BROKEN | wpl.STATE_SECURE_LOW:
level = "mixed";
is_insecure = "insecure";
highlight_urlbar = true;
break;
case wpl.STATE_IS_BROKEN:
level = "broken";
is_insecure = "insecure";
highlight_urlbar = true;
break;
default: // should not be reached
level = null;
is_insecure = "insecure";
}
switch (aState & wpl_security_bits) {
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH | wpl.STATE_IDENTITY_EV_TOPLEVEL:
level = "ev";
is_insecure = "";
highlight_urlbar = true;
break;
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH:
level = "high";
is_insecure = "";
highlight_urlbar = true;
break;
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_MED:
case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW:
level = "low";
is_insecure = "insecure";
break;
case wpl.STATE_IS_BROKEN | wpl.STATE_SECURE_LOW:
level = "mixed";
is_insecure = "insecure";
highlight_urlbar = true;
break;
case wpl.STATE_IS_BROKEN:
level = "broken";
is_insecure = "insecure";
highlight_urlbar = true;
break;
default: // should not be reached
level = null;
is_insecure = "insecure";
}
try {
var proto = gBrowser.contentWindow.location.protocol;
if (proto == "about:" || proto == "chrome:" || proto == "file:" ) {
// do not warn when using local protocols
is_insecure = false;
}
}
catch (ex) {}
try {
var proto = gBrowser.contentWindow.location.protocol;
if (proto == "about:" || proto == "chrome:" || proto == "file:" ) {
// do not warn when using local protocols
is_insecure = false;
}
} catch(ex) {}
let ub = document.getElementById("urlbar");
if (ub) { // Only call if URL bar is present.
if (highlight_urlbar) {
ub.setAttribute("security_level", level);
} else {
ub.removeAttribute("security_level");
}
}
let ub = document.getElementById("urlbar");
if (ub) {
// Only call if URL bar is present.
if (highlight_urlbar) {
ub.setAttribute("security_level", level);
} else {
ub.removeAttribute("security_level");
}
}
try { // URL bar may be hidden
padlock_PadLock.setPadlockLevel("padlock-ib", level);
padlock_PadLock.setPadlockLevel("padlock-ib-left", level);
padlock_PadLock.setPadlockLevel("padlock-ub-right", level);
} catch(e) {}
padlock_PadLock.setPadlockLevel("padlock-sb", level);
padlock_PadLock.setPadlockLevel("padlock-tab", level);
},
try { // URL bar may be hidden
padlock_PadLock.setPadlockLevel("padlock-ib", level);
padlock_PadLock.setPadlockLevel("padlock-ib-left", level);
padlock_PadLock.setPadlockLevel("padlock-ub-right", level);
} catch(e) {}
padlock_PadLock.setPadlockLevel("padlock-sb", level);
padlock_PadLock.setPadlockLevel("padlock-tab", level);
},
setPadlockLevel: function(item, level) {
let secbut = document.getElementById(item);
var sectooltip = "";
@ -120,7 +122,9 @@ var padlock_PadLock =
}
secbut.setAttribute("tooltiptext", sectooltip);
},
prefbranch : null,
onLoad: function() {
gBrowser.addProgressListener(padlock_PadLock);
@ -148,40 +152,32 @@ var padlock_PadLock =
if (prefval == 2) {
position = "ib-left";
padstyle = "modern";
}
else if (prefval == 3) {
} else if (prefval == 3) {
position = "ub-right";
padstyle = "modern";
}
else if (prefval == 4) {
} else if (prefval == 4) {
position = "statbar";
padstyle = "modern";
}
else if (prefval == 5) {
} else if (prefval == 5) {
position = "tabs-bar";
padstyle = "modern";
}
else if (prefval == 6) {
} else if (prefval == 6) {
position = "ib-trans-bg";
padstyle = "classic";
}
else if (prefval == 7) {
} else if (prefval == 7) {
position = "ib-left";
padstyle = "classic";
}
else if (prefval == 8) {
} else if (prefval == 8) {
position = "ub-right";
padstyle = "classic";
}
else if (prefval == 9) {
} else if (prefval == 9) {
position = "statbar";
padstyle = "classic";
}
else if (prefval == 10) {
} else if (prefval == 10) {
position = "tabs-bar";
padstyle = "classic";
}
else { // 1 or anything else_ default
} else {
// 1 or anything else_ default
position = "ib-trans-bg";
padstyle = "modern";
}
@ -198,10 +194,12 @@ var padlock_PadLock =
case 1:
colshow = "secure-only";
break;
default:
colshow = ""; // 0 or anything else: no shading
default:
// 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);
} catch(e) {}
@ -216,6 +214,7 @@ var padlock_PadLock =
document.getElementById("padlock-ib-left").setAttribute("padshow", padshow);
document.getElementById("padlock-ub-right").setAttribute("padshow", padshow);
} catch(e) {}
document.getElementById("padlock-sb").setAttribute("padshow", padshow);
document.getElementById("padlock-tab").setAttribute("padshow", padshow);
@ -224,6 +223,7 @@ var padlock_PadLock =
document.getElementById("padlock-ib-left").setAttribute("padstyle", padstyle);
document.getElementById("padlock-ub-right").setAttribute("padstyle", padstyle);
} catch(e) {}
document.getElementById("padlock-sb").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() {
let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
.getService(Ci.nsIAppStartup);
.getService(Ci.nsIAppStartup);
appStartup.quit(Ci.nsIAppStartup.eForceQuit | Ci.nsIAppStartup.eRestart);
}
function clearAllPrefs() {
var prefService = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService);
.getService(Ci.nsIPrefService);
prefService.resetUserPrefs();
// Remove the pref-overrides dir, if it exists
try {
var fileLocator = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties);
.getService(Ci.nsIProperties);
const NS_APP_PREFS_OVERRIDE_DIR = "PrefDOverride";
var prefOverridesDir = fileLocator.get(NS_APP_PREFS_OVERRIDE_DIR,
Ci.nsIFile);
var prefOverridesDir = fileLocator.get(NS_APP_PREFS_OVERRIDE_DIR, Ci.nsIFile);
prefOverridesDir.remove(true);
} catch (ex) {
} catch(ex) {
Components.utils.reportError(ex);
}
}
function restoreDefaultBookmarks() {
var prefBranch = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefBranch);
.getService(Ci.nsIPrefBranch);
prefBranch.setBoolPref("browser.bookmarks.restore_default_bookmarks", true);
}
@ -42,7 +41,7 @@ function deleteLocalstore() {
const nsIDirectoryServiceContractID = "@mozilla.org/file/directory_service;1";
const nsIProperties = Ci.nsIProperties;
var directoryService = Cc[nsIDirectoryServiceContractID]
.getService(nsIProperties);
.getService(nsIProperties);
// Local store file
var localstoreFile = directoryService.get("LStoreS", Components.interfaces.nsIFile);
// XUL store file
@ -68,8 +67,7 @@ function disableAddons() {
const DEFAULT_THEME_ID = "{972ce4c6-7e08-4474-a285-3208198ce6fd}";
if (aAddon.id == DEFAULT_THEME_ID)
aAddon.userDisabled = false;
}
else {
} else {
aAddon.userDisabled = true;
}
});
@ -80,28 +78,31 @@ function disableAddons() {
function restoreDefaultSearchEngines() {
var searchService = Cc["@mozilla.org/browser/search-service;1"]
.getService(Ci.nsIBrowserSearchService);
.getService(Ci.nsIBrowserSearchService);
searchService.restoreDefaultEngines();
}
function onOK() {
try {
if (document.getElementById("resetUserPrefs").checked)
if (document.getElementById("resetUserPrefs").checked) {
clearAllPrefs();
if (document.getElementById("deleteBookmarks").checked)
}
if (document.getElementById("deleteBookmarks").checked) {
restoreDefaultBookmarks();
if (document.getElementById("resetToolbars").checked)
}
if (document.getElementById("resetToolbars").checked) {
deleteLocalstore();
if (document.getElementById("restoreSearch").checked)
}
if (document.getElementById("restoreSearch").checked) {
restoreDefaultSearchEngines();
}
if (document.getElementById("disableAddons").checked) {
disableAddons();
// disableAddons will asynchronously restart the application
return false;
}
} catch(e) {
}
} catch(e) {}
restartApp();
return false;
@ -109,7 +110,7 @@ function onOK() {
function onCancel() {
let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
.getService(Ci.nsIAppStartup);
.getService(Ci.nsIAppStartup);
appStartup.quit(Ci.nsIAppStartup.eForceQuit);
}

View File

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

View File

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

View File

@ -15,14 +15,15 @@ XPCOMUtils.defineLazyModuleGetter(this, "ShellService",
XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
"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";
function getNewTabPageURL() {
if (!Services.prefs.prefHasUserValue(PREF)) {
if (PrivateBrowsingUtils.isWindowPrivate(window) &&
!PrivateBrowsingUtils.permanentPrivateBrowsing)
!PrivateBrowsingUtils.permanentPrivateBrowsing) {
return "about:privatebrowsing";
}
}
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.
*/
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.
// Original code: return aURL == "about:blank" || aURL == BROWSER_NEW_TAB_URL;
return aURL == "about:blank" || aURL == "about:newtab" || aURL == "about:logopage";
}
function getBrowserURL()
{
function getBrowserURL() {
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
// background windows (bug 626148).
if (top.document.documentElement.getAttribute("windowtype") == "navigator:browser" &&
(!skipPopups || top.toolbar.visible))
(!skipPopups || top.toolbar.visible)) {
return top;
}
let isPrivate = PrivateBrowsingUtils.isWindowPrivate(window);
return RecentWindow.getMostRecentBrowserWindow({private: isPrivate,
allowPopups: !skipPopups});
return RecentWindow.getMostRecentBrowserWindow({ private: isPrivate,
allowPopups: !skipPopups });
}
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".
* - 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.
// e = { shiftKey:false, ctrlKey:false, metaKey:false, altKey:false, button:0 })
// for compatibility purposes.
if (!e)
if (!e) {
return "current";
}
var shift = e.shiftKey;
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.
#ifdef XP_MACOSX
if (meta || (middle && middleUsesTabs))
if (meta || (middle && middleUsesTabs)) {
#else
if (ctrl || (middle && middleUsesTabs))
if (ctrl || (middle && middleUsesTabs)) {
#endif
return shift ? "tabshifted" : "tab";
}
if (alt && Services.prefs.getBoolPref("browser.altClickSave", false))
if (alt && Services.prefs.getBoolPref("browser.altClickSave", false)) {
return "save";
}
if (shift || (middle && !middleUsesTabs))
if (shift || (middle && !middleUsesTabs)) {
return "window";
}
return "current";
}
@ -213,8 +217,9 @@ function openUILinkIn(url, where, aAllowThirdPartyFixup, aPostData, aReferrerURI
/* eslint-disable complexity */
function openLinkIn(url, where, params) {
if (!where || !url)
if (!where || !url) {
return;
}
const Cc = Components.classes;
const Ci = Components.interfaces;
@ -224,7 +229,8 @@ function openLinkIn(url, where, params) {
var aCharset = params.charset;
var aReferrerURI = params.referrerURI;
var aReferrerPolicy = ('referrerPolicy' in params ?
params.referrerPolicy : Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT);
params.referrerPolicy :
Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT);
var aRelatedToCurrent = params.relatedToCurrent;
var aForceAllowDataURI = params.forceAllowDataURI;
var aInBackground = params.inBackground;
@ -233,8 +239,7 @@ function openLinkIn(url, where, params) {
var aIsPrivate = params.private;
var aPrincipal = params.originPrincipal;
var aTriggeringPrincipal = params.triggeringPrincipal;
var aForceAboutBlankViewerInCurrent =
params.forceAboutBlankViewerInCurrent;
var aForceAboutBlankViewerInCurrent = params.forceAboutBlankViewerInCurrent;
var sendReferrerURI = true;
if (where == "save") {
@ -284,33 +289,30 @@ function openLinkIn(url, where, params) {
sendReferrerURI = false;
}
var sa = Cc["@mozilla.org/supports-array;1"].
createInstance(Ci.nsISupportsArray);
var sa = Cc["@mozilla.org/supports-array;1"].createInstance(Ci.nsISupportsArray);
var wuri = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
var wuri = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
wuri.data = url;
let charset = null;
if (aCharset) {
charset = Cc["@mozilla.org/supports-string;1"]
.createInstance(Ci.nsISupportsString);
charset = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
charset.data = "charset=" + aCharset;
}
var allowThirdPartyFixupSupports = Cc["@mozilla.org/supports-PRBool;1"].
createInstance(Ci.nsISupportsPRBool);
var allowThirdPartyFixupSupports = Cc["@mozilla.org/supports-PRBool;1"]
.createInstance(Ci.nsISupportsPRBool);
allowThirdPartyFixupSupports.data = aAllowThirdPartyFixup;
var referrerURISupports = null;
if (aReferrerURI && sendReferrerURI) {
referrerURISupports = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
referrerURISupports = Cc["@mozilla.org/supports-string;1"]
.createInstance(Ci.nsISupportsString);
referrerURISupports.data = aReferrerURI.spec;
}
var referrerPolicySupports = Cc["@mozilla.org/supports-PRUint32;1"].
createInstance(Ci.nsISupportsPRUint32);
var referrerPolicySupports = Cc["@mozilla.org/supports-PRUint32;1"]
.createInstance(Ci.nsISupportsPRUint32);
referrerPolicySupports.data = aReferrerPolicy;
sa.AppendElement(wuri);
@ -334,15 +336,15 @@ function openLinkIn(url, where, params) {
let loadInBackground = where == "current" ? false : aInBackground;
if (loadInBackground == null) {
loadInBackground = aFromChrome ?
false :
Services.prefs.getBoolPref("browser.tabs.loadInBackground");
false :
Services.prefs.getBoolPref("browser.tabs.loadInBackground");
}
let uriObj;
if (where == "current") {
try {
uriObj = Services.io.newURI(url, null, null);
} catch (e) {}
} catch(e) {}
}
if (where == "current" && w.gBrowser.selectedTab.pinned) {
@ -353,7 +355,7 @@ function openLinkIn(url, where, params) {
where = "tab";
loadInBackground = false;
}
} catch (err) {
} catch(err) {
where = "tab";
loadInBackground = false;
}
@ -365,53 +367,51 @@ function openLinkIn(url, where, params) {
let browserUsedForLoad = null;
switch (where) {
case "current":
let flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
if (aAllowThirdPartyFixup) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
}
if (aDisallowInheritPrincipal)
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL;
if (aForceAllowDataURI) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FORCE_ALLOW_DATA_URI;
}
let {URI_INHERITS_SECURITY_CONTEXT} = Ci.nsIProtocolHandler;
if (aForceAboutBlankViewerInCurrent &&
(!uriObj ||
(Services.io.getProtocolFlags(uriObj.scheme) & URI_INHERITS_SECURITY_CONTEXT))) {
// Unless we know for sure we're not inheriting principals,
// force the about:blank viewer to have the right principal:
w.gBrowser.selectedBrowser.createAboutBlankContentViewer(aPrincipal);
}
case "current":
let flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
if (aAllowThirdPartyFixup) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
}
if (aDisallowInheritPrincipal) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL;
}
if (aForceAllowDataURI) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FORCE_ALLOW_DATA_URI;
}
let {URI_INHERITS_SECURITY_CONTEXT} = Ci.nsIProtocolHandler;
if (aForceAboutBlankViewerInCurrent &&
(!uriObj ||
(Services.io.getProtocolFlags(uriObj.scheme) & URI_INHERITS_SECURITY_CONTEXT))) {
// Unless we know for sure we're not inheriting principals,
// force the about:blank viewer to have the right principal:
w.gBrowser.selectedBrowser.createAboutBlankContentViewer(aPrincipal);
}
w.gBrowser.loadURIWithFlags(url, {
flags: flags,
triggeringPrincipal: aTriggeringPrincipal,
referrerURI: aReferrerURI,
referrerPolicy: aReferrerPolicy,
postData: aPostData,
originPrincipal: aPrincipal,
});
browserUsedForLoad = aCurrentBrowser;
break;
case "tabshifted":
loadInBackground = !loadInBackground;
// fall through
case "tab":
let browser = w.gBrowser;
let tabUsedForLoad = browser.loadOneTab(url, {
referrerURI: aReferrerURI,
referrerPolicy: aReferrerPolicy,
charset: aCharset,
postData: aPostData,
inBackground: loadInBackground,
allowThirdPartyFixup: aAllowThirdPartyFixup,
relatedToCurrent: aRelatedToCurrent,
originPrincipal: aPrincipal,
triggeringPrincipal: aTriggeringPrincipal });
browserUsedForLoad = tabUsedForLoad.linkedBrowser;
break;
w.gBrowser.loadURIWithFlags(url, { flags: flags,
triggeringPrincipal: aTriggeringPrincipal,
referrerURI: aReferrerURI,
referrerPolicy: aReferrerPolicy,
postData: aPostData,
originPrincipal: aPrincipal });
browserUsedForLoad = aCurrentBrowser;
break;
case "tabshifted":
loadInBackground = !loadInBackground;
// fall through
case "tab":
let browser = w.gBrowser;
let tabUsedForLoad = browser.loadOneTab(url, { referrerURI: aReferrerURI,
referrerPolicy: aReferrerPolicy,
charset: aCharset,
postData: aPostData,
inBackground: loadInBackground,
allowThirdPartyFixup: aAllowThirdPartyFixup,
relatedToCurrent: aRelatedToCurrent,
originPrincipal: aPrincipal,
triggeringPrincipal: aTriggeringPrincipal });
browserUsedForLoad = tabUsedForLoad.linkedBrowser;
break;
}
// Focus the content, but only if the browser used for the load is selected.
@ -420,10 +420,11 @@ function openLinkIn(url, where, params) {
browserUsedForLoad.focus();
}
if (!loadInBackground && w.isBlankPageURL(url))
if (!loadInBackground && w.isBlankPageURL(url)) {
if (!w.focusAndSelectUrlBar()) {
console.error("Unable to focus and select address bar.")
}
}
}
// Used as an onclick handler for UI elements with link-like behavior.
@ -432,15 +433,18 @@ function checkForMiddleClick(node, event) {
// 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.
// menuitem).
if (node.getAttribute("disabled") == "true")
return; // Do nothing
if (node.getAttribute("disabled") == "true") {
// Do nothing
return;
}
if (event.button == 1) {
/* Execute the node's oncommand or command.
*
* 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"));
var fn = new Function("event", target.getAttribute("oncommand"));
fn.call(target, event);
@ -455,17 +459,17 @@ function checkForMiddleClick(node, event) {
function closeMenus(node)
{
if ("tagName" in node) {
if (node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
&& (node.tagName == "menupopup" || node.tagName == "popup"))
if (node.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" &&
(node.tagName == "menupopup" || node.tagName == "popup")) {
node.hidePopup();
}
closeMenus(node.parentNode);
}
}
// Gather all descendent text under given document node.
function gatherTextUnder ( root )
{
// Gather all descendant text under given document node.
function gatherTextUnder(root) {
var text = "";
var node = root.firstChild;
var depth = 1;
@ -509,15 +513,15 @@ function gatherTextUnder ( root )
}
// This function exists for legacy reasons.
function getShellService()
{
function getShellService() {
return ShellService;
}
function isBidiEnabled() {
// first check the pref.
if (Services.prefs.getBoolPref("bidi.browser.ui", false))
if (Services.prefs.getBoolPref("bidi.browser.ui", false)) {
return true;
}
// if the pref isn't set, check for an RTL locale and force the pref to true
// if we find one.
@ -537,7 +541,7 @@ function isBidiEnabled() {
rv = true;
Services.prefs.setBoolPref("bidi.browser.ui", true);
}
} catch (e) {}
} catch(e) {}
return rv;
}
@ -546,22 +550,20 @@ function isBidiEnabled() {
/**
* Opens the update manager and checks for updates to the application.
*/
function checkForUpdates()
{
var um =
Components.classes["@mozilla.org/updates/update-manager;1"].
getService(Components.interfaces.nsIUpdateManager);
var prompter =
Components.classes["@mozilla.org/updates/update-prompt;1"].
createInstance(Components.interfaces.nsIUpdatePrompt);
function checkForUpdates() {
var um = Components.classes["@mozilla.org/updates/update-manager;1"]
.getService(Components.interfaces.nsIUpdateManager);
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"
// UI instead and let the user know they have to restart the application for
// 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);
else
} else {
prompter.checkForUpdates();
}
}
#endif
@ -569,15 +571,12 @@ function checkForUpdates()
* Set up the help menu software update items to show proper status,
* also disabling the items if update is disabled.
*/
function buildHelpMenu()
{
function buildHelpMenu() {
#ifdef MOZ_UPDATER
var updates =
Components.classes["@mozilla.org/updates/update-service;1"].
getService(Components.interfaces.nsIApplicationUpdateService);
var um =
Components.classes["@mozilla.org/updates/update-manager;1"].
getService(Components.interfaces.nsIUpdateManager);
var updates = Components.classes["@mozilla.org/updates/update-service;1"]
.getService(Components.interfaces.nsIApplicationUpdateService);
var um = 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
// administrator or if we cannot update for some other reason.
@ -601,8 +600,9 @@ function buildHelpMenu()
// If there's an active update, substitute its name into the label
// we show for this item, otherwise display a generic label.
function getStringWithUpdateName(key) {
if (activeUpdate && activeUpdate.name)
if (activeUpdate && activeUpdate.name) {
return strings.getFormattedString(key, [activeUpdate.name]);
}
return strings.getString(key + "Fallback");
}
@ -611,20 +611,20 @@ function buildHelpMenu()
var key = "default";
if (activeUpdate) {
switch (activeUpdate.state) {
case "downloading":
// If we're downloading an update at present, show the text:
// "Downloading Thunderbird x.x..." from updatesItem_downloading or
// updatesItem_downloadingFallback, otherwise we're paused, and show
// "Resume Downloading Thunderbird x.x..." from updatesItem_resume or
// updatesItem_resumeFallback
key = updates.isDownloading ? "downloading" : "resume";
break;
case "pending":
// If we're waiting for the user to restart, show: "Apply Downloaded
// Updates Now..." from updatesItem_pending or
// updatesItem_pendingFallback
key = "pending";
break;
case "downloading":
// If we're downloading an update at present, show the text:
// "Downloading Thunderbird x.x..." from updatesItem_downloading or
// updatesItem_downloadingFallback, otherwise we're paused, and show
// "Resume Downloading Thunderbird x.x..." from updatesItem_resume or
// updatesItem_resumeFallback
key = updates.isDownloading ? "downloading" : "resume";
break;
case "pending":
// If we're waiting for the user to restart, show: "Apply Downloaded
// Updates Now..." from updatesItem_pending or
// updatesItem_pendingFallback
key = "pending";
break;
}
}
@ -636,12 +636,10 @@ function buildHelpMenu()
// updatesItem_default.accesskey, updatesItem_downloading.accesskey,
// updatesItem_resume.accesskey or updatesItem_pending.accesskey
checkForUpdates.accessKey = strings.getString("updatesItem_" + key +
".accesskey");
checkForUpdates.accessKey = strings.getString("updatesItem_" + key + ".accesskey");
if (appMenuCheckForUpdates) {
appMenuCheckForUpdates.accessKey = strings.getString("updatesItem_" + key +
".accesskey");
appMenuCheckForUpdates.accessKey = strings.getString("updatesItem_" + key + ".accesskey");
}
if (um.activeUpdate && updates.isDownloading) {
@ -664,8 +662,9 @@ function buildHelpMenu()
var aboutSeparator = document.getElementById("aboutSeparator");
var checkForUpdates = document.getElementById("checkForUpdates");
if (updatesSeparator.nextSibling === checkForUpdates &&
checkForUpdates.nextSibling === aboutSeparator)
checkForUpdates.nextSibling === aboutSeparator) {
updatesSeparator.hidden = true;
}
#endif
#endif
}
@ -690,8 +689,7 @@ function openAboutDialog() {
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 features = "chrome,titlebar,toolbar,centerscreen" + (instantApply ? ",dialog=no" : ",modal");
@ -715,16 +713,14 @@ function openPreferences(paneID, extraArgs)
"Preferences", features, paneID, extraArgs);
}
function openAdvancedPreferences(tabID)
{
function openAdvancedPreferences(tabID) {
openPreferences("paneAdvanced", { "advancedTab" : tabID });
}
/**
* Opens the release notes page for this version of the application.
*/
function openReleaseNotes()
{
function openReleaseNotes() {
var relnotesURL = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
.getService(Components.interfaces.nsIURLFormatter)
.formatURLPref("app.releaseNotesURL");
@ -736,23 +732,21 @@ function openReleaseNotes()
* Opens the troubleshooting information (about:support) page for this version
* of the application.
*/
function openTroubleshootingPage()
{
function openTroubleshootingPage() {
openUILinkIn("about:support", "tab");
}
/**
* Opens the feedback page for this version of the application.
*/
function openFeedbackPage()
{
function openFeedbackPage() {
openUILinkIn(Services.prefs.getCharPref("browser.feedback.url"), "tab");
}
function isElementVisible(aElement)
{
if (!aElement)
function isElementVisible(aElement) {
if (!aElement) {
return false;
}
// If aElement or a direct or indirect parent is hidden or collapsed,
// height, width or both will be 0.
@ -794,15 +788,17 @@ function makeURLAbsolute(aBase, aUrl)
*/
function openNewTabWith(aURL, aDocument, aPostData, aEvent,
aAllowThirdPartyFixup, aReferrer, aReferrerPolicy) {
if (aDocument)
if (aDocument) {
urlSecurityCheck(aURL, aDocument.nodePrincipal);
}
// As in openNewWindowWith(), we want to pass the charset of the
// current document over to a new tab.
var originCharset = aDocument && aDocument.characterSet;
if (!originCharset &&
document.documentElement.getAttribute("windowtype") == "navigator:browser")
document.documentElement.getAttribute("windowtype") == "navigator:browser") {
originCharset = window.content.document.characterSet;
}
openLinkIn(aURL, aEvent && aEvent.shiftKey ? "tabshifted" : "tab",
{ charset: originCharset,
@ -815,8 +811,9 @@ function openNewTabWith(aURL, aDocument, aPostData, aEvent,
function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup,
aReferrer, aReferrerPolicy) {
if (aDocument)
if (aDocument) {
urlSecurityCheck(aURL, aDocument.nodePrincipal);
}
// 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
@ -824,8 +821,9 @@ function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup,
// window...
var originCharset = aDocument && aDocument.characterSet;
if (!originCharset &&
document.documentElement.getAttribute("windowtype") == "navigator:browser")
document.documentElement.getAttribute("windowtype") == "navigator:browser") {
originCharset = window.content.document.characterSet;
}
openLinkIn(aURL, "window",
{ charset: originCharset,
@ -847,10 +845,10 @@ function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup,
* Whether this is already a known feed or not, if true only a security
* check will be performed.
*/
function isValidFeed(aLink, aPrincipal, aIsFeed)
{
if (!aLink || !aPrincipal)
function isValidFeed(aLink, aPrincipal, aIsFeed) {
if (!aLink || !aPrincipal) {
return false;
}
var type = aLink.type.toLowerCase().replace(/^\s+|\s*(?:;.*)?$/g, "");
if (!aIsFeed) {
@ -863,9 +861,7 @@ function isValidFeed(aLink, aPrincipal, aIsFeed)
urlSecurityCheck(aLink.href, aPrincipal,
Components.interfaces.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
return type || "application/rss+xml";
}
catch(ex) {
}
} catch(ex) {}
}
return null;

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_WROTE_TO = NS_ERROR_MODULE_NETWORK + 9;
function getPanelBrowser()
{
return document.getElementById("web-panels-browser");
function getPanelBrowser() {
return document.getElementById("web-panels-browser");
}
var panelProgressListener = {
onProgressChange : function (aWebProgress, aRequest,
aCurSelfProgress, aMaxSelfProgress,
aCurTotalProgress, aMaxTotalProgress) {
},
onProgressChange: function (aWebProgress, aRequest,
aCurSelfProgress, aMaxSelfProgress,
aCurTotalProgress, aMaxTotalProgress) {
},
onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus)
{
if (!aRequest)
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;
onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
if (!aRequest) {
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;
}
};
var gLoadFired = false;
function loadWebPanel(aURI) {
var panelBrowser = getPanelBrowser();
if (gLoadFired) {
panelBrowser.webNavigation
.loadURI(aURI, nsIWebNavigation.LOAD_FLAGS_NONE,
null, null, null);
}
panelBrowser.setAttribute("cachedurl", aURI);
var panelBrowser = getPanelBrowser();
if (gLoadFired) {
panelBrowser.webNavigation
.loadURI(aURI, nsIWebNavigation.LOAD_FLAGS_NONE,
null, null, null);
}
panelBrowser.setAttribute("cachedurl", aURI);
}
function load()
{
var panelBrowser = getPanelBrowser();
panelBrowser.webProgress.addProgressListener(panelProgressListener,
Ci.nsIWebProgress.NOTIFY_ALL);
var cachedurl = panelBrowser.getAttribute("cachedurl")
if (cachedurl) {
panelBrowser.webNavigation
.loadURI(cachedurl, nsIWebNavigation.LOAD_FLAGS_NONE, null,
null, null);
}
function load() {
var panelBrowser = getPanelBrowser();
panelBrowser.webProgress.addProgressListener(panelProgressListener,
Ci.nsIWebProgress.NOTIFY_ALL);
var cachedurl = panelBrowser.getAttribute("cachedurl")
if (cachedurl) {
panelBrowser.webNavigation
.loadURI(cachedurl, nsIWebNavigation.LOAD_FLAGS_NONE, null,
null, null);
}
gLoadFired = true;
gLoadFired = true;
}
function unload()
{
getPanelBrowser().webProgress.removeProgressListener(panelProgressListener);
function unload() {
getPanelBrowser().webProgress.removeProgressListener(panelProgressListener);
}
function PanelBrowserStop()
{
getPanelBrowser().webNavigation.stop(nsIWebNavigation.STOP_ALL)
function PanelBrowserStop() {
getPanelBrowser().webNavigation.stop(nsIWebNavigation.STOP_ALL)
}
function PanelBrowserReload()
{
getPanelBrowser().webNavigation
.sessionHistory
.QueryInterface(nsIWebNavigation)
.reload(nsIWebNavigation.LOAD_FLAGS_NONE);
function PanelBrowserReload() {
getPanelBrowser().webNavigation
.sessionHistory
.QueryInterface(nsIWebNavigation)
.reload(nsIWebNavigation.LOAD_FLAGS_NONE);
}

View File

@ -17,22 +17,23 @@ XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
this.DistributionCustomizer = function DistributionCustomizer() {
let dirSvc = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties);
let dirSvc = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties);
let iniFile = dirSvc.get("XREExeF", Ci.nsIFile);
iniFile.leafName = "distribution";
iniFile.append("distribution.ini");
if (iniFile.exists())
if (iniFile.exists()) {
this._iniFile = iniFile;
}
}
DistributionCustomizer.prototype = {
_iniFile: null,
get _ini() {
let ini = Cc["@mozilla.org/xpcom/ini-parser-factory;1"].
getService(Ci.nsIINIParserFactory).
createINIParser(this._iniFile);
let ini = Cc["@mozilla.org/xpcom/ini-parser-factory;1"]
.getService(Ci.nsIINIParserFactory)
.createINIParser(this._iniFile);
this.__defineGetter__("_ini", function() ini);
return this._ini;
},
@ -44,8 +45,8 @@ DistributionCustomizer.prototype = {
},
get _prefSvc() {
let svc = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefService);
let svc = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService);
this.__defineGetter__("_prefSvc", function() svc);
return this._prefSvc;
},
@ -57,8 +58,8 @@ DistributionCustomizer.prototype = {
},
get _ioSvc() {
let svc = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
let svc = Cc["@mozilla.org/network/io-service;1"]
.getService(Ci.nsIIOService);
this.__defineGetter__("_ioSvc", function() svc);
return this._ioSvc;
},
@ -70,8 +71,9 @@ DistributionCustomizer.prototype = {
_parseBookmarksSection:
function(parentId, section) {
let keys = [];
for (let i in enumerate(this._ini.getKeys(section)))
for (let i in enumerate(this._ini.getKeys(section))) {
keys.push(i);
}
keys.sort();
let items = {};
@ -84,11 +86,13 @@ DistributionCustomizer.prototype = {
let [foo, iid, iprop, ilocale] = m;
iid = parseInt(iid);
if (ilocale)
if (ilocale) {
continue;
}
if (!items[iid])
if (!items[iid]) {
items[iid] = {};
}
if (keys.indexOf(keys[i] + "." + this._locale) >= 0) {
items[iid][iprop] = this._ini.getString(section, keys[i] + "." +
this._locale);
@ -96,11 +100,13 @@ DistributionCustomizer.prototype = {
items[iid][iprop] = this._ini.getString(section, keys[i]);
}
if (iprop == "type" && items[iid]["type"] == "default")
if (iprop == "type" && items[iid]["type"] == "default") {
defaultItemId = iid;
}
if (maxItemId < iid)
if (maxItemId < iid) {
maxItemId = iid;
}
} else {
dump("Key did not match: " + keys[i] + "\n");
}
@ -108,70 +114,76 @@ DistributionCustomizer.prototype = {
let prependIndex = 0;
for (let iid = 0; iid <= maxItemId; iid++) {
if (!items[iid])
if (!items[iid]) {
continue;
}
let index = PlacesUtils.bookmarks.DEFAULT_INDEX;
let newId;
switch (items[iid]["type"]) {
case "default":
break;
case "default":
break;
case "folder":
if (iid < defaultItemId)
index = prependIndex++;
case "folder":
if (iid < defaultItemId) {
index = prependIndex++;
}
newId = PlacesUtils.bookmarks.createFolder(parentId,
items[iid]["title"],
index);
newId = PlacesUtils.bookmarks.createFolder(parentId,
items[iid]["title"],
index);
this._parseBookmarksSection(newId, "BookmarksFolder-" +
items[iid]["folderId"]);
this._parseBookmarksSection(newId, "BookmarksFolder-" +
items[iid]["folderId"]);
if (items[iid]["description"])
PlacesUtils.annotations.setItemAnnotation(newId,
"bookmarkProperties/description",
items[iid]["description"], 0,
PlacesUtils.annotations.EXPIRE_NEVER);
if (items[iid]["description"])
PlacesUtils.annotations.setItemAnnotation(newId,
"bookmarkProperties/description",
items[iid]["description"], 0,
PlacesUtils.annotations.EXPIRE_NEVER);
break;
break;
case "separator":
if (iid < defaultItemId)
index = prependIndex++;
PlacesUtils.bookmarks.insertSeparator(parentId, index);
break;
case "separator":
if (iid < defaultItemId) {
index = prependIndex++;
}
PlacesUtils.bookmarks.insertSeparator(parentId, index);
break;
case "livemark":
if (iid < defaultItemId)
index = prependIndex++;
case "livemark":
if (iid < defaultItemId) {
index = prependIndex++;
}
// Don't bother updating the livemark contents on creation.
PlacesUtils.livemarks.addLivemark({ title: items[iid]["title"]
, parentId: parentId
, index: index
, feedURI: this._makeURI(items[iid]["feedLink"])
, siteURI: this._makeURI(items[iid]["siteLink"])
}).then(null, Cu.reportError);
break;
// Don't bother updating the livemark contents on creation.
PlacesUtils.livemarks.addLivemark({ title: items[iid]["title"],
parentId: parentId,
index: index,
feedURI: this._makeURI(items[iid]["feedLink"]),
siteURI: this._makeURI(items[iid]["siteLink"])
}).then(null, Cu.reportError);
break;
case "bookmark":
default:
if (iid < defaultItemId)
index = prependIndex++;
case "bookmark":
// Fallthrough
default:
if (iid < defaultItemId) {
index = prependIndex++;
}
newId = PlacesUtils.bookmarks.insertBookmark(parentId,
this._makeURI(items[iid]["link"]),
index, items[iid]["title"]);
newId = PlacesUtils.bookmarks.insertBookmark(parentId,
this._makeURI(items[iid]["link"]),
index, items[iid]["title"]);
if (items[iid]["description"])
PlacesUtils.annotations.setItemAnnotation(newId,
"bookmarkProperties/description",
items[iid]["description"], 0,
PlacesUtils.annotations.EXPIRE_NEVER);
if (items[iid]["description"]) {
PlacesUtils.annotations.setItemAnnotation(newId, "bookmarkProperties/description",
items[iid]["description"], 0,
PlacesUtils.annotations.EXPIRE_NEVER);
}
break;
break;
}
}
},
@ -179,8 +191,9 @@ DistributionCustomizer.prototype = {
_customizationsApplied: false,
applyCustomizations: function() {
this._customizationsApplied = true;
if (!this._iniFile)
if (!this._iniFile) {
return this._checkCustomizationComplete();
}
// nsPrefService loads very early. Reload prefs so we can set
// distribution defaults during the prefservice:after-app-defaults
@ -192,25 +205,27 @@ DistributionCustomizer.prototype = {
_bookmarksApplied: false,
applyBookmarks: function() {
this._bookmarksApplied = true;
if (!this._iniFile)
if (!this._iniFile) {
return this._checkCustomizationComplete();
}
let sections = enumToObject(this._ini.getSections());
// The global section, and several of its fields, is required
// (we also check here to be consistent with applyPrefDefaults below)
if (!sections["Global"])
if (!sections["Global"]) {
return this._checkCustomizationComplete();
}
let globalPrefs = enumToObject(this._ini.getKeys("Global"));
if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"]))
if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"])) {
return this._checkCustomizationComplete();
}
let bmProcessedPref;
try {
bmProcessedPref = this._ini.getString("Global",
"bookmarks.initialized.pref");
}
catch (e) {
} catch(e) {
bmProcessedPref = "distribution." +
this._ini.getString("Global", "id") + ".bookmarksProcessed";
}
@ -218,12 +233,14 @@ DistributionCustomizer.prototype = {
let bmProcessed = this._prefs.getBoolPref(bmProcessedPref, false);
if (!bmProcessed) {
if (sections["BookmarksMenu"])
if (sections["BookmarksMenu"]) {
this._parseBookmarksSection(PlacesUtils.bookmarksMenuFolderId,
"BookmarksMenu");
if (sections["BookmarksToolbar"])
}
if (sections["BookmarksToolbar"]) {
this._parseBookmarksSection(PlacesUtils.toolbarFolderId,
"BookmarksToolbar");
}
this._prefs.setBoolPref(bmProcessedPref, true);
}
return this._checkCustomizationComplete();
@ -232,17 +249,20 @@ DistributionCustomizer.prototype = {
_prefDefaultsApplied: false,
applyPrefDefaults: function() {
this._prefDefaultsApplied = true;
if (!this._iniFile)
if (!this._iniFile) {
return this._checkCustomizationComplete();
}
let sections = enumToObject(this._ini.getSections());
// The global section, and several of its fields, is required
if (!sections["Global"])
if (!sections["Global"]) {
return this._checkCustomizationComplete();
}
let globalPrefs = enumToObject(this._ini.getKeys("Global"));
if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"]))
if (!(globalPrefs["id"] && globalPrefs["version"] && globalPrefs["about"])) {
return this._checkCustomizationComplete();
}
let defaults = this._prefSvc.getDefaultBranch(null);
@ -253,8 +273,8 @@ DistributionCustomizer.prototype = {
defaults.setCharPref("distribution.version",
this._ini.getString("Global", "version"));
let partnerAbout = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
let partnerAbout = Cc["@mozilla.org/supports-string;1"]
.createInstance(Ci.nsISupportsString);
try {
if (globalPrefs["about." + this._locale]) {
partnerAbout.data = this._ini.getString("Global", "about." + this._locale);
@ -263,7 +283,7 @@ DistributionCustomizer.prototype = {
}
defaults.setComplexValue("distribution.about",
Ci.nsISupportsString, partnerAbout);
} catch (e) {
} catch(e) {
/* ignore bad prefs due to bug 895473 and move on */
Cu.reportError(e);
}
@ -273,20 +293,22 @@ DistributionCustomizer.prototype = {
try {
let value = eval(this._ini.getString("Preferences", key));
switch (typeof value) {
case "boolean":
defaults.setBoolPref(key, value);
break;
case "number":
defaults.setIntPref(key, value);
break;
case "string":
defaults.setCharPref(key, value);
break;
case "undefined":
defaults.setCharPref(key, value);
break;
case "boolean":
defaults.setBoolPref(key, value);
break;
case "number":
defaults.setIntPref(key, value);
break;
case "string":
defaults.setCharPref(key, value);
break;
case "undefined":
defaults.setCharPref(key, value);
break;
}
} catch (e) { /* ignore bad prefs and move on */ }
} catch(e) {
/* ignore bad prefs and move on */
}
}
}
@ -294,8 +316,8 @@ DistributionCustomizer.prototype = {
// always get set as a string) to keep the INI format consistent:
// string prefs always need to be in quotes
let localizedStr = Cc["@mozilla.org/pref-localizedstring;1"].
createInstance(Ci.nsIPrefLocalizedString);
let localizedStr = Cc["@mozilla.org/pref-localizedstring;1"]
.createInstance(Ci.nsIPrefLocalizedString);
if (sections["LocalizablePreferences"]) {
for (let key in enumerate(this._ini.getKeys("LocalizablePreferences"))) {
@ -304,7 +326,9 @@ DistributionCustomizer.prototype = {
value = value.replace("%LOCALE%", this._locale, "g");
localizedStr.data = "data:text/plain," + key + "=" + value;
defaults.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr);
} catch (e) { /* ignore bad prefs and move on */ }
} catch(e) {
/* ignore bad prefs and move on */
}
}
}
@ -314,7 +338,9 @@ DistributionCustomizer.prototype = {
let value = eval(this._ini.getString("LocalizablePreferences-" + this._locale, key));
localizedStr.data = "data:text/plain," + key + "=" + value;
defaults.setComplexValue(key, Ci.nsIPrefLocalizedString, localizedStr);
} catch (e) { /* ignore bad prefs and move on */ }
} catch(e) {
/* ignore bad prefs and move on */
}
}
}
@ -325,21 +351,23 @@ DistributionCustomizer.prototype = {
let prefDefaultsApplied = this._prefDefaultsApplied || !this._iniFile;
if (this._customizationsApplied && this._bookmarksApplied &&
prefDefaultsApplied) {
let os = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
let os = Cc["@mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
os.notifyObservers(null, DISTRIBUTION_CUSTOMIZATION_COMPLETE_TOPIC, null);
}
}
};
function enumerate(UTF8Enumerator) {
while (UTF8Enumerator.hasMore())
while (UTF8Enumerator.hasMore()) {
yield UTF8Enumerator.getNext();
}
}
function enumToObject(UTF8Enumerator) {
let ret = {};
for (let i in enumerate(UTF8Enumerator))
for (let i in enumerate(UTF8Enumerator)) {
ret[i] = 1;
}
return ret;
}

View File

@ -88,15 +88,17 @@ AboutRedirector.prototype = {
getURIFlags: function(aURI) {
let name = this._getModuleName(aURI);
if (!(name in this._redirMap))
if (!(name in this._redirMap)) {
throw Cr.NS_ERROR_ILLEGAL_VALUE;
}
return this._redirMap[name].flags;
},
newChannel: function(aURI, aLoadInfo) {
let name = this._getModuleName(aURI);
if (!(name in this._redirMap))
if (!(name in this._redirMap)) {
throw Cr.NS_ERROR_ILLEGAL_VALUE;
}
let newURI = Services.io.newURI(this._redirMap[name].url, null, null);
let channel = Services.io.newChannelFromURIWithLoadInfo(newURI, aLoadInfo);

View File

@ -41,11 +41,12 @@ const NS_ERROR_WONT_HANDLE_CONTENT = 0x805d0001;
const NS_ERROR_ABORT = Components.results.NS_ERROR_ABORT;
const URI_INHERITS_SECURITY_CONTEXT = Components.interfaces.nsIHttpProtocolHandler
.URI_INHERITS_SECURITY_CONTEXT;
.URI_INHERITS_SECURITY_CONTEXT;
function shouldLoadURI(aURI) {
if (aURI && !aURI.schemeIs("chrome"))
if (aURI && !aURI.schemeIs("chrome")) {
return true;
}
dump("*** Preventing external load of chrome: URI into browser window\n");
dump(" Use -chrome <uri> instead\n");
@ -63,10 +64,10 @@ function resolveURIInternal(aCmdLine, aArgument) {
}
try {
if (uri.file.exists())
if (uri.file.exists()) {
return uri;
}
catch (e) {
}
} catch(e) {
Components.utils.reportError(e);
}
@ -75,8 +76,7 @@ function resolveURIInternal(aCmdLine, aArgument) {
try {
uri = urifixup.createFixupURI(aArgument, 0);
}
catch (e) {
} catch(e) {
Components.utils.reportError(e);
}
@ -102,8 +102,9 @@ const OVERRIDE_NEW_BUILD_ID = 3;
function needHomepageOverride(prefb) {
var savedmstone = prefb.getCharPref("browser.startup.homepage_override.mstone", "");
if (savedmstone == "ignore")
if (savedmstone == "ignore") {
return OVERRIDE_NONE;
}
var mstone = Services.appinfo.platformVersion;
@ -116,8 +117,9 @@ function needHomepageOverride(prefb) {
// agreement if the platform's installer had already shown one. Now with
// about:rights we've removed the EULA stuff and default pref, but we need
// a way to make existing profiles retain the default that we removed.
if (savedmstone)
if (savedmstone) {
prefb.setBoolPref("browser.rights.3.shown", true);
}
prefb.setCharPref("browser.startup.homepage_override.mstone", mstone);
prefb.setCharPref("browser.startup.homepage_override.buildID", buildID);
@ -146,7 +148,7 @@ function getPostUpdateOverridePage(defaultOverridePage) {
// If the updates.xml file is deleted then getUpdateAt will throw.
var update = um.getUpdateAt(0)
.QueryInterface(Components.interfaces.nsIPropertyBag);
} catch (e) {
} catch(e) {
// This should never happen.
Components.utils.reportError("Unable to find update: " + e);
return defaultOverridePage;
@ -155,13 +157,15 @@ function getPostUpdateOverridePage(defaultOverridePage) {
let actions = update.getProperty("actions");
// When the update doesn't specify actions fallback to the original behavior
// of displaying the default override page.
if (!actions)
if (!actions) {
return defaultOverridePage;
}
// The existence of silent or the non-existence of showURL in the actions both
// mean that an override page should not be displayed.
if (actions.indexOf("silent") != -1 || actions.indexOf("showURL") == -1)
if (actions.indexOf("silent") != -1 || actions.indexOf("showURL") == -1) {
return "";
}
return update.getProperty("openURL") || defaultOverridePage;
}
@ -187,19 +191,22 @@ function openWindow(parent, url, target, features, args, noExternalArgs) {
// Pass an array to avoid the browser "|"-splitting behavior.
var argArray = Components.classes["@mozilla.org/supports-array;1"]
.createInstance(Components.interfaces.nsISupportsArray);
.createInstance(Components.interfaces.nsISupportsArray);
// add args to the arguments array
var stringArgs = null;
if (args instanceof Array) // array
if (args instanceof Array) {
// array
stringArgs = args;
else if (args) // string
} else if (args) {
// string
stringArgs = [args];
}
if (stringArgs) {
// put the URIs into argArray
var uriArray = Components.classes["@mozilla.org/supports-array;1"]
.createInstance(Components.interfaces.nsISupportsArray);
.createInstance(Components.interfaces.nsISupportsArray);
stringArgs.forEach(function(uri) {
var sstring = Components.classes["@mozilla.org/supports-string;1"]
.createInstance(nsISupportsString);
@ -272,22 +279,22 @@ function doSearch(searchTerm, cmdLine) {
sa);
}
function nsBrowserContentHandler() {
}
function nsBrowserContentHandler() {}
nsBrowserContentHandler.prototype = {
classID: Components.ID("{5d0ce354-df01-421a-83fb-7ead0990c24e}"),
_xpcom_factory: {
createInstance: function(outer, iid) {
if (outer)
if (outer) {
throw Components.results.NS_ERROR_NO_AGGREGATION;
}
return gBrowserContentHandler.QueryInterface(iid);
}
},
/* helper functions */
mChromeURL : null,
mChromeURL: null,
get chromeURL() {
if (this.mChromeURL) {
@ -302,13 +309,13 @@ nsBrowserContentHandler.prototype = {
},
/* nsISupports */
QueryInterface : XPCOMUtils.generateQI([nsICommandLineHandler,
QueryInterface: XPCOMUtils.generateQI([ nsICommandLineHandler,
nsIBrowserHandler,
nsIContentHandler,
nsICommandLineValidator]),
nsICommandLineValidator ]),
/* nsICommandLineHandler */
handle : function(cmdLine) {
handle: function(cmdLine) {
if (cmdLine.handleFlag("browser", false)) {
// Passing defaultArgs, so use NO_EXTERNAL_URIS
openWindow(null, this.chromeURL, "_blank",
@ -319,8 +326,7 @@ nsBrowserContentHandler.prototype = {
try {
var remoteCommand = cmdLine.handleFlagWithParam("remote", true);
}
catch (e) {
} catch(e) {
throw NS_ERROR_ABORT;
}
@ -332,63 +338,63 @@ nsBrowserContentHandler.prototype = {
remoteVerb = a[1].toLowerCase();
var remoteParams = [];
var sepIndex = a[2].lastIndexOf(",");
if (sepIndex == -1)
if (sepIndex == -1) {
remoteParams[0] = a[2];
else {
} else {
remoteParams[0] = a[2].substring(0, sepIndex);
remoteParams[1] = a[2].substring(sepIndex + 1);
}
}
switch (remoteVerb) {
case "openurl":
case "openfile":
// openURL(<url>)
// openURL(<url>,new-window)
// openURL(<url>,new-tab)
// First param is the URL, second param (if present) is the "target"
// (tab, window)
var url = remoteParams[0];
var target = nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW;
if (remoteParams[1]) {
var targetParam = remoteParams[1].toLowerCase()
.replace(/^\s*|\s*$/g, "");
if (targetParam == "new-tab")
target = nsIBrowserDOMWindow.OPEN_NEWTAB;
else if (targetParam == "new-window")
target = nsIBrowserDOMWindow.OPEN_NEWWINDOW;
else {
// The "target" param isn't one of our supported values, so
// assume it's part of a URL that contains commas.
url += "," + remoteParams[1];
case "openurl":
case "openfile":
// openURL(<url>)
// openURL(<url>,new-window)
// openURL(<url>,new-tab)
// First param is the URL, second param (if present) is the "target"
// (tab, window)
var url = remoteParams[0];
var target = nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW;
if (remoteParams[1]) {
var targetParam = remoteParams[1].toLowerCase()
.replace(/^\s*|\s*$/g, "");
if (targetParam == "new-tab") {
target = nsIBrowserDOMWindow.OPEN_NEWTAB;
} else if (targetParam == "new-window") {
target = nsIBrowserDOMWindow.OPEN_NEWWINDOW;
} else {
// The "target" param isn't one of our supported values, so
// assume it's part of a URL that contains commas.
url += "," + remoteParams[1];
}
}
}
var uri = resolveURIInternal(cmdLine, url);
handURIToExistingBrowser(uri, target, cmdLine);
break;
var uri = resolveURIInternal(cmdLine, url);
handURIToExistingBrowser(uri, target, cmdLine);
break;
case "xfedocommand":
// xfeDoCommand(openBrowser)
if (remoteParams[0].toLowerCase() != "openbrowser")
throw NS_ERROR_ABORT;
case "xfedocommand":
// xfeDoCommand(openBrowser)
if (remoteParams[0].toLowerCase() != "openbrowser") {
throw NS_ERROR_ABORT;
}
// Passing defaultArgs, so use NO_EXTERNAL_URIS
openWindow(null, this.chromeURL, "_blank",
"chrome,dialog=no,all" + this.getFeatures(cmdLine),
this.defaultArgs, NO_EXTERNAL_URIS);
break;
// Passing defaultArgs, so use NO_EXTERNAL_URIS
openWindow(null, this.chromeURL, "_blank",
"chrome,dialog=no,all" + this.getFeatures(cmdLine),
this.defaultArgs, NO_EXTERNAL_URIS);
break;
default:
// Somebody sent us a remote command we don't know how to process:
// just abort.
throw "Unknown remote command.";
default:
// Somebody sent us a remote command we don't know how to process:
// just abort.
throw "Unknown remote command.";
}
cmdLine.preventDefault = true;
}
catch (e) {
} catch (e) {
Components.utils.reportError(e);
// If we had a -remote flag but failed to process it, throw
// NS_ERROR_ABORT so that the xremote code knows to return a failure
@ -401,15 +407,15 @@ nsBrowserContentHandler.prototype = {
try {
while ((uriparam = cmdLine.handleFlagWithParam("new-window", false))) {
var uri = resolveURIInternal(cmdLine, uriparam);
if (!shouldLoadURI(uri))
if (!shouldLoadURI(uri)) {
continue;
}
openWindow(null, this.chromeURL, "_blank",
"chrome,dialog=no,all" + this.getFeatures(cmdLine),
uri.spec);
cmdLine.preventDefault = true;
}
}
catch (e) {
} catch(e) {
Components.utils.reportError(e);
}
@ -419,8 +425,7 @@ nsBrowserContentHandler.prototype = {
handURIToExistingBrowser(uri, nsIBrowserDOMWindow.OPEN_NEWTAB, cmdLine);
cmdLine.preventDefault = true;
}
}
catch (e) {
} catch(e) {
Components.utils.reportError(e);
}
@ -431,27 +436,29 @@ nsBrowserContentHandler.prototype = {
if (chromeParam == "chrome://browser/content/pref/pref.xul") {
openPreferences();
cmdLine.preventDefault = true;
} else try {
// only load URIs which do not inherit chrome privs
var features = "chrome,dialog=no,all" + this.getFeatures(cmdLine);
var uri = resolveURIInternal(cmdLine, chromeParam);
var netutil = Components.classes["@mozilla.org/network/util;1"]
.getService(nsINetUtil);
if (!netutil.URIChainHasFlags(uri, URI_INHERITS_SECURITY_CONTEXT)) {
openWindow(null, uri.spec, "_blank", features);
cmdLine.preventDefault = true;
} else {
try {
// only load URIs which do not inherit chrome privs
var features = "chrome,dialog=no,all" + this.getFeatures(cmdLine);
var uri = resolveURIInternal(cmdLine, chromeParam);
var netutil = Components.classes["@mozilla.org/network/util;1"]
.getService(nsINetUtil);
if (!netutil.URIChainHasFlags(uri, URI_INHERITS_SECURITY_CONTEXT)) {
openWindow(null, uri.spec, "_blank", features);
cmdLine.preventDefault = true;
}
} catch(e) {
Components.utils.reportError(e);
}
}
catch (e) {
Components.utils.reportError(e);
}
}
if (cmdLine.handleFlag("preferences", false)) {
openPreferences();
cmdLine.preventDefault = true;
}
if (cmdLine.handleFlag("silent", false))
if (cmdLine.handleFlag("silent", false)) {
cmdLine.preventDefault = true;
}
try {
var privateWindowParam = cmdLine.handleFlagWithParam("private-window", false);
@ -460,15 +467,15 @@ nsBrowserContentHandler.prototype = {
handURIToExistingBrowser(resolvedURI, nsIBrowserDOMWindow.OPEN_NEWTAB, cmdLine, true);
cmdLine.preventDefault = true;
}
} catch (e) {
} catch(e) {
if (e.result != Components.results.NS_ERROR_INVALID_ARG) {
throw e;
}
// NS_ERROR_INVALID_ARG is thrown when flag exists, but has no param.
if (cmdLine.handleFlag("private-window", false)) {
openWindow(null, this.chromeURL, "_blank",
"chrome,dialog=no,private,all" + this.getFeatures(cmdLine),
"about:privatebrowsing");
"chrome,dialog=no,private,all" + this.getFeatures(cmdLine),
"about:privatebrowsing");
cmdLine.preventDefault = true;
}
}
@ -512,16 +519,12 @@ nsBrowserContentHandler.prototype = {
#endif
},
helpInfo : " --browser Open a browser window.\n" +
" --new-window <url> Open <url> in a new window.\n" +
" --new-tab <url> Open <url> in a new tab.\n" +
" --private-window <url> Open <url> in a new private window.\n" +
#ifdef XP_WIN
" --preferences Open Options dialog.\n" +
#else
" --preferences Open Preferences dialog.\n" +
#endif
" --search <term> Search <term> with your default search engine.\n",
helpInfo: " --browser Open a browser window.\n" +
" --new-window <url> Open <url> in a new window.\n" +
" --new-tab <url> Open <url> in a new tab.\n" +
" --private-window <url> Open <url> in a new private window.\n" +
" --preferences Open Preferences dialog.\n" +
" --search <term> Search <term> with your default search engine.\n",
/* nsIBrowserHandler */
@ -559,31 +562,35 @@ nsBrowserContentHandler.prototype = {
.getService(Components.interfaces.nsISessionStartup);
haveUpdateSession = ss.doRestore();
overridePage = Services.urlFormatter.formatURLPref("startup.homepage_override_url");
if (prefb.prefHasUserValue("app.update.postupdate"))
if (prefb.prefHasUserValue("app.update.postupdate")) {
overridePage = getPostUpdateOverridePage(overridePage);
}
overridePage = overridePage.replace("%OLD_VERSION%", old_mstone);
break;
}
}
} catch (ex) {}
} catch(ex) {}
// formatURLPref might return "about:blank" if getting the pref fails
if (overridePage == "about:blank")
if (overridePage == "about:blank") {
overridePage = "";
}
var startPage = "";
try {
var choice = prefb.getIntPref("browser.startup.page");
if (choice == 1 || choice == 3)
if (choice == 1 || choice == 3) {
startPage = this.startPage;
} catch (e) {
}
} catch(e) {
Components.utils.reportError(e);
}
// Only show the startPage if we're not restoring an update session.
if (overridePage && startPage && !haveUpdateSession)
if (overridePage && startPage && !haveUpdateSession) {
return overridePage + "|" + startPage;
}
return overridePage || startPage || "about:logopage";
},
@ -599,9 +606,9 @@ nsBrowserContentHandler.prototype = {
return uri;
},
mFeatures : null,
mFeatures: null,
getFeatures : function(cmdLine) {
getFeatures: function(cmdLine) {
if (this.mFeatures === null) {
this.mFeatures = "";
@ -609,13 +616,13 @@ nsBrowserContentHandler.prototype = {
var width = cmdLine.handleFlagWithParam("width", false);
var height = cmdLine.handleFlagWithParam("height", false);
if (width)
if (width) {
this.mFeatures += ",width=" + width;
if (height)
}
if (height) {
this.mFeatures += ",height=" + height;
}
catch (e) {
}
}
} catch(e) {}
// The global PB Service consumes this flag, so only eat it in per-window
// PB builds.
@ -629,25 +636,24 @@ nsBrowserContentHandler.prototype = {
/* nsIContentHandler */
handleContent : function(contentType, context, request) {
handleContent: function(contentType, context, request) {
try {
var webNavInfo = Components.classes["@mozilla.org/webnavigation-info;1"]
.getService(nsIWebNavigationInfo);
if (!webNavInfo.isTypeSupported(contentType, null)) {
throw NS_ERROR_WONT_HANDLE_CONTENT;
}
} catch (e) {
} catch(e) {
throw NS_ERROR_WONT_HANDLE_CONTENT;
}
request.QueryInterface(nsIChannel);
handURIToExistingBrowser(request.URI,
nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW, null);
handURIToExistingBrowser(request.URI, nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW, null);
request.cancel(NS_BINDING_ABORTED);
},
/* nsICommandLineValidator */
validate : function(cmdLine) {
validate: function(cmdLine) {
// Other handlers may use osint so only handle the osint flag if the url
// flag is also present and the command line is valid.
var osintFlagIdx = cmdLine.findFlag("osint", false);
@ -655,18 +661,20 @@ nsBrowserContentHandler.prototype = {
if (urlFlagIdx > -1 && (osintFlagIdx > -1 ||
cmdLine.state == nsICommandLine.STATE_REMOTE_EXPLICIT)) {
var urlParam = cmdLine.getArgument(urlFlagIdx + 1);
if (cmdLine.length != urlFlagIdx + 2 || /firefoxurl:/.test(urlParam))
if (cmdLine.length != urlFlagIdx + 2 || /firefoxurl:/.test(urlParam)) {
throw NS_ERROR_ABORT;
}
cmdLine.handleFlag("osint", false)
}
},
};
var gBrowserContentHandler = new nsBrowserContentHandler();
function handURIToExistingBrowser(uri, location, cmdLine, forcePrivate)
{
if (!shouldLoadURI(uri))
function handURIToExistingBrowser(uri, location, cmdLine, forcePrivate) {
if (!shouldLoadURI(uri)) {
return;
}
// Unless using a private window is forced, open external links in private
// windows only if we're in perma-private mode.
@ -692,14 +700,12 @@ function handURIToExistingBrowser(uri, location, cmdLine, forcePrivate)
nsIBrowserDOMWindow.OPEN_EXTERNAL);
}
function nsDefaultCommandLineHandler() {
}
function nsDefaultCommandLineHandler() {}
nsDefaultCommandLineHandler.prototype = {
classID: Components.ID("{47cd0651-b1be-4a0f-b5c4-10e5a573ef71}"),
/* nsISupports */
QueryInterface : function(iid) {
QueryInterface: function(iid) {
if (!iid.equals(nsISupports) &&
!iid.equals(nsICommandLineHandler))
throw Components.results.NS_ERROR_NO_INTERFACE;
@ -712,7 +718,7 @@ nsDefaultCommandLineHandler.prototype = {
#endif
/* nsICommandLineHandler */
handle : function(cmdLine) {
handle: function(cmdLine) {
var urilist = [];
#ifdef XP_WIN
@ -729,9 +735,8 @@ nsDefaultCommandLineHandler.prototype = {
.getService(Components.interfaces.nsIProperties);
var dir = fl.get("ProfD", Components.interfaces.nsILocalFile);
this._haveProfile = true;
}
catch (e) {
while ((ar = cmdLine.handleFlagWithParam("url", false))) { }
} catch(e) {
while ((ar = cmdLine.handleFlagWithParam("url", false))) {}
cmdLine.preventDefault = true;
}
}
@ -743,8 +748,7 @@ nsDefaultCommandLineHandler.prototype = {
var uri = resolveURIInternal(cmdLine, ar);
urilist.push(uri);
}
}
catch (e) {
} catch(e) {
Components.utils.reportError(e);
}
@ -760,8 +764,7 @@ nsDefaultCommandLineHandler.prototype = {
} else {
try {
urilist.push(resolveURIInternal(cmdLine, curarg));
}
catch (e) {
} catch(e) {
Components.utils.reportError("Error opening URI '" + curarg + "' from the command line: " + e + "\n");
}
}
@ -775,9 +778,7 @@ nsDefaultCommandLineHandler.prototype = {
try {
handURIToExistingBrowser(urilist[0], nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW, cmdLine);
return;
}
catch (e) {
}
} catch(e) {}
}
var URLlist = urilist.filter(shouldLoadURI).map(function(u) u.spec);
@ -787,8 +788,7 @@ nsDefaultCommandLineHandler.prototype = {
URLlist);
}
}
else if (!cmdLine.preventDefault) {
} else if (!cmdLine.preventDefault) {
// Passing defaultArgs, so use NO_EXTERNAL_URIS
openWindow(null, gBrowserContentHandler.chromeURL, "_blank",
"chrome,dialog=no,all" + gBrowserContentHandler.getFeatures(cmdLine),

View File

@ -69,10 +69,12 @@ const BOOKMARKS_BACKUP_MAX_BACKUPS = 10;
const BrowserGlueServiceFactory = {
_instance: null,
createInstance: function(outer, iid) {
if (outer != null)
if (outer != null) {
throw Components.results.NS_ERROR_NO_AGGREGATION;
}
return this._instance == null ?
this._instance = new BrowserGlue() : this._instance;
this._instance = new BrowserGlue() :
this._instance;
}
};
@ -114,8 +116,9 @@ BrowserGlue.prototype = {
_migrationImportsDefaultBookmarks: false,
_setPrefToSaveSession: function(aForce) {
if (!this._saveSession && !aForce)
if (!this._saveSession && !aForce) {
return;
}
Services.prefs.setBoolPref("browser.sessionstore.resume_session_once", true);
@ -131,8 +134,9 @@ BrowserGlue.prototype = {
if (Services.prefs.prefHasUserValue("services.sync.autoconnectDelay")) {
let prefDelay = Services.prefs.getIntPref("services.sync.autoconnectDelay");
if (prefDelay > 0)
if (prefDelay > 0) {
return;
}
}
// delays are in seconds
@ -184,7 +188,7 @@ BrowserGlue.prototype = {
let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].
getService(Ci.nsIAppStartup);
appStartup.trackStartupCrashEnd();
} catch (e) {
} catch(e) {
Cu.reportError("Could not end startup crash tracking in quit-application-granted: " + e);
}
DateTimePickerHelper.uninit();
@ -213,8 +217,9 @@ BrowserGlue.prototype = {
subject.data = true;
break;
case "places-init-complete":
if (!this._migrationImportsDefaultBookmarks)
if (!this._migrationImportsDefaultBookmarks) {
this._initPlaces(false);
}
Services.obs.removeObserver(this, "places-init-complete");
this._isPlacesInitObserver = false;
@ -249,18 +254,16 @@ BrowserGlue.prototype = {
break;
case "browser-glue-test": // used by tests
if (data == "post-update-notification") {
if (Services.prefs.prefHasUserValue("app.update.postupdate"))
if (Services.prefs.prefHasUserValue("app.update.postupdate")) {
this._showUpdateNotification();
}
else if (data == "force-ui-migration") {
}
} else if (data == "force-ui-migration") {
this._migrateUI();
}
else if (data == "force-distribution-customization") {
} else if (data == "force-distribution-customization") {
this._distributionCustomizer.applyPrefDefaults();
this._distributionCustomizer.applyCustomizations();
// To apply distribution bookmarks use "places-init-complete".
}
else if (data == "force-places-init") {
} else if (data == "force-places-init") {
this._initPlaces(false);
}
break;
@ -296,16 +299,19 @@ BrowserGlue.prototype = {
// No need to initialize the search service, since it's guaranteed to be
// initialized already when this notification fires.
let ss = Services.search;
if (ss.currentEngine.name == ss.defaultEngine.name)
if (ss.currentEngine.name == ss.defaultEngine.name) {
return;
if (data == "engine-current")
}
if (data == "engine-current") {
ss.defaultEngine = ss.currentEngine;
else
} else {
ss.currentEngine = ss.defaultEngine;
}
break;
case "browser-search-service":
if (data != "init-complete")
if (data != "init-complete") {
return;
}
Services.obs.removeObserver(this, "browser-search-service");
this._syncSearchEngines();
break;
@ -374,21 +380,26 @@ BrowserGlue.prototype = {
os.removeObserver(this, "weave:engine:clients:display-uri");
#endif
os.removeObserver(this, "session-save");
if (this._isIdleObserver)
if (this._isIdleObserver) {
this._idleService.removeIdleObserver(this, BOOKMARKS_BACKUP_IDLE_TIME);
if (this._isPlacesInitObserver)
}
if (this._isPlacesInitObserver) {
os.removeObserver(this, "places-init-complete");
if (this._isPlacesLockedObserver)
}
if (this._isPlacesLockedObserver) {
os.removeObserver(this, "places-database-locked");
if (this._isPlacesShutdownObserver)
}
if (this._isPlacesShutdownObserver) {
os.removeObserver(this, "places-shutdown");
}
os.removeObserver(this, "handle-xul-text-link");
os.removeObserver(this, "profile-before-change");
os.removeObserver(this, "browser-search-engine-modified");
try {
os.removeObserver(this, "browser-search-service");
} catch(ex) {
// may have already been removed by the observer
} catch (ex) {}
}
},
_onAppDefaults: function() {
@ -441,9 +452,12 @@ BrowserGlue.prototype = {
let cookies;
try {
cookies = aHttpChannel.getRequestHeader("Cookie");
} catch (e) { /* no cookie sent */ }
if (cookies && cookies.indexOf("MoodleSession") > -1)
} catch(e) {
// no cookie sent
}
if (cookies && cookies.indexOf("MoodleSession") > -1) {
return aOriginalUA.replace(/Goanna\/[^ ]*/, "Goanna/20100101");
}
return null;
});
}
@ -451,8 +465,9 @@ BrowserGlue.prototype = {
_trackSlowStartup: function() {
if (Services.startup.interrupted ||
Services.prefs.getBoolPref("browser.slowStartup.notificationDisabled"))
Services.prefs.getBoolPref("browser.slowStartup.notificationDisabled")) {
return;
}
let currentTime = Date.now() - Services.startup.getStartupInfo().process;
let averageTime = 0;
@ -460,13 +475,14 @@ BrowserGlue.prototype = {
try {
averageTime = Services.prefs.getIntPref("browser.slowStartup.averageTime");
samples = Services.prefs.getIntPref("browser.slowStartup.samples");
} catch (e) { }
} catch(e) {}
averageTime = (averageTime * samples + currentTime) / ++samples;
if (samples >= Services.prefs.getIntPref("browser.slowStartup.maxSamples")) {
if (averageTime > Services.prefs.getIntPref("browser.slowStartup.timeThreshold"))
if (averageTime > Services.prefs.getIntPref("browser.slowStartup.timeThreshold")) {
this._showSlowStartupNotification();
}
averageTime = 0;
samples = 0;
}
@ -477,8 +493,9 @@ BrowserGlue.prototype = {
_showSlowStartupNotification: function() {
let win = this.getMostRecentBrowserWindow();
if (!win)
if (!win) {
return;
}
let productName = gBrandBundle.GetStringFromName("brandFullName");
let message = win.gNavigatorBundle.getFormattedString("slowStartup.message", [productName]);
@ -509,7 +526,7 @@ BrowserGlue.prototype = {
// the first browser window has finished initializing
_onFirstWindowLoaded: function() {
#ifdef XP_WIN
// For windows seven, initialize the jump list module.
// For Windows, initialize the jump list module.
const WINTASKBAR_CONTRACTID = "@mozilla.org/windows-taskbar;1";
if (WINTASKBAR_CONTRACTID in Cc &&
Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available) {
@ -543,8 +560,9 @@ BrowserGlue.prototype = {
// All initial windows have opened.
_onWindowsRestored: function() {
// Show update notification, if needed.
if (Services.prefs.prefHasUserValue("app.update.postupdate"))
if (Services.prefs.prefHasUserValue("app.update.postupdate")) {
this._showUpdateNotification();
}
// Load the "more info" page for a locked places.sqlite
// This property is set earlier by places-database-locked topic.
@ -560,8 +578,9 @@ BrowserGlue.prototype = {
AddonManager.getAddonsByIDs(changedIDs, function(aAddons) {
aAddons.forEach(function(aAddon) {
// If the add-on isn't user disabled or can't be enabled then skip it.
if (!aAddon.userDisabled || !(aAddon.permissions & AddonManager.PERM_CAN_ENABLE))
if (!aAddon.userDisabled || !(aAddon.permissions & AddonManager.PERM_CAN_ENABLE)) {
return;
}
win.openUILinkIn("about:newaddon?id=" + aAddon.id, "tab");
})
@ -586,15 +605,16 @@ BrowserGlue.prototype = {
getService(Ci.nsISessionStartup);
willRecoverSession =
(ss.sessionType == Ci.nsISessionStartup.RECOVER_SESSION);
} catch(ex) {
// never mind; suppose SessionStore is broken
}
catch (ex) { /* never mind; suppose SessionStore is broken */ }
// startup check, check all assoc
let isDefault = false;
let isDefaultError = false;
try {
isDefault = ShellService.isDefaultBrowser(true, false);
} catch (ex) {
} catch(ex) {
isDefaultError = true;
}
@ -636,7 +656,7 @@ BrowserGlue.prototype = {
// Windows 8 is version 6.2.
let version = Services.sysinfo.getProperty("version");
claimAllTypes = (parseFloat(version) < 6.2);
} catch (ex) { }
} catch (ex) {}
#endif
ShellService.setDefaultBrowser(claimAllTypes, false);
}
@ -648,8 +668,9 @@ BrowserGlue.prototype = {
_onQuitRequest: function(aCancelQuit, aQuitType) {
// If user has already dismissed quit request, then do nothing
if ((aCancelQuit instanceof Ci.nsISupportsPRBool) && aCancelQuit.data)
if ((aCancelQuit instanceof Ci.nsISupportsPRBool) && aCancelQuit.data) {
return;
}
// There are several cases where we won't show a dialog here:
// 1. There is only 1 tab open in 1 window
@ -669,8 +690,9 @@ BrowserGlue.prototype = {
// "the last window is closing but we're not quitting (a non-browser window is open)"
// and also "we're quitting by closing the last window".
if (aQuitType == "restart")
if (aQuitType == "restart") {
return;
}
var windowcount = 0;
var pagecount = 0;
@ -680,17 +702,20 @@ BrowserGlue.prototype = {
windowcount++;
var browser = browserEnum.getNext();
if (!PrivateBrowsingUtils.isWindowPrivate(browser))
if (!PrivateBrowsingUtils.isWindowPrivate(browser)) {
allWindowsPrivate = false;
}
var tabbrowser = browser.document.getElementById("content");
if (tabbrowser)
if (tabbrowser) {
pagecount += tabbrowser.browsers.length - tabbrowser._numPinnedTabs;
}
}
this._saveSession = false;
if (!aQuitType)
if (!aQuitType) {
aQuitType = "quit";
}
// browser.warnOnQuit is a hidden global boolean to override all quit prompts
// browser.showQuitWarning specifically covers quitting
@ -698,8 +723,9 @@ BrowserGlue.prototype = {
var sessionWillBeRestored = Services.prefs.getIntPref("browser.startup.page") == 3 ||
Services.prefs.getBoolPref("browser.sessionstore.resume_session_once");
if (sessionWillBeRestored || !Services.prefs.getBoolPref("browser.warnOnQuit"))
if (sessionWillBeRestored || !Services.prefs.getBoolPref("browser.warnOnQuit")) {
return;
}
let win = Services.wm.getMostRecentWindow("navigator:browser");
@ -758,21 +784,22 @@ BrowserGlue.prototype = {
}
switch (choice) {
case 2: // Quit
if (neverAsk.value)
Services.prefs.setBoolPref("browser.showQuitWarning", false);
break;
case 1: // Cancel
aCancelQuit.QueryInterface(Ci.nsISupportsPRBool);
aCancelQuit.data = true;
break;
case 0: // Save & Quit
this._saveSession = true;
if (neverAsk.value) {
// always save state when shutting down
Services.prefs.setIntPref("browser.startup.page", 3);
}
break;
case 2: // Quit
if (neverAsk.value) {
Services.prefs.setBoolPref("browser.showQuitWarning", false);
}
break;
case 1: // Cancel
aCancelQuit.QueryInterface(Ci.nsISupportsPRBool);
aCancelQuit.data = true;
break;
case 0: // Save & Quit
this._saveSession = true;
if (neverAsk.value) {
// always save state when shutting down
Services.prefs.setIntPref("browser.startup.page", 3);
}
break;
}
},
@ -784,32 +811,33 @@ BrowserGlue.prototype = {
try {
// If the updates.xml file is deleted then getUpdateAt will throw.
var update = um.getUpdateAt(0).QueryInterface(Ci.nsIPropertyBag);
}
catch (e) {
} catch(e) {
// This should never happen.
Cu.reportError("Unable to find update: " + e);
return;
}
var actions = update.getProperty("actions");
if (!actions || actions.indexOf("silent") != -1)
if (!actions || actions.indexOf("silent") != -1) {
return;
}
var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
getService(Ci.nsIURLFormatter);
var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"]
.getService(Ci.nsIURLFormatter);
var appName = gBrandBundle.GetStringFromName("brandShortName");
function getNotifyString(aPropData) {
var propValue = update.getProperty(aPropData.propName);
if (!propValue) {
if (aPropData.prefName)
if (aPropData.prefName) {
propValue = formatter.formatURLPref(aPropData.prefName);
else if (aPropData.stringParams)
} else if (aPropData.stringParams) {
propValue = gBrowserBundle.formatStringFromName(aPropData.stringName,
aPropData.stringParams,
aPropData.stringParams.length);
else
} else {
propValue = gBrowserBundle.GetStringFromName(aPropData.stringName);
}
}
return propValue;
}
@ -845,23 +873,25 @@ BrowserGlue.prototype = {
notification.persistence = -1; // Until user closes it
}
if (actions.indexOf("showAlert") == -1)
if (actions.indexOf("showAlert") == -1) {
return;
}
let title = getNotifyString({propName: "alertTitle",
stringName: "puAlertTitle",
stringParams: [appName]});
let text = getNotifyString({propName: "alertText",
stringName: "puAlertText",
stringParams: [appName]});
let url = getNotifyString({propName: "alertURL",
prefName: "startup.homepage_override_url"});
let title = getNotifyString({ propName: "alertTitle",
stringName: "puAlertTitle",
stringParams: [appName] });
let text = getNotifyString({ propName: "alertText",
stringName: "puAlertText",
stringParams: [appName] });
let url = getNotifyString({ propName: "alertURL",
prefName: "startup.homepage_override_url" });
var self = this;
function clickCallback(subject, topic, data) {
// This callback will be called twice but only once with this topic
if (topic != "alertclickcallback")
if (topic != "alertclickcallback") {
return;
}
let win = self.getMostRecentBrowserWindow();
win.openUILinkIn(data, "tab");
}
@ -871,8 +901,7 @@ BrowserGlue.prototype = {
// be displayed per the idl.
AlertsService.showAlertNotification(null, title, text,
true, url, clickCallback);
}
catch (e) {
} catch(e) {
Cu.reportError(e);
}
},
@ -940,15 +969,13 @@ BrowserGlue.prototype = {
// restore from JSON/JSONLZ4 backup
yield BookmarkJSONUtils.importFromFile(bookmarksBackupFile, true);
importBookmarks = false;
}
else {
} else {
// We have created a new database but we don't have any backup available
importBookmarks = true;
if (yield OS.File.exists(BookmarkHTMLUtils.defaultPath)) {
// If bookmarks.html is available in current profile import it...
importBookmarksHTML = true;
}
else {
} else {
// ...otherwise we will restore defaults
restoreDefaultBookmarks = true;
}
@ -966,35 +993,34 @@ BrowserGlue.prototype = {
try {
this._distributionCustomizer.applyBookmarks();
this.ensurePlacesDefaultQueriesInitialized();
} catch (e) {
} catch(e) {
Cu.reportError(e);
}
}
else {
} else {
// An import operation is about to run.
// Don't try to recreate smart bookmarks if autoExportHTML is true or
// smart bookmarks are disabled.
var autoExportHTML = Services.prefs.getBoolPref("browser.bookmarks.autoExportHTML", false);
var smartBookmarksVersion = Services.prefs.getIntPref("browser.places.smartBookmarksVersion", 0);
if (!autoExportHTML && smartBookmarksVersion != -1)
if (!autoExportHTML && smartBookmarksVersion != -1) {
Services.prefs.setIntPref("browser.places.smartBookmarksVersion", 0);
}
var bookmarksUrl = null;
if (restoreDefaultBookmarks) {
// User wants to restore bookmarks.html file from default profile folder
bookmarksUrl = "resource:///defaults/profile/bookmarks.html";
}
else if (yield OS.File.exists(BookmarkHTMLUtils.defaultPath)) {
} else if (yield OS.File.exists(BookmarkHTMLUtils.defaultPath)) {
bookmarksUrl = OS.Path.toFileURI(BookmarkHTMLUtils.defaultPath);
}
if (bookmarksUrl) {
// Import from bookmarks.html file.
try {
BookmarkHTMLUtils.importFromURL(bookmarksUrl, true).then(null,
BookmarkHTMLUtils.importFromURL(bookmarksUrl, true).then(
null,
function onFailure() {
Cu.reportError(
new Error("Bookmarks.html file could be corrupt."));
Cu.reportError(new Error("Bookmarks.html file could be corrupt."));
}
).then(
function onComplete() {
@ -1005,18 +1031,17 @@ BrowserGlue.prototype = {
// Ensure that smart bookmarks are created once the operation
// is complete.
this.ensurePlacesDefaultQueriesInitialized();
} catch (e) {
} catch(e) {
Cu.reportError(e);
}
}.bind(this)
);
} catch (e) {
} catch(e) {
Cu.reportError(
new Error("Bookmarks.html file could be corrupt." + "\n" +
e.message));
}
}
else {
} else {
Cu.reportError(new Error("Unable to find bookmarks.html file."));
}
@ -1126,10 +1151,12 @@ BrowserGlue.prototype = {
let maxBackups = BOOKMARKS_BACKUP_MAX_BACKUPS;
try {
maxBackups = Services.prefs.getIntPref("browser.bookmarks.max_backups");
} catch(ex) {
// Use default.
}
catch(ex) { /* Use default. */ }
yield PlacesBackups.create(maxBackups); // Don't force creation.
// Don't force creation.
yield PlacesBackups.create(maxBackups);
}
});
},
@ -1146,9 +1173,9 @@ BrowserGlue.prototype = {
var accessKey = placesBundle.GetStringFromName("lockPromptInfoButton.accessKey");
var helpTopic = "places-locked";
var url = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
getService(Components.interfaces.nsIURLFormatter).
formatURLPref("app.support.baseURL");
var url = Cc["@mozilla.org/toolkit/URLFormatterService;1"]
.getService(Components.interfaces.nsIURLFormatter)
.formatURLPref("app.support.baseURL");
url += helpTopic;
var win = this.getMostRecentBrowserWindow();
@ -1178,8 +1205,9 @@ BrowserGlue.prototype = {
try {
currentUIVersion = Services.prefs.getIntPref("browser.migration.version");
} catch(ex) {}
if (currentUIVersion >= UI_VERSION)
if (currentUIVersion >= UI_VERSION) {
return;
}
this._rdf = Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);
this._dataSource = this._rdf.GetDataSource("rdf:local-store");
@ -1396,8 +1424,7 @@ BrowserGlue.prototype = {
} else if (ihaValue.includes("image/jxr")) {
Services.prefs.clearUserPref(ihaPref);
}
}
catch (ex) {}
} catch(ex) {}
}
#endif
@ -1453,8 +1480,9 @@ BrowserGlue.prototype = {
return;
}
function clickCallback(subject, topic, data) {
if (topic != "alertclickcallback")
if (topic != "alertclickcallback") {
return;
}
let win = RecentWindow.getMostRecentBrowserWindow();
win.openUILinkIn(data, "tab");
}
@ -1469,8 +1497,7 @@ BrowserGlue.prototype = {
try {
AlertsService.showAlertNotification(imageURL, title, text,
true, url, clickCallback);
}
catch (e) {
} catch(e) {
Cu.reportError(e);
}
},
@ -1480,8 +1507,7 @@ BrowserGlue.prototype = {
var url = "about:permissions";
try {
url = url + "?filter=" + aPrincipal.URI.host;
}
catch (e) {}
} catch(e) {}
win.openUILinkIn(url, "tab");
},
@ -1489,14 +1515,15 @@ BrowserGlue.prototype = {
try {
return !!Cc["@mozilla.org/system-alerts-service;1"].getService(
Ci.nsIAlertsService);
} catch (e) {}
} catch(e) {}
return false;
},
_getPersist: function(aSource, aProperty) {
var target = this._dataSource.GetTarget(aSource, aProperty, true);
if (target instanceof Ci.nsIRDFLiteral)
if (target instanceof Ci.nsIRDFLiteral) {
return target.Value;
}
return null;
},
@ -1505,12 +1532,12 @@ BrowserGlue.prototype = {
try {
var oldTarget = this._dataSource.GetTarget(aSource, aProperty, true);
if (oldTarget) {
if (aTarget)
if (aTarget) {
this._dataSource.Change(aSource, aProperty, oldTarget, this._rdf.GetLiteral(aTarget));
else
} else {
this._dataSource.Unassert(aSource, aProperty, oldTarget);
}
else {
}
} else {
this._dataSource.Assert(aSource, aProperty, this._rdf.GetLiteral(aTarget), true);
}
@ -1522,8 +1549,7 @@ BrowserGlue.prototype = {
if (!this._dataSource.HasAssertion(docResource, persistResource, aSource, true)) {
this._dataSource.Assert(docResource, persistResource, aSource, true);
}
}
catch(ex) {}
} catch(ex) {}
},
// ------------------------------
@ -1625,9 +1651,8 @@ BrowserGlue.prototype = {
smartBookmark.itemId = itemId;
smartBookmark.parent = PlacesUtils.bookmarks.getFolderIdForItem(itemId);
smartBookmark.position = PlacesUtils.bookmarks.getItemIndex(itemId);
}
else {
// We don't remove old Smart Bookmarks because user could still
} else {
// We don't remove old Smart Bookmarks because the user could still
// find them useful, or could have personalized them.
// Instead we remove the Smart Bookmark annotation.
PlacesUtils.annotations.removeItemAnnotation(itemId, SMART_BOOKMARKS_ANNO);
@ -1642,8 +1667,9 @@ BrowserGlue.prototype = {
// bookmark if it has been removed.
if (smartBookmarksCurrentVersion > 0 &&
smartBookmark.newInVersion <= smartBookmarksCurrentVersion &&
!smartBookmark.itemId)
!smartBookmark.itemId) {
continue;
}
// Remove old version of the smart bookmark if it exists, since it
// will be replaced in place.
@ -1681,11 +1707,9 @@ BrowserGlue.prototype = {
try {
PlacesUtils.bookmarks.runInBatchMode(batch, null);
}
catch(ex) {
} catch(ex) {
Components.utils.reportError(ex);
}
finally {
} finally {
Services.prefs.setIntPref(SMART_BOOKMARKS_PREF, SMART_BOOKMARKS_VERSION);
Services.prefs.savePrefFile(null);
}
@ -1714,7 +1738,7 @@ BrowserGlue.prototype = {
// The payload is wrapped weirdly because of how Sync does notifications.
tabbrowser.addTab(data.wrappedJSObject.object.uri);
} catch (ex) {
} catch(ex) {
Cu.reportError("Error displaying tab received by Sync: " + ex);
}
},
@ -1732,7 +1756,6 @@ BrowserGlue.prototype = {
}
function ContentPermissionPrompt() {}
ContentPermissionPrompt.prototype = {
classID: Components.ID("{d8903bf6-68d5-4e97-bcd1-e4d3012f721a}"),
@ -1775,7 +1798,7 @@ ContentPermissionPrompt.prototype = {
* @param aOptions Options for the PopupNotification
*/
_showPrompt: function(aRequest, aMessage, aPermission, aActions,
aNotificationId, aAnchorId, aOptions) {
aNotificationId, aAnchorId, aOptions) {
function onFullScreen() {
popup.remove();
}
@ -1838,8 +1861,9 @@ ContentPermissionPrompt.prototype = {
// If there's no mainAction, this is the autoAllow warning prompt.
let autoAllow = !mainAction;
if (!aOptions)
if (!aOptions) {
aOptions = {};
}
aOptions.removeOnDismissal = autoAllow;
aOptions.eventCallback = type => {
@ -1870,14 +1894,13 @@ ContentPermissionPrompt.prototype = {
var message;
// Share location action.
var actions = [{
stringId: "geolocation.shareLocation",
action: null,
expireType: null,
callback: function() {
// Telemetry stub (left here for safety and compatibility reasons)
},
}];
var actions = [{ stringId: "geolocation.shareLocation",
action: null,
expireType: null,
callback: function() {
// Telemetry stub (left here for safety and compatibility reasons)
}
}];
if (requestingURI.schemeIs("file")) {
message = gBrowserBundle.formatStringFromName("geolocation.shareWithFile",
@ -1892,7 +1915,7 @@ ContentPermissionPrompt.prototype = {
expireType: null,
callback: function() {
// Telemetry stub (left here for safety and compatibility reasons)
},
}
});
// Never share location action.
@ -1902,13 +1925,11 @@ ContentPermissionPrompt.prototype = {
expireType: null,
callback: function() {
// Telemetry stub (left here for safety and compatibility reasons)
},
}
});
}
var options = {
learnMoreURL: Services.urlFormatter.formatURLPref("browser.geolocation.warning.infoURL"),
};
var options = { learnMoreURL: Services.urlFormatter.formatURLPref("browser.geolocation.warning.infoURL") };
this._showPrompt(aRequest, message, "geo", actions, "geolocation",
"geo-notification-icon", options);
@ -1932,7 +1953,7 @@ ContentPermissionPrompt.prototype = {
action: Ci.nsIPermissionManager.ALLOW_ACTION,
expireType: Ci.nsIPermissionManager.EXPIRE_SESSION,
callback: function() {},
},
}
];
} else {
actions = [
@ -1953,7 +1974,7 @@ ContentPermissionPrompt.prototype = {
action: Ci.nsIPermissionManager.DENY_ACTION,
expireType: null,
callback: function() {},
},
}
];
}
var options = {
@ -1994,7 +2015,7 @@ ContentPermissionPrompt.prototype = {
action: Ci.nsIPermissionManager.DENY_ACTION,
expireType: null,
callback: function() {},
},
}
];
}
@ -2058,9 +2079,8 @@ ContentPermissionPrompt.prototype = {
this._promptPointerLock(request, autoAllow);
break;
}
},
};
}
}; // ContentPermissionPrompt
var components = [BrowserGlue, ContentPermissionPrompt];
this.NSGetFactory = XPCOMUtils.generateNSGetFactory(components);