home *** CD-ROM | disk | FTP | other *** search
Wrap
Text File | 2005-07-29 | 281.8 KB | 9,000 lines
const NS_ERROR_MODULE_NETWORK = 2152398848; const NS_NET_STATUS_READ_FROM = NS_ERROR_MODULE_NETWORK + 8; const NS_NET_STATUS_WROTE_TO = NS_ERROR_MODULE_NETWORK + 9; const kXULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; const XHTML_NS = "http://www.w3.org/1999/xhtml"; const nsCI = Components.interfaces; const nsIWebNavigation = nsCI.nsIWebNavigation; const nsIHTMLPluginDocument = Components.interfaces.nsIHTMLPluginDocument; const PRINT_PREVIEW_REQ_WHILE_TRIDENT_LOADING_ERROR = 0; const PRINT_REQ_WHILE_TRIDENT_LOADING_ERROR = 1; const MAX_HISTORY_MENU_ITEMS = 15; var gRDF = null; var gGlobalHistory = null; var gURIFixup = null; var gPageStyleButton = null; var gLivemarksButton = null; var gCharsetMenu = null; var gLastBrowserCharset = null; var gPrevCharset = null; var gURLBar = null; var gProxyButton = null; var gProxyFavIcon = null; var gProxyDeck = null; var gNavigatorBundle = null; var gIsLoadingBlank = false; var gLastValidURLStr = ""; var gLastValidURL = null; var gHaveUpdatedToolbarState = false; var gClickSelectsAll = false; var gIgnoreFocus = false; var gIgnoreClick = false; var gMustLoadSidebar = false; var gProgressMeterPanel = null; var gProgressCollapseTimer = null; var gPrefService = null; var appCore = null; var gBrowser = null; var gSidebarCommand = ""; var gReportButton = null; // Global variable that holds the nsContextMenu instance. var gContextMenu = null; var gChromeState = null; // chrome state before we went into print preview var gFormFillPrefListener = null; var gFormHistory = null; var gFormFillEnabled = true; var gURLBarAutoFillPrefListener = null; var afDataMgr = null; var gOptout = null; var isButtonToggle = true; function showStack() { dump("\n STACK DUMP: \n"); try { var borkbork = 1 / 0; var foobar; foobar.Cannibal; throw "foobar"; } catch (e){ dump(e.stack); } } /** * We can avoid adding multiple load event listeners and save some time by adding * one listener that calls all real handlers. */ function loadEventHandlers(event) { // Filter out events that are not about the document load we are interested in if (event.originalTarget == _content.document) { try { UpdateInternetSearchResults(event); // MERC JA migration ff5->vulpine } catch (ex) { } checkForDirectoryListing(); charsetLoadListener(event); updatePageLivemarks(); } // some event handlers want to be told what the original browser/listener is var targetBrowser = null; var targetListener = null; if (gBrowser.mTabbedMode) { var targetBrowserIndex = gBrowser.getBrowserIndexForDocument(event.originalTarget); if (targetBrowserIndex == -1) return; targetBrowser = gBrowser.getBrowserAtIndex(targetBrowserIndex); targetListener = gBrowser.mTabListeners[targetBrowserIndex]; } else { targetBrowser = gBrowser.mCurrentBrowser; targetListener = null; // no listener for non-tabbed-mode } updatePageFavIcon(targetBrowser, targetListener); // update the last visited date if (targetBrowser.currentURI.spec) BMSVC.updateLastVisitedDate(targetBrowser.currentURI.spec, targetBrowser.contentDocument.characterSet); } /** * Determine whether or not the content area is displaying a page with frames, * and if so, toggle the display of the 'save frame as' menu item. **/ function getContentAreaFrameCount() { var iDF = false; try { iDF = isDocumentFrame(document.commandDispatcher.focusedWindow); } catch(e) { dump ("Caught Exception: " + e + "\n");} var saveFrameItem = document.getElementById("menu_saveFrame"); if (!content || !_content.frames.length || !iDF) saveFrameItem.setAttribute("hidden", "true"); else saveFrameItem.removeAttribute("hidden"); } //////////////////////////////// BOOKMARKS //////////////////////////////////// function UpdateBookmarksLastVisitedDate(event) { var url = getWebNavigation().currentURI.spec; if (url) { // if the URL is bookmarked, update its "Last Visited" date BMSVC.updateLastVisitedDate(url, _content.document.characterSet); } } function HandleBookmarkIcon(iconURL, addFlag) { var url = getWebNavigation().currentURI.spec if (url) { // update URL with new icon reference if (addFlag) { // MERC: TODO: ccampbell: This function call should not use nulls. // Unfortunately the function spec changed between foxforce5 and vulpine // so we will need to do more here in order for this to work properly... // See bookmarks.js for example usage. if (BMSVC) BMSVC.updateBookmarkIcon(url, null, null, 0); } else { if (BMSVC) BMSVC.removeBookmarkIcon(url); } } } function UpdateBackForwardButtons() { var backBroadcaster = document.getElementById("Browser:Back"); var forwardBroadcaster = document.getElementById("Browser:Forward"); var webNavigation = gBrowser.webNavigation; // Avoid setting attributes on broadcasters if the value hasn't changed! // Remember, guys, setting attributes on elements is expensive! They // get inherited into anonymous content, broadcast to other widgets, etc.! // Don't do it if the value hasn't changed! - dwh var backDisabled = backBroadcaster.hasAttribute("disabled"); var forwardDisabled = forwardBroadcaster.hasAttribute("disabled"); if (backDisabled == webNavigation.canGoBack) { if (backDisabled) backBroadcaster.removeAttribute("disabled"); else backBroadcaster.setAttribute("disabled", true); } if (forwardDisabled == webNavigation.canGoForward) { if (forwardDisabled) forwardBroadcaster.removeAttribute("disabled"); else forwardBroadcaster.setAttribute("disabled", true); } } // MERC - JCH : changed pageReport to removePRIcon to check for icon display function UpdatePageReport(event) { if (!gReportButton) gReportButton = document.getElementById("page-report-button"); if (gBrowser.selectedBrowser.showPageReportIcon) { gReportButton.setAttribute("blocked", "true"); if (gPrefService && gPrefService.getBoolPref("privacy.popups.firstTime")) { displayPageReportFirstTime(); // Now set the pref. gPrefService.setBoolPref("privacy.popups.firstTime", "false"); } if (gPrefService && gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) { displayNotificationBar("popup"); } } else { gReportButton.removeAttribute("blocked"); } } const gSessionHistoryObserver = { observe: function(subject, topic, data) { if (topic != "browser:purge-session-history") return; var backCommand = document.getElementById("Browser:Back"); backCommand.setAttribute("disabled", "true"); var fwdCommand = document.getElementById("Browser:Forward"); fwdCommand.setAttribute("disabled", "true"); } }; const gPopupBlockerObserver = { _reportButton: null, _kIPM: Components.interfaces.nsIPermissionManager, onUpdatePageReport: function () { if (!this._reportButton) this._reportButton = document.getElementById("page-report-button"); if (gBrowser.selectedBrowser.pageReport) { this._reportButton.setAttribute("blocked", "true"); if (gPrefService && gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) { displayNotificationBar("popup"); } } else this._reportButton.removeAttribute("blocked"); }, toggleAllowPopupsForSite: function (aEvent) { var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI; var pm = Components.classes["@mozilla.org/permissionmanager;1"] .getService(this._kIPM); var shouldBlock = aEvent.target.getAttribute("block") == "true"; var perm = shouldBlock ? this._kIPM.DENY_ACTION : this._kIPM.ALLOW_ACTION; pm.add(currentURI, "popup", perm); hideNotificationBar("popup", gBrowser); // gBrowser.hideMessage(gBrowser.selectedBrowser, "top"); }, fillPopupList: function (aEvent) { var bundle_browser = document.getElementById("bundle_browser"); // XXXben - rather than using |currentURI| here, which breaks down on multi-framed sites // we should really walk the pageReport and create a list of "allow for <host>" // menuitems for the common subset of hosts present in the report, this will // make us frame-safe. var uri = gBrowser.selectedBrowser.webNavigation.currentURI; var blockedPopupAllowSite = document.getElementById("blockedPopupAllowSite"); try { blockedPopupAllowSite.removeAttribute("hidden"); var pm = Components.classes["@mozilla.org/permissionmanager;1"] .getService(this._kIPM); if (pm.testPermission(uri, "popup") == this._kIPM.ALLOW_ACTION) { // Offer an item to block popups for this site, if a whitelist entry exists // already for it. var blockString = bundle_browser.getFormattedString("popupBlock", [uri.host]); blockedPopupAllowSite.setAttribute("label", blockString); blockedPopupAllowSite.setAttribute("block", "true"); } else { // Offer an item to allow popups for this site var allowString = bundle_browser.getFormattedString("popupAllow", [uri.host]); blockedPopupAllowSite.setAttribute("label", allowString); blockedPopupAllowSite.removeAttribute("block"); } } catch (e) { blockedPopupAllowSite.setAttribute("hidden", "true"); } var item = aEvent.target.lastChild; while (item && item.getAttribute("observes") != "blockedPopupsSeparator") { var next = item.previousSibling; item.parentNode.removeChild(item); item = next; } var pageReport = gBrowser.selectedBrowser.pageReport; if (pageReport && pageReport.length > 0) { var blockedPopupsSeparator = document.getElementById("blockedPopupsSeparator"); blockedPopupsSeparator.removeAttribute("hidden"); for (var i = 0; i < pageReport.length; ++i) { var popupURIspec = pageReport[i].popupWindowURI.spec; if (popupURIspec == "" || popupURIspec == "about:blank" || popupURIspec == uri.spec) { continue; } var menuitem = document.createElement("menuitem"); var label = bundle_browser.getFormattedString("popupShowPopupPrefix", [popupURIspec]); menuitem.setAttribute("label", label); menuitem.setAttribute("requestingWindowURI", pageReport[i].requestingWindowURI.spec); menuitem.setAttribute("popupWindowURI", popupURIspec); menuitem.setAttribute("popupWindowFeatures", pageReport[i].popupWindowFeatures); menuitem.setAttribute("oncommand", "gPopupBlockerObserver.showBlockedPopup(event);"); aEvent.target.appendChild(menuitem); } } else { var blockedPopupsSeparator = document.getElementById("blockedPopupsSeparator"); blockedPopupsSeparator.setAttribute("hidden", "true"); } var blockedPopupDontShowMessage = document.getElementById("blockedPopupDontShowMessage"); var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage"); blockedPopupDontShowMessage.setAttribute("checked", !showMessage); if (aEvent.target.localName == "popup") blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromMessage")); else blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromStatusbar")); }, _findChildShell: function (aDocShell, aSoughtURI) { var webNav = aDocShell.QueryInterface(Components.interfaces.nsIWebNavigation); if (webNav.currentURI.spec == aSoughtURI.spec) return aDocShell; var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode); for (var i = 0; i < node.childCount; ++i) { var docShell = node.getChildAt(i); docShell = this._findChildShell(docShell, aSoughtURI); if (docShell) return docShell; } return null; }, showBlockedPopup: function (aEvent) { var requestingWindowURI = Components.classes["@mozilla.org/network/standard-url;1"] .createInstance(Components.interfaces.nsIURI); requestingWindowURI.spec = aEvent.target.getAttribute("requestingWindowURI"); var popupWindowURI = aEvent.target.getAttribute("popupWindowURI"); var features = aEvent.target.getAttribute("popupWindowFeatures"); var shell = this._findChildShell(gBrowser.selectedBrowser.docShell, requestingWindowURI); if (shell) { var ifr = shell.QueryInterface(Components.interfaces.nsIInterfaceRequestor); var dwi = ifr.getInterface(Components.interfaces.nsIDOMWindowInternal); // XXXben - nsIDOMPopupBlockedEvent needs to store target, too! dwi.open(popupWindowURI, "", features); } }, editPopupSettings: function () { var host = ""; try { var uri = gBrowser.selectedBrowser.webNavigation.currentURI; host = uri.host; } catch (e) { } var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var existingWindow = wm.getMostRecentWindow("exceptions"); if (existingWindow) { existingWindow.setHost(host); existingWindow.focus(); } else { var params = { blockVisible: false, allowVisible: true, prefilledHost: host, permissionType: "popup" }; window.openDialog("chrome://browser/content/cookieviewer/CookieExceptions.xul?permission=popup", "_blank", "chrome,modal,resizable=yes", params); } }, dontShowMessage: function () { var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage"); var firstTime = gPrefService.getBoolPref("privacy.popups.firstTime"); // If the info message is showing at the top of the window, and the user has never // hidden the message before, show an info box telling the user where the info // will be displayed. if (showMessage && firstTime) this._displayPageReportFirstTime(); gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage); hideNotificationBar("popup", gBrowser); }, _displayPageReportFirstTime: function () { window.openDialog("chrome://browser/content/pageReportFirstTime.xul", "_blank", "dependent"); } }; const gXPInstallObserver = { _findChildShell: function (aDocShell, aSoughtShell) { if (aDocShell == aSoughtShell) return aDocShell; var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode); for (var i = 0; i < node.childCount; ++i) { var docShell = node.getChildAt(i); docShell = this._findChildShell(docShell, aSoughtShell); if (docShell == aSoughtShell) return docShell; } return null; }, _getBrowser: function (aDocShell) { var tabbrowser = getBrowser(); for (var i = 0; i < tabbrowser.browsers.length; ++i) { var browser = tabbrowser.getBrowserAtIndex(i); var soughtShell = aDocShell; var shell = this._findChildShell(browser.docShell, soughtShell); if (shell) return browser; } return null; }, observe: function (aSubject, aTopic, aData) { var brandBundle = document.getElementById("bundle_brand"); var browserBundle = document.getElementById("bundle_browser"); switch (aTopic) { case "xpinstall-install-blocked": var shell = aSubject.QueryInterface(Components.interfaces.nsIDocShell); browser = this._getBrowser(shell); if (browser) { var extraData = new Array(); extraData.push(shell); displayNotificationBar("xpi", extraData); } break; case "xpinstall-install-edit-prefs": var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var optionsWindow = wm.getMostRecentWindow("Browser:Options"); if (optionsWindow) { optionsWindow.focus(); optionsWindow.switchPage("catFeaturesbutton"); } else openDialog("chrome://browser/content/pref/pref.xul", "PrefWindow", "chrome,titlebar,resizable,modal", "catFeaturesbutton"); var tabbrowser = getBrowser(); // tabbrowser.hideMessage(tabbrowser.selectedBrowser, "top"); hideNotificationBar("xpi", tabbrowser); break; case "xpinstall-install-edit-permissions": var browser = this._getBrowser(aSubject.QueryInterface(Components.interfaces.nsIDocShell)); if (browser) { var webNav = aSubject.QueryInterface(Components.interfaces.nsIWebNavigation); var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var existingWindow = wm.getMostRecentWindow("exceptions"); if (existingWindow) { existingWindow.setHost(webNav.currentURI.host); existingWindow.focus(); } else { var params = { blockVisible: false, allowVisible: true, prefilledHost: webNav.currentURI.host, permissionType: "install" }; window.openDialog("chrome://browser/content/cookieviewer/CookieExceptions.xul?permission=install", "_blank", "chrome,modal,resizable=yes", params); } var tabbrowser = getBrowser(); // tabbrowser.hideMessage(tabbrowser.selectedBrowser, "top"); hideNotificationBar("xpi", tabbrowser); } break; } } }; function Startup() { dump("Startup()\n"); gBrowser = document.getElementById("content"); // Allows Trident to update security (SSL) state; see nsHTMLPluginDocument.cpp. // We can easily get fields from the window, but not from the browser object. window.securityUI = gBrowser.securityUI; gPrefService = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); titlebar.init(); moveMenubar(); // Mercurial START sitecontrols.initServices(); perfmon.initServices(); search.Init(); passcardUtilsInit(); // need to set up this observer early to deal with field highlighting in Passcards/Datacards var docIsFillable=new docEndObserver(); var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); os.addObserver(docIsFillable, "EndDocumentLoad", false); // Mercurial END var uriToLoad = null; // Check for window.arguments[0]. If present, use that for uriToLoad. if ("arguments" in window && window.arguments.length >= 1 && window.arguments[0]) uriToLoad = window.arguments[0]; // Bug #298255 try { if (makeURL(uriToLoad).schemeIs("chrome")) { dump("Preventing external load of chrome: URI\n"); window.close(); return; } } catch(e) {} // MERC (DP): on first startup of browser, we show the Netscape welcome page pref = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); // JMC: Fix this, it causes no pages on startup bug var firstTime = pref.getBoolPref("browser.startup.firsttime"); if (firstTime) { uriToLoad = uriToLoad + '|' + pref.getCharPref("browser.startup.welcomepage"); pref.setBoolPref("browser.startup.firsttime", false); } // MERC (rpaul) if window shaping is define, move the menu to the left and move // the throbber to the right // read the property from the properties file // N.B. for future themers this file should be placed in the theme jar var windowShapingBundle = document.getElementById("drawOsBorder"); var drawOsWindowBorder = windowShapingBundle.getString("ShowOSTitleBar"); if (drawOsWindowBorder) { if (drawOsWindowBorder == 1) { gPrefService.setBoolPref("browser.menu_in_titlebar", false); moveMenubar(); // remove toggle menu bar position from context menu var toggleMenuItem = document.getElementById('menuitem_toggleMenuBar'); if (toggleMenuItem) { document.getElementById('toolbar-context-menu').removeChild(toggleMenuItem); } // remove the throbber from the top-box var throbber = document.getElementById('throbber-box'); if (throbber) { document.getElementById('topstack').removeChild(throbber); } } else { // not window shaping, so remove throbber as a toolbar item var navBar = document.getElementById('nav-bar'); if (navBar) { var throbberToolbarItem = document.getElementById('throbber-button'); if (throbberToolbarItem) { navBar.removeChild(throbberToolbarItem); // remove from default toolbar set var defaultSet = navBar.getAttribute('defaultset'); var strPos; strPos = defaultSet.indexOf('throbber-button'); if (strPos != -1) { navBar.setAttribute('defaultset', defaultSet.substring(0, strPos-1)); } } } } } gIsLoadingBlank = uriToLoad == "about:blank"; if (!gIsLoadingBlank) prepareForStartup(); // only load url passed in when we're not page cycling if (uriToLoad && !gIsLoadingBlank) { if ("arguments" in window && window.arguments.length >= 3) loadURI(uriToLoad, window.arguments[2], null); else { loadOneOrMoreURIs(uriToLoad); // MERC (DP): select the about tab browsing tab on first time if (firstTime) { var browserTabs = gBrowser.mTabContainer.childNodes; gBrowser.selectedTab = browserTabs[browserTabs.length - 1]; } } } // Determine whether to show the sidebar var sidebarBox = document.getElementById("sidebar-box"); var sidebarSplitter = document.getElementById("sidebar-splitter"); var sidebarCmd = null; if (window.opener && !window.opener.closed) { if (window.opener.gFindMode == FIND_NORMAL) { var openerFindBar = window.opener.document.getElementById("FindToolbar"); if (openerFindBar && !openerFindBar.hidden) openFindBar(); } var openerSidebarBox = window.opener.document.getElementById("sidebar-box"); // The opener can be the hidden window too, if we're coming from the state // where no windows are open, and the hidden window has no sidebar box. if (openerSidebarBox && !openerSidebarBox.hidden) { sidebarBox.setAttribute("width", openerSidebarBox.boxObject.width); if (openerSidebarBox.hasAttribute("sidebarcommand")) { sidebarCmd = openerSidebarBox.getAttribute("sidebarcommand"); sidebarBox.setAttribute("sidebarcommand", sidebarCmd); } } else { // The opener sidebar-box is either hidden or non-existent sidebarBox.hidden = true; sidebarSplitter.hidden = true; } } else { // There is no opener if (sidebarBox.hasAttribute("sidebarcommand")) sidebarCmd = sidebarBox.getAttribute("sidebarcommand"); } if (sidebarCmd) { gMustLoadSidebar = true; sidebarBox.hidden = false; sidebarSplitter.hidden = false; document.getElementById(sidebarCmd).setAttribute("checked", "true"); } // Certain kinds of automigration rely on this notification to complete their // tasks BEFORE the browser window is shown. var obs = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); obs.notifyObservers(null, "browser-window-before-show", ""); // Set a sane starting width/height for all resolutions on new profiles. if (!document.documentElement.hasAttribute("width")) { var defaultWidth = 994, defaultHeight; if (screen.availHeight <= 600) { document.documentElement.setAttribute("sizemode", "maximized"); defaultWidth = 610; defaultHeight = 450; } else { // Create a narrower window for large or wide-aspect displays, to suggest // side-by-side page view. if ((screen.availWidth / 2) >= 800) defaultWidth = (screen.availWidth / 2) - 20; defaultHeight = screen.availHeight - 10; } document.documentElement.setAttribute("width", defaultWidth); document.documentElement.setAttribute("height", defaultHeight); } // Initialize optout list if (!gOptout) { var optoutInstance = Components.classes['@mozilla.org/optout;1'].getService(); gOptout = optoutInstance.QueryInterface(Components.interfaces.nsIOptOutService); if (!gOptout) dump('\nbrowser.js: gOptout has NOT been initialized!\n\n\n'); } if (gOptout) gOptout.RefreshSiteList(); // update tab chrome gBrowser.updateChromeWhenLastTab(); setTimeout(delayedStartup, 0); } function prepareForStartup() { dump ("prepareForStartup()\n"); gURLBar = document.getElementById("urlbar"); gNavigatorBundle = document.getElementById("bundle_browser"); gProgressMeterPanel = document.getElementById("statusbar-progresspanel"); //gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver.onUpdatePageReport, false); gBrowser.addEventListener("DOMUpdatePageReport", UpdatePageReport, false); gBrowser.addEventListener("DOMLinkAdded", livemarkOnLinkAdded, false); gBrowser.addEventListener("PluginNotFound", gMissingPluginInstaller.newMissingPlugin, false); var webNavigation; try { // Create the browser instance component. appCore = Components.classes["@mozilla.org/appshell/component/browser/instance;1"] .createInstance(Components.interfaces.nsIBrowserInstance); if (!appCore) throw "couldn't create a browser instance"; webNavigation = getWebNavigation(); if (!webNavigation) throw "no XBL binding for browser"; } catch (e) { alert("Error launching browser window:" + e); window.close(); // Give up. return; } // initialize observers and listeners // and give C++ access to gBrowser window.XULBrowserWindow = new nsBrowserStatusHandler(); window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIXULWindow) .XULBrowserWindow = window.XULBrowserWindow; gBrowser.docShell .QueryInterface(nsCI.nsIDocShellTreeItem) .rootTreeItem .QueryInterface(nsCI.nsIInterfaceRequestor) .getInterface(nsCI.nsIDOMWindow) .QueryInterface(nsCI.nsIInterfaceRequestor) .getInterface(nsCI.nsIDOMWindowUtils) .browserDOMWindow = new nsBrowserAccess(); window.browserContentListener = new nsBrowserContentListener(window, gBrowser); // set default character set if provided if ("arguments" in window && window.arguments.length > 1 && window.arguments[1]) { if (window.arguments[1].indexOf("charset=") != -1) { var arrayArgComponents = window.arguments[1].split("="); if (arrayArgComponents) { //we should "inherit" the charset menu setting in a new window getMarkupDocumentViewer().defaultCharacterSet = arrayArgComponents[1]; } } } // Initialize browser instance.. appCore.setWebShellWindow(window); // Wire up session and global history before any possible // progress notifications for back/forward button updating webNavigation.sessionHistory = Components.classes["@mozilla.org/browser/shistory;1"] .createInstance(Components.interfaces.nsISHistory); // enable global history gBrowser.docShell.QueryInterface(Components.interfaces.nsIDocShellHistory).useGlobalHistory = true; const selectedBrowser = gBrowser.selectedBrowser; if (selectedBrowser.securityUI) selectedBrowser.securityUI.init(selectedBrowser.contentWindow); // hook up UI through progress listener gBrowser.addProgressListener(window.XULBrowserWindow, Components.interfaces.nsIWebProgress.NOTIFY_ALL); } //Added by SLiu, for customize bookmarks toolbar function populateBookmarks() { var bt = document.getElementById("bookmarks-ptf"); if (bt) { var btf = BMSVC.getBookmarksToolbarFolder().Value; bt.ref = btf; document.getElementById("bookmarks-chevron").ref = btf; bt.database.AddObserver(BookmarksToolbarRDFObserver); bt.controllers.appendController(BookmarksMenuController); bt.builder.rebuild(); } var bm = document.getElementById("bookmarks-menu"); bm.controllers.appendController(BookmarksMenuController); } function ShowPhishingSiteWarning() { displayNotificationBar("phishing"); } function ShowSpywareSiteWarning() { displayNotificationBar("spyware"); } function docEndObserver() { } docEndObserver.prototype = { // Data is a URL // Subject is ? observe: function (subject, topic, data) { if (topic == "EndDocumentLoad") { // dump ("EndDocumentLoad... \n"); // JMC: Check to attach formfill controller, if required. gBrowser.attachFormFill(); // JMC - disabling 404 //if (this.checkRoll(subject, data)) // return; var docType = String(gBrowser.contentDocument.contentType); if (docType.indexOf("/xml") > 0) { var isRss = true; if (getWebNavigation().currentURI.spec.indexOf(".rdf") > -1) ; else if(getWebNavigation().currentURI.spec.indexOf(".rss") > -1) ; else if(gBrowser.contentDocument.getElementsByTagName('rss').length) ; else if (gBrowser.contentDocument.getElementsByTagNameNS('http://my.netscape.com/rdf/simple/0.9/','channel').length) ; // version 0.9 else if (gBrowser.contentDocument.getElementsByTagNameNS('http://purl.org/rss/1.0/','channel').length) ; // version 1.0 else if (gBrowser.contentDocument.getElementsByTagNameNS('http://purl.org/atom/ns#draft-ietf-atompub-format-08', 'entry').length) ; // atom version else { isRss = false; } if(isRss) { displayNotificationBar('rss'); } } this.endDocLoad(subject); } }, checkRoll : function (aWindow, aURL) { if (aWindow) { var titleNodes = gBrowser.contentDocument.getElementsByTagName('title'); for (var i=0; i < titleNodes.length; i++) { for (j=0; j < titleNodes.item(i).childNodes.length; j++) { if (titleNodes.item(i).childNodes[j].nodeValue.indexOf("404") > -1) { // Find an h2 node with the text 'Error 404' var h2Nodes = gBrowser.contentDocument.getElementsByTagName('h2'); dump ("ROLL: Found " + h2Nodes.length + " h2 nodes\n"); for (var i=0; i < h2Nodes.length; i++) { for (j=0; j < h2Nodes.item(i).childNodes.length; j++) { if (h2Nodes.item(i).childNodes[j].nodeValue.indexOf("Error 404") > -1) { var newURL = gPrefService.getCharPref('browser.redirect404.URL'); newURL += aURL; loadURI(newURL, null, null); return true; } } } var h1Nodes = gBrowser.contentDocument.getElementsByTagName('h1'); for (var i=0; i < h1Nodes.length; i++) { for (j=0; j < h1Nodes.item(i).childNodes.length; j++) { if ((h1Nodes.item(i).childNodes[j].nodeValue.indexOf("Error 404") > -1) || (h1Nodes.item(i).childNodes[j].nodeValue == "Not Found")) { var newURL = gPrefService.getCharPref('browser.redirect404.URL'); newURL += aURL; loadURI(newURL, null, null); return true; } } } } } } } return false; }, endDocLoad : function (aWindow) { // dump('***** EndDocLoad: gCurrentNotificationBar: ' + gCurrentNotificationBar + '\n'); // MERC JVL: should not set to null before the message bar can clean itself up //gCurrentNotificationBar = null; if (blacklistUtils.IsSiteInPhishList(gBrowser.currentURI)) { displayNotificationBar("phishing",[gBrowser.currentURI]); // ShowPhishingSiteWarning(); } else if (blacklistUtils.IsSiteInSpywareList(gBrowser.currentURI)) { displayNotificationBar("spyware",[gBrowser.currentURI]); } // MERC - JCH: When page has finished loading, check for password fields // If we invoke the passcard notification bar, don't do the form fill check var bIsPasscardable = CheckForPasscardField(); var hpDoc = getTridentDocument(); if (!hpDoc) { // TODO JVL : see note in isPasscardHighlight() if (bIsPasscardable && isPasscardHighlight() && !PasscardIsSiteBlacklisted(gBrowser.currentURI)) { passcardDebug('highlighting in GECKO\n'); // highlight passcard fields in the root document, // then the ones in each frame this.highlightPasscardFields(gBrowser.contentDocument); } } // Check if page datacard fillable if (!bIsPasscardable) datacardUtils.DoPageLoadedCheck(); }, // observe // highlight passcard fields in the current document highlightPasscardFields : function (doc) // JMC/JVL { if (!doc) return; // highlight if we have a Passcard for the site var domain = new Object(); gPasscardMgr.getDomain(gBrowser.currentURI, domain); passcardDebug('HighlightPasscardFields() - host: ' + gBrowser.currentURI.host + ', domain: ' + domain.value + '\n'); if (!GetFirstPasscardForSite(domain.value)) { var defaultPasscard = GetDefaultPasscard(); if (!defaultPasscard) return; // do not highlight if the Default Passcard's // username and password fields are blank if (defaultPasscard.user.length < 1 || defaultPasscard.password.length < 1) { return; } } var kBackgroundColor = "#ffff66"; var usernameField; var tagList = doc.getElementsByTagName('input'); for (var i = 0; i < tagList.length; i++) { var tag = tagList.item(i); if (tag) { if (tag.getAttribute('type') == 'text' || tag.getAttribute('type') == null) { usernameField = tag; } if (tag.getAttribute('type') == 'password') { tag.style.backgroundColor = kBackgroundColor; if (usernameField) { usernameField.style.backgroundColor = kBackgroundColor; usernameField = null; } } } } this.highlightPasscardFieldsInFrames(doc, 'iframe'); this.highlightPasscardFieldsInFrames(doc, 'frame'); this.highlightPasscardFieldsInFrames(doc, 'object'); }, // highlight passcard fields in each 'frame' ('iframe' and 'object' as well) document highlightPasscardFieldsInFrames : function(doc, elementName) { var iframeElements = doc.getElementsByTagName(elementName); for (var i = 0; i < iframeElements.length; i++) { var iframeElement = iframeElements.item(i); if (iframeElement) { this.highlightPasscardFields(iframeElement.contentDocument); } } } }; // end docEndObserver function toggleMenubar() { // True = Right, False = Left gPrefService.setBoolPref("browser.menu_in_titlebar", gPrefService.getBoolPref("browser.menu_in_titlebar") != true); moveMenubar(); } function moveMenubar() { var mainMenu = document.getElementById('titlebar-menu-stack'); var menuSpacer = document.getElementById('titlebar-menu-replacement'); if (!gPrefService.getPrefType("browser.menu_in_titlebar")) return; if (gPrefService.getBoolPref("browser.menu_in_titlebar") != (mainMenu.parentNode.localName == 'toolbox')) return; var menuWidth=mainMenu.boxObject.width; mainMenu.parentNode.removeChild(mainMenu); var titlebarContainer = document.getElementById('titlebar-container'); if (gPrefService.getBoolPref("browser.menu_in_titlebar")) { // dump(' Moving from toolbox to titlebar\n'); if (menuSpacer) menuSpacer.parentNode.removeChild(menuSpacer); titlebarContainer.appendChild(mainMenu); // document.getElementById('mainMenuPopupBroadcaster').setAttribute('position', 'after_end'); } else { // dump(' Moving from titlebar to toolbox\n'); var toolbox = document.getElementById('navigator-toolbox'); toolbox.insertBefore(mainMenu, toolbox.firstChild); menuSpacer=document.createElement("spacer"); menuSpacer.setAttribute("width",menuWidth + ""); menuSpacer.setAttribute("id","titlebar-menu-replacement"); menuSpacer.setAttribute("class",'titlebar-menu-stack'); titlebarContainer.appendChild(menuSpacer); //document.getElementById('mainMenuPopupBroadcaster').setAttribute('position', 'after_start'); } } function delayedStartup() { dump ("delayedStartup()\n"); var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); os.addObserver(gSessionHistoryObserver, "browser:purge-session-history", false); // We have to do this because we manually hook up history for the first browser in prepareForStartup os.addObserver(gBrowser.browsers[0], "browser:purge-session-history", false); os.addObserver(gXPInstallObserver, "xpinstall-install-blocked", false); os.addObserver(gXPInstallObserver, "xpinstall-install-edit-prefs", false); os.addObserver(gXPInstallObserver, "xpinstall-install-edit-permissions", false); os.addObserver(gMissingPluginInstaller, "missing-plugin", false); // MERC - JCH : To check if history is cleared if (!gGlobalHistory) gGlobalHistory = Components.classes["@mozilla.org/browser/global-history;2"] .getService(Components.interfaces.nsIBrowserHistory); SetHistoryButton(); // JMC: Set anonymous mode button state BrowserOffline.init(); if (gURLBar && document.documentElement.getAttribute("chromehidden").indexOf("toolbar") != -1) { gURLBar.setAttribute("readonly", "true"); gURLBar.setAttribute("enablehistory", "false"); } if (gIsLoadingBlank) prepareForStartup(); if (gURLBar) gURLBar.addEventListener("dragdrop", URLBarOnDrop, true); // resizeSearchBar(); // JMC Disabled for beta // loads the services initServices(); // Initialize SPUI if (spui) { // spui.RefreshComponentList(); setTimeout( "spui.RefreshComponentList()", 0); // this was causing crashes! } else dump('\nbrowser.js: SPUI has NOT been initialized!\n\n\n'); initBMService(); gBrowser.addEventListener("load", function(evt) { setTimeout(loadEventHandlers, 0, evt); }, true); // JMC - Do this earlier if (window.windowState == window.STATE_MAXIMIZED) { // call it, as we deal with the foxy theme in nsWindow window.maximize(); // MERC - Stevo (removed to fix bug with missing title bar on foxy // theme when closed in maximized state and restarted. document.getElementById('main-window').setAttribute('sizemode', 'maximized'); document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down'; isButtonToggle = false; } window.addEventListener("keypress", ctrlNumberTabSelection, false); //if (gMustLoadSidebar) { // var sidebar = document.getElementById("sidebar"); // var sidebarBox = document.getElementById("sidebar-box"); // sidebar.setAttribute("src", sidebarBox.getAttribute("src")); //} initFindBar(); // now load bookmarks BMSVC.readBookmarks(); var bt = document.getElementById("bookmarks-ptf"); if (bt) { var btf = BMSVC.getBookmarksToolbarFolder().Value; bt.ref = btf; document.getElementById("bookmarks-chevron").ref = btf; bt.database.AddObserver(BookmarksToolbarRDFObserver); bt.controllers.appendController(BookmarksMenuController); } var bm = document.getElementById("bookmarks-menu"); bm.controllers.appendController(BookmarksMenuController); //JA ff5->vulp //<Modified by SLiu populateBookmarks(); //SLiu> window.addEventListener("resize", onWindowResize, false); // called when we go into full screen, even if it is // initiated by a web page script window.addEventListener("fullscreen", onFullScreen, false); var element; if (gIsLoadingBlank && gURLBar && !gURLBar.hidden && !gURLBar.parentNode.parentNode.collapsed) element = gURLBar; else element = _content; // This is a redo of the fix for jag bug 91884 var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); if (window == ww.activeWindow) { // JMC - URLBar Focus issue debugging dump ("delayed Startup, setting focus to " + element.id + "\n"); element.focus(); } else { // set the element in command dispatcher so focus will restore properly // when the window does become active if (element instanceof Components.interfaces.nsIDOMWindow) { document.commandDispatcher.focusedWindow = element; document.commandDispatcher.focusedElement = null; } else if (element instanceof Components.interfaces.nsIDOMElement) { document.commandDispatcher.focusedWindow = element.ownerDocument.defaultView; document.commandDispatcher.focusedElement = element; } } // This trashes the urlbar favicon so carefully set up in tabbrowser.xml... //SetPageProxyState("invalid", null); var toolbox = document.getElementById("navigator-toolbox"); toolbox.customizeDone = BrowserToolboxCustomizeDone; // Enable/Disable Form Fill gFormFillPrefListener = new FormFillPrefListener(); var pbi = gPrefService.QueryInterface(Components.interfaces.nsIPrefBranchInternal); pbi.addObserver(gFormFillPrefListener.domain, gFormFillPrefListener, false); gFormFillPrefListener.toggleFormFill(); // Enable/Disable URL Bar Auto Fill gURLBarAutoFillPrefListener = new URLBarAutoFillPrefListener(); pbi.addObserver(gURLBarAutoFillPrefListener.domain, gURLBarAutoFillPrefListener, false); pbi.addObserver(gHomeButton.prefDomain, gHomeButton, false); //gHomeButton.updateTooltip(); DO NOT USE..this is set in the browser.xul file // Initialize Plugin Overrides const kOverridePref = "browser.download.pluginOverrideTypes"; if (gPrefService.prefHasUserValue(kOverridePref)) { var types = gPrefService.getCharPref(kOverridePref); types = types.split(","); const kPluginOverrideTypesNotHandled = "browser.download.pluginOverrideTypesNotHandled"; var catman = Components.classes["@mozilla.org/categorymanager;1"].getService(Components.interfaces.nsICategoryManager); var typesNotHandled = ""; for (var i = 0; i < types.length; ++i) { // Keep track of all overrides for plugins that aren't actually installed, // so we know not to show them in the plugin configuration dialog BUT // don't delete the overrides such that when the user actually installs the // plugin in this build their preferences are remembered. try { var catEntry = catman.getCategoryEntry("Gecko-Content-Viewers", types[i]); } catch (e) { catEntry = ""; } if (catEntry == "") typesNotHandled += types[i] + ","; catman.deleteCategoryEntry("Gecko-Content-Viewers", types[i], false); } if (typesNotHandled) { typesNotHandled = typesNotHandled.substr(0, typesNotHandled.length - 1); gPrefService.setCharPref(kPluginOverrideTypesNotHandled, typesNotHandled); } else if (gPrefService.prefHasUserValue(kPluginOverrideTypesNotHandled)) gPrefService.clearUserPref(kPluginOverrideTypesNotHandled); } gClickSelectsAll = gPrefService.getBoolPref("browser.urlbar.clickSelectsAll"); clearObsoletePrefs(); // Perform default browser checking (after window opens). var shell = getShellService(); if (shell) { var shouldCheck = shell.shouldCheckDefaultBrowser; if (shouldCheck && !shell.isDefaultBrowser(true)) { var brandBundle = document.getElementById("bundle_brand"); var shellBundle = document.getElementById("bundle_shell"); var brandShortName = brandBundle.getString("brandShortName"); var promptTitle = shellBundle.getString("setDefaultBrowserTitle"); var promptMessage = shellBundle.getFormattedString("setDefaultBrowserMessage", [brandShortName]); var checkboxLabel = shellBundle.getFormattedString("setDefaultBrowserDontAsk", [brandShortName]); const IPS = Components.interfaces.nsIPromptService; var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(IPS); var checkEveryTime = { value: shouldCheck }; var rv = ps.confirmEx(window, promptTitle, promptMessage, (IPS.BUTTON_TITLE_YES * IPS.BUTTON_POS_0) + (IPS.BUTTON_TITLE_NO * IPS.BUTTON_POS_1), null, null, null, checkboxLabel, checkEveryTime); if (rv == 0) shell.setDefaultBrowser(true, false); shell.shouldCheckDefaultBrowser = checkEveryTime.value; } } else { // We couldn't get the shell service; go hide the mail toolbar button. var mailbutton = document.getElementById("mail-button"); if (mailbutton) mailbutton.hidden = true; } // START Mercurial // Initialize Webmail webmail.Init(); // For toolbar overflow var nb = document.getElementById('nav-bar'); nb.enableOverflowMenu = true; var pt = document.getElementById('PersonalToolbar'); if (pt) { pt.enableOverflowMenu = true; } // TODO: This form submission observer should really be singleton // (ie., one-per-application, not one-per-browser-window) datacardUtils.InitSubmitObserver(); // END Mercurial var updatePanel = document.getElementById("softwareupdate"); try { updatePanel.init(); } catch (e) { dump("updatePanel failed with " + e + "\n"); } // BiDi UI if (isBidiEnabled()) { document.getElementById("documentDirection-separator").hidden = false; document.getElementById("documentDirection-swap").hidden = false; document.getElementById("textfieldDirection-separator").hidden = false; document.getElementById("textfieldDirection-swap").hidden = false; } // display the correct engine on startup UpdateStatusBarEngineIcon(); } function resizeSearchBar() { var searchBar = document.getElementById("searchbar"); if(searchBar) { searchBar.addEventListener("dragdrop", SearchBarOnDrop, true); if (gPrefService.getPrefType("browser.search.size")) { var searchSize = gPrefService.getCharPref("browser.search.size"); // this.parentNode.style.width = searchSize; // dump("SEARCH: Setting the checked attribute for search size\n"); var sizeMenuItem = document.getAnonymousElementByAttribute(searchBar, "value", searchSize); if (sizeMenuItem) { // dump("SEARCH: Calling doCommand on the sizeMenuItem\n"); sizeMenuItem.doCommand(); // sizeMenuItem.setAttribute('checked', 'true'); } } } } function Shutdown() { var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); os.removeObserver(gSessionHistoryObserver, "browser:purge-session-history"); os.removeObserver(gBrowser.browsers[0], "browser:purge-session-history"); os.removeObserver(gXPInstallObserver, "xpinstall-install-blocked"); os.removeObserver(gXPInstallObserver, "xpinstall-install-edit-permissions"); os.removeObserver(gXPInstallObserver, "xpinstall-install-edit-prefs"); os.removeObserver(gMissingPluginInstaller, "missing-plugin"); try { gBrowser.removeProgressListener(window.XULBrowserWindow); } catch (ex) { } var bt = document.getElementById("bookmarks-ptf"); if (bt) { try { bt.database.RemoveObserver(BookmarksToolbarRDFObserver); bt.controllers.removeController(BookmarksMenuController); } catch (ex) { } } try { var bm = document.getElementById("bookmarks-menu"); bm.controllers.removeController(BookmarksMenuController); } catch (ex) { } try { var pbi = gPrefService.QueryInterface(Components.interfaces.nsIPrefBranchInternal); pbi.removeObserver(gFormFillPrefListener.domain, gFormFillPrefListener); pbi.removeObserver(gURLBarAutoFillPrefListener.domain, gURLBarAutoFillPrefListener); pbi.removeObserver(gHomeButton.prefDomain, gHomeButton); } catch (ex) { } BrowserOffline.uninit(); uninitFindBar(); var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(); var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator); var enumerator = windowManagerInterface.getEnumerator(null); enumerator.getNext(); if (!enumerator.hasMoreElements()) { document.persist("sidebar-box", "sidebarcommand"); document.persist("sidebar-box", "width"); document.persist("sidebar-box", "src"); document.persist("sidebar-title", "value"); } window.XULBrowserWindow.destroy(); window.XULBrowserWindow = null; window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIXULWindow) .XULBrowserWindow = null; gBrowser.docShell .QueryInterface(nsCI.nsIDocShellTreeItem) .rootTreeItem .QueryInterface(nsCI.nsIInterfaceRequestor) .getInterface(nsCI.nsIDOMWindow) .QueryInterface(nsCI.nsIInterfaceRequestor) .getInterface(nsCI.nsIDOMWindowUtils) .browserDOMWindow = null; window.browserContentListener.close(); // Close the app core. if (appCore) appCore.close(); } function FormFillPrefListener() { gBrowser.attachFormFill(); } FormFillPrefListener.prototype = { domain: "browser.formfill.enable", observe: function (aSubject, aTopic, aPrefName) { if (aTopic != "nsPref:changed" || aPrefName != this.domain) return; this.toggleFormFill(); }, toggleFormFill: function () { try { gFormFillEnabled = gPrefService.getBoolPref(this.domain); } catch (e) { } var formController = Components.classes["@mozilla.org/satchel/form-fill-controller;1"].getService(Components.interfaces.nsIAutoCompleteInput); formController.disableAutoComplete = !gFormFillEnabled; var searchBar = document.getElementsByTagName("searchbar"); for (var i=0; i<searchBar.length;i++) { if (gFormFillEnabled) searchBar[i].removeAttribute("disableautocomplete"); else searchBar[i].setAttribute("disableautocomplete", "true"); } } } function URLBarAutoFillPrefListener() { this.toggleAutoFillInURLBar(); } URLBarAutoFillPrefListener.prototype = { domain: "browser.urlbar.autoFill", observe: function (aSubject, aTopic, aPrefName) { if (aTopic != "nsPref:changed" || aPrefName != this.domain) return; this.toggleAutoFillInURLBar(); }, toggleAutoFillInURLBar: function () { if (!gURLBar) return; var prefValue = false; try { prefValue = gPrefService.getBoolPref(this.domain); } catch (e) { } if (prefValue) gURLBar.setAttribute("completedefaultindex", "true"); else gURLBar.removeAttribute("completedefaultindex"); } } function ctrlNumberTabSelection(event) { if (event.altKey && event.keyCode == KeyEvent.DOM_VK_RETURN) { // XXXblake Proper fix is to just check whether focus is in the urlbar. However, focus with the autocomplete widget is all // hacky and broken and there's no way to do that right now. So this just patches it to ensure that alt+enter works when focus // is on a link. if (!(document.commandDispatcher.focusedElement instanceof HTMLAnchorElement)) { // Don't let winxp beep on ALT+ENTER, since the URL bar uses it. event.preventDefault(); return; } } if (!event.ctrlKey) return; //JA const MAX_TABS = 80;//defined in nsGUIEvent.h var index = event.charCode - 49;//49 == '0' if (index < 0 || (index > 8 && (index<0x0700 || index>0x0700+MAX_TABS)) ) return; if(index>=0x0700) index = index-0x0700; //JA end if (index >= gBrowser.tabContainer.childNodes.length) return; var oldTab = gBrowser.selectedTab; var newTab = gBrowser.tabContainer.childNodes[index]; if (newTab != oldTab) { oldTab.selected = false; gBrowser.selectedTab = newTab; } event.preventDefault(); event.preventBubble(); event.preventCapture(); event.stopPropagation(); } function gotoHistoryIndex(aEvent) { var index = aEvent.target.getAttribute("index"); if (!index) return false; /*Mercurial Start */ //JA check if HTML plugin var hpDoc = getTridentDocument(); if(hpDoc) { var docshell=getWebNavigation();; var sessionHistory = docshell.sessionHistory; sessionHistory.setCurrentIndex(index); var loadedByGecko = false; try { var currURI = new Object(); hpDoc.getURIAtIndex(index, currURI); if(currURI) { var site = currURI.value.host; var bControlled=sitecontrols.SCSVC.isControlledSite(site); if(bControlled) { var displayEngine=sitecontrols.SCSVC.readSiteControl(site, "displayEngine"); if(displayEngine=="Gecko") { loadedByGecko=true; hpDoc.geckoLoadURI(uri, Components.interfaces.nsIDocShellLoadInfo.loadBypassHistory); //hpDoc.geckoLoadURI(currURI.value, 10); } } } } catch(ex){dump("GoForward check sitecontrols engine failed!!!\n");} if(!loadedByGecko) hpDoc.goCmd(-index); UpdateBackForwardButtons(); }/*Mercurial Finish*/ else { var where = whereToOpenLink(aEvent); if (where == "current") { // Normal click. Go there in the current tab and update session history. try { getWebNavigation().gotoIndex(index); } catch(ex) { return false; } return true; } else { // Modified click. Go there in a new tab/window. // This code doesn't copy history or work well with framed pages. var sessionHistory = getWebNavigation().sessionHistory; var entry = sessionHistory.getEntryAtIndex(index, false); var url = entry.URI.spec; openUILinkIn(url, where); return true; } } } function BrowserForward(aEvent, aIgnoreAlt) { var docshell = getWebNavigation(); var sessionHistory = docshell.sessionHistory; var count = sessionHistory.count; var index = sessionHistory.index; //JA ff5->vulp + modif if (index >= count-1) return;//error call // Try to get handle on Trident var hpDoc = getTridentDocument(); var fromEngine = 'Gecko'; if (hpDoc) fromEngine = 'Trident'; index++; var uri = sessionHistory.getEntryAtIndex(index, false).URI; // dump(' To page is ==> '+uri.spec+'\n'); var site = sitecontrols.SCSVC.getResourceForURI(uri.spec); var toEngine = sitecontrols.SCSVC.readSiteControlResource(site, 'displayEngine'); docshell.browserEngine = toEngine; if (fromEngine == 'Trident') { sessionHistory.setCurrentIndex(index); if (toEngine == 'Gecko'){ // dump('BrowserForward: Trident=>Gecko\n'); hpDoc.geckoLoadURI(uri, Components.interfaces.nsIDocShellLoadInfo.loadNormalReplace); gBrowser.mCurrentTab.removeAttribute("engine"); //hpDoc.geckoLoadURI(uri, 1); } else { // dump('BrowserForward: Trident ==> Trident\n'); hpDoc.goCmd(2); } } else//original code { var where = whereToOpenLink(aEvent, false, aIgnoreAlt); if (where == "current") { try { docshell.goForward(); } catch(ex) { dump ("Caught Exception: " + ex + "\n");} } else { //JA var sessionHistory = getWebNavigation().sessionHistory; //JA var currentIndex = sessionHistory.index; //JA var entry = sessionHistory.getEntryAtIndex(currentIndex + 1, false); //JA var uri = entry.URI.spec; openUILinkIn(uri, where); } } } function BrowserBack(aEvent, aIgnoreAlt) { var docshell = getWebNavigation(); var sessionHistory = docshell.sessionHistory; var index = sessionHistory.index; if (index <= 0) return;//error! // Try to get handle on Trident var hpDoc = getTridentDocument(); var fromEngine = 'Gecko'; if (hpDoc) fromEngine = 'Trident'; index--; var uri = sessionHistory.getEntryAtIndex(index, false).URI; // dump(' To page is ==> '+uri.spec+'\n'); var site = sitecontrols.SCSVC.getResourceForURI(uri.spec); var toEngine = sitecontrols.SCSVC.readSiteControlResource(site, 'displayEngine'); getWebNavigation().browserEngine = toEngine; if (fromEngine == 'Trident') { sessionHistory.setCurrentIndex(index); if (toEngine == 'Gecko') { // dump('BrowserBack: Trident ==> Gecko\n'); hpDoc.geckoLoadURI(uri, Components.interfaces.nsIDocShellLoadInfo.loadBypassHistory); // remove engine attribute from tab gBrowser.mCurrentTab.removeAttribute("engine"); UpdateStatusBarEngineIcon(); //hpDoc.geckoLoadURI(uri, 10); } else { // dump('BrowserBack: Trident ==> Trident\n'); gBrowser.mCurrentTab.setAttribute("engine", "Trident"); hpDoc.goCmd(1); } } else//Gecko, original code { var where = whereToOpenLink(aEvent, false, aIgnoreAlt); if (where == "current") { try { getWebNavigation().goBack(); } catch(ex) { dump ("Caught Exception: " + ex + "\n"); } } else { //JA var sessionHistory = getWebNavigation().sessionHistory; //JA var currentIndex = sessionHistory.index; //JA var entry = sessionHistory.getEntryAtIndex(currentIndex - 1, false); //JA var uri = entry.URI.spec; openUILinkIn(uri, where); } } } function BrowserHandleBackspace() { BrowserBack(); } function BrowserBackMenu(event) { return FillHistoryMenu(event.target, "back"); } function BrowserForwardMenu(event) { return FillHistoryMenu(event.target, "forward"); } // MERC (DP): fill in the home button dropdown with a each home page item function BrowserHomeMenu(menu) { var homePage = gHomeButton.getHomePage(); var urls = homePage.split("|"); var separator; var referenceNodeList = menu.getElementsByTagName("menuseparator"); var referenceNode = null; var children = menu.childNodes; for (var j = 0; j < children.length; j++) { // clear old menuitems try { var tmpElement = children[j].QueryInterface(Components.interfaces.nsIDOMElement); if(!tmpElement.hasAttribute("nodelete")) { //avoid deleting separators menu.removeChild(children[j]); } } catch(e){ dump ("Caught Exception : "+e+"\n"); //we may still want to delete this node? } } //find the first separator to insert the page links before if (referenceNodeList.length > 0){ referenceNode = referenceNodeList[0]; } for (var i = 0; i < urls.length; i++) { var menuitem = document.createElement( "menuitem" ); menuitem.setAttribute("label", urls[i]); //var tmpStr = "gBrowser.addTab('" + urls[i] + "')"; var tmpStr = "loadURIWithOpenPref('" + urls[i] + "', 'browser.tabs.homepage.open');"; menuitem.setAttribute("oncommand", tmpStr); menuitem.setAttribute("tooltiptext", "Go to this page"); if (referenceNodeList.length > 0){ menu.insertBefore( menuitem, referenceNode ); } else { menu.appendChild( menuitem ); } } } // <MERC function BrowserStop() { var hpDoc = getTridentDocument(); if(hpDoc) { //var stopbutton = document.getElementById("stop-button"); //stopbutton.setAttribute("disabled", "true"); /* var stopReloadBtn = document.getElementById("stop-reload-button"); if (stopReloadBtn) { // JCH: Need to set label according to state stopReloadBtn.setAttribute("label","Reload"); stopReloadBtn.setAttribute("state","reload"); stopReloadBtn.removeAttribute("command"); stopReloadBtn.setAttribute("oncommand","BrowserStopReload(event);"); }*/ var webProgress = gBrowser.webProgress; window.XULBrowserWindow.onStateChange(webProgress, null, Components.interfaces.nsIWebProgressListener.STATE_STOP | Components.interfaces.nsIWebProgressListener.STATE_IS_NETWORK, 0); hpDoc.cancelNavigation(); } else { try { const stopFlags = nsIWebNavigation.STOP_ALL; getWebNavigation().stop(stopFlags); } catch(ex) { dump ("Caught Exception: " + ex + "\n");} } } //MERC/> /** * MERC: ccampbell * Added this function to differentiate between the way Find works in * Gecko (a.k.a Find Bar) and Trident (old fashioned dialog) **/ function findCommand(again) { var hpDoc = getTridentDocument(); if (hpDoc) { // The current tab is in Trident gBrowser.find(); } else { try { // The current tab is in Gecko if (again) onFindAgainCmd(); else onFindCmd(); } catch(ex) { dump ("Caught Exception: " + ex + "\n"); } } } /////////////////////////////////////////////////////////////////////////////////////// // POPUPBLOCK BUTTON GENERAL FUNCTIONALITY // /////////////////////////////////////////////////////////////////////////////////////// // MERC - JCH // Increment the global popup blocked count function IncrementPopupsBlocked(windowDoc) { if (!gBrowser) return; // Get the index of the relevant tab document object var foundIndex = gBrowser.getBrowserIndexForDocument(windowDoc); if (foundIndex < 0) return; // Get ref to target tab var browserTabs = gBrowser.mTabContainer.childNodes; var targetTab = browserTabs[foundIndex]; // Modify the global count ++gBrowser.numberBlocked; // Get the browser object of the current tab var browserForCurrentTab = gBrowser.getBrowserForTab(gBrowser.mCurrentTab); // Get the browser object of the target tab var browserForTargetTab = gBrowser.getBrowserForTab(targetTab); // Compare browser that has popup with the current browser // If they are not the same don't update the UI if (browserForTargetTab != browserForCurrentTab) { return; } // Update UI SetPopupBlockToggle(); // Get a handle to the button element var button = document.getElementById("popupblocker-button"); // JMC added sanity check for when button is removed from toolbar if (button) { // Change icon for two seconds when popups are blocked button.setAttribute("popupDetected","true"); // Show popup block icon for two seconds setTimeout("RestorePBB()", 2000); } } // MERC - JCH : Restore the look of the button function RestorePBB() { // dump("\nIn RestorePBB -> Show image\n"); // Get a handle to the button element var button = document.getElementById("popupblocker-button"); if (button) { button.setAttribute("popupDetected","false"); SetPopupBlockToggle(); } } // MERC - JCH : Determine whether blocking is on // Called from nsGlobalWindow.cpp and nsHTMLPluginDocument.cpp function PopupBlockingOn(windowDoc) { // Get the index of the relevant tab document object var foundIndex = gBrowser.getBrowserIndexForDocument(windowDoc); // dump(">>>>>> In PopupBlockingOn() foundIndex is: " + foundIndex + "\n"); if (foundIndex < 0) return; // Get controlling site resource var site = GetSiteControlResource(gBrowser.getBrowserAtIndex(foundIndex)); // If site is illegitimate and uncontrollable then block pop-ups if (!site) return false; // Get the value of the setting associated with popup blocking var popupsAllowed = sitecontrols.SCSVC.readSiteControlResource(site,"allowPopups"); // Return whether to block popups or not // Assume no blocking var blockPopups = false; if (popupsAllowed.indexOf("false") > -1) blockPopups = true; return blockPopups; } // MERC - JCH : determine whether blocking sound is on // Called from nsGlobalWindow.cpp and nsHTMLPluginDocument.cpp function BlockingSoundOn(windowDoc) { if (!gBrowser) return; // Get the index of the relevant tab browser object var foundIndex = gBrowser.getBrowserIndexForDocument(windowDoc); // dump("@@@@@ in BlockingSoundOn with index: " + foundIndex + "\n"); if (foundIndex < 0) return false; // Get the browser object of the current tab var browserForTab = gBrowser.getBrowserForTab(gBrowser.mCurrentTab); // Compare browser that has popup with the current browser // If they are not the same don't play sound if (gBrowser.getBrowserAtIndex(foundIndex) != browserForTab) return false; if (!gPrefService) return false; return gPrefService.getBoolPref("privacy.popups.sound_enabled"); } /** * Returns the RDF resource for the site control applicable to the * given browser object, or else to the current tab's if no object * is specified **/ function GetSiteControlResource(browser) { // dump('enter >> GetSiteControlResource()\n'); // Grab the right browser object if (!browser) browser = gBrowser.getBrowserForTab(gBrowser.mCurrentTab); // Pull out the URI for that tab/browser var uri; if (!browser.currentURI) uri = ''; else uri = browser.currentURI.spec; //dump(' uri: '+uri+'\n'); // The URI must either be for a controllable site (including local files) // or else 'about:blank'. Otherwise, exit without doing anything. if ((uri != 'about:blank') && (!sitecontrols.SCSVC.isControllableURI(uri))) { // if the site is controlled, it's rendered with Gecko, so update statusbar //UpdateStatusBarEngineIcon(); // dump(' '+uri+' is not a controllable uri\n'); return null; } // Site 'about:blank' is treated as if it's a DEFAULT site. // This should be SiteControls:Default resource. if (uri == 'about:blank') { //UpdateStatusBarEngineIcon(); // dump(' '+uri+' will use default settings\n'); uri = ''; } // Return the RDF resource // Note that if site is not explicitly controlled // the default resource is returned return sitecontrols.SCSVC.getResourceForURI(uri); } // MERC - JCH : Updates XUL related to the popupblock button function SetPopupBlockToggle() { //dump('SetPopupBlockToggle()\n'); // Get current url in proper format var site = GetSiteControlResource(); // If site is not controllable we will use default settings for xul if (!site) site = sitecontrols.SCSVC.getResourceForURI(''); // dump(">>>>>> In SetPopupBlockToggle() site is: " + site + "\n"); // Get the value of the site controls associated with popup blocking var popupsAllowed = sitecontrols.SCSVC.readSiteControlResource(site,"allowPopups"); // Get a handle to the button element var button = document.getElementById("popupblocker-button"); if (!button) return; // JMC Sanity check when button is removed from toolbar var popupDetected = button.getAttribute("popupDetected"); // Get handles to menu checkboxes // Don't need sanity checks for these since they are tied to the button // and that's been checked above var menuItemBlock = document.getElementById("popupblocker-onoff"); var menuItemCount = document.getElementById("popupblocker-showcount"); var menuItemSound = document.getElementById("popupblocker-playsound"); // Don't change icon if the blocked popup icon has not finished showing if (popupDetected.indexOf("false") > -1) { // Check if the value is true, in which case popups are allowed if (popupsAllowed.indexOf("true") > -1) { button.setAttribute("popupblocking","off"); button.setAttribute("tooltiptext", "Turn pop-up blocking on"); menuItemBlock.setAttribute("label", "Enable pop-up blocker"); // DisableSoundCountDisplay // Disable sound/count checkboxes } else { button.setAttribute("popupblocking","on"); menuItemBlock.setAttribute("label", "Disable pop-up blocker"); button.setAttribute("tooltiptext", "Turn pop-up blocking off"); menuItemCount.setAttribute('disabled','false'); // Enable count item menuItemSound.setAttribute('disabled','false'); // Enable sound item } } if (!gPrefService) return; // Pop-up count is a global pref var showCount = gPrefService.getBoolPref("privacy.popups.show_count"); // Check if we show count of popups blocked if (showCount) { // Get number of popups blocked var numBlocked = gBrowser.numberBlocked; button.setAttribute("label", " Blocked: "+numBlocked); // Need to set this property so that in browser.css can override // no text in icons mode button.setAttribute("showCount", "true"); menuItemCount.setAttribute("checked", "true"); } else { // If we don't show count we show a default text if in full or text modes button.setAttribute("showCount", "false"); // Get the navbar and check what mode it's in if (popupsAllowed.indexOf("true") > -1) { button.setAttribute("label", " Allowed"); } // If popups are not allowed else { button.setAttribute("label", " Blocked"); } // Uncheck the show count menu item menuItemCount.setAttribute("checked", "false"); } // Pop-up sound is a global pref var playSound = gPrefService.getBoolPref("privacy.popups.sound_enabled"); // Update sound menu checkbox if (playSound) menuItemSound.setAttribute("checked", "true"); else menuItemSound.setAttribute("checked", "false"); } // MERC - JCH : Handle updating site controls. // When the button is clicked or the sound or count menu item is checked the // update proceeds as follows: If the site is uncontrollable and not about:blank, // then do nothing; if the site is about:blank, update default settings; if the // site is either explicitly controlled or a local-file type uri, then update the // corresponding SC settings; if the site is controlled by the default settings, // then add the site to SCs and update the newly added settings. function PBBUpdateSiteControls(controlName) { if (!gBrowser) return; // Get current url in proper format var uri = gBrowser.currentURI.spec; if (!sitecontrols) return; // If the site is an illegitimate uncontrollable site, do nothing but return. if ((uri != 'about:blank') && (!sitecontrols.SCSVC.isControllableURI(uri))) return; // Get resource related to uri var siteResource = sitecontrols.SCSVC.getResourceForURI(uri); // If the site is about:blank, modify default settings. if (uri == 'about:blank') { siteResource = sitecontrols.SCSVC.getResourceForURI(''); } // Remaining cases are local file, explicitly controlled site, // and the various default site types. If site is controlled by a default setting // it must be added as an explicitly controlled site. if ((uri != 'about:blank') && (siteResource.Value == sitecontrols.SC_VERIFIED_DEFAULT || siteResource.Value == sitecontrols.SC_NOT_VERIFIED_DEFAULT || siteResource.Value == sitecontrols.SC_WARNING_DEFAULT)) { var host = sitecontrols.getStrippedHostFromURL(uri); sitecontrols.SCSVC.addControlledSite(host); siteResource = sitecontrols.SCSVC.getResourceForURI(host); } // Get current site control setting var controlValue = sitecontrols.SCSVC.readSiteControlResource(siteResource, controlName); var invVal; if (controlValue.indexOf("true") > -1) invVal = "false"; else invVal = "true"; // Assign negation of current control value sitecontrols.SCSVC.updateSiteControlResource(siteResource, controlName, invVal); } ///////////////////////////////////////////////////////////////////////////////// // POPUPBLOCK BUTTON MENU ITEMS FUNCTIONALITY // ///////////////////////////////////////////////////////////////////////////////// // MERC - JCH: Popups are about to be allowed so disable showing count and sound // in both the pbb drop-down menu and in the options-advanced-browsing function DisableSoundCountDisplay() { //dump('DisableSoundCountDisplay()\n'); // Get current url in proper format var ctrlSite = GetSiteControlResource(); // If site is not controllable we will use default settings for xul if (!ctrlSite) ctrlSite = sitecontrols.SCSVC.getResourceForURI(''); // Notation: "rg = range = array" var rgMenuSoundAndCount = new Array('popupblocker-showcount','popupblocker-playsound'); // dump("\n####### Well here we are in the zone ######\n"); for (var i=0; i<2; i++) { // Disable the menu item menuItem = document.getElementById(rgMenuSoundAndCount[i]); if (menuItem) menuItem.setAttribute('disabled','true'); } } // MERC - JCH : When you click on the pop-up blocking button or the sound or // count menu items, you first check if the dialog is supposed to show. It will // retrieve the user's decision to change site controls. If the dialog has been // disabled, then site controls are changed without prompting. function DoPBBAction(event, controlName) { //dump('DoPBBAction()\n'); // Assume we are going to update site control settings var updateSite = true; if (!gPrefService) { event.preventBubble(); return; } // Pop-up count is now a global pref if (controlName == "showBlockedCount") { var showCount = gPrefService.getBoolPref("privacy.popups.show_count"); gPrefService.setBoolPref("privacy.popups.show_count", !showCount); SetPopupBlockToggle(); event.preventBubble(); return; } // Pop-up sound is now a global pref if (controlName == "playBlockedSound") { var playSound = gPrefService.getBoolPref("privacy.popups.sound_enabled"); gPrefService.setBoolPref("privacy.popups.sound_enabled", !playSound); SetPopupBlockToggle(); event.preventBubble(); return; } // Check if we show site controls info dialog and get user's choice if we do if (gPrefService.getBoolPref("show.popupblockbutton.dialog")) { // Get current raw url if (!gBrowser) { event.preventBubble(); return; } var uri = gBrowser.currentURI.spec; if (!sitecontrols) { event.preventBubble(); return; } var siteString; // Get resource related to uri var site = sitecontrols.SCSVC.getResourceForURI(uri); // Check for about:blank URI if (uri == 'about:blank') { siteString = "Default Settings"; } else if (site.Value == sitecontrols.SC_LOCAL) { siteString = "Local File Settings"; } // If the site value is null then the site in not controllable else if (!site) { event.preventBubble(); return; } // The site is controllable and not a local file, so, since we // are going to add it to SC, show it's stripped domain on the dialog else { siteString = sitecontrols.getStrippedHostFromURL(uri); } // Pass in the site string and the boolean set to update SC. // The boolean may be modified by the user depending on how // they respond to dialog prompt var args = new Object(); args.doupdate = updateSite; args.site = siteString; updateSite = ShowPBBInfoDialog(args); } // User wants to change site control settings if (updateSite) { PBBUpdateSiteControls(controlName); SetPopupBlockToggle(); } event.preventBubble(); return; } // MERC - JCH: Invoke dialog explaining how to properly change SCs. The user can // cancel the action as well as deactivate the dialog. function ShowPBBInfoDialog(args) { window.openDialog("chrome://browser/content/pbbDecisionDialog.xul", "Decision", "modal,centerscreen,chrome,resizable=no", args); return args.doupdate; } // MERC - JCH: open list of blocked domains with option to make a controlled site function BlockerShowList(event) { try { window.openDialog("chrome://browser/content/pageReport.xul", "_blank", "modal,resizable,centerscreen"); event.preventBubble(); return; } catch(ex) { dump("Exception in browser.js: BlockerShowList\n" + ex + "\n"); } } // MERC - JCH: open site controls dialog with pertinent site selected function BlockerShowSCDialog(event) { // not in tabbed mode, ignore this action if (gPrefService.getBoolPref("browser.tabs.autoHide") && gBrowser.mTabContainer.childNodes.length < 2) return; var myTab = gBrowser.mCurrentTab; // if we're not in tabbed mode, then do nothing if (!myTab) return; var siteControlPopup = document.getElementById('SiteControlsPopup'); // MERC - JCH: For BLT# 147538, set the site controls popup to open the advanced tab when it opens var scTabbox = document.getElementById('scp_tabbox'); if (scTabbox) scTabbox.selectedIndex=1; // wrap around a timeout function to avoid conflicting popup focuses if (siteControlPopup) { setTimeout("document.getElementById('SiteControlsPopup').showPopup(gBrowser.mCurrentTab, -1, -1, 'popup', 'bottomleft', 'topleft');",100); } event.preventBubble(); } // MERC - JCH: Zero the popups blocked count function ClearPopupCount(event) { if (!gBrowser) return; gBrowser.numberBlocked = 0; SetPopupBlockToggle(); event.preventBubble(); return; } //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // MERC (DP): Fired when clear histories button clicked. Will warn the user // via a dialog that they are clearing histories. function ClearHistoriesButtonClick(event, historyLabel) { // Assume we are going to update site control settings var flagval = "true"; // Check if we show site controls info dialog if (!gPrefService.getBoolPref("clearhistories.button.dialog")) flagval = ShowClearHistoriesInfoDialog(historyLabel); // User wants to clear histories if (flagval.indexOf("true") > -1) { PrivacyPanel.clearData['history'](false); SetHistoryButton(); } event.preventBubble(); return; } // MERC (DP): Invoke dialog explaining that user about to clear histories function ShowClearHistoriesInfoDialog(historyLabel) { // Pass "doUpdate" into dialog. If it returns 'true' then clear var doUpdate = new String(); doUpdate.value = "false"; window.openDialog("chrome://browser/content/clearHistoriesDecisionDialog.xul", "Decision", "modal,centerscreen,chrome,resizable=no", doUpdate, historyLabel); return doUpdate.value; } // MERC - JCH : Update the history button. function SetHistoryButton() { try { var button = document.getElementById("clearhistories-button"); if (!button) return; if (gGlobalHistory == null) return; if (gPrefService == null) return; var isAnonymous = gPrefService.getBoolPref("privacy.anonMode.enabled"); var anonMenuItem = document.getElementById("clearHistoryAnonymousMode"); anonMenuItem.setAttribute('checked', isAnonymous); if (isAnonymous) { // dump("browser.js SetHistoryButton(): isAnonymous is " +isAnonymous+ "\n"); button.setAttribute("historyEmpty", "anon"); return; } //dump("browser.js SetHistoryButton(): gGlobalHistory.count is " +gGlobalHistory.count+ "\n"); if (gGlobalHistory != null && gGlobalHistory.count == 0) { button.setAttribute("historyEmpty", "true"); } else { button.setAttribute("historyEmpty", "false"); } } catch(ex) { dump("Exception in browser.js: SetHistoryButton\n" + ex + "\n"); } } //////////////////////////////////////////////////////////////////////////////////////////// //JA ff5->vulp function BrowserReload() { const reloadFlags = nsIWebNavigation.LOAD_FLAGS_NONE; // MERC (DP): we really only need to call this when the engine is Trident. // if Gecko, it is taken care of in the onLocationChange handler in // tabbrowser.xml try { UpdateSiteControlIcon(); } catch (ex) {} UpdateStatusBarEngineIcon(); return BrowserReloadWithFlags(reloadFlags); } //JA/> // MERC (ccampbell) - command for merged stop-reload-button function BrowserStopReload(evt) { var btn = document.getElementById('stop-reload-button'); if (!btn) return; if (btn.getAttribute('state') == 'stop') { } // JMC- hackish fix for coming back from customize dialog, loses state // Else if (btn.getAttribute('state') == 'reload') else // if (btn.getAttribute('state') == 'reload') { if (evt.shiftKey) BrowserReloadSkipCache(); else BrowserReload(); } } // MERC (ccampbell) - execute command for overflow toolbar item function OverflowMenuCommand(btnId) { var btn = document.getElementById(btnId); if (!btn) return; if (btn.hasAttribute('overflowcommand')) { setTimeout(btn.getAttribute('overflowcommand'), 1); } else if (btn.hasAttribute('oncommand')) { btn.doCommand(); } else if (btn.hasAttribute('command')) { var cmd = document.getElementById(btn.getAttribute('command')); cmd.doCommand(); } else { dump('NOTHING TO DO FOR OVERFLOW MENU ITEM: '+btnId+'\n'); } } // MERC (rpaul) - update the statusbar icon to reflect which engine we're currently in function UpdateStatusBarEngineIcon() { var engineBroadcaster = document.getElementById("currentEngineBroadcaster"); var currentEngine; // hide the engine icon if the pref isn't set if (!gPrefService.getBoolPref("browser.show_engine_icon")) { engineBroadcaster.setAttribute("collapsed", "true"); } else { engineBroadcaster.removeAttribute("collapsed"); } // MERC (rpaul)if we have a handle on a tab and we're in tabbed mode, get the current engine // from the tab if (gBrowser.mTabbedMode) { //currentEngine = gBrowser.getBrowserForTab(tab).docShell.browserEngine; currentEngine = gBrowser.mCurrentTab.getAttribute("engine"); if (!currentEngine) currentEngine = "Gecko"; else currentEngine = "Trident"; } else { // browser isn't in tabbed mode if (!gBrowser.mTabbedMode) { var currentTab = gBrowser.mCurrentTab; if (currentTab) currentEngine = gBrowser.getBrowserForTab(currentTab).docShell.browserEngine; } } if (currentEngine == "Gecko") { engineBroadcaster.setAttribute("src", "chrome://browser/skin/firefox-dropmarker-16px.png"); engineBroadcaster.setAttribute("value", "Gecko"); //enable "Toggle Rendering engines in View menu" document.getElementById('viewMenuToggleRenderingEngine').removeAttribute('disabled'); //uncheck "Display Like Internet Explorer" in status bar engine menu document.getElementById('displayLikeIE').removeAttribute('checked'); document.getElementById('displayLikeIE').removeAttribute('disabled'); // check "Display Like Firefox" in status bar engine menu document.getElementById('displayLikeFirefox').setAttribute('checked', 'true'); document.getElementById('displayLikeFirefox').setAttribute('disabled', 'true'); // disable "Display like firefox in view->rendering engines menu document.getElementById('engineIsFirefoxBroadcaster').setAttribute('disabled', 'true'); document.getElementById('engineIsIEBroadcaster').removeAttribute('disabled'); } else if (currentEngine == "Trident") { engineBroadcaster.setAttribute("src", "chrome://browser/skin/ie_icon-dropmarker.gif"); engineBroadcaster.setAttribute("value", "IE"); //enable "Toggle Rendering engines in View menu" document.getElementById('viewMenuToggleRenderingEngine').removeAttribute('disabled'); //uncheck "Display Like Firefox" in status bar engine menu document.getElementById('displayLikeFirefox').removeAttribute('checked'); document.getElementById('displayLikeFirefox').removeAttribute('disabled'); // check "Display Like Internet Explorer" in status bar engine menu document.getElementById('displayLikeIE').setAttribute('checked', 'true'); document.getElementById('displayLikeIE').setAttribute('disabled', 'true'); // disable "Display like IE in view->rendering engines menu document.getElementById('engineIsIEBroadcaster').setAttribute('disabled', 'true'); document.getElementById('engineIsFirefoxBroadcaster').removeAttribute('disabled'); } else { dump("Unknown engine name: " + currentEngine + "\n"); } } function UpdateStatusbarEngineIconTrident() { var engineBroadcaster = document.getElementById("currentEngineBroadcaster"); engineBroadcaster.setAttribute("src", "chrome://browser/skin/ie_icon-dropmarker.gif"); engineBroadcaster.setAttribute("value", "IE"); //enable "Toggle Rendering engines in View menu" document.getElementById('viewMenuToggleRenderingEngine').removeAttribute('disabled'); //uncheck "Display Like Firefox" in status bar engine menu document.getElementById('displayLikeFirefox').removeAttribute('checked'); document.getElementById('displayLikeFirefox').removeAttribute('disabled'); // check "Display Like Internet Explorer" in status bar engine menu document.getElementById('displayLikeIE').setAttribute('checked', 'true'); document.getElementById('displayLikeIE').setAttribute('disabled', 'true'); // disable "Display like IE in view->rendering engines menu document.getElementById('engineIsIEBroadcaster').setAttribute('disabled', 'true'); document.getElementById('engineIsFirefoxBroadcaster').removeAttribute('disabled'); } // MERC (DP): populates partner icons (if any) into the status bar function UpdateStatusbarPartnerIcons() { var iconContainer = document.getElementById('partner-icons-container'); // clear the partner icons while(iconContainer.firstChild) { iconContainer.removeChild(iconContainer.firstChild); } var sc = sitecontrols.SCSVC; var url = gBrowser.getBrowserForTab(gBrowser.mCurrentTab).currentURI.spec; var urlArray; var iconArray; switch(sc.getSiteTrustLevel(url)) { case 0: // whitelisted var whiteListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_WHITELIST_IDX); var urlStr = sc.getSiteTrustProviderURL(whiteListCode); urlArray = urlStr.split('|'); var iconStr = sc.getSiteTrustProviderIcon(whiteListCode); iconArray = iconStr.split('|'); break; case 2: // phish var phishListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_PHISHLIST_IDX); var urlStr = sc.getSiteTrustProviderURL(phishListCode); urlArray = urlStr.split('|'); var iconStr = sc.getSiteTrustProviderIcon(phishListCode); iconArray = iconStr.split('|'); break; case 4: // spy var spyListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_SPYLIST_IDX); var urlStr = sc.getSiteTrustProviderURL(spyListCode); urlArray = urlStr.split('|'); var iconStr = sc.getSiteTrustProviderIcon(spyListCode); iconArray = iconStr.split('|'); break; case 6: var phishListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_PHISHLIST_IDX); var plistStr = sc.getSiteTrustProviderName(phishListCode); var plistArray = plistStr.split('|'); var purlStr = sc.getSiteTrustProviderURL(phishListCode); var purlArray = purlStr.split('|'); var piconStr = sc.getSiteTrustProviderIcon(phishListCode); var piconArray = piconStr.split('|'); var spyListCode = sc.getSiteTrustLevelDetail(url, sc.SC_TRUST_SPYLIST_IDX); var slistStr = sc.getSiteTrustProviderName(spyListCode); var slistArray = slistStr.split('|'); var surlStr = sc.getSiteTrustProviderURL(spyListCode); var surlArray = surlStr.split('|'); var siconStr = sc.getSiteTrustProviderIcon(spyListCode); var siconArray = siconStr.split('|'); var combinedURLArray = purlArray; var combinedIconArray = piconArray; var found; for(var arrayItem in slistArray) { found = false; for(var k = 0; k < plistArray.length; k++) { if(slistArray[arrayItem] == plistArray[k]) { found = true; break; } } if(!found) { combinedURLArray.push(surlArray[arrayItem]); combinedIconArray.push(siconArray[arrayItem]); } } urlArray = combinedURLArray; iconArray = combinedIconArray; break; case 1: default: // unknown } if(!iconArray || !iconArray.length) { iconContainer.setAttribute('hidden', 'true'); } else { iconContainer.removeAttribute('hidden'); var iconElem; for(var i = 0; i < iconArray.length; i++) { if(iconArray[i]) { iconElem = document.createElement("image"); iconElem.setAttribute("src", iconArray[i]); iconElem.setAttribute("onclick", "loadPartnerPageFromStatusBar('" + urlArray[i] + "');"); iconElem.setAttribute("style", "padding-left: 4px;"); iconContainer.appendChild(iconElem); } } } } function loadPartnerPageFromStatusBar(url) { var trustTab = gBrowser.addTabAt(url); if (!gPrefService.getBoolPref("browser.tabs.loadInBackground")) gBrowser.selectedTab = trustTab; } // MERC (DP) - update the icon to match security level AND browser engine function UpdateSiteControlIcon(tab) { //dump('UpdateSiteControlIcon()\n'); // if no tab specified, use the current tab if (!tab) { tab = gBrowser.mCurrentTab; } var tabWindow = gBrowser.getBrowserForTab(tab); var url = tabWindow.currentURI.spec; var menubutton = document.getAnonymousElementByAttribute(tab, 'anonid', 'menubutton'); // MERC - JCH: Sanity check if (!menubutton) return; if (!sitecontrols.SCSVC.isControllableURI(url)) { menubutton.setAttribute('hidden', 'true'); } else { menubutton.removeAttribute('hidden'); var site; if(url == 'about:blank') { site = sitecontrols.SCSVC.getResourceForURI(''); } else { site = sitecontrols.SCSVC.getResourceForURI(url); } // MERC - JCH: 'site' is already a resource // site = site.QueryInterface(Components.interfaces.nsIRDFResource); // if host is not controlled (default), change icon accordingly // MERC - JCH: Three possible default settings now // if (site.Value == sitecontrols.DEFAULT_SITE) if ((site.Value == sitecontrols.SC_VERIFIED_DEFAULT) || (site.Value == sitecontrols.SC_NOT_VERIFIED_DEFAULT) || (site.Value == sitecontrols.SC_WARNING_DEFAULT)) { menubutton.setAttribute("defaultSC", "true"); } else menubutton.removeAttribute("defaultSC"); var trustLevel = 1; try { // MERC - JCH: Pass host string to getSiteTrustLevel() if (tabWindow.currentURI.spec) { trustLevel = sitecontrols.SCSVC.getSiteTrustLevel(tabWindow.currentURI.spec); } } catch (ex) { dump("Caught exception : " + ex + "\n\n"); } menubutton.setAttribute("trustLevel", trustLevel); // if trust settings is disabled var securityLevel; if(trustLevel == -1 && !sitecontrols.SCSVC.isControlledSite(tabWindow.currentURI.host)) { securityLevel = gPrefService.getCharPref("trustsettings.default"); } else { securityLevel = sitecontrols.SCSVC.readSiteControlResource(site, 'securityLevel'); } menubutton.setAttribute("browserSetting", securityLevel); // update the down menubutton icon according to what browser engine is set var currentEngine = gBrowser.getBrowserForTab(tab).docShell.browserEngine; /* dump('********** SECURITY LEVEL ***************\n'); dump('Host: ' + site.Value + ' - Level: ' + securityLevel + '\n'); dump('********** Current Engine ***************\n'); dump('engine: ' + currentEngine + '\n'); dump('*****************************************\n'); */ if (currentEngine == "Gecko") { tab.removeAttribute("engine"); menubutton.setAttribute("engine", "Gecko"); } else if (currentEngine == "Trident") { tab.setAttribute("engine", "Trident"); menubutton.setAttribute("engine", "Trident"); } else { dump("Unknown engine name: " + currentEngine + "\n"); } // MERC (rpaul) update the statusbar engine icon when the // the site control has been updated for a particular tab UpdateStatusBarEngineIcon(); } } /* engine ActiveX Javascript Java securityLevel weight 8 4 2 1 Gecko false false false High Gecko false false true Medium Gecko false true false Medium Gecko false true true Medium Gecko true false false High Gecko true false true Medium Gecko true true false Medium Gecko true true true Medium Trident false false false High Trident false false true Medium Trident false true false Medium Trident false true true Medium Trident true false false Low Trident true false true Low Trident true true false Low Trident true true true Low */ // ********* if you change this var, you need to change in pref-sitecontrols.js as well var gSecurityLevels= new Array('High','Medium','Medium','Medium','High','Medium','Medium','Medium', 'High','Medium', 'Medium', 'Medium', 'Low', 'Low', 'Low', 'Low'); function updateSCSecurityLevel() { var wtEngine, wtActiveX, wtJS, wtJava; // Get RDF resource for the controlled site // *** at this point host should always be controlled since it gets added when // you select activex, java, js from the dropdown menu var site = GetSiteControlResource(); var displayEngine = getWebNavigation().browserEngine; var enableActiveX = sitecontrols.SCSVC.readSiteControlResource(site, 'enableActiveX'); var enableJava = sitecontrols.SCSVC.readSiteControlResource(site, 'enableJava'); var enableJavaScript = sitecontrols.SCSVC.readSiteControlResource(site, 'enableJavaScript'); var sec; if (displayEngine == 'Trident') wtEngine=8; else wtEngine=0; if(enableActiveX == 'true') wtActiveX=4; else wtActiveX=0; if(enableJavaScript == 'true') wtJS=2; else wtJS=0; if(enableJava == 'true') wtJava=1; else wtJava=0; var idx = wtEngine + wtActiveX + wtJS + wtJava; var securityLevel = gSecurityLevels[idx]; /* dump('************** updateSCSecurityLevel() *******************\n'); dump('host: ' + host + '\n'); dump('displayEngine: ' + displayEngine + '\n'); dump('enableActiveX: ' + enableActiveX + '\n'); dump('enableJava: ' + enableJava + '\n'); dump('enableJavaScript: ' + enableJavaScript + '\n'); dump('securityLevel: ' + securityLevel + '\n'); dump('idx: ' + idx + '\n'); dump('**********************************************************\n'); */ sitecontrols.SCSVC.updateSiteControlResource(site, 'securityLevel', securityLevel); // sitecontrols.SCSVC.writeSiteControls(); } function BrowserReloadSkipCache() { // Bypass proxy and cache. const reloadFlags = nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE; return BrowserReloadWithFlags(reloadFlags); } function BrowserHome(forceNewTab) { var homePage = gHomeButton.getHomePage(); //JA ff5->vulp loadOneOrMoreURIs(homePage); // if overwrite: load tabs left to right - add tabs as needed // if new: add tabs starting at position specified browser.tabs.newTabLocation if(!forceNewTab && gPrefService.getCharPref("browser.tabs.homepage.open") == 'overwrite') { loadOneOrMoreURIsOnHomePageClick(homePage); } else { // else == 'new' addOneOrMoreURIs(homePage); }//JA/> } function loadOneOrMoreURIsOnHomePageClick(aURIString) { if (aURIString.indexOf("|") != -1) { var i; // get browser tabs var browserTabs = gBrowser.mTabContainer.childNodes; // get URLs var urls = aURIString.split("|"); // 3 cases: if (browserTabs.length < urls.length) { // a) if # tabs < # URLs for (i = 0; i < browserTabs.length; i++) { gBrowser.getBrowserForTab(browserTabs[i]).loadURI(urls[i]); } for (i = browserTabs.length; i < urls.length; i++) { gBrowser.addTab(urls[i]); } } else if (browserTabs.length > urls.length) { // b) if # tabs > # URLs for (i = 0; i < urls.length; i++) { gBrowser.getBrowserForTab(browserTabs[i]).loadURI(urls[i]); } } else { // c) if # tabs == # URLs for (i = 0; i < urls.length; i++) { gBrowser.getBrowserForTab(browserTabs[i]).loadURI(urls[i]); } } // set focus to the first tab gBrowser.selectedTab = browserTabs[0]; } else { // only one URL specifed loadURI(aURIString, null, null); } // update the tab chrome gBrowser.updateChromeWhenLastTab(); } function closeAllTabsFromSameSite() { var browserPanels = gBrowser.mPanelContainer.childNodes; for(var i = 0; i < browserPanels.length; i++) { // dump("*** URL: " + browserPanels[i].getCurrentURI() + "\n"); } } // MERC (DP): adds tabs starting at browser.tabs.newTabLocation and subsequently // to the right. select the first tab added after. function addOneOrMoreURIs(aURIString) { var savedSelectedTab = gBrowser.selectedTab; var firstAdded; if (aURIString.indexOf("|") != -1) { var urls = aURIString.split("|"); gBrowser.selectedTab = gBrowser.addTabAt(urls[0]); // save the first tab add, so that we can focus it at the end firstAdded = gBrowser.selectedTab; for (var i = 1; i < urls.length; ++i) gBrowser.selectedTab = gBrowser.addTabAt(urls[i], 'right'); } else { firstAdded = gBrowser.addTabAt(aURIString); } /* comment this out because we always want to focus the first tab if(gPrefService.getBoolPref("browser.tabs.loadInBackground")) { // focus the tab active before addition gBrowser.selectedTab = savedSelectedTab; } else { // focus the first added tab gBrowser.selectedTab = firstAdded; } */ // focus the first added tab gBrowser.selectedTab = firstAdded; } function BrowserHomeClick(aEvent) { if (aEvent.button == 2) // right-click: do nothing return; var homePage = gHomeButton.getHomePage(); var where = whereToOpenLink(aEvent); var urls; // openUILinkIn in utilityOverlay.js doesn't handle loading multiple pages switch (where) { case "save": urls = homePage.split("|"); saveURL(urls[0], null, null, true); // only save the first page break; case "current": loadOneOrMoreURIs(homePage); break; case "tabshifted": case "tab": urls = homePage.split("|"); var firstTabAdded = gBrowser.addTab(urls[0]); for (var i = 1; i < urls.length; ++i) gBrowser.addTab(urls[i]); if ((where == "tab") ^ getBoolPref("browser.tabs.loadBookmarksInBackground", false)) { gBrowser.selectedTab = firstTabAdded; _content.focus(); // JMC - URLBar focus bug, workin on it dump ("Just focused the _content, which is " + _content + "\n"); } break; case "window": OpenBrowserWindow(); break; } } function loadOneOrMoreURIs(aURIString) { var urls = aURIString.split("|"); loadURI(urls[0]); for (var i = 1; i < urls.length; ++i) gBrowser.addTab(urls[i]); } function constructGoMenuItem(goMenu, beforeItem, url, title) { var menuitem = document.createElementNS(kXULNS, "menuitem"); menuitem.setAttribute("statustext", url); menuitem.setAttribute("label", title); goMenu.insertBefore(menuitem, beforeItem); return menuitem; } function onGoMenuHidden() { setTimeout(destroyGoMenuItems, 0, document.getElementById('goPopup')); } function destroyGoMenuItems(goMenu) { var startSeparator = document.getElementById("startHistorySeparator"); var endSeparator = document.getElementById("endHistorySeparator"); endSeparator.hidden = true; // Destroy the items. var destroy = false; for (var i = 0; i < goMenu.childNodes.length; i++) { var item = goMenu.childNodes[i]; if (item == endSeparator) break; if (destroy) { i--; goMenu.removeChild(item); } if (item == startSeparator) destroy = true; } } function updateGoMenu(goMenu) { // In case the timer didn't fire. destroyGoMenuItems(goMenu); var history = document.getElementById("hiddenHistoryTree"); if (history.hidden) { history.hidden = false; var globalHistory = Components.classes["@mozilla.org/browser/global-history;2"] .getService(Components.interfaces.nsIRDFDataSource); history.database.AddDataSource(globalHistory); } if (!history.ref) history.ref = "NC:HistoryRoot"; var count = history.treeBoxObject.view.rowCount; if (count > 10) count = 10; if (count == 0) return; const NC_NS = "http://home.netscape.com/NC-rdf#"; if (!gRDF) gRDF = Components.classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); var builder = history.builder.QueryInterface(Components.interfaces.nsIXULTreeBuilder); var beforeItem = document.getElementById("endHistorySeparator"); var nameResource = gRDF.GetResource(NC_NS + "Name"); var endSep = beforeItem; var showSep = false; for (var i = count-1; i >= 0; i--) { var res = builder.getResourceAtIndex(i); var url = res.Value; var titleRes = history.database.GetTarget(res, nameResource, true); if (!titleRes) continue; showSep = true; var titleLiteral = titleRes.QueryInterface(Components.interfaces.nsIRDFLiteral); beforeItem = constructGoMenuItem(goMenu, beforeItem, url, titleLiteral.Value); } if (showSep) endSep.hidden = false; } // MERC - JCH : Add one site to bookmarks. Referred to in browser-context.inc, // browser-sets.inc, browser.xul, tabbox.xml, and tabbrowser.xml. function bookmarkPage(aBrowser, aIsWebPanel) { addBookmarkForBrowser(aBrowser.webNavigation, aIsWebPanel, false); } function bookmarkPageFromMultibar(aBrowser, aIsWebPanel) { addBookmarkForBrowser(aBrowser.webNavigation, aIsWebPanel, true); } // MERC - JCH: Add all the current tabs to bookmarks. function bookmarkAllTabs(aBrowser, isMultibarButton, aIsWebPanel) { const browsers = aBrowser.browsers; if (browsers && browsers.length > 1) addBookmarkForTabBrowser(aBrowser, isMultibarButton); else addBookmarkForBrowser(aBrowser.webNavigation, aIsWebPanel, isMultibarButton); } function addBookmarkAs(aBrowser, aIsWebPanel, bTabGroup) { const browsers = aBrowser.browsers; if (browsers && browsers.length > 1) { if (bTabGroup) { bookmarkAllTabs(aBrowser, true, aIsWebPanel); } else { addBookmarkForTabBrowser(aBrowser); } } else { addBookmarkForBrowser(aBrowser.webNavigation, aIsWebPanel); } } function addBookmarkForTabBrowser(aTabBrowser, aSelect) { var tabsInfo = []; var currentTabInfo = { name: "", url: "", charset: null }; const activeBrowser = aTabBrowser.selectedBrowser; const browsers = aTabBrowser.browsers; for (var i = 0; i < browsers.length; ++i) { var webNav = browsers[i].webNavigation; var url = webNav.currentURI.spec; var name = ""; var charSet; try { var doc = webNav.document; name = doc.title || url; charSet = doc.characterSet; } catch (e) { name = url; } tabsInfo[i] = { name: name, url: url, charset: charSet }; if (browsers[i] == activeBrowser) currentTabInfo = tabsInfo[i]; } openDialog( "chrome://browser/content/bookmarks/addBookmark2.xul", "", "centerscreen,chrome,dialog,resizable,dependent", currentTabInfo.name, currentTabInfo.url, null, currentTabInfo.charset, "addGroup" + (aSelect ? ",group" : ""), tabsInfo, null, null, null, null, null, aSelect); } function addBookmarkForBrowser(aDocShell, aIsWebPanel, cmdFromMultibar) { // Bug 52536: We obtain the URL and title from the nsIWebNavigation // associated with a <browser/> rather than from a DOMWindow. // This is because when a full page plugin is loaded, there is // no DOMWindow (?) but information about the loaded document // may still be obtained from the webNavigation. var url = aDocShell.currentURI.spec; var title, charSet = null; try { title = aDocShell.document.title || url; charSet = aDocShell.document.characterSet; } catch (e) { title = url; } if (cmdFromMultibar) BookmarksUtils.addBookmarkFromMultibar(url, title, charSet, aIsWebPanel); else BookmarksUtils.addBookmark(url, title, charSet, aIsWebPanel); } // MERC (DP): this function is only called from inside tabbrowser. It is needed // for the case when you add a bookmark using the tab context menu from a // non-active tab. function bookmarkPageFromTabRightClick() { var uri = gBrowser.getBrowserForTab(gBrowser.mContextTab).currentURI.spec; var title = gBrowser.mContextTab.label; BookmarksUtils.addBookmark(uri, title); } function openLocation() { if (gURLBar && !gURLBar.parentNode.parentNode.collapsed) { gURLBar.focus(); gURLBar.select(); } else { openDialog("chrome://browser/content/openLocation.xul", "_blank", "chrome,modal,titlebar", window); } } function BrowserOpenTab() { gBrowser.selectedTab = gBrowser.addTabAt('about:blank'); // MERC (rpaul) update the current engine broadcaster for the statusbar // blank tabs are by default Gecko //UpdateStatusBarEngineIcon(); if (gURLBar) setTimeout(function() { gURLBar.focus(); }, 0); } function BrowserNetscapeTab() { var url; var pref = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); try { url = gPrefService.getComplexValue("browser.netscape.homepage", Components.interfaces.nsIPrefLocalizedString).data; } catch(e) {dump ("Caught Exception: " + e + "\n"); } gBrowser.selectedTab = gBrowser.addTabAt(url); } //<JA ff5->vulp var gCurrentDocCharset = null; function BrowserStoreTabCharset() { gCurrentDocCharset = window._content.document.characterSet; } function BrowserOpenPrefTab() { gBrowser.selectedTab = gBrowser.addPrefTab(); } // MERC (DP) function BrowserOpenNewCurrentTab() { currentTab = gBrowser.mCurrentTab; var curTabBrowser=gBrowser.getBrowserForTab(currentTab); var sHistory=curTabBrowser.sessionHistory; gBrowser.selectedTab = gBrowser.addTabAtWithFlag(0,gBrowser.getBrowserForTab(currentTab).currentURI.spec); var newTabBrowser=gBrowser.getBrowserForTab(gBrowser.selectedTab); newTabBrowser.sessionHistory.appendFrom(sHistory); }//JA/> /* Called from the openLocation dialog. This allows that dialog to instruct its opener to open a new window and then step completely out of the way. Anything less byzantine is causing horrible crashes, rather believably, though oddly only on Linux. */ function delayedOpenWindow(chrome,flags,url) { // The other way to use setTimeout, // setTimeout(openDialog, 10, chrome, "_blank", flags, url), // doesn't work here. The extra "magic" extra argument setTimeout adds to // the callback function would confuse prepareForStartup() by making // window.arguments[1] be an integer instead of null. setTimeout(function() { openDialog(chrome, "_blank", flags, url); }, 10); } /* Required because the tab needs time to set up its content viewers and get the load of the URI kicked off before becoming the active content area. */ function delayedOpenTab(url) { setTimeout(function(aTabElt) { gBrowser.selectedTab = aTabElt; }, 0, gBrowser.addTabAt(url)); } function BrowserOpenFileWindow() { // Get filepicker component. try { const nsIFilePicker = Components.interfaces.nsIFilePicker; var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker); fp.init(window, gNavigatorBundle.getString("openFile"), nsIFilePicker.modeOpen); fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText | nsIFilePicker.filterImages | nsIFilePicker.filterXML | nsIFilePicker.filterHTML); if (fp.show() == nsIFilePicker.returnOK) { // MERC (DP): respect local file open pref var openPref = gPrefService.getCharPref("browser.tabs.localfile.open"); if (openPref == 'overwrite') { openTopWin(fp.fileURL.spec); } else { // dump("Opening file: " + fp.fileURL.spec + " with addTabAt()\n"); var t = gBrowser.addTabAt(fp.fileURL.spec); if(!gPrefService.getBoolPref("browser.tabs.loadInBackground")) { gBrowser.selectedTab = t; } } // END MERC } } catch (ex) { } } function BrowserCloseCurrentTab() { setTimeout("gBrowser.removeCurrentTab();", 10); } function BrowserDelayRemoveAllTabsBut() { setTimeout("gBrowser.removeAllTabsBut(gBrowser.mCurrentTab);", 10 ); } function BrowserDelayCloseAllTabsToLeft() { setTimeout("gBrowser.closeAllTabsToLeft(gBrowser.mContextTab);", 10 ); } function BrowserDelayCloseAllTabsToRight() { setTimeout("gBrowser.closeAllTabsToRight(gBrowser.mContextTab);", 10 ); } function BrowserDelayCloseAllBlankTabs() { setTimeout("gBrowser.closeAllBlankTabs();", 10 ); } function DelayCloseAllTabsFromSameSite() { setTimeout("gBrowser.closeAllTabsFromSameSite(gBrowser.mContextTab);", 10 ); } function DelayCloseAllTabsExceptFromSameSite() { setTimeout("gBrowser.closeAllTabsExceptFromSameSite(gBrowser.mContextTab);", 10 ); } function BrowserCloseTabOrWindow() { //dump("\nJA~~~~~~~~~~~~~:BrowserCloseThisTabOrWindow: hpSomeDoc\n"); if (gBrowser.localName == 'tabbrowser' && gBrowser.tabContainer.childNodes.length > 1) { // Just close up a tab. gBrowser.removeCurrentTab(); return; } BrowserCloseWindow(); } //JA function BrowserGetTabsCount() { return gBrowser.tabContainer.childNodes.length; } function BrowserCloseThisTabOrWindow(hpSomeDoc) { //dump("\nJA~~~~~~~~~~~~~:BrowserCloseThisTabOrWindow: hpSomeDoc ="+hpSomeDoc+"\n"); if(!hpSomeDoc) return false;//err var cnTabs = gBrowser.tabContainer.childNodes; var numtabs = cnTabs.length; if (numtabs>1) { for (var i = 0; i < numtabs; ++i) { var doc = gBrowser.getBrowserForTab(cnTabs[i]).contentDocument; if (doc == hpSomeDoc) { //dump("!!!!!~~~~~~~~~~~~~~Found in tab# "+i+"\n"); cnTabs[i].isClosing = true; setTimeout(function(n){ gBrowser.removeTab(gBrowser.tabContainer.childNodes[n]); }, 0, i); //gBrowser.removeTab(cnTabs[i]);crashes plugin! return true; } } } else if(numtabs ==1 && hpSomeDoc == gBrowser.getBrowserForTab(cnTabs[0]).contentDocument) { //dump("~~~~~~~~~~~~~~~~Found in the only tab!\n\n"); setTimeout("BrowserCloseWindow()"); return true; } //dump("~~~~~~~~~~Couldn't find hpSomeDoc!\n\n"); return false; } //end JA function BrowserTryToCloseWindow() { //give tryToClose a chance to veto if it is defined if (typeof(window.tryToClose) != "function" || window.tryToClose()) BrowserCloseWindow(); } function BrowserCloseWindow() { // This code replicates stuff in Shutdown(). It is here because // window.screenX and window.screenY have real values. We need // to fix this eventually but by replicating the code here, we // provide a means of saving position (it just requires that the // user close the window via File->Close (vs. close box). // Get the current window position/size. var x = window.screenX; var y = window.screenY; var h = window.outerHeight; var w = window.outerWidth; // Store these into the window attributes (for persistence). var win = document.getElementById( "main-window" ); win.setAttribute( "x", x ); win.setAttribute( "y", y ); win.setAttribute( "height", h ); win.setAttribute( "width", w ); closeWindow(true); } function loadURI(uri, referrer, postData) { // dump('************ loadURI('+uri+') *******************\n'); var docshell = getWebNavigation(); var hpDoc; if (docshell.browserEngine == 'Trident') hpDoc = getTridentDocument(); //JA if we have Trident running, check if we have to switch to Gecko, otherwise //JA decision about engine is made in nsContenDLF.cpp! if (hpDoc) { var sc = sitecontrols.SCSVC; // this will put a http:// in front of the uri if needed if (!gURIFixup) gURIFixup = Components.classes["@mozilla.org/docshell/urifixup;1"] .getService(Components.interfaces.nsIURIFixup); var urispec; if (!uri || (uri == '')) urispec = 'about:blank'; else urispec = gURIFixup.createFixupURI(uri, 0).spec; if ((urispec != 'about:blank') && (!sc.isControllableURI(urispec))) { // Generally speaking, for non-controllable URIs we want to force // the engine into Gecko... docshell.browserEngine = 'Gecko'; } else { // At this point we know that the URI is either controllable or else // is 'about:blank', so the engine to use will be dictated by // Site Controls var site; if (uri == 'about:blank') { // We will treat this as if it's a DEFAULT site // This should be SiteControls:Default resource site = sc.getResourceForURI(''); } else site = sc.getResourceForURI(uri); docshell.browserEngine = sc.readSiteControlResource(site, "displayEngine"); } } // Check current engine try { if (docshell.browserEngine == 'Trident' && hpDoc) { hpDoc.navigateToURL(uri,null); } else { if (postData === undefined) postData = null; //var webnav = getWebNavigation(); docshell.loadURI(uri, nsIWebNavigation.LOAD_FLAGS_NONE, referrer, postData, null); gBrowser.mCurrentTab.removeAttribute("engine"); // MERC - SL - set focus to url bar for blank page loads (always gecko) if (uri == "about:blank") { var urlbar = document.getElementById("urlbar"); urlbar.focus(); } } } catch(e) {dump ("Caught Exception: " + e + "\n"); } // dump('************ END loadURI('+uri+') *******************\n'); } // MERC (DP): // uses openPref to determine whether to open URI in current tab or new tab. // set focus according to 'browser.tabs.loadInBackground' function loadURIWithOpenPref(uri, openPref, referrer, postData) { if (gPrefService.getCharPref(openPref) == 'overwrite') { loadURI(uri, referrer, postData); } else { // == 'new' var theTab = gBrowser.addTabAt(uri, undefined, referrer, null, postData); if (!gPrefService.getBoolPref("browser.tabs.loadInBackground")) gBrowser.selectedTab = theTab; } } /* trim leading and trailing whitespace from a string */ function trim(str) { str=str.replace(/^\s*/,""); str=str.replace(/\s*$/,""); return str; } /** * Given keywords in uri variable, simulate typing * stuff into search-bar **/ function BrowserSearchURL(uri, referrer, postData) { dump('browser.js: BrowserSearchURL('+uri+')\n'); // trim whitespace from either end of the uri var trimuri = trim(uri); if (trimuri) search.AddToHistory(trimuri); var searchURL = gPrefService.getCharPref('keyword.URL') + encodeURIComponent(trimuri); loadURIWithOpenPref(searchURL, "browser.tabs.searchbarresult.open", referrer, postData); var searchSvc = Components.classes["@mozilla.org/rdf/datasource;1?name=internetsearch"] .getService(Components.interfaces.nsIInternetSearchService); searchSvc.FindInternetSearchResults(searchURL); } // MERC (DP): // added the param bOpenWithPref. this determines whether to open the URL // in current OR new tab function BrowserLoadURL(aTriggeringEvent, aPostData, aOpenWithPref) { if (!gURLBar) gURLBar = document.getElementById("urlbar"); var url = gURLBar.value; dump('browser.js: BrowserLoadURL(): '+url+'\n'); // MERC (DP): save the current URL var currURL = getWebNavigation().currentURI.spec; if (url.match(/^view-source:/)) { BrowserViewSourceOfURL(url.replace(/^view-source:/, ""), null, null); } else if (url.match(/^search:/)) { BrowserSearchURL(url.replace(/^search:/, ""), null, aPostData); } else { if (gBrowser.localName == "tabbrowser" && aTriggeringEvent && 'altKey' in aTriggeringEvent && aTriggeringEvent.altKey) { _content.focus(); // JMC - only happens on an altKey load // MERC (DP): add tab and focus according to prefs var t = gBrowser.addTabAt(url, undefined, null, null, aPostData); // open link in new tab if (!gPrefService.getBoolPref("browser.tabs.loadInBackground")) { gBrowser.selectedTab = t; gURLBar.value = url; } else { gURLBar.value = currURL; } //dump('browser.js: gURLbar.value = '+gURLBar.value+'\n\n'); // END MERC event.preventDefault(); event.preventBubble(); event.preventCapture(); event.stopPropagation(); } else { // if no pref passed in, load in current tab. // otherwise open url according to pref if (aOpenWithPref) { loadURIWithOpenPref(url, aOpenWithPref, null, aPostData); } else { loadURI(url, null, aPostData); } } dump ("BrowserLoadURL: Currently focused element is : " + document.commandDispatcher.focusedElement.getAttribute('anonid') + ", at least that's what commandDispatcher thinks.\n"); if (document.commandDispatcher.focusedElement.getAttribute('anonid') != 'input') { _content.focus(); dump ("Now the _content is focused, which is : " + _content + "\n"); } else { gBrowser.userTypedValue = null; gBrowser.userTypedClear = true; SetPageProxyState("valid", null); // XXX Build a URI and pass it in here. } // JMC - Note that this hack doesn't work in trident navigation // JMC - Is this URLBar defocusing? } UpdateStatusBarEngineIcon(); } function SearchLoadURL(aURL, aTriggeringEvent, reuseTab) { // dump ("SearchLoadURL : " + aURL + "\t"); // showStack(); // We need to add a flag to reuse the same tab for browsing. // First search through the tabs to see if we have a "search" tab var cnTabs = gBrowser.tabContainer.childNodes; var numtabs = cnTabs.length; var tabBrowser = getBrowser(); // MERC (rpaul) only reuse a tab if called from showMoreResults() if (numtabs>=1 && reuseTab) { for (var i = 0; i < numtabs; ++i) { var searchAttrib = cnTabs[i].getAttribute("searchtab"); if (searchAttrib) { // This tab is usable as a search tab gBrowser.selectedTab = cnTabs[i]; loadURI(aURL,null,null); return; } else { cnTabs[i].removeAttribute("searchtab"); } } loadURIWithOpenPref(aURL, "browser.tabs.searchbarresult.open", null, null); gBrowser.selectedTab.setAttribute("searchtab", "true"); } else { // clear any existing searchtab attributes from tabs for (var j = 0; j < numtabs; ++j) { if (cnTabs[j].getAttribute("searchtab")) { cnTabs[j].removeAttribute("searchtab"); } } // Load according to preferences since we are not reusing a search tab loadURIWithOpenPref(aURL, "browser.tabs.searchbarresult.open", null, null); var curTab = gBrowser.selectedTab; if (curTab) { curTab.setAttribute("searchtab","true"); } } _content.focus(); var internetSearch = Components.classes["@mozilla.org/rdf/datasource;1?name=internetsearch"] .getService(nsIInternetSearchService); internetSearch.FindInternetSearchResults(aURL); } function getShortcutOrURI(aURL, aPostDataRef) { // rjc: added support for URL shortcuts (3/30/1999) try { var shortcutURL = BMSVC.resolveKeyword(aURL, aPostDataRef); if (!shortcutURL) { // rjc: add support for string substitution with shortcuts (4/4/2000) // (see bug # 29871 for details) var aOffset = aURL.indexOf(" "); if (aOffset > 0) { var cmd = aURL.substr(0, aOffset); var text = aURL.substr(aOffset+1); shortcutURL = BMSVC.resolveKeyword(cmd, aPostDataRef); if (shortcutURL && text) { if (aPostDataRef && aPostDataRef.value) { // XXXben - currently we only support "application/x-www-form-urlencoded" // enctypes. aPostDataRef.value = unescape(aPostDataRef.value); if (aPostDataRef.value.match(/%s/)) { aPostDataRef.value = getPostDataStream(aPostDataRef.value, text, "application/x-www-form-urlencoded"); } else { shortcutURL = null; aPostDataRef.value = null; } } else shortcutURL = shortcutURL.match(/%s/) ? shortcutURL.replace(/%s/g, encodeURIComponent(text)) : null; } } } if (shortcutURL) aURL = shortcutURL; } catch (ex) { } return aURL; } function getPostDataStream(aStringData, aKeyword, aType) { var dataStream = Components.classes["@mozilla.org/io/string-input-stream;1"] .createInstance(Components.interfaces.nsIStringInputStream); aStringData = aStringData.replace(/%s/g, encodeURIComponent(aKeyword)); dataStream.setData(aStringData, aStringData.length); var mimeStream = Components.classes["@mozilla.org/network/mime-input-stream;1"] .createInstance(Components.interfaces.nsIMIMEInputStream); mimeStream.addHeader("Content-Type", aType); mimeStream.addContentLength = true; mimeStream.setData(dataStream); return mimeStream.QueryInterface(Components.interfaces.nsIInputStream); } function readFromClipboard() { var url; try { // Get clipboard. var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"] .getService(Components.interfaces.nsIClipboard); // Create tranferable that will transfer the text. var trans = Components.classes["@mozilla.org/widget/transferable;1"] .createInstance(Components.interfaces.nsITransferable); trans.addDataFlavor("text/unicode"); // If available, use selection clipboard, otherwise global one if (clipboard.supportsSelectionClipboard()) clipboard.getData(trans, clipboard.kSelectionClipboard); else clipboard.getData(trans, clipboard.kGlobalClipboard); var data = {}; var dataLen = {}; trans.getTransferData("text/unicode", data, dataLen); if (data) { data = data.value.QueryInterface(Components.interfaces.nsISupportsString); url = data.data.substring(0, dataLen.value / 2); } } catch (ex) { } return url; } function BrowserViewSourceOfDocument(aDocument) { var docCharset; var pageCookie; var webNav; // Get the document charset docCharset = "charset=" + aDocument.characterSet; // Get the nsIWebNavigation associated with the document try { var win; var ifRequestor; // Get the DOMWindow for the requested document. If the DOMWindow // cannot be found, then just use the _content window... // // XXX: This is a bit of a hack... win = aDocument.defaultView; if (win == window) { win = _content; } ifRequestor = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor); webNav = ifRequestor.getInterface(nsIWebNavigation); } catch(err) { // If nsIWebNavigation cannot be found, just get the one for the whole // window... webNav = getWebNavigation(); } // // Get the 'PageDescriptor' for the current document. This allows the // view-source to access the cached copy of the content rather than // refetching it from the network... // try { var PageLoader = webNav.QueryInterface(Components.interfaces.nsIWebPageDescriptor); pageCookie = PageLoader.currentDescriptor; } catch(err) { // If no page descriptor is available, just use the view-source URL... } BrowserViewSourceOfURL(webNav.currentURI.spec, docCharset, pageCookie); } function BrowserViewSourceOfURL(url, charset, pageCookie) { // try to open a view-source window while inheriting the charset (if any) openDialog("chrome://global/content/viewSource.xul", "_blank", "scrollbars,resizable,chrome,dialog=no", url, charset, pageCookie); } // doc=null for regular page info, doc=owner document for frame info. function BrowserPageInfo(doc) { var hpDoc = getTridentDocument(); if (hpDoc) { hpDoc.showPageInfo(); } else { window.openDialog("chrome://browser/content/pageInfo.xul", "_blank", "chrome,dialog=no", doc); } } function checkForDirectoryListing() { if ( "HTTPIndex" in _content && _content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) { _content.defaultCharacterset = getMarkupDocumentViewer().defaultCharacterSet; } } function URLBarFocusHandler(aEvent, aElt) { if (gIgnoreFocus) gIgnoreFocus = false; else if (gClickSelectsAll) aElt.select(); } function URLBarMouseDownHandler(aEvent, aElt) { if (aElt.hasAttribute("focused")) { gIgnoreClick = true; } else { gIgnoreFocus = true; gIgnoreClick = false; aElt.setSelectionRange(0, 0); } } function URLBarClickHandler(aEvent, aElt) { if (!gIgnoreClick && gClickSelectsAll && aElt.selectionStart == aElt.selectionEnd) aElt.select(); } // If "ESC" is pressed in the url bar, we replace the urlbar's value with the url of the page // and highlight it, unless it is about:blank, where we reset it to "". function handleURLBarRevert() { dump ("handleURLBarRevent()\n"); var url = getWebNavigation().currentURI.spec; var throbberElement = document.getElementById("throbberBroadcaster"); var isScrolling = gURLBar.popupOpen; // don't revert to last valid url unless page is NOT loading // and user is NOT key-scrolling through autocomplete list if ((!throbberElement || !throbberElement.hasAttribute("busy")) && !isScrolling) { if (url != "about:blank") { gURLBar.value = url; gURLBar.select(); SetPageProxyState("valid", null); // XXX Build a URI and pass it in here. } else { //if about:blank, urlbar becomes "" gURLBar.value = ""; } } gBrowser.userTypedValue = null; // tell widget to revert to last typed text only if the user // was scrolling when they hit escape return !isScrolling; } function TextIsURI(selectedText) { return selectedText && /^http:\/\/|^https:\/\/|^file:\/\/|\ ^ftp:\/\/|^about:|^mailto:|^news:|^snews:|^telnet:|^ldap:|\ ^ldaps:|^gopher:|^finger:|^javascript:/i.test(selectedText); } function shouldPrependSearch(url) { // if search: is already at the beginning, don't add it again if (/^search:/.test(url)) { return false; } // trim leading/trailing whitespace trimmedURL = url.replace(/^\s*/, '').replace(/\s*$/, ''); // if string is empty do not prepend if (!trimmedURL) return false; // if string has protocol, do not prepend if( /^http:\/\/|^https:\/\/|^file:\/\/|\ ^ftp:\/\/|^about:|^mailto:|^news:|^snews:|^telnet:|^ldap:|\ ^ldaps:|^gopher:|^finger:|^javascript:/i.test(trimmedURL) ) { return false; } // if the string looks like a path to a local file, do not prepend if (/^[a-z]:\\/.test(trimmedURL)) { return false; } // if whitespace occurs in the url, treat it as a search if (/\s+/.test(trimmedURL)) { return true; } // if any dots occur in the url, DO NOT treat as search if (/\./.test(url)) { return false; } return false; } function handleURLBarCommand(aTriggeringEvent) { var postData = { }; canonizeUrl(aTriggeringEvent, postData); try { addToUrlbarHistory(); } catch (ex) { // Things may go wrong when adding url to session history, // but don't let that interfere with the loading of the url. } BrowserLoadURL(aTriggeringEvent, postData.value); // BrowserLoadURL(aTriggeringEvent, postData.value, "browser.tabs.history.open"); } function canonizeUrl(aTriggeringEvent, aPostDataRef) { if (!gURLBar || gURLBar.value == '') return; var url = gURLBar.value; if (shouldPrependSearch(url)) { url = 'search:'+url; } // Prevent suffix when already exists www , http , / else if (!/^(www|http)|\/\s*$/i.test(url)) { var suffix = null; if (aTriggeringEvent && 'ctrlKey' in aTriggeringEvent && aTriggeringEvent.ctrlKey && 'shiftKey' in aTriggeringEvent && aTriggeringEvent.shiftKey) { suffix = ".org/"; } else if (aTriggeringEvent && 'ctrlKey' in aTriggeringEvent && aTriggeringEvent.ctrlKey) { suffix = ".com/"; } else if (aTriggeringEvent && 'shiftKey' in aTriggeringEvent && aTriggeringEvent.shiftKey) { suffix = ".net/"; } if (suffix != null) { // trim leading/trailing spaces (bug 233205) url = url.replace(/^\s+/, ""); url = url.replace(/\s+$/, ""); // Tack www. and suffix on. url = "http://www." + url + suffix; } } gURLBar.value = getShortcutOrURI(url, aPostDataRef); } function UpdatePageProxyState() { if (gURLBar && gURLBar.value != gLastValidURLStr) SetPageProxyState("invalid", null); } // MERC - JCH: Called in nsHTMLPluginDocument.cpp to update favicons //function UpdateFavIcons(windowDoc) // MRR - This function signature will change when nsHTMLPluginDocument is rationalized. // Will become: function UpdateFavIcons(windowDoc, aHref) function UpdateFavIcons( aHref, dummy1, dummy2, dummy3, windowDoc) { if (windowDoc == null) return false; var tabIndex = gBrowser.getBrowserIndexForDocument(windowDoc); if (tabIndex < 0) return false; var aTab = gBrowser.tabContainer.childNodes[tabIndex]; if (aTab == null) return false; var tabUri = gBrowser.getBrowserForTab(aTab).currentURI; // dump( ")) WMWMWMWMWMW===> UpdateFavIcons(\""+tabUri.spec+"\") from TRIDENT\n" ); // dump( ")) WMWMWMWMWMW===> UpdateFavIcons - Trident passed \""+aHref+"\"\n" ); if (gBrowser.shouldLoadFavIcon(tabUri)) { var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); var favIconURI = ios.newURI(aHref, null, tabUri); var favIconURIstr = ""; if ( aHref == "" ) { favIconURIstr = gBrowser.buildFavIconString(tabUri); favIconURI.spec = favIconURIstr; } else { favIconURIstr = favIconURI.spec; } // dump( ")) WMWMWMWMWMW===> UpdateFavIcons - Yay; Built \""+favIconURI.spec+"\"\n" ); // This sets the icon on the tab. gBrowser.mCurrentBrowser.mFavIconURL = favIconURIstr; aTab.setAttribute('image', favIconURIstr); // This sets the icon on the listener, so switch tabs synchs the icon in URL bar. if (gBrowser.mTabbedMode) gBrowser.mTabListeners[tabIndex].mIcon = gBrowser.mCurrentBrowser.mFavIconURL; // This sets the icon on the URL bar. PageProxySetIcon(gBrowser.mCurrentBrowser.mFavIconURL); } else { //dump( "---------- UpdateFavIcons: Clearing icon\n"); aTab.removeAttribute("image"); gBrowser.mCurrentBrowser.mFavIconURL = null; if (gBrowser.mTabListeners[tabIndex]) { gBrowser.mTabListeners[tabIndex].mIcon = null; PageProxyClearIcon(); } } return true; } function StartTabProgress(hpSomeDoc) { //dump("\nJA~~~~~~~~~~~~~:StartTabProgress(): hpSomeDoc ="+hpSomeDoc+"\n"); if(!hpSomeDoc) return false;//err // loop through all the tabs and match which trident document this event has originated from var cnTabs = gBrowser.tabContainer.childNodes; var numtabs = cnTabs.length; var tabBrowser = getBrowser(); if (numtabs>=1) { for (var i = 0; i < numtabs; ++i) { var doc = gBrowser.getBrowserForTab(cnTabs[i]).contentDocument; if (doc && doc == hpSomeDoc) { //dump("!!!!!~~~~~~~~~~~~~~Found in tab# "+i+"\n"); cnTabs[i].setAttribute("busy", "true"); cnTabs[i].label = tabBrowser.mStringBundle.getString("tabs.loading"); cnTabs[i].removeAttribute("image"); cnTabs[i].mIcon = null; cnTabs[i].setAttribute("engine", "Trident"); if (cnTabs[i].getAttribute("selected") == "true") { // Start Progress Listener var webProgress = gBrowser.getBrowserForTab(cnTabs[i]).webProgress; window.XULBrowserWindow.onStateChange(webProgress, null, Components.interfaces.nsIWebProgressListener.STATE_START | Components.interfaces.nsIWebProgressListener.STATE_IS_NETWORK, 0); UpdateStatusBarEngineIcon(); } return true; } } } //dump("~~~~~~~~~~Couldn't find hpSomeDoc!\n\n"); return false; } function EndTabProgress(hpSomeDoc) { // loop through all the tabs and match which trident document this event has originated from if(!hpSomeDoc) return false;//err var cnTabs = gBrowser.tabContainer.childNodes; var numtabs = cnTabs.length; var tabBrowser = getBrowser(); if (numtabs>=1) { for (var i = 0; i < numtabs; ++i) { var doc = gBrowser.getBrowserForTab(cnTabs[i]).contentDocument; if (doc && doc == hpSomeDoc) { //dump("!!!!!~~~~~~~~~~~~~~Found in tab# "+i+"\n"); cnTabs[i].removeAttribute("busy") tabBrowser.setTabTitle(cnTabs[i]); if (cnTabs[i].getAttribute("selected") == "true") { // Stop Progress Listener var webProgress = gBrowser.getBrowserForTab(cnTabs[i]).webProgress; window.XULBrowserWindow.onStateChange(webProgress, null, Components.interfaces.nsIWebProgressListener.STATE_STOP | Components.interfaces.nsIWebProgressListener.STATE_IS_NETWORK, 0); } return true; } } } //dump("~~~~~~~~~~Couldn't find hpSomeDoc!\n\n"); return false; } function SetPageProxyState(aState, aURI) { if (!gURLBar) return; if (!gProxyButton) gProxyButton = document.getElementById("page-proxy-button"); if (!gProxyFavIcon) gProxyFavIcon = document.getElementById("page-proxy-favicon"); if (!gProxyDeck) gProxyDeck = document.getElementById("page-proxy-deck"); gProxyButton.setAttribute("pageproxystate", aState); // if ( aURI ) // dump( ")) WMWMWMWMWMW===> SetPageProxyState(\""+aURI.spec+"\") - gProxyFavIcon is: \""+gProxyFavIcon.getAttribute("src")+"\"\n" ); // else // dump( ")) WMWMWMWMWMW===> SetPageProxyState(null) - gProxyFavIcon is: \""+gProxyFavIcon.getAttribute("src")+"\"\n" ); // the page proxy state is set to valid via OnLocationChange, which // gets called when we switch tabs. We'll let updatePageFavIcon // take care of updating the mFavIconURL because it knows exactly // for which tab to update things, instead of confusing the issue // here. if (aState == "valid") { gLastValidURLStr = gURLBar.value; gURLBar.addEventListener("input", UpdatePageProxyState, false); if (gBrowser.mCurrentBrowser.mFavIconURL != null) { if (gBrowser.isFavIconKnownMissing(gBrowser.mCurrentBrowser.mFavIconURL)) { gBrowser.mFavIconURL = null; // dump( ")) WMWMWMWMWMW===> SetPageProxyState() - clearing icon (#1)\n" ); PageProxyClearIcon(); } else { PageProxySetIcon(gBrowser.mCurrentBrowser.mFavIconURL); } } else { // dump( ")) WMWMWMWMWMW===> SetPageProxyState() - clearing icon (#2)\n" ); PageProxyClearIcon(); } } else if (aState == "invalid") { gURLBar.removeEventListener("input", UpdatePageProxyState, false); PageProxyClearIcon(); } } function PageProxySetIcon (aURL) { if (!gProxyFavIcon) return; if (gProxyFavIcon.getAttribute("src") != aURL) gProxyFavIcon.setAttribute("src", aURL); if (gProxyDeck && gProxyDeck.selectedIndex != 1 && gProxyFavIcon.getAttribute("src")) gProxyDeck.selectedIndex = 1; else if (gProxyDeck && gProxyDeck.selectedIndex != 0 && !gProxyFavIcon.getAttribute("src")) gProxyDeck.selectedIndex = 0; // dump( ")) WMWMWMWMWMW===> PageProxySetIcon(\""+aURL+"\"); index="+gProxyDeck.selectedIndex+"\n" ); } function PageProxyClearIcon () { // dump( ")) WMWMWMWMWMW===> PageProxyClearIcon()\n" ); if (gProxyDeck && gProxyDeck.selectedIndex != 0) gProxyDeck.selectedIndex = 0; if (gProxyFavIcon && gProxyFavIcon.hasAttribute("src")) gProxyFavIcon.removeAttribute("src"); } function PageProxyDragGesture(aEvent) { if (gProxyButton.getAttribute("pageproxystate") == "valid") { nsDragAndDrop.startDrag(aEvent, proxyIconDNDObserver); return true; } return false; } function URLBarOnDrop(evt) { nsDragAndDrop.drop(evt, urlbarObserver); } var urlbarObserver = { onDrop: function (aEvent, aXferData, aDragSession) { var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType); // The URL bar automatically handles inputs with newline characters, // so we can get away with treating text/x-moz-url flavours as text/unicode. if (url) { getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url); // XXXBlake Workaround caret crash when you try to set the textbox's value on dropping setTimeout(function(u) { gURLBar.value = u; handleURLBarCommand(); }, 0, url); } }, getSupportedFlavours: function () { var flavourSet = new FlavourSet(); // Plain text drops are often misidentified as "text/x-moz-url", so favor plain text. flavourSet.appendFlavour("text/unicode"); flavourSet.appendFlavour("text/x-moz-url"); flavourSet.appendFlavour("application/x-moz-file", "nsIFile"); return flavourSet; } } function SearchBarOnDrop(evt) { nsDragAndDrop.drop(evt, searchbarObserver); } var searchbarObserver = { onDrop: function (aEvent, aXferData, aDragSession) { var data = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType); if (data) { // XXXBlake Workaround caret crash when you try to set the textbox's value on dropping var field = document.getElementById("search-bar"); setTimeout(function(field, data, evt) { field.value = data; field.onTextEntered(evt); }, 0, field, data, aEvent); } }, getSupportedFlavours: function () { var flavourSet = new FlavourSet(); flavourSet.appendFlavour("text/unicode"); flavourSet.appendFlavour("text/x-moz-url"); flavourSet.appendFlavour("application/x-moz-file", "nsIFile"); return flavourSet; } } function SearchBarPopupShowing(aEvent) { } function SearchBarPopupCommand(aEvent) { if (!aEvent.target.id) return; if (aEvent.target.id == "miAddEngines") { var regionBundle = document.getElementById("bundle_browser_region"); loadURI(regionBundle.getString("searchEnginesURL"), null, null); return; } document.getElementById("search-bar").currentEngine = aEvent.target.id; } function showSearchEnginePopup() { var searchEnginePopup = document.getElementById("SearchBarPopup"); var searchEngineButton = document.getElementById("search-proxy-button"); searchEnginePopup.showPopup(searchEngineButton); } function updateToolbarStates(toolbarMenuElt) { if (!gHaveUpdatedToolbarState) { var mainWindow = document.getElementById("main-window"); if (mainWindow.hasAttribute("chromehidden")) { gHaveUpdatedToolbarState = true; var i; for (i = 0; i < toolbarMenuElt.childNodes.length; ++i) document.getElementById(toolbarMenuElt.childNodes[i].getAttribute("observes")).removeAttribute("checked"); var toolbars = document.getElementsByTagName("toolbar"); // Start i at 1, since we skip the menubar. for (i = 1; i < toolbars.length; ++i) { if (toolbars[i].getAttribute("class").indexOf("chromeclass") != -1) toolbars[i].setAttribute("collapsed", "true"); } toolbars = document.getElementsByTagName("multibar"); for (i = 0; i < toolbars.length; ++i) { if (toolbars[i].getAttribute("class").indexOf("chromeclass") != -1) toolbars[i].setAttribute("collapsed", "true"); } var statusbars = document.getElementsByTagName("statusbar"); for (i = 1; i < statusbars.length; ++i) { if (statusbars[i].getAttribute("class").indexOf("chromeclass") != -1) statusbars[i].setAttribute("collapsed", "true"); } var toolbox = document.getElementById("navigator-toolbox"); toolbox.reorderToolbars(); mainWindow.removeAttribute("chromehidden"); } } } function BrowserImport() { var features = "modal,centerscreen,chrome,resizable=no"; window.openDialog("chrome://browser/content/migration/migration.xul", "migration", features); } function BrowserFullScreen() { window.fullScreen = !window.fullScreen; } function BrowserToggleMaximize() { if (window.windowState == window.STATE_MAXIMIZED) { window.restore(); document.getElementById('main-window').setAttribute('sizemode', 'normal'); document.getElementById('restoreButtonBroadcaster').tooltipText = 'Maximize'; isButtonToggle = true; } else { window.maximize(); document.getElementById('main-window').setAttribute('sizemode', 'maximized'); document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down'; isButtonToggle = false; } reshuffleToolbars(); } function onWindowResize() { if (window.windowState == window.STATE_MAXIMIZED) document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down'; else if (window.windowState == window.STATE_NORMAL) document.getElementById('restoreButtonBroadcaster').tooltipText = 'Maximize'; BookmarksToolbar.resizeFunc(); } function onFullScreen() { if(isButtonToggle) { if (window.windowState == window.STATE_MAXIMIZED) { document.getElementById('main-window').setAttribute('sizemode', 'normal'); document.getElementById('restoreButtonBroadcaster').tooltipText = 'Maximize'; } else { document.getElementById('main-window').setAttribute('sizemode', 'maximized'); document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down'; } } else { document.getElementById('main-window').setAttribute('sizemode', 'maximized'); document.getElementById('restoreButtonBroadcaster').tooltipText = 'Restore Down'; } FullScreen.toggle(); } function getWebNavigation() { try { return gBrowser.webNavigation; } catch (e) { return null; } } function BrowserReloadWithFlags(reloadFlags) { // MERC JVL // stop the browser first (within the context) before proceeding with the reload BrowserStop(); //JA var hpDoc; var webNav = getWebNavigation(); if(webNav.browserEngine=="Trident") hpDoc=getTridentDocument(); if(hpDoc) { var webProgress = gBrowser.webProgress; window.XULBrowserWindow.onStateChange(webProgress, null, Components.interfaces.nsIWebProgressListener.STATE_START | Components.interfaces.nsIWebProgressListener.STATE_IS_NETWORK, 0); hpDoc.reloadDocument();//end JA } else //default { /* First, we'll try to use the session history object to reload so * that framesets are handled properly. If we're in a special * window (such as view-source) that has no session history, fall * back on using the web navigation's reload method. */ // check site control to try to switch engine var needSwitchEngine=false; var bRedirected; try { var site = webNav.currentURI.host; var bControlled=sitecontrols.SCSVC.isControlledSite(site); var displayEngine; if(bControlled) displayEngine=sitecontrols.SCSVC.readSiteControl(site, "displayEngine"); else displayEngine=sitecontrols.SCSVC.readSiteControl(sitecontrols.DEFAULT_SITE, "displayEngine"); if (displayEngine=="Trident") { needSwitchEngine=true; webNav.browserEngine='Trident'; } if (needSwitchEngine) { var filePath=webNav.currentURI.path; //SLiu, if it is a image url, and reload will cause switch engine from Gecko to Trident //we let browser load a Trident blank page first then navigate to the image url var len=filePath.length; var isImgURL=false; if (len > 4) //".jpg" { var fileType=filePath.substr(len-3, 3); fileType.toLowerCase(); var imgExtList= new Array('gif','jpg','bmp','png'); var i; for (i=0;i<imgExtList.length;i++) { if (fileType==imgExtList[i]) { isImgURL=true; break; } } } if(isImgURL) { bRedirected=true; var urlStr = Components.classes["@mozilla.org/supports-string;1"] .createInstance(Components.interfaces.nsISupportsString); urlStr.data = webNav.currentURI.spec; gPrefService.setComplexValue("browser.navigation.nexturl", Components.interfaces.nsISupportsString, urlStr); var blankPage="about:blank"; webNav.loadURI(blankPage, nsIWebNavigation.LOAD_FLAGS_NONE, null, null, null); } } }//end default catch(ex){ dump ("Caught Exception: " + ex + "\n");} try { if(!bRedirected) { // dump ("~~~~~~~~browser.js: webNav.reload(...)\n"); webNav.reload(reloadFlags); } } catch(ex){ dump ("Caught Exception: " + ex + "\n");} } } function toggleAffectedChrome(aHide) { // chrome to toggle includes: // (*) menubar // (*) navigation bar // (*) bookmarks toolbar // (*) sidebar // (*) find bar // (*) statusbar var menuBar = document.getElementById("menubar-items"); if (menuBar) menuBar.hidden = aHide; var navToolbox = document.getElementById("navigator-toolbox"); navToolbox.hidden = aHide; var statusbar = document.getElementById("status-bar"); statusbar.hidden = aHide; var throbber = document.getElementById("throbber-box"); if (throbber) { throbber.hidden = aHide; } if (aHide) { gChromeState = {}; var sidebar = document.getElementById("sidebar-box"); gChromeState.sidebarOpen = !sidebar.hidden; gSidebarCommand = sidebar.getAttribute("sidebarcommand"); var findBar = document.getElementById("FindToolbar"); gChromeState.findOpen = !findBar.hidden; closeFindBar(); } else { if (gChromeState.findOpen) openFindBar(); } if (gChromeState.sidebarOpen) toggleSidebar(gSidebarCommand); } function onEnterPrintPreview() { toggleAffectedChrome(true); } function onExitPrintPreview() { // restore chrome to original state toggleAffectedChrome(false); if (spui) spui.RedrawComponents(); } function browserDoOLECmd(iCmd) { //Mercurial start var hpDoc = getTridentDocument(); try { switch(iCmd) { case 0://Page Setup if(hpDoc) hpDoc.doOLECmd(0); else PrintUtils.showPageSetup(); break; case 1://Print Preview // dump("Customize printpreview!\n"); if (hpDoc) { if (hpDoc.loadingState==nsIHTMLPluginDocument.LOADING) { ShowPrintErrorDialogForTrident(PRINT_PREVIEW_REQ_WHILE_TRIDENT_LOADING_ERROR); //alert("Page loading not finished, please wait!"); } else hpDoc.doOLECmd(1); } else PrintUtils.printPreview(onEnterPrintPreview, onExitPrintPreview); break; case 2: if (hpDoc) { if (hpDoc.loadingState==nsIHTMLPluginDocument.LOADING) { ShowPrintErrorDialogForTrident(PRINT_REQ_WHILE_TRIDENT_LOADING_ERROR); //alert("Page loading not finished, please wait!"); } else hpDoc.doOLECmd(2); } else PrintUtils.print(); break; case 4: if (hpDoc) hpDoc.doOLECmd(4); else ZoomManager.prototype.getInstance().reduce(); break; case 5: if (hpDoc) hpDoc.doOLECmd(5); else ZoomManager.prototype.getInstance().enlarge(); break; } } catch(e){ dump ("Caught Exception: " + e + "\n");} } function getMarkupDocumentViewer() { return gBrowser.markupDocumentViewer; } /** * Content area tooltip. * XXX - this must move into XBL binding/equiv! Do not want to pollute * browser.js with functionality that can be encapsulated into * browser widget. TEMPORARY! * * NOTE: Any changes to this routine need to be mirrored in ChromeListener::FindTitleText() * (located in mozilla/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp) * which performs the same function, but for embedded clients that * don't use a XUL/JS layer. It is important that the logic of * these two routines be kept more or less in sync. * (pinkerton) **/ function FillInHTMLTooltip(tipElement) { var retVal = false; if (tipElement.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") return retVal; const XLinkNS = "http://www.w3.org/1999/xlink"; var titleText = null; var XLinkTitleText = null; while (!titleText && !XLinkTitleText && tipElement) { if (tipElement.nodeType == Node.ELEMENT_NODE) { titleText = tipElement.getAttribute("title"); XLinkTitleText = tipElement.getAttributeNS(XLinkNS, "title"); } tipElement = tipElement.parentNode; } var texts = [titleText, XLinkTitleText]; var tipNode = document.getElementById("aHTMLTooltip"); for (var i = 0; i < texts.length; ++i) { var t = texts[i]; if (t && t.search(/\S/) >= 0) { tipNode.setAttribute("label", t); retVal = true; } } return retVal; } var proxyIconDNDObserver = { onDragStart: function (aEvent, aXferData, aDragAction) { var value = gURLBar.value; // XXX - do we want to allow the user to set a blank page to their homepage? // if so then we want to modify this a little to set about:blank as // the homepage in the event of an empty urlbar. if (!value) return; var urlString = value + "\n" + window._content.document.title; var htmlString = "<a href=\"" + value + "\">" + value + "</a>"; aXferData.data = new TransferData(); aXferData.data.addDataForFlavour("text/x-moz-url", urlString); aXferData.data.addDataForFlavour("text/unicode", value); aXferData.data.addDataForFlavour("text/html", htmlString); // we're copying the URL from the proxy icon, not moving // we specify all of them though, because d&d sucks and OS's // get confused if they don't get the one they want aDragAction.action = Components.interfaces.nsIDragService.DRAGDROP_ACTION_COPY | Components.interfaces.nsIDragService.DRAGDROP_ACTION_MOVE | Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK; } } var homeButtonObserver = { onDrop: function (aEvent, aXferData, aDragSession) { var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType); setTimeout(openHomeDialog, 0, url); }, onDragOver: function (aEvent, aFlavour, aDragSession) { var statusTextFld = document.getElementById("statusbar-display"); statusTextFld.label = gNavigatorBundle.getString("droponhomebutton"); aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK; }, onDragExit: function (aEvent, aDragSession) { var statusTextFld = document.getElementById("statusbar-display"); statusTextFld.label = ""; }, getSupportedFlavours: function () { var flavourSet = new FlavourSet(); flavourSet.appendFlavour("application/x-moz-file", "nsIFile"); flavourSet.appendFlavour("text/x-moz-url"); flavourSet.appendFlavour("text/unicode"); return flavourSet; } } function openHomeDialog(aURL) { var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService); var promptTitle = gNavigatorBundle.getString("droponhometitle"); var promptMsg = gNavigatorBundle.getString("droponhomemsg"); var pressedVal = promptService.confirmEx(window, promptTitle, promptMsg, (promptService.BUTTON_TITLE_YES * promptService.BUTTON_POS_0) + (promptService.BUTTON_TITLE_NO * promptService.BUTTON_POS_1), null, null, null, null, {value:0}); if (pressedVal == 0) { try { var str = Components.classes["@mozilla.org/supports-string;1"] .createInstance(Components.interfaces.nsISupportsString); str.data = aURL; gPrefService.setComplexValue("browser.startup.homepage", Components.interfaces.nsISupportsString, str); var homeButton = document.getElementById("home-button"); //homeButton.setAttribute("tooltiptext", aURL); //replaced as this is reported as a bug..JC } catch (ex) { dump("Failed to set the home page.\n"+ex+"\n"); } } } var bookmarksButtonObserver = { onDrop: function (aEvent, aXferData, aDragSession) { var split = aXferData.data.split("\n"); var url = split[0]; if (url != aXferData.data) { //do nothing if it's not a valid URL var name = split[1]; openDialog("chrome://browser/content/bookmarks/addBookmark2.xul", "", "centerscreen,chrome,dialog,resizable,dependent", name, url); } }, onDragOver: function (aEvent, aFlavour, aDragSession) { var statusTextFld = document.getElementById("statusbar-display"); statusTextFld.label = gNavigatorBundle.getString("droponbookmarksbutton"); aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK; }, onDragExit: function (aEvent, aDragSession) { var statusTextFld = document.getElementById("statusbar-display"); statusTextFld.label = ""; }, getSupportedFlavours: function () { var flavourSet = new FlavourSet(); flavourSet.appendFlavour("application/x-moz-file", "nsIFile"); flavourSet.appendFlavour("text/x-moz-url"); flavourSet.appendFlavour("text/unicode"); return flavourSet; } } var goButtonObserver = { onDragOver: function(aEvent, aFlavour, aDragSession) { var statusTextFld = document.getElementById("statusbar-display"); statusTextFld.label = gNavigatorBundle.getString("dropongobutton"); aEvent.target.setAttribute("dragover", "true"); return true; }, onDragExit: function (aEvent, aDragSession) { var statusTextFld = document.getElementById("statusbar-display"); statusTextFld.label = ""; aEvent.target.removeAttribute("dragover"); }, onDrop: function (aEvent, aXferData, aDragSession) { var xferData = aXferData.data.split("\n"); var uri = xferData[0] ? xferData[0] : xferData[1]; if (uri) { getBrowser().dragDropSecurityCheck(aEvent, aDragSession, uri); loadURI(uri, null, null); } }, getSupportedFlavours: function () { var flavourSet = new FlavourSet(); flavourSet.appendFlavour("application/x-moz-file", "nsIFile"); flavourSet.appendFlavour("text/x-moz-url"); flavourSet.appendFlavour("text/unicode"); return flavourSet; } } var DownloadsButtonDNDObserver = { ///////////////////////////////////////////////////////////////////////////// // nsDragAndDrop onDragOver: function (aEvent, aFlavour, aDragSession) { var statusTextFld = document.getElementById("statusbar-display"); statusTextFld.label = gNavigatorBundle.getString("dropondownloadsbutton"); aDragSession.canDrop = (aFlavour.contentType == "text/x-moz-url" || aFlavour.contentType == "text/unicode"); }, onDragExit: function (aEvent, aDragSession) { var statusTextFld = document.getElementById("statusbar-display"); statusTextFld.label = ""; }, onDrop: function (aEvent, aXferData, aDragSession) { var split = aXferData.data.split("\n"); var url = split[0]; if (url != aXferData.data) { //do nothing, not a valid URL getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url); var name = split[1]; saveURL(url, name, null, true, true); } }, getSupportedFlavours: function () { var flavourSet = new FlavourSet(); flavourSet.appendFlavour("text/x-moz-url"); flavourSet.appendFlavour("text/unicode"); return flavourSet; } } function focusSearchBar() { dump ("focusSearchBar()"); var searchBar = document.getElementsByTagName("searchbar"); if (searchBar.length > 0) { searchBar[0].select(); searchBar[0].focus(); } } // MERC - JCH: Wrapper for OpenSearch, called from nsHTMLPluginDocument.cpp function WrapperOpenSearch(searchStr) { OpenSearch("internet", searchStr); } // MERC - JCH: Slightly modified version of onTextEntered() from search.xml function OpenSearch(tabName, searchStr, newTabFlag) { dump("OpenSearch called. tabName : " + tabName + ", searchStr : " + searchStr + ", newTabFlag : " + newTabFlag); // dump("\nINPUT SEARCH STRING: " +searchStr+ "\n"); var searchURL = null; var PREF = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService) .getBranch(null); var ISEARCHSVC = Components.classes["@mozilla.org/rdf/datasource;1?name=internetsearch"] .getService(Components.interfaces.nsIInternetSearchService); // GET THE SEARCH ENGINE AS SET IN SIDEBAR SEARCH OR NAV BAR SEARCH DROPDOWN MENUS var broadcaster = document.getElementById('searchEngineBroadcaster'); var currentEngine = broadcaster.getAttribute("searchengine"); // JMC : If it's netscape, use the context menu link, not the default from the .src file // dump("JMC: currentEngine is " + currentEngine + "\n"); if (currentEngine.indexOf('NetscapeSearch') > -1) { searchURL = gPrefService.getCharPref('browser.contextSearch.URL') +(searchStr? encodeURIComponent(searchStr):""); // searchURL = gPrefService.getCharPref('browser.contextSearch.URL') + (searchStr? searchStr:""); } else { // NOW GET THE WHOLE SEARCH URI searchURL = ISEARCHSVC.GetInternetSearchURL( currentEngine, searchStr? encodeURIComponent(searchStr):"", 0, 0, {value:0}); } // dump("\nOUTPUT SEARCH STRING: " +searchURL+ "\n"); // if the search box is empty, let's go to netscape search if (!searchURL) { // GO TO FALLBACK POSITION, WHICH IS NETSCAPE SEARCH PAGE // This gets chrome URL from browser\base\content\browser-sets.inc var navigatorRegionBundle = document.getElementById("bundle_browser_region"); searchURL = navigatorRegionBundle.getString("fallbackDefaultSearchURL"); } SearchLoadURL(searchURL, null); } // MERC - JCH: Made changes to regular expression which selects a valid URI. // There is no internetsearch.rdf file so I commented out a bunch of // code that tries to access it. The URIs associated with 'fallbackDefaultSearchURL' // and 'browser.search.defaulturl' were changed to ones that work. See region.properties file. function OpenSearchBAK(tabName, searchStr, newTabFlag) { //This function needs to be split up someday. //XXXnoririty I don't want any prefs switching open by tabs to window //XXXpch: this routine needs to be cleaned up. // GET FALLBACK SEARCH ENGINE: jch set it to google. var defaultSearchURL = null; // This gets chrome URL from browser\base\content\browser-sets.inc var navigatorRegionBundle = document.getElementById("bundle_browser_region"); var fallbackDefaultSearchURL = navigatorRegionBundle.getString("fallbackDefaultSearchURL"); dump("#$#$#$ OpenSearch(): Search String : " +searchStr+ "\n"); //Check to see if search string contains "://" or "ftp." or white space. //If it does treat as url and match for pattern //var urlmatch= /(:\/\/|^ftp\.)[^ \S]+$/ var urlmatch = /^(http|https|ftp|chrome|file):\/\/.+|^www\..+/; var forceAsURL = urlmatch.test(searchStr); dump("#$#$#$ OpenSearch() FORCE TO A URL : " +forceAsURL+ "\n"); // TRY TO GET PREFERRED SEARCH ENGINE try { defaultSearchURL = gPrefService.getComplexValue("browser.search.defaulturl", Components.interfaces.nsIPrefLocalizedString).data; } catch (ex) {} // Fallback to a default url (one that we can get sidebar search results for) if (!defaultSearchURL) defaultSearchURL = fallbackDefaultSearchURL; if (!defaultSearchURL) return; dump("#$#$#$ OpenSearch(): Default String : " +defaultSearchURL+ "\n"); if (!searchStr) { return; // BrowserSearchInternet(); } else { //Check to see if location bar field is a url //If it is a url go to URL. A Url is "://" or "." as commented above //Otherwise search on entry if (forceAsURL) { if (!newTabFlag) { loadURI(searchStr, null, null); } else { var newTab = getBrowser().addTab(searchStr); if (!pref.getBoolPref("browser.tabs.loadInBackground")) getBrowser().selectedTab = newTab; } return; // BrowserLoadURL(null, null) } else { if (searchStr) { var escapedSearchStr = encodeURIComponent(searchStr); defaultSearchURL += escapedSearchStr; /* var searchDS = Components.classes["@mozilla.org/rdf/datasource;1?name=internetsearch"] .getService(Components.interfaces.nsIInternetSearchService); searchDS.RememberLastSearchText(escapedSearchStr); try { var searchEngineURI = gPrefService.getCharPref("browser.search.defaultengine"); if (searchEngineURI) { var searchURL = getSearchUrl("actionButton"); if (searchURL) { defaultSearchURL = searchURL + escapedSearchStr; } else { searchURL = searchDS.GetInternetSearchURL(searchEngineURI, escapedSearchStr, 0, 0, {value:0}); if (searchURL) defaultSearchURL = searchURL; } } } catch (ex) { } */ dump("#$#$#$ Complete string : " +defaultSearchURL+ "\n"); if (!newTabFlag) { loadURI(defaultSearchURL, null, null); } else { var newTab = getBrowser().addTab(defaultSearchURL); if (!pref.getBoolPref("browser.tabs.loadInBackground")) getBrowser().selectedTab = newTab; } } } } } function FillHistoryMenu(aParent, aMenu) { // Remove old entries if any deleteHistoryItems(aParent); var sessionHistory = getWebNavigation().sessionHistory; var count = sessionHistory.count; var index = sessionHistory.index; var end; var j; var entry; switch (aMenu) { case "back": end = (index > MAX_HISTORY_MENU_ITEMS) ? index - MAX_HISTORY_MENU_ITEMS : 0; if ((index - 1) < end) return false; for (j = index - 1; j >= end; j--) { entry = sessionHistory.getEntryAtIndex(j, false); if (entry) var menuItem = createMenuItem(aParent, j, entry.title); if (menuItem) menuItem.setAttribute("tooltiptext", "Go back to "+menuItem.label); } break; case "forward": end = ((count-index) > MAX_HISTORY_MENU_ITEMS) ? index + MAX_HISTORY_MENU_ITEMS : count; if ((index + 1) >= end) return false; for (j = index + 1; j < end; j++) { entry = sessionHistory.getEntryAtIndex(j, false); if (entry) var menuItem = createMenuItem(aParent, j, entry.title); if (menuItem) menuItem.setAttribute("tooltiptext", "Go forward to "+menuItem.label); } break; case "go": aParent.lastChild.hidden = (count == 0); end = count > MAX_HISTORY_MENU_ITEMS ? count - MAX_HISTORY_MENU_ITEMS : 0; for (j = count - 1; j >= end; j--) { entry = sessionHistory.getEntryAtIndex(j, false); if (entry) createRadioMenuItem(aParent, j, entry.title, j==index); } break; } return true; } function addToUrlbarHistory() { var urlToAdd = gURLBar.value; if (!urlToAdd) return; if (urlToAdd.search(/[\x00-\x1F]/) != -1) // don't store bad URLs return; if (!gGlobalHistory) gGlobalHistory = Components.classes["@mozilla.org/browser/global-history;2"] .getService(Components.interfaces.nsIBrowserHistory); if (!gURIFixup) gURIFixup = Components.classes["@mozilla.org/docshell/urifixup;1"] .getService(Components.interfaces.nsIURIFixup); try { if (urlToAdd.indexOf(" ") == -1) { var fixedUpURI = gURIFixup.createFixupURI(urlToAdd, 0); if(fixedUpURI.spec=="about:blank") return; // MERC (DP): history debug gGlobalHistory.markPageAsTyped(fixedUpURI); } } catch(ex) { dump ("Caught Exception: " + ex + "\n"); } } function createMenuItem( aParent, aIndex, aLabel) { var menuitem = document.createElement( "menuitem" ); menuitem.setAttribute( "label", aLabel ); menuitem.setAttribute( "index", aIndex ); aParent.appendChild( menuitem ); return menuitem; } function createRadioMenuItem( aParent, aIndex, aLabel, aChecked) { var menuitem = document.createElement( "menuitem" ); menuitem.setAttribute( "type", "radio" ); menuitem.setAttribute( "label", aLabel ); menuitem.setAttribute( "index", aIndex ); if (aChecked==true) menuitem.setAttribute( "checked", "true" ); aParent.appendChild( menuitem ); } function deleteHistoryItems(aParent) { var children = aParent.childNodes; for (var i = 0; i < children.length; i++) { var index = children[i].getAttribute("index"); if (index) aParent.removeChild(children[i]); } } function toJavaScriptConsole() { toOpenWindowByType("global:console", "chrome://global/content/console.xul"); } function toOpenWindowByType(inType, uri, features) { var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(); var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator); var topWindow = windowManagerInterface.getMostRecentWindow(inType); if (topWindow) topWindow.focus(); else if (features) window.open(uri, "_blank", features); else window.open(uri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar"); } // MERC (DP): when the user presses CTRL-N we look at the pref // browser.tabs.newtabinsteadofwindow to determine whether to open // a new window or a new tab. effectively if the pref is on, // pressing CTRL-N is equiv to pressing CTRL-T function OpenBrowserWindowWithPref() { if (gPrefService.getBoolPref("browser.tabs.newtabinsteadofwindow")) { BrowserHome(true); } else { OpenBrowserWindow(); } } function tridentStartNav(urlStr) { // dump ("\nStarting trident navigation to url " + urlStr); getBrowser().userTypedClear = true; // JMC - Ought to call observer service notify for startDocumentLoad // But need to haul out the trident-hacked code there first } function tridentStartSubFrameNav(urlStr) { // dump ("\nStarting trident subframe navigation to url " + urlStr); } function tridentEndNav(urlStr) { // dump ("\nStopping trident navigation to : " + urlStr); // JMC - Ought to call observer service notify for endDocumentLoad // But need to haul out the trident-hacked code there first } function tridentEndSubFrameNav(urlStr) { // dump ("\nStopping trident subframe navigation to : " + urlStr); // JMC - Ought to call observer service notify for endDocumentLoad // But need to haul out the trident-hacked code there first } function OpenBrowserWindow() { var charsetArg = new String(); var handler = Components.classes['@mozilla.org/commandlinehandler/general-startup;1?type=browser']; handler = handler.getService(); handler = handler.QueryInterface(Components.interfaces.nsICmdLineHandler); var startpage = handler.defaultArgs; var url = handler.chromeUrlForTask; var wintype = document.firstChild.getAttribute('windowtype'); // 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 setting from the current document and use it to // initialize the new browser window... if (window && (wintype == "navigator:browser") && window._content && window._content.document) { var DocCharset = window._content.document.characterSet; charsetArg = "charset="+DocCharset; //we should "inherit" the charset menu setting in a new window window.openDialog(url, "_blank", "chrome,all,dialog=no", startpage, charsetArg); } else // forget about the charset information. { window.openDialog(url, "_blank", "chrome,all,dialog=no", startpage); } } function openAboutDialog() { window.openDialog("chrome://browser/content/aboutDialog.xul", "About", "modal,centerscreen,chrome,resizable=no"); } function BrowserCustomizeToolbar() { // Disable the toolbar context menu items var menubar = document.getElementById("main-menubar"); for (var i = 0; i < menubar.childNodes.length; ++i) menubar.childNodes[i].setAttribute("disabled", true); var cmd = document.getElementById("cmd_CustomizeToolbars"); cmd.setAttribute("disabled", "true"); window.openDialog("chrome://global/content/customizeToolbar.xul", "CustomizeToolbar", "chrome,dependent,dialog", document.getElementById("navigator-toolbox")); } function BrowserToolboxCustomizeDone(aToolboxChanged) { // Update global UI elements that may have been added or removed if (aToolboxChanged) { gURLBar = document.getElementById("urlbar"); gProxyButton = document.getElementById("page-proxy-button"); gProxyFavIcon = document.getElementById("page-proxy-favicon"); gProxyDeck = document.getElementById("page-proxy-deck"); //gHomeButton.updateTooltip(); DO NOT USE..this is set in the browser.xul file //<added by SLiu , fixing customize personal bookmarks toolbar var ptf = document.getElementById("personal-bookmarks"); if (ptf) populateBookmarks(); //<added by MSD , fixing webmail button webmail.fixMenus(); window.XULBrowserWindow.init(); } // Update the urlbar var url = getWebNavigation().currentURI.spec; if (gURLBar) { gURLBar.value = url; var uri = Components.classes["@mozilla.org/network/standard-url;1"] .createInstance(Components.interfaces.nsIURI); uri.spec = url; SetPageProxyState("valid", uri); } // Re-enable parts of the UI we disabled during the dialog var menubar = document.getElementById("main-menubar"); for (var i = 0; i < menubar.childNodes.length; ++i) menubar.childNodes[i].setAttribute("disabled", false); var cmd = document.getElementById("cmd_CustomizeToolbars"); cmd.removeAttribute("disabled"); // fix up the personal toolbar folder var bt = document.getElementById("bookmarks-ptf"); if (bt) { var btf = BMSVC.getBookmarksToolbarFolder().Value; var btchevron = document.getElementById("bookmarks-chevron"); bt.ref = btf; btchevron.ref = btf; // no uniqueness is guaranteed, so we have to remove first try { bt.database.RemoveObserver(BookmarksToolbarRDFObserver); bt.controllers.removeController(BookmarksMenuController); } catch (ex) { // ignore } bt.database.AddObserver(BookmarksToolbarRDFObserver); bt.controllers.appendController(BookmarksMenuController); bt.builder.rebuild(); btchevron.builder.rebuild(); // fake a resize; this function takes care of flowing bookmarks // from the bar to the overflow item BookmarksToolbar.resizeFunc(null); } // Initialize SPUI // JMC - NEEDS to refresh spui components here, but this is not quite right // if (spui) spui.RefreshComponentList(); if (spui) spui.RedrawComponents(); reshuffleToolbars(true); // XXX Shouldn't have to do this, but I do // JMC - Don't like this... dump("Focusing the window\n"); window.focus(); } function reshuffleToolbars(aForce) { var toolbox = document.getElementById("navigator-toolbox"); var toolbars = toolbox.getElementsByTagName('toolbar'); for (var i = 0; i < toolbars.length; i++) { var toolbar = toolbars.item(i); try { toolbar.allocateItems(aForce); } catch (ex) { // not a overflow toolbar } } toolbars = toolbox.getElementsByTagName('multibartray'); for (var i = 0; i < toolbars.length; i++) { var toolbar = toolbars.item(i); try { toolbar.allocateItems(aForce); } catch (ex) { // not a overflow toolbar } } } var FullScreen = { toggle: function() { // show/hide all menubars, toolbars, and statusbars (except the full screen toolbar) this.showXULChrome("toolbar", window.fullScreen); this.showXULChrome("multibar", window.fullScreen); this.showXULChrome("statusbar", window.fullScreen); var throbberBox = document.getElementById('throbber-box'); if (throbberBox) { throbberBox.setAttribute('hidden', !window.fullScreen); //JMC : hide throbber in fullscreen } var popupBlockerButton = document.getElementById("popupblocker-button"); if (popupBlockerButton) popupBlockerButton.setAttribute('hideLabel', !window.fullScreen); }, showXULChrome: function(aTag, aShow) { var XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var els = document.getElementsByTagNameNS(XULNS, aTag); var i; for (i = 0; i < els.length; ++i) { // XXX don't interfere with previously collapsed toolbars if (els[i].getAttribute("fullscreentoolbar") == "true") { if (!aShow) { var toolbarMode = els[i].getAttribute("mode"); var iconSize = els[i].getAttribute("iconsize"); var contextMenu = els[i].getAttribute("context"); if (toolbarMode != "text") { els[i].setAttribute("saved-mode", toolbarMode); els[i].setAttribute("saved-iconsize", iconSize); els[i].setAttribute("mode", "icons"); els[i].setAttribute("iconsize", "small"); } // XXX See bug 202978: we disable the context menu // to prevent customization while in fullscreen, which // causes menu breakage. els[i].setAttribute("saved-context", contextMenu); els[i].removeAttribute("context"); } else { if (els[i].hasAttribute("saved-mode")) { var savedMode = els[i].getAttribute("saved-mode"); els[i].setAttribute("mode", savedMode); els[i].removeAttribute("saved-mode"); } if (els[i].hasAttribute("saved-iconsize")) { var savedIconSize = els[i].getAttribute("saved-iconsize"); els[i].setAttribute("iconsize", savedIconSize); els[i].removeAttribute("saved-iconsize"); } // XXX see above. if (els[i].hasAttribute("saved-context")) { var savedContext = els[i].getAttribute("saved-context"); els[i].setAttribute("context", savedContext); els[i].removeAttribute("saved-context"); } } } else { // use moz-collapsed so it doesn't persist hidden/collapsed, // so that new windows don't have missing toolbars if (aShow) els[i].removeAttribute("moz-collapsed"); else els[i].setAttribute("moz-collapsed", "true"); } } var controls = document.getElementsByAttribute("fullscreencontrol", "true"); for (i = 0; i < controls.length; ++i) controls[i].hidden = aShow; } }; function nsBrowserStatusHandler() { this.init(); } nsBrowserStatusHandler.prototype = { // Stored Status, Link and Loading values status : "", defaultStatus : "", jsStatus : "", jsDefaultStatus : "", overLink : "", startTime : 0, statusText: "", lastURI: null, statusTimeoutInEffect : false, QueryInterface : function(aIID) { if (aIID.equals(Components.interfaces.nsIWebProgressListener) || aIID.equals(Components.interfaces.nsISupportsWeakReference) || aIID.equals(Components.interfaces.nsIXULBrowserWindow) || aIID.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_NOINTERFACE; }, init : function() { this.throbberElement = document.getElementById("throbberBroadcaster"); this.statusMeter = document.getElementById("statusbar-icon"); this.stopCommand = document.getElementById("Browser:Stop"); this.stopReloadBtn = document.getElementById("stop-reload-button"); this.statusTextField = document.getElementById("statusbar-display"); this.securityButton = document.getElementById("security-button"); this.urlBar = document.getElementById("urlbar"); // Initialize the security button's state and tooltip text const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener; this.onSecurityChange(null, null, nsIWebProgressListener.STATE_IS_INSECURE); }, destroy : function() { // XXXjag to avoid leaks :-/, see bug 60729 this.throbberElement = null; this.statusMeter = null; this.stopCommand = null; this.stopReloadBtn = null; this.statusTextField = null; this.securityButton = null; this.urlBar = null; this.statusText = null; this.lastURI = null; }, setJSStatus : function(status) { this.jsStatus = status; this.updateStatusField(); }, setJSDefaultStatus : function(status) { this.jsDefaultStatus = status; this.updateStatusField(); }, setDefaultStatus : function(status) { this.defaultStatus = status; this.updateStatusField(); }, setOverLink : function(link, b) { this.overLink = link; this.updateStatusField(); }, updateStatusField : function() { var text = this.overLink || this.status || this.jsStatus || this.jsDefaultStatus || this.defaultStatus; // check the current value so we don't trigger an attribute change // and cause needless (slow!) UI updates if (this.statusText != text) { this.statusTextField.label = text; this.statusText = text; } }, onLinkIconAvailable : function(aBrowser, aHref) { // dump( ")) WMWMWMWMWMW===> onLinkIconAvailable(aBowser, \""+aHref+"\")\n" ); if (gProxyFavIcon && gBrowser.mCurrentBrowser == aBrowser && gBrowser.userTypedValue === null) { PageProxySetIcon(aHref); } aBrowser.mFavIconURL = aHref; }, onProgressChange : function (aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) { if (aMaxTotalProgress > 0) { // This is highly optimized. Don't touch this code unless // you are intimately familiar with the cost of setting // attrs on XUL elements. -- hyatt var percentage = (aCurTotalProgress * 100) / aMaxTotalProgress; this.statusMeter.value = percentage; } }, onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus) { var docshell = getWebNavigation(); if (aRequest) { blacklistUtils.debug('\nonStateChange('+aRequest.name+')\n'); if (blacklistUtils.IsSiteInPhishList(aRequest.originalURI)) { // ShowPhishingSiteWarning(); displayNotificationBar("phishing",[aRequest.originalURI]); //aRequest.suspend(); //aRequest.cancel(Components.results.NS_BINDING_ABORTED); } else if (blacklistUtils.IsSiteInSpywareList(aRequest.originalURI)) { //ShowSpywareSiteWarning(); displayNotificationBar("spyware",[aRequest.originalURI]); } } /* if (aRequest) { for (var p in aRequest) { dump(' aRequest.'+p+': '+aRequest[p]+'\n'); } } */ const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener; const nsIChannel = Components.interfaces.nsIChannel; if (aStateFlags & nsIWebProgressListener.STATE_START) { // This (thanks to the filter) is a network start or the first // stray request (the first request outside of the document load), // initialize the throbber and his friends. // always reset the favicon if (gBrowser.mTabbedMode) { var browserIndex = gBrowser.getBrowserIndexForDocument(aWebProgress.DOMWindow); if (browserIndex != -1) gBrowser.getBrowserAtIndex(browserIndex).mFavIconURL = null; } else gBrowser.mCurrentBrowser.mFavIconURL = null; // Call start document load listeners (only if this is a network load) if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK && aRequest && aWebProgress.DOMWindow == content) this.startDocumentLoad(aRequest); if (this.throbberElement) { // Turn the throbber on. this.throbberElement.setAttribute("busy", "true"); } // Turn the status meter on. this.statusMeter.value = 0; // be sure to clear the progress bar if (gProgressCollapseTimer) { window.clearTimeout(gProgressCollapseTimer); gProgressCollapseTimer = null; } else this.statusMeter.parentNode.collapsed = false; // XXX: This needs to be based on window activity... this.stopCommand.removeAttribute("disabled"); if (this.stopReloadBtn) { // JCH: Need to set label according to state this.stopReloadBtn.setAttribute("label","Stop"); this.stopReloadBtn.setAttribute("state","stop"); this.stopReloadBtn.removeAttribute("oncommand"); this.stopReloadBtn.setAttribute("command","Browser:Stop"); } } else if (aStateFlags & nsIWebProgressListener.STATE_STOP) { if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) { if (aRequest) { if (aWebProgress.DOMWindow == content) this.endDocumentLoad(aRequest, aStatus); } } // This (thanks to the filter) is a network stop or the last // request stop outside of loading the document, stop throbbers // and progress bars and such if (aRequest) { var msg = ""; // Get the channel if the request is a channel var channel; try { channel = aRequest.QueryInterface(nsIChannel); } catch(e) { }; if (channel) { var location = channel.URI; // For keyword URIs clear the user typed value since they will be changed into real URIs if (location.scheme == "keyword" && aWebProgress.DOMWindow == content) getBrowser().userTypedValue = null; if (location.spec != "about:blank") { const kErrorBindingAborted = 0x804B0002; const kErrorNetTimeout = 0x804B000E; switch (aStatus) { case kErrorBindingAborted: msg = gNavigatorBundle.getString("nv_stopped"); break; case kErrorNetTimeout: msg = gNavigatorBundle.getString("nv_timeout"); break; } } } // If msg is false then we did not have an error (channel may have // been null, in the case of a stray image load). if (!msg) { msg = gNavigatorBundle.getString("nv_done"); } this.status = ""; this.setDefaultStatus(msg); } // Turn the progress meter and throbber off. gProgressCollapseTimer = window.setTimeout( function() { gProgressMeterPanel.collapsed = true; gProgressCollapseTimer = null; }, 100); if (this.throbberElement) this.throbberElement.removeAttribute("busy"); this.stopCommand.setAttribute("disabled", "true"); if (this.stopReloadBtn) { // JCH: Need to set label according to state this.stopReloadBtn.setAttribute("label","Reload"); this.stopReloadBtn.setAttribute("state","reload"); this.stopReloadBtn.removeAttribute("command"); //this.stopReloadBtn.setAttribute("oncommand","BrowserStopReload(event);"); this.stopReloadBtn.setAttribute("oncommand","BrowserReload(event);"); } } }, onLocationChange : function(aWebProgress, aRequest, aLocation) { var location = aLocation.spec; if (location == "about:blank") location = ""; // dump("browser.js: onLocationChange: location = "+location+"\n"); if (blacklistUtils.IsSiteInPhishList(aLocation)) { // Get partners who think it's bad displayNotificationBar("phishing", [aLocation]); } else if (blacklistUtils.IsSiteInSpywareList(aLocation)) { // ShowSpywareSiteWarning(); displayNotificationBar("spyware", [aLocation]); } // This code here does not compare uris exactly when determining // whether or not the message should be hidden since the message // may be prematurely hidden when an install is invoked by a click // on a link that looks like this: // // <a href="#" onclick="return install();">Install Foo</a> // // - which fires a onLocationChange message to uri + '#'... var selectedBrowser = getBrowser().selectedBrowser; if (selectedBrowser.lastURI) { var oldSpec = selectedBrowser.lastURI.spec; var oldIndexOfHash = oldSpec.indexOf("#"); if (oldIndexOfHash != -1) oldSpec = oldSpec.substr(0, oldIndexOfHash); var newSpec = aLocation.spec; var newIndexOfHash = newSpec.indexOf("#"); if (newIndexOfHash != -1) newSpec = newSpec.substr(0, newSpec.indexOf("#")); if (newSpec != oldSpec) { var tabbrowser = getBrowser(); tabbrowser.hideMessage(tabbrowser.selectedBrowser, "both"); gCurrentNotificationBar = null; } else { // MERC (DP): added this ELSE branch to fix BLT # 129362 - popup message bar doesn't // disappear when you turn off blocking and reload page. var site = sitecontrols.SCSVC.getResourceForURI(gBrowser.currentURI.spec); var blockState = sitecontrols.SCSVC.readSiteControlResource(site, 'allowPopups'); if (blockState == 'true' && gCurrentNotificationBar == 'popup') { var tabbrowser = getBrowser(); tabbrowser.hideMessage(tabbrowser.selectedBrowser, "top"); gCurrentNotificationBar = null; } } } selectedBrowser.lastURI = aLocation; this.setOverLink("", null); // MERC - JCH : update popup block button SetPopupBlockToggle(); // We should probably not do this if the value has changed since the user // searched // Update urlbar only if a new page was loaded on the primary content area // Do not update urlbar if there was a subframe navigation var browser = getBrowser().selectedBrowser; var findField = document.getElementById("find-field"); // MERC: set up for Trident var hpDoc = getTridentDocument(); if (aWebProgress.DOMWindow == content) { // The document loaded correctly, clear the value if we should if (browser.userTypedClear) { // dump("Going to clear user's typed values\n"); browser.userTypedValue = null; } if (findField) setTimeout(function() { findField.value = browser.findString; }, 0, findField, browser); //XXXBlake don't we have to reinit this.urlBar, etc. // when the toolbar changes? if (hpDoc) { //clean it here as we are not using startDocumentLoad // JMC - trying to fix clobbering of urlbar // If the typedValue is the same as where we are, clear it // dump ("/nJMC Trying to clear userTypedValue when appropriate"); // dump ("Location is : " + location + ", userTypedValue : " + browser.userTypedValue); if (browser.userTypedClear || browser.userTypedValue == location) { // dump("Going to clear user's typed values because we're hpDoc?\n"); browser.userTypedValue = null; } if (findField) closeFindBar(); } if (gURLBar) { var userTypedValue = browser.userTypedValue; if (!userTypedValue) { // If the url has "wyciwyg://" as the protocol, strip it off. // Nobody wants to see it on the urlbar for dynamically generated // pages. if (!gURIFixup) { gURIFixup = Components.classes["@mozilla.org/docshell/urifixup;1"] .getService(Components.interfaces.nsIURIFixup); } if (location && gURIFixup) { try { var locationURI = gURIFixup.createExposableURI(aLocation); location = locationURI.spec; } catch (exception) {} } if (getBrowser().forceSyncURLBarUpdate) { gURLBar.value = ""; // hack for bug 249322 gURLBar.value = location; SetPageProxyState("valid", aLocation); } else { setTimeout(function(loc, aloc) { gURLBar.value = ""; // hack for bug 249322 gURLBar.value = loc; SetPageProxyState("valid", aloc); }, 0, location, aLocation); } // Setting the urlBar value in some cases causes userTypedValue to // become set because of oninput, so reset it to its old value. browser.userTypedValue = userTypedValue; } else { // JMC - introduced bug with urlBarValue dump ("userTYpedValue is non-null, setting invalid proxy state\n"); gURLBar.value = userTypedValue; SetPageProxyState("invalid", null); } } } //MERC - Durga : display default passcard on toolbar in text mode // TODO (DP): this should be in the onClick handler of tabbrowser as well SetPasscard(); UpdateBackForwardButtons(); if (findField && gFindMode != FIND_NORMAL) { // Close the Find toolbar if we're in old-style TAF mode closeFindBar(); gBackProtectBuffer = 0; } //fix bug 253793 - turn off highlight when page changes if (document.getElementById("highlight").checked) document.getElementById("highlight").removeAttribute("checked"); // clear missing plugins gMissingPluginInstaller.clearMissingPlugins(getBrowser().selectedTab); setTimeout(function () { updatePageLivemarks(); }, 0); }, onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) { this.status = aMessage; this.updateStatusField(); }, onSecurityChange : function(aWebProgress, aRequest, aState) { const wpl = Components.interfaces.nsIWebProgressListener; this.securityButton.removeAttribute("label"); switch (aState) { case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH: this.securityButton.setAttribute("level", "high"); if (this.urlBar) this.urlBar.setAttribute("level", "high"); try { this.securityButton.setAttribute("label", gBrowser.contentWindow.location.host); } catch(exception) {} break; case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW: this.securityButton.setAttribute("level", "low"); if (this.urlBar) this.urlBar.setAttribute("level", "low"); try { this.securityButton.setAttribute("label", gBrowser.contentWindow.location.host); } catch(exception) {} break; case wpl.STATE_IS_BROKEN: this.securityButton.setAttribute("level", "broken"); if (this.urlBar) this.urlBar.setAttribute("level", "broken"); break; case wpl.STATE_IS_INSECURE: default: this.securityButton.removeAttribute("level"); if (this.urlBar) this.urlBar.removeAttribute("level"); break; } var securityUI = gBrowser.securityUI; if (securityUI) { this.securityButton.setAttribute("tooltiptext", securityUI.tooltipText); if (this.urlBar) this.urlBar.setAttribute("infotext", securityUI.tooltipText); } else { this.securityButton.setAttribute("tooltiptext", securityUI.tooltipText); if (this.urlBar) this.urlBar.removeAttribute("infotext"); } }, startDocumentLoad : function(aRequest) { dump("StartDocumentLoad\n"); dump("removing engine attribute\n"); //MERC (rpaul) remove the engine for the tab //gBrowser.mCurrentTab.removeAttribute("engine"); // It's okay to clear what the user typed when we start // loading a document. If the user types, this flag gets // set to false, if the document load ends without an // onLocationChange, this flag also gets set to false // (so we keep it while switching tabs after failed load getBrowser().userTypedClear = true; // clear out livemark data gBrowser.mCurrentBrowser.livemarkLinks = null; // hide all message bars on reload gBrowser.hideMessage(gBrowser.mCurrentBrowser, "both"); gCurrentNotificationBar = null; const nsIChannel = Components.interfaces.nsIChannel; var urlStr = aRequest.QueryInterface(nsIChannel).URI.spec; var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); try { observerService.notifyObservers(_content, "StartDocumentLoad", urlStr); } catch (e) { } }, endDocumentLoad : function(aRequest, aStatus) { dump ("endDocumentLoad\n"); // The document is done loading, it's okay to clear // the value again. getBrowser().userTypedClear = false; const nsIChannel = Components.interfaces.nsIChannel; var urlStr = aRequest.QueryInterface(nsIChannel).originalURI.spec; var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); var notification = Components.isSuccessCode(aStatus) ? "EndDocumentLoad" : "FailDocumentLoad"; try { observerService.notifyObservers(_content, notification, urlStr); } catch (e) { } setTimeout(function() { if (document.getElementById("highlight").checked) toggleHighlight(true); }, 0); UpdateStatusbarPartnerIcons(); } } function nsBrowserAccess() { } nsBrowserAccess.prototype = { QueryInterface : function(aIID) { if (aIID.equals(nsCI.nsIBrowserDOMWindow) || aIID.equals(nsCI.nsISupports)) return this; throw Components.results.NS_NOINTERFACE; }, openURI : function(aURI, aOpener, aWhere, aContext) { var newWindow = null; var referrer = null; // Bug #298255 var isExternal = (aContext == nsCI.nsIBrowserDOMWindow.OPEN_EXTERNAL); if (isExternal && aURI && aURI.schemeIs("chrome")) return null; var loadflags = isExternal ? nsCI.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL : nsCI.nsIWebNavigation.LOAD_FLAGS_NONE; if (aWhere == nsCI.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW) { switch (aContext) { case nsCI.nsIBrowserDOMWindow.OPEN_EXTERNAL : aWhere = gPrefService.getIntPref("browser.link.open_external"); break; default : // OPEN_NEW or an illegal value aWhere = gPrefService.getIntPref("browser.link.open_newwindow"); } } var url = aURI ? aURI.spec : "about:blank"; switch(aWhere) { case nsCI.nsIBrowserDOMWindow.OPEN_NEWWINDOW : newWindow = openDialog(getBrowserURL(), "_blank", "all,dialog=no", url); break; case nsCI.nsIBrowserDOMWindow.OPEN_NEWTAB : var newTab = gBrowser.addTab("about:blank"); if (!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground")) gBrowser.selectedTab = newTab; newWindow = gBrowser.getBrowserForTab(newTab).docShell .QueryInterface(nsCI.nsIInterfaceRequestor) .getInterface(nsCI.nsIDOMWindow); try { if (aOpener) { referrer = Components.classes["@mozilla.org/network/standard-url;1"] .createInstance(nsCI.nsIURI); referrer.spec = Components.lookupMethod(aOpener,"location") .call(aOpener); } newWindow.QueryInterface(nsCI.nsIInterfaceRequestor) .getInterface(nsCI.nsIWebNavigation) .loadURI(url, loadflags, referrer, null, null); } catch(e) { } break; default : // OPEN_CURRENTWINDOW or an illegal value try { if (aOpener) { newWindow = Components.lookupMethod(aOpener,"top") .call(aOpener); referrer = Components.classes["@mozilla.org/network/standard-url;1"] .createInstance(nsCI.nsIURI); referrer.spec = Components.lookupMethod(aOpener,"location") .call(aOpener); newWindow.QueryInterface(nsCI.nsIInterfaceRequestor) .getInterface(nsIWebNavigation) .loadURI(url, loadflags, referrer, null, null); } else { newWindow = gBrowser.selectedBrowser.docShell .QueryInterface(nsCI.nsIInterfaceRequestor) .getInterface(nsCI.nsIDOMWindow); getWebNavigation().loadURI(url, loadflags, null, null, null); } } catch(e) { } } return newWindow; } } function onViewToolbarsPopupShowing(aEvent) { var popup = aEvent.target; var i; // Empty the menu for (i = popup.childNodes.length-1; i >= 0; --i) { var deadItem = popup.childNodes[i]; if (deadItem.hasAttribute("toolbarindex")) popup.removeChild(deadItem); } var firstMenuItem = popup.firstChild; var highestOrdinal = 0; var toolbox = document.getElementById("navigator-toolbox"); for (i = 0; i < toolbox.childNodes.length; ++i) { var toolbar = toolbox.childNodes[i]; var toolbarName = toolbar.getAttribute("toolbarname"); var type = toolbar.getAttribute("type"); if (toolbarName && type != "menubar") { var menuItem = document.createElement("menuitem"); menuItem.setAttribute("toolbarindex", i); menuItem.setAttribute("type", "checkbox"); menuItem.setAttribute("label", toolbarName); menuItem.setAttribute("accesskey", toolbar.getAttribute("accesskey")); menuItem.setAttribute("checked", toolbar.getAttribute("collapsed") != "true"); // JMC- Hack to order the items to match the toolbar orders var toolbarordinal = toolbar.getAttribute("ordinal"); menuItem.setAttribute('ordinal',toolbarordinal); if (toolbarordinal > highestOrdinal) highestOrdinal = toolbarordinal; popup.insertBefore(menuItem, firstMenuItem); menuItem.addEventListener("command", onViewToolbarCommand, false); } // JMC: Iterate through all multibartrays, too // toolbar = toolbar.nextSibling; if (toolbar.localName == 'multibar') toolbar = toolbar.firstChild; else if (toolbar.localName == 'multibartray' && (!toolbar.nextSibling)) { toolbar = toolbar.parentNode.nextSibling; } else { toolbar = toolbar.nextSibling; } } firstMenuItem.setAttribute('ordinal',highestOrdinal + 1); firstMenuItem.nextSibling.setAttribute('ordinal',highestOrdinal + 2); if (firstMenuItem.nextSibling.nextSibling) firstMenuItem.nextSibling.nextSibling.setAttribute('ordinal',highestOrdinal + 3); // JMC : HACK HACK HACK } function onViewToolbarCommand(aEvent) { var toolbox = document.getElementById("navigator-toolbox"); var index = aEvent.originalTarget.getAttribute("toolbarindex"); var toolbar = toolbox.childNodes[index]; toolbar.collapsed = aEvent.originalTarget.getAttribute("checked") != "true"; document.persist(toolbar.id, "collapsed"); toolbox.reorderToolbars(); } function displaySecurityInfo() { // MERC - JCH: Temporary fix to show a Properties dialog // when lock icon is clicked and Trident is the engine. This code triggers // a Trident Properties dialog when Trident is the engine. It would be better // to show Gecko pageInfo dialog that has appropriate info. var docshell = getWebNavigation(); if (docshell.browserEngine=="Trident") { var hpDoc = getTridentDocument(); if(hpDoc) { hpDoc.showPageInfo(); } } else { window.openDialog("chrome://browser/content/pageInfo.xul", "_blank", "dialog=no", null, "securityTab"); } } function displayPageReportFirstTime() { window.openDialog("chrome://browser/content/pageReportFirstTime.xul", "_blank", "dependent"); } function displayPageReport() { window.openDialog("chrome://browser/content/pageReport.xul", "_blank", "dialog,modal,resizable"); } function nsBrowserContentListener(toplevelWindow, contentWindow) { // this one is not as easy as you would hope. // need to convert toplevelWindow to an XPConnected object, instead // of a DOM-based object, to be able to QI() it to nsIXULWindow this.init(toplevelWindow, contentWindow); } /* implements nsIURIContentListener */ nsBrowserContentListener.prototype = { init: function(toplevelWindow, contentWindow) { const nsIWebBrowserChrome = Components.interfaces.nsIWebBrowserChrome; this.toplevelWindow = toplevelWindow; this.contentWindow = contentWindow; // hook up the whole parent chain thing var windowDocShell = this.convertWindowToDocShell(toplevelWindow); if (windowDocShell) windowDocshell.parentURIContentListener = this; var registerWindow = false; try { var treeItem = contentWindow.docShell.QueryInterface(Components.interfaces.nsIDocShellTreeItem); var treeOwner = treeItem.treeOwner; var interfaceRequestor = treeOwner.QueryInterface(Components.interfaces.nsIInterfaceRequestor); var webBrowserChrome = interfaceRequestor.getInterface(nsIWebBrowserChrome); if (webBrowserChrome) { var chromeFlags = webBrowserChrome.chromeFlags; var res = chromeFlags & nsIWebBrowserChrome.CHROME_ALL; var res2 = chromeFlags & nsIWebBrowserChrome.CHROME_DEFAULT; if ( res == nsIWebBrowserChrome.CHROME_ALL || res2 == nsIWebBrowserChrome.CHROME_DEFAULT) { registerWindow = true; } } } catch (ex) {} // register ourselves if (registerWindow) { var uriLoader = Components.classes["@mozilla.org/uriloader;1"].getService(Components.interfaces.nsIURILoader); uriLoader.registerContentListener(this); } }, close: function() { this.contentWindow = null; var uriLoader = Components.classes["@mozilla.org/uriloader;1"].getService(Components.interfaces.nsIURILoader); uriLoader.unRegisterContentListener(this); }, QueryInterface: function(iid) { if (iid.equals(Components.interfaces.nsIURIContentListener) || iid.equals(Components.interfaces.nsISupportsWeakReference) || iid.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_NOINTERFACE; }, onStartURIOpen: function(uri) { // ignore and don't abort return false; }, doContent: function(contentType, isContentPreferred, request, contentHandler) { // forward the doContent to our content area webshell var docShell = this.contentWindow.docShell; var contentListener; try { contentListener = docShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIURIContentListener); } catch (ex) { dump(ex); } if (!contentListener) return false; return contentListener.doContent(contentType, isContentPreferred, request, contentHandler); }, isPreferred: function(contentType, desiredContentType) { // seems like we should be getting this from helper apps or something switch(contentType) { case "text/html": case "text/xul": case "text/rdf": case "text/xml": case "text/css": case "image/gif": case "image/jpeg": case "image/png": case "text/plain": case "application/http-index-format": return true; } return false; }, canHandleContent: function(contentType, isContentPreferred, desiredContentType) { var docShell = this.contentWindow.docShell; var contentListener; try { contentListener = docShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIURIContentListener); } catch (ex) { dump(ex); } if (!contentListener) return false; return contentListener.canHandleContent(contentType, isContentPreferred, desiredContentType); }, convertWindowToDocShell: function(win) { // don't know how to do this return null; }, loadCookie: null, parentContentListener: null } // |forceOpen| is a bool that indicates that the sidebar should be forced open. In other words // the toggle won't be allowed to close the sidebar. function toggleSidebar(aCommandID, forceOpen) { var sidebarBox = document.getElementById("sidebar-box"); if (!aCommandID) aCommandID = sidebarBox.getAttribute("sidebarcommand"); var elt = document.getElementById(aCommandID); if (!elt) return; var sidebar = document.getElementById("sidebar"); var sidebarSplitter = document.getElementById("sidebar-splitter"); if (!forceOpen && elt.getAttribute("checked") == "true") { elt.removeAttribute("checked"); sidebarBox.setAttribute("sidebarcommand", ""); sidebarBox.hidden = true; sidebarSplitter.hidden = true; _content.focus(); return; } var elts = document.getElementsByAttribute("group", "sidebar"); for (var i = 0; i < elts.length; ++i) elts[i].removeAttribute("checked"); elt.setAttribute("checked", "true");; if (sidebarBox.hidden) { sidebarBox.hidden = false; sidebarSplitter.hidden = false; } var url = elt.getAttribute("sidebarurl"); var title = elt.getAttribute("sidebartitle"); if (!title) title = elt.getAttribute("label"); sidebar.setAttribute("src", url); sidebarBox.setAttribute("src", url); sidebarBox.setAttribute("sidebarcommand", elt.id); if (aCommandID != "viewWebPanelsSidebar") { // no searchbox there // if the sidebar we want is already constructed, focus the searchbox if ((aCommandID == "viewBookmarksSidebar" && sidebar.contentDocument.getElementById("bookmarksPanel")) || (aCommandID == "viewHistorySidebar" && sidebar.contentDocument.getElementById("history-panel"))) sidebar.contentDocument.getElementById("search-box").focus(); // otherwiese, attach an onload handler else sidebar.addEventListener("load", asyncFocusSearchBox, true); } } function asyncFocusSearchBox(event) { var sidebar = document.getElementById("sidebar"); var searchBox = sidebar.contentDocument.getElementById("search-box"); searchBox.focus(); sidebar.removeEventListener("load", asyncFocusSearchBox, true); } function openPreferences() { // dump ("The parent browser window is : " + window); /*JA ff5->vulp gPrefWindow =*/ openDialog("chrome://browser/content/pref/pref.xul","PrefWindow", "chrome,titlebar,resizable,modal"); } var gHomeButton = { prefDomain: "browser.startup.homepage", observe: function (aSubject, aTopic, aPrefName) { if (aTopic != "nsPref:changed" || aPrefName != this.prefDomain) return; this.updateTooltip(); }, updateTooltip: function () { var homeButton = document.getElementById("home-button"); if (homeButton) { var homePage = this.getHomePage(); homePage = homePage.replace(/\|/g,', '); homeButton.setAttribute("tooltiptext", homePage); } }, getHomePage: function () { var url; try { url = gPrefService.getComplexValue(this.prefDomain, Components.interfaces.nsIPrefLocalizedString).data; } catch (e) { } // use this if we can't find the pref if (!url) { var navigatorRegionBundle = document.getElementById("bundle_browser_region"); url = navigatorRegionBundle.getString("homePageDefault"); } return url; } }; function nsContextMenu( xulMenu ) { this.target = null; this.menu = null; this.onTextInput = false; this.onKeywordField = false; this.onImage = false; this.onLink = false; this.onMailtoLink = false; this.onSaveableLink = false; this.onMetaDataItem = false; this.onMathML = false; this.link = false; this.inFrame = false; this.hasBGImage = false; this.isTextSelected = false; this.inDirList = false; this.shouldDisplay = true; // Initialize new menu. this.initMenu( xulMenu ); } // Prototype for nsContextMenu "class." nsContextMenu.prototype = { // onDestroy is a no-op at this point. onDestroy : function () { }, // Initialize context menu. initMenu : function ( popup ) { // Save menu. this.menu = popup; // Get contextual info. this.setTarget( document.popupNode ); this.isTextSelected = this.isTextSelection(); // Initialize (disable/remove) menu items. this.initItems(); }, initItems : function () { this.initTridentSwitchItem(); // MERC (DP): disable/enable Trident switch this.initOpenItems(); this.initNavigationItems(); this.initViewItems(); this.initMiscItems(); this.initSaveItems(); this.initClipboardItems(); this.initMetadataItems(); this.initPrintItems(); }, // MERC (DP): this function will disable the Trident switch menu item. // for all 'about:*' we disable, except for 'about:blank' - allow engine switch on blank page initTridentSwitchItem : function () { //dump('*** target: ' + this.target.localName + '\n'); var engineMenuItem = document.getElementById('switchToTrident'); //dump('*** switch to trident menu item: ' + engineMenuItem.getAttribute('label') + '\n'); var url = gBrowser.getBrowserForTab(gBrowser.mCurrentTab).currentURI.spec; var regex = /^about:/; if(regex.test(url) && url != 'about:blank') { engineMenuItem.setAttribute('disabled', 'true'); } else { engineMenuItem.removeAttribute('disabled'); } this.showItem( "switchToTrident", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) ); }, initOpenItems : function () { this.showItem( "context-openlink", this.onSaveableLink || ( this.inDirList && this.onLink ) ); this.showItem( "context-openlinkintab", this.onSaveableLink || ( this.inDirList && this.onLink ) ); //this.showItem( "context-sep-open", this.onSaveableLink || ( this.inDirList && this.onLink ) ); this.showItem( "context-sep-open", false ); }, initNavigationItems : function () { // Back determined by canGoBack broadcaster. this.setItemAttrFromNode( "context-back", "disabled", "canGoBack" ); // Forward determined by canGoForward broadcaster. this.setItemAttrFromNode( "context-forward", "disabled", "canGoForward" ); this.showItem( "context-back", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) ); this.showItem( "context-forward", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) ); this.showItem( "context-reload", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) ); this.showItem( "context-stop", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) ); this.showItem( "context-sep-stop", !( this.isTextSelected || this.onTextInput || this.onImage ) ); // XXX: Stop is determined in navigator.js; the canStop broadcaster is broken //this.setItemAttrFromNode( "context-stop", "disabled", "canStop" ); }, initSaveItems : function () { this.showItem( "context-savepage", !( this.inDirList || this.isTextSelected || this.onTextInput || this.onLink || this.onImage )); this.showItem( "context-sendpage", !( this.inDirList || this.isTextSelected || this.onTextInput || this.onLink || this.onImage )); // Save link depends on whether we're in a link. this.showItem( "context-savelink", this.onSaveableLink ); // Save image depends on whether there is one. this.showItem( "context-saveimage", this.onImage ); this.showItem( "context-sendimage", this.onImage ); // Send link depends on whether we're in a link. //this.showItem( "context-sendlink", this.onSaveableLink ); this.showItem( "context-sendlink", false ); }, initViewItems : function () { // View source is always OK, unless in directory listing. this.showItem( "context-viewpartialsource-selection", this.isTextSelected ); this.showItem( "context-viewpartialsource-mathml", this.onMathML && !this.isTextSelected ); this.showItem( "context-viewsource", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) ); this.showItem( "context-viewinfo", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) ); this.showItem( "context-sep-properties", !( this.inDirList || this.isTextSelected || this.onTextInput ) ); // Set As Wallpaper depends on whether an image was clicked on, and only works if we have a shell service. var haveSetWallpaper = false; // Only enable set as wallpaper if we can get the shell service. var shell = getShellService(); if (shell) haveSetWallpaper = true; this.showItem( "context-setWallpaper", haveSetWallpaper && this.onImage ); if( haveSetWallpaper && this.onImage ) { // Disable the Set As Wallpaper menu item if we're still trying to load the image or the load failed const nsIImageLoadingContent = Components.interfaces.nsIImageLoadingContent; var disableSetWallpaper = false; if (("complete" in this.target) && !this.target.complete) disableSetWallpaper = true; else if (this.target instanceof nsIImageLoadingContent) { var request = this.target.QueryInterface(nsIImageLoadingContent) .getRequest(nsIImageLoadingContent.CURRENT_REQUEST); if (!request) disableSetWallpaper = true; } else if (makeURL(this.target.src).scheme == "javascript") disableSetWallpaper = true; this.setItemAttr( "context-setWallpaper", "disabled", disableSetWallpaper); } // View Image depends on whether an image was clicked on. this.showItem( "context-viewimage", this.onImage ); // View background image depends on whether there is one. this.showItem( "context-viewbgimage", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) ); this.showItem( "context-sep-viewbgimage", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) ); this.setItemAttr( "context-viewbgimage", "disabled", this.hasBGImage ? null : "true"); }, initMiscItems : function () { // Use "Bookmark This Link" if on a link. this.showItem( "context-bookmarkpage", !( this.isTextSelected || this.onTextInput || this.onLink || this.onImage ) ); //this.showItem( "context-bookmarklink", this.onLink && !this.onMailtoLink ); this.showItem( "context-bookmarklink", false ); this.showItem( "context-addBookmarkAsTabGrp", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) ); //this.showItem( "context-addBookmarkAsTabGrp", false); this.showItem( "context-searchselect", this.isTextSelected ); //this.showItem( "context-keywordfield", this.onTextInput && this.onKeywordField ); this.showItem( "context-keywordfield", false ); this.showItem( "frame", this.inFrame ); this.showItem( "frame-sep", this.inFrame ); /* MERC: ccampbell: commented this out because it needs to be updated to use Site Controls instead this.showItem( "context-blockimage", this.onImage); // BiDi UI var showBIDI = isBidiEnabled(); this.showItem( "context-sep-bidi", showBIDI); this.showItem( "context-bidi-text-direction-toggle", this.onTextInput && showBIDI); this.showItem( "context-bidi-page-direction-toggle", !this.onTextInput && showBIDI); if (this.onImage) { var blockImage = document.getElementById("context-blockimage"); var uri = Components.classes['@mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURI); uri.spec = this.imageURL; var shortenedUriHost = uri.host.replace(/^www\./i,""); if (shortenedUriHost.length > 15) shortenedUriHost = shortenedUriHost.substr(0,15) + "..."; blockImage.label = gNavigatorBundle.getFormattedString ("blockImages", [shortenedUriHost]); if (this.isImageBlocked()) { blockImage.setAttribute("checked", "true"); } else blockImage.removeAttribute("checked"); } */ }, initClipboardItems : function () { // Copy depends on whether there is selected text. // Enabling this context menu item is now done through the global // command updating system // this.setItemAttr( "context-copy", "disabled", !this.isTextSelected() ); goUpdateGlobalEditMenuItems(); this.showItem( "context-undo", this.onTextInput ); this.showItem( "context-sep-undo", this.onTextInput ); this.showItem( "context-cut", this.onTextInput ); this.showItem( "context-copy", this.isTextSelected || this.onTextInput ); this.showItem( "context-paste", this.onTextInput ); this.showItem( "context-delete", this.onTextInput ); this.showItem( "context-sep-paste", this.onTextInput ); this.showItem( "context-selectall", !( this.onLink || this.onImage ) ); //this.showItem( "context-sep-selectall", this.isTextSelected ); //this.showItem( "context-sep-selectall", true ); this.showItem( "context-sep-selectall", !( this.isTextSelected || this.onLink || this.onImage || this.onTextInput ) ); // XXX dr // ------ // nsDocumentViewer.cpp has code to determine whether we're // on a link or an image. we really ought to be using that... // Copy email link depends on whether we're on an email link. this.showItem( "context-copyemail", this.onMailtoLink ); // Copy link location depends on whether we're on a link. this.showItem( "context-copylink", this.onLink ); //this.showItem( "context-copylink", false ); this.showItem( "context-sep-copylink", this.onLink && this.onImage); //this.showItem( "context-sep-copylink", false ); // Copy image contents depends on whether we're on an image. //this.showItem( "context-copyimage-contents", this.onImage ); this.showItem( "context-copyimage-contents", false ); // Copy image location depends on whether we're on an image. //this.showItem( "context-copyimage", this.onImage ); this.showItem( "context-copyimage", false ); this.showItem( "context-sep-copyimage", this.onImage && this.onLink ); this.showItem( "context-sep-copyimage", false ); }, initMetadataItems : function () { // Show if user clicked on something which has metadata. this.showItem( "context-metadata", this.onMetaDataItem ); }, // MERC (DP): control the print menu items initPrintItems : function () { this.showItem( "context-sep-print", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) ); this.showItem( "context-print", !( this.inDirList || this.onImage || this.isTextSelected || this.onLink || this.onTextInput ) ); }, // Set various context menu attributes based on the state of the world. setTarget : function ( node ) { const xulNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; if ( node.namespaceURI == xulNS ) { this.shouldDisplay = false; return; } // Initialize contextual info. this.onImage = false; this.onMetaDataItem = false; this.onTextInput = false; this.onKeywordField = false; this.imageURL = ""; this.onLink = false; this.onMathML = false; this.inFrame = false; this.hasBGImage = false; this.bgImageURL = ""; // Remember the node that was clicked. this.target = node; // See if the user clicked on an image. if ( this.target.nodeType == Node.ELEMENT_NODE ) { if ( this.target instanceof HTMLImageElement ) { this.onImage = true; this.imageURL = this.target.src; // Look for image map. var mapName = this.target.getAttribute( "usemap" ); if ( mapName ) { // Find map. var map = this.target.ownerDocument.getElementById( mapName.substr(1) ); if ( map ) { // Search child <area>s for a match. var areas = map.childNodes; //XXX Client side image maps are too hard for now! areas.length = 0; for ( var i = 0; i < areas.length && !this.onLink; i++ ) { var area = areas[i]; if ( area instanceof HTMLAreaElement ) { // Get type (rect/circle/polygon/default). var type = area.getAttribute( "type" ); var coords = this.parseCoords( area ); switch ( type.toUpperCase() ) { case "RECT": case "RECTANGLE": break; case "CIRC": case "CIRCLE": break; case "POLY": case "POLYGON": break; case "DEFAULT": // Default matches entire image. this.onLink = true; this.link = area; this.onSaveableLink = this.isLinkSaveable( this.link ); break; } } } } } } else if ( this.target instanceof HTMLObjectElement && // See if object tag is for an image. this.objectIsImage( this.target ) ) { // This is an image. this.onImage = true; // URL must be constructed. this.imageURL = this.objectImageURL( this.target ); } else if ( this.target instanceof HTMLInputElement) { type = this.target.getAttribute("type"); if(type && type.toUpperCase() == "IMAGE") { this.onImage = true; // Convert src attribute to absolute URL. this.imageURL = makeURLAbsolute( this.target.baseURI, this.target.src ); } else /* if (this.target.getAttribute( "type" ).toUpperCase() == "TEXT") */ { this.onTextInput = this.isTargetATextBox(this.target); this.onKeywordField = this.isTargetAKeywordField(this.target); } } else if ( this.target instanceof HTMLTextAreaElement ) { this.onTextInput = true; } else if ( this.target instanceof HTMLHtmlElement ) { // pages with multiple <body>s are lame. we'll teach them a lesson. var bodyElt = this.target.ownerDocument.getElementsByTagName("body")[0]; if ( bodyElt ) { var computedURL = this.getComputedURL( bodyElt, "background-image" ); if ( computedURL ) { this.hasBGImage = true; this.bgImageURL = makeURLAbsolute( bodyElt.baseURI, computedURL ); } } } else if ( "HTTPIndex" in _content && _content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) { this.inDirList = true; // Bubble outward till we get to an element with URL attribute // (which should be the href). var root = this.target; while ( root && !this.link ) { if ( root.tagName == "tree" ) { // Hit root of tree; must have clicked in empty space; // thus, no link. break; } if ( root.getAttribute( "URL" ) ) { // Build pseudo link object so link-related functions work. this.onLink = true; this.link = { href : root.getAttribute("URL"), getAttribute: function (attr) { if (attr == "title") { return root.firstChild.firstChild.getAttribute("label"); } else { return ""; } } }; // If element is a directory, then you can't save it. if ( root.getAttribute( "container" ) == "true" ) { this.onSaveableLink = false; } else { this.onSaveableLink = true; } } else { root = root.parentNode; } } } } // We have meta data on images. this.onMetaDataItem = this.onImage; // See if the user clicked on MathML const NS_MathML = "http://www.w3.org/1998/Math/MathML"; if ((this.target.nodeType == Node.TEXT_NODE && this.target.parentNode.namespaceURI == NS_MathML) || (this.target.namespaceURI == NS_MathML)) this.onMathML = true; // See if the user clicked in a frame. if ( this.target.ownerDocument != window._content.document ) { this.inFrame = true; } // Bubble out, looking for items of interest var elem = this.target; while ( elem ) { if ( elem.nodeType == Node.ELEMENT_NODE ) { // Link? if ( !this.onLink && ( (elem instanceof HTMLAnchorElement && elem.href) || elem instanceof HTMLAreaElement || elem instanceof HTMLLinkElement || elem.getAttributeNS( "http://www.w3.org/1999/xlink", "type") == "simple" ) ) { // Clicked on a link. this.onLink = true; this.onMetaDataItem = true; // Remember corresponding element. this.link = elem; this.onMailtoLink = this.isLinkType( "mailto:", this.link ); // Remember if it is saveable. this.onSaveableLink = this.isLinkSaveable( this.link ); } // Text input? if ( !this.onTextInput ) { // Clicked on a link. this.onTextInput = this.isTargetATextBox(elem); } // Metadata item? if ( !this.onMetaDataItem ) { // We currently display metadata on anything which fits // the below test. if ( ( elem instanceof HTMLQuoteElement && elem.cite) || ( elem instanceof HTMLTableElement && elem.summary) || ( elem instanceof HTMLModElement && ( elem.cite || elem.dateTime ) ) || ( elem instanceof HTMLElement && ( elem.title || elem.lang ) ) ) { this.onMetaDataItem = true; } } // Background image? Don't bother if we've already found a // background image further down the hierarchy. Otherwise, // we look for the computed background-image style. if ( !this.hasBGImage ) { var bgImgUrl = this.getComputedURL( elem, "background-image" ); if ( bgImgUrl ) { this.hasBGImage = true; this.bgImageURL = makeURLAbsolute( elem.baseURI, bgImgUrl ); } } } elem = elem.parentNode; } }, // Returns the computed style attribute for the given element. getComputedStyle: function( elem, prop ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, '' ).getPropertyValue( prop ); }, // Returns a "url"-type computed style attribute value, with the url() stripped. getComputedURL: function( elem, prop ) { var url = elem.ownerDocument.defaultView.getComputedStyle( elem, '' ).getPropertyCSSValue( prop ); return ( url.primitiveType == CSSPrimitiveValue.CSS_URI ) ? url.getStringValue() : null; }, // Returns true iff clicked on link is saveable. isLinkSaveable : function ( link ) { // We don't do the Right Thing for news/snews yet, so turn them off // until we do. return !(this.isLinkType( "mailto:" , link ) || this.isLinkType( "javascript:" , link ) || this.isLinkType( "news:", link ) || this.isLinkType( "snews:", link ) ); }, // Returns true iff clicked on link is of type given. isLinkType : function ( linktype, link ) { try { // Test for missing protocol property. if ( !link.protocol ) { // We must resort to testing the URL string :-(. var protocol; var wrapper = new XPCNativeWrapper(link, "href", "getAttributeNS()"); if (wrapper.href) { protocol = wrapper.href.substr(0, linktype.length); } else { protocol = wrapper.getAttributeNS("http://www.w3.org/1999/xlink","href"); if (protocol) { protocol = protocol.substr(0, linktype.length); } } return protocol.toLowerCase() === linktype; } else { // Presume all but javascript: urls are saveable. return link.protocol.toLowerCase() === linktype; } } catch (e) { // something was wrong with the link, // so we won't be able to save it anyway return false; } }, // Open linked-to URL in a new window. openLink : function () { // Determine linked-to URL. openNewWindowWith(this.linkURL(), this.link, true); }, // Open linked-to URL in a new tab. openLinkInTab : function () { // Determine linked-to URL. openNewTabWith(this.linkURL(), this.link, null, true); }, // Open frame in a new tab. openFrameInTab : function () { // Determine linked-to URL. openNewTabWith(this.target.ownerDocument.location.href, null, null, true); }, // Reload clicked-in frame. reloadFrame : function () { this.target.ownerDocument.location.reload(); }, // Open clicked-in frame in its own window. openFrame : function () { openNewWindowWith(this.target.ownerDocument.location.href, null, true); }, // Open clicked-in frame in the same window showOnlyThisFrame : function () { window.loadURI(this.target.ownerDocument.location.href, null, null); }, // View Partial Source viewPartialSource : function ( context ) { var focusedWindow = document.commandDispatcher.focusedWindow; if (focusedWindow == window) focusedWindow = _content; var docCharset = null; if (focusedWindow) docCharset = "charset=" + focusedWindow.document.characterSet; // "View Selection Source" and others such as "View MathML Source" // are mutually exclusive, with the precedence given to the selection // when there is one var reference = null; if (context == "selection") reference = focusedWindow.getSelection(); else if (context == "mathml") reference = this.target; else throw "not reached"; var docUrl = null; // unused (and play nice for fragments generated via XSLT too) window.openDialog("chrome://global/content/viewPartialSource.xul", "_blank", "scrollbars,resizable,chrome,dialog=no", docUrl, docCharset, reference, context); }, // Open new "view source" window with the frame's URL. viewFrameSource : function () { BrowserViewSourceOfDocument(this.target.ownerDocument); }, viewInfo : function () { BrowserPageInfo(); }, viewFrameInfo : function () { BrowserPageInfo(this.target.ownerDocument); }, // Change current window to the URL of the image. viewImage : function (e) { urlSecurityCheck( this.imageURL, document ) openUILink( this.imageURL, e ); }, // Change current window to the URL of the background image. viewBGImage : function (e) { urlSecurityCheck( this.bgImageURL, document ) openUILink( this.bgImageURL, e ); }, setWallpaper: function() { // Confirm since it's annoying if you hit this accidentally. openDialog("chrome://browser/content/setWallpaper.xul", "", "centerscreen,chrome,dialog,modal,dependent", this.target); }, // Save URL of clicked-on frame. saveFrame : function () { saveDocument( this.target.ownerDocument ); }, // Save URL of clicked-on link. saveLink : function () { saveURL( this.linkURL(), this.linkText(), null, true, false ); }, sendLink : function () { MailIntegration.sendMessage( this.linkURL(), "" ); // we don't know the title of the link so pass in an empty string }, // Save URL of clicked-on image. saveImage : function () { saveURL( this.imageURL, null, "SaveImageTitle", false ); }, sendImage : function () { MailIntegration.sendMessage(this.imageURL, ""); }, toggleImageBlocking : function (aBlock) { var nsIPermissionManager = Components.interfaces.nsIPermissionManager; var permissionmanager = Components.classes["@mozilla.org/permissionmanager;1"] .getService(nsIPermissionManager); var uri = Components.classes["@mozilla.org/network/standard-url;1"] .createInstance(Components.interfaces.nsIURI); uri.spec = this.imageURL; permissionmanager.add(uri, "image", aBlock ? nsIPermissionManager.DENY_ACTION : nsIPermissionManager.ALLOW_ACTION); }, isImageBlocked : function() { var nsIPermissionManager = Components.interfaces.nsIPermissionManager; var permissionmanager = Components.classes["@mozilla.org/permissionmanager;1"] .getService(Components.interfaces.nsIPermissionManager); var uri = Components.classes["@mozilla.org/network/standard-url;1"] .createInstance(Components.interfaces.nsIURI); uri.spec = this.imageURL; return permissionmanager.testPermission(uri, "image") == nsIPermissionManager.DENY_ACTION; }, // Generate email address and put it on clipboard. copyEmail : function () { // Copy the comma-separated list of email addresses only. // There are other ways of embedding email addresses in a mailto: // link, but such complex parsing is beyond us. var url = this.linkURL(); var qmark = url.indexOf( "?" ); var addresses; if ( qmark > 7 ) { // 7 == length of "mailto:" addresses = url.substring( 7, qmark ); } else { addresses = url.substr( 7 ); } // Let's try to unescape it using a character set // in case the address is not ASCII. try { var characterSet = Components.lookupMethod(this.target.ownerDocument, "characterSet") .call(this.target.ownerDocument); const textToSubURI = Components.classes["@mozilla.org/intl/texttosuburi;1"] .getService(Components.interfaces.nsITextToSubURI); addresses = textToSubURI.unEscapeNonAsciiURI(characterSet, addresses); } catch(ex) { // Do nothing. } var clipboard = this.getService( "@mozilla.org/widget/clipboardhelper;1", Components.interfaces.nsIClipboardHelper ); clipboard.copyString(addresses); }, addBookmark : function() { var docshell = document.getElementById( "content" ).webNavigation; BookmarksUtils.addBookmark( docshell.currentURI.spec, docshell.document.title, docshell.document.charset); }, addBookmarkForFrame : function() { var doc = this.target.ownerDocument; var uri = doc.location.href; var title = doc.title; if ( !title ) title = uri; BookmarksUtils.addBookmark(uri, title, doc.charset); }, // Open Metadata window for node showMetadata : function () { window.openDialog( "chrome://browser/content/metaData.xul", "_blank", "scrollbars,resizable,chrome,dialog=no", this.target); }, /////////////// // Utilities // /////////////// // Create instance of component given contractId and iid (as string). createInstance : function ( contractId, iidName ) { var iid = Components.interfaces[ iidName ]; return Components.classes[ contractId ].createInstance( iid ); }, // Get service given contractId and iid (as string). getService : function ( contractId, iidName ) { var iid = Components.interfaces[ iidName ]; return Components.classes[ contractId ].getService( iid ); }, // Show/hide one item (specified via name or the item element itself). showItem : function ( itemOrId, show ) { var item = itemOrId.constructor == String ? document.getElementById(itemOrId) : itemOrId; if (item) item.hidden = !show; }, // Set given attribute of specified context-menu item. If the // value is null, then it removes the attribute (which works // nicely for the disabled attribute). setItemAttr : function ( id, attr, val ) { var elem = document.getElementById( id ); if ( elem ) { if ( val == null ) { // null indicates attr should be removed. elem.removeAttribute( attr ); } else { // Set attr=val. elem.setAttribute( attr, val ); } } }, // Set context menu attribute according to like attribute of another node // (such as a broadcaster). setItemAttrFromNode : function ( item_id, attr, other_id ) { var elem = document.getElementById( other_id ); if ( elem && elem.getAttribute( attr ) == "true" ) { this.setItemAttr( item_id, attr, "true" ); } else { this.setItemAttr( item_id, attr, null ); } }, // Temporary workaround for DOM api not yet implemented by XUL nodes. cloneNode : function ( item ) { // Create another element like the one we're cloning. var node = document.createElement( item.tagName ); // Copy attributes from argument item to the new one. var attrs = item.attributes; for ( var i = 0; i < attrs.length; i++ ) { var attr = attrs.item( i ); node.setAttribute( attr.nodeName, attr.nodeValue ); } // Voila! return node; }, // Generate fully-qualified URL for clicked-on link. linkURL : function () { var wrapper = new XPCNativeWrapper(this.link, "href", "baseURI", "getAttributeNS()"); if (wrapper.href) { return wrapper.href; } var href = wrapper.getAttributeNS("http://www.w3.org/1999/xlink", "href"); if (!href || !href.match(/\S/)) { throw "Empty href"; // Without this we try to save as the current doc, for example, HTML case also throws if empty } href = makeURLAbsolute(wrapper.baseURI, href); return href; }, // Get text of link. linkText : function () { var text = gatherTextUnder( this.link ); if (!text || !text.match(/\S/)) { text = this.link.getAttribute("title"); if (!text || !text.match(/\S/)) { text = this.link.getAttribute("alt"); if (!text || !text.match(/\S/)) { var wrapper = new XPCNativeWrapper(this.link, "href", "baseURI", "getAttributeNS()"); if (wrapper.href) { text = wrapper.href; } else { text = wrapper.getAttributeNS("http://www.w3.org/1999/xlink", "href"); if (text && text.match(/\S/)) { text = makeURLAbsolute(wrapper.baseURI, text); } } } } } return text; }, //Get selected object and convert it to a string to get //selected text. Only use the first 15 chars. isTextSelection : function() { var result = false; var selection = this.searchSelected(16); var searchSelectText; if (selection) { searchSelectText = selection.toString(); dump("1: In isTextSelection(): " +searchSelectText+ "\n"); if (searchSelectText.length > 15) searchSelectText = searchSelectText.substr(0,15) + "..."; result = true; // format "Search for <selection>" string to show in menu searchSelectText = gNavigatorBundle.getFormattedString("searchText", [searchSelectText]); dump("2: In isTextSelection(): " +searchSelectText+ "\n"); this.setItemAttr("context-searchselect", "label", searchSelectText); } return result; }, searchSelected : function( charlen ) { var focusedWindow = document.commandDispatcher.focusedWindow; var searchStr = focusedWindow.getSelection(); searchStr = searchStr.toString(); dump("In searchSelected(): " +searchStr+ "\n"); // searching for more than 150 chars makes no sense if (!charlen) charlen = 150; if (charlen < searchStr.length) { // only use the first charlen important chars. see bug 221361 var pattern = new RegExp("^(?:\\s*.){0," + charlen + "}"); pattern.test(searchStr); searchStr = RegExp.lastMatch; } searchStr = searchStr.replace(/\s*(.*?)\s*$/, "$1"); searchStr = searchStr.replace(/\s+/g, " "); return searchStr; }, // Determine if target <object> is an image. objectIsImage : function ( objElem ) { var result = false; // Get type and data attributes. var type = objElem.getAttribute( "type" ); var data = objElem.getAttribute( "data" ); // Presume any mime type of the form "image/..." is an image. // There must be a data= attribute with an URL, also. if ( type.substring( 0, 6 ) == "image/" && data) { result = true; } return result; }, // Extract image URL from <object> tag. objectImageURL : function ( objElem ) { // Extract url from data= attribute. var data = objElem.getAttribute( "data" ); // Make it absolute. return makeURLAbsolute( objElem.baseURI, data ); }, // Parse coords= attribute and return array. parseCoords : function ( area ) { return []; }, toString : function () { return "contextMenu.target = " + this.target + "\n" + "contextMenu.onImage = " + this.onImage + "\n" + "contextMenu.onLink = " + this.onLink + "\n" + "contextMenu.link = " + this.link + "\n" + "contextMenu.inFrame = " + this.inFrame + "\n" + "contextMenu.hasBGImage = " + this.hasBGImage + "\n"; }, isTargetATextBox : function ( node ) { if (node instanceof HTMLInputElement) return (node.type == "text" || node.type == "password") return (node instanceof HTMLTextAreaElement); }, isTargetAKeywordField : function ( node ) { var form = node.form; if (!form) return false; var method = form.method.toUpperCase(); // These are the following types of forms we can create keywords for: // // method encoding type can create keyword // GET * YES // * YES // POST YES // POST application/x-www-form-urlencoded YES // POST text/plain NO (a little tricky to do) // POST multipart/form-data NO // POST everything else YES return (method == "GET" || method == "") || (form.enctype != "text/plain") && (form.enctype != "multipart/form-data"); }, // Determines whether or not the separator with the specified ID should be // shown or not by determining if there are any non-hidden items between it // and the previous separator. shouldShowSeparator : function ( aSeparatorID ) { var separator = document.getElementById(aSeparatorID); if (separator) { var sibling = separator.previousSibling; while (sibling && sibling.localName != "menuseparator") { if (sibling.getAttribute("hidden") != "true") return true; sibling = sibling.previousSibling; } } return false; } } var gWebPanelURI; function openWebPanel(aTitle, aURI) { // Ensure that the web panels sidebar is open. toggleSidebar('viewWebPanelsSidebar', true); // Set the title of the panel. document.getElementById("sidebar-title").value = aTitle; // Tell the Web Panels sidebar to load the bookmark. var sidebar = document.getElementById("sidebar"); if (sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser')) { sidebar.contentWindow.loadWebPanel(aURI); if (gWebPanelURI) { gWebPanelURI = ""; sidebar.removeEventListener("load", asyncOpenWebPanel, true); } } else { // The panel is still being constructed. Attach an onload handler. if (!gWebPanelURI) sidebar.addEventListener("load", asyncOpenWebPanel, true); gWebPanelURI = aURI; } } function asyncOpenWebPanel(event) { var sidebar = document.getElementById("sidebar"); if (gWebPanelURI && sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser')) sidebar.contentWindow.loadWebPanel(gWebPanelURI); gWebPanelURI = ""; sidebar.removeEventListener("load", asyncOpenWebPanel, true); } /* * - [ Dependencies ] --------------------------------------------------------- * utilityOverlay.js: * - gatherTextUnder */ // Called whenever the user clicks in the content area, // except when left-clicking on links (special case) // should always return true for click to go through function contentAreaClick(event, fieldNormalClicks) { if (!event.isTrusted) { return true; } var target = event.target; var linkNode; if (target instanceof HTMLAnchorElement || target instanceof HTMLAreaElement || target instanceof HTMLLinkElement) { if (target.hasAttribute("href")) linkNode = target; } else { linkNode = event.originalTarget; while (linkNode && !(linkNode instanceof HTMLAnchorElement)) linkNode = linkNode.parentNode; // <a> cannot be nested. So if we find an anchor without an // href, there is no useful <a> around the target if (linkNode && !linkNode.hasAttribute("href")) linkNode = null; } if (linkNode) { var wrapper = new XPCNativeWrapper(linkNode, "href", "getAttribute()", "ownerDocument"); if (event.button == 0 && !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey) { // A Web panel's links should target the main content area. Do this // if no modifier keys are down and if there's no target or the target equals // _main (the IE convention) or _content (the Mozilla convention). // The only reason we field _main and _content here is for the markLinkVisited // hack. target = wrapper.getAttribute("target"); var docWrapper = new XPCNativeWrapper(wrapper.ownerDocument, "location"); var locWrapper = new XPCNativeWrapper(docWrapper.location, "href"); if (fieldNormalClicks && (!target || target == "_content" || target == "_main")) // IE uses _main, SeaMonkey uses _content, we support both { if (!wrapper.href) return true; if (wrapper.getAttribute("onclick")) return true; // javascript links should be executed in the current browser if (wrapper.href.substr(0, 11) === "javascript:") return true; // data links should be executed in the current browser if (wrapper.href.substr(0, 5) === "data:") return true; if (!webPanelSecurityCheck(locWrapper.href, wrapper.href)) return false; var postData = { }; var url = getShortcutOrURI(wrapper.href, postData); if (!url) return true; markLinkVisited(wrapper.href, linkNode); loadURI(url, null, postData.value); event.preventDefault(); return false; } else if (linkNode.getAttribute("rel") == "sidebar") { // This is the Opera convention for a special link that - when clicked - allows // you to add a sidebar panel. We support the Opera convention here. The link's // title attribute contains the title that should be used for the sidebar panel. openDialog("chrome://browser/content/bookmarks/addBookmark2.xul", "", "centerscreen,chrome,dialog,resizable,dependent", wrapper.getAttribute("title"), wrapper.href, null, null, null, null, true); event.preventDefault(); return false; } else if (target == "_search") { // Used in WinIE as a way of transiently loading pages in a sidebar. We // mimic that WinIE functionality here and also load the page transiently. // javascript links targeting the sidebar shouldn't be allowed // we copied this from IE, and IE blocks this completely if (wrapper.href.substr(0, 11) === "javascript:") return false; // data: URIs are just as dangerous if (wrapper.href.substr(0, 5) === "data:") return false; if (!webPanelSecurityCheck(locWrapper.href, wrapper.href)) return false; openWebPanel(gNavigatorBundle.getString("webPanels"), wrapper.href); event.preventDefault(); return false; } } else { handleLinkClick(event, wrapper.href, linkNode); } return true; } else { // Try simple XLink var href; linkNode = target; while (linkNode) { if (linkNode.nodeType == Node.ELEMENT_NODE) { var wrapper = new XPCNativeWrapper(linkNode, "getAttributeNS()"); href = wrapper.getAttributeNS("http://www.w3.org/1999/xlink", "href"); break; } linkNode = linkNode.parentNode; } if (href) { var baseURI = new XPCNativeWrapper(linkNode, "baseURI").baseURI; href = makeURLAbsolute(baseURI, href); handleLinkClick(event, href, null); return true; } } if (event.button == 1 && !event.getPreventDefault() && gPrefService.getBoolPref("middlemouse.contentLoadURL")) { middleMousePaste(event); } return true; } function handleLinkClick(event, href, linkNode) { switch (event.button) { case 0: if (event.ctrlKey) { openNewTabWith(href, linkNode, event, true); event.preventBubble(); return true; } // if left button clicked if (event.shiftKey) { openNewWindowWith(href, linkNode, true); event.preventBubble(); return true; } if (event.altKey) { saveURL(href, linkNode ? gatherTextUnder(linkNode) : "", null, true, true); return true; } return false; case 1: // if middle button clicked var tab; try { tab = gPrefService.getBoolPref("browser.tabs.opentabfor.middleclick") } catch(ex) { tab = true; } if (tab) openNewTabWith(href, linkNode, event, true); else openNewWindowWith(href, linkNode, true); event.preventBubble(); return true; } return false; } function middleMousePaste(event) { var url = readFromClipboard(); if (!url) return; var postData = { }; url = getShortcutOrURI(url, postData); if (!url) return; openUILink(url, event, true /* ignore the fact this is a middle click */); event.preventBubble(); } function makeURLAbsolute( base, url ) { // Construct nsIURL. var ioService = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var baseURI = ioService.newURI(base, null, null); return ioService.newURI(baseURI.resolve(url), null, null).spec; } function saveFrameDocument() { var focusedWindow = document.commandDispatcher.focusedWindow; if (isContentFrame(focusedWindow)) saveDocument(focusedWindow.document); } /* * Note that most of this routine has been moved into C++ in order to * be available for all <browser> tags as well as gecko embedding. See * mozilla/content/base/src/nsContentAreaDragDrop.cpp. * * Do not add any new fuctionality here other than what is needed for * a standalone product. */ var contentAreaDNDObserver = { onDrop: function (aEvent, aXferData, aDragSession) { var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType); // valid urls don't contain spaces ' '; if we have a space it // isn't a valid url, or if it's a javascript: or data: url, // bail out if (!url || !url.length || url.indexOf(" ", 0) != -1 || /^\s*(javascript|data):/.test(url)) return; getBrowser().dragDropSecurityCheck(aEvent, aDragSession, url); switch (document.firstChild.getAttribute('windowtype')) { case "navigator:browser": var postData = { }; var uri = getShortcutOrURI(url, postData); loadURI(uri, null, postData.value); break; case "navigator:view-source": viewSource(url); break; } // keep the event from being handled by the dragDrop listeners // built-in to gecko if they happen to be above us. aEvent.preventDefault(); }, getSupportedFlavours: function () { var flavourSet = new FlavourSet(); flavourSet.appendFlavour("text/x-moz-url"); flavourSet.appendFlavour("text/unicode"); flavourSet.appendFlavour("application/x-moz-file", "nsIFile"); return flavourSet; } }; // For extensions function getBrowser() { if (!gBrowser) gBrowser = document.getElementById("content"); return gBrowser; } function MultiplexHandler(event) { try { var node = event.target; var name = node.getAttribute('name'); if (name == 'detectorGroup') { SetForcedDetector(true); SelectDetector(event, false); } else if (name == 'charsetGroup') { var charset = node.getAttribute('id'); charset = charset.substring('charset.'.length, charset.length) SetForcedCharset(charset); SetDefaultCharacterSet(charset); } else if (name == 'charsetCustomize') { //do nothing - please remove this else statement, once the charset prefs moves to the pref window } else { SetForcedCharset(node.getAttribute('id')); SetDefaultCharacterSet(node.getAttribute('id')); } } catch(ex) { dump ("Caught Exception: " + ex + "\n"); } } function SetDefaultCharacterSet(charset) { BrowserSetDefaultCharacterSet(charset); } function SelectDetector(event, doReload) { var uri = event.target.getAttribute("id"); var prefvalue = uri.substring('chardet.'.length, uri.length); if ("off" == prefvalue) { // "off" is special value to turn off the detectors prefvalue = ""; } try { var pref = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); var str = Components.classes["@mozilla.org/supports-string;1"] .createInstance(Components.interfaces.nsISupportsString); str.data = prefvalue; pref.setComplexValue("intl.charset.detector", Components.interfaces.nsISupportsString, str); if (doReload) window._content.location.reload(); } catch (ex) { dump("Failed to set the intl.charset.detector preference.\n"); } } function SetForcedDetector(doReload) { BrowserSetForcedDetector(doReload); } function SetForcedCharset(charset) { BrowserSetForcedCharacterSet(charset); } function BrowserSetDefaultCharacterSet(aCharset) { // no longer needed; set when setting Force; see bug 79608 } function BrowserSetForcedCharacterSet(aCharset) { var docCharset = getBrowser().docShell.QueryInterface( Components.interfaces.nsIDocCharset); docCharset.charset = aCharset; BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE); } function BrowserSetForcedDetector(doReload) { getBrowser().documentCharsetInfo.forcedDetector = true; if (doReload) BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE); } function UpdateCurrentCharset() { var menuitem = null; // exctract the charset from DOM var wnd = document.commandDispatcher.focusedWindow; if ((window == wnd) || (wnd == null)) wnd = window._content; menuitem = document.getElementById('charset.' + wnd.document.characterSet); if (menuitem) { // uncheck previously checked item to workaround Mac checkmark problem // bug 98625 if (gPrevCharset) { var pref_item = document.getElementById('charset.' + gPrevCharset); if (pref_item) pref_item.setAttribute('checked', 'false'); } menuitem.setAttribute('checked', 'true'); } } function UpdateCharsetDetector() { // showStack(); var prefvalue; try { var pref = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch); prefvalue = pref.getComplexValue("intl.charset.detector", Components.interfaces.nsIPrefLocalizedString).data; } catch (ex) { prefvalue = ""; } if (prefvalue == "") prefvalue = "off"; // dump("intl.charset.detector = "+ prefvalue + "\n"); prefvalue = 'chardet.' + prefvalue; var menuitem = document.getElementById(prefvalue); if (menuitem) { menuitem.setAttribute('checked', 'true'); } } function UpdateMenus(event) { // use setTimeout workaround to delay checkmark the menu // when onmenucomplete is ready then use it instead of oncreate // see bug 78290 for the detail UpdateCurrentCharset(); setTimeout(UpdateCurrentCharset, 0); UpdateCharsetDetector(); setTimeout(UpdateCharsetDetector, 0); } function CreateMenu(node) { // dump (" Calling CreateMenu to make a charset menu from within Browser.js\n\n"); // showStack(); var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); observerService.notifyObservers(null, "charsetmenu-selected", node); } function charsetLoadListener (event) { var charset = window._content.document.characterSet; if (charset.length > 0 && (charset != gLastBrowserCharset)) { if (!gCharsetMenu) gCharsetMenu = Components.classes['@mozilla.org/rdf/datasource;1?name=charset-menu'].getService().QueryInterface(Components.interfaces.nsICurrentCharsetListener); gCharsetMenu.SetCurrentCharset(charset); gPrevCharset = gLastBrowserCharset; gLastBrowserCharset = charset; } } /* Begin Page Style Functions */ function getStyleSheetArray(frame) { var styleSheets = frame.document.styleSheets; var styleSheetsArray = new Array(styleSheets.length); for (var i = 0; i < styleSheets.length; i++) { styleSheetsArray[i] = styleSheets[i]; } return styleSheetsArray; } function getAllStyleSheets(frameset) { var styleSheetsArray = getStyleSheetArray(frameset); for (var i = 0; i < frameset.frames.length; i++) { var frameSheets = getAllStyleSheets(frameset.frames[i]); styleSheetsArray = styleSheetsArray.concat(frameSheets); } return styleSheetsArray; } function stylesheetFillPopup(menuPopup) { var noStyle = menuPopup.firstChild; var persistentOnly = noStyle.nextSibling; var sep = persistentOnly.nextSibling; while (sep.nextSibling) menuPopup.removeChild(sep.nextSibling); var styleSheets = getAllStyleSheets(window._content); var currentStyleSheets = []; var styleDisabled = getMarkupDocumentViewer().authorStyleDisabled; var haveAltSheets = false; var altStyleSelected = false; for (var i = 0; i < styleSheets.length; ++i) { var currentStyleSheet = styleSheets[i]; // Skip any stylesheets that don't match the screen media type. var media = currentStyleSheet.media.mediaText.toLowerCase(); if (media && (media.indexOf("screen") == -1) && (media.indexOf("all") == -1)) continue; if (currentStyleSheet.title) { if (!currentStyleSheet.disabled) altStyleSelected = true; haveAltSheets = true; var lastWithSameTitle = null; if (currentStyleSheet.title in currentStyleSheets) lastWithSameTitle = currentStyleSheets[currentStyleSheet.title]; if (!lastWithSameTitle) { var menuItem = document.createElement("menuitem"); menuItem.setAttribute("type", "radio"); menuItem.setAttribute("label", currentStyleSheet.title); menuItem.setAttribute("data", currentStyleSheet.title); menuItem.setAttribute("checked", !currentStyleSheet.disabled && !styleDisabled); menuPopup.appendChild(menuItem); currentStyleSheets[currentStyleSheet.title] = menuItem; } else { if (currentStyleSheet.disabled) lastWithSameTitle.removeAttribute("checked"); } } } noStyle.setAttribute("checked", styleDisabled); persistentOnly.setAttribute("checked", !altStyleSelected && !styleDisabled); persistentOnly.hidden = (window._content.document.preferredStylesheetSet) ? true : false; sep.hidden = (noStyle.hidden && persistentOnly.hidden) || !haveAltSheets; return true; } function stylesheetInFrame(frame, title) { var docStyleSheets = frame.document.styleSheets; for (var i = 0; i < docStyleSheets.length; ++i) { if (docStyleSheets[i].title == title) return true; } return false; } function stylesheetSwitchFrame(frame, title) { var docStyleSheets = frame.document.styleSheets; for (var i = 0; i < docStyleSheets.length; ++i) { var docStyleSheet = docStyleSheets[i]; if (title == "_nostyle") docStyleSheet.disabled = true; else if (docStyleSheet.title) docStyleSheet.disabled = (docStyleSheet.title != title); else if (docStyleSheet.disabled) docStyleSheet.disabled = false; } } function stylesheetSwitchAll(frameset, title) { if (!title || title == "_nostyle" || stylesheetInFrame(frameset, title)) { stylesheetSwitchFrame(frameset, title); } for (var i = 0; i < frameset.frames.length; i++) { stylesheetSwitchAll(frameset.frames[i], title); } } function setStyleDisabled(disabled) { getMarkupDocumentViewer().authorStyleDisabled = disabled; } /* End of the Page Style functions */ function clearObsoletePrefs() { // removed 10/03/2003 try { PREF.clearUserPref("timebomb.first_launch_time"); } catch (e) {} // removed 10/16/2003 // migrate firebird cookie prefs, if they exist. try { PREF.clearUserPref("network.cookie.enable"); // No error: it means this pref was not the default one, cookie were disabled. PREF.SetIntPref("network.cookie.cookieBehavior", 2); } catch (e) { try { PREF.clearUserPref("network.cookie.enableForOriginatingWebsiteOnly"); // No error: it means that enableForOriginatingWebsiteOnly was true. PREF.SetIntPref("network.cookie.cookieBehavior", 1); } catch (e) { // here, either we already have migrated the cookie pref // or the new and old behavior are the same (0). In any case: nothing to do. } } // removed 03/09/2003 // last of the forked cookie prefs try { PREF.clearUserPref("network.cookie.enableForCurrentSessionOnly"); // No error, therefore we were limiting cookies to session PREF.setIntPref("network.cookie.lifetimePolicy", 2); } catch (e) { // nothing to do in this case } try { PREF.clearUserPref("network.cookie.warnAboutCookies"); // No error: the pref is set to ask for cookies, set the correct pref // This will replace the setting if enableForCurrentSessionOnly was // also true, because dialogs explictly allow accepting for session PREF.setIntPref("network.cookie.lifetimePolicy", 1); } catch (e) { // nothing to do in this case } // removed 10/22/2003 try { PREF.clearUserPref("browser.search.defaultengine"); } catch (e) {} // removed 11/01/2003 try { PREF.clearUserPref("print.use_global_printsettings"); } catch (e) {} try { PREF.clearUserPref("print.save_print_settings"); } catch (e) {} } var BrowserOffline = { ///////////////////////////////////////////////////////////////////////////// // BrowserOffline Public Methods init: function () { var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); os.addObserver(this, "network:offline-status-changed", false); if (!this._uiElement) this._uiElement = document.getElementById("goOfflineMenuitem"); // set the initial state var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); var isOffline = false; try { isOffline = gPrefService.getBoolPref("browser.offline"); } catch (e) { } ioService.offline = isOffline; this._updateOfflineUI(isOffline); }, uninit: function () { try { var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); os.removeObserver(this, "network:offline-status-changed"); } catch (ex) { } }, toggleOfflineStatus: function () { if (!this._canGoOffline()) { this._updateOfflineUI(false); return; } var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); ioService.offline = !ioService.offline; gPrefService.setBoolPref("browser.offline", ioService.offline); }, ///////////////////////////////////////////////////////////////////////////// // nsIObserver observe: function (aSubject, aTopic, aState) { if (aTopic != "network:offline-status-changed") return; this._updateOfflineUI(aState == "offline"); }, ///////////////////////////////////////////////////////////////////////////// // BrowserOffline Implementation Methods _canGoOffline: function () { var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); if (os) { try { var cancelGoOffline = Components.classes["@mozilla.org/supports-PRBool;1"].createInstance(Components.interfaces.nsISupportsPRBool); os.notifyObservers(cancelGoOffline, "offline-requested", null); // Something aborted the quit process. if (cancelGoOffline.data) return false; } catch (ex) { } } return true; }, _uiElement: null, _updateOfflineUI: function (aOffline) { var offlineLocked = gPrefService.prefIsLocked("network.online"); if (offlineLocked) this._uiElement.setAttribute("disabled", "true"); this._uiElement.setAttribute("checked", aOffline); } }; function WindowIsClosing() { var browser = getBrowser(); var cn = browser.tabContainer.childNodes; var numtabs = cn.length; var reallyClose = browser.warnAboutClosingTabs(true); for (var i = 0; reallyClose && i < numtabs; ++i) { var ds = browser.getBrowserForTab(cn[i]).docShell; if (ds.contentViewer && !ds.contentViewer.permitUnload()) reallyClose = false; } if (reallyClose) return closeWindow(false); return reallyClose; } var MailIntegration = { sendLinkForContent: function () { this.sendMessage(Components.lookupMethod(window._content, 'location').call(window._content).href, Components.lookupMethod(window._content.document, 'title').call(window._content.document)); }, sendMessage: function (aBody, aSubject) { // generate a mailto url based on the url and the url's title var mailtoUrl = aBody ? "mailto:?body=" + encodeURIComponent(aBody) + "&subject=" + encodeURIComponent(aSubject) : "mailto:"; var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); var uri = ioService.newURI(mailtoUrl, null, null); // now pass this url to the operating system this._launchExternalUrl(uri); }, // a generic method which can be used to pass arbitrary urls to the operating system. // aURL --> a nsIURI which represents the url to launch _launchExternalUrl: function(aURL) { var extProtocolSvc = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"].getService(Components.interfaces.nsIExternalProtocolService); if (extProtocolSvc) extProtocolSvc.loadUrl(aURL); }, readMail: function () { var shell = getShellService(); if (shell) shell.openPreferredApplication(Components.interfaces.nsIShellService.APPLICATION_MAIL); }, readNews: function () { var shell = getShellService(); if (shell) shell.openPreferredApplication(Components.interfaces.nsIShellService.APPLICATION_NEWS); }, updateUnreadCount: function () { var shell = Components.classes["@mozilla.org/browser/shell-service;1"] .getService(Components.interfaces.nsIWindowsShellService); var unreadCount = shell.unreadMailCount; var message = gNavigatorBundle.getFormattedString("mailUnreadTooltip", [unreadCount]); var element = document.getElementById("mail-button"); if (element) element.setAttribute("tooltiptext", message); message = gNavigatorBundle.getFormattedString("mailUnreadMenuitem", [unreadCount]); element = document.getElementById("Browser:ReadMail"); if (element) element.setAttribute("label", message); } }; function BrowserOpenExtensions(aOpenMode) { const EMTYPE = "Extension:Manager"; var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var needToOpen = true; var windowType = EMTYPE + "-" + aOpenMode; var windows = wm.getEnumerator(windowType); while (windows.hasMoreElements()) { var theEM = windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindowInternal); if (theEM.document.documentElement.getAttribute("windowtype") == windowType) { theEM.focus(); needToOpen = false; break; } } if (needToOpen) { const EMURL = "chrome://mozapps/content/extensions/extensions.xul?type=" + aOpenMode; const EMFEATURES = "chrome,dialog=no,resizable"; window.openDialog(EMURL, "", EMFEATURES); } } function AutofillEdit() { const EMTYPE = "AutoFill:Manager"; var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var needToOpen = true; var windowType = EMTYPE; var windows = wm.getEnumerator(windowType); while (windows.hasMoreElements()) { var theEM = windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindowInternal); var wtype=theEM.document.documentElement.getAttribute("windowtype"); dump("window type:"+wtype+"\n"); if (theEM.document.documentElement.getAttribute("windowtype") == windowType) { theEM.focus(); needToOpen = false; break; } } if (needToOpen) { const EMURL = "chrome://browser/content/pref/pref.xul"; const EMFEATURES = "chrome,dialog=no,resizable"; window.openDialog(EMURL, "", EMFEATURES); } } // MERC - JCH: Combined datacard and passcard button behaviour. // Check whether page is passcardable first. If page isn't, then // assume it's datacardable. function DoCombinedAutofill() { // Does page have password/username fields? // (The boolean means: true = ignore whether there is text in fields, // false = insist that both fields have text otherwise return false). if (CheckIsPasscardable(true)) { DoPasscardOneTime(); } else { datacardButton(); } } // MERC - JCH: Fired when datacard-passcard button fill form menu item invoked. function DoCombinedFill(menuitem, doSubmit) { if (CheckIsPasscardable(true)) { fillUsernamePassword(menuitem, doSubmit); } else { if (doSubmit) datacardUtils.DoAutoFillAndSubmit(); else datacardUtils.DoAutoFill(); } } // MERC - JCH: Fired when datacard-passcard button save form menu item invoked. function DoCombinedSave() { if (CheckIsPasscardable(true)) { savePasscard(); } else { datacardUtils.SaveDatacard(); } } // MERC - JCH: Fired when datacard-passcard button drop-down menu is opened. function UpdateCombinedMenu(menuitem) { clearDatacardMenu(); clearPasscardMenu(); if (CheckIsPasscardable(true)) { updatePasscardMenu(menuitem); } else { updateDatacardMenu(); } } function AddKeywordForSearchField() { var node = document.popupNode; var ioService = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var uri = Components.classes["@mozilla.org/network/standard-url;1"] .getService(Components.interfaces.nsIURI); uri.spec = node.ownerDocument.URL; var keywordURL = ioService.newURI(node.form.action, node.ownerDocument.characterSet, uri); var spec = keywordURL.spec; var postData = ""; if (node.form.method.toUpperCase() == "POST" && (node.form.enctype == "application/x-www-form-urlencoded" || node.form.enctype == "")) { for (var i = 0; i < node.form.elements.length; ++i) { var e = node.form.elements[i]; if (e.type.toLowerCase() == "text" || e.type.toLowerCase() == "hidden" || e instanceof HTMLTextAreaElement) postData += escape(e.name + "=" + (e == node ? "%s" : e.value)) + "&"; else if (e instanceof HTMLSelectElement && e.selectedIndex >= 0) postData += escape(e.name + "=" + e.options[e.selectedIndex].value) + "&"; else if ((e.type.toLowerCase() == "checkbox" || e.type.toLowerCase() == "radio") && e.checked) postData += escape(e.name + "=" + e.value) + "&"; } } else { spec += "?" + escape(node.name) + "=%s"; for (var i = 0; i < node.form.elements.length; ++i) { var e = node.form.elements[i]; if (e == node) // avoid duplication of the target field value, which was populated above. continue; if (e.type.toLowerCase() == "text" || e.type.toLowerCase() == "hidden" || e instanceof HTMLTextAreaElement) spec += "&" + escape(e.name) + "=" + escape(e.value); else if (e instanceof HTMLSelectElement && e.selectedIndex >= 0) spec += "&" + escape(e.name) + "=" + escape(e.options[e.selectedIndex].value); else if ((e.type.toLowerCase() == "checkbox" || e.type.toLowerCase() == "radio") && e.checked) spec += "&" + escape(e.name) + "=" + escape(e.value); } } openDialog("chrome://browser/content/bookmarks/addBookmark2.xul", "", "centerscreen,chrome,dialog,resizable,dependent", "", spec, null, node.ownerDocument.characterSet, null, null, false, "", true, postData); } // MERC - This function opens the options panel as specified by the // optionToOpen parameter we need to setup string constants for all of these // panels, ie WEB_FEATURES = 2 so anyone can call any panel function openPrefs(optionToOpen) { // WARNING: KLUGE ALERT!!! gPrefService.setIntPref('browser.preferences.lastpanel', optionToOpen); openPreferences(); } // MERC (DP): opens the site controls prefs dialog with the entry for the // current tab selected. function openSiteControlPrefs() { var url = gBrowser.currentURI.spec; // is this a controlled site? var controlledSite = sitecontrols.getControlledSiteFromURL(url); var site; if (!controlledSite) { site = sitecontrols.DEFAULT_SITE; } else { site = controlledSite; } gPrefService.setCharPref('browser.preferences.selectedSite', site); openPrefs(3); } function getTridentDocument() { var hpDoc = null; try { hpDoc = gBrowser.contentDocument.QueryInterface(nsIHTMLPluginDocument); } catch(e) { } // Not trident return hpDoc; } // MERC (DP): enables/disables the "Clear Download Manager History" menu item in the // downloads toolbar button dropdown function updateDownloadsMenu(menu) { var dlMgr = Components.classes["@mozilla.org/download-manager;1"].getService(Components.interfaces.nsIDownloadManager); var clearDownloadsItem = document.getElementById('clearDownloadsHistory'); var clearDownloadsCmd = document.getElementById('History:ClearDownloads'); if(dlMgr.canCleanUp) { clearDownloadsItem.removeAttribute('disabled'); clearDownloadsCmd.removeAttribute('disabled'); } else { clearDownloadsItem.setAttribute('disabled', 'true'); clearDownloadsCmd.setAttribute('disabled', 'true'); } } // Clear out the specific datacards from the menu function clearDatacardMenu() { var menu = document.getElementById('combinedFormFillPopup'); if (!menu) return; var dcSep = document.getElementById('combinedFormFillDatacardSep'); if (!dcSep) return; dcSep.setAttribute('hidden', 'true'); var node = dcSep; while (node) { var temp = node; node = node.nextSibling; if (temp.hasAttribute('datacard')) menu.removeChild(temp); } } // MERC - JCH: Element IDs were modified to work with the // new combined datacard-passcard button. function updateDatacardMenu() { // Grab the menu items var formFill = document.getElementById('combinedFillFormMenuItem'); var formFillAndSubmit = document.getElementById('combinedFillAndSubmitMenuItem'); var save = document.getElementById('combinedSaveMenuItem'); // See if the current page is fillable var htmlFields = datacardUtils.RipFields(); var fillable = datacardUtils.IsPageAutoFillable( gBrowser.currentURI, htmlFields, true); // check for data var isBlacklisted = datacardUtils.IsSiteBlacklisted(gBrowser.currentURI); if (fillable) { if (!isBlacklisted && datacardUtils.DatacardsExist()) { var menu = document.getElementById('combinedFormFillPopup'); var dcSep = document.getElementById('combinedFormFillDatacardSep'); var pcSep = document.getElementById('combinedFormFillPasscardSep'); formFill.removeAttribute('disabled'); formFillAndSubmit.removeAttribute('disabled'); dcSep.removeAttribute('hidden'); var allDatacards = datacardUtils.GetDatacardList(); var siteDatacard = datacardUtils.FindDatacardForURI(gBrowser.currentURI); for (var i = 0; i < allDatacards.length; i++) { var item = document.createElement('menuitem'); item.setAttribute('label', allDatacards[i]); item.setAttribute('type', 'checkbox'); item.setAttribute('tooltiptext', 'Use this datacard'); item.setAttribute('datacard', 'true'); if (allDatacards[i] == siteDatacard) item.setAttribute('checked', 'true'); item.setAttribute('oncommand', 'datacardUtils.DoAutoFill(undefined,"'+allDatacards[i]+'");'); menu.insertBefore(item, pcSep); } } else { formFill.setAttribute('disabled','true'); formFillAndSubmit.setAttribute('disabled','true'); } } else { formFill.setAttribute('disabled','true'); formFillAndSubmit.setAttribute('disabled','true'); } // check if the user has entered any data on the page var bHasData = false; for (var j = 0; j < htmlFields.values.length; j++) { if (htmlFields.values[j] != '') { bHasData = true; break; } } // enable/disable the Save Form menu option if (!isBlacklisted && (fillable || bHasData)) save.removeAttribute('disabled'); else save.setAttribute('disabled','true'); } function datacardButton() { if (gPrefService.getPrefType('datacard.fillandsubmit') && gPrefService.getBoolPref('datacard.fillandsubmit')) { datacardUtils.DoAutoFillAndSubmit(); } else { datacardUtils.DoAutoFill(); } } var gCurrentNotificationBar = null; /* JMC: Enforces order of precedence between all possible simultaneous notification bars... */ function displayNotificationBar(barId, extraData) { dump("browser.js: Trying to show notification bar for : " + barId + "\n"); // Simple case - no other bars if (!gCurrentNotificationBar) { showNBar(barId, extraData); } else if (barPriority(barId) >= barPriority(gCurrentNotificationBar)) { showNBar(barId, extraData); } else { dump("browser.js: Not showing it - not important enough.\n"); } } function hideNotificationBar(barId, thisBrowser) { if (gCurrentNotificationBar == barId) { thisBrowser.hideMessage(thisBrowser.selectedBrowser, "top"); gCurrentNotificationBar = null; } } function barPriority(barId) { var priority; switch (barId) { case "phishing" : priority = 9; break; case "spyware" : priority = 10; break; case "webmail" : priority = 1; break; case "rss" : priority = 2; break; case "popup" : priority = 3; break; case "datacard" : priority = 4; break; case "passcard" : priority = 5; break; case "xpi" : priority = 6; break; case "missing-plugin" : priority = 6; break; } return priority; } function showNBar(barId, extraData) { dump("browser.js: Showing bar : " + barId + "\n"); var browser = gBrowser.selectedBrowser; var tabbrowser = getBrowser(); var bundle_browser = document.getElementById("bundle_browser"); var brandBundle = document.getElementById("bundle_brand"); var brandShortName = brandBundle.getString("brandShortName"); var imgIcon = "chrome://browser/skin/Info.png"; var message = ""; var buttonString = ""; var deckIdx = 0; var aSource; var aPopup; var aDocShell; switch (barId) { case "phishing" : // don't show bar if pref is not set if (!gPrefService.getBoolPref("trustsettings.showwarnings")) return; var siteURL = extraData[0]; var matchingPartners = blacklistUtils.lastSitePartners.join(", "); message = bundle_browser.getFormattedString("phishingNotification", [siteURL.host, matchingPartners]); deckIdx = 3; break; case "spyware" : // don't show bar if pref is not set if (!gPrefService.getBoolPref("trustsettings.showwarnings")) return; var siteURL = extraData[0]; var matchingPartners = blacklistUtils.lastSitePartners.join(", "); message = bundle_browser.getFormattedString("spywareNotification", [siteURL.host, matchingPartners]); deckIdx = 4; break; case "webmail" : deckIdx = 5; imgIcon = extraData[0]; message = extraData[1]; break; case "rss" : deckIdx = 0; message = bundle_browser.getFormattedString("rssWarning", [brandShortName]); aPopup = "blockedRSSOptions"; imgIcon = "chrome://browser/skin/page-livemarks.png"; break; case "popup" : deckIdx = 6; //var popupCount = gBrowser.selectedBrowser.pageReport.length; //if (popupCount > 1) // message = bundle_browser.getFormattedString("popupWarningMultiple", [brandShortName, popupCount]); //else message = bundle_browser.getFormattedString("popupWarning", [brandShortName]); break; case "datacard" : deckIdx = 2; break; case "passcard" : deckIdx = 1; message = bundle_browser.getString("passcardMsg"); imgIcon = "chrome://browser/skin/icons/passwordsm_h.png"; break; case "xpi" : deckIdx = 0; imgIcon = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png"; var messageKey = "xpinstallWarning"; var buttonKey = "xpinstallWarningButton"; var shell = extraData[0]; var host = browser.docShell.QueryInterface(Components.interfaces.nsIWebNavigation).currentURI.host; aSource = "xpinstall-install-edit-permissions"; if (!gPrefService.getBoolPref("xpinstall.enabled")) { message = bundle_browser.getFormattedString("xpinstallDisabledWarning", [brandShortName, host]); buttonString = bundle_browser.getString("xpinstallDisabledWarningButton"); } else { message = bundle_browser.getFormattedString(messageKey, [brandShortName, host]); buttonString = bundle_browser.getString(buttonKey); } aDocShell = shell; break; case "missing-plugin" : browser = extraData[0]; imgIcon = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png"; message = bundle_browser.getString("missingpluginsMessage.title"); buttonString = bundle_browser.getString("missingpluginsMessage.button.label"); aSource = "missing-plugin"; break; } gBrowser.hideMessage(browser, "both"); dump('Bar will show message : ' + message + '\n'); gBrowser.showMessage(browser, imgIcon, message, buttonString, aDocShell, aSource, aPopup, "top", true, deckIdx); gCurrentNotificationBar = barId; } // MERC - JCH function openFormfillPrefs() { gPrefService.setCharPref('browser.preferences.formfillORpasscard', 'formfilltab'); openPrefs(5); } // MERC - JCH: This is called from nsHTMLPluginDocument.cpp. function IsTridentFillable() { if (blacklistUtils.IsSiteInPhishList(gBrowser.currentURI)) { displayNotificationBar("phishing",[gBrowser.currentURI]); // ShowPhishingSiteWarning(); } else if (blacklistUtils.IsSiteInSpywareList(gBrowser.currentURI)) { displayNotificationBar("spyware",[gBrowser.currentURI]); } datacardUtils.DoPageLoadedCheck(); } // MERC (DP): simply calls toggleDisplayEngineSiteControl() for the current tab. // called from nsHTMLPluginDocument::ToggleEngine() function BrowserToggleDisplayEngineSiteControl() { //dump("Browser Engine Toggle : \n\n"); //showStack(); gBrowser.mCurrentTab.toggleDisplayEngineSiteControl(); } function BrowserClosedByCloseButton() { var webBrowserPrint = PrintUtils.getWebBrowserPrint(); if (webBrowserPrint.doingPrintPreview) { // setTimeout(FinallyClose, 10); PrintUtils.exitPrintPreview(); } else { FinallyClose(); } } function FinallyClose() { if (WindowIsClosing()) window.close(); } //Merc , SLiu function ShowPrintErrorDialogForTrident(errorId) { const bundleURL = "chrome://global/locale/printing.properties"; const sbsContractID = "@mozilla.org/intl/stringbundle;1"; const sbsIID = Components.interfaces.nsIStringBundleService; const sbs = Components.classes[sbsContractID].getService(sbsIID); const lsContractID = "@mozilla.org/intl/nslocaleservice;1"; const lsIID = Components.interfaces.nsILocaleService; const ls = Components.classes[lsContractID].getService(lsIID); var appLocale = ls.getApplicationLocale(); var strBundle = sbs.createBundle(bundleURL, appLocale); var titleStr=null; var msg=null; if(errorId==PRINT_PREVIEW_REQ_WHILE_TRIDENT_LOADING_ERROR) { titleStr=strBundle.GetStringFromName("printpreview_error_dialog_title"); msg=strBundle.GetStringFromName("NS_ERROR_GFX_PRINTER_DOC_IS_BUSY_PP"); } else if(errorId==PRINT_REQ_WHILE_TRIDENT_LOADING_ERROR) { titleStr=strBundle.GetStringFromName("print_req_error_dialog_title"); msg=strBundle.GetStringFromName("NS_ERROR_GFX_PRINTER_DOC_IS_BUSY"); } if(titleStr && msg) { var promptSvc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService); promptSvc.alert(null,titleStr, msg); } } /////////////// livemark handling // MERC - JCH: Receives RSS data from Trident. Called from nsHTMLPluginDocument.cpp. function OnTridentLinkFound(href, rel, title, type, doc) { var link = document.createElementNS(XHTML_NS, "link"); link.setAttribute("href", href); link.setAttribute("title", title); link.setAttribute("type", type); link.setAttribute("rel", rel); var event = new Object(); event.target = link; event.isTrusted = true; livemarkOnLinkAdded(event, doc); } // XXX this event listener can/should probably be combined with the onLinkAdded // listener in tabbrowser.xml, which only listens for favicons and then passes // them to onLinkIconAvailable in the ProgressListener. We could extend the // progress listener to have a generic onLinkAvailable and have tabbrowser pass // along all events. It should give us the browser for the tab, as well as // the actual event. // MERC - JCH: Added the extra 'doc' argument to allow Trident RSS feed data // to display properly. function livemarkOnLinkAdded(event, doc) { dump("~~~~~~ BROWSER.JS livemarkOnLinkAdded() ~~~~~~~~\n"); // dump ("Think doc is " + doc); if (!event.isTrusted) return; if (!gLivemarksButton) gLivemarksButton = document.getElementById("livemark-button"); // from tabbrowser.xml // mechanism for reading properties of the underlying XPCOM object // (ignoring potential getters/setters added by malicious content) var safeGetProperty = function(obj, propname) { return Components.lookupMethod(obj, propname).call(obj); } var erel = event.target.rel; var etype = event.target.type; var etitle = event.target.title; // this is a blogger post service URL; so skip it if (erel && erel == "service.post") return; if (etype == "application/rss+xml" || etype == "application/atom+xml" || etype == "application/x.atom+xml" || etitle.indexOf("RSS") != -1 || etitle.indexOf("Atom") != -1 || etitle.indexOf("rss") != -1) { // const targetDoc; var targetDoc; if (doc != null) { targetDoc = doc; } else { targetDoc = safeGetProperty(event.target, "ownerDocument"); } // find which tab this is for, and set the attribute on the browser // should there be a getTabForDocument method on tabbedbrowser? var browserForLink = null; if (gBrowser.mTabbedMode) { var browserIndex = gBrowser.getBrowserIndexForDocument(targetDoc); if (browserIndex == -1) { dump ("Uhoh - couldn't get browserindex for targetdoc"); return; } browserForLink = gBrowser.getBrowserAtIndex(browserIndex); } else if (gBrowser.mCurrentBrowser.contentDocument == targetDoc) { browserForLink = gBrowser.mCurrentBrowser; } if (!browserForLink) { // ??? this really shouldn't happen.. dump("Uhoh - couldn't find browserForLink"); return; } var livemarkLinks = []; if (browserForLink.livemarkLinks != null) livemarkLinks = browserForLink.livemarkLinks; var wrapper = new XPCNativeWrapper(event.target, "href", "type", "title"); livemarkLinks.push({ href: wrapper.href, type: wrapper.type, title: wrapper.title}); browserForLink.livemarkLinks = livemarkLinks; if ((browserForLink == gBrowser || browserForLink == gBrowser.mCurrentBrowser) && gLivemarksButton) gLivemarksButton.setAttribute("livemarks", "true"); } } // this is called both from onload and also whenever the user // switches tabs; we update whether we show or hide the livemark // button based on whether the window has livemarks set. function updatePageLivemarks() { // dump("~~~~~~ BROWSER.JS updatePageLivemarks() ~~~~~~~~\n"); if (!gLivemarksButton) gLivemarksButton = document.getElementById("livemark-button"); if (!gLivemarksButton) return; var livemarkLinks = gBrowser.mCurrentBrowser.livemarkLinks; if (!livemarkLinks || livemarkLinks.length == 0) { gLivemarksButton.removeAttribute("livemarks"); gLivemarksButton.setAttribute("tooltiptext", gNavigatorBundle.getString("livemarkNoLivemarksTooltip")); } else { gLivemarksButton.setAttribute("livemarks", "true"); gLivemarksButton.setAttribute("tooltiptext", gNavigatorBundle.getString("livemarkHasLivemarksTooltip")); } } // MERC - JCH: Called from nsHTMLPluginDocument.cpp to remove livemarks button function wrappedUpdatePageLivemarks() { // Clear livemark data gBrowser.mCurrentBrowser.livemarkLinks = null; updatePageLivemarks(); } function livemarkFillPopup(menuPopup) { dump("~~~~~~ BROWSER.JS livemarkFillPopup() ~~~~~~~~\n"); var livemarkLinks = gBrowser.mCurrentBrowser.livemarkLinks; if (livemarkLinks == null) { // XXX hack -- menu opening depends on setting of an "open" // attribute, and the menu refuses to open if that attribute is // set (because it thinks it's already open). onpopupshowing gets // called after the attribute is unset, and it doesn't get unset // if we return false. so we unset it here; otherwise, the menu // refuses to work past this point. menuPopup.parentNode.removeAttribute("open"); return false; } while (menuPopup.firstChild) { menuPopup.removeChild(menuPopup.firstChild); } for (var i = 0; i < livemarkLinks.length; i++) { var markinfo = livemarkLinks[i]; var menuItem = document.createElement("menuitem"); var baseTitle = markinfo.title || markinfo.href; var labelStr = gNavigatorBundle.getFormattedString("livemarkSubscribeTo", [baseTitle]); menuItem.setAttribute("label", labelStr); menuItem.setAttribute("data", markinfo.href); menuItem.setAttribute("tooltiptext", markinfo.href); menuPopup.appendChild(menuItem); } return true; } function livemarkAddMark(wincontent, data, altRef) { dump("~~~~~~ BROWSER.JS livemarkAddMark() ~~~~~~~~\n"); var title = wincontent.document.title; // BookmarksUtils.addLivemark(wincontent.document.baseURI, data, title); var refURI; if (altRef) { try { var channels = gBrowser.contentDocument.getElementsByTagName('channel'); refURI = channels[0].getAttribute('rdf:about'); } catch (ex) {} } if (!refURI) { refURI = wincontent.document.baseURI; } spui.addLivemark(refURI, data, title); reshuffleToolbars(true); } function updatePageFavIcon(aBrowser, aListener) { var uri = aBrowser.currentURI; if (!gBrowser.shouldLoadFavIcon(uri)) return; // if we made it here with this null, then no <link> was found for // the page load. We try to fetch a generic favicon.ico. if (aBrowser.mFavIconURL == null) { aBrowser.mFavIconURL = gBrowser.buildFavIconString(uri); // dump( ")) WMWMWMWMWMW===> updatePageFavIcon built default path: \""+aBrowser.mFavIconURL+"\"\n" ); // give it to the listener as well // XXX - there is no listener for non-tabbed-mode: this is why // the urlbar has no favicon when you switch from tabbed mode to // non-tabbed-mode. if (aListener) aListener.mIcon = aBrowser.mFavIconURL; } // dump( ")) WMWMWMWMWMW===> updatePageFavIcon resulted in: \""+aBrowser.mFavIconURL+"\"\n" ); if (aBrowser == gBrowser.mCurrentBrowser) PageProxySetIcon(aBrowser.mFavIconURL); if (aBrowser.mFavIconURL != null) BookmarksUtils.loadFavIcon(uri.spec, aBrowser.mFavIconURL); } function getUILink(item) { var regionBundle = document.getElementById("bundle_browser_region"); if (item == "tellAFriend") return regionBundle.getString("tellAFriendURL"); if (item == "promote") return regionBundle.getString("promoteURL"); return ""; } function isBidiEnabled(){ var rv = false; var systemLocale; try { var localService = Components.classes["@mozilla.org/intl/nslocaleservice;1"] .getService(Components.interfaces.nsILocaleService); systemLocale = localService.getSystemLocale().getCategory("NSILOCALE_CTYPE").substr(0,3); } catch (e){} rv = ( (systemLocale == "he-") || (systemLocale == "ar-") || (systemLocale == "syr") || (systemLocale == "fa-") || (systemLocale == "ur-") ); if (!rv) { // check the overriding pref var mPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch); try { rv = mPrefs.getBoolPref("bidi.browser.ui"); } catch (e){} } return rv; } function GetFrameDocumentsFromWindow(aWindow){ if (aWindow.getComputedStyle(aWindow.document.body, "").direction == "ltr") aWindow.document.dir = "rtl"; else aWindow.document.dir = "ltr"; for (var run = 0; run < aWindow.frames.length; run++) GetFrameDocumentsFromWindow(aWindow.frames[run]); } function SwitchDocumentDirection(){ GetFrameDocumentsFromWindow(window.content); } function SwitchFocusedTextEntryDirection() { if (isBidiEnabled()) { var focusedElement = document.commandDispatcher.focusedElement; if (focusedElement) if (window.getComputedStyle(focusedElement, "").direction == "ltr") focusedElement.style.direction = "rtl"; else focusedElement.style.direction = "ltr"; } } function missingPluginInstaller(){ this.missingPlugins = new Object(); } missingPluginInstaller.prototype.installSinglePlugin = function(aEvent){ // Check if the event is trust-worthy. if (!aEvent.isTrusted) { return; } var tabbrowser = getBrowser(); var missingPluginsArray = new Object; var tagMimetype; var pluginsPage; if (aEvent.target instanceof HTMLAppletElement) { tagMimetype = "application/x-java-vm"; } else if (aEvent.target instanceof HTMLObjectElement) { tagMimetype = aEvent.target.type; pluginsPage = aEvent.target.getAttribute("codebase"); } else { tagMimetype = aEvent.target.type; pluginsPage = aEvent.target.getAttribute("pluginspage"); } missingPluginsArray[tagMimetype] = {mimetype: tagMimetype, pluginsPage: pluginsPage}; if (missingPluginsArray) { window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul", "PFSWindow", "modal,chrome,resizable=yes", {plugins: missingPluginsArray, tab: tabbrowser.mCurrentTab}); } aEvent.preventDefault(); } missingPluginInstaller.prototype.newMissingPlugin = function(aEvent){ // Check if the event is trust-worthy. if (!aEvent.isTrusted) { return; } // For broken non-object plugin tags, register a click handler so // that the user can click the plugin replacement to get the new // plugin. Object tags can, and often do, deal with that themselves, // so don't stomp on the page developers toes. if (!(aEvent.target instanceof HTMLObjectElement)) { aEvent.target.addEventListener("click", gMissingPluginInstaller.installSinglePlugin, false); } var tabbrowser = getBrowser(); const browsers = tabbrowser.mPanelContainer.childNodes; var window = aEvent.target.ownerDocument.__parent__; // walk up till the toplevel window while (window.parent != window) window = window.parent; var i = 0; for (; i < browsers.length; i++) { if (tabbrowser.getBrowserAtIndex(i).contentWindow == window) break; } var tab = tabbrowser.mTabContainer.childNodes[i]; if (!gMissingPluginInstaller.missingPlugins) gMissingPluginInstaller.missingPlugins = new Object(); if (!gMissingPluginInstaller.missingPlugins[tab]) gMissingPluginInstaller.missingPlugins[tab] = new Object(); var tagMimetype; var pluginsPage; if (aEvent.target instanceof HTMLAppletElement) { tagMimetype = "application/x-java-vm"; } else if (aEvent.target instanceof HTMLObjectElement) { tagMimetype = aEvent.target.type; pluginsPage = aEvent.target.getAttribute("codebase"); } else { tagMimetype = aEvent.target.type; pluginsPage = aEvent.target.getAttribute("pluginspage"); } gMissingPluginInstaller.missingPlugins[tab][tagMimetype] = { mimetype: tagMimetype, pluginsPage: pluginsPage }; displayNotificationBar("missing-plugin", [tabbrowser.getBrowserAtIndex(i)]); } missingPluginInstaller.prototype.clearMissingPlugins = function(aTab){ this.missingPlugins[aTab] = null; } missingPluginInstaller.prototype.observe = function(aSubject, aTopic, aData){ switch (aTopic) { case "missing-plugin": // get the urls of missing plugins var tabbrowser = getBrowser(); var missingPluginsArray = gMissingPluginInstaller.missingPlugins[tabbrowser.mCurrentTab]; if (missingPluginsArray) { window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul", "PFSWindow", "modal,chrome,resizable=yes", {plugins: missingPluginsArray, tab: tabbrowser.mCurrentTab}); } hideNotificationBar(tabbrowser, "xpi"); // tabbrowser.hideMessage(tabbrowser.selectedBrowser, "top"); break; } } var gMissingPluginInstaller = new missingPluginInstaller(); function AboutTabBrowsing() { var aboutPage = gPrefService.getCharPref("browser.tabs.abouturl"); loadURI(aboutPage); } function AboutSiteControls() { var aboutPage = gPrefService.getCharPref("browser.sitecontrols.abouturl"); loadURI(aboutPage); } function submitFormdata(fNew,fAction,fMeathod,elementList) { // fNew is boolean: true means open in a new tab, false means open in this tab // fAction is the URL for the post // fMeathod is "post" or "get" // elementList must be an Array() of element-value pairs // where elementList[n].value is put into elementList[n].name input // NOTE: if elementList[n].type is defined it will be set as well // i.e. for passwords //initially, it puts the form onto an existing tab try { if (fNew) { BrowserOpenTab(); } var myDoc=document.getElementById("content").selectedBrowser.contentDocument; var retval=document.getElementById("content").selectedBrowser; var body=myDoc.getElementsByTagName("body")[0]; var myForm=myDoc.createElement("form"); myForm.name="readyForMe"; var newInput; if (!elementList || elementList.length < 1) { dump("submitFormdata not doing much: no elements\n"); } else { for (var i = 0;i<elementList.length;i++) { newInput=myDoc.createElement("input"); newInput.name=elementList[i].name; newInput.value=elementList[i].value; if (elementList[i].type) { newInput.type=elementList[i].type; } myForm.appendChild(newInput); dump("Added input name="+elementList[i].name+"\n"); } } myForm.action=fAction; myForm.method=fMeathod; myForm.target="_self"; body.appendChild(myForm); dump("submitting form\n"); myForm.submit(); dump("done submitPost()\n"); } catch (ex) { dump("Exception in browser.js: submitFormdata\n"); dump(ex); } } function webmailHandleURI(urlStr,extra) { webmail.debug("webmailHandleURI();"); webmail.handleURI(urlStr); } function SetTridentCookies(cookieStr) { // dump ("Setting Trident Cookies with " + cookieStr + "\n\n"); return true; } function OpenSecurityCenter() { // MERC (rpaul) quick function to open security center tab of site control preferences var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch); if (prefs) prefs.setCharPref("browser.sitecontrols.prefs", "prefsTab"); openPrefs(3); }