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

View File

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

View File

@ -30,39 +30,40 @@ function removeNotificationOnEnd(notification, installs) {
} }
const gXPInstallObserver = { const gXPInstallObserver = {
_findChildShell: function (aDocShell, aSoughtShell) _findChildShell: function (aDocShell, aSoughtShell) {
{ if (aDocShell == aSoughtShell) {
if (aDocShell == aSoughtShell)
return aDocShell; return aDocShell;
}
var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeItem); var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeItem);
for (var i = 0; i < node.childCount; ++i) { for (var i = 0; i < node.childCount; ++i) {
var docShell = node.getChildAt(i); var docShell = node.getChildAt(i);
docShell = this._findChildShell(docShell, aSoughtShell); docShell = this._findChildShell(docShell, aSoughtShell);
if (docShell == aSoughtShell) if (docShell == aSoughtShell) {
return docShell; return docShell;
}
} }
return null; return null;
}, },
_getBrowser: function (aDocShell) _getBrowser: function (aDocShell) {
{
for (let browser of gBrowser.browsers) { for (let browser of gBrowser.browsers) {
if (this._findChildShell(browser.docShell, aDocShell)) if (this._findChildShell(browser.docShell, aDocShell)) {
return browser; return browser;
}
} }
return null; return null;
}, },
observe: function (aSubject, aTopic, aData) observe: function (aSubject, aTopic, aData) {
{
var brandBundle = document.getElementById("bundle_brand"); var brandBundle = document.getElementById("bundle_brand");
var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo); var installInfo = aSubject.QueryInterface(Components.interfaces.amIWebInstallInfo);
var browser = installInfo.browser; var browser = installInfo.browser;
// Make sure the browser is still alive. // Make sure the browser is still alive.
if (!browser || gBrowser.browsers.indexOf(browser) == -1) if (!browser || gBrowser.browsers.indexOf(browser) == -1) {
return; return;
}
const anchorID = "addons-notification-icon"; const anchorID = "addons-notification-icon";
var messageString, action; var messageString, action;
@ -70,152 +71,159 @@ const gXPInstallObserver = {
var notificationID = aTopic; var notificationID = aTopic;
// Make notifications persist a minimum of 30 seconds // Make notifications persist a minimum of 30 seconds
var options = { var options = { timeout: Date.now() + 30000 };
timeout: Date.now() + 30000
};
switch (aTopic) { switch (aTopic) {
case "addon-install-disabled": case "addon-install-disabled": {
notificationID = "xpinstall-disabled" notificationID = "xpinstall-disabled"
if (gPrefService.prefIsLocked("xpinstall.enabled")) { if (gPrefService.prefIsLocked("xpinstall.enabled")) {
messageString = gNavigatorBundle.getString("xpinstallDisabledMessageLocked"); messageString = gNavigatorBundle.getString("xpinstallDisabledMessageLocked");
buttons = []; buttons = [];
} } else {
else { messageString = gNavigatorBundle.getString("xpinstallDisabledMessage");
messageString = gNavigatorBundle.getString("xpinstallDisabledMessage");
action = { action = {
label: gNavigatorBundle.getString("xpinstallDisabledButton"), label: gNavigatorBundle.getString("xpinstallDisabledButton"),
accessKey: gNavigatorBundle.getString("xpinstallDisabledButton.accesskey"), accessKey: gNavigatorBundle.getString("xpinstallDisabledButton.accesskey"),
callback: function editPrefs() { callback: function editPrefs() {
gPrefService.setBoolPref("xpinstall.enabled", true); 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();
} }
};
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, PopupNotifications.show(browser, notificationID, messageString, anchorID,
action, null, options); action, null, options);
break;
} }
break; case "addon-install-origin-blocked": {
case "addon-install-complete": messageString = gNavigatorBundle.getFormattedString("xpinstallPromptWarningOrigin",
var needsRestart = installInfo.installs.some(function(i) { [brandShortName]);
return i.addon.pendingOperations != AddonManager.PENDING_NONE;
}); 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 = { action = {
label: gNavigatorBundle.getString("addonInstallRestartButton"), label: gNavigatorBundle.getString("xpinstallPromptAllowButton"),
accessKey: gNavigatorBundle.getString("addonInstallRestartButton.accesskey"), accessKey: gNavigatorBundle.getString("xpinstallPromptAllowButton.accesskey"),
callback: function() { callback: function() {
Application.restart(); installInfo.install();
} }
}; };
let popup = PopupNotifications.show(browser, notificationID, messageString,
anchorID, action, null, options);
removeNotificationOnEnd(popup, installInfo.installs);
break;
} }
else { case "addon-install-started": {
messageString = gNavigatorBundle.getString("addonsInstalled"); var needsDownload = function needsDownload(aInstall) {
action = null; 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); let error = (host || install.error == 0) ? "addonError" : "addonLocalError";
messageString = messageString.replace("#1", installInfo.installs[0].name); if (install.error != 0) {
messageString = messageString.replace("#2", installInfo.installs.length); error += install.error;
messageString = messageString.replace("#3", brandShortName); } 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 messageString = gNavigatorBundle.getString(error);
// install through the addons manager UI, making the "restart" prompt messageString = messageString.replace("#1", install.name);
// irrelevant. if (host) {
options.removeOnDismissal = true; messageString = messageString.replace("#2", host);
}
messageString = messageString.replace("#3", brandShortName);
messageString = messageString.replace("#4", Services.appinfo.version);
PopupNotifications.show(browser, notificationID, messageString, anchorID, PopupNotifications.show(browser, notificationID, messageString, anchorID,
action, null, options); action, null, options);
break; }
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(",") .split(",")
.concat(["separator", "spacer", "spring"]); .concat(["separator", "spacer", "spring"]);
for (let item of this.addonBar.currentSet.split(",")) { for (let item of this.addonBar.currentSet.split(",")) {
if (defaultOrNoninteractive.indexOf(item) == -1) if (defaultOrNoninteractive.indexOf(item) == -1) {
itemCount++; itemCount++;
}
} }
return itemCount; return itemCount;
@ -247,20 +256,30 @@ var AddonsMgrListener = {
this.lastAddonBarCount = this.getAddonBarItemCount(); this.lastAddonBarCount = this.getAddonBarItemCount();
}, },
onInstalled: function(aAddon) { onInstalled: function(aAddon) {
if (this.getAddonBarItemCount() > this.lastAddonBarCount) if (this.getAddonBarItemCount() > this.lastAddonBarCount) {
setToolbarVisibility(this.addonBar, true); setToolbarVisibility(this.addonBar, true);
}
}, },
onUninstalling: function(aAddon) { onUninstalling: function(aAddon) {
this.lastAddonBarCount = this.getAddonBarItemCount(); this.lastAddonBarCount = this.getAddonBarItemCount();
}, },
onUninstalled: function(aAddon) { onUninstalled: function(aAddon) {
if (this.getAddonBarItemCount() == 0) if (this.getAddonBarItemCount() == 0) {
setToolbarVisibility(this.addonBar, false); setToolbarVisibility(this.addonBar, false);
}
}, },
onEnabling: function(aAddon) this.onInstalling(), onEnabling: function(aAddon) {
onEnabled: function(aAddon) this.onInstalled(), return this.onInstalling();
onDisabling: function(aAddon) this.onUninstalling(), },
onDisabled: function(aAddon) this.onUninstalled(), onEnabled: function(aAddon) {
return this.onInstalled();
},
onDisabling: function(aAddon) {
return this.onUninstalling();
},
onDisabled: function(aAddon) {
return this.onUninstalled();
}
}; };
#ifdef MOZ_PERSONAS #ifdef MOZ_PERSONAS
@ -271,8 +290,9 @@ var LightWeightThemeWebInstaller = {
case "PreviewBrowserTheme": case "PreviewBrowserTheme":
case "ResetBrowserThemePreview": case "ResetBrowserThemePreview":
// ignore requests from background tabs // ignore requests from background tabs
if (event.target.ownerDocument.defaultView.top != content) if (event.target.ownerDocument.defaultView.top != content) {
return; return;
}
} }
switch (event.type) { switch (event.type) {
case "InstallBrowserTheme": case "InstallBrowserTheme":
@ -301,21 +321,19 @@ var LightWeightThemeWebInstaller = {
_installRequest: function (event) { _installRequest: function (event) {
var node = event.target; var node = event.target;
var data = this._getThemeFromNode(node); var data = this._getThemeFromNode(node);
if (!data) if (!data) {
return; return;
}
if (this._isAllowed(node)) { if (this._isAllowed(node)) {
this._install(data); this._install(data);
return; return;
} }
var allowButtonText = var allowButtonText = gNavigatorBundle.getString("lwthemeInstallRequest.allowButton");
gNavigatorBundle.getString("lwthemeInstallRequest.allowButton"); var allowButtonAccesskey = gNavigatorBundle.getString("lwthemeInstallRequest.allowButton.accesskey");
var allowButtonAccesskey = var message = gNavigatorBundle.getFormattedString("lwthemeInstallRequest.message",
gNavigatorBundle.getString("lwthemeInstallRequest.allowButton.accesskey"); [node.ownerDocument.location.host]);
var message =
gNavigatorBundle.getFormattedString("lwthemeInstallRequest.message",
[node.ownerDocument.location.host]);
var buttons = [{ var buttons = [{
label: allowButtonText, label: allowButtonText,
accessKey: allowButtonAccesskey, accessKey: allowButtonAccesskey,
@ -339,11 +357,12 @@ var LightWeightThemeWebInstaller = {
var listener = { var listener = {
onEnabling: function(aAddon, aRequiresRestart) { onEnabling: function(aAddon, aRequiresRestart) {
if (!aRequiresRestart) if (!aRequiresRestart) {
return; return;
}
let messageString = gNavigatorBundle.getFormattedString("lwthemeNeedsRestart.message", let messageString = gNavigatorBundle.getFormattedString("lwthemeNeedsRestart.message",
[aAddon.name], 1); [aAddon.name], 1);
let action = { let action = {
label: gNavigatorBundle.getString("lwthemeNeedsRestart.button"), label: gNavigatorBundle.getString("lwthemeNeedsRestart.button"),
@ -353,9 +372,7 @@ var LightWeightThemeWebInstaller = {
} }
}; };
let options = { let options = { timeout: Date.now() + 30000 };
timeout: Date.now() + 30000
};
PopupNotifications.show(gBrowser.selectedBrowser, "addon-theme-change", PopupNotifications.show(gBrowser.selectedBrowser, "addon-theme-change",
messageString, "addons-notification-icon", messageString, "addons-notification-icon",
@ -417,12 +434,14 @@ var LightWeightThemeWebInstaller = {
_previewWindow: null, _previewWindow: null,
_preview: function (event) { _preview: function (event) {
if (!this._isAllowed(event.target)) if (!this._isAllowed(event.target)) {
return; return;
}
var data = this._getThemeFromNode(event.target); var data = this._getThemeFromNode(event.target);
if (!data) if (!data) {
return; return;
}
this._resetPreview(); this._resetPreview();
@ -435,8 +454,9 @@ var LightWeightThemeWebInstaller = {
_resetPreview: function (event) { _resetPreview: function (event) {
if (!this._previewWindow || if (!this._previewWindow ||
event && !this._isAllowed(event.target)) (event && !this._isAllowed(event.target))) {
return; return;
}
this._previewWindow.removeEventListener("pagehide", this, true); this._previewWindow.removeEventListener("pagehide", this, true);
this._previewWindow = null; this._previewWindow = null;
@ -475,8 +495,9 @@ var LightweightThemeListener = {
Services.obs.addObserver(this, "lightweight-theme-styling-update", false); Services.obs.addObserver(this, "lightweight-theme-styling-update", false);
Services.obs.addObserver(this, "lightweight-theme-optimized", 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); this.updateStyleSheet(document.documentElement.style.backgroundImage);
}
}, },
uninit: function () { uninit: function () {
@ -491,8 +512,9 @@ var LightweightThemeListener = {
* @param headerImage - a string containing a CSS image for the lightweight theme header. * @param headerImage - a string containing a CSS image for the lightweight theme header.
*/ */
updateStyleSheet: function(headerImage) { updateStyleSheet: function(headerImage) {
if (!this.styleSheet) if (!this.styleSheet) {
return; return;
}
this.substituteRules(this.styleSheet.cssRules, headerImage); this.substituteRules(this.styleSheet.cssRules, headerImage);
}, },
@ -504,11 +526,13 @@ var LightweightThemeListener = {
// Add the number of modified sub-rules to the modified count // Add the number of modified sub-rules to the modified count
styleRulesModified += this.substituteRules(rule.cssRules, headerImage, existingStyleRulesModified + styleRulesModified); styleRulesModified += this.substituteRules(rule.cssRules, headerImage, existingStyleRulesModified + styleRulesModified);
} else if (rule instanceof Ci.nsIDOMCSSStyleRule) { } else if (rule instanceof Ci.nsIDOMCSSStyleRule) {
if (!rule.style.backgroundImage) if (!rule.style.backgroundImage) {
continue; continue;
}
let modifiedIndex = existingStyleRulesModified + styleRulesModified; let modifiedIndex = existingStyleRulesModified + styleRulesModified;
if (!this._modifiedStyles[modifiedIndex]) if (!this._modifiedStyles[modifiedIndex]) {
this._modifiedStyles[modifiedIndex] = { backgroundImage: rule.style.backgroundImage }; this._modifiedStyles[modifiedIndex] = { backgroundImage: rule.style.backgroundImage };
}
rule.style.backgroundImage = this._modifiedStyles[modifiedIndex].backgroundImage + ", " + headerImage; rule.style.backgroundImage = this._modifiedStyles[modifiedIndex].backgroundImage + ", " + headerImage;
styleRulesModified++; styleRulesModified++;
@ -522,15 +546,18 @@ var LightweightThemeListener = {
// nsIObserver // nsIObserver
observe: function (aSubject, aTopic, aData) { observe: function (aSubject, aTopic, aData) {
if ((aTopic != "lightweight-theme-styling-update" && aTopic != "lightweight-theme-optimized") || if ((aTopic != "lightweight-theme-styling-update" && aTopic != "lightweight-theme-optimized") ||
!this.styleSheet) !this.styleSheet) {
return; return;
}
if (aTopic == "lightweight-theme-optimized" && aSubject != window) if (aTopic == "lightweight-theme-optimized" && aSubject != window) {
return; return;
}
let themeData = JSON.parse(aData); let themeData = JSON.parse(aData);
if (!themeData) if (!themeData) {
return; return;
}
this.updateStyleSheet("url(" + themeData.headerURL + ")"); this.updateStyleSheet("url(" + themeData.headerURL + ")");
}, },
}; };

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -117,12 +117,14 @@ var gSyncUI = {
// Functions called by observers // Functions called by observers
onActivityStart: function() { onActivityStart: function() {
if (!gBrowser) if (!gBrowser) {
return; return;
}
let button = document.getElementById("sync-button"); let button = document.getElementById("sync-button");
if (!button) if (!button) {
return; return;
}
button.setAttribute("status", "active"); button.setAttribute("status", "active");
button.setAttribute("label", this._stringBundle.GetStringFromName("syncing2.label")); button.setAttribute("label", this._stringBundle.GetStringFromName("syncing2.label"));
@ -182,7 +184,10 @@ var gSyncUI = {
buttons.push(new Weave.NotificationButton( buttons.push(new Weave.NotificationButton(
this._stringBundle.GetStringFromName("error.login.prefs.label"), this._stringBundle.GetStringFromName("error.login.prefs.label"),
this._stringBundle.GetStringFromName("error.login.prefs.accesskey"), 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, let notification = new Weave.Notification(title, description, null,
@ -206,7 +211,10 @@ var gSyncUI = {
buttons.push(new Weave.NotificationButton( buttons.push(new Weave.NotificationButton(
this._stringBundle.GetStringFromName("error.sync.viewQuotaButton.label"), this._stringBundle.GetStringFromName("error.sync.viewQuotaButton.label"),
this._stringBundle.GetStringFromName("error.sync.viewQuotaButton.accesskey"), this._stringBundle.GetStringFromName("error.sync.viewQuotaButton.accesskey"),
function() { gSyncUI.openQuotaDialog(); return true; } function() {
gSyncUI.openQuotaDialog();
return true;
}
)); ));
let notification = new Weave.Notification( let notification = new Weave.Notification(
@ -225,10 +233,11 @@ var gSyncUI = {
}, },
handleToolbarButton: function() { handleToolbarButton: function() {
if (this._needsSetup()) if (this._needsSetup()) {
this.openSetup(); this.openSetup();
else } else {
this.doSync(); this.doSync();
}
}, },
//XXXzpao should be part of syncCommon.js - which we might want to make a module... //XXXzpao should be part of syncCommon.js - which we might want to make a module...
@ -246,9 +255,9 @@ var gSyncUI = {
openSetup: function(wizardType) { openSetup: function(wizardType) {
let win = Services.wm.getMostRecentWindow("Weave:AccountSetup"); let win = Services.wm.getMostRecentWindow("Weave:AccountSetup");
if (win) if (win) {
win.focus(); win.focus();
else { } else {
window.openDialog("chrome://browser/content/sync/setup.xul", window.openDialog("chrome://browser/content/sync/setup.xul",
"weaveSetup", "centerscreen,chrome,resizable=no", "weaveSetup", "centerscreen,chrome,resizable=no",
wizardType); wizardType);
@ -256,25 +265,28 @@ var gSyncUI = {
}, },
openAddDevice: function() { openAddDevice: function() {
if (!Weave.Utils.ensureMPUnlocked()) if (!Weave.Utils.ensureMPUnlocked()) {
return; return;
}
let win = Services.wm.getMostRecentWindow("Sync:AddDevice"); let win = Services.wm.getMostRecentWindow("Sync:AddDevice");
if (win) if (win) {
win.focus(); win.focus();
else } else {
window.openDialog("chrome://browser/content/sync/addDevice.xul", window.openDialog("chrome://browser/content/sync/addDevice.xul",
"syncAddDevice", "centerscreen,chrome,resizable=no"); "syncAddDevice", "centerscreen,chrome,resizable=no");
}
}, },
openQuotaDialog: function() { openQuotaDialog: function() {
let win = Services.wm.getMostRecentWindow("Sync:ViewQuota"); let win = Services.wm.getMostRecentWindow("Sync:ViewQuota");
if (win) if (win) {
win.focus(); win.focus();
else } else {
Services.ww.activeWindow.openDialog( Services.ww.activeWindow.openDialog(
"chrome://browser/content/sync/quota.xul", "", "chrome://browser/content/sync/quota.xul", "",
"centerscreen,chrome,dialog,modal"); "centerscreen,chrome,dialog,modal");
}
}, },
openPrefs: function() { openPrefs: function() {
@ -284,12 +296,14 @@ var gSyncUI = {
// Helpers // Helpers
_updateLastSyncTime: function() { _updateLastSyncTime: function() {
if (!gBrowser) if (!gBrowser) {
return; return;
}
let syncButton = document.getElementById("sync-button"); let syncButton = document.getElementById("sync-button");
if (!syncButton) if (!syncButton) {
return; return;
}
let lastSync = Services.prefs.getCharPref("services.sync.lastSync", ""); let lastSync = Services.prefs.getCharPref("services.sync.lastSync", "");
if (!lastSync || this._needsSetup()) { if (!lastSync || this._needsSetup()) {
@ -348,8 +362,9 @@ var gSyncUI = {
// Check if the client is outdated in some way // Check if the client is outdated in some way
let outdated = Weave.Status.sync == Weave.VERSION_OUT_OF_DATE; 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; outdated = outdated || reason == Weave.VERSION_OUT_OF_DATE;
}
if (outdated) { if (outdated) {
description = this._stringBundle.GetStringFromName( description = this._stringBundle.GetStringFromName(
@ -362,8 +377,7 @@ var gSyncUI = {
return true; return true;
} }
)); ));
} } else if (Weave.Status.sync == Weave.OVER_QUOTA) {
else if (Weave.Status.sync == Weave.OVER_QUOTA) {
description = this._stringBundle.GetStringFromName( description = this._stringBundle.GetStringFromName(
"error.sync.quota.description"); "error.sync.quota.description");
buttons.push(new Weave.NotificationButton( buttons.push(new Weave.NotificationButton(
@ -371,23 +385,30 @@ var gSyncUI = {
"error.sync.viewQuotaButton.label"), "error.sync.viewQuotaButton.label"),
this._stringBundle.GetStringFromName( this._stringBundle.GetStringFromName(
"error.sync.viewQuotaButton.accesskey"), "error.sync.viewQuotaButton.accesskey"),
function() { gSyncUI.openQuotaDialog(); return true; } ) function() {
); gSyncUI.openQuotaDialog();
} return true;
else if (Weave.Status.enforceBackoff) { }
));
} else if (Weave.Status.enforceBackoff) {
priority = Weave.Notifications.PRIORITY_INFO; priority = Weave.Notifications.PRIORITY_INFO;
buttons.push(new Weave.NotificationButton( buttons.push(new Weave.NotificationButton(
this._stringBundle.GetStringFromName("error.sync.serverStatusButton.label"), this._stringBundle.GetStringFromName("error.sync.serverStatusButton.label"),
this._stringBundle.GetStringFromName("error.sync.serverStatusButton.accesskey"), this._stringBundle.GetStringFromName("error.sync.serverStatusButton.accesskey"),
function() { gSyncUI.openServerStatus(); return true; } function() {
gSyncUI.openServerStatus();
return true;
}
)); ));
} } else {
else {
priority = Weave.Notifications.PRIORITY_INFO; priority = Weave.Notifications.PRIORITY_INFO;
buttons.push(new Weave.NotificationButton( buttons.push(new Weave.NotificationButton(
this._stringBundle.GetStringFromName("error.sync.tryAgainButton.label"), this._stringBundle.GetStringFromName("error.sync.tryAgainButton.label"),
this._stringBundle.GetStringFromName("error.sync.tryAgainButton.accesskey"), 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() { init: function() {
if (this._selectedTab) if (this._selectedTab) {
return; return;
}
this._selectedTab = gBrowser.selectedTab; this._selectedTab = gBrowser.selectedTab;
gBrowser.tabContainer.addEventListener("TabSelect", this, false); gBrowser.tabContainer.addEventListener("TabSelect", this, false);
@ -40,8 +41,9 @@ var tabPreviews = {
aTab.__thumbnail_lastURI = null; aTab.__thumbnail_lastURI = null;
} }
if (aTab.__thumbnail) if (aTab.__thumbnail) {
return aTab.__thumbnail; return aTab.__thumbnail;
}
if (aTab.getAttribute("pending") == "true") { if (aTab.getAttribute("pending") == "true") {
let img = new Image; let img = new Image;
@ -90,8 +92,9 @@ var tabPreviews = {
self._pendingUpdate = false; self._pendingUpdate = false;
if (aTab.parentNode && if (aTab.parentNode &&
!aTab.hasAttribute("busy") && !aTab.hasAttribute("busy") &&
!aTab.hasAttribute("pending")) !aTab.hasAttribute("pending")) {
self.capture(aTab, true); self.capture(aTab, true);
}
}, 2000, this, this._selectedTab); }, 2000, this, this._selectedTab);
} }
this._selectedTab = event.target; this._selectedTab = event.target;
@ -123,20 +126,23 @@ var tabPreviewPanelHelper = {
}; };
}, },
_popupshown: function(host) { _popupshown: function(host) {
if ("setupGUI" in host) if ("setupGUI" in host) {
host.setupGUI(); host.setupGUI();
}
}, },
_popuphiding: function(host) { _popuphiding: function(host) {
if ("suspendGUI" in host) if ("suspendGUI" in host) {
host.suspendGUI(); host.suspendGUI();
}
if (host._prevFocus) { if (host._prevFocus) {
Cc["@mozilla.org/focus-manager;1"] Cc["@mozilla.org/focus-manager;1"]
.getService(Ci.nsIFocusManager) .getService(Ci.nsIFocusManager)
.setFocus(host._prevFocus, Ci.nsIFocusManager.FLAG_NOSCROLL); .setFocus(host._prevFocus, Ci.nsIFocusManager.FLAG_NOSCROLL);
host._prevFocus = null; host._prevFocus = null;
} else } else {
gBrowser.selectedBrowser.focus(); gBrowser.selectedBrowser.focus();
}
if (host.tabToSelect) { if (host.tabToSelect) {
gBrowser.selectedTab = host.tabToSelect; gBrowser.selectedTab = host.tabToSelect;
@ -149,23 +155,23 @@ var tabPreviewPanelHelper = {
* Ctrl-Tab panel * Ctrl-Tab panel
*/ */
var ctrlTab = { var ctrlTab = {
get panel () { get panel() {
delete this.panel; delete this.panel;
return this.panel = document.getElementById("ctrlTab-panel"); return this.panel = document.getElementById("ctrlTab-panel");
}, },
get showAllButton () { get showAllButton() {
delete this.showAllButton; delete this.showAllButton;
return this.showAllButton = document.getElementById("ctrlTab-showAll"); return this.showAllButton = document.getElementById("ctrlTab-showAll");
}, },
get previews () { get previews() {
delete this.previews; delete this.previews;
return this.previews = this.panel.getElementsByClassName("ctrlTab-preview"); return this.previews = this.panel.getElementsByClassName("ctrlTab-preview");
}, },
get recentlyUsedLimit () { get recentlyUsedLimit() {
delete this.recentlyUsedLimit; delete this.recentlyUsedLimit;
return this.recentlyUsedLimit = gPrefService.getIntPref("browser.ctrlTab.recentlyUsedLimit"); return this.recentlyUsedLimit = gPrefService.getIntPref("browser.ctrlTab.recentlyUsedLimit");
}, },
get keys () { get keys() {
var keys = {}; var keys = {};
["close", "find", "selectAll"].forEach(function(key) { ["close", "find", "selectAll"].forEach(function(key) {
keys[key] = document.getElementById("key_" + key) keys[key] = document.getElementById("key_" + key)
@ -176,17 +182,26 @@ var ctrlTab = {
return this.keys = keys; return this.keys = keys;
}, },
_selectedIndex: 0, _selectedIndex: 0,
get selected () this._selectedIndex < 0 ? get selected() {
document.activeElement : return this._selectedIndex < 0 ? document.activeElement : this.previews.item(this._selectedIndex);
this.previews.item(this._selectedIndex), },
get isOpen () this.panel.state == "open" || this.panel.state == "showing" || this._timer, get isOpen() {
get tabCount () this.tabList.length, return this.panel.state == "open" || this.panel.state == "showing" || this._timer;
get tabPreviewCount () Math.min(this.previews.length - 1, this.tabCount), },
get canvasWidth () Math.min(tabPreviews.width, get tabCount() {
Math.ceil(screen.availWidth * .85 / this.tabPreviewCount)), return this.tabList.length;
get canvasHeight () Math.round(this.canvasWidth * tabPreviews.aspectRatio), },
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) if (this._tabList)
return this._tabList; return this._tabList;
@ -196,8 +211,9 @@ var ctrlTab = {
let list = Array.filter(gBrowser.tabs, function(tab) !tab.hidden); let list = Array.filter(gBrowser.tabs, function(tab) !tab.hidden);
// Rotate the list until the selected tab is first // Rotate the list until the selected tab is first
while (!list[0].selected) while (!list[0].selected) {
list.push(list.shift()); list.push(list.shift());
}
list = list.filter(function(tab) !tab.closing); list = list.filter(function(tab) !tab.closing);
@ -206,8 +222,9 @@ var ctrlTab = {
for (let tab of this._recentlyUsedTabs) { for (let tab of this._recentlyUsedTabs) {
if (!tab.hidden && !tab.closing) { if (!tab.hidden && !tab.closing) {
recentlyUsedTabs.push(tab); recentlyUsedTabs.push(tab);
if (this.recentlyUsedLimit > 0 && recentlyUsedTabs.length >= this.recentlyUsedLimit) if (this.recentlyUsedLimit > 0 && recentlyUsedTabs.length >= this.recentlyUsedLimit) {
break; break;
}
} }
} }
for (let i = recentlyUsedTabs.length - 1; i >= 0; i--) { for (let i = recentlyUsedTabs.length - 1; i >= 0; i--) {
@ -249,18 +266,20 @@ var ctrlTab = {
(!gPrefService.prefHasUserValue("browser.ctrlTab.disallowForScreenReaders") || (!gPrefService.prefHasUserValue("browser.ctrlTab.disallowForScreenReaders") ||
!gPrefService.getBoolPref("browser.ctrlTab.disallowForScreenReaders")); !gPrefService.getBoolPref("browser.ctrlTab.disallowForScreenReaders"));
if (enable) if (enable) {
this.init(); this.init();
else } else {
this.uninit(); this.uninit();
}
}, },
observe: function(aSubject, aTopic, aPrefName) { observe: function(aSubject, aTopic, aPrefName) {
this.readPref(); this.readPref();
}, },
updatePreviews: function() { 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]); this.updatePreview(this.previews[i], this.tabList[i]);
}
var showAllLabel = gNavigatorBundle.getString("ctrlTab.showAll.label"); var showAllLabel = gNavigatorBundle.getString("ctrlTab.showAll.label");
this.showAllButton.label = this.showAllButton.label =
@ -268,13 +287,15 @@ var ctrlTab = {
}, },
updatePreview: function(aPreview, aTab) { updatePreview: function(aPreview, aTab) {
if (aPreview == this.showAllButton) if (aPreview == this.showAllButton) {
return; return;
}
aPreview._tab = aTab; aPreview._tab = aTab;
if (aPreview.firstChild) if (aPreview.firstChild) {
aPreview.removeChild(aPreview.firstChild); aPreview.removeChild(aPreview.firstChild);
}
if (aTab) { if (aTab) {
let canvasWidth = this.canvasWidth; let canvasWidth = this.canvasWidth;
let canvasHeight = this.canvasHeight; let canvasHeight = this.canvasHeight;
@ -305,10 +326,11 @@ var ctrlTab = {
let selectedIndex = Array.indexOf(this.previews, this.selected); let selectedIndex = Array.indexOf(this.previews, this.selected);
do { do {
selectedIndex += aForward ? 1 : -1; selectedIndex += aForward ? 1 : -1;
if (selectedIndex < 0) if (selectedIndex < 0) {
selectedIndex = this.previews.length - 1; selectedIndex = this.previews.length - 1;
else if (selectedIndex >= this.previews.length) } else if (selectedIndex >= this.previews.length) {
selectedIndex = 0; selectedIndex = 0;
}
} while (this.previews[selectedIndex].hidden); } while (this.previews[selectedIndex].hidden);
if (this._selectedIndex == -1) { if (this._selectedIndex == -1) {
@ -331,15 +353,17 @@ var ctrlTab = {
}, },
pick: function(aPreview) { pick: function(aPreview) {
if (!this.tabCount) if (!this.tabCount) {
return; return;
}
var select = (aPreview || this.selected); var select = (aPreview || this.selected);
if (select == this.showAllButton) if (select == this.showAllButton) {
this.showAllTabs(); this.showAllTabs();
else } else {
this.close(select._tab); this.close(select._tab);
}
}, },
showAllTabs: function(aPreview) { showAllTabs: function(aPreview) {
@ -348,27 +372,31 @@ var ctrlTab = {
}, },
remove: function(aPreview) { remove: function(aPreview) {
if (aPreview._tab) if (aPreview._tab) {
gBrowser.removeTab(aPreview._tab); gBrowser.removeTab(aPreview._tab);
}
}, },
attachTab: function(aTab, aPos) { attachTab: function(aTab, aPos) {
if (aPos == 0) if (aPos == 0) {
this._recentlyUsedTabs.unshift(aTab); this._recentlyUsedTabs.unshift(aTab);
else if (aPos) } else if (aPos) {
this._recentlyUsedTabs.splice(aPos, 0, aTab); this._recentlyUsedTabs.splice(aPos, 0, aTab);
else } else {
this._recentlyUsedTabs.push(aTab); this._recentlyUsedTabs.push(aTab);
}
}, },
detachTab: function(aTab) { detachTab: function(aTab) {
var i = this._recentlyUsedTabs.indexOf(aTab); var i = this._recentlyUsedTabs.indexOf(aTab);
if (i >= 0) if (i >= 0) {
this._recentlyUsedTabs.splice(i, 1); this._recentlyUsedTabs.splice(i, 1);
}
}, },
open: function() { open: function() {
if (this.isOpen) if (this.isOpen) {
return; return;
}
allTabs.close(); allTabs.close();
@ -397,15 +425,17 @@ var ctrlTab = {
}, },
close: function(aTabToSelect) { close: function(aTabToSelect) {
if (!this.isOpen) if (!this.isOpen) {
return; return;
}
if (this._timer) { if (this._timer) {
clearTimeout(this._timer); clearTimeout(this._timer);
this._timer = null; this._timer = null;
this.suspendGUI(); this.suspendGUI();
if (aTabToSelect) if (aTabToSelect) {
gBrowser.selectedTab = aTabToSelect; gBrowser.selectedTab = aTabToSelect;
}
return; return;
} }
@ -421,8 +451,9 @@ var ctrlTab = {
// to be under the mouse pointer initially won't be selected unintentionally. // to be under the mouse pointer initially won't be selected unintentionally.
this._trackMouseOver = false; this._trackMouseOver = false;
setTimeout(function(self) { setTimeout(function(self) {
if (self.isOpen) if (self.isOpen) {
self._trackMouseOver = true; self._trackMouseOver = true;
}
}, 0, this); }, 0, this);
}, },
@ -490,10 +521,12 @@ var ctrlTab = {
this._tabList = null; this._tabList = null;
this.updatePreviews(); this.updatePreviews();
if (this.selected.hidden) if (this.selected.hidden) {
this.advanceFocus(false); this.advanceFocus(false);
if (this.selected == this.showAllButton) }
if (this.selected == this.showAllButton) {
this.advanceFocus(false); this.advanceFocus(false);
}
// If the current tab is removed, another tab can steal our focus. // If the current tab is removed, another tab can steal our focus.
if (aTab.selected && this.panel.state == "open") { if (aTab.selected && this.panel.state == "open") {
@ -523,15 +556,17 @@ var ctrlTab = {
break; break;
case "TabClose": case "TabClose":
this.detachTab(event.target); this.detachTab(event.target);
if (this.isOpen) if (this.isOpen) {
this.removeClosingTabFromUI(event.target); this.removeClosingTabFromUI(event.target);
}
break; break;
case "keypress": case "keypress":
this.onKeyPress(event); this.onKeyPress(event);
break; break;
case "keyup": case "keyup":
if (event.keyCode == event.DOM_VK_CONTROL) if (event.keyCode == event.DOM_VK_CONTROL) {
this.pick(); this.pick();
}
break; break;
} }
}, },
@ -555,10 +590,11 @@ var ctrlTab = {
// Also disable the <key> to ensure Shift+Ctrl+Tab never triggers // Also disable the <key> to ensure Shift+Ctrl+Tab never triggers
// Show All Tabs. // Show All Tabs.
var key_showAllTabs = document.getElementById("key_showAllTabs"); var key_showAllTabs = document.getElementById("key_showAllTabs");
if (enable) if (enable) {
key_showAllTabs.removeAttribute("disabled"); key_showAllTabs.removeAttribute("disabled");
else } else {
key_showAllTabs.setAttribute("disabled", "true"); key_showAllTabs.setAttribute("disabled", "true");
}
} }
}; };
@ -567,29 +603,36 @@ var ctrlTab = {
* All Tabs panel * All Tabs panel
*/ */
var allTabs = { var allTabs = {
get panel () { get panel() {
delete this.panel; delete this.panel;
return this.panel = document.getElementById("allTabs-panel"); return this.panel = document.getElementById("allTabs-panel");
}, },
get filterField () { get filterField() {
delete this.filterField; delete this.filterField;
return this.filterField = document.getElementById("allTabs-filter"); return this.filterField = document.getElementById("allTabs-filter");
}, },
get container () { get container() {
delete this.container; delete this.container;
return this.container = document.getElementById("allTabs-container"); return this.container = document.getElementById("allTabs-container");
}, },
get tabCloseButton () { get tabCloseButton() {
delete this.tabCloseButton; delete this.tabCloseButton;
return this.tabCloseButton = document.getElementById("allTabs-tab-close-button"); return this.tabCloseButton = document.getElementById("allTabs-tab-close-button");
}, },
get toolbarButton() document.getElementById("alltabs-button"), get toolbarButton() {
get previews () this.container.getElementsByClassName("allTabs-preview"), return document.getElementById("alltabs-button");
get isOpen () this.panel.state == "open" || this.panel.state == "showing", },
get previews() {
return this.container.getElementsByClassName("allTabs-preview");
},
get isOpen() {
return this.panel.state == "open" || this.panel.state == "showing";
},
init: function() { init: function() {
if (this._initiated) if (this._initiated) {
return; return;
}
this._initiated = true; this._initiated = true;
tabPreviews.init(); tabPreviews.init();
@ -605,16 +648,18 @@ var allTabs = {
}, },
uninit: function() { uninit: function() {
if (!this._initiated) if (!this._initiated) {
return; return;
}
gBrowser.tabContainer.removeEventListener("TabOpen", this, false); gBrowser.tabContainer.removeEventListener("TabOpen", this, false);
gBrowser.tabContainer.removeEventListener("TabAttrModified", this, false); gBrowser.tabContainer.removeEventListener("TabAttrModified", this, false);
gBrowser.tabContainer.removeEventListener("TabMove", this, false); gBrowser.tabContainer.removeEventListener("TabMove", this, false);
gBrowser.tabContainer.removeEventListener("TabClose", this, false); gBrowser.tabContainer.removeEventListener("TabClose", this, false);
while (this.container.hasChildNodes()) while (this.container.hasChildNodes()) {
this.container.removeChild(this.container.firstChild); this.container.removeChild(this.container.firstChild);
}
this._initiated = false; this._initiated = false;
}, },
@ -622,8 +667,9 @@ var allTabs = {
prefName: "browser.allTabs.previews", prefName: "browser.allTabs.previews",
readPref: function() { readPref: function() {
var allTabsButton = this.toolbarButton; var allTabsButton = this.toolbarButton;
if (!allTabsButton) if (!allTabsButton) {
return; return;
}
if (gPrefService.getBoolPref(this.prefName)) { if (gPrefService.getBoolPref(this.prefName)) {
allTabsButton.removeAttribute("type"); allTabsButton.removeAttribute("type");
@ -639,10 +685,12 @@ var allTabs = {
}, },
pick: function(aPreview) { pick: function(aPreview) {
if (!aPreview) if (!aPreview) {
aPreview = this._firstVisiblePreview; aPreview = this._firstVisiblePreview;
if (aPreview) }
if (aPreview) {
this.tabToSelect = aPreview._tab; this.tabToSelect = aPreview._tab;
}
this.close(); this.close();
}, },
@ -653,8 +701,9 @@ var allTabs = {
}, },
filter: function() { filter: function() {
if (this._currentFilter == this.filterField.value) if (this._currentFilter == this.filterField.value) {
return; return;
}
this._currentFilter = this.filterField.value; this._currentFilter = this.filterField.value;
@ -676,15 +725,15 @@ var allTabs = {
let tabstring = tab.linkedBrowser.currentURI.spec; let tabstring = tab.linkedBrowser.currentURI.spec;
try { try {
tabstring = decodeURI(tabstring); tabstring = decodeURI(tabstring);
} catch (e) {} } catch(e) {}
tabstring = tab.label + " " + tab.label.toLocaleLowerCase() + " " + tabstring; 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]); matches += tabstring.includes(filter[i]);
}
} }
if (matches < filter.length || tab.hidden || (hidePinnedTabs && tab.pinned)) { if (matches < filter.length || tab.hidden || (hidePinnedTabs && tab.pinned)) {
preview.hidden = true; preview.hidden = true;
} } else {
else {
this._visible++; this._visible++;
this._updatePreview(preview); this._updatePreview(preview);
preview.hidden = false; preview.hidden = false;
@ -708,8 +757,9 @@ var allTabs = {
this.init(); this.init();
if (this.isOpen) if (this.isOpen) {
return; return;
}
this._maxPanelHeight = Math.max(gBrowser.clientHeight, screen.availHeight / 2); this._maxPanelHeight = Math.max(gBrowser.clientHeight, screen.availHeight / 2);
this._maxPanelWidth = Math.max(gBrowser.clientWidth, screen.availWidth / 2); this._maxPanelWidth = Math.max(gBrowser.clientWidth, screen.availWidth / 2);
@ -758,27 +808,31 @@ var allTabs = {
handleEvent: function(event) { handleEvent: function(event) {
if (event.type.startsWith("Tab")) { if (event.type.startsWith("Tab")) {
var tab = event.target; var tab = event.target;
if (event.type != "TabOpen") if (event.type != "TabOpen") {
var preview = this._getPreview(tab); var preview = this._getPreview(tab);
}
} }
switch (event.type) { switch (event.type) {
case "TabAttrModified": case "TabAttrModified":
// tab attribute modified (e.g. label, crop, busy, image) // tab attribute modified (e.g. label, crop, busy, image)
if (!preview.hidden) if (!preview.hidden) {
this._updatePreview(preview); this._updatePreview(preview);
}
break; break;
case "TabOpen": case "TabOpen":
if (this.isOpen) if (this.isOpen) {
this.close(); this.close();
}
this._addPreview(tab); this._addPreview(tab);
break; break;
case "TabMove": case "TabMove":
let siblingPreview = tab.nextSibling && let siblingPreview = tab.nextSibling &&
this._getPreview(tab.nextSibling); this._getPreview(tab.nextSibling);
if (siblingPreview) if (siblingPreview) {
siblingPreview.parentNode.insertBefore(preview, siblingPreview); siblingPreview.parentNode.insertBefore(preview, siblingPreview);
else } else {
this.container.lastChild.appendChild(preview); this.container.lastChild.appendChild(preview);
}
if (this.isOpen && !preview.hidden) { if (this.isOpen && !preview.hidden) {
this._reflow(); this._reflow();
preview.focus(); preview.focus();
@ -801,23 +855,23 @@ var allTabs = {
_visible: 0, _visible: 0,
_currentFilter: null, _currentFilter: null,
get _stack () { get _stack() {
delete this._stack; delete this._stack;
return this._stack = document.getElementById("allTabs-stack"); return this._stack = document.getElementById("allTabs-stack");
}, },
get _browserCommandSet () { get _browserCommandSet() {
delete this._browserCommandSet; delete this._browserCommandSet;
return this._browserCommandSet = document.getElementById("mainCommandSet"); return this._browserCommandSet = document.getElementById("mainCommandSet");
}, },
get _previewLabelHeight () { get _previewLabelHeight() {
delete this._previewLabelHeight; delete this._previewLabelHeight;
return this._previewLabelHeight = parseInt(getComputedStyle(this.previews[0], "").lineHeight); return this._previewLabelHeight = parseInt(getComputedStyle(this.previews[0], "").lineHeight);
}, },
get _visiblePreviews () get _visiblePreviews()
Array.filter(this.previews, function(preview) !preview.hidden), Array.filter(this.previews, function(preview) !preview.hidden),
get _firstVisiblePreview () { get _firstVisiblePreview() {
if (this._visible == 0) if (this._visible == 0)
return null; return null;
var previews = this.previews; var previews = this.previews;
@ -860,10 +914,12 @@ var allTabs = {
var previews = Array.slice(this.previews); var previews = Array.slice(this.previews);
while (this.container.hasChildNodes()) while (this.container.hasChildNodes()) {
this.container.removeChild(this.container.firstChild); 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")); this.container.appendChild(document.createElement("hbox"));
}
var row = this.container.firstChild; var row = this.container.firstChild;
var colCount = 0; var colCount = 0;
@ -907,19 +963,23 @@ var allTabs = {
_getPreview: function(aTab) { _getPreview: function(aTab) {
var previews = this.previews; var previews = this.previews;
for (let i = 0; i < previews.length; i++) for (let i = 0; i < previews.length; i++) {
if (previews[i]._tab == aTab) if (previews[i]._tab == aTab) {
return previews[i]; return previews[i];
}
}
return null; return null;
}, },
_updateTabCloseButton: function(event) { _updateTabCloseButton: function(event) {
if (event && event.target == this.tabCloseButton) if (event && event.target == this.tabCloseButton) {
return; return;
}
if (this.tabCloseButton._targetPreview) { if (this.tabCloseButton._targetPreview) {
if (event && event.target == this.tabCloseButton._targetPreview) if (event && event.target == this.tabCloseButton._targetPreview) {
return; return;
}
this.tabCloseButton._targetPreview.removeAttribute("closebuttonhover"); this.tabCloseButton._targetPreview.removeAttribute("closebuttonhover");
} }
@ -954,22 +1014,25 @@ var allTabs = {
aPreview.setAttribute("label", aPreview._tab.label); aPreview.setAttribute("label", aPreview._tab.label);
aPreview.setAttribute("tooltiptext", aPreview._tab.label); aPreview.setAttribute("tooltiptext", aPreview._tab.label);
aPreview.setAttribute("crop", aPreview._tab.crop); aPreview.setAttribute("crop", aPreview._tab.crop);
if (aPreview._tab.image) if (aPreview._tab.image) {
aPreview.setAttribute("image", aPreview._tab.image); aPreview.setAttribute("image", aPreview._tab.image);
else } else {
aPreview.removeAttribute("image"); aPreview.removeAttribute("image");
}
aPreview.removeAttribute("soundplaying"); aPreview.removeAttribute("soundplaying");
aPreview.removeAttribute("muted"); aPreview.removeAttribute("muted");
if (aPreview._tab.hasAttribute("muted")) if (aPreview._tab.hasAttribute("muted")) {
aPreview.setAttribute("muted", "true"); aPreview.setAttribute("muted", "true");
else if (aPreview._tab.hasAttribute("soundplaying")) } else if (aPreview._tab.hasAttribute("soundplaying")) {
aPreview.setAttribute("soundplaying", "true"); aPreview.setAttribute("soundplaying", "true");
}
var thumbnail = tabPreviews.get(aPreview._tab); var thumbnail = tabPreviews.get(aPreview._tab);
if (aPreview.firstChild) { if (aPreview.firstChild) {
if (aPreview.firstChild == thumbnail) if (aPreview.firstChild == thumbnail) {
return; return;
}
aPreview.removeChild(aPreview.firstChild); aPreview.removeChild(aPreview.firstChild);
} }
aPreview.appendChild(thumbnail); aPreview.appendChild(thumbnail);
@ -1014,8 +1077,9 @@ var allTabs = {
switch (event.keyCode) { switch (event.keyCode) {
case event.DOM_VK_UP: case event.DOM_VK_UP:
case event.DOM_VK_DOWN: case event.DOM_VK_DOWN:
if (event.target != this.filterField) if (event.target != this.filterField) {
this._advanceFocusVertically(event); this._advanceFocusVertically(event);
}
break; break;
case event.DOM_VK_RETURN: case event.DOM_VK_RETURN:
if (event.target == this.filterField) { if (event.target == this.filterField) {
@ -1030,8 +1094,9 @@ var allTabs = {
_advanceFocusVertically: function(event) { _advanceFocusVertically: function(event) {
var preview = document.activeElement; var preview = document.activeElement;
if (!preview || preview.parentNode.parentNode != this.container) if (!preview || preview.parentNode.parentNode != this.container) {
return; return;
}
event.stopPropagation(); event.stopPropagation();
@ -1057,8 +1122,9 @@ var allTabs = {
let rows = Math.ceil(previews.length / columns); let rows = Math.ceil(previews.length / columns);
row = rows - 1; row = rows - 1;
column--; column--;
if (outOfBounds()) if (outOfBounds()) {
row--; row--;
}
} }
} else { } else {
row++; row++;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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