home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 May / maximum-cd-2009-05.iso / DiscContents / Firefox Setup 3.0.6.exe / nonlocalized / chrome / browser.jar / content / browser / browser.js < prev    next >
Encoding:
Text File  |  2008-11-17  |  264.6 KB  |  7,691 lines

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