home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / firefox-3.0.14 / chrome / browser.jar / content / browser / browser.js < prev    next >
Encoding:
Text File  |  2009-09-07  |  267.7 KB  |  7,708 lines

  1. //@line 60 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2.  
  3. let Ci = Components.interfaces;
  4. let Cu = Components.utils;
  5. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  6.  
  7. const nsIWebNavigation = Components.interfaces.nsIWebNavigation;
  8.  
  9. const MAX_HISTORY_MENU_ITEMS = 15;
  10.  
  11. // We use this once, for Clear Private Data
  12. const GLUE_CID = "@mozilla.org/browser/browserglue;1";
  13.  
  14. var gURIFixup = null;
  15. var gCharsetMenu = null;
  16. var gLastBrowserCharset = null;
  17. var gPrevCharset = null;
  18. var gURLBar = null;
  19. var gFindBar = null;
  20. var gProxyFavIcon = null;
  21. var gNavigatorBundle = null;
  22. var gIsLoadingBlank = false;
  23. var gLastValidURLStr = "";
  24. var gMustLoadSidebar = false;
  25. var gProgressMeterPanel = null;
  26. var gProgressCollapseTimer = null;
  27. var gPrefService = null;
  28. var appCore = null;
  29. var gBrowser = null;
  30. var gNavToolbox = null;
  31. var gSidebarCommand = "";
  32. var gInPrintPreviewMode = false;
  33. let gDownloadMgr = null;
  34.  
  35. // Global variable that holds the nsContextMenu instance.
  36. var gContextMenu = null;
  37.  
  38. var gChromeState = null; // chrome state before we went into print preview
  39.  
  40. var gSanitizeListener = null;
  41.  
  42. var gAutoHideTabbarPrefListener = null;
  43. var gBookmarkAllTabsHandler = null;
  44.  
  45. //@line 106 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  46.  
  47. //@line 108 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  48. var gEditUIVisible = true;
  49. //@line 110 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  50.  
  51. /**
  52. * We can avoid adding multiple load event listeners and save some time by adding
  53. * one listener that calls all real handlers.
  54. */
  55.  
  56. function pageShowEventHandlers(event)
  57. {
  58.   // Filter out events that are not about the document load we are interested in
  59.   if (event.originalTarget == content.document) {
  60.     checkForDirectoryListing();
  61.     charsetLoadListener(event);
  62.     
  63.     XULBrowserWindow.asyncUpdateUI();
  64.   }
  65. }
  66.  
  67. /**
  68.  * Determine whether or not the content area is displaying a page with frames,
  69.  * and if so, toggle the display of the 'save frame as' menu item.
  70.  **/
  71. function getContentAreaFrameCount()
  72. {
  73.   var saveFrameItem = document.getElementById("menu_saveFrame");
  74.   if (!content || !content.frames.length || !isContentFrame(document.commandDispatcher.focusedWindow))
  75.     saveFrameItem.setAttribute("hidden", "true");
  76.   else
  77.     saveFrameItem.removeAttribute("hidden");
  78. }
  79.  
  80. function UpdateBackForwardCommands(aWebNavigation)
  81. {
  82.   var backBroadcaster = document.getElementById("Browser:Back");
  83.   var forwardBroadcaster = document.getElementById("Browser:Forward");
  84.  
  85.   // Avoid setting attributes on broadcasters if the value hasn't changed!
  86.   // Remember, guys, setting attributes on elements is expensive!  They
  87.   // get inherited into anonymous content, broadcast to other widgets, etc.!
  88.   // Don't do it if the value hasn't changed! - dwh
  89.  
  90.   var backDisabled = backBroadcaster.hasAttribute("disabled");
  91.   var forwardDisabled = forwardBroadcaster.hasAttribute("disabled");
  92.   if (backDisabled == aWebNavigation.canGoBack) {
  93.     if (backDisabled)
  94.       backBroadcaster.removeAttribute("disabled");
  95.     else
  96.       backBroadcaster.setAttribute("disabled", true);
  97.   }
  98.  
  99.   if (forwardDisabled == aWebNavigation.canGoForward) {
  100.     if (forwardDisabled)
  101.       forwardBroadcaster.removeAttribute("disabled");
  102.     else
  103.       forwardBroadcaster.setAttribute("disabled", true);
  104.   }
  105. }
  106.  
  107. //@line 253 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  108.  
  109. function BookmarkThisTab()
  110. {
  111.   var tab = getBrowser().mContextTab;
  112.   if (tab.localName != "tab")
  113.     tab = getBrowser().mCurrentTab;
  114.  
  115.   PlacesCommandHook.bookmarkPage(tab.linkedBrowser,
  116.                                  PlacesUtils.bookmarksMenuFolderId, true);
  117. }
  118.  
  119. /**
  120.  * Initialize the bookmarks toolbar and the menuitem for it.
  121.  */
  122. function initBookmarksToolbar() {
  123.   var place = PlacesUtils.getQueryStringForFolder(PlacesUtils.bookmarks.toolbarFolder);
  124.   var bt = document.getElementById("bookmarksBarContent");
  125.   if (bt)
  126.     bt.place = place;
  127.  
  128.   document.getElementById("bookmarksToolbarFolderPopup").place = place;
  129.   document.getElementById("bookmarksToolbarFolderMenu").label =
  130.     PlacesUtils.bookmarks.getItemTitle(PlacesUtils.bookmarks.toolbarFolder);
  131. }
  132.  
  133. const gSessionHistoryObserver = {
  134.   observe: function(subject, topic, data)
  135.   {
  136.     if (topic != "browser:purge-session-history")
  137.       return;
  138.  
  139.     var backCommand = document.getElementById("Browser:Back");
  140.     backCommand.setAttribute("disabled", "true");
  141.     var fwdCommand = document.getElementById("Browser:Forward");
  142.     fwdCommand.setAttribute("disabled", "true");
  143.  
  144.     if (gURLBar) {
  145.       // Clear undo history of the URL bar
  146.       gURLBar.editor.transactionManager.clear()
  147.     }
  148.   }
  149. };
  150.  
  151. /**
  152.  * Given a starting docshell and a URI to look up, find the docshell the URI
  153.  * is loaded in. 
  154.  * @param   aDocument
  155.  *          A document to find instead of using just a URI - this is more specific. 
  156.  * @param   aDocShell
  157.  *          The doc shell to start at
  158.  * @param   aSoughtURI
  159.  *          The URI that we're looking for
  160.  * @returns The doc shell that the sought URI is loaded in. Can be in 
  161.  *          subframes.
  162.  */
  163. function findChildShell(aDocument, aDocShell, aSoughtURI) {
  164.   aDocShell.QueryInterface(Components.interfaces.nsIWebNavigation);
  165.   aDocShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  166.   var doc = aDocShell.getInterface(Components.interfaces.nsIDOMDocument);
  167.   if ((aDocument && doc == aDocument) || 
  168.       (aSoughtURI && aSoughtURI.spec == aDocShell.currentURI.spec))
  169.     return aDocShell;
  170.  
  171.   var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode);
  172.   for (var i = 0; i < node.childCount; ++i) {
  173.     var docShell = node.getChildAt(i);
  174.     docShell = findChildShell(aDocument, docShell, aSoughtURI);
  175.     if (docShell)
  176.       return docShell;
  177.   }
  178.   return null;
  179. }
  180.  
  181. const gPopupBlockerObserver = {
  182.   _reportButton: null,
  183.   _kIPM: Components.interfaces.nsIPermissionManager,
  184.  
  185.   onUpdatePageReport: function (aEvent)
  186.   {
  187.     if (aEvent.originalTarget != gBrowser.selectedBrowser)
  188.       return;
  189.  
  190.     if (!this._reportButton)
  191.       this._reportButton = document.getElementById("page-report-button");
  192.  
  193.     if (!gBrowser.pageReport) {
  194.       // Hide the popup blocker statusbar button
  195.       this._reportButton.removeAttribute("blocked");
  196.  
  197.       return;
  198.     }
  199.  
  200.     this._reportButton.setAttribute("blocked", true);
  201.  
  202.     // Only show the notification again if we've not already shown it. Since
  203.     // notifications are per-browser, we don't need to worry about re-adding
  204.     // it.
  205.     if (!gBrowser.pageReport.reported) {
  206.       if (!gPrefService)
  207.         gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
  208.                                  .getService(Components.interfaces.nsIPrefBranch2);
  209.       if (gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) {
  210.         var bundle_browser = document.getElementById("bundle_browser");
  211.         var brandBundle = document.getElementById("bundle_brand");
  212.         var brandShortName = brandBundle.getString("brandShortName");
  213.         var message;
  214.         var popupCount = gBrowser.pageReport.length;
  215. //@line 364 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  216.         var popupButtonText = bundle_browser.getString("popupWarningButtonUnix");
  217.         var popupButtonAccesskey = bundle_browser.getString("popupWarningButtonUnix.accesskey");
  218. //@line 367 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  219.         if (popupCount > 1)
  220.           message = bundle_browser.getFormattedString("popupWarningMultiple", [brandShortName, popupCount]);
  221.         else
  222.           message = bundle_browser.getFormattedString("popupWarning", [brandShortName]);
  223.  
  224.         var notificationBox = gBrowser.getNotificationBox();
  225.         var notification = notificationBox.getNotificationWithValue("popup-blocked");
  226.         if (notification) {
  227.           notification.label = message;
  228.         }
  229.         else {
  230.           var buttons = [{
  231.             label: popupButtonText,
  232.             accessKey: popupButtonAccesskey,
  233.             popup: "blockedPopupOptions",
  234.             callback: null
  235.           }];
  236.  
  237.           const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  238.           notificationBox.appendNotification(message, "popup-blocked",
  239.                                              "chrome://browser/skin/Info.png",
  240.                                              priority, buttons);
  241.         }
  242.       }
  243.  
  244.       // Record the fact that we've reported this blocked popup, so we don't
  245.       // show it again.
  246.       gBrowser.pageReport.reported = true;
  247.     }
  248.   },
  249.  
  250.   toggleAllowPopupsForSite: function (aEvent)
  251.   {
  252.     var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI;
  253.     var pm = Components.classes["@mozilla.org/permissionmanager;1"]
  254.                        .getService(this._kIPM);
  255.     var shouldBlock = aEvent.target.getAttribute("block") == "true";
  256.     var perm = shouldBlock ? this._kIPM.DENY_ACTION : this._kIPM.ALLOW_ACTION;
  257.     pm.add(currentURI, "popup", perm);
  258.  
  259.     gBrowser.getNotificationBox().removeCurrentNotification();
  260.   },
  261.  
  262.   fillPopupList: function (aEvent)
  263.   {
  264.     var bundle_browser = document.getElementById("bundle_browser");
  265.     // XXXben - rather than using |currentURI| here, which breaks down on multi-framed sites
  266.     //          we should really walk the pageReport and create a list of "allow for <host>"
  267.     //          menuitems for the common subset of hosts present in the report, this will
  268.     //          make us frame-safe.
  269.     //
  270.     // XXXjst - Note that when this is fixed to work with multi-framed sites,
  271.     //          also back out the fix for bug 343772 where
  272.     //          nsGlobalWindow::CheckOpenAllow() was changed to also
  273.     //          check if the top window's location is whitelisted.
  274.     var uri = gBrowser.selectedBrowser.webNavigation.currentURI;
  275.     var blockedPopupAllowSite = document.getElementById("blockedPopupAllowSite");
  276.     try {
  277.       blockedPopupAllowSite.removeAttribute("hidden");
  278.  
  279.       var pm = Components.classes["@mozilla.org/permissionmanager;1"]
  280.                         .getService(this._kIPM);
  281.       if (pm.testPermission(uri, "popup") == this._kIPM.ALLOW_ACTION) {
  282.         // Offer an item to block popups for this site, if a whitelist entry exists
  283.         // already for it.
  284.         var blockString = bundle_browser.getFormattedString("popupBlock", [uri.host]);
  285.         blockedPopupAllowSite.setAttribute("label", blockString);
  286.         blockedPopupAllowSite.setAttribute("block", "true");
  287.       }
  288.       else {
  289.         // Offer an item to allow popups for this site
  290.         var allowString = bundle_browser.getFormattedString("popupAllow", [uri.host]);
  291.         blockedPopupAllowSite.setAttribute("label", allowString);
  292.         blockedPopupAllowSite.removeAttribute("block");
  293.       }
  294.     }
  295.     catch (e) {
  296.       blockedPopupAllowSite.setAttribute("hidden", "true");
  297.     }
  298.  
  299.     var item = aEvent.target.lastChild;
  300.     while (item && item.getAttribute("observes") != "blockedPopupsSeparator") {
  301.       var next = item.previousSibling;
  302.       item.parentNode.removeChild(item);
  303.       item = next;
  304.     }
  305.  
  306.     var foundUsablePopupURI = false;
  307.     var pageReport = gBrowser.pageReport;
  308.     if (pageReport) {
  309.       for (var i = 0; i < pageReport.length; ++i) {
  310.         var popupURIspec = pageReport[i].popupWindowURI.spec;
  311.  
  312.         // Sometimes the popup URI that we get back from the pageReport
  313.         // isn't useful (for instance, netscape.com's popup URI ends up
  314.         // being "http://www.netscape.com", which isn't really the URI of
  315.         // the popup they're trying to show).  This isn't going to be
  316.         // useful to the user, so we won't create a menu item for it.
  317.         if (popupURIspec == "" || popupURIspec == "about:blank" ||
  318.             popupURIspec == uri.spec)
  319.           continue;
  320.  
  321.         // Because of the short-circuit above, we may end up in a situation
  322.         // in which we don't have any usable popup addresses to show in
  323.         // the menu, and therefore we shouldn't show the separator.  However,
  324.         // since we got past the short-circuit, we must've found at least
  325.         // one usable popup URI and thus we'll turn on the separator later.
  326.         foundUsablePopupURI = true;
  327.  
  328.         var menuitem = document.createElement("menuitem");
  329.         var label = bundle_browser.getFormattedString("popupShowPopupPrefix",
  330.                                                       [popupURIspec]);
  331.         menuitem.setAttribute("label", label);
  332.         menuitem.setAttribute("popupWindowURI", popupURIspec);
  333.         menuitem.setAttribute("popupWindowFeatures", pageReport[i].popupWindowFeatures);
  334.         menuitem.setAttribute("popupWindowName", pageReport[i].popupWindowName);
  335.         menuitem.setAttribute("oncommand", "gPopupBlockerObserver.showBlockedPopup(event);");
  336.         menuitem.requestingWindow = pageReport[i].requestingWindow;
  337.         menuitem.requestingDocument = pageReport[i].requestingDocument;
  338.         aEvent.target.appendChild(menuitem);
  339.       }
  340.     }
  341.  
  342.     // Show or hide the separator, depending on whether we added any
  343.     // showable popup addresses to the menu.
  344.     var blockedPopupsSeparator =
  345.       document.getElementById("blockedPopupsSeparator");
  346.     if (foundUsablePopupURI)
  347.       blockedPopupsSeparator.removeAttribute("hidden");
  348.     else
  349.       blockedPopupsSeparator.setAttribute("hidden", true);
  350.  
  351.     var blockedPopupDontShowMessage = document.getElementById("blockedPopupDontShowMessage");
  352.     var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
  353.     blockedPopupDontShowMessage.setAttribute("checked", !showMessage);
  354.     if (aEvent.target.localName == "popup")
  355.       blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromMessage"));
  356.     else
  357.       blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromStatusbar"));
  358.   },
  359.  
  360.   showBlockedPopup: function (aEvent)
  361.   {
  362.     var target = aEvent.target;
  363.     var popupWindowURI = target.getAttribute("popupWindowURI");
  364.     var features = target.getAttribute("popupWindowFeatures");
  365.     var name = target.getAttribute("popupWindowName");
  366.  
  367.     var dwi = target.requestingWindow;
  368.  
  369.     // If we have a requesting window and the requesting document is
  370.     // still the current document, open the popup.
  371.     if (dwi && dwi.document == target.requestingDocument) {
  372.       dwi.open(popupWindowURI, name, features);
  373.     }
  374.   },
  375.  
  376.   editPopupSettings: function ()
  377.   {
  378.     var host = "";
  379.     try {
  380.       var uri = gBrowser.selectedBrowser.webNavigation.currentURI;
  381.       host = uri.host;
  382.     }
  383.     catch (e) { }
  384.  
  385.     var bundlePreferences = document.getElementById("bundle_preferences");
  386.     var params = { blockVisible   : false,
  387.                    sessionVisible : false,
  388.                    allowVisible   : true,
  389.                    prefilledHost  : host,
  390.                    permissionType : "popup",
  391.                    windowTitle    : bundlePreferences.getString("popuppermissionstitle"),
  392.                    introText      : bundlePreferences.getString("popuppermissionstext") };
  393.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  394.                         .getService(Components.interfaces.nsIWindowMediator);
  395.     var existingWindow = wm.getMostRecentWindow("Browser:Permissions");
  396.     if (existingWindow) {
  397.       existingWindow.initWithParams(params);
  398.       existingWindow.focus();
  399.     }
  400.     else
  401.       window.openDialog("chrome://browser/content/preferences/permissions.xul",
  402.                         "_blank", "resizable,dialog=no,centerscreen", params);
  403.   },
  404.  
  405.   dontShowMessage: function ()
  406.   {
  407.     var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
  408.     var firstTime = gPrefService.getBoolPref("privacy.popups.firstTime");
  409.  
  410.     // If the info message is showing at the top of the window, and the user has never
  411.     // hidden the message before, show an info box telling the user where the info
  412.     // will be displayed.
  413.     if (showMessage && firstTime)
  414.       this._displayPageReportFirstTime();
  415.  
  416.     gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage);
  417.  
  418.     gBrowser.getNotificationBox().removeCurrentNotification();
  419.   },
  420.  
  421.   _displayPageReportFirstTime: function ()
  422.   {
  423.     window.openDialog("chrome://browser/content/pageReportFirstTime.xul", "_blank",
  424.                       "dependent");
  425.   }
  426. };
  427.  
  428. const gXPInstallObserver = {
  429.   _findChildShell: function (aDocShell, aSoughtShell)
  430.   {
  431.     if (aDocShell == aSoughtShell)
  432.       return aDocShell;
  433.  
  434.     var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode);
  435.     for (var i = 0; i < node.childCount; ++i) {
  436.       var docShell = node.getChildAt(i);
  437.       docShell = this._findChildShell(docShell, aSoughtShell);
  438.       if (docShell == aSoughtShell)
  439.         return docShell;
  440.     }
  441.     return null;
  442.   },
  443.  
  444.   _getBrowser: function (aDocShell)
  445.   {
  446.     var tabbrowser = getBrowser();
  447.     for (var i = 0; i < tabbrowser.browsers.length; ++i) {
  448.       var browser = tabbrowser.getBrowserAtIndex(i);
  449.       if (this._findChildShell(browser.docShell, aDocShell))
  450.         return browser;
  451.     }
  452.     return null;
  453.   },
  454.  
  455.   observe: function (aSubject, aTopic, aData)
  456.   {
  457.     var brandBundle = document.getElementById("bundle_brand");
  458.     var browserBundle = document.getElementById("bundle_browser");
  459.     switch (aTopic) {
  460.     case "xpinstall-install-blocked":
  461.       var installInfo = aSubject.QueryInterface(Components.interfaces.nsIXPIInstallInfo);
  462.       var win = installInfo.originatingWindow;
  463.       var shell = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  464.                      .getInterface(Components.interfaces.nsIWebNavigation)
  465.                      .QueryInterface(Components.interfaces.nsIDocShell);
  466.       var browser = this._getBrowser(shell);
  467.       if (browser) {
  468.         var host = installInfo.originatingURI.host;
  469.         var brandShortName = brandBundle.getString("brandShortName");
  470.         var notificationName, messageString, buttons;
  471.         if (!gPrefService.getBoolPref("xpinstall.enabled")) {
  472.           notificationName = "xpinstall-disabled"
  473.           if (gPrefService.prefIsLocked("xpinstall.enabled")) {
  474.             messageString = browserBundle.getString("xpinstallDisabledMessageLocked");
  475.             buttons = [];
  476.           }
  477.           else {
  478.             messageString = browserBundle.getFormattedString("xpinstallDisabledMessage",
  479.                                                              [brandShortName, host]);
  480.  
  481.             buttons = [{
  482.               label: browserBundle.getString("xpinstallDisabledButton"),
  483.               accessKey: browserBundle.getString("xpinstallDisabledButton.accesskey"),
  484.               popup: null,
  485.               callback: function editPrefs() {
  486.                 gPrefService.setBoolPref("xpinstall.enabled", true);
  487.                 return false;
  488.               }
  489.             }];
  490.           }
  491.         }
  492.         else {
  493.           notificationName = "xpinstall"
  494.           messageString = browserBundle.getFormattedString("xpinstallPromptWarning",
  495.                                                            [brandShortName, host]);
  496.  
  497.           buttons = [{
  498.             label: browserBundle.getString("xpinstallPromptAllowButton"),
  499.             accessKey: browserBundle.getString("xpinstallPromptAllowButton.accesskey"),
  500.             popup: null,
  501.             callback: function() {
  502.               var mgr = Components.classes["@mozilla.org/xpinstall/install-manager;1"]
  503.                                   .createInstance(Components.interfaces.nsIXPInstallManager);
  504.               mgr.initManagerWithInstallInfo(installInfo);
  505.               return false;
  506.             }
  507.           }];
  508.         }
  509.  
  510.         var notificationBox = gBrowser.getNotificationBox(browser);
  511.         if (!notificationBox.getNotificationWithValue(notificationName)) {
  512.           const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  513.           const iconURL = "chrome://mozapps/skin/update/update.png";
  514.           notificationBox.appendNotification(messageString, notificationName,
  515.                                              iconURL, priority, buttons);
  516.         }
  517.       }
  518.       break;
  519.     }
  520.   }
  521. };
  522.  
  523. function BrowserStartup()
  524. {
  525.   gBrowser = document.getElementById("content");
  526.  
  527.   var uriToLoad = null;
  528.  
  529.   // window.arguments[0]: URI to load (string), or an nsISupportsArray of
  530.   //                      nsISupportsStrings to load
  531.   //                 [1]: character set (string)
  532.   //                 [2]: referrer (nsIURI)
  533.   //                 [3]: postData (nsIInputStream)
  534.   //                 [4]: allowThirdPartyFixup (bool)
  535.   if ("arguments" in window && window.arguments[0])
  536.     uriToLoad = window.arguments[0];
  537.  
  538.   gIsLoadingBlank = uriToLoad == "about:blank";
  539.  
  540.   prepareForStartup();
  541.  
  542. //@line 694 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  543.   if (uriToLoad && !gIsLoadingBlank) {
  544.     if (uriToLoad instanceof Components.interfaces.nsISupportsArray) {
  545.       var count = uriToLoad.Count();
  546.       var specs = [];
  547.       for (var i = 0; i < count; i++) {
  548.         var urisstring = uriToLoad.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString);
  549.         specs.push(urisstring.data);
  550.       }
  551.  
  552.       // This function throws for certain malformed URIs, so use exception handling
  553.       // so that we don't disrupt startup
  554.       try {
  555.         gBrowser.loadTabs(specs, false, true);
  556.       } catch (e) {}
  557.     }
  558.     else if (window.arguments.length >= 3) {
  559.       loadURI(uriToLoad, window.arguments[2], window.arguments[3] || null,
  560.               window.arguments[4] || false);
  561.       content.focus();
  562.     }
  563.     // Note: loadOneOrMoreURIs *must not* be called if window.arguments.length >= 3.
  564.     // Such callers expect that window.arguments[0] is handled as a single URI.
  565.     else
  566.       loadOneOrMoreURIs(uriToLoad);
  567.   }
  568. //@line 720 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  569.  
  570.   var sidebarSplitter;
  571.   if (window.opener && !window.opener.closed) {
  572.     var openerFindBar = window.opener.gFindBar;
  573.     if (openerFindBar && !openerFindBar.hidden &&
  574.         openerFindBar.findMode == gFindBar.FIND_NORMAL)
  575.       gFindBar.open();
  576.  
  577.     var openerSidebarBox = window.opener.document.getElementById("sidebar-box");
  578.     // If the opener had a sidebar, open the same sidebar in our window.
  579.     // The opener can be the hidden window too, if we're coming from the state
  580.     // where no windows are open, and the hidden window has no sidebar box.
  581.     if (openerSidebarBox && !openerSidebarBox.hidden) {
  582.       var sidebarBox = document.getElementById("sidebar-box");
  583.       var sidebarTitle = document.getElementById("sidebar-title");
  584.       sidebarTitle.setAttribute("value", window.opener.document.getElementById("sidebar-title").getAttribute("value"));
  585.       sidebarBox.setAttribute("width", openerSidebarBox.boxObject.width);
  586.       var sidebarCmd = openerSidebarBox.getAttribute("sidebarcommand");
  587.       sidebarBox.setAttribute("sidebarcommand", sidebarCmd);
  588.       // Note: we're setting 'src' on sidebarBox, which is a <vbox>, not on the
  589.       // <browser id="sidebar">. This lets us delay the actual load until
  590.       // delayedStartup().
  591.       sidebarBox.setAttribute("src", window.opener.document.getElementById("sidebar").getAttribute("src"));
  592.       gMustLoadSidebar = true;
  593.  
  594.       sidebarBox.hidden = false;
  595.       sidebarSplitter = document.getElementById("sidebar-splitter");
  596.       sidebarSplitter.hidden = false;
  597.       document.getElementById(sidebarCmd).setAttribute("checked", "true");
  598.     }
  599.   }
  600.   else {
  601.     var box = document.getElementById("sidebar-box");
  602.     if (box.hasAttribute("sidebarcommand")) {
  603.       var commandID = box.getAttribute("sidebarcommand");
  604.       if (commandID) {
  605.         var command = document.getElementById(commandID);
  606.         if (command) {
  607.           gMustLoadSidebar = true;
  608.           box.hidden = false;
  609.           sidebarSplitter = document.getElementById("sidebar-splitter");
  610.           sidebarSplitter.hidden = false;
  611.           command.setAttribute("checked", "true");
  612.         }
  613.         else {
  614.           // Remove the |sidebarcommand| attribute, because the element it 
  615.           // refers to no longer exists, so we should assume this sidebar
  616.           // panel has been uninstalled. (249883)
  617.           box.removeAttribute("sidebarcommand");
  618.         }
  619.       }
  620.     }
  621.   }
  622.  
  623.   // Certain kinds of automigration rely on this notification to complete their
  624.   // tasks BEFORE the browser window is shown.
  625.   var obs = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  626.   obs.notifyObservers(null, "browser-window-before-show", "");
  627.  
  628.   // Set a sane starting width/height for all resolutions on new profiles.
  629.   if (!document.documentElement.hasAttribute("width")) {
  630.     var defaultWidth = 994, defaultHeight;
  631.     if (screen.availHeight <= 600) {
  632.       document.documentElement.setAttribute("sizemode", "maximized");
  633.       defaultWidth = 610;
  634.       defaultHeight = 450;
  635.     }
  636.     else {
  637.       // Create a narrower window for large or wide-aspect displays, to suggest
  638.       // side-by-side page view.
  639.       if (screen.availWidth >= 1600)
  640.         defaultWidth = (screen.availWidth / 2) - 20;
  641.       defaultHeight = screen.availHeight - 10;
  642. //@line 794 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  643.       // On X, we're not currently able to account for the size of the window
  644.       // border.  Use 28px as a guess (titlebar + bottom window border)
  645.       defaultHeight -= 28;
  646. //@line 798 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  647.     }
  648.     document.documentElement.setAttribute("width", defaultWidth);
  649.     document.documentElement.setAttribute("height", defaultHeight);
  650.   }
  651.  
  652.   if (gURLBar && document.documentElement.getAttribute("chromehidden").indexOf("toolbar") != -1) {
  653.  
  654.     gURLBar.setAttribute("readonly", "true");
  655.     gURLBar.setAttribute("enablehistory", "false");
  656.   }
  657.  
  658.   setTimeout(delayedStartup, 0);
  659. }
  660.  
  661. function HandleAppCommandEvent(evt)
  662. {
  663.   evt.stopPropagation();
  664.   switch (evt.command) {
  665.   case "Back":
  666.     BrowserBack();
  667.     break;
  668.   case "Forward":
  669.     BrowserForward();
  670.     break;
  671.   case "Reload":
  672.     BrowserReloadSkipCache();
  673.     break;
  674.   case "Stop":
  675.     BrowserStop();
  676.     break;
  677.   case "Search":
  678.     BrowserSearch.webSearch();
  679.     break;
  680.   case "Bookmarks":
  681.     toggleSidebar('viewBookmarksSidebar');
  682.     break;
  683.   case "Home":
  684.     BrowserHome();
  685.     break;
  686.   default:
  687.     break;
  688.   }
  689. }
  690.  
  691. function prepareForStartup()
  692. {
  693.   gURLBar = document.getElementById("urlbar");
  694.   gNavigatorBundle = document.getElementById("bundle_browser");
  695.   gProgressMeterPanel = document.getElementById("statusbar-progresspanel");
  696.   gFindBar = document.getElementById("FindToolbar");
  697.   gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver.onUpdatePageReport, false);
  698.   // Note: we need to listen to untrusted events, because the pluginfinder XBL
  699.   // binding can't fire trusted ones (runs with page privileges).
  700.   gBrowser.addEventListener("PluginNotFound", gMissingPluginInstaller.newMissingPlugin, true, true);
  701.   gBrowser.addEventListener("PluginBlocklisted", gMissingPluginInstaller.newMissingPlugin, true, true);
  702.   gBrowser.addEventListener("NewPluginInstalled", gMissingPluginInstaller.refreshBrowserAndPlugins, false);
  703.   gBrowser.addEventListener("NewTab", BrowserOpenTab, false);
  704.   window.addEventListener("AppCommand", HandleAppCommandEvent, true);
  705.  
  706.   var webNavigation;
  707.   try {
  708.     // Create the browser instance component.
  709.     appCore = Components.classes["@mozilla.org/appshell/component/browser/instance;1"]
  710.                         .createInstance(Components.interfaces.nsIBrowserInstance);
  711.     if (!appCore)
  712.       throw "couldn't create a browser instance";
  713.  
  714.     webNavigation = getWebNavigation();
  715.     if (!webNavigation)
  716.       throw "no XBL binding for browser";
  717.   } catch (e) {
  718.     alert("Error launching browser window:" + e);
  719.     window.close(); // Give up.
  720.     return;
  721.   }
  722.  
  723.   // initialize observers and listeners
  724.   // and give C++ access to gBrowser
  725.   window.XULBrowserWindow = new nsBrowserStatusHandler();
  726.   window.QueryInterface(Ci.nsIInterfaceRequestor)
  727.         .getInterface(nsIWebNavigation)
  728.         .QueryInterface(Ci.nsIDocShellTreeItem).treeOwner
  729.         .QueryInterface(Ci.nsIInterfaceRequestor)
  730.         .getInterface(Ci.nsIXULWindow)
  731.         .XULBrowserWindow = window.XULBrowserWindow;
  732.   window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow =
  733.     new nsBrowserAccess();
  734.  
  735.   // set default character set if provided
  736.   if ("arguments" in window && window.arguments.length > 1 && window.arguments[1]) {
  737.     if (window.arguments[1].indexOf("charset=") != -1) {
  738.       var arrayArgComponents = window.arguments[1].split("=");
  739.       if (arrayArgComponents) {
  740.         //we should "inherit" the charset menu setting in a new window
  741.         getMarkupDocumentViewer().defaultCharacterSet = arrayArgComponents[1];
  742.       }
  743.     }
  744.   }
  745.  
  746.   // Initialize browser instance..
  747.   appCore.setWebShellWindow(window);
  748.  
  749.   // Manually hook up session and global history for the first browser
  750.   // so that we don't have to load global history before bringing up a
  751.   // window.
  752.   // Wire up session and global history before any possible
  753.   // progress notifications for back/forward button updating
  754.   webNavigation.sessionHistory = Components.classes["@mozilla.org/browser/shistory;1"]
  755.                                            .createInstance(Components.interfaces.nsISHistory);
  756.   var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  757.   os.addObserver(gBrowser.browsers[0], "browser:purge-session-history", false);
  758.  
  759.   // remove the disablehistory attribute so the browser cleans up, as
  760.   // though it had done this work itself
  761.   gBrowser.browsers[0].removeAttribute("disablehistory");
  762.  
  763.   // enable global history
  764.   gBrowser.docShell.QueryInterface(Components.interfaces.nsIDocShellHistory).useGlobalHistory = true;
  765.  
  766.   // hook up UI through progress listener
  767.   gBrowser.addProgressListener(window.XULBrowserWindow, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
  768.  
  769.   // setup our common DOMLinkAdded listener
  770.   gBrowser.addEventListener("DOMLinkAdded", DOMLinkHandler, false);
  771. }
  772.  
  773. function delayedStartup()
  774. {
  775.   var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  776.   os.addObserver(gSessionHistoryObserver, "browser:purge-session-history", false);
  777.   os.addObserver(gXPInstallObserver, "xpinstall-install-blocked", false);
  778.  
  779.   if (!gPrefService)
  780.     gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
  781.                              .getService(Components.interfaces.nsIPrefBranch2);
  782.   BrowserOffline.init();
  783.   OfflineApps.init();
  784.  
  785.   gBrowser.addEventListener("pageshow", function(evt) { setTimeout(pageShowEventHandlers, 0, evt); }, true);
  786.  
  787.   window.addEventListener("keypress", onBrowserKeyPress, false);
  788.  
  789.   // Ensure login manager is up and running.
  790.   Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
  791.  
  792.   if (gMustLoadSidebar) {
  793.     var sidebar = document.getElementById("sidebar");
  794.     var sidebarBox = document.getElementById("sidebar-box");
  795.     sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
  796.   }
  797.  
  798.   UpdateUrlbarSearchSplitterState();
  799.   
  800.   try {
  801.     placesMigrationTasks();
  802.   } catch(ex) {}
  803.   initBookmarksToolbar();
  804.   PlacesStarButton.init();
  805.  
  806.   // called when we go into full screen, even if it is
  807.   // initiated by a web page script
  808.   window.addEventListener("fullscreen", onFullScreen, true);
  809.  
  810.   if (gIsLoadingBlank && gURLBar && isElementVisible(gURLBar))
  811.     focusElement(gURLBar);
  812.   else
  813.     focusElement(content);
  814.  
  815.   var navToolbox = getNavToolbox();
  816.   navToolbox.customizeDone = BrowserToolboxCustomizeDone;
  817.   navToolbox.customizeChange = BrowserToolboxCustomizeChange;
  818.  
  819.   // Set up Sanitize Item
  820.   gSanitizeListener = new SanitizeListener();
  821.  
  822.   // Enable/Disable auto-hide tabbar
  823.   gAutoHideTabbarPrefListener = new AutoHideTabbarPrefListener();
  824.   gPrefService.addObserver(gAutoHideTabbarPrefListener.domain,
  825.                            gAutoHideTabbarPrefListener, false);
  826.  
  827.   gPrefService.addObserver(gHomeButton.prefDomain, gHomeButton, false);
  828.  
  829.   var homeButton = document.getElementById("home-button");
  830.   gHomeButton.updateTooltip(homeButton);
  831.   gHomeButton.updatePersonalToolbarStyle(homeButton);
  832.  
  833. //@line 985 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  834.   // Perform default browser checking (after window opens).
  835.   var shell = getShellService();
  836.   if (shell) {
  837.     var shouldCheck = shell.shouldCheckDefaultBrowser;
  838.     var willRecoverSession = false;
  839.     try {
  840.       var ss = Cc["@mozilla.org/browser/sessionstartup;1"].
  841.                getService(Ci.nsISessionStartup);
  842.       willRecoverSession =
  843.         (ss.sessionType == Ci.nsISessionStartup.RECOVER_SESSION);
  844.     }
  845.     catch (ex) { /* never mind; suppose SessionStore is broken */ }
  846.     if (shouldCheck && !shell.isDefaultBrowser(true) && !willRecoverSession) {
  847.       var brandBundle = document.getElementById("bundle_brand");
  848.       var shellBundle = document.getElementById("bundle_shell");
  849.  
  850.       var brandShortName = brandBundle.getString("brandShortName");
  851.       var promptTitle = shellBundle.getString("setDefaultBrowserTitle");
  852.       var promptMessage = shellBundle.getFormattedString("setDefaultBrowserMessage",
  853.                                                          [brandShortName]);
  854.       var checkboxLabel = shellBundle.getFormattedString("setDefaultBrowserDontAsk",
  855.                                                          [brandShortName]);
  856.       const IPS = Components.interfaces.nsIPromptService;
  857.       var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
  858.                                                 .getService(IPS);
  859.       var checkEveryTime = { value: shouldCheck };
  860.       var rv = ps.confirmEx(window, promptTitle, promptMessage,
  861.                             IPS.STD_YES_NO_BUTTONS,
  862.                             null, null, null, checkboxLabel, checkEveryTime);
  863.       if (rv == 0)
  864.         shell.setDefaultBrowser(true, false);
  865.       shell.shouldCheckDefaultBrowser = checkEveryTime.value;
  866.     }
  867.   }
  868. //@line 1020 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  869.  
  870.   // BiDi UI
  871.   gBidiUI = isBidiEnabled();
  872.   if (gBidiUI) {
  873.     document.getElementById("documentDirection-separator").hidden = false;
  874.     document.getElementById("documentDirection-swap").hidden = false;
  875.     document.getElementById("textfieldDirection-separator").hidden = false;
  876.     document.getElementById("textfieldDirection-swap").hidden = false;
  877.   }
  878.  
  879. //@line 1036 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  880.  
  881.   // Initialize the microsummary service by retrieving it, prompting its factory
  882.   // to create its singleton, whose constructor initializes the service.
  883.   try {
  884.     Cc["@mozilla.org/microsummary/service;1"].getService(Ci.nsIMicrosummaryService);
  885.   } catch (ex) {
  886.     Components.utils.reportError("Failed to init microsummary service:\n" + ex);
  887.   }
  888.  
  889.   // Initialize the full zoom setting.
  890.   // We do this before the session restore service gets initialized so we can
  891.   // apply full zoom settings to tabs restored by the session restore service.
  892.   try {
  893.     FullZoom.init();
  894.   }
  895.   catch(ex) {
  896.     Components.utils.reportError("Failed to init content pref service:\n" + ex);
  897.   }
  898.  
  899. //@line 1073 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  900.  
  901.   // initialize the session-restore service (in case it's not already running)
  902.   if (document.documentElement.getAttribute("windowtype") == "navigator:browser") {
  903.     try {
  904.       var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  905.                getService(Ci.nsISessionStore);
  906.       ss.init(window);
  907.     } catch(ex) {
  908.       dump("nsSessionStore could not be initialized: " + ex + "\n");
  909.     }
  910.   }
  911.  
  912.   // bookmark-all-tabs command
  913.   gBookmarkAllTabsHandler = new BookmarkAllTabsHandler();
  914.  
  915.   // Attach a listener to watch for "command" events bubbling up from error
  916.   // pages.  This lets us fix bugs like 401575 which require error page UI to
  917.   // do privileged things, without letting error pages have any privilege
  918.   // themselves.
  919.   gBrowser.addEventListener("command", BrowserOnCommand, false);
  920.  
  921.   // Delayed initialization of the livemarks update timer.
  922.   // Livemark updates don't need to start until after bookmark UI 
  923.   // such as the toolbar has initialized. Starting 5 seconds after
  924.   // delayedStartup in order to stagger this before the download
  925.   // manager starts (see below).
  926.   setTimeout(function() PlacesUtils.livemarks.start(), 5000);
  927.  
  928.   // Initialize the download manager some time after the app starts so that
  929.   // auto-resume downloads begin (such as after crashing or quitting with
  930.   // active downloads) and speeds up the first-load of the download manager UI.
  931.   // If the user manually opens the download manager before the timeout, the
  932.   // downloads will start right away, and getting the service again won't hurt.
  933.   setTimeout(function() {
  934.     gDownloadMgr = Cc["@mozilla.org/download-manager;1"].
  935.                    getService(Ci.nsIDownloadManager);
  936.  
  937.     // Initialize the downloads monitor panel listener
  938.     DownloadMonitorPanel.init();
  939.   }, 10000);
  940.  
  941. //@line 1115 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  942.   updateEditUIVisibility();
  943.   let placesContext = document.getElementById("placesContext");
  944.   placesContext.addEventListener("popupshowing", updateEditUIVisibility, false);
  945.   placesContext.addEventListener("popuphiding", updateEditUIVisibility, false);
  946. //@line 1120 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  947. }
  948.  
  949. function BrowserShutdown()
  950. {
  951.   try {
  952.     FullZoom.destroy();
  953.   }
  954.   catch(ex) {
  955.     Components.utils.reportError(ex);
  956.   }
  957.  
  958.   var os = Components.classes["@mozilla.org/observer-service;1"]
  959.     .getService(Components.interfaces.nsIObserverService);
  960.   os.removeObserver(gSessionHistoryObserver, "browser:purge-session-history");
  961.   os.removeObserver(gXPInstallObserver, "xpinstall-install-blocked");
  962.  
  963.   try {
  964.     gBrowser.removeProgressListener(window.XULBrowserWindow);
  965.   } catch (ex) {
  966.   }
  967.  
  968.   PlacesStarButton.uninit();
  969.  
  970.   try {
  971.     gPrefService.removeObserver(gAutoHideTabbarPrefListener.domain,
  972.                                 gAutoHideTabbarPrefListener);
  973.     gPrefService.removeObserver(gHomeButton.prefDomain, gHomeButton);
  974.   } catch (ex) {
  975.     Components.utils.reportError(ex);
  976.   }
  977.  
  978.   if (gSanitizeListener)
  979.     gSanitizeListener.shutdown();
  980.  
  981.   BrowserOffline.uninit();
  982.   OfflineApps.uninit();
  983.   DownloadMonitorPanel.uninit();
  984.  
  985.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  986.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  987.   var enumerator = windowManagerInterface.getEnumerator(null);
  988.   enumerator.getNext();
  989.   if (!enumerator.hasMoreElements()) {
  990.     document.persist("sidebar-box", "sidebarcommand");
  991.     document.persist("sidebar-box", "width");
  992.     document.persist("sidebar-box", "src");
  993.     document.persist("sidebar-title", "value");
  994.   }
  995.  
  996.   window.XULBrowserWindow.destroy();
  997.   window.XULBrowserWindow = null;
  998.   window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  999.         .getInterface(Components.interfaces.nsIWebNavigation)
  1000.         .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner
  1001.         .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  1002.         .getInterface(Components.interfaces.nsIXULWindow)
  1003.         .XULBrowserWindow = null;
  1004.   window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow = null;
  1005.  
  1006.   // Close the app core.
  1007.   if (appCore)
  1008.     appCore.close();
  1009. }
  1010.  
  1011. //@line 1251 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1012.  
  1013. function AutoHideTabbarPrefListener()
  1014. {
  1015.   this.toggleAutoHideTabbar();
  1016. }
  1017.  
  1018. AutoHideTabbarPrefListener.prototype =
  1019. {
  1020.   domain: "browser.tabs.autoHide",
  1021.   observe: function (aSubject, aTopic, aPrefName)
  1022.   {
  1023.     if (aTopic != "nsPref:changed" || aPrefName != this.domain)
  1024.       return;
  1025.  
  1026.     this.toggleAutoHideTabbar();
  1027.   },
  1028.  
  1029.   toggleAutoHideTabbar: function ()
  1030.   {
  1031.     if (gBrowser.tabContainer.childNodes.length == 1 &&
  1032.         window.toolbar.visible) {
  1033.       var aVisible = false;
  1034.       try {
  1035.         aVisible = !gPrefService.getBoolPref(this.domain);
  1036.       }
  1037.       catch (e) {
  1038.       }
  1039.       gBrowser.setStripVisibilityTo(aVisible);
  1040.       gPrefService.setBoolPref("browser.tabs.forceHide", false);
  1041.     }
  1042.   }
  1043. }
  1044.  
  1045. function SanitizeListener()
  1046. {
  1047.   gPrefService.addObserver(this.promptDomain, this, false);
  1048.  
  1049.   this._defaultLabel = document.getElementById("sanitizeItem")
  1050.                                .getAttribute("label");
  1051.   this._updateSanitizeItem();
  1052.  
  1053.   if (gPrefService.prefHasUserValue(this.didSanitizeDomain)) {
  1054.     gPrefService.clearUserPref(this.didSanitizeDomain);
  1055.     // We need to persist this preference change, since we want to
  1056.     // check it at next app start even if the browser exits abruptly
  1057.     gPrefService.QueryInterface(Ci.nsIPrefService).savePrefFile(null);
  1058.   }
  1059. }
  1060.  
  1061. SanitizeListener.prototype =
  1062. {
  1063.   promptDomain      : "privacy.sanitize.promptOnSanitize",
  1064.   didSanitizeDomain : "privacy.sanitize.didShutdownSanitize",
  1065.  
  1066.   observe: function (aSubject, aTopic, aPrefName)
  1067.   {
  1068.     this._updateSanitizeItem();
  1069.   },
  1070.  
  1071.   shutdown: function ()
  1072.   {
  1073.     gPrefService.removeObserver(this.promptDomain, this);
  1074.   },
  1075.  
  1076.   _updateSanitizeItem: function ()
  1077.   {
  1078.     var label = gPrefService.getBoolPref(this.promptDomain) ?
  1079.         gNavigatorBundle.getString("sanitizeWithPromptLabel") : 
  1080.         this._defaultLabel;
  1081.     document.getElementById("sanitizeItem").setAttribute("label", label);
  1082.   }
  1083. }
  1084.  
  1085. function onBrowserKeyPress(event)
  1086. {
  1087.   if (event.altKey && event.keyCode == KeyEvent.DOM_VK_RETURN) {
  1088.     // XXXblake Proper fix is to just check whether focus is in the urlbar. However, focus with the autocomplete widget is all
  1089.     // 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
  1090.     // is on a link.
  1091.     if (!(document.commandDispatcher.focusedElement instanceof HTMLAnchorElement)) {
  1092.       // Don't let winxp beep on ALT+ENTER, since the URL bar uses it.
  1093.       event.preventDefault();
  1094.       return;
  1095.     }
  1096.   }
  1097. }
  1098.  
  1099. function BrowserNumberTabSelection(event, index)
  1100. {
  1101.   // [Ctrl]+[9] always selects the last tab
  1102.   if (index == 8)
  1103.     index = gBrowser.tabContainer.childNodes.length - 1;
  1104.   else if (index >= gBrowser.tabContainer.childNodes.length)
  1105.     return;
  1106.  
  1107.   var oldTab = gBrowser.selectedTab;
  1108.   var newTab = gBrowser.tabContainer.childNodes[index];
  1109.   if (newTab != oldTab)
  1110.     gBrowser.selectedTab = newTab;
  1111.  
  1112.   event.preventDefault();
  1113.   event.stopPropagation();
  1114. }
  1115.  
  1116. function gotoHistoryIndex(aEvent)
  1117. {
  1118.   var index = aEvent.target.getAttribute("index");
  1119.   if (!index)
  1120.     return false;
  1121.  
  1122.   var where = whereToOpenLink(aEvent);
  1123.  
  1124.   if (where == "current") {
  1125.     // Normal click.  Go there in the current tab and update session history.
  1126.  
  1127.     try {
  1128.       getBrowser().gotoIndex(index);
  1129.     }
  1130.     catch(ex) {
  1131.       return false;
  1132.     }
  1133.     return true;
  1134.   }
  1135.   else {
  1136.     // Modified click.  Go there in a new tab/window.
  1137.     // This code doesn't copy history or work well with framed pages.
  1138.  
  1139.     var sessionHistory = getWebNavigation().sessionHistory;
  1140.     var entry = sessionHistory.getEntryAtIndex(index, false);
  1141.     var url = entry.URI.spec;
  1142.     openUILinkIn(url, where);
  1143.     return true;
  1144.   }
  1145. }
  1146.  
  1147. function BrowserForward(aEvent, aIgnoreAlt)
  1148. {
  1149.   var where = whereToOpenLink(aEvent, false, aIgnoreAlt);
  1150.  
  1151.   if (where == "current") {
  1152.     try {
  1153.       getBrowser().goForward();
  1154.     }
  1155.     catch(ex) {
  1156.     }
  1157.   }
  1158.   else {
  1159.     var sessionHistory = getWebNavigation().sessionHistory;
  1160.     var currentIndex = sessionHistory.index;
  1161.     var entry = sessionHistory.getEntryAtIndex(currentIndex + 1, false);
  1162.     var url = entry.URI.spec;
  1163.     openUILinkIn(url, where);
  1164.   }
  1165. }
  1166.  
  1167. function BrowserBack(aEvent, aIgnoreAlt)
  1168. {
  1169.   var where = whereToOpenLink(aEvent, false, aIgnoreAlt);
  1170.  
  1171.   if (where == "current") {
  1172.     try {
  1173.       getBrowser().goBack();
  1174.     }
  1175.     catch(ex) {
  1176.     }
  1177.   }
  1178.   else {
  1179.     var sessionHistory = getWebNavigation().sessionHistory;
  1180.     var currentIndex = sessionHistory.index;
  1181.     var entry = sessionHistory.getEntryAtIndex(currentIndex - 1, false);
  1182.     var url = entry.URI.spec;
  1183.     openUILinkIn(url, where);
  1184.   }
  1185. }
  1186.  
  1187. function BrowserHandleBackspace()
  1188. {
  1189.   switch (gPrefService.getIntPref("browser.backspace_action")) {
  1190.   case 0:
  1191.     BrowserBack();
  1192.     break;
  1193.   case 1:
  1194.     goDoCommand("cmd_scrollPageUp");
  1195.     break;
  1196.   }
  1197. }
  1198.  
  1199. function BrowserHandleShiftBackspace()
  1200. {
  1201.   switch (gPrefService.getIntPref("browser.backspace_action")) {
  1202.   case 0:
  1203.     BrowserForward();
  1204.     break;
  1205.   case 1:
  1206.     goDoCommand("cmd_scrollPageDown");
  1207.     break;
  1208.   }
  1209. }
  1210.  
  1211. function BrowserStop()
  1212. {
  1213.   try {
  1214.     const stopFlags = nsIWebNavigation.STOP_ALL;
  1215.     getWebNavigation().stop(stopFlags);
  1216.   }
  1217.   catch(ex) {
  1218.   }
  1219. }
  1220.  
  1221. function BrowserReload()
  1222. {
  1223.   const reloadFlags = nsIWebNavigation.LOAD_FLAGS_NONE;
  1224.   return BrowserReloadWithFlags(reloadFlags);
  1225. }
  1226.  
  1227. function BrowserReloadSkipCache()
  1228. {
  1229.   // Bypass proxy and cache.
  1230.   const reloadFlags = nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  1231.   return BrowserReloadWithFlags(reloadFlags);
  1232. }
  1233.  
  1234. function BrowserHome()
  1235. {
  1236.   var homePage = gHomeButton.getHomePage();
  1237.   loadOneOrMoreURIs(homePage);
  1238. }
  1239.  
  1240. function BrowserGoHome(aEvent)
  1241. {
  1242.   if (aEvent && "button" in aEvent &&
  1243.       aEvent.button == 2) // right-click: do nothing
  1244.     return;
  1245.  
  1246.   var homePage = gHomeButton.getHomePage();
  1247.   var where = whereToOpenLink(aEvent);
  1248.   var urls;
  1249.  
  1250.   // openUILinkIn in utilityOverlay.js doesn't handle loading multiple pages
  1251.   switch (where) {
  1252.   case "save":
  1253.     urls = homePage.split("|");
  1254.     saveURL(urls[0], null, null, true);  // only save the first page
  1255.     break;
  1256.   case "current":
  1257.     loadOneOrMoreURIs(homePage);
  1258.     break;
  1259.   case "tabshifted":
  1260.   case "tab":
  1261.     urls = homePage.split("|");
  1262.     var loadInBackground = getBoolPref("browser.tabs.loadBookmarksInBackground", false);
  1263.     gBrowser.loadTabs(urls, loadInBackground);
  1264.     break;
  1265.   case "window":
  1266.     OpenBrowserWindow();
  1267.     break;
  1268.   }
  1269. }
  1270.  
  1271. function loadOneOrMoreURIs(aURIString)
  1272. {
  1273. //@line 1520 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1274.   // This function throws for certain malformed URIs, so use exception handling
  1275.   // so that we don't disrupt startup
  1276.   try {
  1277.     gBrowser.loadTabs(aURIString.split("|"), false, true);
  1278.   } 
  1279.   catch (e) {
  1280.   }
  1281. }
  1282.  
  1283. function focusAndSelectUrlBar()
  1284. {
  1285.   if (gURLBar && isElementVisible(gURLBar) && !gURLBar.readOnly) {
  1286.     gURLBar.focus();
  1287.     gURLBar.select();
  1288.     return true;
  1289.   }
  1290.   return false;
  1291. }
  1292.  
  1293. function openLocation()
  1294. {
  1295.   if (window.fullScreen)
  1296.     FullScreen.mouseoverToggle(true);
  1297.  
  1298.   if (focusAndSelectUrlBar())
  1299.     return;
  1300. //@line 1563 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1301.   openDialog("chrome://browser/content/openLocation.xul", "_blank",
  1302.              "chrome,modal,titlebar", window);
  1303. }
  1304.  
  1305. function openLocationCallback()
  1306. {
  1307.   // make sure the DOM is ready
  1308.   setTimeout(function() { this.openLocation(); }, 0);
  1309. }
  1310.  
  1311. function BrowserOpenTab()
  1312. {
  1313.   if (!gBrowser) {
  1314.     // If there are no open browser windows, open a new one
  1315.     window.openDialog("chrome://browser/content/", "_blank",
  1316.                       "chrome,all,dialog=no", "about:blank");
  1317.     return;
  1318.   }
  1319.   gBrowser.loadOneTab("about:blank", null, null, null, false, false);
  1320.   if (gURLBar)
  1321.     gURLBar.focus();
  1322. }
  1323.  
  1324. /* Called from the openLocation dialog. This allows that dialog to instruct
  1325.    its opener to open a new window and then step completely out of the way.
  1326.    Anything less byzantine is causing horrible crashes, rather believably,
  1327.    though oddly only on Linux. */
  1328. function delayedOpenWindow(chrome, flags, href, postData)
  1329. {
  1330.   // The other way to use setTimeout,
  1331.   // setTimeout(openDialog, 10, chrome, "_blank", flags, url),
  1332.   // doesn't work here.  The extra "magic" extra argument setTimeout adds to
  1333.   // the callback function would confuse prepareForStartup() by making
  1334.   // window.arguments[1] be an integer instead of null.
  1335.   setTimeout(function() { openDialog(chrome, "_blank", flags, href, null, null, postData); }, 10);
  1336. }
  1337.  
  1338. /* Required because the tab needs time to set up its content viewers and get the load of
  1339.    the URI kicked off before becoming the active content area. */
  1340. function delayedOpenTab(aUrl, aReferrer, aCharset, aPostData, aAllowThirdPartyFixup)
  1341. {
  1342.   gBrowser.loadOneTab(aUrl, aReferrer, aCharset, aPostData, false, aAllowThirdPartyFixup);
  1343. }
  1344.  
  1345. function BrowserOpenFileWindow()
  1346. {
  1347.   // Get filepicker component.
  1348.   try {
  1349.     const nsIFilePicker = Components.interfaces.nsIFilePicker;
  1350.     var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  1351.     fp.init(window, gNavigatorBundle.getString("openFile"), nsIFilePicker.modeOpen);
  1352.     fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText | nsIFilePicker.filterImages |
  1353.                      nsIFilePicker.filterXML | nsIFilePicker.filterHTML);
  1354.  
  1355.     if (fp.show() == nsIFilePicker.returnOK)
  1356.       openTopWin(fp.fileURL.spec);
  1357.   } catch (ex) {
  1358.   }
  1359. }
  1360.  
  1361. function BrowserCloseTabOrWindow()
  1362. {
  1363. //@line 1632 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1364.  
  1365.   if (gBrowser.tabContainer.childNodes.length > 1) {
  1366.     gBrowser.removeCurrentTab(); 
  1367.     return;
  1368.   }
  1369.  
  1370. //@line 1639 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1371.   if (gBrowser.localName == "tabbrowser" && window.toolbar.visible &&
  1372.       !gPrefService.getBoolPref("browser.tabs.autoHide")) {
  1373.     // Replace the remaining tab with a blank one and focus the address bar
  1374.     gBrowser.removeCurrentTab();
  1375.     if (gURLBar)
  1376.       setTimeout(function() { gURLBar.focus(); }, 0);
  1377.     return;
  1378.   }
  1379. //@line 1648 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1380.  
  1381.   closeWindow(true);
  1382. }
  1383.  
  1384. function BrowserTryToCloseWindow()
  1385. {
  1386.   if (WindowIsClosing()) {
  1387.     if (window.fullScreen) {
  1388.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  1389.                                                    FullScreen._collapseCallback, false);
  1390.       document.removeEventListener("keypress", FullScreen._keyToggleCallback, false);
  1391.       document.removeEventListener("popupshown", FullScreen._setPopupOpen, false);
  1392.       document.removeEventListener("popuphidden", FullScreen._setPopupOpen, false);
  1393.       gPrefService.removeObserver("browser.fullscreen", FullScreen);
  1394.  
  1395.       var fullScrToggler = document.getElementById("fullscr-toggler");
  1396.       if (fullScrToggler) {
  1397.         fullScrToggler.removeEventListener("mouseover", FullScreen._expandCallback, false);
  1398.         fullScrToggler.removeEventListener("dragenter", FullScreen._expandCallback, false);
  1399.       }
  1400.     }
  1401.  
  1402.     window.close();     // WindowIsClosing does all the necessary checks
  1403.   }
  1404. }
  1405.  
  1406. function loadURI(uri, referrer, postData, allowThirdPartyFixup)
  1407. {
  1408.   try {
  1409.     if (postData === undefined)
  1410.       postData = null;
  1411.     var flags = nsIWebNavigation.LOAD_FLAGS_NONE;
  1412.     if (allowThirdPartyFixup) {
  1413.       flags = nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
  1414.     }
  1415.     getBrowser().loadURIWithFlags(uri, flags, referrer, null, postData);
  1416.   } catch (e) {
  1417.   }
  1418. }
  1419.  
  1420. function BrowserLoadURL(aTriggeringEvent, aPostData) {
  1421.   var url = gURLBar.value;
  1422.  
  1423.   if (aTriggeringEvent instanceof MouseEvent) {
  1424.     if (aTriggeringEvent.button == 2)
  1425.       return; // Do nothing for right clicks
  1426.  
  1427.     // We have a mouse event (from the go button), so use the standard
  1428.     // UI link behaviors
  1429.     openUILink(url, aTriggeringEvent, false, false,
  1430.                true /* allow third party fixup */, aPostData);
  1431.     return;
  1432.   }
  1433.  
  1434.   if (aTriggeringEvent && aTriggeringEvent.altKey) {
  1435.     handleURLBarRevert();
  1436.     content.focus();
  1437.     gBrowser.loadOneTab(url, null, null, aPostData, false,
  1438.                         true /* allow third party fixup */);
  1439.     aTriggeringEvent.preventDefault();
  1440.     aTriggeringEvent.stopPropagation();
  1441.   }
  1442.   else
  1443.     loadURI(url, null, aPostData, true /* allow third party fixup */);
  1444.  
  1445.   focusElement(content);
  1446. }
  1447.  
  1448. function getShortcutOrURI(aURL, aPostDataRef) {
  1449.   var shortcutURL = null;
  1450.   var keyword = aURL;
  1451.   var param = "";
  1452.   var searchService = Cc["@mozilla.org/browser/search-service;1"].
  1453.                       getService(Ci.nsIBrowserSearchService);
  1454.  
  1455.   var offset = aURL.indexOf(" ");
  1456.   if (offset > 0) {
  1457.     keyword = aURL.substr(0, offset);
  1458.     param = aURL.substr(offset + 1);
  1459.   }
  1460.  
  1461.   if (!aPostDataRef)
  1462.     aPostDataRef = {};
  1463.  
  1464.   var engine = searchService.getEngineByAlias(keyword);
  1465.   if (engine) {
  1466.     var submission = engine.getSubmission(param, null);
  1467.     aPostDataRef.value = submission.postData;
  1468.     return submission.uri.spec;
  1469.   }
  1470.  
  1471.   [shortcutURL, aPostDataRef.value] =
  1472.     PlacesUtils.getURLAndPostDataForKeyword(keyword);
  1473.  
  1474.   if (!shortcutURL)
  1475.     return aURL;
  1476.  
  1477.   var postData = "";
  1478.   if (aPostDataRef.value)
  1479.     postData = unescape(aPostDataRef.value);
  1480.  
  1481.   if (/%s/i.test(shortcutURL) || /%s/i.test(postData)) {
  1482.     var charset = "";
  1483.     const re = /^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/;
  1484.     var matches = shortcutURL.match(re);
  1485.     if (matches)
  1486.       [, shortcutURL, charset] = matches;
  1487.     else {
  1488.       // Try to get the saved character-set.
  1489.       try {
  1490.         // makeURI throws if URI is invalid.
  1491.         // Will return an empty string if character-set is not found.
  1492.         charset = PlacesUtils.history.getCharsetForURI(makeURI(shortcutURL));
  1493.       } catch (e) {}
  1494.     }
  1495.  
  1496.     var encodedParam = "";
  1497.     if (charset)
  1498.       encodedParam = escape(convertFromUnicode(charset, param));
  1499.     else // Default charset is UTF-8
  1500.       encodedParam = encodeURIComponent(param);
  1501.  
  1502.     shortcutURL = shortcutURL.replace(/%s/g, encodedParam).replace(/%S/g, param);
  1503.  
  1504.     if (/%s/i.test(postData)) // POST keyword
  1505.       aPostDataRef.value = getPostDataStream(postData, param, encodedParam,
  1506.                                              "application/x-www-form-urlencoded");
  1507.   }
  1508.   else if (param) {
  1509.     // This keyword doesn't take a parameter, but one was provided. Just return
  1510.     // the original URL.
  1511.     aPostDataRef.value = null;
  1512.  
  1513.     return aURL;
  1514.   }
  1515.  
  1516.   return shortcutURL;
  1517. }
  1518.  
  1519. function getPostDataStream(aStringData, aKeyword, aEncKeyword, aType) {
  1520.   var dataStream = Cc["@mozilla.org/io/string-input-stream;1"].
  1521.                    createInstance(Ci.nsIStringInputStream);
  1522.   aStringData = aStringData.replace(/%s/g, aEncKeyword).replace(/%S/g, aKeyword);
  1523.   dataStream.data = aStringData;
  1524.  
  1525.   var mimeStream = Cc["@mozilla.org/network/mime-input-stream;1"].
  1526.                    createInstance(Ci.nsIMIMEInputStream);
  1527.   mimeStream.addHeader("Content-Type", aType);
  1528.   mimeStream.addContentLength = true;
  1529.   mimeStream.setData(dataStream);
  1530.   return mimeStream.QueryInterface(Ci.nsIInputStream);
  1531. }
  1532.  
  1533. function readFromClipboard()
  1534. {
  1535.   var url;
  1536.  
  1537.   try {
  1538.     // Get clipboard.
  1539.     var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
  1540.                               .getService(Components.interfaces.nsIClipboard);
  1541.  
  1542.     // Create tranferable that will transfer the text.
  1543.     var trans = Components.classes["@mozilla.org/widget/transferable;1"]
  1544.                           .createInstance(Components.interfaces.nsITransferable);
  1545.  
  1546.     trans.addDataFlavor("text/unicode");
  1547.  
  1548.     // If available, use selection clipboard, otherwise global one
  1549.     if (clipboard.supportsSelectionClipboard())
  1550.       clipboard.getData(trans, clipboard.kSelectionClipboard);
  1551.     else
  1552.       clipboard.getData(trans, clipboard.kGlobalClipboard);
  1553.  
  1554.     var data = {};
  1555.     var dataLen = {};
  1556.     trans.getTransferData("text/unicode", data, dataLen);
  1557.  
  1558.     if (data) {
  1559.       data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
  1560.       url = data.data.substring(0, dataLen.value / 2);
  1561.     }
  1562.   } catch (ex) {
  1563.   }
  1564.  
  1565.   return url;
  1566. }
  1567.  
  1568. function BrowserViewSourceOfDocument(aDocument)
  1569. {
  1570.   var pageCookie;
  1571.   var webNav;
  1572.  
  1573.   // Get the document charset
  1574.   var docCharset = "charset=" + aDocument.characterSet;
  1575.  
  1576.   // Get the nsIWebNavigation associated with the document
  1577.   try {
  1578.       var win;
  1579.       var ifRequestor;
  1580.  
  1581.       // Get the DOMWindow for the requested document.  If the DOMWindow
  1582.       // cannot be found, then just use the content window...
  1583.       //
  1584.       // XXX:  This is a bit of a hack...
  1585.       win = aDocument.defaultView;
  1586.       if (win == window) {
  1587.         win = content;
  1588.       }
  1589.       ifRequestor = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  1590.  
  1591.       webNav = ifRequestor.getInterface(nsIWebNavigation);
  1592.   } catch(err) {
  1593.       // If nsIWebNavigation cannot be found, just get the one for the whole
  1594.       // window...
  1595.       webNav = getWebNavigation();
  1596.   }
  1597.   //
  1598.   // Get the 'PageDescriptor' for the current document. This allows the
  1599.   // view-source to access the cached copy of the content rather than
  1600.   // refetching it from the network...
  1601.   //
  1602.   try{
  1603.     var PageLoader = webNav.QueryInterface(Components.interfaces.nsIWebPageDescriptor);
  1604.  
  1605.     pageCookie = PageLoader.currentDescriptor;
  1606.   } catch(err) {
  1607.     // If no page descriptor is available, just use the view-source URL...
  1608.   }
  1609.  
  1610.   ViewSourceOfURL(webNav.currentURI.spec, pageCookie, aDocument);
  1611. }
  1612.  
  1613. function ViewSourceOfURL(aURL, aPageDescriptor, aDocument)
  1614. {
  1615.   var utils = window.top.gViewSourceUtils;
  1616.   if (getBoolPref("view_source.editor.external", false)) {
  1617.     utils.openInExternalEditor(aURL, aPageDescriptor, aDocument);
  1618.   }
  1619.   else {
  1620.     utils.openInInternalViewer(aURL, aPageDescriptor, aDocument);
  1621.   }
  1622. }
  1623.  
  1624. // doc - document to use for source, or null for this window's document
  1625. // initialTab - name of the initial tab to display, or null for the first tab
  1626. function BrowserPageInfo(doc, initialTab)
  1627. {
  1628.   var args = {doc: doc, initialTab: initialTab};
  1629.   toOpenDialogByTypeAndUrl("Browser:page-info",
  1630.                            doc ? doc.location : window.content.document.location,
  1631.                            "chrome://browser/content/pageinfo/pageInfo.xul",
  1632.                            "chrome,toolbar,dialog=no,resizable",
  1633.                            args);
  1634. }
  1635.  
  1636. //@line 1953 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1637.  
  1638. function checkForDirectoryListing()
  1639. {
  1640.   if ( "HTTPIndex" in content &&
  1641.        content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) {
  1642.     content.wrappedJSObject.defaultCharacterset =
  1643.       getMarkupDocumentViewer().defaultCharacterSet;
  1644.   }
  1645. }
  1646.  
  1647. function URLBarSetURI(aURI) {
  1648.   var value = getBrowser().userTypedValue;
  1649.   var state = "invalid";
  1650.  
  1651.   if (!value) {
  1652.     if (aURI) {
  1653.       // If the url has "wyciwyg://" as the protocol, strip it off.
  1654.       // Nobody wants to see it on the urlbar for dynamically generated
  1655.       // pages.
  1656.       if (!gURIFixup)
  1657.         gURIFixup = Cc["@mozilla.org/docshell/urifixup;1"]
  1658.                       .getService(Ci.nsIURIFixup);
  1659.       try {
  1660.         aURI = gURIFixup.createExposableURI(aURI);
  1661.       } catch (ex) {}
  1662.     } else {
  1663.       aURI = getWebNavigation().currentURI;
  1664.     }
  1665.  
  1666.     if (aURI.spec == "about:blank") {
  1667.       // Replace "about:blank" with an empty string
  1668.       // only if there's no opener (bug 370555).
  1669.       value = content.opener ? aURI.spec : "";
  1670.     } else {
  1671.       value = losslessDecodeURI(aURI);
  1672.       state = "valid";
  1673.     }
  1674.   }
  1675.  
  1676.   gURLBar.value = value;
  1677.   SetPageProxyState(state);
  1678. }
  1679.  
  1680. function losslessDecodeURI(aURI) {
  1681.   var value = aURI.spec;
  1682.   // Try to decode as UTF-8 if there's no encoding sequence that we would break.
  1683.   if (!/%25(?:3B|2F|3F|3A|40|26|3D|2B|24|2C|23)/i.test(value))
  1684.     try {
  1685.       value = decodeURI(value)
  1686.                 // 1. decodeURI decodes %25 to %, which creates unintended
  1687.                 //    encoding sequences. Re-encode it, unless it's part of
  1688.                 //    a sequence that survived decodeURI, i.e. one for:
  1689.                 //    ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '#'
  1690.                 //    (RFC 3987 section 3.2)
  1691.                 // 2. Re-encode whitespace so that it doesn't get eaten away
  1692.                 //    by the location bar (bug 410726).
  1693.                 .replace(/%(?!3B|2F|3F|3A|40|26|3D|2B|24|2C|23)|[\r\n\t]/ig,
  1694.                          encodeURIComponent);
  1695.     } catch (e) {}
  1696.  
  1697.   // Encode invisible characters (soft hyphen, zero-width space, BOM,
  1698.   // line and paragraph separator, word joiner, invisible times,
  1699.   // invisible separator, object replacement character) (bug 452979)
  1700.   value = value.replace(/[\v\x0c\x1c\x1d\x1e\x1f\u00ad\u200b\ufeff\u2028\u2029\u2060\u2062\u2063\ufffc]/g,
  1701.                         encodeURIComponent);
  1702.  
  1703.   // Encode bidirectional formatting characters.
  1704.   // (RFC 3987 sections 3.2 and 4.1 paragraph 6)
  1705.   value = value.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g,
  1706.                         encodeURIComponent);
  1707.   return value;
  1708. }
  1709.  
  1710. // Replace the urlbar's value with the url of the page.
  1711. function handleURLBarRevert() {
  1712.   var throbberElement = document.getElementById("navigator-throbber");
  1713.   var isScrolling = gURLBar.popupOpen;
  1714.  
  1715.   gBrowser.userTypedValue = null;
  1716.  
  1717.   // don't revert to last valid url unless page is NOT loading
  1718.   // and user is NOT key-scrolling through autocomplete list
  1719.   if ((!throbberElement || !throbberElement.hasAttribute("busy")) && !isScrolling) {
  1720.     URLBarSetURI();
  1721.  
  1722.     // If the value isn't empty and the urlbar has focus, select the value.
  1723.     if (gURLBar.value && gURLBar.hasAttribute("focused"))
  1724.       gURLBar.select();
  1725.   }
  1726.  
  1727.   // tell widget to revert to last typed text only if the user
  1728.   // was scrolling when they hit escape
  1729.   return !isScrolling;
  1730. }
  1731.  
  1732. function handleURLBarCommand(aTriggeringEvent) {
  1733.   if (!gURLBar.value)
  1734.     return;
  1735.  
  1736.   var postData = { };
  1737.   canonizeUrl(aTriggeringEvent, postData);
  1738.  
  1739.   try {
  1740.     addToUrlbarHistory(gURLBar.value);
  1741.   } catch (ex) {
  1742.     // Things may go wrong when adding url to session history,
  1743.     // but don't let that interfere with the loading of the url.
  1744.   }
  1745.  
  1746.   BrowserLoadURL(aTriggeringEvent, postData.value);
  1747. }
  1748.  
  1749. function canonizeUrl(aTriggeringEvent, aPostDataRef) {
  1750.   if (!gURLBar || !gURLBar.value)
  1751.     return;
  1752.  
  1753.   var url = gURLBar.value;
  1754.  
  1755.   // Only add the suffix when the URL bar value isn't already "URL-like".
  1756.   // Since this function is called from handleURLBarCommand, which receives
  1757.   // both mouse (from the go button) and keyboard events, we also make sure not
  1758.   // to do the fixup unless we get a keyboard event, to match user expectations.
  1759.   if (!/^(www|https?)\b|\/\s*$/i.test(url) &&
  1760.       (aTriggeringEvent instanceof KeyEvent)) {
  1761. //@line 2080 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1762.     var accel = aTriggeringEvent.ctrlKey;
  1763. //@line 2082 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1764.     var shift = aTriggeringEvent.shiftKey;
  1765.  
  1766.     var suffix = "";
  1767.  
  1768.     switch (true) {
  1769.       case (accel && shift):
  1770.         suffix = ".org/";
  1771.         break;
  1772.       case (shift):
  1773.         suffix = ".net/";
  1774.         break;
  1775.       case (accel):
  1776.         try {
  1777.           suffix = gPrefService.getCharPref("browser.fixup.alternate.suffix");
  1778.           if (suffix.charAt(suffix.length - 1) != "/")
  1779.             suffix += "/";
  1780.         } catch(e) {
  1781.           suffix = ".com/";
  1782.         }
  1783.         break;
  1784.     }
  1785.  
  1786.     if (suffix) {
  1787.       // trim leading/trailing spaces (bug 233205)
  1788.       url = url.replace(/^\s+/, "").replace(/\s+$/, "");
  1789.  
  1790.       // Tack www. and suffix on.  If user has appended directories, insert
  1791.       // suffix before them (bug 279035).  Be careful not to get two slashes.
  1792.       // Also, don't add the suffix if it's in the original url (bug 233853).
  1793.       
  1794.       var firstSlash = url.indexOf("/");
  1795.       var existingSuffix = url.indexOf(suffix.substring(0, suffix.length - 1));
  1796.  
  1797.       // * Logic for slash and existing suffix (example)
  1798.       // No slash, no suffix: Add suffix (mozilla)
  1799.       // No slash, yes suffix: Add slash (mozilla.com)
  1800.       // Yes slash, no suffix: Insert suffix (mozilla/stuff)
  1801.       // Yes slash, suffix before slash: Do nothing (mozilla.com/stuff)
  1802.       // Yes slash, suffix after slash: Insert suffix (mozilla/?stuff=.com)
  1803.       
  1804.       if (firstSlash >= 0) {
  1805.         if (existingSuffix == -1 || existingSuffix > firstSlash)
  1806.           url = url.substring(0, firstSlash) + suffix +
  1807.                 url.substring(firstSlash + 1);
  1808.       } else
  1809.         url = url + (existingSuffix == -1 ? suffix : "/");
  1810.  
  1811.       url = "http://www." + url;
  1812.     }
  1813.   }
  1814.  
  1815.   gURLBar.value = getShortcutOrURI(url, aPostDataRef);
  1816.  
  1817.   // Also update this so the browser display keeps the new value (bug 310651)
  1818.   gBrowser.userTypedValue = gURLBar.value;
  1819. }
  1820.  
  1821. function UpdateUrlbarSearchSplitterState()
  1822. {
  1823.   var splitter = document.getElementById("urlbar-search-splitter");
  1824.   var urlbar = document.getElementById("urlbar-container");
  1825.   var searchbar = document.getElementById("search-container");
  1826.  
  1827.   var ibefore = null;
  1828.   if (urlbar && searchbar) {
  1829.     if (urlbar.nextSibling == searchbar)
  1830.       ibefore = searchbar;
  1831.     else if (searchbar.nextSibling == urlbar)
  1832.       ibefore = urlbar;
  1833.   }
  1834.  
  1835.   if (ibefore) {
  1836.     if (!splitter) {
  1837.       splitter = document.createElement("splitter");
  1838.       splitter.id = "urlbar-search-splitter";
  1839.       splitter.setAttribute("resizebefore", "flex");
  1840.       splitter.setAttribute("resizeafter", "flex");
  1841.       splitter.className = "chromeclass-toolbar-additional";
  1842.     }
  1843.     urlbar.parentNode.insertBefore(splitter, ibefore);
  1844.   } else if (splitter)
  1845.     splitter.parentNode.removeChild(splitter);
  1846. }
  1847.  
  1848. var LocationBarHelpers = {
  1849.   _timeoutID: null,
  1850.  
  1851.   _searchBegin: function LocBar_searchBegin() {
  1852.     function delayedBegin(self) {
  1853.       self._timeoutID = null;
  1854.       document.getElementById("urlbar-throbber").setAttribute("busy", "true");
  1855.     }
  1856.  
  1857.     this._timeoutID = setTimeout(delayedBegin, 500, this);
  1858.   },
  1859.  
  1860.   _searchComplete: function LocBar_searchComplete() {
  1861.     // Did we finish the search before delayedBegin was invoked?
  1862.     if (this._timeoutID) {
  1863.       clearTimeout(this._timeoutID);
  1864.       this._timeoutID = null;
  1865.     }
  1866.     document.getElementById("urlbar-throbber").removeAttribute("busy");
  1867.   }
  1868. };
  1869.  
  1870. function UpdatePageProxyState()
  1871. {
  1872.   if (gURLBar && gURLBar.value != gLastValidURLStr)
  1873.     SetPageProxyState("invalid");
  1874. }
  1875.  
  1876. function SetPageProxyState(aState)
  1877. {
  1878.   if (!gURLBar)
  1879.     return;
  1880.  
  1881.   if (!gProxyFavIcon)
  1882.     gProxyFavIcon = document.getElementById("page-proxy-favicon");
  1883.  
  1884.   gURLBar.setAttribute("pageproxystate", aState);
  1885.   gProxyFavIcon.setAttribute("pageproxystate", aState);
  1886.  
  1887.   // the page proxy state is set to valid via OnLocationChange, which
  1888.   // gets called when we switch tabs.
  1889.   if (aState == "valid") {
  1890.     gLastValidURLStr = gURLBar.value;
  1891.     gURLBar.addEventListener("input", UpdatePageProxyState, false);
  1892.  
  1893.     PageProxySetIcon(gBrowser.mCurrentBrowser.mIconURL);
  1894.   } else if (aState == "invalid") {
  1895.     gURLBar.removeEventListener("input", UpdatePageProxyState, false);
  1896.     PageProxyClearIcon();
  1897.   }
  1898. }
  1899.  
  1900. function PageProxySetIcon (aURL)
  1901. {
  1902.   if (!gProxyFavIcon)
  1903.     return;
  1904.  
  1905.   if (!aURL)
  1906.     PageProxyClearIcon();
  1907.   else if (gProxyFavIcon.getAttribute("src") != aURL)
  1908.     gProxyFavIcon.setAttribute("src", aURL);
  1909. }
  1910.  
  1911. function PageProxyClearIcon ()
  1912. {
  1913.   gProxyFavIcon.removeAttribute("src");
  1914. }
  1915.  
  1916.  
  1917. function PageProxyDragGesture(aEvent)
  1918. {
  1919.   if (gProxyFavIcon.getAttribute("pageproxystate") == "valid") {
  1920.     nsDragAndDrop.startDrag(aEvent, proxyIconDNDObserver);
  1921.     return true;
  1922.   }
  1923.   return false;
  1924. }
  1925.  
  1926. function PageProxyClickHandler(aEvent)
  1927. {
  1928.   if (aEvent.button == 1 && gPrefService.getBoolPref("middlemouse.paste"))
  1929.     middleMousePaste(aEvent);
  1930. }
  1931.  
  1932. function URLBarOnInput(evt)
  1933. {
  1934.   gBrowser.userTypedValue = gURLBar.value;
  1935.   
  1936.   // If the user is interacting with the url bar, get rid of the identity popup
  1937.   var ih = getIdentityHandler();
  1938.   if(ih._identityPopup)
  1939.     ih._identityPopup.hidePopup();
  1940. }
  1941.  
  1942. function BrowserImport()
  1943. {
  1944. //@line 2273 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1945.   window.openDialog("chrome://browser/content/migration/migration.xul",
  1946.                     "migration", "modal,centerscreen,chrome,resizable=no");
  1947. //@line 2276 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  1948. }
  1949.  
  1950. /**
  1951.  * Handle command events bubbling up from error page content
  1952.  */
  1953. function BrowserOnCommand(event) {
  1954.     // Don't trust synthetic events
  1955.     if (!event.isTrusted)
  1956.       return;
  1957.  
  1958.     var ot = event.originalTarget;
  1959.     var errorDoc = ot.ownerDocument;
  1960.  
  1961.     // If the event came from an ssl error page, it is probably either the "Add
  1962.     // Exception…" or "Get me out of here!" button
  1963.     if (/^about:neterror\?e=nssBadCert/.test(errorDoc.documentURI)) {
  1964.       if (ot == errorDoc.getElementById('exceptionDialogButton')) {
  1965.         var params = { exceptionAdded : false };
  1966.         
  1967.         try {
  1968.           switch (gPrefService.getIntPref("browser.ssl_override_behavior")) {
  1969.             case 2 : // Pre-fetch & pre-populate
  1970.               params.prefetchCert = true;
  1971.             case 1 : // Pre-populate
  1972.               params.location = errorDoc.location.href;
  1973.           }
  1974.         } catch (e) {
  1975.           Components.utils.reportError("Couldn't get ssl_override pref: " + e);
  1976.         }
  1977.         
  1978.         window.openDialog('chrome://pippki/content/exceptionDialog.xul',
  1979.                           '','chrome,centerscreen,modal', params);
  1980.         
  1981.         // If the user added the exception cert, attempt to reload the page
  1982.         if (params.exceptionAdded)
  1983.           errorDoc.location.reload();
  1984.       }
  1985.       else if (ot == errorDoc.getElementById('getMeOutOfHereButton')) {
  1986.         getMeOutOfHere();
  1987.       }
  1988.     }
  1989.     else if (/^about:blocked/.test(errorDoc.documentURI)) {
  1990.       // The event came from a button on a malware/phishing block page
  1991.       
  1992.       if (ot == errorDoc.getElementById('getMeOutButton')) {
  1993.         getMeOutOfHere();
  1994.       }
  1995.       else if (ot == errorDoc.getElementById('reportButton')) {
  1996.         // This is the "Why is this site blocked" button.  For malware,
  1997.         // we can fetch a site-specific report, for phishing, we redirect
  1998.         // to the generic page describing phishing protection.
  1999.         var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"]
  2000.                        .getService(Components.interfaces.nsIURLFormatter);
  2001.         
  2002.         if (/e=malwareBlocked/.test(errorDoc.documentURI)) {
  2003.           // Get the stop badware "why is this blocked" report url,
  2004.           // append the current url, and go there.
  2005.           try {
  2006.             var reportURL = formatter.formatURLPref("browser.safebrowsing.malware.reportURL");
  2007.             reportURL += errorDoc.location.href;
  2008.             content.location = reportURL;
  2009.           } catch (e) {
  2010.             Components.utils.reportError("Couldn't get malware report URL: " + e);
  2011.           }
  2012.         }
  2013.         else if (/e=phishingBlocked/.test(errorDoc.documentURI)) {
  2014.           try {
  2015.             content.location = formatter.formatURLPref("browser.safebrowsing.warning.infoURL");
  2016.           } catch (e) {
  2017.             Components.utils.reportError("Couldn't get phishing info URL: " + e);
  2018.           }
  2019.         }
  2020.       }
  2021.       else if (ot == errorDoc.getElementById('ignoreWarningButton')) {
  2022.         // Allow users to override and continue through to the site,
  2023.         // but add a notify bar as a reminder, so that they don't lose
  2024.         // track after, e.g., tab switching.
  2025.         gBrowser.loadURIWithFlags(content.location.href,
  2026.                                   nsIWebNavigation.LOAD_FLAGS_BYPASS_CLASSIFIER,
  2027.                                   null, null, null);
  2028.         var notificationBox = gBrowser.getNotificationBox();
  2029.         notificationBox.appendNotification(
  2030.           errorDoc.title, /* Re-use the error page's title, e.g. "Reported Web Forgery!" */
  2031.           "blocked-badware-page",
  2032.           "chrome://global/skin/icons/blacklist_favicon.png",
  2033.           notificationBox.PRIORITY_CRITICAL_HIGH,
  2034.           null
  2035.         );
  2036.       }
  2037.     }
  2038. }
  2039.  
  2040. /**
  2041.  * Re-direct the browser to a known-safe page.  This function is
  2042.  * used when, for example, the user browses to a known malware page
  2043.  * and is presented with about:blocked.  The "Get me out of here!"
  2044.  * button should take the user to the default start page so that even
  2045.  * when their own homepage is infected, we can get them somewhere safe.
  2046.  */
  2047. function getMeOutOfHere() {
  2048.   // Get the start page from the *default* pref branch, not the user's
  2049.   var prefs = Cc["@mozilla.org/preferences-service;1"]
  2050.              .getService(Ci.nsIPrefService).getDefaultBranch(null);
  2051.   var url = "about:blank";
  2052.   try {
  2053.     url = prefs.getComplexValue("browser.startup.homepage",
  2054.                                 Ci.nsIPrefLocalizedString).data;
  2055.     // If url is a pipe-delimited set of pages, just take the first one.
  2056.     if (url.indexOf("|") != -1)
  2057.       url = url.split("|")[0];
  2058.   } catch(e) {
  2059.     Components.utils.reportError("Couldn't get homepage pref: " + e);
  2060.   }
  2061.   content.location = url;
  2062. }
  2063.  
  2064. function BrowserFullScreen()
  2065. {
  2066.   window.fullScreen = !window.fullScreen;
  2067. }
  2068.  
  2069. function onFullScreen()
  2070. {
  2071.   FullScreen.toggle();
  2072. }
  2073.  
  2074. function getWebNavigation()
  2075. {
  2076.   try {
  2077.     return gBrowser.webNavigation;
  2078.   } catch (e) {
  2079.     return null;
  2080.   }
  2081. }
  2082.  
  2083. function BrowserReloadWithFlags(reloadFlags)
  2084. {
  2085.   /* First, we'll try to use the session history object to reload so
  2086.    * that framesets are handled properly. If we're in a special
  2087.    * window (such as view-source) that has no session history, fall
  2088.    * back on using the web navigation's reload method.
  2089.    */
  2090.  
  2091.   var webNav = getWebNavigation();
  2092.   try {
  2093.     var sh = webNav.sessionHistory;
  2094.     if (sh)
  2095.       webNav = sh.QueryInterface(nsIWebNavigation);
  2096.   } catch (e) {
  2097.   }
  2098.  
  2099.   try {
  2100.     webNav.reload(reloadFlags);
  2101.   } catch (e) {
  2102.   }
  2103. }
  2104.  
  2105. function toggleAffectedChrome(aHide)
  2106. {
  2107.   // chrome to toggle includes:
  2108.   //   (*) menubar
  2109.   //   (*) navigation bar
  2110.   //   (*) bookmarks toolbar
  2111.   //   (*) tabstrip
  2112.   //   (*) browser messages
  2113.   //   (*) sidebar
  2114.   //   (*) find bar
  2115.   //   (*) statusbar
  2116.  
  2117.   getNavToolbox().hidden = aHide;
  2118.   if (aHide)
  2119.   {
  2120.     gChromeState = {};
  2121.     var sidebar = document.getElementById("sidebar-box");
  2122.     gChromeState.sidebarOpen = !sidebar.hidden;
  2123.     gSidebarCommand = sidebar.getAttribute("sidebarcommand");
  2124.  
  2125.     gChromeState.hadTabStrip = gBrowser.getStripVisibility();
  2126.     gBrowser.setStripVisibilityTo(false);
  2127.  
  2128.     var notificationBox = gBrowser.getNotificationBox();
  2129.     gChromeState.notificationsOpen = !notificationBox.notificationsHidden;
  2130.     notificationBox.notificationsHidden = aHide;
  2131.  
  2132.     document.getElementById("sidebar").setAttribute("src", "about:blank");
  2133.     var statusbar = document.getElementById("status-bar");
  2134.     gChromeState.statusbarOpen = !statusbar.hidden;
  2135.     statusbar.hidden = aHide;
  2136.  
  2137.     gChromeState.findOpen = !gFindBar.hidden;
  2138.     gFindBar.close();
  2139.   }
  2140.   else {
  2141.     if (gChromeState.hadTabStrip) {
  2142.       gBrowser.setStripVisibilityTo(true);
  2143.     }
  2144.  
  2145.     if (gChromeState.notificationsOpen) {
  2146.       gBrowser.getNotificationBox().notificationsHidden = aHide;
  2147.     }
  2148.  
  2149.     if (gChromeState.statusbarOpen) {
  2150.       var statusbar = document.getElementById("status-bar");
  2151.       statusbar.hidden = aHide;
  2152.     }
  2153.  
  2154.     if (gChromeState.findOpen)
  2155.       gFindBar.open();
  2156.   }
  2157.  
  2158.   if (gChromeState.sidebarOpen)
  2159.     toggleSidebar(gSidebarCommand);
  2160. }
  2161.  
  2162. function onEnterPrintPreview()
  2163. {
  2164.   gInPrintPreviewMode = true;
  2165.   toggleAffectedChrome(true);
  2166. }
  2167.  
  2168. function onExitPrintPreview()
  2169. {
  2170.   // restore chrome to original state
  2171.   gInPrintPreviewMode = false;
  2172.   FullZoom.setSettingValue();
  2173.   toggleAffectedChrome(false);
  2174. }
  2175.  
  2176. function getPPBrowser()
  2177. {
  2178.   return getBrowser();
  2179. }
  2180.  
  2181. function getMarkupDocumentViewer()
  2182. {
  2183.   return gBrowser.markupDocumentViewer;
  2184. }
  2185.  
  2186. /**
  2187.  * Content area tooltip.
  2188.  * XXX - this must move into XBL binding/equiv! Do not want to pollute
  2189.  *       browser.js with functionality that can be encapsulated into
  2190.  *       browser widget. TEMPORARY!
  2191.  *
  2192.  * NOTE: Any changes to this routine need to be mirrored in ChromeListener::FindTitleText()
  2193.  *       (located in mozilla/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp)
  2194.  *       which performs the same function, but for embedded clients that
  2195.  *       don't use a XUL/JS layer. It is important that the logic of
  2196.  *       these two routines be kept more or less in sync.
  2197.  *       (pinkerton)
  2198.  **/
  2199. function FillInHTMLTooltip(tipElement)
  2200. {
  2201.   var retVal = false;
  2202.   if (tipElement.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul")
  2203.     return retVal;
  2204.  
  2205.   const XLinkNS = "http://www.w3.org/1999/xlink";
  2206.  
  2207.  
  2208.   var titleText = null;
  2209.   var XLinkTitleText = null;
  2210.   var direction = tipElement.ownerDocument.dir;
  2211.  
  2212.   while (!titleText && !XLinkTitleText && tipElement) {
  2213.     if (tipElement.nodeType == Node.ELEMENT_NODE) {
  2214.       titleText = tipElement.getAttribute("title");
  2215.       XLinkTitleText = tipElement.getAttributeNS(XLinkNS, "title");
  2216.       var defView = tipElement.ownerDocument.defaultView;
  2217.       // XXX Work around bug 350679:
  2218.       // "Tooltips can be fired in documents with no view".
  2219.       if (!defView)
  2220.         return retVal;
  2221.       direction = defView.getComputedStyle(tipElement, "")
  2222.         .getPropertyValue("direction");
  2223.     }
  2224.     tipElement = tipElement.parentNode;
  2225.   }
  2226.  
  2227.   var tipNode = document.getElementById("aHTMLTooltip");
  2228.   tipNode.style.direction = direction;
  2229.   
  2230.   for each (var t in [titleText, XLinkTitleText]) {
  2231.     if (t && /\S/.test(t)) {
  2232.  
  2233.       // Per HTML 4.01 6.2 (CDATA section), literal CRs and tabs should be
  2234.       // replaced with spaces, and LFs should be removed entirely.
  2235.       // XXX Bug 322270: We don't preserve the result of entities like  ,
  2236.       // which should result in a line break in the tooltip, because we can't
  2237.       // distinguish that from a literal character in the source by this point.
  2238.       t = t.replace(/[\r\t]/g, ' ');
  2239.       t = t.replace(/\n/g, '');
  2240.  
  2241.       tipNode.setAttribute("label", t);
  2242.       retVal = true;
  2243.     }
  2244.   }
  2245.  
  2246.   return retVal;
  2247. }
  2248.  
  2249. var proxyIconDNDObserver = {
  2250.   onDragStart: function (aEvent, aXferData, aDragAction)
  2251.     {
  2252.       var value = content.location.href;
  2253.       var urlString = value + "\n" + content.document.title;
  2254.       var htmlString = "<a href=\"" + value + "\">" + value + "</a>";
  2255.  
  2256.       aXferData.data = new TransferData();
  2257.       aXferData.data.addDataForFlavour("text/x-moz-url", urlString);
  2258.       aXferData.data.addDataForFlavour("text/unicode", value);
  2259.       aXferData.data.addDataForFlavour("text/html", htmlString);
  2260.  
  2261.       // we're copying the URL from the proxy icon, not moving
  2262.       // we specify all of them though, because d&d sucks and OS's
  2263.       // get confused if they don't get the one they want
  2264.       aDragAction.action =
  2265.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_COPY |
  2266.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_MOVE |
  2267.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2268.     }
  2269. }
  2270.  
  2271. var homeButtonObserver = {
  2272.   onDrop: function (aEvent, aXferData, aDragSession)
  2273.     {
  2274.       var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  2275.       setTimeout(openHomeDialog, 0, url);
  2276.     },
  2277.  
  2278.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2279.     {
  2280.       var statusTextFld = document.getElementById("statusbar-display");
  2281.       statusTextFld.label = gNavigatorBundle.getString("droponhomebutton");
  2282.       aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2283.     },
  2284.  
  2285.   onDragExit: function (aEvent, aDragSession)
  2286.     {
  2287.       var statusTextFld = document.getElementById("statusbar-display");
  2288.       statusTextFld.label = "";
  2289.     },
  2290.  
  2291.   getSupportedFlavours: function ()
  2292.     {
  2293.       var flavourSet = new FlavourSet();
  2294.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2295.       flavourSet.appendFlavour("text/x-moz-url");
  2296.       flavourSet.appendFlavour("text/unicode");
  2297.       return flavourSet;
  2298.     }
  2299. }
  2300.  
  2301. function openHomeDialog(aURL)
  2302. {
  2303.   var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  2304.   var promptTitle = gNavigatorBundle.getString("droponhometitle");
  2305.   var promptMsg   = gNavigatorBundle.getString("droponhomemsg");
  2306.   var pressedVal  = promptService.confirmEx(window, promptTitle, promptMsg,
  2307.                           promptService.STD_YES_NO_BUTTONS,
  2308.                           null, null, null, null, {value:0});
  2309.  
  2310.   if (pressedVal == 0) {
  2311.     try {
  2312.       var str = Components.classes["@mozilla.org/supports-string;1"]
  2313.                           .createInstance(Components.interfaces.nsISupportsString);
  2314.       str.data = aURL;
  2315.       gPrefService.setComplexValue("browser.startup.homepage",
  2316.                                    Components.interfaces.nsISupportsString, str);
  2317.       var homeButton = document.getElementById("home-button");
  2318.       homeButton.setAttribute("tooltiptext", aURL);
  2319.     } catch (ex) {
  2320.       dump("Failed to set the home page.\n"+ex+"\n");
  2321.     }
  2322.   }
  2323. }
  2324.  
  2325. var bookmarksButtonObserver = {
  2326.   onDrop: function (aEvent, aXferData, aDragSession)
  2327.   {
  2328.     var split = aXferData.data.split("\n");
  2329.     var url = split[0];
  2330.     if (url != aXferData.data)  // do nothing if it's not a valid URL
  2331.       PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(url), split[1]);
  2332.   },
  2333.  
  2334.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2335.   {
  2336.     var statusTextFld = document.getElementById("statusbar-display");
  2337.     statusTextFld.label = gNavigatorBundle.getString("droponbookmarksbutton");
  2338.     aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2339.   },
  2340.  
  2341.   onDragExit: function (aEvent, aDragSession)
  2342.   {
  2343.     var statusTextFld = document.getElementById("statusbar-display");
  2344.     statusTextFld.label = "";
  2345.   },
  2346.  
  2347.   getSupportedFlavours: function ()
  2348.   {
  2349.     var flavourSet = new FlavourSet();
  2350.     flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2351.     flavourSet.appendFlavour("text/x-moz-url");
  2352.     flavourSet.appendFlavour("text/unicode");
  2353.     return flavourSet;
  2354.   }
  2355. }
  2356.  
  2357. var newTabButtonObserver = {
  2358.   onDragOver: function(aEvent, aFlavour, aDragSession)
  2359.     {
  2360.       var statusTextFld = document.getElementById("statusbar-display");
  2361.       statusTextFld.label = gNavigatorBundle.getString("droponnewtabbutton");
  2362.       aEvent.target.setAttribute("dragover", "true");
  2363.       return true;
  2364.     },
  2365.   onDragExit: function (aEvent, aDragSession)
  2366.     {
  2367.       var statusTextFld = document.getElementById("statusbar-display");
  2368.       statusTextFld.label = "";
  2369.       aEvent.target.removeAttribute("dragover");
  2370.     },
  2371.   onDrop: function (aEvent, aXferData, aDragSession)
  2372.     {
  2373.       var xferData = aXferData.data.split("\n");
  2374.       var draggedText = xferData[0] || xferData[1];
  2375.       var postData = {};
  2376.       var url = getShortcutOrURI(draggedText, postData);
  2377.       if (url) {
  2378.         nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2379.         // allow third-party services to fixup this URL
  2380.         openNewTabWith(url, null, postData.value, aEvent, true);
  2381.       }
  2382.     },
  2383.   getSupportedFlavours: function ()
  2384.     {
  2385.       var flavourSet = new FlavourSet();
  2386.       flavourSet.appendFlavour("text/unicode");
  2387.       flavourSet.appendFlavour("text/x-moz-url");
  2388.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2389.       return flavourSet;
  2390.     }
  2391. }
  2392.  
  2393. var newWindowButtonObserver = {
  2394.   onDragOver: function(aEvent, aFlavour, aDragSession)
  2395.     {
  2396.       var statusTextFld = document.getElementById("statusbar-display");
  2397.       statusTextFld.label = gNavigatorBundle.getString("droponnewwindowbutton");
  2398.       aEvent.target.setAttribute("dragover", "true");
  2399.       return true;
  2400.     },
  2401.   onDragExit: function (aEvent, aDragSession)
  2402.     {
  2403.       var statusTextFld = document.getElementById("statusbar-display");
  2404.       statusTextFld.label = "";
  2405.       aEvent.target.removeAttribute("dragover");
  2406.     },
  2407.   onDrop: function (aEvent, aXferData, aDragSession)
  2408.     {
  2409.       var xferData = aXferData.data.split("\n");
  2410.       var draggedText = xferData[0] || xferData[1];
  2411.       var postData = {};
  2412.       var url = getShortcutOrURI(draggedText, postData);
  2413.       if (url) {
  2414.         nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2415.         // allow third-party services to fixup this URL
  2416.         openNewWindowWith(url, null, postData.value, true);
  2417.       }
  2418.     },
  2419.   getSupportedFlavours: function ()
  2420.     {
  2421.       var flavourSet = new FlavourSet();
  2422.       flavourSet.appendFlavour("text/unicode");
  2423.       flavourSet.appendFlavour("text/x-moz-url");
  2424.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2425.       return flavourSet;
  2426.     }
  2427. }
  2428.  
  2429. var DownloadsButtonDNDObserver = {
  2430.   /////////////////////////////////////////////////////////////////////////////
  2431.   // nsDragAndDrop
  2432.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2433.   {
  2434.     var statusTextFld = document.getElementById("statusbar-display");
  2435.     statusTextFld.label = gNavigatorBundle.getString("dropondownloadsbutton");
  2436.     aDragSession.canDrop = (aFlavour.contentType == "text/x-moz-url" ||
  2437.                             aFlavour.contentType == "text/unicode");
  2438.   },
  2439.  
  2440.   onDragExit: function (aEvent, aDragSession)
  2441.   {
  2442.     var statusTextFld = document.getElementById("statusbar-display");
  2443.     statusTextFld.label = "";
  2444.   },
  2445.  
  2446.   onDrop: function (aEvent, aXferData, aDragSession)
  2447.   {
  2448.     var split = aXferData.data.split("\n");
  2449.     var url = split[0];
  2450.     if (url != aXferData.data) {  //do nothing, not a valid URL
  2451.       nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2452.  
  2453.       var name = split[1];
  2454.       saveURL(url, name, null, true, true);
  2455.     }
  2456.   },
  2457.   getSupportedFlavours: function ()
  2458.   {
  2459.     var flavourSet = new FlavourSet();
  2460.     flavourSet.appendFlavour("text/x-moz-url");
  2461.     flavourSet.appendFlavour("text/unicode");
  2462.     return flavourSet;
  2463.   }
  2464. }
  2465.  
  2466. const DOMLinkHandler = {
  2467.   handleEvent: function (event) {
  2468.     switch (event.type) {
  2469.       case "DOMLinkAdded":
  2470.         this.onLinkAdded(event);
  2471.         break;
  2472.     }
  2473.   },
  2474.   onLinkAdded: function (event) {
  2475.     var link = event.originalTarget;
  2476.     var rel = link.rel && link.rel.toLowerCase();
  2477.     if (!link || !link.ownerDocument || !rel || !link.href)
  2478.       return;
  2479.  
  2480.     var feedAdded = false;
  2481.     var iconAdded = false;
  2482.     var searchAdded = false;
  2483.     var relStrings = rel.split(/\s+/);
  2484.     var rels = {};
  2485.     for (let i = 0; i < relStrings.length; i++)
  2486.       rels[relStrings[i]] = true;
  2487.  
  2488.     for (let relVal in rels) {
  2489.       switch (relVal) {
  2490.         case "feed":
  2491.         case "alternate":
  2492.           if (!feedAdded) {
  2493.             if (!rels.feed && rels.alternate && rels.stylesheet)
  2494.               break;
  2495.  
  2496.             var feed = { title: link.title, href: link.href, type: link.type };
  2497.             if (isValidFeed(feed, link.ownerDocument.nodePrincipal, rels.feed)) {
  2498.               FeedHandler.addFeed(feed, link.ownerDocument);
  2499.               feedAdded = true;
  2500.             }
  2501.           }
  2502.           break;
  2503.         case "icon":
  2504.           if (!iconAdded) {
  2505.             if (!gPrefService.getBoolPref("browser.chrome.site_icons"))
  2506.               break;
  2507.  
  2508.             var targetDoc = link.ownerDocument;
  2509.             var ios = Cc["@mozilla.org/network/io-service;1"].
  2510.                       getService(Ci.nsIIOService);
  2511.             var uri = ios.newURI(link.href, targetDoc.characterSet, null);
  2512.  
  2513.             if (gBrowser.isFailedIcon(uri))
  2514.               break;
  2515.  
  2516.             // Verify that the load of this icon is legal.
  2517.             // error pages can load their favicon, to be on the safe side,
  2518.             // only allow chrome:// favicons
  2519.             const aboutNeterr = /^about:neterror\?/;
  2520.             const aboutBlocked = /^about:blocked\?/;
  2521.             if (!(aboutNeterr.test(targetDoc.documentURI) ||
  2522.                   aboutBlocked.test(targetDoc.documentURI)) ||
  2523.                 !uri.schemeIs("chrome")) {
  2524.               var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].
  2525.                         getService(Ci.nsIScriptSecurityManager);
  2526.               try {
  2527.                 ssm.checkLoadURIWithPrincipal(targetDoc.nodePrincipal, uri,
  2528.                                               Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT);
  2529.               } catch(e) {
  2530.                 break;
  2531.               }
  2532.             }
  2533.  
  2534.             try {
  2535.               var contentPolicy = Cc["@mozilla.org/layout/content-policy;1"].
  2536.                                   getService(Ci.nsIContentPolicy);
  2537.             } catch(e) {
  2538.               break; // Refuse to load if we can't do a security check.
  2539.             }
  2540.  
  2541.             // Security says okay, now ask content policy
  2542.             if (contentPolicy.shouldLoad(Ci.nsIContentPolicy.TYPE_IMAGE,
  2543.                                          uri, targetDoc.documentURIObject,
  2544.                                          link, link.type, null)
  2545.                                          != Ci.nsIContentPolicy.ACCEPT)
  2546.               break;
  2547.  
  2548.             var browserIndex = gBrowser.getBrowserIndexForDocument(targetDoc);
  2549.             // no browser? no favicon.
  2550.             if (browserIndex == -1)
  2551.               break;
  2552.  
  2553.             var tab = gBrowser.mTabContainer.childNodes[browserIndex];
  2554.             gBrowser.setIcon(tab, link.href);
  2555.             iconAdded = true;
  2556.           }
  2557.           break;
  2558.         case "search":
  2559.           if (!searchAdded) {
  2560.             var type = link.type && link.type.toLowerCase();
  2561.             type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
  2562.  
  2563.             if (type == "application/opensearchdescription+xml" && link.title &&
  2564.                 /^(?:https?|ftp):/i.test(link.href)) {
  2565.               var engine = { title: link.title, href: link.href };
  2566.               BrowserSearch.addEngine(engine, link.ownerDocument);
  2567.               searchAdded = true;
  2568.             }
  2569.           }
  2570.           break;
  2571.       }
  2572.     }
  2573.   }
  2574. }
  2575.  
  2576. const BrowserSearch = {
  2577.   addEngine: function(engine, targetDoc) {
  2578.     if (!this.searchBar)
  2579.       return;
  2580.  
  2581.     var browser = gBrowser.getBrowserForDocument(targetDoc);
  2582.  
  2583.     // Check to see whether we've already added an engine with this title
  2584.     if (browser.engines) {
  2585.       if (browser.engines.some(function (e) e.title == engine.title))
  2586.         return;
  2587.     }
  2588.  
  2589.     // Append the URI and an appropriate title to the browser data.
  2590.     var iconURL = null;
  2591.     if (gBrowser.shouldLoadFavIcon(browser.currentURI))
  2592.       iconURL = browser.currentURI.prePath + "/favicon.ico";
  2593.  
  2594.     var hidden = false;
  2595.     // If this engine (identified by title) is already in the list, add it
  2596.     // to the list of hidden engines rather than to the main list.
  2597.     // XXX This will need to be changed when engines are identified by URL;
  2598.     // see bug 335102.
  2599.     var searchService = Cc["@mozilla.org/browser/search-service;1"].
  2600.                         getService(Ci.nsIBrowserSearchService);
  2601.     if (searchService.getEngineByName(engine.title))
  2602.       hidden = true;
  2603.  
  2604.     var engines = (hidden ? browser.hiddenEngines : browser.engines) || [];
  2605.  
  2606.     engines.push({ uri: engine.href,
  2607.                    title: engine.title,
  2608.                    icon: iconURL });
  2609.  
  2610.     if (hidden)
  2611.       browser.hiddenEngines = engines;
  2612.     else {
  2613.       browser.engines = engines;
  2614.       if (browser == gBrowser.mCurrentBrowser)
  2615.         this.updateSearchButton();
  2616.     }
  2617.   },
  2618.  
  2619.   /**
  2620.    * Update the browser UI to show whether or not additional engines are 
  2621.    * available when a page is loaded or the user switches tabs to a page that 
  2622.    * has search engines.
  2623.    */
  2624.   updateSearchButton: function() {
  2625.     var searchBar = this.searchBar;
  2626.     
  2627.     // The search bar binding might not be applied even though the element is
  2628.     // in the document (e.g. when the navigation toolbar is hidden), so check
  2629.     // for .searchButton specifically.
  2630.     if (!searchBar || !searchBar.searchButton)
  2631.       return;
  2632.  
  2633.     var engines = gBrowser.mCurrentBrowser.engines;
  2634.     if (engines && engines.length > 0)
  2635.       searchBar.searchButton.setAttribute("addengines", "true");
  2636.     else
  2637.       searchBar.searchButton.removeAttribute("addengines");
  2638.   },
  2639.  
  2640.   /**
  2641.    * Gives focus to the search bar, if it is present on the toolbar, or loads
  2642.    * the default engine's search form otherwise. For Mac, opens a new window
  2643.    * or focuses an existing window, if necessary.
  2644.    */
  2645.   webSearch: function BrowserSearch_webSearch() {
  2646. //@line 2997 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2647.     if (window.fullScreen)
  2648.       FullScreen.mouseoverToggle(true);
  2649.  
  2650.     var searchBar = this.searchBar;
  2651.     if (isElementVisible(searchBar)) {
  2652.       searchBar.select();
  2653.       searchBar.focus();
  2654.     } else {
  2655.       var ss = Cc["@mozilla.org/browser/search-service;1"].
  2656.                getService(Ci.nsIBrowserSearchService);
  2657.       var searchForm = ss.defaultEngine.searchForm;
  2658.       loadURI(searchForm, null, null, false);
  2659.     }
  2660.   },
  2661.  
  2662.   /**
  2663.    * Loads a search results page, given a set of search terms. Uses the current
  2664.    * engine if the search bar is visible, or the default engine otherwise.
  2665.    *
  2666.    * @param searchText
  2667.    *        The search terms to use for the search.
  2668.    *
  2669.    * @param useNewTab
  2670.    *        Boolean indicating whether or not the search should load in a new
  2671.    *        tab.
  2672.    */
  2673.   loadSearch: function BrowserSearch_search(searchText, useNewTab) {
  2674.     var ss = Cc["@mozilla.org/browser/search-service;1"].
  2675.              getService(Ci.nsIBrowserSearchService);
  2676.     var engine;
  2677.   
  2678.     // If the search bar is visible, use the current engine, otherwise, fall
  2679.     // back to the default engine.
  2680.     if (isElementVisible(this.searchBar))
  2681.       engine = ss.currentEngine;
  2682.     else
  2683.       engine = ss.defaultEngine;
  2684.   
  2685.     var submission = engine.getSubmission(searchText, null); // HTML response
  2686.  
  2687.     // getSubmission can return null if the engine doesn't have a URL
  2688.     // with a text/html response type.  This is unlikely (since
  2689.     // SearchService._addEngineToStore() should fail for such an engine),
  2690.     // but let's be on the safe side.
  2691.     if (!submission)
  2692.       return;
  2693.   
  2694.     if (useNewTab) {
  2695.       getBrowser().loadOneTab(submission.uri.spec, null, null,
  2696.                               submission.postData, null, false);
  2697.     } else
  2698.       loadURI(submission.uri.spec, null, submission.postData, false);
  2699.   },
  2700.  
  2701.   /**
  2702.    * Returns the search bar element if it is present in the toolbar, null otherwise.
  2703.    */
  2704.   get searchBar() {
  2705.     return document.getElementById("searchbar");
  2706.   },
  2707.  
  2708.   loadAddEngines: function BrowserSearch_loadAddEngines() {
  2709.     var newWindowPref = gPrefService.getIntPref("browser.link.open_newwindow");
  2710.     var where = newWindowPref == 3 ? "tab" : "window";
  2711.     var regionBundle = document.getElementById("bundle_browser_region");
  2712.     var searchEnginesURL = formatURL("browser.search.searchEnginesURL", true);
  2713.     openUILinkIn(searchEnginesURL, where);
  2714.   }
  2715. }
  2716.  
  2717. function FillHistoryMenu(aParent) {
  2718.   // Remove old entries if any
  2719.   var children = aParent.childNodes;
  2720.   for (var i = children.length - 1; i >= 0; --i) {
  2721.     if (children[i].hasAttribute("index"))
  2722.       aParent.removeChild(children[i]);
  2723.   }
  2724.  
  2725.   var webNav = getWebNavigation();
  2726.   var sessionHistory = webNav.sessionHistory;
  2727.   var bundle_browser = document.getElementById("bundle_browser");
  2728.  
  2729.   var count = sessionHistory.count;
  2730.   var index = sessionHistory.index;
  2731.   var end;
  2732.  
  2733.   if (count <= 1) // don't display the popup for a single item
  2734.     return false;
  2735.  
  2736.   var half_length = Math.floor(MAX_HISTORY_MENU_ITEMS / 2);
  2737.   var start = Math.max(index - half_length, 0);
  2738.   end = Math.min(start == 0 ? MAX_HISTORY_MENU_ITEMS : index + half_length + 1, count);
  2739.   if (end == count)
  2740.     start = Math.max(count - MAX_HISTORY_MENU_ITEMS, 0);
  2741.  
  2742.   var tooltipBack = bundle_browser.getString("tabHistory.goBack");
  2743.   var tooltipCurrent = bundle_browser.getString("tabHistory.current");
  2744.   var tooltipForward = bundle_browser.getString("tabHistory.goForward");
  2745.  
  2746.   for (var j = end - 1; j >= start; j--) {
  2747.     let item = document.createElement("menuitem");
  2748.     let entry = sessionHistory.getEntryAtIndex(j, false);
  2749.  
  2750.     item.setAttribute("label", entry.title || entry.URI.spec);
  2751.     item.setAttribute("index", j);
  2752.  
  2753.     if (j != index) {
  2754.       try {
  2755.         let iconURL = Cc["@mozilla.org/browser/favicon-service;1"]
  2756.                          .getService(Ci.nsIFaviconService)
  2757.                          .getFaviconForPage(entry.URI).spec;
  2758.         item.style.listStyleImage = "url(" + iconURL + ")";
  2759.       } catch (ex) {}
  2760.     }
  2761.  
  2762.     if (j < index) {
  2763.       item.className = "unified-nav-back menuitem-iconic";
  2764.       item.setAttribute("tooltiptext", tooltipBack);
  2765.     } else if (j == index) {
  2766.       item.setAttribute("type", "radio");
  2767.       item.setAttribute("checked", "true");
  2768.       item.className = "unified-nav-current";
  2769.       item.setAttribute("tooltiptext", tooltipCurrent);
  2770.     } else {
  2771.       item.className = "unified-nav-forward menuitem-iconic";
  2772.       item.setAttribute("tooltiptext", tooltipForward);
  2773.     }
  2774.  
  2775.     aParent.appendChild(item);
  2776.   }
  2777.   return true;
  2778. }
  2779.  
  2780. function addToUrlbarHistory(aUrlToAdd)
  2781. {
  2782.   if (!aUrlToAdd)
  2783.      return;
  2784.   if (aUrlToAdd.search(/[\x00-\x1F]/) != -1) // don't store bad URLs
  2785.      return;
  2786.  
  2787.    try {
  2788.      if (aUrlToAdd.indexOf(" ") == -1) {
  2789.        PlacesUIUtils.markPageAsTyped(aUrlToAdd);
  2790.      }
  2791.    }
  2792.    catch(ex) {
  2793.    }
  2794. }
  2795.  
  2796. function toJavaScriptConsole()
  2797. {
  2798.   toOpenWindowByType("global:console", "chrome://global/content/console.xul");
  2799. }
  2800.  
  2801. function BrowserDownloadsUI()
  2802. {
  2803.   Cc["@mozilla.org/download-manager-ui;1"].
  2804.   getService(Ci.nsIDownloadManagerUI).show(window);
  2805. }
  2806.  
  2807. function toOpenWindowByType(inType, uri, features)
  2808. {
  2809.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  2810.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  2811.   var topWindow = windowManagerInterface.getMostRecentWindow(inType);
  2812.  
  2813.   if (topWindow)
  2814.     topWindow.focus();
  2815.   else if (features)
  2816.     window.open(uri, "_blank", features);
  2817.   else
  2818.     window.open(uri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar");
  2819. }
  2820.  
  2821. function toOpenDialogByTypeAndUrl(inType, relatedUrl, windowUri, features, extraArgument)
  2822. {
  2823.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  2824.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  2825.   var windows = windowManagerInterface.getEnumerator(inType);
  2826.  
  2827.   // Check for windows matching the url
  2828.   while (windows.hasMoreElements()) {
  2829.     var currentWindow = windows.getNext();
  2830.     if (currentWindow.document.documentElement.getAttribute("relatedUrl") == relatedUrl) {
  2831.         currentWindow.focus();
  2832.         return;
  2833.     }
  2834.   }
  2835.  
  2836.   // We didn't find a matching window, so open a new one.
  2837.   if (features)
  2838.     window.openDialog(windowUri, "_blank", features, extraArgument);
  2839.   else
  2840.     window.openDialog(windowUri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar", extraArgument);
  2841. }
  2842.  
  2843. function OpenBrowserWindow()
  2844. {
  2845.   var charsetArg = new String();
  2846.   var handler = Components.classes["@mozilla.org/browser/clh;1"]
  2847.                           .getService(Components.interfaces.nsIBrowserHandler);
  2848.   var defaultArgs = handler.defaultArgs;
  2849.   var wintype = document.documentElement.getAttribute('windowtype');
  2850.  
  2851.   // if and only if the current window is a browser window and it has a document with a character
  2852.   // set, then extract the current charset menu setting from the current document and use it to
  2853.   // initialize the new browser window...
  2854.   var win;
  2855.   if (window && (wintype == "navigator:browser") && window.content && window.content.document)
  2856.   {
  2857.     var DocCharset = window.content.document.characterSet;
  2858.     charsetArg = "charset="+DocCharset;
  2859.  
  2860.     //we should "inherit" the charset menu setting in a new window
  2861.     win = window.openDialog("chrome://browser/content/", "_blank", "chrome,all,dialog=no", defaultArgs, charsetArg);
  2862.   }
  2863.   else // forget about the charset information.
  2864.   {
  2865.     win = window.openDialog("chrome://browser/content/", "_blank", "chrome,all,dialog=no", defaultArgs);
  2866.   }
  2867.  
  2868.   return win;
  2869. }
  2870.  
  2871. function BrowserCustomizeToolbar()
  2872. {
  2873.   // Disable the toolbar context menu items
  2874.   var menubar = document.getElementById("main-menubar");
  2875.   for (var i = 0; i < menubar.childNodes.length; ++i)
  2876.     menubar.childNodes[i].setAttribute("disabled", true);
  2877.  
  2878.   var cmd = document.getElementById("cmd_CustomizeToolbars");
  2879.   cmd.setAttribute("disabled", "true");
  2880.  
  2881.   var splitter = document.getElementById("urlbar-search-splitter");
  2882.   if (splitter)
  2883.     splitter.parentNode.removeChild(splitter);
  2884.  
  2885.   var customizeURL = "chrome://global/content/customizeToolbar.xul";
  2886. //@line 3254 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2887.   window.openDialog(customizeURL,
  2888.                     "CustomizeToolbar",
  2889.                     "chrome,all,dependent",
  2890.                     getNavToolbox());
  2891. //@line 3259 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2892. }
  2893.  
  2894. function BrowserToolboxCustomizeDone(aToolboxChanged)
  2895. {
  2896. //@line 3267 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2897.  
  2898.   // Update global UI elements that may have been added or removed
  2899.   if (aToolboxChanged) {
  2900.     gURLBar = document.getElementById("urlbar");
  2901.     gProxyFavIcon = document.getElementById("page-proxy-favicon");
  2902.     gHomeButton.updateTooltip();
  2903.     gIdentityHandler._cacheElements();
  2904.     window.XULBrowserWindow.init();
  2905.  
  2906.     var backForwardDropmarker = document.getElementById("back-forward-dropmarker");
  2907.     if (backForwardDropmarker)
  2908.       backForwardDropmarker.disabled =
  2909.         document.getElementById('Browser:Back').hasAttribute('disabled') &&
  2910.         document.getElementById('Browser:Forward').hasAttribute('disabled');
  2911.  
  2912.     // support downgrading to Firefox 2.0
  2913.     var navBar = document.getElementById("nav-bar");
  2914.     navBar.setAttribute("currentset",
  2915.                         navBar.getAttribute("currentset")
  2916.                               .replace("unified-back-forward-button",
  2917.                                 "unified-back-forward-button,back-button,forward-button"));
  2918.     document.persist(navBar.id, "currentset");
  2919.  
  2920. //@line 3291 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2921.     updateEditUIVisibility();
  2922. //@line 3293 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2923.   }
  2924.  
  2925.   UpdateUrlbarSearchSplitterState();
  2926.  
  2927.   gHomeButton.updatePersonalToolbarStyle();
  2928.  
  2929.   // Update the urlbar
  2930.   if (gURLBar) {
  2931.     URLBarSetURI();
  2932.     XULBrowserWindow.asyncUpdateUI();
  2933.     PlacesStarButton.updateState();
  2934.   }
  2935.  
  2936.   // Re-enable parts of the UI we disabled during the dialog
  2937.   var menubar = document.getElementById("main-menubar");
  2938.   for (var i = 0; i < menubar.childNodes.length; ++i)
  2939.     menubar.childNodes[i].setAttribute("disabled", false);
  2940.   var cmd = document.getElementById("cmd_CustomizeToolbars");
  2941.   cmd.removeAttribute("disabled");
  2942.  
  2943.   // XXXmano bug 287105: wallpaper to bug 309953,
  2944.   // the reload button isn't in sync with the reload command.
  2945.   var reloadButton = document.getElementById("reload-button");
  2946.   if (reloadButton) {
  2947.     reloadButton.disabled =
  2948.       document.getElementById("Browser:Reload").getAttribute("disabled") == "true";
  2949.   }
  2950.  
  2951. //@line 3326 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2952.  
  2953.   initBookmarksToolbar();
  2954.  
  2955. //@line 3330 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2956.   // XXX Shouldn't have to do this, but I do
  2957.   window.focus();
  2958. //@line 3333 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2959. }
  2960.  
  2961. function BrowserToolboxCustomizeChange() {
  2962.   gHomeButton.updatePersonalToolbarStyle();
  2963. }
  2964.  
  2965. /**
  2966.  * Update the global flag that tracks whether or not any edit UI (the Edit menu,
  2967.  * edit-related items in the context menu, and edit-related toolbar buttons
  2968.  * is visible, then update the edit commands' enabled state accordingly.  We use
  2969.  * this flag to skip updating the edit commands on focus or selection changes
  2970.  * when no UI is visible to improve performance (including pageload performance,
  2971.  * since focus changes when you load a new page).
  2972.  *
  2973.  * If UI is visible, we use goUpdateGlobalEditMenuItems to set the commands'
  2974.  * enabled state so the UI will reflect it appropriately.
  2975.  * 
  2976.  * If the UI isn't visible, we enable all edit commands so keyboard shortcuts
  2977.  * still work and just lazily disable them as needed when the user presses a
  2978.  * shortcut.
  2979.  *
  2980.  * This doesn't work on Mac, since Mac menus flash when users press their
  2981.  * keyboard shortcuts, so edit UI is essentially always visible on the Mac,
  2982.  * and we need to always update the edit commands.  Thus on Mac this function
  2983.  * is a no op.
  2984.  */
  2985. function updateEditUIVisibility()
  2986. {
  2987. //@line 3362 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  2988.   let editMenuPopupState = document.getElementById("menu_EditPopup").state;
  2989.   let contextMenuPopupState = document.getElementById("contentAreaContextMenu").state;
  2990.   let placesContextMenuPopupState = document.getElementById("placesContext").state;
  2991.  
  2992.   // The UI is visible if the Edit menu is opening or open, if the context menu
  2993.   // is open, or if the toolbar has been customized to include the Cut, Copy,
  2994.   // or Paste toolbar buttons.
  2995.   gEditUIVisible = editMenuPopupState == "showing" ||
  2996.                    editMenuPopupState == "open" ||
  2997.                    contextMenuPopupState == "showing" ||
  2998.                    contextMenuPopupState == "open" ||
  2999.                    placesContextMenuPopupState == "showing" ||
  3000.                    placesContextMenuPopupState == "open" ||
  3001.                    document.getElementById("cut-button") ||
  3002.                    document.getElementById("copy-button") ||
  3003.                    document.getElementById("paste-button") ? true : false;
  3004.  
  3005.   // If UI is visible, update the edit commands' enabled state to reflect
  3006.   // whether or not they are actually enabled for the current focus/selection.
  3007.   if (gEditUIVisible)
  3008.     goUpdateGlobalEditMenuItems();
  3009.  
  3010.   // Otherwise, enable all commands, so that keyboard shortcuts still work,
  3011.   // then lazily determine their actual enabled state when the user presses
  3012.   // a keyboard shortcut.
  3013.   else {
  3014.     goSetCommandEnabled("cmd_undo", true);
  3015.     goSetCommandEnabled("cmd_redo", true);
  3016.     goSetCommandEnabled("cmd_cut", true);
  3017.     goSetCommandEnabled("cmd_copy", true);
  3018.     goSetCommandEnabled("cmd_paste", true);
  3019.     goSetCommandEnabled("cmd_selectAll", true);
  3020.     goSetCommandEnabled("cmd_delete", true);
  3021.     goSetCommandEnabled("cmd_switchTextDirection", true);
  3022.   }
  3023. //@line 3398 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  3024. }
  3025.  
  3026. var FullScreen =
  3027. {
  3028.   _XULNS: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
  3029.   toggle: function()
  3030.   {
  3031.     // show/hide all menubars, toolbars, and statusbars (except the full screen toolbar)
  3032.     this.showXULChrome("toolbar", window.fullScreen);
  3033.     this.showXULChrome("statusbar", window.fullScreen);
  3034.     document.getElementById("fullScreenItem").setAttribute("checked", !window.fullScreen);
  3035.  
  3036.     var fullScrToggler = document.getElementById("fullscr-toggler");
  3037.     if (!window.fullScreen) {
  3038.       // Add a tiny toolbar to receive mouseover and dragenter events, and provide affordance.
  3039.       // This will help simulate the "collapse" metaphor while also requiring less code and
  3040.       // events than raw listening of mouse coords.
  3041.       if (!fullScrToggler) {
  3042.         fullScrToggler = document.createElement("toolbar");
  3043.         fullScrToggler.id = "fullscr-toggler";
  3044.         fullScrToggler.setAttribute("customizable", "false");
  3045.         fullScrToggler.setAttribute("moz-collapsed", "true");
  3046.         var navBar = document.getElementById("nav-bar");
  3047.         navBar.parentNode.insertBefore(fullScrToggler, navBar);
  3048.       }
  3049.       fullScrToggler.addEventListener("mouseover", this._expandCallback, false);
  3050.       fullScrToggler.addEventListener("dragenter", this._expandCallback, false);
  3051.  
  3052.       if (gPrefService.getBoolPref("browser.fullscreen.autohide"))
  3053.         gBrowser.mPanelContainer.addEventListener("mousemove",
  3054.                                                   this._collapseCallback, false);
  3055.  
  3056.       document.addEventListener("keypress", this._keyToggleCallback, false);
  3057.       document.addEventListener("popupshown", this._setPopupOpen, false);
  3058.       document.addEventListener("popuphidden", this._setPopupOpen, false);
  3059.       this._shouldAnimate = true;
  3060.       this.mouseoverToggle(false);
  3061.  
  3062.       // Autohide prefs
  3063.       gPrefService.addObserver("browser.fullscreen", this, false);
  3064.     }
  3065.     else {
  3066.       document.removeEventListener("keypress", this._keyToggleCallback, false);
  3067.       document.removeEventListener("popupshown", this._setPopupOpen, false);
  3068.       document.removeEventListener("popuphidden", this._setPopupOpen, false);
  3069.       gPrefService.removeObserver("browser.fullscreen", this);
  3070.  
  3071.       if (fullScrToggler) {
  3072.         fullScrToggler.removeEventListener("mouseover", this._expandCallback, false);
  3073.         fullScrToggler.removeEventListener("dragenter", this._expandCallback, false);
  3074.       }
  3075.  
  3076.       // The user may quit fullscreen during an animation
  3077.       clearInterval(this._animationInterval);
  3078.       clearTimeout(this._animationTimeout);
  3079.       getNavToolbox().style.marginTop = "0px";
  3080.       if (this._isChromeCollapsed)
  3081.         this.mouseoverToggle(true);
  3082.       this._isAnimating = false;
  3083.       // This is needed if they use the context menu to quit fullscreen
  3084.       this._isPopupOpen = false;
  3085.  
  3086.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  3087.                                                    this._collapseCallback, false);
  3088.     }
  3089.   },
  3090.  
  3091.   observe: function(aSubject, aTopic, aData)
  3092.   {
  3093.     if (aData == "browser.fullscreen.autohide") {
  3094.       if (gPrefService.getBoolPref("browser.fullscreen.autohide")) {
  3095.         gBrowser.mPanelContainer.addEventListener("mousemove",
  3096.                                                   this._collapseCallback, false);
  3097.       }
  3098.       else {
  3099.         gBrowser.mPanelContainer.removeEventListener("mousemove",
  3100.                                                      this._collapseCallback, false);
  3101.       }
  3102.     }
  3103.   },
  3104.  
  3105.   // Event callbacks
  3106.   _expandCallback: function()
  3107.   {
  3108.     FullScreen.mouseoverToggle(true);
  3109.   },
  3110.   _collapseCallback: function()
  3111.   {
  3112.     FullScreen.mouseoverToggle(false);
  3113.   },
  3114.   _keyToggleCallback: function(aEvent)
  3115.   {
  3116.     // if we can use the keyboard (eg Ctrl+L or Ctrl+E) to open the toolbars, we
  3117.     // should provide a way to collapse them too.
  3118.     if (aEvent.keyCode == aEvent.DOM_VK_ESCAPE) {
  3119.       FullScreen._shouldAnimate = false;
  3120.       FullScreen.mouseoverToggle(false, true);
  3121.     }
  3122.     // F6 is another shortcut to the address bar, but its not covered in OpenLocation()
  3123.     else if (aEvent.keyCode == aEvent.DOM_VK_F6)
  3124.       FullScreen.mouseoverToggle(true);
  3125.   },
  3126.  
  3127.   // Checks whether we are allowed to collapse the chrome
  3128.   _isPopupOpen: false,
  3129.   _isChromeCollapsed: false,
  3130.   _safeToCollapse: function(forceHide)
  3131.   {
  3132.     if (!gPrefService.getBoolPref("browser.fullscreen.autohide"))
  3133.       return false;
  3134.  
  3135.     // a popup menu is open in chrome: don't collapse chrome
  3136.     if (!forceHide && this._isPopupOpen)
  3137.       return false;
  3138.  
  3139.     // a textbox in chrome is focused (location bar anyone?): don't collapse chrome
  3140.     if (document.commandDispatcher.focusedElement &&
  3141.         document.commandDispatcher.focusedElement.ownerDocument == document &&
  3142.         document.commandDispatcher.focusedElement.localName == "input") {
  3143.       if (forceHide)
  3144.         // hidden textboxes that still have focus are bad bad bad
  3145.         document.commandDispatcher.focusedElement.blur();
  3146.       else
  3147.         return false;
  3148.     }
  3149.     return true;
  3150.   },
  3151.  
  3152.   _setPopupOpen: function(aEvent)
  3153.   {
  3154.     // Popups should only veto chrome collapsing if they were opened when the chrome was not collapsed.
  3155.     // Otherwise, they would not affect chrome and the user would expect the chrome to go away.
  3156.     // e.g. we wouldn't want the autoscroll icon firing this event, so when the user
  3157.     // toggles chrome when moving mouse to the top, it doesn't go away again.
  3158.     if (aEvent.type == "popupshown" && !FullScreen._isChromeCollapsed &&
  3159.         aEvent.target.localName != "tooltip" && aEvent.target.localName != "window")
  3160.       FullScreen._isPopupOpen = true;
  3161.     else if (aEvent.type == "popuphidden" && aEvent.target.localName != "tooltip" &&
  3162.              aEvent.target.localName != "window")
  3163.       FullScreen._isPopupOpen = false;
  3164.   },
  3165.  
  3166.   // Autohide helpers for the context menu item
  3167.   getAutohide: function(aItem)
  3168.   {
  3169.     aItem.setAttribute("checked", gPrefService.getBoolPref("browser.fullscreen.autohide"));
  3170.   },
  3171.   setAutohide: function()
  3172.   {
  3173.     gPrefService.setBoolPref("browser.fullscreen.autohide", !gPrefService.getBoolPref("browser.fullscreen.autohide"));
  3174.   },
  3175.  
  3176.   // Animate the toolbars disappearing
  3177.   _shouldAnimate: true,
  3178.   _isAnimating: false,
  3179.   _animationTimeout: null,
  3180.   _animationInterval: null,
  3181.   _animateUp: function()
  3182.   {
  3183.     // check again, the user may have done something before the animation was due to start
  3184.     if (!window.fullScreen || !FullScreen._safeToCollapse(false)) {
  3185.       FullScreen._isAnimating = false;
  3186.       FullScreen._shouldAnimate = true;
  3187.       return;
  3188.     }
  3189.  
  3190.     var navToolbox = getNavToolbox();
  3191.     var animateFrameAmount = 2;
  3192.     function animateUpFrame() {
  3193.       animateFrameAmount *= 2;
  3194.       if (animateFrameAmount >=
  3195.           (navToolbox.boxObject.height + gBrowser.mStrip.boxObject.height)) {
  3196.         // We've animated enough
  3197.         clearInterval(FullScreen._animationInterval);
  3198.         navToolbox.style.marginTop = "0px";
  3199.         FullScreen._isAnimating = false;
  3200.         FullScreen._shouldAnimate = false; // Just to make sure
  3201.         FullScreen.mouseoverToggle(false);
  3202.         return;
  3203.       }
  3204.       navToolbox.style.marginTop = (animateFrameAmount * -1) + "px";
  3205.     }
  3206.  
  3207.     FullScreen._animationInterval = setInterval(animateUpFrame, 70);
  3208.   },
  3209.  
  3210.   mouseoverToggle: function(aShow, forceHide)
  3211.   {
  3212.     // Don't do anything if:
  3213.     // a) we're already in the state we want,
  3214.     // b) we're animating and will become collapsed soon, or
  3215.     // c) we can't collapse because it would be undesirable right now
  3216.     if (aShow != this._isChromeCollapsed || (!aShow && this._isAnimating) ||
  3217.         (!aShow && !this._safeToCollapse(forceHide)))
  3218.       return;
  3219.  
  3220.     // browser.fullscreen.animateUp
  3221.     // 0 - never animate up
  3222.     // 1 - animate only for first collapse after entering fullscreen (default for perf's sake)
  3223.     // 2 - animate every time it collapses
  3224.     if (gPrefService.getIntPref("browser.fullscreen.animateUp") == 0)
  3225.       this._shouldAnimate = false;
  3226.  
  3227.     if (!aShow && this._shouldAnimate) {
  3228.       this._isAnimating = true;
  3229.       this._shouldAnimate = false;
  3230.       this._animationTimeout = setTimeout(this._animateUp, 800);
  3231.       return;
  3232.     }
  3233.  
  3234.     // The chrome is collapsed so don't spam needless mousemove events
  3235.     if (aShow) {
  3236.       gBrowser.mPanelContainer.addEventListener("mousemove",
  3237.                                                 this._collapseCallback, false);
  3238.     }
  3239.     else {
  3240.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  3241.                                                    this._collapseCallback, false);
  3242.     }
  3243.  
  3244.     gBrowser.mStrip.setAttribute("moz-collapsed", !aShow);
  3245.     var allFSToolbars = document.getElementsByTagNameNS(this._XULNS, "toolbar");
  3246.     for (var i = 0; i < allFSToolbars.length; i++) {
  3247.       if (allFSToolbars[i].getAttribute("fullscreentoolbar") == "true")
  3248.         allFSToolbars[i].setAttribute("moz-collapsed", !aShow);
  3249.     }
  3250.     document.getElementById("fullscr-toggler").setAttribute("moz-collapsed", aShow);
  3251.     this._isChromeCollapsed = !aShow;
  3252.     if (gPrefService.getIntPref("browser.fullscreen.animateUp") == 2)
  3253.       this._shouldAnimate = true;
  3254.   },
  3255.  
  3256.   showXULChrome: function(aTag, aShow)
  3257.   {
  3258.     var els = document.getElementsByTagNameNS(this._XULNS, aTag);
  3259.  
  3260.     for (var i = 0; i < els.length; ++i) {
  3261.       // XXX don't interfere with previously collapsed toolbars
  3262.       if (els[i].getAttribute("fullscreentoolbar") == "true") {
  3263.         if (!aShow) {
  3264.  
  3265.           var toolbarMode = els[i].getAttribute("mode");
  3266.           if (toolbarMode != "text") {
  3267.             els[i].setAttribute("saved-mode", toolbarMode);
  3268.             els[i].setAttribute("saved-iconsize",
  3269.                                 els[i].getAttribute("iconsize"));
  3270.             els[i].setAttribute("mode", "icons");
  3271.             els[i].setAttribute("iconsize", "small");
  3272.           }
  3273.  
  3274.           // Give the main nav bar the fullscreen context menu, otherwise remove it
  3275.           // to prevent breakage
  3276.           els[i].setAttribute("saved-context",
  3277.                               els[i].getAttribute("context"));
  3278.           if (els[i].id == "nav-bar")
  3279.             els[i].setAttribute("context", "autohide-context");
  3280.           else
  3281.             els[i].removeAttribute("context");
  3282.  
  3283.           // Set the inFullscreen attribute to allow specific styling
  3284.           // in fullscreen mode
  3285.           els[i].setAttribute("inFullscreen", true);
  3286.         }
  3287.         else {
  3288.           function restoreAttr(attrName) {
  3289.             var savedAttr = "saved-" + attrName;
  3290.             if (els[i].hasAttribute(savedAttr)) {
  3291.               els[i].setAttribute(attrName, els[i].getAttribute(savedAttr));
  3292.               els[i].removeAttribute(savedAttr);
  3293.             }
  3294.           }
  3295.  
  3296.           restoreAttr("mode");
  3297.           restoreAttr("iconsize");
  3298.           restoreAttr("context");
  3299.  
  3300.           els[i].removeAttribute("inFullscreen");
  3301.         }
  3302.       } else {
  3303.         // use moz-collapsed so it doesn't persist hidden/collapsed,
  3304.         // so that new windows don't have missing toolbars
  3305.         if (aShow)
  3306.           els[i].removeAttribute("moz-collapsed");
  3307.         else
  3308.           els[i].setAttribute("moz-collapsed", "true");
  3309.       }
  3310.     }
  3311.  
  3312.     var toolbox = getNavToolbox();
  3313.     if (aShow)
  3314.       toolbox.removeAttribute("inFullscreen");
  3315.     else
  3316.       toolbox.setAttribute("inFullscreen", true);
  3317.  
  3318. //@line 3693 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  3319.     var controls = document.getElementsByAttribute("fullscreencontrol", "true");
  3320.     for (var i = 0; i < controls.length; ++i)
  3321.       controls[i].hidden = aShow;
  3322. //@line 3697 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  3323.   }
  3324. };
  3325.  
  3326. /**
  3327.  * Returns true if |aMimeType| is text-based, false otherwise.
  3328.  *
  3329.  * @param aMimeType
  3330.  *        The MIME type to check.
  3331.  *
  3332.  * If adding types to this function, please also check the similar 
  3333.  * function in findbar.xml
  3334.  */
  3335. function mimeTypeIsTextBased(aMimeType)
  3336. {
  3337.   return /^text\/|\+xml$/.test(aMimeType) ||
  3338.          aMimeType == "application/x-javascript" ||
  3339.          aMimeType == "application/javascript" ||
  3340.          aMimeType == "application/xml" ||
  3341.          aMimeType == "mozilla.application/cached-xul";
  3342. }
  3343.  
  3344. function nsBrowserStatusHandler()
  3345. {
  3346.   this.init();
  3347. }
  3348.  
  3349. nsBrowserStatusHandler.prototype =
  3350. {
  3351.   // Stored Status, Link and Loading values
  3352.   status : "",
  3353.   defaultStatus : "",
  3354.   jsStatus : "",
  3355.   jsDefaultStatus : "",
  3356.   overLink : "",
  3357.   startTime : 0,
  3358.   statusText: "",
  3359.   lastURI: null,
  3360.  
  3361.   statusTimeoutInEffect : false,
  3362.  
  3363.   QueryInterface : function(aIID)
  3364.   {
  3365.     if (aIID.equals(Ci.nsIWebProgressListener) ||
  3366.         aIID.equals(Ci.nsIWebProgressListener2) ||
  3367.         aIID.equals(Ci.nsISupportsWeakReference) ||
  3368.         aIID.equals(Ci.nsIXULBrowserWindow) ||
  3369.         aIID.equals(Ci.nsISupports))
  3370.       return this;
  3371.     throw Cr.NS_NOINTERFACE;
  3372.   },
  3373.  
  3374.   init : function()
  3375.   {
  3376.     this.throbberElement        = document.getElementById("navigator-throbber");
  3377.     this.statusMeter            = document.getElementById("statusbar-icon");
  3378.     this.stopCommand            = document.getElementById("Browser:Stop");
  3379.     this.reloadCommand          = document.getElementById("Browser:Reload");
  3380.     this.reloadSkipCacheCommand = document.getElementById("Browser:ReloadSkipCache");
  3381.     this.statusTextField        = document.getElementById("statusbar-display");
  3382.     this.securityButton         = document.getElementById("security-button");
  3383.     this.urlBar                 = document.getElementById("urlbar");
  3384.     this.isImage                = document.getElementById("isImage");
  3385.  
  3386.     // Initialize the security button's state and tooltip text.  Remember to reset
  3387.     // _hostChanged, otherwise onSecurityChange will short circuit.
  3388.     var securityUI = getBrowser().securityUI;
  3389.     this._hostChanged = true;
  3390.     this.onSecurityChange(null, null, securityUI.state);
  3391.   },
  3392.  
  3393.   destroy : function()
  3394.   {
  3395.     // XXXjag to avoid leaks :-/, see bug 60729
  3396.     this.throbberElement        = null;
  3397.     this.statusMeter            = null;
  3398.     this.stopCommand            = null;
  3399.     this.reloadCommand          = null;
  3400.     this.reloadSkipCacheCommand = null;
  3401.     this.statusTextField        = null;
  3402.     this.securityButton         = null;
  3403.     this.urlBar                 = null;
  3404.     this.statusText             = null;
  3405.     this.lastURI                = null;
  3406.   },
  3407.  
  3408.   setJSStatus : function(status)
  3409.   {
  3410.     this.jsStatus = status;
  3411.     this.updateStatusField();
  3412.   },
  3413.  
  3414.   setJSDefaultStatus : function(status)
  3415.   {
  3416.     this.jsDefaultStatus = status;
  3417.     this.updateStatusField();
  3418.   },
  3419.  
  3420.   setDefaultStatus : function(status)
  3421.   {
  3422.     this.defaultStatus = status;
  3423.     this.updateStatusField();
  3424.   },
  3425.  
  3426.   setOverLink : function(link, b)
  3427.   {
  3428.     // Encode bidirectional formatting characters.
  3429.     // (RFC 3987 sections 3.2 and 4.1 paragraph 6)
  3430.     this.overLink = link.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g,
  3431.                                  encodeURIComponent);
  3432.     this.updateStatusField();
  3433.   },
  3434.  
  3435.   updateStatusField : function()
  3436.   {
  3437.     var text = this.overLink || this.status || this.jsStatus || this.jsDefaultStatus || this.defaultStatus;
  3438.  
  3439.     // check the current value so we don't trigger an attribute change
  3440.     // and cause needless (slow!) UI updates
  3441.     if (this.statusText != text) {
  3442.       this.statusTextField.label = text;
  3443.       this.statusText = text;
  3444.     }
  3445.   },
  3446.   
  3447.   onLinkIconAvailable : function(aBrowser)
  3448.   {
  3449.     if (gProxyFavIcon && gBrowser.mCurrentBrowser == aBrowser &&
  3450.         gBrowser.userTypedValue === null)
  3451.       PageProxySetIcon(aBrowser.mIconURL); // update the favicon in the URL bar
  3452.   },
  3453.  
  3454.   onProgressChange : function (aWebProgress, aRequest,
  3455.                                aCurSelfProgress, aMaxSelfProgress,
  3456.                                aCurTotalProgress, aMaxTotalProgress)
  3457.   {
  3458.     if (aMaxTotalProgress > 0) {
  3459.       // This is highly optimized.  Don't touch this code unless
  3460.       // you are intimately familiar with the cost of setting
  3461.       // attrs on XUL elements. -- hyatt
  3462.       var percentage = (aCurTotalProgress * 100) / aMaxTotalProgress;
  3463.       this.statusMeter.value = percentage;
  3464.     }
  3465.   },
  3466.  
  3467.   onProgressChange64 : function (aWebProgress, aRequest,
  3468.                                  aCurSelfProgress, aMaxSelfProgress,
  3469.                                  aCurTotalProgress, aMaxTotalProgress)
  3470.   {
  3471.     return this.onProgressChange(aWebProgress, aRequest,
  3472.       aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress,
  3473.       aMaxTotalProgress);
  3474.   },
  3475.  
  3476.   onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus)
  3477.   {
  3478.     const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
  3479.     const nsIChannel = Components.interfaces.nsIChannel;
  3480.     if (aStateFlags & nsIWebProgressListener.STATE_START) {
  3481.         // This (thanks to the filter) is a network start or the first
  3482.         // stray request (the first request outside of the document load),
  3483.         // initialize the throbber and his friends.
  3484.  
  3485.         // Call start document load listeners (only if this is a network load)
  3486.         if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK &&
  3487.             aRequest && aWebProgress.DOMWindow == content)
  3488.           this.startDocumentLoad(aRequest);
  3489.  
  3490.         if (this.throbberElement) {
  3491.           // Turn the throbber on.
  3492.           this.throbberElement.setAttribute("busy", "true");
  3493.         }
  3494.  
  3495.         // Turn the status meter on.
  3496.         this.statusMeter.value = 0;  // be sure to clear the progress bar
  3497.         if (gProgressCollapseTimer) {
  3498.           window.clearTimeout(gProgressCollapseTimer);
  3499.           gProgressCollapseTimer = null;
  3500.         }
  3501.         else
  3502.           this.statusMeter.parentNode.collapsed = false;
  3503.  
  3504.         // XXX: This needs to be based on window activity...
  3505.         this.stopCommand.removeAttribute("disabled");
  3506.     }
  3507.     else if (aStateFlags & nsIWebProgressListener.STATE_STOP) {
  3508.       if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) {
  3509.         if (aWebProgress.DOMWindow == content) {
  3510.           if (aRequest)
  3511.             this.endDocumentLoad(aRequest, aStatus);
  3512.           var browser = gBrowser.mCurrentBrowser;
  3513.           if (!gBrowser.mTabbedMode && !browser.mIconURL)
  3514.             gBrowser.useDefaultIcon(gBrowser.mCurrentTab);
  3515.  
  3516.           if (Components.isSuccessCode(aStatus) &&
  3517.               content.document.documentElement.getAttribute("manifest")) {
  3518.             OfflineApps.offlineAppRequested(content);
  3519.           }
  3520.         }
  3521.       }
  3522.  
  3523.       // This (thanks to the filter) is a network stop or the last
  3524.       // request stop outside of loading the document, stop throbbers
  3525.       // and progress bars and such
  3526.       if (aRequest) {
  3527.         var msg = "";
  3528.           // Get the URI either from a channel or a pseudo-object
  3529.           if (aRequest instanceof nsIChannel || "URI" in aRequest) {
  3530.             var location = aRequest.URI;
  3531.  
  3532.             // For keyword URIs clear the user typed value since they will be changed into real URIs
  3533.             if (location.scheme == "keyword" && aWebProgress.DOMWindow == content)
  3534.               getBrowser().userTypedValue = null;
  3535.  
  3536.             if (location.spec != "about:blank") {
  3537.               const kErrorBindingAborted = 0x804B0002;
  3538.               const kErrorNetTimeout = 0x804B000E;
  3539.               switch (aStatus) {
  3540.                 case kErrorBindingAborted:
  3541.                   msg = gNavigatorBundle.getString("nv_stopped");
  3542.                   break;
  3543.                 case kErrorNetTimeout:
  3544.                   msg = gNavigatorBundle.getString("nv_timeout");
  3545.                   break;
  3546.               }
  3547.             }
  3548.           }
  3549.           // If msg is false then we did not have an error (channel may have
  3550.           // been null, in the case of a stray image load).
  3551.           if (!msg && (!location || location.spec != "about:blank")) {
  3552.             msg = gNavigatorBundle.getString("nv_done");
  3553.           }
  3554.           this.status = "";
  3555.           this.setDefaultStatus(msg);
  3556.  
  3557.           // Disable menu entries for images, enable otherwise
  3558.           if (content.document && mimeTypeIsTextBased(content.document.contentType))
  3559.             this.isImage.removeAttribute('disabled');
  3560.           else
  3561.             this.isImage.setAttribute('disabled', 'true');
  3562.         }
  3563.  
  3564.         // Turn the progress meter and throbber off.
  3565.         gProgressCollapseTimer = window.setTimeout(
  3566.           function() {
  3567.             gProgressMeterPanel.collapsed = true;
  3568.             gProgressCollapseTimer = null;
  3569.           }, 100);
  3570.  
  3571.         if (this.throbberElement)
  3572.           this.throbberElement.removeAttribute("busy");
  3573.  
  3574.         this.stopCommand.setAttribute("disabled", "true");
  3575.     }
  3576.   },
  3577.  
  3578.   onLocationChange : function(aWebProgress, aRequest, aLocationURI)
  3579.   {
  3580.     var location = aLocationURI ? aLocationURI.spec : "";
  3581.     this._hostChanged = true;
  3582.  
  3583.     if (document.tooltipNode) {
  3584.       // Optimise for the common case
  3585.       if (aWebProgress.DOMWindow == content) {
  3586.         document.getElementById("aHTMLTooltip").hidePopup();
  3587.         document.tooltipNode = null;
  3588.       }
  3589.       else {
  3590.         for (var tooltipWindow =
  3591.                document.tooltipNode.ownerDocument.defaultView;
  3592.              tooltipWindow != tooltipWindow.parent;
  3593.              tooltipWindow = tooltipWindow.parent) {
  3594.           if (tooltipWindow == aWebProgress.DOMWindow) {
  3595.             document.getElementById("aHTMLTooltip").hidePopup();
  3596.             document.tooltipNode = null;
  3597.             break;
  3598.           }
  3599.         }
  3600.       }
  3601.     }
  3602.  
  3603.     // This code here does not compare uris exactly when determining
  3604.     // whether or not the message should be hidden since the message
  3605.     // may be prematurely hidden when an install is invoked by a click
  3606.     // on a link that looks like this:
  3607.     //
  3608.     // <a href="#" onclick="return install();">Install Foo</a>
  3609.     //
  3610.     // - which fires a onLocationChange message to uri + '#'...
  3611.     var selectedBrowser = getBrowser().selectedBrowser;
  3612.     if (selectedBrowser.lastURI) {
  3613.       var oldSpec = selectedBrowser.lastURI.spec;
  3614.       var oldIndexOfHash = oldSpec.indexOf("#");
  3615.       if (oldIndexOfHash != -1)
  3616.         oldSpec = oldSpec.substr(0, oldIndexOfHash);
  3617.       var newSpec = location;
  3618.       var newIndexOfHash = newSpec.indexOf("#");
  3619.       if (newIndexOfHash != -1)
  3620.         newSpec = newSpec.substr(0, newSpec.indexOf("#"));
  3621.       if (newSpec != oldSpec) {
  3622.         // Remove all the notifications, except for those which want to
  3623.         // persist across the first location change.
  3624.         var nBox = gBrowser.getNotificationBox(selectedBrowser);
  3625.         nBox.removeTransientNotifications();
  3626.       }
  3627.     }
  3628.     selectedBrowser.lastURI = aLocationURI;
  3629.  
  3630.     // Disable menu entries for images, enable otherwise
  3631.     if (content.document && mimeTypeIsTextBased(content.document.contentType))
  3632.       this.isImage.removeAttribute('disabled');
  3633.     else
  3634.       this.isImage.setAttribute('disabled', 'true');
  3635.  
  3636.     this.setOverLink("", null);
  3637.  
  3638.     // We should probably not do this if the value has changed since the user
  3639.     // searched
  3640.     // Update urlbar only if a new page was loaded on the primary content area
  3641.     // Do not update urlbar if there was a subframe navigation
  3642.  
  3643.     var browser = getBrowser().selectedBrowser;
  3644.     if (aWebProgress.DOMWindow == content) {
  3645.  
  3646.       if ((location == "about:blank" && !content.opener) ||
  3647.            location == "") {  // Second condition is for new tabs, otherwise
  3648.                               // reload function is enabled until tab is refreshed.
  3649.         this.reloadCommand.setAttribute("disabled", "true");
  3650.         this.reloadSkipCacheCommand.setAttribute("disabled", "true");
  3651.       } else {
  3652.         this.reloadCommand.removeAttribute("disabled");
  3653.         this.reloadSkipCacheCommand.removeAttribute("disabled");
  3654.       }
  3655.  
  3656.       if (!gBrowser.mTabbedMode && aWebProgress.isLoadingDocument)
  3657.         gBrowser.setIcon(gBrowser.mCurrentTab, null);
  3658.  
  3659.       if (gURLBar) {
  3660.         URLBarSetURI(aLocationURI);
  3661.  
  3662.         // Update starring UI
  3663.         PlacesStarButton.updateState();
  3664.       }
  3665.     }
  3666.     UpdateBackForwardCommands(gBrowser.webNavigation);
  3667.  
  3668.     if (gFindBar.findMode != gFindBar.FIND_NORMAL) {
  3669.       // Close the Find toolbar if we're in old-style TAF mode
  3670.       gFindBar.close();
  3671.     }
  3672.  
  3673.     // XXXmano new-findbar, do something useful once it lands.
  3674.     // Of course, this is especially wrong with bfcache on...
  3675.  
  3676.     // fix bug 253793 - turn off highlight when page changes
  3677.     gFindBar.getElement("highlight").checked = false;
  3678.  
  3679.     // See bug 358202, when tabs are switched during a drag operation,
  3680.     // timers don't fire on windows (bug 203573)
  3681.     if (aRequest) {
  3682.       var self = this;
  3683.       setTimeout(function() { self.asyncUpdateUI(); }, 0);
  3684.     } 
  3685.     else
  3686.       this.asyncUpdateUI();
  3687.  
  3688.     // Catch exceptions until bug 376222 gets fixed so we don't hork
  3689.     // other progress listeners if this call throws an exception.
  3690.     try {
  3691.       FullZoom.onLocationChange(aLocationURI);
  3692.     }
  3693.     catch(ex) {
  3694.       Components.utils.reportError(ex);
  3695.     }
  3696.   },
  3697.   
  3698.   asyncUpdateUI : function () {
  3699.     FeedHandler.updateFeeds();
  3700.     BrowserSearch.updateSearchButton();
  3701.   },
  3702.  
  3703.   onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage)
  3704.   {
  3705.     this.status = aMessage;
  3706.     this.updateStatusField();
  3707.   },
  3708.  
  3709.   onRefreshAttempted : function(aWebProgress, aURI, aDelay, aSameURI)
  3710.   {
  3711.     if (gPrefService.getBoolPref("accessibility.blockautorefresh")) {
  3712.       var brandBundle = document.getElementById("bundle_brand");
  3713.       var brandShortName = brandBundle.getString("brandShortName");
  3714.       var refreshButtonText = 
  3715.         gNavigatorBundle.getString("refreshBlocked.goButton");
  3716.       var refreshButtonAccesskey = 
  3717.         gNavigatorBundle.getString("refreshBlocked.goButton.accesskey");
  3718.       var message;
  3719.       if (aSameURI)
  3720.         message = gNavigatorBundle.getFormattedString(
  3721.           "refreshBlocked.refreshLabel", [brandShortName]);
  3722.       else
  3723.         message = gNavigatorBundle.getFormattedString(
  3724.           "refreshBlocked.redirectLabel", [brandShortName]);
  3725.       var topBrowser = getBrowserFromContentWindow(aWebProgress.DOMWindow.top);
  3726.       var docShell = aWebProgress.DOMWindow
  3727.                                  .QueryInterface(Ci.nsIInterfaceRequestor)
  3728.                                  .getInterface(Ci.nsIWebNavigation)
  3729.                                  .QueryInterface(Ci.nsIDocShell);
  3730.       var notificationBox = gBrowser.getNotificationBox(topBrowser);
  3731.       var notification = notificationBox.getNotificationWithValue(
  3732.         "refresh-blocked");
  3733.       if (notification) {
  3734.         notification.label = message;
  3735.         notification.refreshURI = aURI;
  3736.         notification.delay = aDelay;
  3737.         notification.docShell = docShell;
  3738.       }
  3739.       else {
  3740.         var buttons = [{
  3741.           label: refreshButtonText,
  3742.           accessKey: refreshButtonAccesskey,
  3743.           callback: function(aNotification, aButton) {
  3744.             var refreshURI = aNotification.docShell
  3745.                                           .QueryInterface(Ci.nsIRefreshURI);
  3746.             refreshURI.forceRefreshURI(aNotification.refreshURI,
  3747.                                        aNotification.delay, true);
  3748.           }
  3749.         }];
  3750.         const priority = notificationBox.PRIORITY_INFO_MEDIUM;
  3751.         notification = notificationBox.appendNotification(
  3752.           message,
  3753.           "refresh-blocked",
  3754.           "chrome://browser/skin/Info.png",
  3755.           priority,
  3756.           buttons);
  3757.         notification.refreshURI = aURI;
  3758.         notification.delay = aDelay;
  3759.         notification.docShell = docShell;
  3760.       }
  3761.       return false;
  3762.     }
  3763.     return true;
  3764.   },
  3765.  
  3766.   // Properties used to cache security state used to update the UI
  3767.   _state: null,
  3768.   _host: undefined,
  3769.   _tooltipText: null,
  3770.   _hostChanged: false, // onLocationChange will flip this bit
  3771.  
  3772.   onSecurityChange : function browser_onSecChange(aWebProgress,
  3773.                                                   aRequest, aState)
  3774.   {
  3775.     // Don't need to do anything if the data we use to update the UI hasn't
  3776.     // changed
  3777.     if (this._state == aState &&
  3778.         this._tooltipText == gBrowser.securityUI.tooltipText &&
  3779.         !this._hostChanged) {
  3780. //@line 4165 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  3781.       return;
  3782.     }
  3783.     this._state = aState;
  3784.  
  3785.     try {
  3786.       this._host = gBrowser.contentWindow.location.host;
  3787.     } catch(ex) {
  3788.       this._host = null;
  3789.     }
  3790.  
  3791.     this._hostChanged = false;
  3792.     this._tooltipText = gBrowser.securityUI.tooltipText
  3793.  
  3794.     // aState is defined as a bitmask that may be extended in the future.
  3795.     // We filter out any unknown bits before testing for known values.
  3796.     const wpl = Components.interfaces.nsIWebProgressListener;
  3797.     const wpl_security_bits = wpl.STATE_IS_SECURE |
  3798.                               wpl.STATE_IS_BROKEN |
  3799.                               wpl.STATE_IS_INSECURE |
  3800.                               wpl.STATE_SECURE_HIGH |
  3801.                               wpl.STATE_SECURE_MED |
  3802.                               wpl.STATE_SECURE_LOW;
  3803.     var level = null;
  3804.     var setHost = false;
  3805.  
  3806.     switch (this._state & wpl_security_bits) {
  3807.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH:
  3808.         level = "high";
  3809.         setHost = true;
  3810.         break;
  3811.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_MED:
  3812.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW:
  3813.         level = "low";
  3814.         setHost = true;
  3815.         break;
  3816.       case wpl.STATE_IS_BROKEN:
  3817.         level = "broken";
  3818.         break;
  3819.     }
  3820.  
  3821.     if (level) {
  3822.       this.securityButton.setAttribute("level", level);
  3823.       if (this.urlBar)
  3824.         this.urlBar.setAttribute("level", level);    
  3825.     } else {
  3826.       this.securityButton.removeAttribute("level");
  3827.       if (this.urlBar)
  3828.         this.urlBar.removeAttribute("level");
  3829.     }
  3830.  
  3831.     if (setHost && this._host)
  3832.       this.securityButton.setAttribute("label", this._host);
  3833.     else
  3834.       this.securityButton.removeAttribute("label");
  3835.  
  3836.     this.securityButton.setAttribute("tooltiptext", this._tooltipText);
  3837.  
  3838.     // Don't pass in the actual location object, since it can cause us to 
  3839.     // hold on to the window object too long.  Just pass in the fields we
  3840.     // care about. (bug 424829)
  3841.     var location = gBrowser.contentWindow.location;
  3842.     var locationObj = {};
  3843.     try {
  3844.       locationObj.host = location.host;
  3845.       locationObj.hostname = location.hostname;
  3846.       locationObj.port = location.port;
  3847.     } catch (ex) {
  3848.       // Can sometimes throw if the URL being visited has no host/hostname,
  3849.       // e.g. about:blank. The _state for these pages means we won't need these
  3850.       // properties anyways, though.
  3851.     }
  3852.     getIdentityHandler().checkIdentity(this._state, locationObj);
  3853.   },
  3854.  
  3855.   // simulate all change notifications after switching tabs
  3856.   onUpdateCurrentBrowser : function(aStateFlags, aStatus, aMessage, aTotalProgress)
  3857.   {
  3858.     var nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
  3859.     var loadingDone = aStateFlags & nsIWebProgressListener.STATE_STOP;
  3860.     // use a pseudo-object instead of a (potentially non-existing) channel for getting
  3861.     // a correct error message - and make sure that the UI is always either in
  3862.     // loading (STATE_START) or done (STATE_STOP) mode
  3863.     this.onStateChange(
  3864.       gBrowser.webProgress,
  3865.       { URI: gBrowser.currentURI },
  3866.       loadingDone ? nsIWebProgressListener.STATE_STOP : nsIWebProgressListener.STATE_START,
  3867.       aStatus
  3868.     );
  3869.     // status message and progress value are undefined if we're done with loading
  3870.     if (loadingDone)
  3871.       return;
  3872.     this.onStatusChange(gBrowser.webProgress, null, 0, aMessage);
  3873.     this.onProgressChange(gBrowser.webProgress, 0, 0, aTotalProgress, 1);
  3874.   },
  3875.  
  3876.   startDocumentLoad : function(aRequest)
  3877.   {
  3878.     // clear out feed data
  3879.     gBrowser.mCurrentBrowser.feeds = null;
  3880.  
  3881.     // clear out search-engine data
  3882.     gBrowser.mCurrentBrowser.engines = null;    
  3883.  
  3884.     const nsIChannel = Components.interfaces.nsIChannel;
  3885.     var urlStr = aRequest.QueryInterface(nsIChannel).URI.spec;
  3886.     var observerService = Components.classes["@mozilla.org/observer-service;1"]
  3887.                                     .getService(Components.interfaces.nsIObserverService);
  3888.     try {
  3889.       observerService.notifyObservers(content, "StartDocumentLoad", urlStr);
  3890.     } catch (e) {
  3891.     }
  3892.   },
  3893.  
  3894.   endDocumentLoad : function(aRequest, aStatus)
  3895.   {
  3896.     const nsIChannel = Components.interfaces.nsIChannel;
  3897.     var urlStr = aRequest.QueryInterface(nsIChannel).originalURI.spec;
  3898.  
  3899.     var observerService = Components.classes["@mozilla.org/observer-service;1"]
  3900.                                     .getService(Components.interfaces.nsIObserverService);
  3901.  
  3902.     var notification = Components.isSuccessCode(aStatus) ? "EndDocumentLoad" : "FailDocumentLoad";
  3903.     try {
  3904.       observerService.notifyObservers(content, notification, urlStr);
  3905.     } catch (e) {
  3906.     }
  3907.   }
  3908. }
  3909.  
  3910. function nsBrowserAccess()
  3911. {
  3912. }
  3913.  
  3914. nsBrowserAccess.prototype =
  3915. {
  3916.   QueryInterface : function(aIID)
  3917.   {
  3918.     if (aIID.equals(Ci.nsIBrowserDOMWindow) ||
  3919.         aIID.equals(Ci.nsISupports))
  3920.       return this;
  3921.     throw Components.results.NS_NOINTERFACE;
  3922.   },
  3923.  
  3924.   openURI : function(aURI, aOpener, aWhere, aContext)
  3925.   {
  3926.     var newWindow = null;
  3927.     var referrer = null;
  3928.     var isExternal = (aContext == Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL);
  3929.  
  3930.     if (isExternal && aURI && aURI.schemeIs("chrome")) {
  3931.       dump("use -chrome command-line option to load external chrome urls\n");
  3932.       return null;
  3933.     }
  3934.  
  3935.     if (!gPrefService)
  3936.       gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
  3937.                                .getService(Components.interfaces.nsIPrefBranch2);
  3938.  
  3939.     var loadflags = isExternal ?
  3940.                        Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL :
  3941.                        Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
  3942.     var location;
  3943.     if (aWhere == Ci.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW) {
  3944.       switch (aContext) {
  3945.         case Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL :
  3946.           aWhere = gPrefService.getIntPref("browser.link.open_external");
  3947.           break;
  3948.         default : // OPEN_NEW or an illegal value
  3949.           aWhere = gPrefService.getIntPref("browser.link.open_newwindow");
  3950.       }
  3951.     }
  3952.     switch(aWhere) {
  3953.       case Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW :
  3954.         // FIXME: Bug 408379. So how come this doesn't send the
  3955.         // referrer like the other loads do?
  3956.         var url = aURI ? aURI.spec : "about:blank";
  3957.         // Pass all params to openDialog to ensure that "url" isn't passed through
  3958.         // loadOneOrMoreURIs, which splits based on "|"
  3959.         newWindow = openDialog(getBrowserURL(), "_blank", "all,dialog=no", url, null, null, null);
  3960.         break;
  3961.       case Ci.nsIBrowserDOMWindow.OPEN_NEWTAB :
  3962.         var win = this._getMostRecentBrowserWindow();
  3963.         if (!win) {
  3964.           // we couldn't find a suitable window, a new one needs to be opened.
  3965.           return null;
  3966.         }
  3967.         var loadInBackground = gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground");
  3968.         var newTab = win.gBrowser.loadOneTab("about:blank", null, null, null, loadInBackground, false);
  3969.         newWindow = win.gBrowser.getBrowserForTab(newTab).docShell
  3970.                                 .QueryInterface(Ci.nsIInterfaceRequestor)
  3971.                                 .getInterface(Ci.nsIDOMWindow);
  3972.         try {
  3973.           if (aURI) {
  3974.             if (aOpener) {
  3975.               location = aOpener.location;
  3976.               referrer =
  3977.                       Components.classes["@mozilla.org/network/io-service;1"]
  3978.                                 .getService(Components.interfaces.nsIIOService)
  3979.                                 .newURI(location, null, null);
  3980.             }
  3981.             newWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  3982.                      .getInterface(Ci.nsIWebNavigation)
  3983.                      .loadURI(aURI.spec, loadflags, referrer, null, null);
  3984.           }
  3985.           if (!loadInBackground && isExternal)
  3986.             newWindow.focus();
  3987.         } catch(e) {
  3988.         }
  3989.         break;
  3990.       default : // OPEN_CURRENTWINDOW or an illegal value
  3991.         try {
  3992.           if (aOpener) {
  3993.             newWindow = aOpener.top;
  3994.             if (aURI) {
  3995.               location = aOpener.location;
  3996.               referrer =
  3997.                       Components.classes["@mozilla.org/network/io-service;1"]
  3998.                                 .getService(Components.interfaces.nsIIOService)
  3999.                                 .newURI(location, null, null);
  4000.  
  4001.               newWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  4002.                        .getInterface(nsIWebNavigation)
  4003.                        .loadURI(aURI.spec, loadflags, referrer, null, null);
  4004.             }
  4005.           } else {
  4006.             newWindow = gBrowser.selectedBrowser.docShell
  4007.                                 .QueryInterface(Ci.nsIInterfaceRequestor)
  4008.                                 .getInterface(Ci.nsIDOMWindow);
  4009.             if (aURI) {
  4010.               gBrowser.loadURIWithFlags(aURI.spec, loadflags, null, 
  4011.                                         null, null);
  4012.             }
  4013.           }
  4014.           if(!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground"))
  4015.             content.focus();
  4016.         } catch(e) {
  4017.         }
  4018.     }
  4019.     return newWindow;
  4020.   },
  4021.  
  4022. //@line 4414 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  4023.  
  4024.   // this returns the most recent non-popup browser window
  4025.   _getMostRecentBrowserWindow : function ()
  4026.   {
  4027.     if (!window.document.documentElement.getAttribute("chromehidden"))
  4028.       return window;
  4029.  
  4030.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  4031.                        .getService(Components.interfaces.nsIWindowMediator);
  4032.  
  4033. //@line 4425 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  4034.     var win = wm.getMostRecentWindow("navigator:browser", true);
  4035.  
  4036.     // if we're lucky, this isn't a popup, and we can just return this
  4037.     if (win && win.document.documentElement.getAttribute("chromehidden")) {
  4038.       win = null;
  4039.       var windowList = wm.getEnumerator("navigator:browser", true);
  4040.       // this is oldest to newest, so this gets a bit ugly
  4041.       while (windowList.hasMoreElements()) {
  4042.         var nextWin = windowList.getNext();
  4043.         if (!nextWin.document.documentElement.getAttribute("chromehidden"))
  4044.           win = nextWin;
  4045.       }
  4046.     }
  4047. //@line 4451 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  4048.  
  4049.     return win;
  4050.   },
  4051.  
  4052.   isTabContentWindow : function(aWindow)
  4053.   {
  4054.     var browsers = gBrowser.browsers;
  4055.     for (var ctr = 0; ctr < browsers.length; ctr++)
  4056.       if (browsers.item(ctr).contentWindow == aWindow)
  4057.         return true;
  4058.     return false;
  4059.   }
  4060. }
  4061.  
  4062. function onViewToolbarsPopupShowing(aEvent)
  4063. {
  4064.   var popup = aEvent.target;
  4065.   var i;
  4066.  
  4067.   // Empty the menu
  4068.   for (i = popup.childNodes.length-1; i >= 0; --i) {
  4069.     var deadItem = popup.childNodes[i];
  4070.     if (deadItem.hasAttribute("toolbarindex"))
  4071.       popup.removeChild(deadItem);
  4072.   }
  4073.  
  4074.   var firstMenuItem = popup.firstChild;
  4075.  
  4076.   var toolbox = getNavToolbox();
  4077.   for (i = 0; i < toolbox.childNodes.length; ++i) {
  4078.     var toolbar = toolbox.childNodes[i];
  4079.     var toolbarName = toolbar.getAttribute("toolbarname");
  4080.     var type = toolbar.getAttribute("type");
  4081.     if (toolbarName && type != "menubar") {
  4082.       var menuItem = document.createElement("menuitem");
  4083.       menuItem.setAttribute("toolbarindex", i);
  4084.       menuItem.setAttribute("type", "checkbox");
  4085.       menuItem.setAttribute("label", toolbarName);
  4086.       menuItem.setAttribute("accesskey", toolbar.getAttribute("accesskey"));
  4087.       menuItem.setAttribute("checked", toolbar.getAttribute("collapsed") != "true");
  4088.       popup.insertBefore(menuItem, firstMenuItem);
  4089.  
  4090.       menuItem.addEventListener("command", onViewToolbarCommand, false);
  4091.     }
  4092.     toolbar = toolbar.nextSibling;
  4093.   }
  4094. }
  4095.  
  4096. function onViewToolbarCommand(aEvent)
  4097. {
  4098.   var toolbox = getNavToolbox();
  4099.   var index = aEvent.originalTarget.getAttribute("toolbarindex");
  4100.   var toolbar = toolbox.childNodes[index];
  4101.  
  4102.   toolbar.collapsed = aEvent.originalTarget.getAttribute("checked") != "true";
  4103.   document.persist(toolbar.id, "collapsed");
  4104. }
  4105.  
  4106. function displaySecurityInfo()
  4107. {
  4108.   BrowserPageInfo(null, "securityTab");
  4109. }
  4110.  
  4111. /**
  4112.  * Opens or closes the sidebar identified by commandID.
  4113.  *
  4114.  * @param commandID a string identifying the sidebar to toggle; see the
  4115.  *                  note below. (Optional if a sidebar is already open.)
  4116.  * @param forceOpen boolean indicating whether the sidebar should be
  4117.  *                  opened regardless of it's current state (optional).
  4118.  * @note
  4119.  * We expect to find a xul:broadcaster element with the specified ID.
  4120.  * The following attributes on that element may be used and/or modified:
  4121.  *  - id           (required) the string to match commandID. The convention
  4122.  *                 is to use this naming scheme: 'view<sidebar-name>Sidebar'.
  4123.  *  - sidebarurl   (required) specifies the URL to load in this sidebar.
  4124.  *  - sidebartitle or label (in that order) specify the title to 
  4125.  *                 display on the sidebar.
  4126.  *  - checked      indicates whether the sidebar is currently displayed.
  4127.  *                 Note that toggleSidebar updates this attribute when
  4128.  *                 it changes the sidebar's visibility.
  4129.  *  - group        this attribute must be set to "sidebar".
  4130.  */
  4131. function toggleSidebar(commandID, forceOpen) {
  4132.  
  4133.   var sidebarBox = document.getElementById("sidebar-box");
  4134.   if (!commandID)
  4135.     commandID = sidebarBox.getAttribute("sidebarcommand");
  4136.  
  4137.   var sidebarBroadcaster = document.getElementById(commandID);
  4138.   var sidebar = document.getElementById("sidebar"); // xul:browser
  4139.   var sidebarTitle = document.getElementById("sidebar-title");
  4140.   var sidebarSplitter = document.getElementById("sidebar-splitter");
  4141.  
  4142.   if (sidebarBroadcaster.getAttribute("checked") == "true") {
  4143.     if (!forceOpen) {
  4144.       sidebarBroadcaster.removeAttribute("checked");
  4145.       sidebarBox.setAttribute("sidebarcommand", "");
  4146.       sidebarTitle.value = "";
  4147.       sidebar.setAttribute("src", "about:blank");
  4148.       sidebarBox.hidden = true;
  4149.       sidebarSplitter.hidden = true;
  4150.       content.focus();
  4151.     } else {
  4152.       fireSidebarFocusedEvent();
  4153.     }
  4154.     return;
  4155.   }
  4156.  
  4157.   // now we need to show the specified sidebar
  4158.  
  4159.   // ..but first update the 'checked' state of all sidebar broadcasters
  4160.   var broadcasters = document.getElementsByAttribute("group", "sidebar");
  4161.   for (var i = 0; i < broadcasters.length; ++i) {
  4162.     // skip elements that observe sidebar broadcasters and random
  4163.     // other elements
  4164.     if (broadcasters[i].localName != "broadcaster")
  4165.       continue;
  4166.  
  4167.     if (broadcasters[i] != sidebarBroadcaster)
  4168.       broadcasters[i].removeAttribute("checked");
  4169.     else
  4170.       sidebarBroadcaster.setAttribute("checked", "true");
  4171.   }
  4172.  
  4173.   sidebarBox.hidden = false;
  4174.   sidebarSplitter.hidden = false;
  4175.  
  4176.   var url = sidebarBroadcaster.getAttribute("sidebarurl");
  4177.   var title = sidebarBroadcaster.getAttribute("sidebartitle");
  4178.   if (!title)
  4179.     title = sidebarBroadcaster.getAttribute("label");
  4180.   sidebar.setAttribute("src", url); // kick off async load
  4181.   sidebarBox.setAttribute("sidebarcommand", sidebarBroadcaster.id);
  4182.   sidebarTitle.value = title;
  4183.  
  4184.   // We set this attribute here in addition to setting it on the <browser>
  4185.   // element itself, because the code in BrowserShutdown persists this
  4186.   // attribute, not the "src" of the <browser id="sidebar">. The reason it
  4187.   // does that is that we want to delay sidebar load a bit when a browser
  4188.   // window opens. See delayedStartup().
  4189.   sidebarBox.setAttribute("src", url);
  4190.  
  4191.   if (sidebar.contentDocument.location.href != url)
  4192.     sidebar.addEventListener("load", sidebarOnLoad, true);
  4193.   else // older code handled this case, so we do it too
  4194.     fireSidebarFocusedEvent();
  4195. }
  4196.  
  4197. function sidebarOnLoad(event) {
  4198.   var sidebar = document.getElementById("sidebar");
  4199.   sidebar.removeEventListener("load", sidebarOnLoad, true);
  4200.   // We're handling the 'load' event before it bubbles up to the usual
  4201.   // (non-capturing) event handlers. Let it bubble up before firing the
  4202.   // SidebarFocused event.
  4203.   setTimeout(fireSidebarFocusedEvent, 0);
  4204. }
  4205.  
  4206. /**
  4207.  * Fire a "SidebarFocused" event on the sidebar's |window| to give the sidebar
  4208.  * a chance to adjust focus as needed. An additional event is needed, because
  4209.  * we don't want to focus the sidebar when it's opened on startup or in a new
  4210.  * window, only when the user opens the sidebar.
  4211.  */
  4212. function fireSidebarFocusedEvent() {
  4213.   var sidebar = document.getElementById("sidebar");
  4214.   var event = document.createEvent("Events");
  4215.   event.initEvent("SidebarFocused", true, false);
  4216.   sidebar.contentWindow.dispatchEvent(event);
  4217. }
  4218.  
  4219. var gHomeButton = {
  4220.   prefDomain: "browser.startup.homepage",
  4221.   observe: function (aSubject, aTopic, aPrefName)
  4222.   {
  4223.     if (aTopic != "nsPref:changed" || aPrefName != this.prefDomain)
  4224.       return;
  4225.  
  4226.     this.updateTooltip();
  4227.   },
  4228.  
  4229.   updateTooltip: function (homeButton)
  4230.   {
  4231.     if (!homeButton)
  4232.       homeButton = document.getElementById("home-button");
  4233.     if (homeButton) {
  4234.       var homePage = this.getHomePage();
  4235.       homePage = homePage.replace(/\|/g,', ');
  4236.       homeButton.setAttribute("tooltiptext", homePage);
  4237.     }
  4238.   },
  4239.  
  4240.   getHomePage: function ()
  4241.   {
  4242.     var url;
  4243.     try {
  4244.       url = gPrefService.getComplexValue(this.prefDomain,
  4245.                                 Components.interfaces.nsIPrefLocalizedString).data;
  4246.     } catch (e) {
  4247.     }
  4248.  
  4249.     // use this if we can't find the pref
  4250.     if (!url) {
  4251.       var SBS = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
  4252.       var configBundle = SBS.createBundle("resource:/browserconfig.properties");
  4253.       url = configBundle.GetStringFromName(this.prefDomain);
  4254.     }
  4255.  
  4256.     return url;
  4257.   },
  4258.  
  4259.   updatePersonalToolbarStyle: function (homeButton)
  4260.   {
  4261.     if (!homeButton)
  4262.       homeButton = document.getElementById("home-button");
  4263.     if (homeButton)
  4264.       homeButton.className = homeButton.parentNode.id == "PersonalToolbar"
  4265.                                || homeButton.parentNode.parentNode.id == "PersonalToolbar" ?
  4266.                              homeButton.className.replace("toolbarbutton-1", "bookmark-item") :
  4267.                              homeButton.className.replace("bookmark-item", "toolbarbutton-1");
  4268.   }
  4269. };
  4270.  
  4271. /**
  4272.  * Gets the selected text in the active browser. Leading and trailing
  4273.  * whitespace is removed, and consecutive whitespace is replaced by a single
  4274.  * space. A maximum of 150 characters will be returned, regardless of the value
  4275.  * of aCharLen.
  4276.  *
  4277.  * @param aCharLen
  4278.  *        The maximum number of characters to return.
  4279.  */
  4280. function getBrowserSelection(aCharLen) {
  4281.   // selections of more than 150 characters aren't useful
  4282.   const kMaxSelectionLen = 150;
  4283.   const charLen = Math.min(aCharLen || kMaxSelectionLen, kMaxSelectionLen);
  4284.  
  4285.   var focusedWindow = document.commandDispatcher.focusedWindow;
  4286.   var selection = focusedWindow.getSelection().toString();
  4287.  
  4288.   if (selection) {
  4289.     if (selection.length > charLen) {
  4290.       // only use the first charLen important chars. see bug 221361
  4291.       var pattern = new RegExp("^(?:\\s*.){0," + charLen + "}");
  4292.       pattern.test(selection);
  4293.       selection = RegExp.lastMatch;
  4294.     }
  4295.  
  4296.     selection = selection.replace(/^\s+/, "")
  4297.                          .replace(/\s+$/, "")
  4298.                          .replace(/\s+/g, " ");
  4299.  
  4300.     if (selection.length > charLen)
  4301.       selection = selection.substr(0, charLen);
  4302.   }
  4303.   return selection;
  4304. }
  4305.  
  4306. var gWebPanelURI;
  4307. function openWebPanel(aTitle, aURI)
  4308. {
  4309.     // Ensure that the web panels sidebar is open.
  4310.     toggleSidebar('viewWebPanelsSidebar', true);
  4311.  
  4312.     // Set the title of the panel.
  4313.     document.getElementById("sidebar-title").value = aTitle;
  4314.  
  4315.     // Tell the Web Panels sidebar to load the bookmark.
  4316.     var sidebar = document.getElementById("sidebar");
  4317.     if (sidebar.docShell && sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser')) {
  4318.         sidebar.contentWindow.loadWebPanel(aURI);
  4319.         if (gWebPanelURI) {
  4320.             gWebPanelURI = "";
  4321.             sidebar.removeEventListener("load", asyncOpenWebPanel, true);
  4322.         }
  4323.     }
  4324.     else {
  4325.         // The panel is still being constructed.  Attach an onload handler.
  4326.         if (!gWebPanelURI)
  4327.             sidebar.addEventListener("load", asyncOpenWebPanel, true);
  4328.         gWebPanelURI = aURI;
  4329.     }
  4330. }
  4331.  
  4332. function asyncOpenWebPanel(event)
  4333. {
  4334.     var sidebar = document.getElementById("sidebar");
  4335.     if (gWebPanelURI && sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser'))
  4336.         sidebar.contentWindow.loadWebPanel(gWebPanelURI);
  4337.     gWebPanelURI = "";
  4338.     sidebar.removeEventListener("load", asyncOpenWebPanel, true);
  4339. }
  4340.  
  4341. /*
  4342.  * - [ Dependencies ] ---------------------------------------------------------
  4343.  *  utilityOverlay.js:
  4344.  *    - gatherTextUnder
  4345.  */
  4346.  
  4347.  // Called whenever the user clicks in the content area,
  4348.  // except when left-clicking on links (special case)
  4349.  // should always return true for click to go through
  4350.  function contentAreaClick(event, fieldNormalClicks)
  4351.  {
  4352.    if (!event.isTrusted || event.getPreventDefault()) {
  4353.      return true;
  4354.    }
  4355.  
  4356.    var target = event.target;
  4357.    var linkNode;
  4358.  
  4359.    if (target instanceof HTMLAnchorElement ||
  4360.        target instanceof HTMLAreaElement ||
  4361.        target instanceof HTMLLinkElement) {
  4362.      if (target.hasAttribute("href"))
  4363.        linkNode = target;
  4364.  
  4365.      // xxxmpc: this is kind of a hack to work around a Gecko bug (see bug 266932)
  4366.      // we're going to walk up the DOM looking for a parent link node,
  4367.      // this shouldn't be necessary, but we're matching the existing behaviour for left click
  4368.      var parent = target.parentNode;
  4369.      while (parent) {
  4370.        if (parent instanceof HTMLAnchorElement ||
  4371.            parent instanceof HTMLAreaElement ||
  4372.            parent instanceof HTMLLinkElement) {
  4373.            if (parent.hasAttribute("href"))
  4374.              linkNode = parent;
  4375.        }
  4376.        parent = parent.parentNode;
  4377.      }
  4378.    }
  4379.    else {
  4380.      linkNode = event.originalTarget;
  4381.      while (linkNode && !(linkNode instanceof HTMLAnchorElement))
  4382.        linkNode = linkNode.parentNode;
  4383.      // <a> cannot be nested.  So if we find an anchor without an
  4384.      // href, there is no useful <a> around the target
  4385.      if (linkNode && !linkNode.hasAttribute("href"))
  4386.        linkNode = null;
  4387.    }
  4388.    var wrapper = null;
  4389.    if (linkNode) {
  4390.      wrapper = linkNode;
  4391.      if (event.button == 0 && !event.ctrlKey && !event.shiftKey &&
  4392.          !event.altKey && !event.metaKey) {
  4393.        // A Web panel's links should target the main content area.  Do this
  4394.        // if no modifier keys are down and if there's no target or the target equals
  4395.        // _main (the IE convention) or _content (the Mozilla convention).
  4396.        // XXX Now that markLinkVisited is gone, we may not need to field _main and
  4397.        // _content here.
  4398.        target = wrapper.getAttribute("target");
  4399.        if (fieldNormalClicks &&
  4400.            (!target || target == "_content" || target  == "_main"))
  4401.          // IE uses _main, SeaMonkey uses _content, we support both
  4402.        {
  4403.          if (!wrapper.href)
  4404.            return true;
  4405.          if (wrapper.getAttribute("onclick"))
  4406.            return true;
  4407.          // javascript links should be executed in the current browser
  4408.          if (wrapper.href.substr(0, 11) === "javascript:")
  4409.            return true;
  4410.          // data links should be executed in the current browser
  4411.          if (wrapper.href.substr(0, 5) === "data:")
  4412.            return true;
  4413.  
  4414.          try {
  4415.            urlSecurityCheck(wrapper.href, wrapper.ownerDocument.nodePrincipal);
  4416.          }
  4417.          catch(ex) {
  4418.            return false;
  4419.          } 
  4420.  
  4421.          var postData = { };
  4422.          var url = getShortcutOrURI(wrapper.href, postData);
  4423.          if (!url)
  4424.            return true;
  4425.          loadURI(url, null, postData.value, false);
  4426.          event.preventDefault();
  4427.          return false;
  4428.        }
  4429.        else if (linkNode.getAttribute("rel") == "sidebar") {
  4430.          // This is the Opera convention for a special link that - when clicked - allows
  4431.          // you to add a sidebar panel.  We support the Opera convention here.  The link's
  4432.          // title attribute contains the title that should be used for the sidebar panel.
  4433.          PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(wrapper.href),
  4434.                                                 wrapper.getAttribute("title"),
  4435.                                                 null, null, true, true);
  4436.          event.preventDefault();
  4437.          return false;
  4438.        }
  4439.      }
  4440.      else {
  4441.        handleLinkClick(event, wrapper.href, linkNode);
  4442.      }
  4443.  
  4444.      return true;
  4445.    } else {
  4446.      // Try simple XLink
  4447.      var href, realHref, baseURI;
  4448.      linkNode = target;
  4449.      while (linkNode) {
  4450.        if (linkNode.nodeType == Node.ELEMENT_NODE) {
  4451.          wrapper = linkNode;
  4452.  
  4453.          realHref = wrapper.getAttributeNS("http://www.w3.org/1999/xlink", "href");
  4454.          if (realHref) {
  4455.            href = realHref;
  4456.            baseURI = wrapper.baseURI
  4457.          }
  4458.        }
  4459.        linkNode = linkNode.parentNode;
  4460.      }
  4461.      if (href) {
  4462.        href = makeURLAbsolute(baseURI, href);
  4463.        handleLinkClick(event, href, null);
  4464.        return true;
  4465.      }
  4466.    }
  4467.    if (event.button == 1 &&
  4468.        gPrefService.getBoolPref("middlemouse.contentLoadURL") &&
  4469.        !gPrefService.getBoolPref("general.autoScroll")) {
  4470.      middleMousePaste(event);
  4471.    }
  4472.    return true;
  4473.  }
  4474.  
  4475. function handleLinkClick(event, href, linkNode)
  4476. {
  4477.   var doc = event.target.ownerDocument;
  4478.  
  4479.   switch (event.button) {
  4480.     case 0:    // if left button clicked
  4481. //@line 4887 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  4482.       if (event.ctrlKey) {
  4483. //@line 4889 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  4484.         openNewTabWith(href, doc, null, event, false);
  4485.         event.stopPropagation();
  4486.         return true;
  4487.       }
  4488.  
  4489.       if (event.shiftKey && event.altKey) {
  4490.         var feedService = 
  4491.             Cc["@mozilla.org/browser/feeds/result-service;1"].
  4492.             getService(Ci.nsIFeedResultService);
  4493.         feedService.forcePreviewPage = true;
  4494.         loadURI(href, null, null, false);
  4495.         return false;
  4496.       }
  4497.                                                        
  4498.       if (event.shiftKey) {
  4499.         openNewWindowWith(href, doc, null, false);
  4500.         event.stopPropagation();
  4501.         return true;
  4502.       }
  4503.  
  4504.       if (event.altKey) {
  4505.         saveURL(href, linkNode ? gatherTextUnder(linkNode) : "", null, true,
  4506.                 true, doc.documentURIObject);
  4507.         return true;
  4508.       }
  4509.  
  4510.       return false;
  4511.     case 1:    // if middle button clicked
  4512.       var tab;
  4513.       try {
  4514.         tab = gPrefService.getBoolPref("browser.tabs.opentabfor.middleclick")
  4515.       }
  4516.       catch(ex) {
  4517.         tab = true;
  4518.       }
  4519.       if (tab)
  4520.         openNewTabWith(href, doc, null, event, false);
  4521.       else
  4522.         openNewWindowWith(href, doc, null, false);
  4523.       event.stopPropagation();
  4524.       return true;
  4525.   }
  4526.   return false;
  4527. }
  4528.  
  4529. function middleMousePaste(event)
  4530. {
  4531.   var url = readFromClipboard();
  4532.   if (!url)
  4533.     return;
  4534.   var postData = { };
  4535.   url = getShortcutOrURI(url, postData);
  4536.   if (!url)
  4537.     return;
  4538.  
  4539.   try {
  4540.     addToUrlbarHistory(url);
  4541.   } catch (ex) {
  4542.     // Things may go wrong when adding url to session history,
  4543.     // but don't let that interfere with the loading of the url.
  4544.   }
  4545.  
  4546.   openUILink(url,
  4547.              event,
  4548.              true /* ignore the fact this is a middle click */);
  4549.  
  4550.   event.stopPropagation();
  4551. }
  4552.  
  4553. /*
  4554.  * Note that most of this routine has been moved into C++ in order to
  4555.  * be available for all <browser> tags as well as gecko embedding. See
  4556.  * mozilla/content/base/src/nsContentAreaDragDrop.cpp.
  4557.  *
  4558.  * Do not add any new fuctionality here other than what is needed for
  4559.  * a standalone product.
  4560.  */
  4561.  
  4562. var contentAreaDNDObserver = {
  4563.   onDrop: function (aEvent, aXferData, aDragSession)
  4564.     {
  4565.       var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  4566.  
  4567.       // valid urls don't contain spaces ' '; if we have a space it
  4568.       // isn't a valid url, or if it's a javascript: or data: url,
  4569.       // bail out
  4570.       if (!url || !url.length || url.indexOf(" ", 0) != -1 ||
  4571.           /^\s*(javascript|data):/.test(url))
  4572.         return;
  4573.  
  4574.       nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  4575.  
  4576.       switch (document.documentElement.getAttribute('windowtype')) {
  4577.         case "navigator:browser":
  4578.           var postData = { };
  4579.           var uri = getShortcutOrURI(url, postData);
  4580.           loadURI(uri, null, postData.value, false);
  4581.           break;
  4582.         case "navigator:view-source":
  4583.           viewSource(url);
  4584.           break;
  4585.       }
  4586.  
  4587.       // keep the event from being handled by the dragDrop listeners
  4588.       // built-in to gecko if they happen to be above us.
  4589.       aEvent.preventDefault();
  4590.     },
  4591.  
  4592.   getSupportedFlavours: function ()
  4593.     {
  4594.       var flavourSet = new FlavourSet();
  4595.       flavourSet.appendFlavour("text/x-moz-url");
  4596.       flavourSet.appendFlavour("text/unicode");
  4597.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  4598.       return flavourSet;
  4599.     }
  4600.  
  4601. };
  4602.  
  4603. function getBrowser()
  4604. {
  4605.   if (!gBrowser)
  4606.     gBrowser = document.getElementById("content");
  4607.   return gBrowser;
  4608. }
  4609.  
  4610. function getNavToolbox()
  4611. {
  4612.   if (!gNavToolbox)
  4613.     gNavToolbox = document.getElementById("navigator-toolbox");
  4614.   return gNavToolbox;
  4615. }
  4616.  
  4617. function MultiplexHandler(event)
  4618. { try {
  4619.     var node = event.target;
  4620.     var name = node.getAttribute('name');
  4621.  
  4622.     if (name == 'detectorGroup') {
  4623.         SetForcedDetector(true);
  4624.         SelectDetector(event, false);
  4625.     } else if (name == 'charsetGroup') {
  4626.         var charset = node.getAttribute('id');
  4627.         charset = charset.substring('charset.'.length, charset.length)
  4628.         SetForcedCharset(charset);
  4629.     } else if (name == 'charsetCustomize') {
  4630.         //do nothing - please remove this else statement, once the charset prefs moves to the pref window
  4631.     } else {
  4632.         SetForcedCharset(node.getAttribute('id'));
  4633.     }
  4634.     } catch(ex) { alert(ex); }
  4635. }
  4636.  
  4637. function SelectDetector(event, doReload)
  4638. {
  4639.     var uri =  event.target.getAttribute("id");
  4640.     var prefvalue = uri.substring('chardet.'.length, uri.length);
  4641.     if ("off" == prefvalue) { // "off" is special value to turn off the detectors
  4642.         prefvalue = "";
  4643.     }
  4644.  
  4645.     try {
  4646.         var pref = Components.classes["@mozilla.org/preferences-service;1"]
  4647.                              .getService(Components.interfaces.nsIPrefBranch);
  4648.         var str =  Components.classes["@mozilla.org/supports-string;1"]
  4649.                              .createInstance(Components.interfaces.nsISupportsString);
  4650.  
  4651.         str.data = prefvalue;
  4652.         pref.setComplexValue("intl.charset.detector",
  4653.                              Components.interfaces.nsISupportsString, str);
  4654.         if (doReload) window.content.location.reload();
  4655.     }
  4656.     catch (ex) {
  4657.         dump("Failed to set the intl.charset.detector preference.\n");
  4658.     }
  4659. }
  4660.  
  4661. function SetForcedDetector(doReload)
  4662. {
  4663.     BrowserSetForcedDetector(doReload);
  4664. }
  4665.  
  4666. function SetForcedCharset(charset)
  4667. {
  4668.     BrowserSetForcedCharacterSet(charset);
  4669. }
  4670.  
  4671. function BrowserSetForcedCharacterSet(aCharset)
  4672. {
  4673.   var docCharset = getBrowser().docShell.QueryInterface(
  4674.                             Components.interfaces.nsIDocCharset);
  4675.   docCharset.charset = aCharset;
  4676.   // Save the forced character-set
  4677.   PlacesUtils.history.setCharsetForURI(getWebNavigation().currentURI, aCharset);
  4678.   BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
  4679. }
  4680.  
  4681. function BrowserSetForcedDetector(doReload)
  4682. {
  4683.   getBrowser().documentCharsetInfo.forcedDetector = true;
  4684.   if (doReload)
  4685.     BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
  4686. }
  4687.  
  4688. function UpdateCurrentCharset()
  4689. {
  4690.     // extract the charset from DOM
  4691.     var wnd = document.commandDispatcher.focusedWindow;
  4692.     if ((window == wnd) || (wnd == null)) wnd = window.content;
  4693.  
  4694.     // Uncheck previous item
  4695.     if (gPrevCharset) {
  4696.         var pref_item = document.getElementById('charset.' + gPrevCharset);
  4697.         if (pref_item)
  4698.           pref_item.setAttribute('checked', 'false');
  4699.     }
  4700.  
  4701.     var menuitem = document.getElementById('charset.' + wnd.document.characterSet);
  4702.     if (menuitem) {
  4703.         menuitem.setAttribute('checked', 'true');
  4704.     }
  4705. }
  4706.  
  4707. function UpdateCharsetDetector()
  4708. {
  4709.     var prefvalue;
  4710.  
  4711.     try {
  4712.         var pref = Components.classes["@mozilla.org/preferences-service;1"]
  4713.                              .getService(Components.interfaces.nsIPrefBranch);
  4714.         prefvalue = pref.getComplexValue("intl.charset.detector",
  4715.                                          Components.interfaces.nsIPrefLocalizedString).data;
  4716.     }
  4717.     catch (ex) {
  4718.         prefvalue = "";
  4719.     }
  4720.  
  4721.     if (prefvalue == "") prefvalue = "off";
  4722.     dump("intl.charset.detector = "+ prefvalue + "\n");
  4723.  
  4724.     prefvalue = 'chardet.' + prefvalue;
  4725.     var menuitem = document.getElementById(prefvalue);
  4726.  
  4727.     if (menuitem) {
  4728.         menuitem.setAttribute('checked', 'true');
  4729.     }
  4730. }
  4731.  
  4732. function UpdateMenus(event)
  4733. {
  4734.     // use setTimeout workaround to delay checkmark the menu
  4735.     // when onmenucomplete is ready then use it instead of oncreate
  4736.     // see bug 78290 for the detail
  4737.     UpdateCurrentCharset();
  4738.     setTimeout(UpdateCurrentCharset, 0);
  4739.     UpdateCharsetDetector();
  4740.     setTimeout(UpdateCharsetDetector, 0);
  4741. }
  4742.  
  4743. function CreateMenu(node)
  4744. {
  4745.   var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4746.   observerService.notifyObservers(null, "charsetmenu-selected", node);
  4747. }
  4748.  
  4749. function charsetLoadListener (event)
  4750. {
  4751.     var charset = window.content.document.characterSet;
  4752.  
  4753.     if (charset.length > 0 && (charset != gLastBrowserCharset)) {
  4754.         if (!gCharsetMenu)
  4755.           gCharsetMenu = Components.classes['@mozilla.org/rdf/datasource;1?name=charset-menu'].getService().QueryInterface(Components.interfaces.nsICurrentCharsetListener);
  4756.         gCharsetMenu.SetCurrentCharset(charset);
  4757.         gPrevCharset = gLastBrowserCharset;
  4758.         gLastBrowserCharset = charset;
  4759.     }
  4760. }
  4761.  
  4762. /* Begin Page Style Functions */
  4763. function getStyleSheetArray(frame)
  4764. {
  4765.   var styleSheets = frame.document.styleSheets;
  4766.   var styleSheetsArray = new Array(styleSheets.length);
  4767.   for (var i = 0; i < styleSheets.length; i++) {
  4768.     styleSheetsArray[i] = styleSheets[i];
  4769.   }
  4770.   return styleSheetsArray;
  4771. }
  4772.  
  4773. function getAllStyleSheets(frameset)
  4774. {
  4775.   var styleSheetsArray = getStyleSheetArray(frameset);
  4776.   for (var i = 0; i < frameset.frames.length; i++) {
  4777.     var frameSheets = getAllStyleSheets(frameset.frames[i]);
  4778.     styleSheetsArray = styleSheetsArray.concat(frameSheets);
  4779.   }
  4780.   return styleSheetsArray;
  4781. }
  4782.  
  4783. function stylesheetFillPopup(menuPopup)
  4784. {
  4785.   var noStyle = menuPopup.firstChild;
  4786.   var persistentOnly = noStyle.nextSibling;
  4787.   var sep = persistentOnly.nextSibling;
  4788.   while (sep.nextSibling)
  4789.     menuPopup.removeChild(sep.nextSibling);
  4790.  
  4791.   var styleSheets = getAllStyleSheets(window.content);
  4792.   var currentStyleSheets = [];
  4793.   var styleDisabled = getMarkupDocumentViewer().authorStyleDisabled;
  4794.   var haveAltSheets = false;
  4795.   var altStyleSelected = false;
  4796.  
  4797.   for (var i = 0; i < styleSheets.length; ++i) {
  4798.     var currentStyleSheet = styleSheets[i];
  4799.  
  4800.     // Skip any stylesheets that don't match the screen media type.
  4801.     var media = currentStyleSheet.media.mediaText.toLowerCase();
  4802.     if (media && (media.indexOf("screen") == -1) && (media.indexOf("all") == -1))
  4803.         continue;
  4804.  
  4805.     if (currentStyleSheet.title) {
  4806.       if (!currentStyleSheet.disabled)
  4807.         altStyleSelected = true;
  4808.  
  4809.       haveAltSheets = true;
  4810.  
  4811.       var lastWithSameTitle = null;
  4812.       if (currentStyleSheet.title in currentStyleSheets)
  4813.         lastWithSameTitle = currentStyleSheets[currentStyleSheet.title];
  4814.  
  4815.       if (!lastWithSameTitle) {
  4816.         var menuItem = document.createElement("menuitem");
  4817.         menuItem.setAttribute("type", "radio");
  4818.         menuItem.setAttribute("label", currentStyleSheet.title);
  4819.         menuItem.setAttribute("data", currentStyleSheet.title);
  4820.         menuItem.setAttribute("checked", !currentStyleSheet.disabled && !styleDisabled);
  4821.         menuPopup.appendChild(menuItem);
  4822.         currentStyleSheets[currentStyleSheet.title] = menuItem;
  4823.       } else {
  4824.         if (currentStyleSheet.disabled)
  4825.           lastWithSameTitle.removeAttribute("checked");
  4826.       }
  4827.     }
  4828.   }
  4829.  
  4830.   noStyle.setAttribute("checked", styleDisabled);
  4831.   persistentOnly.setAttribute("checked", !altStyleSelected && !styleDisabled);
  4832.   persistentOnly.hidden = (window.content.document.preferredStyleSheetSet) ? haveAltSheets : false;
  4833.   sep.hidden = (noStyle.hidden && persistentOnly.hidden) || !haveAltSheets;
  4834.   return true;
  4835. }
  4836.  
  4837. function stylesheetInFrame(frame, title) {
  4838.   var docStyleSheets = frame.document.styleSheets;
  4839.  
  4840.   for (var i = 0; i < docStyleSheets.length; ++i) {
  4841.     if (docStyleSheets[i].title == title)
  4842.       return true;
  4843.   }
  4844.   return false;
  4845. }
  4846.  
  4847. function stylesheetSwitchFrame(frame, title) {
  4848.   var docStyleSheets = frame.document.styleSheets;
  4849.  
  4850.   for (var i = 0; i < docStyleSheets.length; ++i) {
  4851.     var docStyleSheet = docStyleSheets[i];
  4852.  
  4853.     if (title == "_nostyle")
  4854.       docStyleSheet.disabled = true;
  4855.     else if (docStyleSheet.title)
  4856.       docStyleSheet.disabled = (docStyleSheet.title != title);
  4857.     else if (docStyleSheet.disabled)
  4858.       docStyleSheet.disabled = false;
  4859.   }
  4860. }
  4861.  
  4862. function stylesheetSwitchAll(frameset, title) {
  4863.   if (!title || title == "_nostyle" || stylesheetInFrame(frameset, title)) {
  4864.     stylesheetSwitchFrame(frameset, title);
  4865.   }
  4866.   for (var i = 0; i < frameset.frames.length; i++) {
  4867.     stylesheetSwitchAll(frameset.frames[i], title);
  4868.   }
  4869. }
  4870.  
  4871. function setStyleDisabled(disabled) {
  4872.   getMarkupDocumentViewer().authorStyleDisabled = disabled;
  4873. }
  4874.  
  4875. /* End of the Page Style functions */
  4876.  
  4877. var BrowserOffline = {
  4878.   /////////////////////////////////////////////////////////////////////////////
  4879.   // BrowserOffline Public Methods
  4880.   init: function ()
  4881.   {
  4882.     if (!this._uiElement)
  4883.       this._uiElement = document.getElementById("goOfflineMenuitem");
  4884.  
  4885.     var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4886.     os.addObserver(this, "network:offline-status-changed", false);
  4887.  
  4888.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].
  4889.       getService(Components.interfaces.nsIIOService2);
  4890.  
  4891.     // if ioService is managing the offline status, then ioservice.offline
  4892.     // is already set correctly. We will continue to allow the ioService
  4893.     // to manage its offline state until the user uses the "Work Offline" UI.
  4894.     
  4895.     if (!ioService.manageOfflineStatus) {
  4896.       // set the initial state
  4897.       var isOffline = false;
  4898.       try {
  4899.         isOffline = gPrefService.getBoolPref("browser.offline");
  4900.       }
  4901.       catch (e) { }
  4902.       ioService.offline = isOffline;
  4903.     }
  4904.     
  4905.     this._updateOfflineUI(ioService.offline);
  4906.   },
  4907.  
  4908.   uninit: function ()
  4909.   {
  4910.     try {
  4911.       var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4912.       os.removeObserver(this, "network:offline-status-changed");
  4913.     } catch (ex) {
  4914.     }
  4915.   },
  4916.  
  4917.   toggleOfflineStatus: function ()
  4918.   {
  4919.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].
  4920.       getService(Components.interfaces.nsIIOService2);
  4921.  
  4922.     // Stop automatic management of the offline status
  4923.     try {
  4924.       ioService.manageOfflineStatus = false;
  4925.     } catch (ex) {
  4926.     }
  4927.   
  4928.     if (!ioService.offline && !this._canGoOffline()) {
  4929.       this._updateOfflineUI(false);
  4930.       return;
  4931.     }
  4932.  
  4933.     ioService.offline = !ioService.offline;
  4934.  
  4935.     // Save the current state for later use as the initial state
  4936.     // (if there is no netLinkService)
  4937.     gPrefService.setBoolPref("browser.offline", ioService.offline);
  4938.   },
  4939.  
  4940.   /////////////////////////////////////////////////////////////////////////////
  4941.   // nsIObserver
  4942.   observe: function (aSubject, aTopic, aState)
  4943.   {
  4944.     if (aTopic != "network:offline-status-changed")
  4945.       return;
  4946.  
  4947.     this._updateOfflineUI(aState == "offline");
  4948.   },
  4949.  
  4950.   /////////////////////////////////////////////////////////////////////////////
  4951.   // BrowserOffline Implementation Methods
  4952.   _canGoOffline: function ()
  4953.   {
  4954.     var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4955.     if (os) {
  4956.       try {
  4957.         var cancelGoOffline = Components.classes["@mozilla.org/supports-PRBool;1"].createInstance(Components.interfaces.nsISupportsPRBool);
  4958.         os.notifyObservers(cancelGoOffline, "offline-requested", null);
  4959.  
  4960.         // Something aborted the quit process.
  4961.         if (cancelGoOffline.data)
  4962.           return false;
  4963.       }
  4964.       catch (ex) {
  4965.       }
  4966.     }
  4967.     return true;
  4968.   },
  4969.  
  4970.   _uiElement: null,
  4971.   _updateOfflineUI: function (aOffline)
  4972.   {
  4973.     var offlineLocked = gPrefService.prefIsLocked("network.online");
  4974.     if (offlineLocked)
  4975.       this._uiElement.setAttribute("disabled", "true");
  4976.  
  4977.     this._uiElement.setAttribute("checked", aOffline);
  4978.   }
  4979. };
  4980.  
  4981. var OfflineApps = {
  4982.   /////////////////////////////////////////////////////////////////////////////
  4983.   // OfflineApps Public Methods
  4984.   init: function ()
  4985.   {
  4986.     var obs = Cc["@mozilla.org/observer-service;1"].
  4987.               getService(Ci.nsIObserverService);
  4988.     obs.addObserver(this, "dom-storage-warn-quota-exceeded", false);
  4989.     obs.addObserver(this, "offline-cache-update-completed", false);
  4990.   },
  4991.  
  4992.   uninit: function ()
  4993.   {
  4994.     var obs = Cc["@mozilla.org/observer-service;1"].
  4995.               getService(Ci.nsIObserverService);
  4996.     obs.removeObserver(this, "dom-storage-warn-quota-exceeded");
  4997.     obs.removeObserver(this, "offline-cache-update-completed");
  4998.   },
  4999.  
  5000.   /////////////////////////////////////////////////////////////////////////////
  5001.   // OfflineApps Implementation Methods
  5002.  
  5003.   // XXX: _getBrowserWindowForContentWindow and _getBrowserForContentWindow
  5004.   // were taken from browser/components/feeds/src/WebContentConverter.
  5005.   _getBrowserWindowForContentWindow: function(aContentWindow) {
  5006.     return aContentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  5007.                          .getInterface(Ci.nsIWebNavigation)
  5008.                          .QueryInterface(Ci.nsIDocShellTreeItem)
  5009.                          .rootTreeItem
  5010.                          .QueryInterface(Ci.nsIInterfaceRequestor)
  5011.                          .getInterface(Ci.nsIDOMWindow)
  5012.                          .wrappedJSObject;
  5013.   },
  5014.  
  5015.   _getBrowserForContentWindow: function(aBrowserWindow, aContentWindow) {
  5016.     // This depends on pseudo APIs of browser.js and tabbrowser.xml
  5017.     aContentWindow = aContentWindow.top;
  5018.     var browsers = aBrowserWindow.getBrowser().browsers;
  5019.     for (var i = 0; i < browsers.length; ++i) {
  5020.       if (browsers[i].contentWindow == aContentWindow)
  5021.         return browsers[i];
  5022.     }
  5023.   },
  5024.  
  5025.   _getManifestURI: function(aWindow) {
  5026.     var attr = aWindow.document.documentElement.getAttribute("manifest");
  5027.     if (!attr) return null;
  5028.  
  5029.     try {
  5030.       var ios = Cc["@mozilla.org/network/io-service;1"].
  5031.                 getService(Ci.nsIIOService);
  5032.  
  5033.       var contentURI = ios.newURI(aWindow.location.href, null, null);
  5034.       return ios.newURI(attr, aWindow.document.characterSet, contentURI);
  5035.     } catch (e) {
  5036.       return null;
  5037.     }
  5038.   },
  5039.  
  5040.   // A cache update isn't tied to a specific window.  Try to find
  5041.   // the best browser in which to warn the user about space usage
  5042.   _getBrowserForCacheUpdate: function(aCacheUpdate) {
  5043.     // Prefer the current browser
  5044.     var uri = this._getManifestURI(gBrowser.mCurrentBrowser.contentWindow);
  5045.     if (uri && uri.equals(aCacheUpdate.manifestURI)) {
  5046.       return gBrowser.mCurrentBrowser;
  5047.     }
  5048.  
  5049.     var browsers = getBrowser().browsers;
  5050.     for (var i = 0; i < browsers.length; ++i) {
  5051.       uri = this._getManifestURI(browsers[i].contentWindow);
  5052.       if (uri && uri.equals(aCacheUpdate.manifestURI)) {
  5053.         return browsers[i];
  5054.       }
  5055.     }
  5056.  
  5057.     return null;
  5058.   },
  5059.  
  5060.   _warnUsage: function(aBrowser, aURI) {
  5061.     if (!aBrowser)
  5062.       return;
  5063.  
  5064.     var notificationBox = gBrowser.getNotificationBox(aBrowser);
  5065.     var notification = notificationBox.getNotificationWithValue("offline-app-usage");
  5066.     if (!notification) {
  5067.       var bundle_browser = document.getElementById("bundle_browser");
  5068.  
  5069.       var buttons = [{
  5070.           label: bundle_browser.getString("offlineApps.manageUsage"),
  5071.           accessKey: bundle_browser.getString("offlineApps.manageUsageAccessKey"),
  5072.           callback: OfflineApps.manage
  5073.         }];
  5074.  
  5075.       var warnQuota = gPrefService.getIntPref("offline-apps.quota.warn");
  5076.       const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  5077.       var message = bundle_browser.getFormattedString("offlineApps.usage",
  5078.                                                       [ aURI.host,
  5079.                                                         warnQuota / 1024 ]);
  5080.  
  5081.       notificationBox.appendNotification(message, "offline-app-usage",
  5082.                                          "chrome://browser/skin/Info.png",
  5083.                                          priority, buttons);
  5084.     }
  5085.  
  5086.     // Now that we've warned once, prevent the warning from showing up
  5087.     // again.
  5088.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5089.              getService(Ci.nsIPermissionManager);
  5090.     pm.add(aURI, "offline-app",
  5091.            Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN);
  5092.   },
  5093.  
  5094.   // XXX: duplicated in preferences/advanced.js
  5095.   _getOfflineAppUsage: function (host)
  5096.   {
  5097.     var cacheService = Components.classes["@mozilla.org/network/cache-service;1"].
  5098.                        getService(Components.interfaces.nsICacheService);
  5099.     var cacheSession = cacheService.createSession("HTTP-offline",
  5100.                                                   Components.interfaces.nsICache.STORE_OFFLINE,
  5101.                                                   true).
  5102.                        QueryInterface(Components.interfaces.nsIOfflineCacheSession);
  5103.     var usage = cacheSession.getDomainUsage(host);
  5104.  
  5105.     var storageManager = Components.classes["@mozilla.org/dom/storagemanager;1"].
  5106.                          getService(Components.interfaces.nsIDOMStorageManager);
  5107.     usage += storageManager.getUsage(host);
  5108.  
  5109.     return usage;
  5110.   },
  5111.  
  5112.   _checkUsage: function(aURI) {
  5113.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5114.              getService(Ci.nsIPermissionManager);
  5115.  
  5116.     // if the user has already allowed excessive usage, don't bother checking
  5117.     if (pm.testExactPermission(aURI, "offline-app") !=
  5118.         Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN) {
  5119.       var usage = this._getOfflineAppUsage(aURI.asciiHost);
  5120.       var warnQuota = gPrefService.getIntPref("offline-apps.quota.warn");
  5121.       if (usage >= warnQuota * 1024) {
  5122.         return true;
  5123.       }
  5124.     }
  5125.  
  5126.     return false;
  5127.   },
  5128.  
  5129.   offlineAppRequested: function(aContentWindow) {
  5130.     if (!gPrefService.getBoolPref("browser.offline-apps.notify")) {
  5131.       return;
  5132.     }
  5133.  
  5134.     var browserWindow = this._getBrowserWindowForContentWindow(aContentWindow);
  5135.     var browser = this._getBrowserForContentWindow(browserWindow,
  5136.                                                    aContentWindow);
  5137.  
  5138.     var currentURI = browser.webNavigation.currentURI;
  5139.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5140.              getService(Ci.nsIPermissionManager);
  5141.  
  5142.     // don't bother showing UI if the user has already made a decision
  5143.     if (pm.testExactPermission(currentURI, "offline-app") !=
  5144.         Ci.nsIPermissionManager.UNKNOWN_ACTION)
  5145.       return;
  5146.  
  5147.     try {
  5148.       if (gPrefService.getBoolPref("offline-apps.allow_by_default")) {
  5149.         // all pages can use offline capabilities, no need to ask the user
  5150.         return;
  5151.       }
  5152.     } catch(e) {
  5153.       // this pref isn't set by default, ignore failures
  5154.     }
  5155.  
  5156.     var notificationBox = gBrowser.getNotificationBox(browser);
  5157.     var notification = notificationBox.getNotificationWithValue("offline-app-requested");
  5158.     if (!notification) {
  5159.       var bundle_browser = document.getElementById("bundle_browser");
  5160.  
  5161.       var buttons = [{
  5162.         label: bundle_browser.getString("offlineApps.allow"),
  5163.         accessKey: bundle_browser.getString("offlineApps.allowAccessKey"),
  5164.         callback: function() { OfflineApps.allowSite(); }
  5165.       },{
  5166.         label: bundle_browser.getString("offlineApps.never"),
  5167.         accessKey: bundle_browser.getString("offlineApps.neverAccessKey"),
  5168.         callback: function() { OfflineApps.disallowSite(); }
  5169.       },{
  5170.         label: bundle_browser.getString("offlineApps.notNow"),
  5171.         accessKey: bundle_browser.getString("offlineApps.notNowAccessKey"),
  5172.         callback: function() { /* noop */ }
  5173.       }];
  5174.  
  5175.       const priority = notificationBox.PRIORITY_INFO_LOW;
  5176.       var message = bundle_browser.getFormattedString("offlineApps.available",
  5177.                                                       [ currentURI.host ]);
  5178.       notificationBox.appendNotification(message, "offline-app-requested",
  5179.                                          "chrome://browser/skin/Info.png",
  5180.                                          priority, buttons);
  5181.     }
  5182.   },
  5183.  
  5184.   allowSite: function() {
  5185.     var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI;
  5186.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5187.              getService(Ci.nsIPermissionManager);
  5188.     pm.add(currentURI, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
  5189.  
  5190.     // When a site is enabled while loading, <link rel="offline-resource">
  5191.     // resources will start fetching immediately.  This one time we need to
  5192.     // do it ourselves.
  5193.     this._startFetching();
  5194.   },
  5195.  
  5196.   disallowSite: function() {
  5197.     var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI;
  5198.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5199.              getService(Ci.nsIPermissionManager);
  5200.     pm.add(currentURI, "offline-app", Ci.nsIPermissionManager.DENY_ACTION);
  5201.   },
  5202.  
  5203.   manage: function() {
  5204.     openAdvancedPreferences("networkTab");
  5205.   },
  5206.  
  5207.   _startFetching: function() {
  5208.     var manifest = content.document.documentElement.getAttribute("manifest");
  5209.     if (!manifest)
  5210.       return;
  5211.  
  5212.     var ios = Cc["@mozilla.org/network/io-service;1"].
  5213.               getService(Ci.nsIIOService);
  5214.  
  5215.     var contentURI = ios.newURI(content.location.href, null, null);
  5216.     var manifestURI = ios.newURI(manifest, content.document.characterSet,
  5217.                                  contentURI);
  5218.  
  5219.     var updateService = Cc["@mozilla.org/offlinecacheupdate-service;1"].
  5220.                         getService(Ci.nsIOfflineCacheUpdateService);
  5221.     updateService.scheduleUpdate(manifestURI, contentURI);
  5222.   },
  5223.  
  5224.   /////////////////////////////////////////////////////////////////////////////
  5225.   // nsIObserver
  5226.   observe: function (aSubject, aTopic, aState)
  5227.   {
  5228.     if (aTopic == "dom-storage-warn-quota-exceeded") {
  5229.       if (aSubject) {
  5230.         var uri = Cc["@mozilla.org/network/io-service;1"].
  5231.                   getService(Ci.nsIIOService).
  5232.                   newURI(aSubject.location.href, null, null);
  5233.  
  5234.         if (OfflineApps._checkUsage(uri)) {
  5235.           var browserWindow =
  5236.             this._getBrowserWindowForContentWindow(aSubject);
  5237.           var browser = this._getBrowserForContentWindow(browserWindow,
  5238.                                                          aSubject);
  5239.           OfflineApps._warnUsage(browser, uri);
  5240.         }
  5241.       }
  5242.     } else if (aTopic == "offline-cache-update-completed") {
  5243.       var cacheUpdate = aSubject.QueryInterface(Ci.nsIOfflineCacheUpdate);
  5244.  
  5245.       var uri = cacheUpdate.manifestURI;
  5246.       if (OfflineApps._checkUsage(uri)) {
  5247.         var browser = this._getBrowserForCacheUpdate(cacheUpdate);
  5248.         if (browser) {
  5249.           OfflineApps._warnUsage(browser, cacheUpdate.manifestURI);
  5250.         }
  5251.       }
  5252.     }
  5253.   }
  5254. };
  5255.  
  5256. function WindowIsClosing()
  5257. {
  5258.   var browser = getBrowser();
  5259.   var cn = browser.tabContainer.childNodes;
  5260.   var numtabs = cn.length;
  5261.   var reallyClose = true;
  5262.  
  5263.   for (var i = 0; reallyClose && i < numtabs; ++i) {
  5264.     var ds = browser.getBrowserForTab(cn[i]).docShell;
  5265.  
  5266.     if (ds.contentViewer && !ds.contentViewer.permitUnload())
  5267.       reallyClose = false;
  5268.   }
  5269.  
  5270.   if (!reallyClose)
  5271.     return false;
  5272.  
  5273.   // closeWindow takes a second optional function argument to open up a
  5274.   // window closing warning dialog if we're not quitting. (Quitting opens
  5275.   // up another dialog so we don't need to.)
  5276.   return closeWindow(false,
  5277.     function () {
  5278.       return browser.warnAboutClosingTabs(true);
  5279.     });
  5280. }
  5281.  
  5282. var MailIntegration = {
  5283.   sendLinkForWindow: function (aWindow) {
  5284.     this.sendMessage(aWindow.location.href,
  5285.                      aWindow.document.title);
  5286.   },
  5287.  
  5288.   sendMessage: function (aBody, aSubject) {
  5289.     // generate a mailto url based on the url and the url's title
  5290.     var mailtoUrl = "mailto:";
  5291.     if (aBody) {
  5292.       mailtoUrl += "?body=" + encodeURIComponent(aBody);
  5293.       mailtoUrl += "&subject=" + encodeURIComponent(aSubject);
  5294.     }
  5295.  
  5296.     var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  5297.                               .getService(Components.interfaces.nsIIOService);
  5298.     var uri = ioService.newURI(mailtoUrl, null, null);
  5299.  
  5300.     // now pass this uri to the operating system
  5301.     this._launchExternalUrl(uri);
  5302.   },
  5303.  
  5304.   // a generic method which can be used to pass arbitrary urls to the operating
  5305.   // system.
  5306.   // aURL --> a nsIURI which represents the url to launch
  5307.   _launchExternalUrl: function (aURL) {
  5308.     var extProtocolSvc =
  5309.        Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]
  5310.                  .getService(Components.interfaces.nsIExternalProtocolService);
  5311.     if (extProtocolSvc)
  5312.       extProtocolSvc.loadUrl(aURL);
  5313.   }
  5314. };
  5315.  
  5316. function BrowserOpenAddonsMgr()
  5317. {
  5318.   const EMTYPE = "Extension:Manager";
  5319.   var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  5320.                      .getService(Components.interfaces.nsIWindowMediator);
  5321.   var theEM = wm.getMostRecentWindow(EMTYPE);
  5322.   if (theEM) {
  5323.     theEM.focus();
  5324.     return;
  5325.   }
  5326.  
  5327.   const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  5328.   const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
  5329.   window.openDialog(EMURL, "", EMFEATURES);
  5330. }
  5331.  
  5332. function escapeNameValuePair(aName, aValue, aIsFormUrlEncoded)
  5333. {
  5334.   if (aIsFormUrlEncoded)
  5335.     return escape(aName + "=" + aValue);
  5336.   else
  5337.     return escape(aName) + "=" + escape(aValue);
  5338. }
  5339.  
  5340. function AddKeywordForSearchField()
  5341. {
  5342.   var node = document.popupNode;
  5343.  
  5344.   var charset = node.ownerDocument.characterSet;
  5345.  
  5346.   var docURI = makeURI(node.ownerDocument.URL,
  5347.                        charset);
  5348.  
  5349.   var formURI = makeURI(node.form.getAttribute("action"),
  5350.                         charset,
  5351.                         docURI);
  5352.  
  5353.   var spec = formURI.spec;
  5354.  
  5355.   var isURLEncoded = 
  5356.                (node.form.method.toUpperCase() == "POST"
  5357.                 && (node.form.enctype == "application/x-www-form-urlencoded" ||
  5358.                     node.form.enctype == ""));
  5359.  
  5360.   var el, type;
  5361.   var formData = [];
  5362.  
  5363.   for (var i=0; i < node.form.elements.length; i++) {
  5364.     el = node.form.elements[i];
  5365.  
  5366.     if (!el.type) // happens with fieldsets
  5367.       continue;
  5368.  
  5369.     if (el == node) {
  5370.       formData.push((isURLEncoded) ? escapeNameValuePair(el.name, "%s", true) :
  5371.                                      // Don't escape "%s", just append
  5372.                                      escapeNameValuePair(el.name, "", false) + "%s");
  5373.       continue;
  5374.     }
  5375.  
  5376.     type = el.type.toLowerCase();
  5377.     
  5378.     if ((type == "text" || type == "hidden" || type == "textarea") ||
  5379.         ((type == "checkbox" || type == "radio") && el.checked)) {
  5380.       formData.push(escapeNameValuePair(el.name, el.value, isURLEncoded));
  5381.     } else if (el instanceof HTMLSelectElement && el.selectedIndex >= 0) {
  5382.       for (var j=0; j < el.options.length; j++) {
  5383.         if (el.options[j].selected)
  5384.           formData.push(escapeNameValuePair(el.name, el.options[j].value,
  5385.                                             isURLEncoded));
  5386.       }
  5387.     }
  5388.   }
  5389.  
  5390.   var postData;
  5391.  
  5392.   if (isURLEncoded)
  5393.     postData = formData.join("&");
  5394.   else
  5395.     spec += "?" + formData.join("&");
  5396.  
  5397.   var description = PlacesUIUtils.getDescriptionFromDocument(node.ownerDocument);
  5398.   PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(spec), "", description, null,
  5399.                                          null, null, "", postData, charset);
  5400. }
  5401.  
  5402. function SwitchDocumentDirection(aWindow) {
  5403.   aWindow.document.dir = (aWindow.document.dir == "ltr" ? "rtl" : "ltr");
  5404.   for (var run = 0; run < aWindow.frames.length; run++)
  5405.     SwitchDocumentDirection(aWindow.frames[run]);
  5406. }
  5407.  
  5408. function missingPluginInstaller(){
  5409. }
  5410.  
  5411. function getPluginInfo(pluginElement)
  5412. {
  5413.   var tagMimetype;
  5414.   var pluginsPage;
  5415.   if (pluginElement instanceof HTMLAppletElement) {
  5416.     tagMimetype = "application/x-java-vm";
  5417.   } else {
  5418.     if (pluginElement instanceof HTMLObjectElement) {
  5419.       pluginsPage = pluginElement.getAttribute("codebase");
  5420.     } else {
  5421.       pluginsPage = pluginElement.getAttribute("pluginspage");
  5422.     }
  5423.  
  5424.     // only attempt if a pluginsPage is defined.
  5425.     if (pluginsPage) {
  5426.       var doc = pluginElement.ownerDocument;
  5427.       var docShell = findChildShell(doc, gBrowser.selectedBrowser.docShell, null);
  5428.       try {
  5429.         pluginsPage = makeURI(pluginsPage, doc.characterSet, docShell.currentURI).spec;
  5430.       } catch (ex) { 
  5431.         pluginsPage = "";
  5432.       }
  5433.     }
  5434.  
  5435.     tagMimetype = pluginElement.QueryInterface(Components.interfaces.nsIObjectLoadingContent)
  5436.                                .actualType;
  5437.  
  5438.     if (tagMimetype == "") {
  5439.       tagMimetype = pluginElement.type;
  5440.     }
  5441.   }
  5442.  
  5443.   return {mimetype: tagMimetype, pluginsPage: pluginsPage};
  5444. }
  5445.  
  5446. missingPluginInstaller.prototype.installSinglePlugin = function(aEvent){
  5447.   var tabbrowser = getBrowser();
  5448.   var missingPluginsArray = {};
  5449.  
  5450.   var pluginInfo = getPluginInfo(aEvent.target);
  5451.   missingPluginsArray[pluginInfo.mimetype] = pluginInfo;
  5452.  
  5453.   gBrowser.selectedBrowser.addEventListener("NewPluginInstalled",
  5454.                                             gMissingPluginInstaller.refreshBrowserAndPlugins,
  5455.                                             false);
  5456.  
  5457.   if (missingPluginsArray) {
  5458.     window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul",
  5459.                       "PFSWindow", "chrome,centerscreen,resizable=yes",
  5460.                       {plugins: missingPluginsArray, browser: tabbrowser.selectedBrowser});
  5461.   }
  5462.  
  5463.   tabbrowser.selectedBrowser.removeEventListener("NewPluginInstalled",
  5464.                                                  gMissingPluginInstaller.refreshBrowserAndPlugins,
  5465.                                                  false);
  5466.  
  5467.   aEvent.preventDefault();
  5468. }
  5469.  
  5470. missingPluginInstaller.prototype.newMissingPlugin = function(aEvent){
  5471.   // Since we are expecting also untrusted events, make sure
  5472.   // that the target is a plugin
  5473.   if (!(aEvent.target instanceof Components.interfaces.nsIObjectLoadingContent))
  5474.     return;
  5475.  
  5476.   // For broken non-object plugin tags, register a click handler so
  5477.   // that the user can click the plugin replacement to get the new
  5478.   // plugin. Object tags can, and often do, deal with that themselves,
  5479.   // so don't stomp on the page developers toes.
  5480.  
  5481.   if (aEvent.type != "PluginBlocklisted" &&
  5482.       !(aEvent.target instanceof HTMLObjectElement)) {
  5483.     aEvent.target.addEventListener("click",
  5484.                                    gMissingPluginInstaller.installSinglePlugin,
  5485.                                    false);
  5486.   }
  5487.  
  5488.   try {
  5489.     if (gPrefService.getBoolPref("plugins.hide_infobar_for_missing_plugin"))
  5490.       return;
  5491.   } catch (ex) {} // if the pref is missing, treat it as false, which shows the infobar
  5492.  
  5493.   var tabbrowser = getBrowser();
  5494.   const browsers = tabbrowser.mPanelContainer.childNodes;
  5495.  
  5496.   var contentWindow = aEvent.target.ownerDocument.defaultView.top;
  5497.  
  5498.   var i = 0;
  5499.   for (; i < browsers.length; i++) {
  5500.     if (tabbrowser.getBrowserAtIndex(i).contentWindow == contentWindow)
  5501.       break;
  5502.   }
  5503.  
  5504.   var browser = tabbrowser.getBrowserAtIndex(i);
  5505.   if (!browser.missingPlugins)
  5506.     browser.missingPlugins = {};
  5507.  
  5508.   var pluginInfo = getPluginInfo(aEvent.target);
  5509.  
  5510.   browser.missingPlugins[pluginInfo.mimetype] = pluginInfo;
  5511.  
  5512.   var notificationBox = gBrowser.getNotificationBox(browser);
  5513.  
  5514.   // If there is already a missing plugin notification then do nothing
  5515.   if (notificationBox.getNotificationWithValue("missing-plugins"))
  5516.     return;
  5517.  
  5518.   var bundle_browser = document.getElementById("bundle_browser");
  5519.   var blockedNotification = notificationBox.getNotificationWithValue("blocked-plugins");
  5520.   const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  5521.   const iconURL = "chrome://mozapps/skin/plugins/pluginGeneric-16.png";
  5522.  
  5523.   if (aEvent.type == "PluginBlocklisted" && !blockedNotification) {
  5524.     var messageString = bundle_browser.getString("blockedpluginsMessage.title");
  5525.     var buttons = [{
  5526.       label: bundle_browser.getString("blockedpluginsMessage.infoButton.label"),
  5527.       accessKey: bundle_browser.getString("blockedpluginsMessage.infoButton.accesskey"),
  5528.       popup: null,
  5529.       callback: blocklistInfo
  5530.     }, {
  5531.       label: bundle_browser.getString("blockedpluginsMessage.searchButton.label"),
  5532.       accessKey: bundle_browser.getString("blockedpluginsMessage.searchButton.accesskey"),
  5533.       popup: null,
  5534.       callback: pluginsMissing
  5535.     }];
  5536.  
  5537.     notificationBox.appendNotification(messageString, "blocked-plugins",
  5538.                                        iconURL, priority, buttons);
  5539.   }
  5540.  
  5541.   if (aEvent.type == "PluginNotFound") {
  5542.     // Cancel any notification about blocklisting
  5543.     if (blockedNotification)
  5544.       blockedNotification.close();
  5545.  
  5546.     var messageString = bundle_browser.getString("missingpluginsMessage.title");
  5547.     var buttons = [{
  5548.       label: bundle_browser.getString("missingpluginsMessage.button.label"),
  5549.       accessKey: bundle_browser.getString("missingpluginsMessage.button.accesskey"),
  5550.       popup: null,
  5551.       callback: pluginsMissing
  5552.     }];
  5553.  
  5554.     notificationBox.appendNotification(messageString, "missing-plugins",
  5555.                                        iconURL, priority, buttons);
  5556.   }
  5557. }
  5558.  
  5559. missingPluginInstaller.prototype.refreshBrowserAndPlugins = function(aEvent) {
  5560.   // browser elements are anonymous so we can't just use target.
  5561.   var browser = aEvent.originalTarget;
  5562.   var notificationBox = gBrowser.getNotificationBox(browser);
  5563.   var notification = notificationBox.getNotificationWithValue("missing-plugins");
  5564.  
  5565.   // clear the plugin list, now that at least one plugin has been installed
  5566.   browser.missingPlugins = null;
  5567.   if (notification) {
  5568.     // reset UI
  5569.     notificationBox.removeNotification(notification);
  5570.   }
  5571.  
  5572.   // reload plugins
  5573.   var pm = Components.classes["@mozilla.org/plugin/manager;1"]
  5574.         .getService(Components.interfaces.nsIPluginManager);
  5575.   pm.reloadPlugins(false);
  5576.  
  5577.   // ... and reload the browser to activate new plugins available
  5578.   browser.reload();
  5579. }
  5580.  
  5581. function blocklistInfo()
  5582. {
  5583.   var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  5584.                             .getService(Components.interfaces.nsIURLFormatter);
  5585.   var url = formatter.formatURLPref("extensions.blocklist.detailsURL");
  5586.   gBrowser.loadOneTab(url, null, null, null, false, false);
  5587.   return true;
  5588. }
  5589.  
  5590. function pluginsMissing()
  5591. {
  5592.   // get the urls of missing plugins
  5593.   var tabbrowser = getBrowser();
  5594.   var missingPluginsArray = tabbrowser.selectedBrowser.missingPlugins;
  5595.   tabbrowser.selectedBrowser.addEventListener("NewPluginInstalled",
  5596.                                               gMissingPluginInstaller.refreshBrowserAndPlugins,
  5597.                                               false);
  5598.   if (missingPluginsArray) {
  5599.     window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul",
  5600.                       "PFSWindow", "chrome,centerscreen,resizable=yes",
  5601.                       {plugins: missingPluginsArray, browser: tabbrowser.selectedBrowser});
  5602.   }
  5603.   tabbrowser.selectedBrowser.removeEventListener("NewPluginInstalled",
  5604.                                                  gMissingPluginInstaller.refreshBrowserAndPlugins,
  5605.                                                  false);
  5606. }
  5607.  
  5608. var gMissingPluginInstaller = new missingPluginInstaller();
  5609.  
  5610. function convertFromUnicode(charset, str)
  5611. {
  5612.   try {
  5613.     var unicodeConverter = Components
  5614.        .classes["@mozilla.org/intl/scriptableunicodeconverter"]
  5615.        .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  5616.     unicodeConverter.charset = charset;
  5617.     str = unicodeConverter.ConvertFromUnicode(str);
  5618.     return str + unicodeConverter.Finish();
  5619.   } catch(ex) {
  5620.     return null; 
  5621.   }
  5622. }
  5623.  
  5624. /**
  5625.  * The Feed Handler object manages discovery of RSS/ATOM feeds in web pages
  5626.  * and shows UI when they are discovered. 
  5627.  */
  5628. var FeedHandler = {
  5629.   /**
  5630.    * The click handler for the Feed icon in the location bar. Opens the
  5631.    * subscription page if user is not given a choice of feeds.
  5632.    * (Otherwise the list of available feeds will be presented to the 
  5633.    * user in a popup menu.)
  5634.    */
  5635.   onFeedButtonClick: function(event) {
  5636.     event.stopPropagation();
  5637.  
  5638.     if (event.target.hasAttribute("feed") &&
  5639.         event.eventPhase == Event.AT_TARGET &&
  5640.         (event.button == 0 || event.button == 1)) {
  5641.         this.subscribeToFeed(null, event);
  5642.     }
  5643.   },
  5644.   
  5645.   /**
  5646.    * Called when the user clicks on the Feed icon in the location bar. 
  5647.    * Builds a menu of unique feeds associated with the page, and if there
  5648.    * is only one, shows the feed inline in the browser window. 
  5649.    * @param   menuPopup
  5650.    *          The feed list menupopup to be populated.
  5651.    * @returns true if the menu should be shown, false if there was only
  5652.    *          one feed and the feed should be shown inline in the browser
  5653.    *          window (do not show the menupopup).
  5654.    */
  5655.   buildFeedList: function(menuPopup) {
  5656.     var feeds = gBrowser.selectedBrowser.feeds;
  5657.     if (feeds == null) {
  5658.       // XXX hack -- menu opening depends on setting of an "open"
  5659.       // attribute, and the menu refuses to open if that attribute is
  5660.       // set (because it thinks it's already open).  onpopupshowing gets
  5661.       // called after the attribute is unset, and it doesn't get unset
  5662.       // if we return false.  so we unset it here; otherwise, the menu
  5663.       // refuses to work past this point.
  5664.       menuPopup.parentNode.removeAttribute("open");
  5665.       return false;
  5666.     }
  5667.  
  5668.     while (menuPopup.firstChild)
  5669.       menuPopup.removeChild(menuPopup.firstChild);
  5670.  
  5671.     if (feeds.length == 1) {
  5672.       var feedButton = document.getElementById("feed-button");
  5673.       if (feedButton)
  5674.         feedButton.setAttribute("feed", feeds[0].href);
  5675.       return false;
  5676.     }
  5677.  
  5678.     // Build the menu showing the available feed choices for viewing. 
  5679.     for (var i = 0; i < feeds.length; ++i) {
  5680.       var feedInfo = feeds[i];
  5681.       var menuItem = document.createElement("menuitem");
  5682.       var baseTitle = feedInfo.title || feedInfo.href;
  5683.       var labelStr = gNavigatorBundle.getFormattedString("feedShowFeedNew", [baseTitle]);
  5684.       menuItem.setAttribute("label", labelStr);
  5685.       menuItem.setAttribute("feed", feedInfo.href);
  5686.       menuItem.setAttribute("tooltiptext", feedInfo.href);
  5687.       menuItem.setAttribute("crop", "center");
  5688.       menuPopup.appendChild(menuItem);
  5689.     }
  5690.     return true;
  5691.   },
  5692.   
  5693.   /**
  5694.    * Subscribe to a given feed.  Called when
  5695.    *   1. Page has a single feed and user clicks feed icon in location bar
  5696.    *   2. Page has a single feed and user selects Subscribe menu item
  5697.    *   3. Page has multiple feeds and user selects from feed icon popup
  5698.    *   4. Page has multiple feeds and user selects from Subscribe submenu
  5699.    * @param   href
  5700.    *          The feed to subscribe to. May be null, in which case the
  5701.    *          event target's feed attribute is examined.
  5702.    * @param   event
  5703.    *          The event this method is handling. Used to decide where 
  5704.    *          to open the preview UI. (Optional, unless href is null)
  5705.    */
  5706.   subscribeToFeed: function(href, event) {
  5707.     // Just load the feed in the content area to either subscribe or show the
  5708.     // preview UI
  5709.     if (!href)
  5710.       href = event.target.getAttribute("feed");
  5711.     urlSecurityCheck(href, gBrowser.contentPrincipal,
  5712.                      Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
  5713.     var feedURI = makeURI(href, document.characterSet);
  5714.     // Use the feed scheme so X-Moz-Is-Feed will be set
  5715.     // The value doesn't matter
  5716.     if (/^https?/.test(feedURI.scheme))
  5717.       href = "feed:" + href;
  5718.     this.loadFeed(href, event);
  5719.   },
  5720.  
  5721.   loadFeed: function(href, event) {
  5722.     var feeds = gBrowser.selectedBrowser.feeds;
  5723.     try {
  5724.       openUILink(href, event, false, true, false, null);
  5725.     }
  5726.     finally {
  5727.       // We might default to a livebookmarks modal dialog, 
  5728.       // so reset that if the user happens to click it again
  5729.       gBrowser.selectedBrowser.feeds = feeds;
  5730.     }
  5731.   },
  5732.  
  5733.   /**
  5734.    * Update the browser UI to show whether or not feeds are available when
  5735.    * a page is loaded or the user switches tabs to a page that has feeds. 
  5736.    */
  5737.   updateFeeds: function() {
  5738.     var feedButton = document.getElementById("feed-button");
  5739.     if (!this._feedMenuitem)
  5740.       this._feedMenuitem = document.getElementById("subscribeToPageMenuitem");
  5741.     if (!this._feedMenupopup)
  5742.       this._feedMenupopup = document.getElementById("subscribeToPageMenupopup");
  5743.  
  5744.     var feeds = gBrowser.mCurrentBrowser.feeds;
  5745.     if (!feeds || feeds.length == 0) {
  5746.       if (feedButton) {
  5747.         feedButton.removeAttribute("feeds");
  5748.         feedButton.removeAttribute("feed");
  5749.         feedButton.setAttribute("tooltiptext", 
  5750.                                 gNavigatorBundle.getString("feedNoFeeds"));
  5751.       }
  5752.       this._feedMenuitem.setAttribute("disabled", "true");
  5753.       this._feedMenupopup.setAttribute("hidden", "true");
  5754.       this._feedMenuitem.removeAttribute("hidden");
  5755.     } else {
  5756.       if (feedButton) {
  5757.         feedButton.setAttribute("feeds", "true");
  5758.         feedButton.setAttribute("tooltiptext", 
  5759.                                 gNavigatorBundle.getString("feedHasFeedsNew"));
  5760.       }
  5761.       
  5762.       if (feeds.length > 1) {
  5763.         this._feedMenuitem.setAttribute("hidden", "true");
  5764.         this._feedMenupopup.removeAttribute("hidden");
  5765.         if (feedButton)
  5766.           feedButton.removeAttribute("feed");
  5767.       } else {
  5768.         if (feedButton)
  5769.           feedButton.setAttribute("feed", feeds[0].href);
  5770.  
  5771.         this._feedMenuitem.setAttribute("feed", feeds[0].href);
  5772.         this._feedMenuitem.removeAttribute("disabled");
  5773.         this._feedMenuitem.removeAttribute("hidden");
  5774.         this._feedMenupopup.setAttribute("hidden", "true");
  5775.       }
  5776.     }
  5777.   }, 
  5778.  
  5779.   addFeed: function(feed, targetDoc) {
  5780.     if (feed) {
  5781.       // find which tab this is for, and set the attribute on the browser
  5782.       var browserForLink = gBrowser.getBrowserForDocument(targetDoc);
  5783.       if (!browserForLink) {
  5784.         // ??? this really shouldn't happen..
  5785.         return;
  5786.       }
  5787.  
  5788.       var feeds = [];
  5789.       if (browserForLink.feeds != null)
  5790.         feeds = browserForLink.feeds;
  5791.  
  5792.       feeds.push(feed);
  5793.       browserForLink.feeds = feeds;
  5794.       if (browserForLink == gBrowser || browserForLink == gBrowser.mCurrentBrowser) {
  5795.         var feedButton = document.getElementById("feed-button");
  5796.         if (feedButton) {
  5797.           feedButton.setAttribute("feeds", "true");
  5798.           feedButton.setAttribute("tooltiptext", 
  5799.                                   gNavigatorBundle.getString("feedHasFeedsNew"));
  5800.         }
  5801.       }
  5802.     }
  5803.   }
  5804. };
  5805.  
  5806. //@line 39 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-places.js"
  5807.  
  5808.  
  5809. var StarUI = {
  5810.   _itemId: -1,
  5811.   uri: null,
  5812.   _batching: false,
  5813.  
  5814.   // nsISupports
  5815.   QueryInterface: function SU_QueryInterface(aIID) {
  5816.     if (aIID.equals(Ci.nsIDOMEventListener) ||
  5817.         aIID.equals(Ci.nsISupports))
  5818.       return this;
  5819.  
  5820.     throw Cr.NS_NOINTERFACE;
  5821.   },
  5822.  
  5823.   _element: function(aID) {
  5824.     return document.getElementById(aID);
  5825.   },
  5826.  
  5827.   // Edit-bookmark panel
  5828.   get panel() {
  5829.     delete this.panel;
  5830.     var element = this._element("editBookmarkPanel");
  5831.     // initially the panel is hidden
  5832.     // to avoid impacting startup / new window performance
  5833.     element.hidden = false;
  5834.     element.addEventListener("popuphidden", this, false);
  5835.     element.addEventListener("keypress", this, true);
  5836.     return this.panel = element;
  5837.   },
  5838.  
  5839.   // list of command elements (by id) to disable when the panel is opened
  5840.   _blockedCommands: ["cmd_close", "cmd_closeWindow"],
  5841.   _blockCommands: function SU__blockCommands() {
  5842.     for each(var key in this._blockedCommands) {
  5843.       var elt = this._element(key);
  5844.       // make sure not to permanently disable this item (see bug 409155)
  5845.       if (elt.hasAttribute("wasDisabled"))
  5846.         continue;
  5847.       if (elt.getAttribute("disabled") == "true")
  5848.         elt.setAttribute("wasDisabled", "true");
  5849.       else {
  5850.         elt.setAttribute("wasDisabled", "false");
  5851.         elt.setAttribute("disabled", "true");
  5852.       }
  5853.     }
  5854.   },
  5855.  
  5856.   _restoreCommandsState: function SU__restoreCommandsState() {
  5857.     for each(var key in this._blockedCommands) {
  5858.       var elt = this._element(key);
  5859.       if (elt.getAttribute("wasDisabled") != "true")
  5860.         elt.removeAttribute("disabled");
  5861.       elt.removeAttribute("wasDisabled");
  5862.     }
  5863.   },
  5864.  
  5865.   // nsIDOMEventListener
  5866.   handleEvent: function SU_handleEvent(aEvent) {
  5867.     switch (aEvent.type) {
  5868.       case "popuphidden":
  5869.         if (aEvent.originalTarget == this.panel) {
  5870.           if (!this._element("editBookmarkPanelContent").hidden)
  5871.             this.quitEditMode();
  5872.           this._restoreCommandsState();
  5873.           this._itemId = -1;
  5874.           this._uri = null;
  5875.           if (this._batching) {
  5876.             PlacesUIUtils.ptm.endBatch();
  5877.             this._batching = false;
  5878.           }
  5879.         }
  5880.         break;
  5881.       case "keypress":
  5882.         if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) {
  5883.           // In edit mode, if we're not editing a folder, the ESC key is mapped
  5884.           // to the cancel button
  5885.           if (!this._element("editBookmarkPanelContent").hidden) {
  5886.             var elt = aEvent.target;
  5887.             if (elt.localName != "tree" ||
  5888.                 (elt.localName == "tree" && !elt.hasAttribute("editing")))
  5889.               this.cancelButtonOnCommand();
  5890.           }
  5891.         }
  5892.         else if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN) {
  5893.           // hide the panel unless the folder tree is focused
  5894.           if (aEvent.target.localName != "tree")
  5895.             this.panel.hidePopup();
  5896.         }
  5897.         break;
  5898.     }
  5899.   },
  5900.  
  5901.   _overlayLoaded: false,
  5902.   _overlayLoading: false,
  5903.   showEditBookmarkPopup:
  5904.   function SU_showEditBookmarkPopup(aItemId, aAnchorElement, aPosition) {
  5905.     // Performance: load the overlay the first time the panel is opened
  5906.     // (see bug 392443).
  5907.     if (this._overlayLoading)
  5908.       return;
  5909.  
  5910.     if (this._overlayLoaded) {
  5911.       this._doShowEditBookmarkPanel(aItemId, aAnchorElement, aPosition);
  5912.       return;
  5913.     }
  5914.  
  5915.     var loadObserver = {
  5916.       _self: this,
  5917.       _itemId: aItemId,
  5918.       _anchorElement: aAnchorElement,
  5919.       _position: aPosition,
  5920.       observe: function (aSubject, aTopic, aData) {
  5921.         this._self._overlayLoading = false;
  5922.         this._self._overlayLoaded = true;
  5923.         this._self._doShowEditBookmarkPanel(this._itemId, this._anchorElement,
  5924.                                             this._position);
  5925.       }
  5926.     };
  5927.     this._overlayLoading = true;
  5928.     document.loadOverlay("chrome://browser/content/places/editBookmarkOverlay.xul",
  5929.                          loadObserver);
  5930.   },
  5931.  
  5932.   _doShowEditBookmarkPanel:
  5933.   function SU__doShowEditBookmarkPanel(aItemId, aAnchorElement, aPosition) {
  5934.     this._blockCommands(); // un-done in the popuphiding handler
  5935.  
  5936.     var bundle = this._element("bundle_browser");
  5937.  
  5938.     // Set panel title:
  5939.     // if we are batching, i.e. the bookmark has been added now,
  5940.     // then show Page Bookmarked, else if the bookmark did already exist,
  5941.     // we are about editing it, then use Edit This Bookmark.
  5942.     this._element("editBookmarkPanelTitle").value =
  5943.       this._batching ?
  5944.         bundle.getString("editBookmarkPanel.pageBookmarkedTitle") :
  5945.         bundle.getString("editBookmarkPanel.editBookmarkTitle");
  5946.  
  5947.     // No description; show the Done, Cancel;
  5948.     // hide the Edit, Undo buttons
  5949.     this._element("editBookmarkPanelDescription").textContent = "";
  5950.     this._element("editBookmarkPanelBottomButtons").hidden = false;
  5951.     this._element("editBookmarkPanelContent").hidden = false;
  5952.     this._element("editBookmarkPanelEditButton").hidden = true;
  5953.     this._element("editBookmarkPanelUndoRemoveButton").hidden = true;
  5954.  
  5955.     // The remove button is shown only if we're not already batching, i.e.
  5956.     // if the cancel button/ESC does not remove the bookmark.
  5957.     this._element("editBookmarkPanelRemoveButton").hidden = this._batching;
  5958.  
  5959.     // unset the unstarred state, if set
  5960.     this._element("editBookmarkPanelStarIcon").removeAttribute("unstarred");
  5961.  
  5962.     this._itemId = aItemId !== undefined ? aItemId : this._itemId;
  5963.     this.beginBatch();
  5964.  
  5965.     // XXXmano hack: We push a no-op transaction on the stack so it's always
  5966.     // safe for the Cancel button to call undoTransaction after endBatch.
  5967.     // Otherwise, if no changes were done in the edit-item panel, the last
  5968.     // transaction on the undo stack may be the initial createItem transaction,
  5969.     // or worse, the batched editing of some other item.
  5970.     PlacesUIUtils.ptm.doTransaction({ doTransaction: function() { },
  5971.                                       undoTransaction: function() { },
  5972.                                       redoTransaction: function() { },
  5973.                                       isTransient: false,
  5974.                                       merge: function() { return false; } });
  5975.  
  5976.     if (this.panel.state == "closed") {
  5977.       // Consume dismiss clicks, see bug 400924
  5978.       this.panel.popupBoxObject
  5979.           .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  5980.       this.panel.openPopup(aAnchorElement, aPosition, -1, -1);
  5981.     }
  5982.     else {
  5983.       var namePicker = this._element("editBMPanel_namePicker");
  5984.       namePicker.focus();
  5985.       namePicker.editor.selectAll();
  5986.     }
  5987.  
  5988.     gEditItemOverlay.initPanel(this._itemId,
  5989.                                { hiddenRows: ["description", "location",
  5990.                                               "loadInSidebar", "keyword"] });
  5991.   },
  5992.  
  5993.   panelShown:
  5994.   function SU_panelShown(aEvent) {
  5995.     if (aEvent.target == this.panel) {
  5996.       if (!this._element("editBookmarkPanelContent").hidden) {
  5997.         var namePicker = this._element("editBMPanel_namePicker");
  5998.         namePicker.focus();
  5999.         namePicker.editor.selectAll();
  6000.       }
  6001.       else
  6002.         this.panel.focus();
  6003.     }
  6004.   },
  6005.  
  6006.   showPageBookmarkedNotification:
  6007.   function PCH_showPageBookmarkedNotification(aItemId, aAnchorElement, aPosition) {
  6008.     this._blockCommands(); // un-done in the popuphiding handler
  6009.  
  6010.     var bundle = this._element("bundle_browser");
  6011.     var brandBundle = this._element("bundle_brand");
  6012.     var brandShortName = brandBundle.getString("brandShortName");
  6013.  
  6014.     // "Page Bookmarked" title
  6015.     this._element("editBookmarkPanelTitle").value =
  6016.       bundle.getString("editBookmarkPanel.pageBookmarkedTitle");
  6017.  
  6018.     // description
  6019.     this._element("editBookmarkPanelDescription").textContent =
  6020.       bundle.getFormattedString("editBookmarkPanel.pageBookmarkedDescription",
  6021.                                 [brandShortName]);
  6022.  
  6023.     // show the "Edit.." button and the Remove Bookmark button, hide the
  6024.     // undo-remove-bookmark button.
  6025.     this._element("editBookmarkPanelEditButton").hidden = false;
  6026.     this._element("editBookmarkPanelRemoveButton").hidden = false;
  6027.     this._element("editBookmarkPanelUndoRemoveButton").hidden = true;
  6028.  
  6029.     // unset the unstarred state, if set
  6030.     this._element("editBookmarkPanelStarIcon").removeAttribute("unstarred");
  6031.  
  6032.     this._itemId = aItemId !== undefined ? aItemId : this._itemId;
  6033.     if (this.panel.state == "closed") {
  6034.       // Consume dismiss clicks, see bug 400924
  6035.       this.panel.popupBoxObject
  6036.           .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  6037.       this.panel.openPopup(aAnchorElement, aPosition, -1, -1);
  6038.     }
  6039.     else
  6040.       this.panel.focus();
  6041.   },
  6042.  
  6043.   quitEditMode: function SU_quitEditMode() {
  6044.     this._element("editBookmarkPanelContent").hidden = true;
  6045.     this._element("editBookmarkPanelBottomButtons").hidden = true;
  6046.     gEditItemOverlay.uninitPanel(true);
  6047.   },
  6048.  
  6049.   editButtonCommand: function SU_editButtonCommand() {
  6050.     this.showEditBookmarkPopup();
  6051.   },
  6052.  
  6053.   cancelButtonOnCommand: function SU_cancelButtonOnCommand() {
  6054.     // The order here is important! We have to hide the panel first, otherwise
  6055.     // changes done as part of Undo may change the panel contents and by
  6056.     // that force it to commit more transactions
  6057.     this.panel.hidePopup();
  6058.     this.endBatch();
  6059.     PlacesUIUtils.ptm.undoTransaction();
  6060.   },
  6061.  
  6062.   removeBookmarkButtonCommand: function SU_removeBookmarkButtonCommand() {
  6063. //@line 321 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-places.js"
  6064.  
  6065.     // cache its uri so we can get the new itemId in the case of undo
  6066.     this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._itemId);
  6067.  
  6068.     // remove all bookmarks for the bookmark's url, this also removes
  6069.     // the tags for the url
  6070.     var itemIds = PlacesUtils.getBookmarksForURI(this._uri);
  6071.     for (var i=0; i < itemIds.length; i++) {
  6072.       var txn = PlacesUIUtils.ptm.removeItem(itemIds[i]);
  6073.       PlacesUIUtils.ptm.doTransaction(txn);
  6074.     }
  6075.  
  6076. //@line 338 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-places.js"
  6077.       this.panel.hidePopup();
  6078.   },
  6079.  
  6080.   undoRemoveBookmarkCommand: function SU_undoRemoveBookmarkCommand() {
  6081.     // restore the bookmark by undoing the last transaction and go back
  6082.     // to the edit state
  6083.     this.endBatch();
  6084.     PlacesUIUtils.ptm.undoTransaction();
  6085.     this._itemId = PlacesUtils.getMostRecentBookmarkForURI(this._uri);
  6086.     this.showEditBookmarkPopup();
  6087.   },
  6088.  
  6089.   beginBatch: function SU_beginBatch() {
  6090.     if (!this._batching) {
  6091.       PlacesUIUtils.ptm.beginBatch();
  6092.       this._batching = true;
  6093.     }
  6094.   },
  6095.  
  6096.   endBatch: function SU_endBatch() {
  6097.     if (this._batching) {
  6098.       PlacesUIUtils.ptm.endBatch();
  6099.       this._batching = false;
  6100.     }
  6101.   }
  6102. }
  6103.  
  6104. var PlacesCommandHook = {
  6105.   /**
  6106.    * Adds a bookmark to the page loaded in the given browser.
  6107.    *
  6108.    * @param aBrowser
  6109.    *        a <browser> element.
  6110.    * @param [optional] aParent
  6111.    *        The folder in which to create a new bookmark if the page loaded in
  6112.    *        aBrowser isn't bookmarked yet, defaults to the unfiled root.
  6113.    * @param [optional] aShowEditUI
  6114.    *        whether or not to show the edit-bookmark UI for the bookmark item
  6115.    */  
  6116.   bookmarkPage: function PCH_bookmarkPage(aBrowser, aParent, aShowEditUI) {
  6117.     var uri = aBrowser.currentURI;
  6118.     var itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
  6119.     if (itemId == -1) {
  6120.       // Copied over from addBookmarkForBrowser:
  6121.       // Bug 52536: We obtain the URL and title from the nsIWebNavigation
  6122.       // associated with a <browser/> rather than from a DOMWindow.
  6123.       // This is because when a full page plugin is loaded, there is
  6124.       // no DOMWindow (?) but information about the loaded document
  6125.       // may still be obtained from the webNavigation.
  6126.       var webNav = aBrowser.webNavigation;
  6127.       var url = webNav.currentURI;
  6128.       var title;
  6129.       var description;
  6130.       var charset;
  6131.       try {
  6132.         title = webNav.document.title || url.spec;
  6133.         description = PlacesUIUtils.getDescriptionFromDocument(webNav.document);
  6134.         charset = webNav.document.characterSet;
  6135.       }
  6136.       catch (e) { }
  6137.  
  6138.       if (aShowEditUI) {
  6139.         // If we bookmark the page here (i.e. page was not "starred" already)
  6140.         // but open right into the "edit" state, start batching here, so
  6141.         // "Cancel" in that state removes the bookmark.
  6142.         StarUI.beginBatch();
  6143.       }
  6144.  
  6145.       var parent = aParent != undefined ?
  6146.                    aParent : PlacesUtils.unfiledBookmarksFolderId;
  6147.       var descAnno = { name: DESCRIPTION_ANNO, value: description };
  6148.       var txn = PlacesUIUtils.ptm.createItem(uri, parent, -1,
  6149.                                              title, null, [descAnno]);
  6150.       PlacesUIUtils.ptm.doTransaction(txn);
  6151.       // Set the character-set
  6152.       if (charset)
  6153.         PlacesUtils.history.setCharsetForURI(uri, charset);
  6154.       itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
  6155.     }
  6156.  
  6157.     // Revert the contents of the location bar
  6158.     handleURLBarRevert();
  6159.  
  6160.     // dock the panel to the star icon when possible, otherwise dock
  6161.     // it to the content area
  6162.     if (aBrowser.contentWindow == window.content) {
  6163.       var starIcon = aBrowser.ownerDocument.getElementById("star-button");
  6164.       if (starIcon && isElementVisible(starIcon)) {
  6165.         if (aShowEditUI)
  6166.           StarUI.showEditBookmarkPopup(itemId, starIcon, "after_end");
  6167. //@line 432 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-places.js"
  6168.         return;
  6169.       }
  6170.     }
  6171.  
  6172.     StarUI.showEditBookmarkPopup(itemId, aBrowser, "overlap");
  6173.   },
  6174.  
  6175.   /**
  6176.    * Adds a bookmark to the page loaded in the current tab. 
  6177.    */
  6178.   bookmarkCurrentPage: function PCH_bookmarkCurrentPage(aShowEditUI, aParent) {
  6179.     this.bookmarkPage(getBrowser().selectedBrowser, aParent, aShowEditUI);
  6180.   },
  6181.  
  6182.   /**
  6183.    * Adds a bookmark to the page targeted by a link.
  6184.    * @param aParent
  6185.    *        The folder in which to create a new bookmark if aURL isn't
  6186.    *        bookmarked.
  6187.    * @param aURL (string)
  6188.    *        the address of the link target
  6189.    * @param aTitle
  6190.    *        The link text
  6191.    */
  6192.   bookmarkLink: function PCH_bookmarkLink(aParent, aURL, aTitle) {
  6193.     var linkURI = makeURI(aURL);
  6194.     var itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
  6195.     if (itemId == -1) {
  6196.       StarUI.beginBatch();
  6197.       var txn = PlacesUIUtils.ptm.createItem(linkURI, aParent, -1, aTitle);
  6198.       PlacesUIUtils.ptm.doTransaction(txn);
  6199.       itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
  6200.     }
  6201.  
  6202.     StarUI.showEditBookmarkPopup(itemId, getBrowser(), "overlap");
  6203.   },
  6204.  
  6205.   /**
  6206.    * This function returns a list of nsIURI objects characterizing the
  6207.    * tabs currently open in the browser.  The URIs will appear in the
  6208.    * list in the order in which their corresponding tabs appeared.  However,
  6209.    * only the first instance of each URI will be returned.
  6210.    *
  6211.    * @returns a list of nsIURI objects representing unique locations open
  6212.    */
  6213.   _getUniqueTabInfo: function BATC__getUniqueTabInfo() {
  6214.     var tabList = [];
  6215.     var seenURIs = [];
  6216.  
  6217.     var browsers = getBrowser().browsers;
  6218.     for (var i = 0; i < browsers.length; ++i) {
  6219.       var webNav = browsers[i].webNavigation;
  6220.       var uri = webNav.currentURI;
  6221.  
  6222.       // skip redundant entries
  6223.       if (uri.spec in seenURIs)
  6224.         continue;
  6225.  
  6226.       // add to the set of seen URIs
  6227.       seenURIs[uri.spec] = true;
  6228.       tabList.push(uri);
  6229.     }
  6230.     return tabList;
  6231.   },
  6232.  
  6233.   /**
  6234.    * Adds a folder with bookmarks to all of the currently open tabs in this 
  6235.    * window.
  6236.    */
  6237.   bookmarkCurrentPages: function PCH_bookmarkCurrentPages() {
  6238.     var tabURIs = this._getUniqueTabInfo();
  6239.     PlacesUIUtils.showMinimalAddMultiBookmarkUI(tabURIs);
  6240.   },
  6241.  
  6242.   
  6243.   /**
  6244.    * Adds a Live Bookmark to a feed associated with the current page. 
  6245.    * @param     url
  6246.    *            The nsIURI of the page the feed was attached to
  6247.    * @title     title
  6248.    *            The title of the feed. Optional.
  6249.    * @subtitle  subtitle
  6250.    *            A short description of the feed. Optional.
  6251.    */
  6252.   addLiveBookmark: function PCH_addLiveBookmark(url, feedTitle, feedSubtitle) {
  6253.     var ios = 
  6254.         Cc["@mozilla.org/network/io-service;1"].
  6255.         getService(Ci.nsIIOService);
  6256.     var feedURI = ios.newURI(url, null, null);
  6257.     
  6258.     var doc = gBrowser.contentDocument;
  6259.     var title = (arguments.length > 1) ? feedTitle : doc.title;
  6260.  
  6261.     var description;
  6262.     if (arguments.length > 2)
  6263.       description = feedSubtitle;
  6264.     else
  6265.       description = PlacesUIUtils.getDescriptionFromDocument(doc);
  6266.  
  6267.     var toolbarIP =
  6268.       new InsertionPoint(PlacesUtils.bookmarks.toolbarFolder, -1);
  6269.     PlacesUIUtils.showMinimalAddLivemarkUI(feedURI, gBrowser.currentURI,
  6270.                                            title, description, toolbarIP, true);
  6271.   },
  6272.  
  6273.   /**
  6274.    * Opens the Places Organizer. 
  6275.    * @param   aLeftPaneRoot
  6276.    *          The query to select in the organizer window - options
  6277.    *          are: History, AllBookmarks, BookmarksMenu, BookmarksToolbar,
  6278.    *          UnfiledBookmarks and Tags.
  6279.    */
  6280.   showPlacesOrganizer: function PCH_showPlacesOrganizer(aLeftPaneRoot) {
  6281.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  6282.              getService(Ci.nsIWindowMediator);
  6283.     var organizer = wm.getMostRecentWindow("Places:Organizer");
  6284.     if (!organizer) {
  6285.       // No currently open places window, so open one with the specified mode.
  6286.       openDialog("chrome://browser/content/places/places.xul", 
  6287.                  "", "chrome,toolbar=yes,dialog=no,resizable", aLeftPaneRoot);
  6288.     }
  6289.     else {
  6290.       organizer.PlacesOrganizer.selectLeftPaneQuery(aLeftPaneRoot);
  6291.       organizer.focus();
  6292.     }
  6293.   },
  6294.  
  6295.   deleteButtonOnCommand: function PCH_deleteButtonCommand() {
  6296.     PlacesUtils.bookmarks.removeItem(gEditItemOverlay.itemId);
  6297.  
  6298.     // remove all tags for the associated url
  6299.     PlacesUtils.tagging.untagURI(gEditItemOverlay._uri, null);
  6300.  
  6301.     this.panel.hidePopup();
  6302.   }
  6303. };
  6304.  
  6305. // Functions for the history menu.
  6306. var HistoryMenu = {
  6307.   /**
  6308.    * popupshowing handler for the history menu.
  6309.    * @param aMenuPopup
  6310.    *        XULNode for the history menupopup
  6311.    */
  6312.   onPopupShowing: function PHM_onPopupShowing(aMenuPopup) {
  6313.     var resultNode = aMenuPopup.getResultNode();
  6314.     var wasOpen = resultNode.containerOpen;
  6315.     resultNode.containerOpen = true;
  6316.     document.getElementById("endHistorySeparator").hidden =
  6317.       resultNode.childCount == 0;
  6318.  
  6319.     if (!wasOpen)
  6320.       resultNode.containerOpen = false;
  6321.  
  6322.     // HistoryMenu.toggleRecentlyClosedTabs is defined in browser.js
  6323.     this.toggleRecentlyClosedTabs();
  6324.   }
  6325. };
  6326.  
  6327. /**
  6328.  * Functions for handling events in the Bookmarks Toolbar and menu.
  6329.  */
  6330. var BookmarksEventHandler = {  
  6331.   /**
  6332.    * Handler for click event for an item in the bookmarks toolbar or menu.
  6333.    * Menus and submenus from the folder buttons bubble up to this handler.
  6334.    * Left-click is handled in the onCommand function.
  6335.    * When items are middle-clicked (or clicked with modifier), open in tabs.
  6336.    * If the click came through a menu, close the menu.
  6337.    * @param aEvent
  6338.    *        DOMEvent for the click
  6339.    */
  6340.   onClick: function BT_onClick(aEvent) {
  6341.     // Only handle middle-click or left-click with modifiers.
  6342. //@line 609 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-places.js"
  6343.     var modifKey = aEvent.ctrlKey || aEvent.shiftKey;
  6344. //@line 611 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-places.js"
  6345.     if (aEvent.button == 2 || (aEvent.button == 0 && !modifKey))
  6346.       return;
  6347.  
  6348.     var target = aEvent.originalTarget;
  6349.     // If this event bubbled up from a menu or menuitem, close the menus.
  6350.     // Do this before opening tabs, to avoid hiding the open tabs confirm-dialog.
  6351.     if (target.localName == "menu" || target.localName == "menuitem") {
  6352.       for (node = target.parentNode; node; node = node.parentNode) {
  6353.         if (node.localName == "menupopup")
  6354.           node.hidePopup();
  6355.         else if (node.localName != "menu")
  6356.           break;
  6357.       }
  6358.     }
  6359.  
  6360.     if (target.node && PlacesUtils.nodeIsContainer(target.node)) {
  6361.       // Don't open the root folder in tabs when the empty area on the toolbar
  6362.       // is middle-clicked or when a non-bookmark item except for Open in Tabs)
  6363.       // in a bookmarks menupopup is middle-clicked.
  6364.       if (target.localName == "menu" || target.localName == "toolbarbutton")
  6365.         PlacesUIUtils.openContainerNodeInTabs(target.node, aEvent);
  6366.     }
  6367.     else if (aEvent.button == 1) {
  6368.       // left-clicks with modifier are already served by onCommand
  6369.       this.onCommand(aEvent);
  6370.     }
  6371.   },
  6372.  
  6373.   /**
  6374.    * Handler for command event for an item in the bookmarks toolbar.
  6375.    * Menus and submenus from the folder buttons bubble up to this handler.
  6376.    * Opens the item.
  6377.    * @param aEvent 
  6378.    *        DOMEvent for the command
  6379.    */
  6380.   onCommand: function BM_onCommand(aEvent) {
  6381.     var target = aEvent.originalTarget;
  6382.     if (target.node)
  6383.       PlacesUIUtils.openNodeWithEvent(target.node, aEvent);
  6384.   },
  6385.  
  6386.   /**
  6387.    * Handler for popupshowing event for an item in bookmarks toolbar or menu.
  6388.    * If the item isn't the main bookmarks menu, add an "Open All in Tabs"
  6389.    * menuitem to the bottom of the popup.
  6390.    * @param event 
  6391.    *        DOMEvent for popupshowing
  6392.    */
  6393.   onPopupShowing: function BM_onPopupShowing(event) {
  6394.     var target = event.originalTarget;
  6395.     if (!target.hasAttribute("placespopup"))
  6396.       return;
  6397.  
  6398.     // Check if the popup contains at least 2 menuitems with places nodes
  6399.     var numNodes = 0;
  6400.     var hasMultipleURIs = false;
  6401.     var currentChild = target.firstChild;
  6402.     while (currentChild) {
  6403.       if (currentChild.localName == "menuitem" && currentChild.node) {
  6404.         if (++numNodes == 2) {
  6405.           hasMultipleURIs = true;
  6406.           break;
  6407.         }
  6408.       }
  6409.       currentChild = currentChild.nextSibling;
  6410.     }
  6411.  
  6412.     var itemId = target._resultNode.itemId;
  6413.     var siteURIString = "";
  6414.     if (itemId != -1 && PlacesUtils.livemarks.isLivemark(itemId)) {
  6415.       var siteURI = PlacesUtils.livemarks.getSiteURI(itemId);
  6416.       if (siteURI)
  6417.         siteURIString = siteURI.spec;
  6418.     }
  6419.  
  6420.     if (!siteURIString && target._endOptOpenSiteURI) {
  6421.         target.removeChild(target._endOptOpenSiteURI);
  6422.         target._endOptOpenSiteURI = null;
  6423.     }
  6424.  
  6425.     if (!hasMultipleURIs && target._endOptOpenAllInTabs) {
  6426.       target.removeChild(target._endOptOpenAllInTabs);
  6427.       target._endOptOpenAllInTabs = null;
  6428.     }
  6429.  
  6430.     if (!(hasMultipleURIs || siteURIString)) {
  6431.       // we don't have to show any option
  6432.       if (target._endOptSeparator) {
  6433.         target.removeChild(target._endOptSeparator);
  6434.         target._endOptSeparator = null;
  6435.         target._endMarker = -1;
  6436.       }
  6437.       return;
  6438.     }
  6439.  
  6440.     if (!target._endOptSeparator) {
  6441.       // create a separator before options
  6442.       target._endOptSeparator = document.createElement("menuseparator");
  6443.       target._endOptSeparator.setAttribute("builder", "end");
  6444.       target._endMarker = target.childNodes.length;
  6445.       target.appendChild(target._endOptSeparator);
  6446.     }
  6447.  
  6448.     if (siteURIString && !target._endOptOpenSiteURI) {
  6449.       // Add "Open (Feed Name)" menuitem if it's a livemark with a siteURI
  6450.       target._endOptOpenSiteURI = document.createElement("menuitem");
  6451.       target._endOptOpenSiteURI.setAttribute("siteURI", siteURIString);
  6452.       target._endOptOpenSiteURI.setAttribute("oncommand",
  6453.           "openUILink(this.getAttribute('siteURI'), event);");
  6454.       // If a user middle-clicks this item we serve the oncommand event
  6455.       // We are using checkForMiddleClick because of Bug 246720
  6456.       // Note: stopPropagation is needed to avoid serving middle-click 
  6457.       // with BT_onClick that would open all items in tabs
  6458.       target._endOptOpenSiteURI.setAttribute("onclick",
  6459.           "checkForMiddleClick(this, event); event.stopPropagation();");
  6460.       target._endOptOpenSiteURI.setAttribute("label",
  6461.           PlacesUIUtils.getFormattedString("menuOpenLivemarkOrigin.label",
  6462.           [target.parentNode.getAttribute("label")]));
  6463.       target.appendChild(target._endOptOpenSiteURI);
  6464.     }
  6465.  
  6466.     if (hasMultipleURIs && !target._endOptOpenAllInTabs) {
  6467.         // Add the "Open All in Tabs" menuitem if there are
  6468.         // at least two menuitems with places result nodes.
  6469.         target._endOptOpenAllInTabs = document.createElement("menuitem");
  6470.         target._endOptOpenAllInTabs.setAttribute("oncommand",
  6471.             "PlacesUIUtils.openContainerNodeInTabs(this.parentNode._resultNode, event);");
  6472.         target._endOptOpenAllInTabs.setAttribute("onclick",
  6473.             "checkForMiddleClick(this, event); event.stopPropagation();");
  6474.         target._endOptOpenAllInTabs.setAttribute("label",
  6475.             gNavigatorBundle.getString("menuOpenAllInTabs.label"));
  6476.         target.appendChild(target._endOptOpenAllInTabs);
  6477.     }
  6478.   },
  6479.  
  6480.   fillInBTTooltip: function(aTipElement) {
  6481.     // Fx2XP: Don't show tooltips for bookmarks under sub-folders
  6482.     if (aTipElement.localName != "toolbarbutton")
  6483.       return false;
  6484.  
  6485.     // Fx2XP: Only show tooltips for URL items
  6486.     if (!PlacesUtils.nodeIsURI(aTipElement.node))
  6487.       return false;
  6488.  
  6489.     var url = aTipElement.node.uri;
  6490.     if (!url) 
  6491.       return false;
  6492.  
  6493.     var tooltipUrl = document.getElementById("btUrlText");
  6494.     tooltipUrl.value = url;
  6495.  
  6496.     var title = aTipElement.label;
  6497.     var tooltipTitle = document.getElementById("btTitleText");
  6498.     if (title && title != url) {
  6499.       tooltipTitle.hidden = false;
  6500.       tooltipTitle.value = title;
  6501.     }
  6502.     else
  6503.       tooltipTitle.hidden = true;
  6504.  
  6505.     // show tooltip
  6506.     return true;
  6507.   }
  6508. };
  6509.  
  6510. /**
  6511.  * Drag and Drop handling specifically for the Bookmarks Menu item in the
  6512.  * top level menu bar
  6513.  */
  6514. var BookmarksMenuDropHandler = {
  6515.   /**
  6516.    * Need to tell the session to update the state of the cursor as we drag
  6517.    * over the Bookmarks Menu to show the "can drop" state vs. the "no drop"
  6518.    * state.
  6519.    */
  6520.   onDragOver: function BMDH_onDragOver(event, flavor, session) {
  6521.     session.canDrop = this.canDrop(event, session);
  6522.   },
  6523.  
  6524.   /**
  6525.    * Advertises the set of data types that can be dropped on the Bookmarks
  6526.    * Menu
  6527.    * @returns a FlavourSet object per nsDragAndDrop parlance.
  6528.    */
  6529.   getSupportedFlavours: function BMDH_getSupportedFlavours() {
  6530.     var view = document.getElementById("bookmarksMenuPopup");
  6531.     return view.getSupportedFlavours();
  6532.   },
  6533.  
  6534.   /**
  6535.    * Determine whether or not the user can drop on the Bookmarks Menu.
  6536.    * @param   event
  6537.    *          A dragover event
  6538.    * @param   session
  6539.    *          The active DragSession
  6540.    * @returns true if the user can drop onto the Bookmarks Menu item, false 
  6541.    *          otherwise.
  6542.    */
  6543.   canDrop: function BMDH_canDrop(event, session) {
  6544.     var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1);  
  6545.     return ip && PlacesControllerDragHelper.canDrop(ip);
  6546.   },
  6547.  
  6548.   /**
  6549.    * Called when the user drops onto the top level Bookmarks Menu item.
  6550.    * @param   event
  6551.    *          A drop event
  6552.    * @param   data
  6553.    *          Data that was dropped
  6554.    * @param   session
  6555.    *          The active DragSession
  6556.    */
  6557.   onDrop: function BMDH_onDrop(event, data, session) {
  6558.     // Put the item at the end of bookmark menu
  6559.     var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1);
  6560.     PlacesControllerDragHelper.onDrop(ip);
  6561.   }
  6562. };
  6563.  
  6564. /**
  6565.  * Handles special drag and drop functionality for menus on the Bookmarks 
  6566.  * Toolbar and Bookmarks Menu.
  6567.  */
  6568. var PlacesMenuDNDController = {
  6569.   _springLoadDelay: 350, // milliseconds
  6570.  
  6571.   /**
  6572.    * All Drag Timers set for the Places UI
  6573.    */
  6574.   _timers: { },
  6575.   
  6576.   /**
  6577.    * Called when the user drags over the Bookmarks top level <menu> element.
  6578.    * @param   event
  6579.    *          The DragEnter event that spawned the opening. 
  6580.    */
  6581.   onBookmarksMenuDragEnter: function PMDC_onDragEnter(event) {
  6582.     if ("loadTime" in this._timers) 
  6583.       return;
  6584.     
  6585.     this._setDragTimer("loadTime", this._openBookmarksMenu, 
  6586.                        this._springLoadDelay, [event]);
  6587.   },
  6588.   
  6589.   /**
  6590.    * Creates a timer that will fire during a drag and drop operation.
  6591.    * @param   id
  6592.    *          The identifier of the timer being set
  6593.    * @param   callback
  6594.    *          The function to call when the timer "fires"
  6595.    * @param   delay
  6596.    *          The time to wait before calling the callback function
  6597.    * @param   args
  6598.    *          An array of arguments to pass to the callback function
  6599.    */
  6600.   _setDragTimer: function PMDC__setDragTimer(id, callback, delay, args) {
  6601.     if (!this._dragSupported)
  6602.       return;
  6603.  
  6604.     // Cancel this timer if it's already running.
  6605.     if (id in this._timers)
  6606.       this._timers[id].cancel();
  6607.       
  6608.     /**
  6609.      * An object implementing nsITimerCallback that calls a user-supplied
  6610.      * method with the specified args in the context of the supplied object.
  6611.      */
  6612.     function Callback(object, method, args) {
  6613.       this._method = method;
  6614.       this._args = args;
  6615.       this._object = object;
  6616.     }
  6617.     Callback.prototype = {
  6618.       notify: function C_notify(timer) {
  6619.         this._method.apply(this._object, this._args);
  6620.       }
  6621.     };
  6622.     
  6623.     var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  6624.     timer.initWithCallback(new Callback(this, callback, args), delay, 
  6625.                            timer.TYPE_ONE_SHOT);
  6626.     this._timers[id] = timer;
  6627.   },
  6628.   
  6629.   /**
  6630.    * Determines if a XUL element represents a container in the Bookmarks system
  6631.    * @returns true if the element is a container element (menu or 
  6632.    *`         menu-toolbarbutton), false otherwise.
  6633.    */
  6634.   _isContainer: function PMDC__isContainer(node) {
  6635.     return node.localName == "menu" || 
  6636.            node.localName == "toolbarbutton" && node.getAttribute("type") == "menu";
  6637.   },
  6638.   
  6639.   /**
  6640.    * Opens the Bookmarks Menu when it is dragged over. (This is special-cased, 
  6641.    * since the toplevel Bookmarks <menu> is not a member of an existing places
  6642.    * container, as folders on the personal toolbar or submenus are. 
  6643.    * @param   event
  6644.    *          The DragEnter event that spawned the opening. 
  6645.    */
  6646.   _openBookmarksMenu: function PMDC__openBookmarksMenu(event) {
  6647.     if ("loadTime" in this._timers)
  6648.       delete this._timers.loadTime;
  6649.     if (event.target.id == "bookmarksMenu") {
  6650.       // If this is the bookmarks menu, tell its menupopup child to show.
  6651.       event.target.lastChild.setAttribute("autoopened", "true");
  6652.       event.target.lastChild.showPopup(event.target.lastChild);
  6653.     }  
  6654.   },
  6655.  
  6656.   // Whether or not drag and drop to menus is supported on this platform
  6657.   // Dragging in menus is disabled on OS X due to various repainting issues.
  6658. //@line 927 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-places.js"
  6659.   _dragSupported: true
  6660. //@line 929 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-places.js"
  6661. };
  6662.  
  6663. var PlacesStarButton = {
  6664.   init: function PSB_init() {
  6665.     PlacesUtils.bookmarks.addObserver(this, false);
  6666.   },
  6667.  
  6668.   uninit: function PSB_uninit() {
  6669.     PlacesUtils.bookmarks.removeObserver(this);
  6670.   },
  6671.  
  6672.   QueryInterface: function PSB_QueryInterface(aIID) {
  6673.     if (aIID.equals(Ci.nsINavBookmarkObserver) ||
  6674.         aIID.equals(Ci.nsISupports))
  6675.       return this;
  6676.  
  6677.     throw Cr.NS_NOINTERFACE;
  6678.   },
  6679.  
  6680.   _starred: false,
  6681.   _batching: false,
  6682.  
  6683.   updateState: function PSB_updateState() {
  6684.     var starIcon = document.getElementById("star-button");
  6685.     if (!starIcon)
  6686.       return;
  6687.  
  6688.     var browserBundle = document.getElementById("bundle_browser");
  6689.     var uri = getBrowser().currentURI;
  6690.     this._starred = uri && (PlacesUtils.getMostRecentBookmarkForURI(uri) != -1 ||
  6691.                             PlacesUtils.getMostRecentFolderForFeedURI(uri) != -1);
  6692.     if (this._starred) {
  6693.       starIcon.setAttribute("starred", "true");
  6694.       starIcon.setAttribute("tooltiptext", browserBundle.getString("starButtonOn.tooltip"));
  6695.     }
  6696.     else {
  6697.       starIcon.removeAttribute("starred");
  6698.       starIcon.setAttribute("tooltiptext", browserBundle.getString("starButtonOff.tooltip"));
  6699.     }
  6700.   },
  6701.  
  6702.   onClick: function PSB_onClick(aEvent) {
  6703.     if (aEvent.button == 0)
  6704.       PlacesCommandHook.bookmarkCurrentPage(this._starred);
  6705.  
  6706.     // don't bubble to the textbox so that the address won't be selected
  6707.     aEvent.stopPropagation();
  6708.   },
  6709.  
  6710.   // nsINavBookmarkObserver  
  6711.   onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {
  6712.     this._batching = true;
  6713.   },
  6714.  
  6715.   onEndUpdateBatch: function PSB_onEndUpdateBatch() {
  6716.     this.updateState();
  6717.     this._batching = false;
  6718.   },
  6719.   
  6720.   onItemAdded: function PSB_onItemAdded(aItemId, aFolder, aIndex) {
  6721.     if (!this._batching && !this._starred)
  6722.       this.updateState();
  6723.   },
  6724.  
  6725.   onItemRemoved: function PSB_onItemRemoved(aItemId, aFolder, aIndex) {
  6726.     if (!this._batching)
  6727.       this.updateState();
  6728.   },
  6729.  
  6730.   onItemChanged: function PSB_onItemChanged(aItemId, aProperty,
  6731.                                             aIsAnnotationProperty, aValue) {
  6732.     if (!this._batching && aProperty == "uri")
  6733.       this.updateState();
  6734.   },
  6735.  
  6736.   onItemVisited: function() { },
  6737.   onItemMoved: function() { }
  6738. };
  6739.  
  6740. /**
  6741.  * Various migration tasks.
  6742.  */
  6743. function placesMigrationTasks() {
  6744.   // bug 398914 - move all post-data annotations from URIs to bookmarks
  6745.   // XXX - REMOVE ME FOR BETA 3 (bug 391419)
  6746.   if (gPrefService.getBoolPref("browser.places.migratePostDataAnnotations")) {
  6747.     const annosvc = PlacesUtils.annotations;
  6748.     var bmsvc = PlacesUtils.bookmarks;
  6749.     const oldPostDataAnno = "URIProperties/POSTData";
  6750.     var pages = annosvc.getPagesWithAnnotation(oldPostDataAnno, {});
  6751.     for (let i = 0; i < pages.length; i++) {
  6752.       try {
  6753.         let uri = pages[i];
  6754.         var postData = annosvc.getPageAnnotation(uri, oldPostDataAnno);
  6755.         // We can't know which URI+keyword combo this postdata was for, but
  6756.         // it's very likely that if this URI is bookmarked and has a keyword
  6757.         // *and* the URI has postdata, then this bookmark was using the
  6758.         // postdata. Propagate the annotation to all bookmarks for this URI
  6759.         // just to be safe.
  6760.         let bookmarks = bmsvc.getBookmarkIdsForURI(uri, {});
  6761.         for (let i = 0; i < bookmarks.length; i++) {
  6762.           var keyword = bmsvc.getKeywordForBookmark(bookmarks[i]);
  6763.           if (keyword)
  6764.             annosvc.setItemAnnotation(bookmarks[i], POST_DATA_ANNO, postData, 0, annosvc.EXPIRE_NEVER); 
  6765.         }
  6766.         // Remove the old annotation.
  6767.         annosvc.removePageAnnotation(uri, oldPostDataAnno);
  6768.       } catch(ex) {}
  6769.     }
  6770.     gPrefService.setBoolPref("browser.places.migratePostDataAnnotations", false);
  6771.   }
  6772.  
  6773.   if (gPrefService.getBoolPref("browser.places.updateRecentTagsUri")) {
  6774.     var oldUriSpec = "place:folder=TAGS&group=3&queryType=1" +
  6775.                      "&applyOptionsToContainers=1&sort=12&maxResults=10";
  6776.  
  6777.     var maxResults = 10;
  6778.     var newUriSpec = "place:type=" + 
  6779.                      Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY +
  6780.                      "&sort=" + 
  6781.                      Ci.nsINavHistoryQueryOptions.SORT_BY_LASTMODIFIED_DESCENDING +
  6782.                      "&maxResults=" + maxResults;
  6783.                      
  6784.     var ios = Cc["@mozilla.org/network/io-service;1"].
  6785.               getService(Ci.nsIIOService);
  6786.  
  6787.     var oldUri = ios.newURI(oldUriSpec, null, null);
  6788.     var newUri = ios.newURI(newUriSpec, null, null);
  6789.  
  6790.     let bmsvc = PlacesUtils.bookmarks;
  6791.     let bookmarks = bmsvc.getBookmarkIdsForURI( oldUri, {});
  6792.     for (let i = 0; i < bookmarks.length; i++) {
  6793.       bmsvc.changeBookmarkURI( bookmarks[i], newUri);
  6794.     }
  6795.     gPrefService.setBoolPref("browser.places.updateRecentTagsUri", false);
  6796.   }
  6797. }
  6798. //@line 6212 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  6799.  
  6800. /*
  6801. //@line 40 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser-textZoom.js"
  6802.  */
  6803.  
  6804. // From nsMouseScrollEvent::kIsHorizontal
  6805. const MOUSE_SCROLL_IS_HORIZONTAL = 1 << 2;
  6806.  
  6807. // One of the possible values for the mousewheel.* preferences.
  6808. // From nsEventStateManager.cpp.
  6809. const MOUSE_SCROLL_ZOOM = 3;
  6810.  
  6811. /**
  6812.  * Controls the "full zoom" setting and its site-specific preferences.
  6813.  */
  6814. var FullZoom = {
  6815.  
  6816.   //**************************************************************************//
  6817.   // Name & Values
  6818.  
  6819.   // The name of the setting.  Identifies the setting in the prefs database.
  6820.   name: "browser.content.full-zoom",
  6821.  
  6822.   // The global value (if any) for the setting.  Lazily loaded from the service
  6823.   // when first requested, then updated by the pref change listener as it changes.
  6824.   // If there is no global value, then this should be undefined.
  6825.   get globalValue FullZoom_get_globalValue() {
  6826.     var globalValue = this._cps.getPref(null, this.name);
  6827.     if (typeof globalValue != "undefined")
  6828.       globalValue = this._ensureValid(globalValue);
  6829.     delete this.globalValue;
  6830.     return this.globalValue = globalValue;
  6831.   },
  6832.  
  6833.  
  6834.   //**************************************************************************//
  6835.   // Convenience Getters
  6836.  
  6837.   // Content Pref Service
  6838.   get _cps FullZoom_get__cps() {
  6839.     delete this._cps;
  6840.     return this._cps = Cc["@mozilla.org/content-pref/service;1"].
  6841.                        getService(Ci.nsIContentPrefService);
  6842.   },
  6843.  
  6844.   get _prefBranch FullZoom_get__prefBranch() {
  6845.     delete this._prefBranch;
  6846.     return this._prefBranch = Cc["@mozilla.org/preferences-service;1"].
  6847.                               getService(Ci.nsIPrefBranch2);
  6848.   },
  6849.  
  6850.   // browser.zoom.siteSpecific preference cache
  6851.   siteSpecific: undefined,
  6852.  
  6853.  
  6854.   //**************************************************************************//
  6855.   // nsISupports
  6856.  
  6857.   // We can't use the Ci shortcut here because it isn't defined yet.
  6858.   interfaces: [Components.interfaces.nsIDOMEventListener,
  6859.                Components.interfaces.nsIObserver,
  6860.                Components.interfaces.nsIContentPrefObserver,
  6861.                Components.interfaces.nsISupportsWeakReference,
  6862.                Components.interfaces.nsISupports],
  6863.  
  6864.   QueryInterface: function FullZoom_QueryInterface(aIID) {
  6865.     if (!this.interfaces.some(function (v) aIID.equals(v)))
  6866.       throw Cr.NS_ERROR_NO_INTERFACE;
  6867.     return this;
  6868.   },
  6869.  
  6870.  
  6871.   //**************************************************************************//
  6872.   // Initialization & Destruction
  6873.  
  6874.   init: function FullZoom_init() {
  6875.     // Listen for scrollwheel events so we can save scrollwheel-based changes.
  6876.     window.addEventListener("DOMMouseScroll", this, false);
  6877.  
  6878.     // Register ourselves with the service so we know when our pref changes.
  6879.     this._cps.addObserver(this.name, this);
  6880.  
  6881.     // Listen for changes to the browser.zoom.siteSpecific preference so we can
  6882.     // enable/disable per-site saving and restoring of zoom levels accordingly.
  6883.     this.siteSpecific =
  6884.       this._prefBranch.getBoolPref("browser.zoom.siteSpecific");
  6885.     this._prefBranch.addObserver("browser.zoom.siteSpecific", this, true);
  6886.   },
  6887.  
  6888.   destroy: function FullZoom_destroy() {
  6889.     this._prefBranch.removeObserver("browser.zoom.siteSpecific", this);
  6890.     this._cps.removeObserver(this.name, this);
  6891.     window.removeEventListener("DOMMouseScroll", this, false);
  6892.     delete this._cps;
  6893.   },
  6894.  
  6895.  
  6896.   //**************************************************************************//
  6897.   // Event Handlers
  6898.  
  6899.   // nsIDOMEventListener
  6900.  
  6901.   handleEvent: function FullZoom_handleEvent(event) {
  6902.     switch (event.type) {
  6903.       case "DOMMouseScroll":
  6904.         this._handleMouseScrolled(event);
  6905.         break;
  6906.     }
  6907.   },
  6908.  
  6909.   _handleMouseScrolled: function FullZoom__handleMouseScrolled(event) {
  6910.     // Construct the "mousewheel action" pref key corresponding to this event.
  6911.     // Based on nsEventStateManager::GetBasePrefKeyForMouseWheel.
  6912.     var pref = "mousewheel";
  6913.     if (event.scrollFlags & MOUSE_SCROLL_IS_HORIZONTAL)
  6914.       pref += ".horizscroll";
  6915.  
  6916.     if (event.shiftKey)
  6917.       pref += ".withshiftkey";
  6918.     else if (event.ctrlKey)
  6919.       pref += ".withcontrolkey";
  6920.     else if (event.altKey)
  6921.       pref += ".withaltkey";
  6922.     else if (event.metaKey)
  6923.       pref += ".withmetakey";
  6924.     else
  6925.       pref += ".withnokey";
  6926.  
  6927.     pref += ".action";
  6928.  
  6929.     // Don't do anything if this isn't a "zoom" scroll event.
  6930.     var isZoomEvent = false;
  6931.     try {
  6932.       isZoomEvent = (gPrefService.getIntPref(pref) == MOUSE_SCROLL_ZOOM);
  6933.     } catch (e) {}
  6934.     if (!isZoomEvent)
  6935.       return;
  6936.  
  6937.     // XXX Lazily cache all the possible action prefs so we don't have to get
  6938.     // them anew from the pref service for every scroll event?  We'd have to
  6939.     // make sure to observe them so we can update the cache when they change.
  6940.  
  6941.     // We have to call _applySettingToPref in a timeout because we handle
  6942.     // the event before the event state manager has a chance to apply the zoom
  6943.     // during nsEventStateManager::PostHandleEvent.
  6944.     window.setTimeout(function (self) { self._applySettingToPref() }, 0, this);
  6945.   },
  6946.  
  6947.   // nsIObserver
  6948.  
  6949.   observe: function (aSubject, aTopic, aData) {
  6950.     switch(aTopic) {
  6951.       case "nsPref:changed":
  6952.         switch(aData) {
  6953.           case "browser.zoom.siteSpecific":
  6954.             this.siteSpecific =
  6955.               this._prefBranch.getBoolPref("browser.zoom.siteSpecific");
  6956.             break;
  6957.         }
  6958.         break;
  6959.     }
  6960.   },
  6961.  
  6962.   // nsIContentPrefObserver
  6963.  
  6964.   onContentPrefSet: function FullZoom_onContentPrefSet(aGroup, aName, aValue) {
  6965.     if (aGroup == this._cps.grouper.group(gBrowser.currentURI))
  6966.       this._applyPrefToSetting(aValue);
  6967.     else if (aGroup == null) {
  6968.       this.globalValue = this._ensureValid(aValue);
  6969.  
  6970.       // If the current page doesn't have a site-specific preference,
  6971.       // then its zoom should be set to the new global preference now that
  6972.       // the global preference has changed.
  6973.       if (!this._cps.hasPref(gBrowser.currentURI, this.name))
  6974.         this._applyPrefToSetting();
  6975.     }
  6976.   },
  6977.  
  6978.   onContentPrefRemoved: function FullZoom_onContentPrefRemoved(aGroup, aName) {
  6979.     if (aGroup == this._cps.grouper.group(gBrowser.currentURI))
  6980.       this._applyPrefToSetting();
  6981.     else if (aGroup == null) {
  6982.       this.globalValue = undefined;
  6983.  
  6984.       // If the current page doesn't have a site-specific preference,
  6985.       // then its zoom should be set to the default preference now that
  6986.       // the global preference has changed.
  6987.       if (!this._cps.hasPref(gBrowser.currentURI, this.name))
  6988.         this._applyPrefToSetting();
  6989.     }
  6990.   },
  6991.  
  6992.   // location change observer
  6993.  
  6994.   onLocationChange: function FullZoom_onLocationChange(aURI) {
  6995.     if (!aURI)
  6996.       return;
  6997.     this._applyPrefToSetting(this._cps.getPref(aURI, this.name));
  6998.   },
  6999.  
  7000.   // update state of zoom type menu item
  7001.  
  7002.   updateMenu: function FullZoom_updateMenu() {
  7003.     var menuItem = document.getElementById("toggle_zoom");
  7004.  
  7005.     menuItem.setAttribute("checked", !ZoomManager.useFullZoom);
  7006.   },
  7007.  
  7008.   //**************************************************************************//
  7009.   // Setting & Pref Manipulation
  7010.  
  7011.   reduce: function FullZoom_reduce() {
  7012.     ZoomManager.reduce();
  7013.     this._applySettingToPref();
  7014.   },
  7015.  
  7016.   enlarge: function FullZoom_enlarge() {
  7017.     ZoomManager.enlarge();
  7018.     this._applySettingToPref();
  7019.   },
  7020.  
  7021.   reset: function FullZoom_reset() {
  7022.     if (typeof this.globalValue != "undefined")
  7023.       ZoomManager.zoom = this.globalValue;
  7024.     else
  7025.       ZoomManager.reset();
  7026.  
  7027.     this._removePref();
  7028.   },
  7029.  
  7030.   setSettingValue: function FullZoom_setSettingValue() {
  7031.     var value = this._cps.getPref(gBrowser.currentURI, this.name);
  7032.     this._applyPrefToSetting(value);
  7033.   },
  7034.  
  7035.   /**
  7036.    * Set the zoom level for the current tab.
  7037.    *
  7038.    * Per nsPresContext::setFullZoom, we can set the zoom to its current value
  7039.    * without significant impact on performance, as the setting is only applied
  7040.    * if it differs from the current setting.  In fact getting the zoom and then
  7041.    * checking ourselves if it differs costs more.
  7042.    * 
  7043.    * And perhaps we should always set the zoom even if it was more expensive,
  7044.    * since DocumentViewerImpl::SetTextZoom claims that child documents can have
  7045.    * a different text zoom (although it would be unusual), and it implies that
  7046.    * those child text zooms should get updated when the parent zoom gets set,
  7047.    * and perhaps the same is true for full zoom
  7048.    * (although DocumentViewerImpl::SetFullZoom doesn't mention it).
  7049.    *
  7050.    * So when we apply new zoom values to the browser, we simply set the zoom.
  7051.    * We don't check first to see if the new value is the same as the current
  7052.    * one.
  7053.    **/
  7054.   _applyPrefToSetting: function FullZoom__applyPrefToSetting(aValue) {
  7055.     if (!this.siteSpecific || gInPrintPreviewMode)
  7056.       return;
  7057.  
  7058.     try {
  7059.       if (typeof aValue != "undefined")
  7060.         ZoomManager.zoom = this._ensureValid(aValue);
  7061.       else if (typeof this.globalValue != "undefined")
  7062.         ZoomManager.zoom = this.globalValue;
  7063.       else
  7064.         ZoomManager.zoom = 1;
  7065.     }
  7066.     catch(ex) {}
  7067.   },
  7068.  
  7069.   _applySettingToPref: function FullZoom__applySettingToPref() {
  7070.     if (!this.siteSpecific || gInPrintPreviewMode)
  7071.       return;
  7072.  
  7073.     var zoomLevel = ZoomManager.zoom;
  7074.     this._cps.setPref(gBrowser.currentURI, this.name, zoomLevel);
  7075.   },
  7076.  
  7077.   _removePref: function FullZoom__removePref() {
  7078.     this._cps.removePref(gBrowser.currentURI, this.name);
  7079.   },
  7080.  
  7081.  
  7082.   //**************************************************************************//
  7083.   // Utilities
  7084.  
  7085.   _ensureValid: function FullZoom__ensureValid(aValue) {
  7086.     if (isNaN(aValue))
  7087.       return 1;
  7088.  
  7089.     if (aValue < ZoomManager.MIN)
  7090.       return ZoomManager.MIN;
  7091.  
  7092.     if (aValue > ZoomManager.MAX)
  7093.       return ZoomManager.MAX;
  7094.  
  7095.     return aValue;
  7096.   }
  7097. };
  7098. //@line 6214 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/base/content/browser.js"
  7099.  
  7100. HistoryMenu.toggleRecentlyClosedTabs = function PHM_toggleRecentlyClosedTabs() {
  7101.   // enable/disable the Recently Closed Tabs sub menu
  7102.   var undoPopup = document.getElementById("historyUndoPopup");
  7103.  
  7104.   // get closed-tabs from nsSessionStore
  7105.   var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  7106.            getService(Ci.nsISessionStore);
  7107.   // no restorable tabs, so disable menu
  7108.   if (ss.getClosedTabCount(window) == 0)
  7109.     undoPopup.parentNode.setAttribute("disabled", true);
  7110.   else
  7111.     undoPopup.parentNode.removeAttribute("disabled");
  7112. }
  7113.  
  7114. /**
  7115.  * Populate when the history menu is opened
  7116.  */
  7117. HistoryMenu.populateUndoSubmenu = function PHM_populateUndoSubmenu() {
  7118.   var undoPopup = document.getElementById("historyUndoPopup");
  7119.  
  7120.   // remove existing menu items
  7121.   while (undoPopup.hasChildNodes())
  7122.     undoPopup.removeChild(undoPopup.firstChild);
  7123.  
  7124.   // get closed-tabs from nsSessionStore
  7125.   var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  7126.            getService(Ci.nsISessionStore);
  7127.   // no restorable tabs, so make sure menu is disabled, and return
  7128.   if (ss.getClosedTabCount(window) == 0) {
  7129.     undoPopup.parentNode.setAttribute("disabled", true);
  7130.     return;
  7131.   }
  7132.  
  7133.   // enable menu
  7134.   undoPopup.parentNode.removeAttribute("disabled");
  7135.  
  7136.   // populate menu
  7137.   var undoItems = eval("(" + ss.getClosedTabData(window) + ")");
  7138.   for (var i = 0; i < undoItems.length; i++) {
  7139.     var m = document.createElement("menuitem");
  7140.     m.setAttribute("label", undoItems[i].title);
  7141.     if (undoItems[i].image)
  7142.       m.setAttribute("image", undoItems[i].image);
  7143.     m.setAttribute("class", "menuitem-iconic bookmark-item");
  7144.     m.setAttribute("value", i);
  7145.     m.setAttribute("oncommand", "undoCloseTab(" + i + ");");
  7146.     m.addEventListener("click", undoCloseMiddleClick, false);
  7147.     if (i == 0)
  7148.       m.setAttribute("key", "key_undoCloseTab");
  7149.     undoPopup.appendChild(m);
  7150.   }
  7151.  
  7152.   // "Open All in Tabs"
  7153.   var strings = gNavigatorBundle;
  7154.   undoPopup.appendChild(document.createElement("menuseparator"));
  7155.   m = undoPopup.appendChild(document.createElement("menuitem"));
  7156.   m.setAttribute("label", strings.getString("menuOpenAllInTabs.label"));
  7157.   m.setAttribute("accesskey", strings.getString("menuOpenAllInTabs.accesskey"));
  7158.   m.addEventListener("command", function() {
  7159.     for (var i = 0; i < undoItems.length; i++)
  7160.       undoCloseTab();
  7161.   }, false);
  7162. }
  7163.  
  7164. /**
  7165.   * Re-open a closed tab and put it to the end of the tab strip. 
  7166.   * Used for a middle click.
  7167.   * @param aEvent
  7168.   *        The event when the user clicks the menu item
  7169.   */
  7170. function undoCloseMiddleClick(aEvent) {
  7171.   if (aEvent.button != 1)
  7172.     return;
  7173.  
  7174.   undoCloseTab(aEvent.originalTarget.value);
  7175.   getBrowser().moveTabToEnd();
  7176. }
  7177.  
  7178. /**
  7179.  * Re-open a closed tab.
  7180.  * @param aIndex
  7181.  *        The index of the tab (via nsSessionStore.getClosedTabData)
  7182.  */
  7183. function undoCloseTab(aIndex) {
  7184.   // wallpaper patch to prevent an unnecessary blank tab (bug 343895)
  7185.   var tabbrowser = getBrowser();
  7186.   var blankTabToRemove = null;
  7187.   if (tabbrowser.tabContainer.childNodes.length == 1 &&
  7188.       !gPrefService.getBoolPref("browser.tabs.autoHide") &&
  7189.       tabbrowser.selectedBrowser.sessionHistory.count < 2 &&
  7190.       tabbrowser.selectedBrowser.currentURI.spec == "about:blank" &&
  7191.       !tabbrowser.selectedBrowser.contentDocument.body.hasChildNodes() &&
  7192.       !tabbrowser.selectedTab.hasAttribute("busy"))
  7193.     blankTabToRemove = tabbrowser.selectedTab;
  7194.  
  7195.   var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  7196.            getService(Ci.nsISessionStore);
  7197.   if (ss.getClosedTabCount(window) == 0)
  7198.     return;
  7199.   ss.undoCloseTab(window, aIndex || 0);
  7200.  
  7201.   if (blankTabToRemove)
  7202.     tabbrowser.removeTab(blankTabToRemove);
  7203. }
  7204.  
  7205. /**
  7206.  * Format a URL
  7207.  * eg:
  7208.  * echo formatURL("http://%LOCALE%.amo.mozilla.org/%LOCALE%/%APP%/%VERSION%/");
  7209.  * > http://en-US.amo.mozilla.org/en-US/firefox/3.0a1/
  7210.  *
  7211.  * Currently supported built-ins are LOCALE, APP, and any value from nsIXULAppInfo, uppercased.
  7212.  */
  7213. function formatURL(aFormat, aIsPref) {
  7214.   var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].getService(Ci.nsIURLFormatter);
  7215.   return aIsPref ? formatter.formatURLPref(aFormat) : formatter.formatURL(aFormat);
  7216. }
  7217.  
  7218. /**
  7219.  * This also takes care of updating the command enabled-state when tabs are
  7220.  * created or removed.
  7221.  */
  7222. function BookmarkAllTabsHandler() {
  7223.   this._command = document.getElementById("Browser:BookmarkAllTabs");
  7224.   gBrowser.addEventListener("TabOpen", this, true);
  7225.   gBrowser.addEventListener("TabClose", this, true);
  7226.   this._updateCommandState();
  7227. }
  7228.  
  7229. BookmarkAllTabsHandler.prototype = {
  7230.   QueryInterface: function BATH_QueryInterface(aIID) {
  7231.     if (aIID.equals(Ci.nsIDOMEventListener) ||
  7232.         aIID.equals(Ci.nsISupports))
  7233.       return this;
  7234.  
  7235.     throw Cr.NS_NOINTERFACE;
  7236.   },
  7237.  
  7238.   _updateCommandState: function BATH__updateCommandState(aTabClose) {
  7239.     var numTabs = gBrowser.tabContainer.childNodes.length;
  7240.  
  7241.     // The TabClose event is fired before the tab is removed from the DOM
  7242.     if (aTabClose)
  7243.       numTabs--;
  7244.  
  7245.     if (numTabs > 1)
  7246.       this._command.removeAttribute("disabled");
  7247.     else
  7248.       this._command.setAttribute("disabled", "true");
  7249.   },
  7250.  
  7251.   doCommand: function BATH_doCommand() {
  7252.     PlacesCommandHook.bookmarkCurrentPages();
  7253.   },
  7254.  
  7255.   // nsIDOMEventListener
  7256.   handleEvent: function(aEvent) {
  7257.     this._updateCommandState(aEvent.type == "TabClose");
  7258.   }
  7259. };
  7260.  
  7261. /**
  7262.  * Utility class to handle manipulations of the identity indicators in the UI
  7263.  */
  7264. function IdentityHandler() {
  7265.   this._stringBundle = document.getElementById("bundle_browser");
  7266.   this._staticStrings = {};
  7267.   this._staticStrings[this.IDENTITY_MODE_DOMAIN_VERIFIED] = {
  7268.     encryption_label: this._stringBundle.getString("identity.encrypted")  
  7269.   };
  7270.   this._staticStrings[this.IDENTITY_MODE_IDENTIFIED] = {
  7271.     encryption_label: this._stringBundle.getString("identity.encrypted")
  7272.   };
  7273.   this._staticStrings[this.IDENTITY_MODE_UNKNOWN] = {
  7274.     encryption_label: this._stringBundle.getString("identity.unencrypted")  
  7275.   };
  7276.  
  7277.   this._cacheElements();
  7278. }
  7279.  
  7280. IdentityHandler.prototype = {
  7281.  
  7282.   // Mode strings used to control CSS display
  7283.   IDENTITY_MODE_IDENTIFIED       : "verifiedIdentity", // High-quality identity information
  7284.   IDENTITY_MODE_DOMAIN_VERIFIED  : "verifiedDomain",   // Minimal SSL CA-signed domain verification
  7285.   IDENTITY_MODE_UNKNOWN          : "unknownIdentity",  // No trusted identity information
  7286.  
  7287.   // Cache the most recent SSLStatus and Location seen in checkIdentity
  7288.   _lastStatus : null,
  7289.   _lastLocation : null,
  7290.  
  7291.   /**
  7292.    * Build out a cache of the elements that we need frequently.
  7293.    */
  7294.   _cacheElements : function() {
  7295.     this._identityPopup = document.getElementById("identity-popup");
  7296.     this._identityBox = document.getElementById("identity-box");
  7297.     this._identityPopupContentBox = document.getElementById("identity-popup-content-box");
  7298.     this._identityPopupContentHost = document.getElementById("identity-popup-content-host");
  7299.     this._identityPopupContentOwner = document.getElementById("identity-popup-content-owner");
  7300.     this._identityPopupContentSupp = document.getElementById("identity-popup-content-supplemental");
  7301.     this._identityPopupContentVerif = document.getElementById("identity-popup-content-verifier");
  7302.     this._identityPopupEncLabel = document.getElementById("identity-popup-encryption-label");
  7303.     this._identityIconLabel = document.getElementById("identity-icon-label");
  7304.   },
  7305.  
  7306.   /**
  7307.    * Handler for mouseclicks on the "More Information" button in the
  7308.    * "identity-popup" panel.
  7309.    */
  7310.   handleMoreInfoClick : function(event) {
  7311.     displaySecurityInfo();
  7312.     event.stopPropagation();
  7313.   },
  7314.   
  7315.   /**
  7316.    * Helper to parse out the important parts of _lastStatus (of the SSL cert in
  7317.    * particular) for use in constructing identity UI strings
  7318.   */
  7319.   getIdentityData : function() {
  7320.     var result = {};
  7321.     var status = this._lastStatus.QueryInterface(Components.interfaces.nsISSLStatus);
  7322.     var cert = status.serverCert;
  7323.     
  7324.     // Human readable name of Subject
  7325.     result.subjectOrg = cert.organization;
  7326.     
  7327.     // SubjectName fields, broken up for individual access
  7328.     if (cert.subjectName) {
  7329.       result.subjectNameFields = {};
  7330.       cert.subjectName.split(",").forEach(function(v) {
  7331.         var field = v.split("=");
  7332.         this[field[0]] = field[1];
  7333.       }, result.subjectNameFields);
  7334.       
  7335.       // Call out city, state, and country specifically
  7336.       result.city = result.subjectNameFields.L;
  7337.       result.state = result.subjectNameFields.ST;
  7338.       result.country = result.subjectNameFields.C;
  7339.     }
  7340.     
  7341.     // Human readable name of Certificate Authority
  7342.     result.caOrg =  cert.issuerOrganization || cert.issuerCommonName;
  7343.     result.cert = cert;
  7344.     
  7345.     return result;
  7346.   },
  7347.   
  7348.   /**
  7349.    * Determine the identity of the page being displayed by examining its SSL cert
  7350.    * (if available) and, if necessary, update the UI to reflect this.  Intended to
  7351.    * be called by onSecurityChange
  7352.    * 
  7353.    * @param PRUint32 state
  7354.    * @param JS Object location that mirrors an nsLocation (i.e. has .host and
  7355.    *                           .hostname and .port)
  7356.    */
  7357.   checkIdentity : function(state, location) {
  7358.     var currentStatus = gBrowser.securityUI
  7359.                                 .QueryInterface(Components.interfaces.nsISSLStatusProvider)
  7360.                                 .SSLStatus;
  7361.     this._lastStatus = currentStatus;
  7362.     this._lastLocation = location;
  7363.     
  7364.     if (state & Components.interfaces.nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL)
  7365.       this.setMode(this.IDENTITY_MODE_IDENTIFIED);
  7366.     else if (state & Components.interfaces.nsIWebProgressListener.STATE_SECURE_HIGH)
  7367.       this.setMode(this.IDENTITY_MODE_DOMAIN_VERIFIED);
  7368.     else
  7369.       this.setMode(this.IDENTITY_MODE_UNKNOWN);
  7370.   },
  7371.   
  7372.   /**
  7373.    * Return the eTLD+1 version of the current hostname
  7374.    */
  7375.   getEffectiveHost : function() {
  7376.     // Cache the eTLDService if this is our first time through
  7377.     if (!this._eTLDService)
  7378.       this._eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"]
  7379.                          .getService(Ci.nsIEffectiveTLDService);
  7380.     try {
  7381.       return this._eTLDService.getBaseDomainFromHost(this._lastLocation.hostname);
  7382.     } catch (e) {
  7383.       // If something goes wrong (e.g. hostname is an IP address) just fail back
  7384.       // to the full domain.
  7385.       return this._lastLocation.hostname;
  7386.     }
  7387.   },
  7388.   
  7389.   /**
  7390.    * Update the UI to reflect the specified mode, which should be one of the
  7391.    * IDENTITY_MODE_* constants.
  7392.    */
  7393.   setMode : function(newMode) {
  7394.     if (!this._identityBox) {
  7395.       // No identity box means the identity box is not visible, in which
  7396.       // case there's nothing to do.
  7397.       return;
  7398.     }
  7399.  
  7400.     this._identityBox.className = newMode;
  7401.     this.setIdentityMessages(newMode);
  7402.     
  7403.     // Update the popup too, if it's open
  7404.     if (this._identityPopup.state == "open")
  7405.       this.setPopupMessages(newMode);
  7406.   },
  7407.   
  7408.   /**
  7409.    * Set up the messages for the primary identity UI based on the specified mode,
  7410.    * and the details of the SSL cert, where applicable
  7411.    *
  7412.    * @param newMode The newly set identity mode.  Should be one of the IDENTITY_MODE_* constants.
  7413.    */
  7414.   setIdentityMessages : function(newMode) {
  7415.     if (newMode == this.IDENTITY_MODE_DOMAIN_VERIFIED) {
  7416.       var iData = this.getIdentityData();     
  7417.       
  7418.       // It would be sort of nice to use the CN= field in the cert, since that's
  7419.       // typically what we want here, but thanks to x509 certs being extensible,
  7420.       // it's not the only place you have to check, there can be more than one domain,
  7421.       // et cetera, ad nauseum.  We know the cert is valid for location.host, so
  7422.       // let's just use that. Check the pref to determine how much of the verified
  7423.       // hostname to show
  7424.       var icon_label = "";
  7425.       switch (gPrefService.getIntPref("browser.identity.ssl_domain_display")) {
  7426.         case 2 : // Show full domain
  7427.           icon_label = this._lastLocation.hostname;
  7428.           break;
  7429.         case 1 : // Show eTLD.
  7430.           icon_label = this.getEffectiveHost();
  7431.       }
  7432.       
  7433.       // We need a port number for all lookups.  If one hasn't been specified, use
  7434.       // the https default
  7435.       var lookupHost = this._lastLocation.host;
  7436.       if (lookupHost.indexOf(':') < 0)
  7437.         lookupHost += ":443";
  7438.  
  7439.       // Cache the override service the first time we need to check it
  7440.       if (!this._overrideService)
  7441.         this._overrideService = Components.classes["@mozilla.org/security/certoverride;1"]
  7442.                                           .getService(Components.interfaces.nsICertOverrideService);
  7443.  
  7444.       // Verifier is either the CA Org, for a normal cert, or a special string
  7445.       // for certs that are trusted because of a security exception.
  7446.       var tooltip = this._stringBundle.getFormattedString("identity.identified.verifier",
  7447.                                                           [iData.caOrg]);
  7448.       
  7449.       // Check whether this site is a security exception. XPConnect does the right
  7450.       // thing here in terms of converting _lastLocation.port from string to int, but
  7451.       // the overrideService doesn't like undefined ports, so make sure we have
  7452.       // something in the default case (bug 432241).
  7453.       if (this._overrideService.hasMatchingOverride(this._lastLocation.hostname, 
  7454.                                                     (this._lastLocation.port || 443),
  7455.                                                     iData.cert, {}, {}))
  7456.         tooltip = this._stringBundle.getString("identity.identified.verified_by_you");
  7457.     }
  7458.     else if (newMode == this.IDENTITY_MODE_IDENTIFIED) {
  7459.       // If it's identified, then we can populate the dialog with credentials
  7460.       iData = this.getIdentityData();  
  7461.       tooltip = this._stringBundle.getFormattedString("identity.identified.verifier",
  7462.                                                       [iData.caOrg]);
  7463.       if (iData.country)
  7464.         icon_label = this._stringBundle.getFormattedString("identity.identified.title_with_country",
  7465.                                                            [iData.subjectOrg, iData.country]);
  7466.       else
  7467.         icon_label = iData.subjectOrg;
  7468.     }
  7469.     else {
  7470.       tooltip = this._stringBundle.getString("identity.unknown.tooltip");
  7471.       icon_label = "";
  7472.     }
  7473.     
  7474.     // Push the appropriate strings out to the UI
  7475.     this._identityBox.tooltipText = tooltip;
  7476.     this._identityIconLabel.value = icon_label;
  7477.   },
  7478.   
  7479.   /**
  7480.    * Set up the title and content messages for the identity message popup,
  7481.    * based on the specified mode, and the details of the SSL cert, where
  7482.    * applicable
  7483.    *
  7484.    * @param newMode The newly set identity mode.  Should be one of the IDENTITY_MODE_* constants.
  7485.    */
  7486.   setPopupMessages : function(newMode) {
  7487.       
  7488.     this._identityPopup.className = newMode;
  7489.     this._identityPopupContentBox.className = newMode;
  7490.     
  7491.     // Set the static strings up front
  7492.     this._identityPopupEncLabel.textContent = this._staticStrings[newMode].encryption_label;
  7493.     
  7494.     // Initialize the optional strings to empty values
  7495.     var supplemental = "";
  7496.     var verifier = "";
  7497.     
  7498.     if (newMode == this.IDENTITY_MODE_DOMAIN_VERIFIED) {
  7499.       var iData = this.getIdentityData();
  7500.       var host = this.getEffectiveHost();
  7501.       var owner = this._stringBundle.getString("identity.ownerUnknown2");
  7502.       verifier = this._identityBox.tooltipText;
  7503.       supplemental = "";
  7504.     }
  7505.     else if (newMode == this.IDENTITY_MODE_IDENTIFIED) {
  7506.       // If it's identified, then we can populate the dialog with credentials
  7507.       iData = this.getIdentityData();
  7508.       host = this.getEffectiveHost();
  7509.       owner = iData.subjectOrg; 
  7510.       verifier = this._identityBox.tooltipText;
  7511.  
  7512.       // Build an appropriate supplemental block out of whatever location data we have
  7513.       if (iData.city)
  7514.         supplemental += iData.city + "\n";        
  7515.       if (iData.state && iData.country)
  7516.         supplemental += this._stringBundle.getFormattedString("identity.identified.state_and_country",
  7517.                                                               [iData.state, iData.country]);
  7518.       else if (iData.state) // State only
  7519.         supplemental += iData.state;
  7520.       else if (iData.country) // Country only
  7521.         supplemental += iData.country;
  7522.     }
  7523.     else {
  7524.       // These strings will be hidden in CSS anyhow
  7525.       host = "";
  7526.       owner = "";
  7527.     }
  7528.     
  7529.     // Push the appropriate strings out to the UI
  7530.     this._identityPopupContentHost.textContent = host;
  7531.     this._identityPopupContentOwner.textContent = owner;
  7532.     this._identityPopupContentSupp.textContent = supplemental;
  7533.     this._identityPopupContentVerif.textContent = verifier;
  7534.   },
  7535.  
  7536.   hideIdentityPopup : function() {
  7537.     this._identityPopup.hidePopup();
  7538.   },
  7539.  
  7540.   /**
  7541.    * Click handler for the identity-box element in primary chrome.  
  7542.    */
  7543.   handleIdentityButtonEvent : function(event) {
  7544.   
  7545.     event.stopPropagation();
  7546.  
  7547.     if ((event.type == "click" && event.button != 0) ||
  7548.         (event.type == "keypress" && event.charCode != KeyEvent.DOM_VK_SPACE &&
  7549.          event.keyCode != KeyEvent.DOM_VK_RETURN))
  7550.       return; // Left click, space or enter only
  7551.  
  7552.     // Revert the contents of the location bar, see bug 406779
  7553.     handleURLBarRevert();
  7554.  
  7555.     // Make sure that the display:none style we set in xul is removed now that
  7556.     // the popup is actually needed
  7557.     this._identityPopup.hidden = false;
  7558.     
  7559.     // Tell the popup to consume dismiss clicks, to avoid bug 395314
  7560.     this._identityPopup.popupBoxObject
  7561.         .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  7562.     
  7563.     // Update the popup strings
  7564.     this.setPopupMessages(this._identityBox.className);
  7565.     
  7566.     // Now open the popup, anchored off the primary chrome element
  7567.     this._identityPopup.openPopup(this._identityBox, 'after_start');
  7568.   }
  7569. };
  7570.  
  7571. var gIdentityHandler; 
  7572.  
  7573. /**
  7574.  * Returns the singleton instance of the identity handler class.  Should always be
  7575.  * used instead of referencing the global variable directly or creating new instances
  7576.  */
  7577. function getIdentityHandler() {
  7578.   if (!gIdentityHandler)
  7579.     gIdentityHandler = new IdentityHandler();
  7580.   return gIdentityHandler;    
  7581. }
  7582.  
  7583. let DownloadMonitorPanel = {
  7584.   //////////////////////////////////////////////////////////////////////////////
  7585.   //// DownloadMonitorPanel Member Variables
  7586.  
  7587.   _panel: null,
  7588.   _activeStr: null,
  7589.   _pausedStr: null,
  7590.   _lastTime: Infinity,
  7591.   _listening: false,
  7592.  
  7593.   //////////////////////////////////////////////////////////////////////////////
  7594.   //// DownloadMonitorPanel Public Methods
  7595.  
  7596.   /**
  7597.    * Initialize the status panel and member variables
  7598.    */
  7599.   init: function DMP_init() {
  7600.     // Load the modules to help display strings
  7601.     Cu.import("resource://gre/modules/DownloadUtils.jsm");
  7602.     Cu.import("resource://gre/modules/PluralForm.jsm");
  7603.  
  7604.     // Initialize "private" member variables
  7605.     this._panel = document.getElementById("download-monitor");
  7606.  
  7607.     // Cache the status strings
  7608.     let (bundle = document.getElementById("bundle_browser")) {
  7609.       this._activeStr = bundle.getString("activeDownloads");
  7610.       this._pausedStr = bundle.getString("pausedDownloads");
  7611.     }
  7612.  
  7613.     gDownloadMgr.addListener(this);
  7614.     this._listening = true;
  7615.  
  7616.     this.updateStatus();
  7617.   },
  7618.  
  7619.   uninit: function DMP_uninit() {
  7620.     if (this._listening)
  7621.       gDownloadMgr.removeListener(this);
  7622.   },
  7623.  
  7624.   /**
  7625.    * Update status based on the number of active and paused downloads
  7626.    */
  7627.   updateStatus: function DMP_updateStatus() {
  7628.     let numActive = gDownloadMgr.activeDownloadCount;
  7629.  
  7630.     // Hide the panel and reset the "last time" if there's no downloads
  7631.     if (numActive == 0) {
  7632.       this._panel.hidden = true;
  7633.       this._lastTime = Infinity;
  7634.  
  7635.       return;
  7636.     }
  7637.   
  7638.     // Find the download with the longest remaining time
  7639.     let numPaused = 0;
  7640.     let maxTime = -Infinity;
  7641.     let dls = gDownloadMgr.activeDownloads;
  7642.     while (dls.hasMoreElements()) {
  7643.       let dl = dls.getNext().QueryInterface(Ci.nsIDownload);
  7644.       if (dl.state == gDownloadMgr.DOWNLOAD_DOWNLOADING) {
  7645.         // Figure out if this download takes longer
  7646.         if (dl.speed > 0 && dl.size > 0)
  7647.           maxTime = Math.max(maxTime, (dl.size - dl.amountTransferred) / dl.speed);
  7648.         else
  7649.           maxTime = -1;
  7650.       }
  7651.       else if (dl.state == gDownloadMgr.DOWNLOAD_PAUSED)
  7652.         numPaused++;
  7653.     }
  7654.  
  7655.     // Get the remaining time string and last sec for time estimation
  7656.     let timeLeft;
  7657.     [timeLeft, this._lastTime] = DownloadUtils.getTimeLeft(maxTime, this._lastTime);
  7658.  
  7659.     // Figure out how many downloads are currently downloading
  7660.     let numDls = numActive - numPaused;
  7661.     let status = this._activeStr;
  7662.  
  7663.     // If all downloads are paused, show the paused message instead
  7664.     if (numDls == 0) {
  7665.       numDls = numPaused;
  7666.       status = this._pausedStr;
  7667.     }
  7668.  
  7669.     // Get the correct plural form and insert the number of downloads and time
  7670.     // left message if necessary
  7671.     status = PluralForm.get(numDls, status);
  7672.     status = status.replace("#1", numDls);
  7673.     status = status.replace("#2", timeLeft);
  7674.  
  7675.     // Update the panel and show it
  7676.     this._panel.label = status;
  7677.     this._panel.hidden = false;
  7678.   },
  7679.  
  7680.   //////////////////////////////////////////////////////////////////////////////
  7681.   //// nsIDownloadProgressListener
  7682.  
  7683.   /**
  7684.    * Update status for download progress changes
  7685.    */
  7686.   onProgressChange: function() {
  7687.     this.updateStatus();
  7688.   },
  7689.  
  7690.   /**
  7691.    * Update status for download state changes
  7692.    */
  7693.   onDownloadStateChange: function() {
  7694.     this.updateStatus();
  7695.   },
  7696.  
  7697.   onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus, aDownload) {
  7698.   },
  7699.  
  7700.   onSecurityChange: function(aWebProgress, aRequest, aState, aDownload) {
  7701.   },
  7702.  
  7703.   //////////////////////////////////////////////////////////////////////////////
  7704.   //// nsISupports
  7705.  
  7706.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIDownloadProgressListener]),
  7707. };
  7708.