home *** CD-ROM | disk | FTP | other *** search
/ Computer Shopper 233 / Computer Shopper 233 / ComputerShopperDVD233.iso / Toolkit / Internet / Firefox / Firefox Setup 2.0.0.3.exe / nonlocalized / components / nsSessionStore.js < prev    next >
Encoding:
JavaScript  |  2007-03-10  |  71.9 KB  |  2,151 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is the nsSessionStore component.
  15.  *
  16.  * The Initial Developer of the Original Code is
  17.  * Simon B├╝nzli <zeniko@gmail.com>
  18.  *
  19.  * Portions created by the Initial Developer are Copyright (C) 2006
  20.  * the Initial Developer. All Rights Reserved.
  21.  *
  22.  * Contributor(s):
  23.  * Dietrich Ayala <autonome@gmail.com>
  24.  *
  25.  * Alternatively, the contents of this file may be used under the terms of
  26.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  27.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28.  * in which case the provisions of the GPL or the LGPL are applicable instead
  29.  * of those above. If you wish to allow use of your version of this file only
  30.  * under the terms of either the GPL or the LGPL, and not to allow others to
  31.  * use your version of this file under the terms of the MPL, indicate your
  32.  * decision by deleting the provisions above and replace them with the notice
  33.  * and other provisions required by the GPL or the LGPL. If you do not delete
  34.  * the provisions above, a recipient may use your version of this file under
  35.  * the terms of any one of the MPL, the GPL or the LGPL.
  36.  *
  37.  * ***** END LICENSE BLOCK ***** */
  38.  
  39. /**
  40.  * Session Storage and Restoration
  41.  * 
  42.  * Overview
  43.  * This service keeps track of a user's session, storing the various bits
  44.  * required to return the browser to it's current state. The relevant data is 
  45.  * stored in memory, and is periodically saved to disk in a file in the 
  46.  * profile directory. The service is started at first window load, in
  47.  * delayedStartup, and will restore the session from the data received from
  48.  * the nsSessionStartup service.
  49.  */
  50.  
  51. /* :::::::: Constants and Helpers ::::::::::::::: */
  52.  
  53. const Cc = Components.classes;
  54. const Ci = Components.interfaces;
  55. const Cr = Components.results;
  56.  
  57. const CID = Components.ID("{5280606b-2510-4fe0-97ef-9b5a22eafe6b}");
  58. const CONTRACT_ID = "@mozilla.org/browser/sessionstore;1";
  59. const CLASS_NAME = "Browser Session Store Service";
  60.  
  61. const STATE_STOPPED = 0;
  62. const STATE_RUNNING = 1;
  63. const STATE_QUITTING = -1;
  64.  
  65. const STATE_STOPPED_STR = "stopped";
  66. const STATE_RUNNING_STR = "running";
  67.  
  68. const PRIVACY_NONE = 0;
  69. const PRIVACY_ENCRYPTED = 1;
  70. const PRIVACY_FULL = 2;
  71.  
  72. /* :::::::: Pref Defaults :::::::::::::::::::: */
  73.  
  74. // whether the service is enabled
  75. const DEFAULT_ENABLED = true;
  76.  
  77. // minimal interval between two save operations (in milliseconds)
  78. const DEFAULT_INTERVAL = 10000;
  79.  
  80. // maximum number of closed tabs remembered (per window)
  81. const DEFAULT_MAX_TABS_UNDO = 10;
  82.  
  83. // maximal amount of POSTDATA to be stored (in bytes, -1 = all of it)
  84. const DEFAULT_POSTDATA = 0;
  85.  
  86. // on which sites to save text data, POSTDATA and cookies
  87. // (0 = everywhere, 1 = unencrypted sites, 2 = nowhere)
  88. const DEFAULT_PRIVACY_LEVEL = PRIVACY_ENCRYPTED;
  89.  
  90. // resume the current session at startup just this once
  91. const DEFAULT_RESUME_SESSION_ONCE = false;
  92.  
  93. // resume the current session at startup if it had previously crashed
  94. const DEFAULT_RESUME_FROM_CRASH = true;
  95.  
  96. // global notifications observed
  97. const OBSERVING = [
  98.   "domwindowopened", "domwindowclosed",
  99.   "quit-application-requested", "quit-application-granted",
  100.   "quit-application", "browser:purge-session-history"
  101. ];
  102.  
  103. /*
  104. XUL Window properties to (re)store
  105. Restored in restoreDimensions_proxy()
  106. */
  107. const WINDOW_ATTRIBUTES = ["width", "height", "screenX", "screenY", "sizemode"];
  108.  
  109. /* 
  110. Hideable window features to (re)store
  111. Restored in restoreWindowFeatures()
  112. */
  113. const WINDOW_HIDEABLE_FEATURES = [
  114.   "menubar", "toolbar", "locationbar", 
  115.   "personalbar", "statusbar", "scrollbars"
  116. ];
  117.  
  118. /*
  119. docShell capabilities to (re)store
  120. Restored in restoreHistory()
  121. eg: browser.docShell["allow" + aCapability] = false;
  122. */
  123. const CAPABILITIES = [
  124.   "Subframes", "Plugins", "Javascript", "MetaRedirects", "Images"
  125. ];
  126.  
  127. function debug(aMsg) {
  128.   aMsg = ("SessionStore: " + aMsg).replace(/\S{80}/g, "$&\n");
  129.   Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService)
  130.                                      .logStringMessage(aMsg);
  131. }
  132.  
  133. /* :::::::: The Service ::::::::::::::: */
  134.  
  135. function SessionStoreService() {
  136. }
  137.  
  138. SessionStoreService.prototype = {
  139.  
  140.   // xul:tab attributes to (re)store (extensions might want to hook in here)
  141.   xulAttributes: [],
  142.  
  143.   // set default load state
  144.   _loadState: STATE_STOPPED,
  145.  
  146.   // minimal interval between two save operations (in milliseconds)
  147.   _interval: DEFAULT_INTERVAL,
  148.  
  149.   // when crash recovery is disabled, session data is not written to disk
  150.   _resume_from_crash: DEFAULT_RESUME_FROM_CRASH,
  151.  
  152.   // time in milliseconds (Date.now()) when the session was last written to file
  153.   _lastSaveTime: 0, 
  154.  
  155.   // states for all currently opened windows
  156.   _windows: {},
  157.  
  158.   // in case the last closed window ain't a navigator:browser one
  159.   _lastWindowClosed: null,
  160.  
  161.   // not-"dirty" windows usually don't need to have their data updated
  162.   _dirtyWindows: {},
  163.  
  164.   // flag all windows as dirty
  165.   _dirty: false,
  166.  
  167. /* ........ Global Event Handlers .............. */
  168.  
  169.   /**
  170.    * Initialize the component
  171.    */
  172.   init: function sss_init(aWindow) {
  173.     if (!aWindow || this._loadState == STATE_RUNNING) {
  174.       // make sure that all browser windows which try to initialize
  175.       // SessionStore are really tracked by it
  176.       if (aWindow && (!aWindow.__SSi || !this._windows[aWindow.__SSi]))
  177.         this.onLoad(aWindow);
  178.       return;
  179.     }
  180.  
  181.     this._prefBranch = Cc["@mozilla.org/preferences-service;1"].
  182.                        getService(Ci.nsIPrefService).getBranch("browser.");
  183.     this._prefBranch.QueryInterface(Ci.nsIPrefBranch2);
  184.  
  185.     // if the service is disabled, do not init 
  186.     if (!this._getPref("sessionstore.enabled", DEFAULT_ENABLED))
  187.       return;
  188.  
  189.     var observerService = Cc["@mozilla.org/observer-service;1"].
  190.                           getService(Ci.nsIObserverService);
  191.  
  192.     OBSERVING.forEach(function(aTopic) {
  193.       observerService.addObserver(this, aTopic, true);
  194.     }, this);
  195.     
  196.     // get interval from prefs - used often, so caching/observing instead of fetching on-demand
  197.     this._interval = this._getPref("sessionstore.interval", DEFAULT_INTERVAL);
  198.     this._prefBranch.addObserver("sessionstore.interval", this, true);
  199.     
  200.     // get crash recovery state from prefs and allow for proper reaction to state changes
  201.     this._resume_from_crash = this._getPref("sessionstore.resume_from_crash", DEFAULT_RESUME_FROM_CRASH);
  202.     this._prefBranch.addObserver("sessionstore.resume_from_crash", this, true);
  203.     
  204.     // observe prefs changes so we can modify stored data to match
  205.     this._prefBranch.addObserver("sessionstore.max_tabs_undo", this, true);
  206.  
  207.     // get file references
  208.     var dirService = Cc["@mozilla.org/file/directory_service;1"].
  209.                      getService(Ci.nsIProperties);
  210.     this._sessionFile = dirService.get("ProfD", Ci.nsILocalFile);
  211.     this._sessionFileBackup = this._sessionFile.clone();
  212.     this._sessionFile.append("sessionstore.js");
  213.     this._sessionFileBackup.append("sessionstore.bak");
  214.    
  215.     // get string containing session state
  216.     var iniString;
  217.     try {
  218.       var ss = Cc["@mozilla.org/browser/sessionstartup;1"].
  219.                getService(Ci.nsISessionStartup);
  220.       if (ss.doRestore())
  221.         iniString = ss.state;
  222.     }
  223.     catch(ex) { dump(ex + "\n"); } // no state to restore, which is ok
  224.  
  225.     if (iniString) {
  226.       try {
  227.         // parse the session state into JS objects
  228.         this._initialState = this._safeEval(iniString);
  229.         // set bool detecting crash
  230.         this._lastSessionCrashed =
  231.           this._initialState.session && this._initialState.session.state &&
  232.           this._initialState.session.state == STATE_RUNNING_STR;
  233.         
  234.         // restore the features of the first window from localstore.rdf
  235.         WINDOW_ATTRIBUTES.forEach(function(aAttr) {
  236.           delete this._initialState.windows[0][aAttr];
  237.         }, this);
  238.         delete this._initialState.windows[0].hidden;
  239.       }
  240.       catch (ex) { debug("The session file is invalid: " + ex); }
  241.     }
  242.     
  243.     // if last session crashed, backup the session
  244.     if (this._lastSessionCrashed) {
  245.       try {
  246.         this._writeFile(this._sessionFileBackup, iniString);
  247.       }
  248.       catch (ex) { } // nothing else we can do here
  249.     }
  250.  
  251.     // remove the session data files if crash recovery is disabled
  252.     if (!this._resume_from_crash)
  253.       this._clearDisk();
  254.     
  255.     // As this is called at delayedStartup, restoration must be initiated here
  256.     this.onLoad(aWindow);
  257.   },
  258.  
  259.   /**
  260.    * Called on application shutdown, after notifications:
  261.    * quit-application-granted, quit-application
  262.    */
  263.   _uninit: function sss_uninit() {
  264.     if (this._doResumeSession()) { // save all data for session resuming 
  265.       this.saveState(true);
  266.     }
  267.     else { // discard all session related data 
  268.       this._clearDisk();
  269.     }
  270.     // Make sure to break our cycle with the save timer
  271.     if (this._saveTimer) {
  272.       this._saveTimer.cancel();
  273.       this._saveTimer = null;
  274.     }
  275.   },
  276.  
  277.   /**
  278.    * Handle notifications
  279.    */
  280.   observe: function sss_observe(aSubject, aTopic, aData) {
  281.     // for event listeners
  282.     var _this = this;
  283.  
  284.     switch (aTopic) {
  285.     case "domwindowopened": // catch new windows
  286.       aSubject.addEventListener("load", function(aEvent) {
  287.         aEvent.currentTarget.removeEventListener("load", arguments.callee, false);
  288.         _this.onLoad(aEvent.currentTarget);
  289.         }, false);
  290.       break;
  291.     case "domwindowclosed": // catch closed windows
  292.       this.onClose(aSubject);
  293.       break;
  294.     case "quit-application-requested":
  295.       // get a current snapshot of all windows
  296.       this._forEachBrowserWindow(function(aWindow) {
  297.         this._collectWindowData(aWindow);
  298.       });
  299.       this._dirtyWindows = [];
  300.       this._dirty = false;
  301.       break;
  302.     case "quit-application-granted":
  303.       // freeze the data at what we've got (ignoring closing windows)
  304.       this._loadState = STATE_QUITTING;
  305.       break;
  306.     case "quit-application":
  307.       if (aData == "restart")
  308.         this._prefBranch.setBoolPref("sessionstore.resume_session_once", true);
  309.       this._loadState = STATE_QUITTING; // just to be sure
  310.       this._uninit();
  311.       break;
  312.     case "browser:purge-session-history": // catch sanitization 
  313.       this._forEachBrowserWindow(function(aWindow) {
  314.         Array.forEach(aWindow.getBrowser().browsers, function(aBrowser) {
  315.           delete aBrowser.parentNode.__SS_data;
  316.         });
  317.       });
  318.       this._clearDisk();
  319.       // also clear all data about closed tabs
  320.       for (ix in this._windows) {
  321.         this._windows[ix]._closedTabs = [];
  322.       }
  323.       // give the tabbrowsers a chance to clear their histories first
  324.       var win = this._getMostRecentBrowserWindow();
  325.       if (win)
  326.         win.setTimeout(function() { _this.saveState(true); }, 0);
  327.       else
  328.         this.saveState(true);
  329.       break;
  330.     case "nsPref:changed": // catch pref changes
  331.       switch (aData) {
  332.       // if the user decreases the max number of closed tabs they want
  333.       // preserved update our internal states to match that max
  334.       case "sessionstore.max_tabs_undo":
  335.         var ix;
  336.         for (ix in this._windows) {
  337.           this._windows[ix]._closedTabs.splice(this._getPref("sessionstore.max_tabs_undo", DEFAULT_MAX_TABS_UNDO));
  338.         }
  339.         break;
  340.       case "sessionstore.interval":
  341.         this._interval = this._getPref("sessionstore.interval", this._interval);
  342.         // reset timer and save
  343.         if (this._saveTimer) {
  344.           this._saveTimer.cancel();
  345.           this._saveTimer = null;
  346.         }
  347.         this.saveStateDelayed(null, -1);
  348.         break;
  349.       case "sessionstore.resume_from_crash":
  350.         this._resume_from_crash = this._getPref("sessionstore.resume_from_crash", this._resume_from_crash);
  351.         // either create the file with crash recovery information or remove it
  352.         // (when _loadState is not STATE_RUNNING, that file is used for session resuming instead)
  353.         if (this._resume_from_crash)
  354.           this.saveState(true);
  355.         else if (this._loadState == STATE_RUNNING)
  356.           this._clearDisk();
  357.         break;
  358.       }
  359.       break;
  360.     case "timer-callback": // timer call back for delayed saving
  361.       this._saveTimer = null;
  362.       this.saveState();
  363.       break;
  364.     }
  365.   },
  366.  
  367. /* ........ Window Event Handlers .............. */
  368.  
  369.   /**
  370.    * Implement nsIDOMEventListener for handling various window and tab events
  371.    */
  372.   handleEvent: function sss_handleEvent(aEvent) {
  373.     switch (aEvent.type) {
  374.       case "load":
  375.         this.onTabLoad(aEvent.currentTarget.ownerDocument.defaultView, aEvent.currentTarget, aEvent);
  376.         break;
  377.       case "pageshow":
  378.         this.onTabLoad(aEvent.currentTarget.ownerDocument.defaultView, aEvent.currentTarget, aEvent);
  379.         break;
  380.       case "input":
  381.         this.onTabInput(aEvent.currentTarget.ownerDocument.defaultView, aEvent.currentTarget, aEvent);
  382.         break;
  383.       case "DOMAutoComplete":
  384.         this.onTabInput(aEvent.currentTarget.ownerDocument.defaultView, aEvent.currentTarget, aEvent);
  385.         break;
  386.       case "TabOpen":
  387.       case "TabClose":
  388.         var panelID = aEvent.originalTarget.linkedPanel;
  389.         var tabpanel = aEvent.originalTarget.ownerDocument.getElementById(panelID);
  390.         if (aEvent.type == "TabOpen") {
  391.           this.onTabAdd(aEvent.currentTarget.ownerDocument.defaultView, tabpanel);
  392.         }
  393.         else {
  394.           this.onTabClose(aEvent.currentTarget.ownerDocument.defaultView, aEvent.originalTarget);
  395.           this.onTabRemove(aEvent.currentTarget.ownerDocument.defaultView, tabpanel);
  396.         }
  397.         break;
  398.       case "TabSelect":
  399.         var tabpanels = aEvent.currentTarget.mPanelContainer;
  400.         this.onTabSelect(aEvent.currentTarget.ownerDocument.defaultView, tabpanels);
  401.         break;
  402.     }
  403.   },
  404.  
  405.   /**
  406.    * If it's the first window load since app start...
  407.    * - determine if we're reloading after a crash or a forced-restart
  408.    * - restore window state
  409.    * - restart downloads
  410.    * Set up event listeners for this window's tabs
  411.    * @param aWindow
  412.    *        Window reference
  413.    */
  414.   onLoad: function sss_onLoad(aWindow) {
  415.     // return if window has already been initialized
  416.     if (aWindow && aWindow.__SSi && this._windows[aWindow.__SSi])
  417.       return;
  418.  
  419.     var _this = this;
  420.  
  421.     // ignore non-browser windows and windows opened while shutting down
  422.     if (aWindow.document.documentElement.getAttribute("windowtype") != "navigator:browser" ||
  423.       this._loadState == STATE_QUITTING)
  424.       return;
  425.  
  426.     // assign it a unique identifier (timestamp)
  427.     aWindow.__SSi = "window" + Date.now();
  428.  
  429.     // and create its data object
  430.     this._windows[aWindow.__SSi] = { tabs: [], selected: 0, _closedTabs: [] };
  431.     
  432.     // perform additional initialization when the first window is loading
  433.     if (this._loadState == STATE_STOPPED) {
  434.       this._loadState = STATE_RUNNING;
  435.       this._lastSaveTime = Date.now();
  436.       
  437.       // don't save during the first five seconds
  438.       // (until most of the pages have been restored)
  439.       this.saveStateDelayed(aWindow, 10000);
  440.  
  441.       // restore a crashed session resp. resume the last session if requested
  442.       if (this._initialState) {
  443.         // make sure that the restored tabs are first in the window
  444.         this._initialState._firstTabs = true;
  445.         this.restoreWindow(aWindow, this._initialState, this._isCmdLineEmpty(aWindow));
  446.         delete this._initialState;
  447.       }
  448.       
  449.       if (this._lastSessionCrashed) {
  450.         // restart any interrupted downloads
  451.         aWindow.setTimeout(function(){ _this.retryDownloads(aWindow); }, 0);
  452.       }
  453.     }
  454.     
  455.     var tabbrowser = aWindow.getBrowser();
  456.     var tabpanels = tabbrowser.mPanelContainer;
  457.     
  458.     // add tab change listeners to all already existing tabs
  459.     for (var i = 0; i < tabpanels.childNodes.length; i++) {
  460.       this.onTabAdd(aWindow, tabpanels.childNodes[i], true);
  461.     }
  462.     // notification of tab add/remove/selection
  463.     tabbrowser.addEventListener("TabOpen", this, true);
  464.     tabbrowser.addEventListener("TabClose", this, true);
  465.     tabbrowser.addEventListener("TabSelect", this, true);
  466.   },
  467.  
  468.   /**
  469.    * On window close...
  470.    * - remove event listeners from tabs
  471.    * - save all window data
  472.    * @param aWindow
  473.    *        Window reference
  474.    */
  475.   onClose: function sss_onClose(aWindow) {
  476.     // ignore windows not tracked by SessionStore
  477.     if (!aWindow.__SSi || !this._windows[aWindow.__SSi]) {
  478.       return;
  479.     }
  480.     
  481.     var tabbrowser = aWindow.getBrowser();
  482.     var tabpanels = tabbrowser.mPanelContainer;
  483.  
  484.     tabbrowser.removeEventListener("TabOpen", this, true);
  485.     tabbrowser.removeEventListener("TabClose", this, true);
  486.     tabbrowser.removeEventListener("TabSelect", this, true);
  487.     
  488.     for (var i = 0; i < tabpanels.childNodes.length; i++) {
  489.       this.onTabRemove(aWindow, tabpanels.childNodes[i], true);
  490.     }
  491.     
  492.     if (this._loadState == STATE_RUNNING) { // window not closed during a regular shut-down 
  493.       // update all window data for a last time
  494.       this._collectWindowData(aWindow);
  495.       
  496.       // preserve this window's data (in case it was the last navigator:browser)
  497.       this._lastWindowClosed = this._windows[aWindow.__SSi];
  498.       this._lastWindowClosed.title = aWindow.content.document.title;
  499.       this._updateCookies([this._lastWindowClosed]);
  500.       
  501.       // clear this window from the list
  502.       delete this._windows[aWindow.__SSi];
  503.       
  504.       // save the state without this window to disk
  505.       this.saveStateDelayed();
  506.     }
  507.     
  508.     delete aWindow.__SSi;
  509.   },
  510.  
  511.   /**
  512.    * set up listeners for a new tab
  513.    * @param aWindow
  514.    *        Window reference
  515.    * @param aPanel
  516.    *        TabPanel reference
  517.    * @param aNoNotification
  518.    *        bool Do not save state if we're updating an existing tab
  519.    */
  520.   onTabAdd: function sss_onTabAdd(aWindow, aPanel, aNoNotification) {
  521.     aPanel.addEventListener("load", this, true);
  522.     aPanel.addEventListener("pageshow", this, true);
  523.     aPanel.addEventListener("input", this, true);
  524.     aPanel.addEventListener("DOMAutoComplete", this, true);
  525.     
  526.     if (!aNoNotification) {
  527.       this.saveStateDelayed(aWindow);
  528.     }
  529.   },
  530.  
  531.   /**
  532.    * remove listeners for a tab
  533.    * @param aWindow
  534.    *        Window reference
  535.    * @param aPanel
  536.    *        TabPanel reference
  537.    * @param aNoNotification
  538.    *        bool Do not save state if we're updating an existing tab
  539.    */
  540.   onTabRemove: function sss_onTabRemove(aWindow, aPanel, aNoNotification) {
  541.     aPanel.removeEventListener("load", this, true);
  542.     aPanel.removeEventListener("pageshow", this, true);
  543.     aPanel.removeEventListener("input", this, true);
  544.     aPanel.removeEventListener("DOMAutoComplete", this, true);
  545.     
  546.     delete aPanel.__SS_data;
  547.     delete aPanel.__SS_text;
  548.     
  549.     if (!aNoNotification) {
  550.       this.saveStateDelayed(aWindow);
  551.     }
  552.   },
  553.  
  554.   /**
  555.    * When a tab closes, collect it's properties
  556.    * @param aWindow
  557.    *        Window reference
  558.    * @param aTab
  559.    *        TabPanel reference
  560.    */
  561.   onTabClose: function sss_onTabClose(aWindow, aTab) {
  562.     // don't update our internal state if we don't have to
  563.     if (this._getPref("sessionstore.max_tabs_undo", DEFAULT_MAX_TABS_UNDO) == 0) {
  564.       return;
  565.     }
  566.     
  567.     // make sure that the tab related data is up-to-date
  568.     this._saveWindowHistory(aWindow);
  569.     this._updateTextAndScrollData(aWindow);
  570.     
  571.     // store closed-tab data for undo
  572.     var tabState = this._windows[aWindow.__SSi].tabs[aTab._tPos];
  573.     if (tabState && (tabState.entries.length > 1 ||
  574.         tabState.entries[0].url != "about:blank")) {
  575.       this._windows[aWindow.__SSi]._closedTabs.unshift({
  576.         state: tabState,
  577.         title: aTab.getAttribute("label"),
  578.         pos: aTab._tPos
  579.       });
  580.       var maxTabsUndo = this._getPref("sessionstore.max_tabs_undo", DEFAULT_MAX_TABS_UNDO);
  581.       var length = this._windows[aWindow.__SSi]._closedTabs.length;
  582.       if (length > maxTabsUndo)
  583.         this._windows[aWindow.__SSi]._closedTabs.splice(maxTabsUndo, length - maxTabsUndo);
  584.     }
  585.   },
  586.  
  587.   /**
  588.    * When a tab loads, save state.
  589.    * @param aWindow
  590.    *        Window reference
  591.    * @param aPanel
  592.    *        TabPanel reference
  593.    * @param aEvent
  594.    *        Event obj
  595.    */
  596.   onTabLoad: function sss_onTabLoad(aWindow, aPanel, aEvent) { 
  597.     // react on "load" and solitary "pageshow" events (the first "pageshow"
  598.     // following "load" is too late for deleting the data caches)
  599.     if (aEvent.type != "load" && !aEvent.persisted) {
  600.       return;
  601.     }
  602.     
  603.     delete aPanel.__SS_data;
  604.     delete aPanel.__SS_text;
  605.     this.saveStateDelayed(aWindow);
  606.   },
  607.  
  608.   /**
  609.    * Called when a tabpanel sends the "input" notification 
  610.    * stores textarea data
  611.    * @param aWindow
  612.    *        Window reference
  613.    * @param aPanel
  614.    *        TabPanel reference
  615.    * @param aEvent
  616.    *        Event obj
  617.    */
  618.   onTabInput: function sss_onTabInput(aWindow, aPanel, aEvent) {
  619.     if (this._saveTextData(aPanel, aEvent.originalTarget)) {
  620.       this.saveStateDelayed(aWindow, 3000);
  621.     }
  622.   },
  623.  
  624.   /**
  625.    * When a tab is selected, save session data
  626.    * @param aWindow
  627.    *        Window reference
  628.    * @param aPanels
  629.    *        TabPanel reference
  630.    */
  631.   onTabSelect: function sss_onTabSelect(aWindow, aPanels) {
  632.     if (this._loadState == STATE_RUNNING) {
  633.       this._windows[aWindow.__SSi].selected = aPanels.selectedIndex;
  634.       this.saveStateDelayed(aWindow);
  635.     }
  636.   },
  637.  
  638. /* ........ nsISessionStore API .............. */
  639.  
  640.   getBrowserState: function sss_getBrowserState() {
  641.     return this._toJSONString(this._getCurrentState());
  642.   },
  643.  
  644.   setBrowserState: function sss_setBrowserState(aState) {
  645.     var window = this._getMostRecentBrowserWindow();
  646.     if (!window) {
  647.       this._openWindowWithState("(" + aState + ")");
  648.       return;
  649.     }
  650.  
  651.     // close all other browser windows
  652.     this._forEachBrowserWindow(function(aWindow) {
  653.       if (aWindow != window) {
  654.         aWindow.close();
  655.       }
  656.     });
  657.  
  658.     // restore to the given state
  659.     this.restoreWindow(window, "(" + aState + ")", true);
  660.   },
  661.  
  662.   getWindowState: function sss_getWindowState(aWindow) {
  663.     return this._toJSONString(this._getWindowState(aWindow));
  664.   },
  665.  
  666.   setWindowState: function sss_setWindowState(aWindow, aState, aOverwrite) {
  667.     this.restoreWindow(aWindow, "(" + aState + ")", aOverwrite);
  668.   },
  669.  
  670.   getClosedTabCount: function sss_getClosedTabCount(aWindow) {
  671.     return this._windows[aWindow.__SSi]._closedTabs.length;
  672.   },
  673.  
  674.   closedTabNameAt: function sss_closedTabNameAt(aWindow, aIx) {
  675.     var tabs = this._windows[aWindow.__SSi]._closedTabs;
  676.     
  677.     return aIx in tabs ? tabs[aIx].title : null;
  678.   },
  679.  
  680.   getClosedTabData: function sss_getClosedTabDataAt(aWindow) {
  681.     return this._toJSONString(this._windows[aWindow.__SSi]._closedTabs);
  682.   },
  683.  
  684.   undoCloseTab: function sss_undoCloseTab(aWindow, aIndex) {
  685.     var closedTabs = this._windows[aWindow.__SSi]._closedTabs;
  686.  
  687.     // default to the most-recently closed tab
  688.     aIndex = aIndex || 0;
  689.     
  690.     if (aIndex in closedTabs) {
  691.       var browser = aWindow.getBrowser();
  692.  
  693.       // fetch the data of closed tab, while removing it from the array
  694.       var closedTab = closedTabs.splice(aIndex, 1).shift();
  695.       var closedTabState = closedTab.state;
  696.  
  697.       // create a new tab
  698.       closedTabState._tab = browser.addTab();
  699.       
  700.       // restore the tab's position
  701.       browser.moveTabTo(closedTabState._tab, closedTab.pos);
  702.  
  703.       // restore tab content
  704.       this.restoreHistoryPrecursor(aWindow, [closedTabState], 1, 0, 0);
  705.     }
  706.     else {
  707.       Components.returnCode = Cr.NS_ERROR_INVALID_ARG;
  708.     }
  709.   },
  710.  
  711.   getWindowValue: function sss_getWindowValue(aWindow, aKey) {
  712.     if (aWindow.__SSi) {
  713.       var data = this._windows[aWindow.__SSi].extData || {};
  714.       return data[aKey] || "";
  715.     }
  716.     else {
  717.       Components.returnCode = Cr.NS_ERROR_INVALID_ARG;
  718.     }
  719.   },
  720.  
  721.   setWindowValue: function sss_setWindowValue(aWindow, aKey, aStringValue) {
  722.     if (aWindow.__SSi) {
  723.       if (!this._windows[aWindow.__SSi].extData) {
  724.         this._windows[aWindow.__SSi].extData = {};
  725.       }
  726.       this._windows[aWindow.__SSi].extData[aKey] = aStringValue;
  727.       this.saveStateDelayed(aWindow);
  728.     }
  729.     else {
  730.       Components.returnCode = Cr.NS_ERROR_INVALID_ARG;
  731.     }
  732.   },
  733.  
  734.   deleteWindowValue: function sss_deleteWindowValue(aWindow, aKey) {
  735.     if (this._windows[aWindow.__SSi].extData[aKey])
  736.       delete this._windows[aWindow.__SSi].extData[aKey];
  737.     else
  738.       Components.returnCode = Cr.NS_ERROR_INVALID_ARG;
  739.   },
  740.  
  741.   getTabValue: function sss_getTabValue(aTab, aKey) {
  742.     var data = aTab.__SS_extdata || {};
  743.     return data[aKey] || "";
  744.   },
  745.  
  746.   setTabValue: function sss_setTabValue(aTab, aKey, aStringValue) {
  747.     if (!aTab.__SS_extdata) {
  748.       aTab.__SS_extdata = {};
  749.     }
  750.     aTab.__SS_extdata[aKey] = aStringValue;
  751.     this.saveStateDelayed(aTab.ownerDocument.defaultView);
  752.   },
  753.  
  754.   deleteTabValue: function sss_deleteTabValue(aTab, aKey) {
  755.     if (aTab.__SS_extdata[aKey])
  756.       delete aTab.__SS_extdata[aKey];
  757.     else
  758.       Components.returnCode = Cr.NS_ERROR_INVALID_ARG;
  759.   },
  760.  
  761.  
  762.   persistTabAttribute: function sss_persistTabAttribute(aName) {
  763.     this.xulAttributes.push(aName);
  764.     this.saveStateDelayed();
  765.   },
  766.  
  767. /* ........ Saving Functionality .............. */
  768.  
  769.   /**
  770.    * Store all session data for a window
  771.    * @param aWindow
  772.    *        Window reference
  773.    */
  774.   _saveWindowHistory: function sss_saveWindowHistory(aWindow) {
  775.     var tabbrowser = aWindow.getBrowser();
  776.     var browsers = tabbrowser.browsers;
  777.     var tabs = this._windows[aWindow.__SSi].tabs = [];
  778.     this._windows[aWindow.__SSi].selected = 0;
  779.     
  780.     for (var i = 0; i < browsers.length; i++) {
  781.       var tabData = { entries: [], index: 0 };
  782.       
  783.       var browser = browsers[i];
  784.       if (!browser || !browser.currentURI) {
  785.         // can happen when calling this function right after .addTab()
  786.         tabs.push(tabData);
  787.         continue;
  788.       }
  789.       var history = null;
  790.       
  791.       try {
  792.         history = browser.sessionHistory;
  793.       }
  794.       catch (ex) { } // this could happen if we catch a tab during (de)initialization
  795.       
  796.       if (history && browser.parentNode.__SS_data && browser.parentNode.__SS_data.entries[history.index]) {
  797.         tabData = browser.parentNode.__SS_data;
  798.         tabData.index = history.index + 1;
  799.       }
  800.       else if (history && history.count > 0) {
  801.         for (var j = 0; j < history.count; j++) {
  802.           tabData.entries.push(this._serializeHistoryEntry(history.getEntryAtIndex(j, false)));
  803.         }
  804.         tabData.index = history.index + 1;
  805.         
  806.         browser.parentNode.__SS_data = tabData;
  807.       }
  808.       else {
  809.         tabData.entries[0] = { url: browser.currentURI.spec };
  810.         tabData.index = 1;
  811.       }
  812.       tabData.zoom = browser.markupDocumentViewer.textZoom;
  813.       
  814.       var disallow = CAPABILITIES.filter(function(aCapability) {
  815.         return !browser.docShell["allow" + aCapability];
  816.       });
  817.       tabData.disallow = disallow.join(",");
  818.       
  819.       var _this = this;
  820.       var xulattr = Array.filter(tabbrowser.mTabs[i].attributes, function(aAttr) {
  821.         return (_this.xulAttributes.indexOf(aAttr.name) > -1);
  822.       }).map(function(aAttr) {
  823.         return aAttr.name + "=" + encodeURI(aAttr.value);
  824.       });
  825.       tabData.xultab = xulattr.join(" ");
  826.       
  827.       tabData.extData = tabbrowser.mTabs[i].__SS_extdata || null;
  828.       
  829.       tabs.push(tabData);
  830.       
  831.       if (browser == tabbrowser.selectedBrowser) {
  832.         this._windows[aWindow.__SSi].selected = i + 1;
  833.       }
  834.     }
  835.   },
  836.  
  837.   /**
  838.    * Get an object that is a serialized representation of a History entry
  839.    * Used for data storage
  840.    * @param aEntry
  841.    *        nsISHEntry instance
  842.    * @returns object
  843.    */
  844.   _serializeHistoryEntry: function sss_serializeHistoryEntry(aEntry) {
  845.     var entry = { url: aEntry.URI.spec, children: [] };
  846.     
  847.     if (aEntry.title && aEntry.title != entry.url) {
  848.       entry.title = aEntry.title;
  849.     }
  850.     if (aEntry.isSubFrame) {
  851.       entry.subframe = true;
  852.     }
  853.     if (!(aEntry instanceof Ci.nsISHEntry)) {
  854.       return entry;
  855.     }
  856.     
  857.     var cacheKey = aEntry.cacheKey;
  858.     if (cacheKey && cacheKey instanceof Ci.nsISupportsPRUint32) {
  859.       entry.cacheKey = cacheKey.data;
  860.     }
  861.     entry.ID = aEntry.ID;
  862.     
  863.     var x = {}, y = {};
  864.     aEntry.getScrollPosition(x, y);
  865.     entry.scroll = x.value + "," + y.value;
  866.     
  867.     try {
  868.       var prefPostdata = this._getPref("sessionstore.postdata", DEFAULT_POSTDATA);
  869.       if (prefPostdata && aEntry.postData && this._checkPrivacyLevel(aEntry.URI.schemeIs("https"))) {
  870.         aEntry.postData.QueryInterface(Ci.nsISeekableStream).
  871.                         seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
  872.         var stream = Cc["@mozilla.org/scriptableinputstream;1"].
  873.                      createInstance(Ci.nsIScriptableInputStream);
  874.         stream.init(aEntry.postData);
  875.         var postdata = stream.read(stream.available());
  876.         if (prefPostdata == -1 || postdata.replace(/^(Content-.*\r\n)+(\r\n)*/, "").length <= prefPostdata) {
  877.           entry.postdata = postdata;
  878.         }
  879.       }
  880.     }
  881.     catch (ex) { debug(ex); } // POSTDATA is tricky - especially since some extensions don't get it right
  882.     
  883.     if (!(aEntry instanceof Ci.nsISHContainer)) {
  884.       return entry;
  885.     }
  886.     
  887.     for (var i = 0; i < aEntry.childCount; i++) {
  888.       var child = aEntry.GetChildAt(i);
  889.       if (child) {
  890.         entry.children.push(this._serializeHistoryEntry(child));
  891.       }
  892.       else { // to maintain the correct frame order, insert a dummy entry 
  893.         entry.children.push({ url: "about:blank" });
  894.       }
  895.     }
  896.     
  897.     return entry;
  898.   },
  899.  
  900.   /**
  901.    * Updates the current document's cache of user entered text data
  902.    * @param aPanel
  903.    *        TabPanel reference
  904.    * @param aTextarea
  905.    *        HTML content element (without an XPCNativeWrapper applied)
  906.    * @returns bool
  907.    */
  908.   _saveTextData: function sss_saveTextData(aPanel, aTextarea) {
  909.     var wrappedTextarea = XPCNativeWrapper(aTextarea);
  910.     var id = wrappedTextarea.id ? "#" + wrappedTextarea.id :
  911.                                   wrappedTextarea.name;
  912.     if (!id
  913.       || !(wrappedTextarea instanceof Ci.nsIDOMHTMLTextAreaElement 
  914.       || wrappedTextarea instanceof Ci.nsIDOMHTMLInputElement)) {
  915.       return false; // nothing to save
  916.     }
  917.     
  918.     if (!aPanel.__SS_text) {
  919.       aPanel.__SS_text = [];
  920.       aPanel.__SS_text._refs = [];
  921.     }
  922.     
  923.     // get the index of the reference to the text element
  924.     var ix = aPanel.__SS_text._refs.indexOf(aTextarea);
  925.     if (ix == -1) {
  926.       // we haven't registered this text element yet - do so now
  927.       aPanel.__SS_text._refs.push(aTextarea);
  928.       ix = aPanel.__SS_text.length;
  929.     }
  930.     else if (!aPanel.__SS_text[ix].cache) {
  931.       // we've already marked this text element for saving (the cache is
  932.       // added during save operations and would have to be updated here)
  933.       return false;
  934.     }
  935.     
  936.     // determine the frame we're in and encode it into the textarea's ID
  937.     var content = wrappedTextarea.ownerDocument.defaultView;
  938.     while (content != content.top) {
  939.       var frames = content.parent.frames;
  940.       for (var i = 0; i < frames.length && frames[i] != content; i++);
  941.       id = i + "|" + id;
  942.       content = content.parent;
  943.     }
  944.     
  945.     // mark this element for saving
  946.     aPanel.__SS_text[ix] = { id: id, element: wrappedTextarea };
  947.     
  948.     return true;
  949.   },
  950.  
  951.   /**
  952.    * go through all frames and store the current scroll positions
  953.    * and innerHTML content of WYSIWYG editors
  954.    * @param aWindow
  955.    *        Window reference
  956.    */
  957.   _updateTextAndScrollData: function sss_updateTextAndScrollData(aWindow) {
  958.     var _this = this;
  959.     function updateRecursively(aContent, aData) {
  960.       for (var i = 0; i < aContent.frames.length; i++) {
  961.         if (aData.children && aData.children[i]) {
  962.           updateRecursively(aContent.frames[i], aData.children[i]);
  963.         }
  964.       }
  965.       // designMode is undefined e.g. for XUL documents (as about:config)
  966.       var isHTTPS = _this._getURIFromString((aContent.parent || aContent).
  967.                                         document.location.href).schemeIs("https");
  968.       if ((aContent.document.designMode || "") == "on" && _this._checkPrivacyLevel(isHTTPS)) {
  969.         if (aData.innerHTML == undefined) {
  970.           // we get no "input" events from iframes - listen for keypress here
  971.           aContent.addEventListener("keypress", function(aEvent) { _this.saveStateDelayed(aWindow, 3000); }, true);
  972.         }
  973.         aData.innerHTML = aContent.document.body.innerHTML;
  974.       }
  975.       aData.scroll = aContent.scrollX + "," + aContent.scrollY;
  976.     }
  977.     
  978.     Array.forEach(aWindow.getBrowser().browsers, function(aBrowser, aIx) {
  979.       try {
  980.         var tabData = this._windows[aWindow.__SSi].tabs[aIx];
  981.         if (tabData.entries.length == 0)
  982.           return; // ignore incompletely initialized tabs
  983.         
  984.         var text = [];
  985.         if (aBrowser.parentNode.__SS_text && this._checkPrivacyLevel(aBrowser.currentURI.schemeIs("https"))) {
  986.           for (var ix = aBrowser.parentNode.__SS_text.length - 1; ix >= 0; ix--) {
  987.             var data = aBrowser.parentNode.__SS_text[ix];
  988.             if (!data.cache) {
  989.               // update the text element's value before adding it to the data structure
  990.               data.cache = encodeURI(data.element.value);
  991.             }
  992.             text.push(data.id + "=" + data.cache);
  993.           }
  994.         }
  995.         if (aBrowser.currentURI.spec == "about:config") {
  996.           text = ["#textbox=" + encodeURI(aBrowser.contentDocument.getElementById("textbox").wrappedJSObject.value)];
  997.         }
  998.         tabData.text = text.join(" ");
  999.         
  1000.         updateRecursively(XPCNativeWrapper(aBrowser.contentWindow), tabData.entries[tabData.index - 1]);
  1001.       }
  1002.       catch (ex) { debug(ex); } // get as much data as possible, ignore failures (might succeed the next time)
  1003.     }, this);
  1004.   },
  1005.  
  1006.   /**
  1007.    * store all hosts for a URL
  1008.    * @param aWindow
  1009.    *        Window reference
  1010.    */
  1011.   _updateCookieHosts: function sss_updateCookieHosts(aWindow) {
  1012.     var hosts = this._windows[aWindow.__SSi]._hosts = {};
  1013.     
  1014.     // get all possible subdomain levels for a given URL
  1015.     var _this = this;
  1016.     function extractHosts(aEntry) {
  1017.       if (/^https?:\/\/(?:[^@\/\s]+@)?([\w.-]+)/.test(aEntry.url) &&
  1018.         !hosts[RegExp.$1] && _this._checkPrivacyLevel(_this._getURIFromString(aEntry.url).schemeIs("https"))) {
  1019.         var host = RegExp.$1;
  1020.         var ix;
  1021.         for (ix = host.indexOf(".") + 1; ix; ix = host.indexOf(".", ix) + 1) {
  1022.           hosts[host.substr(ix)] = true;
  1023.         }
  1024.         hosts[host] = true;
  1025.       }
  1026.       if (aEntry.children) {
  1027.         aEntry.children.forEach(extractHosts);
  1028.       }
  1029.     }
  1030.     
  1031.     this._windows[aWindow.__SSi].tabs.forEach(function(aTabData) { aTabData.entries.forEach(extractHosts); });
  1032.   },
  1033.  
  1034.   /**
  1035.    * Serialize cookie data
  1036.    * @param aWindows
  1037.    *        array of Window references
  1038.    */
  1039.   _updateCookies: function sss_updateCookies(aWindows) {
  1040.     var cookiesEnum = Cc["@mozilla.org/cookiemanager;1"].
  1041.                       getService(Ci.nsICookieManager).enumerator;
  1042.     // collect the cookies per window
  1043.     for (var i = 0; i < aWindows.length; i++) {
  1044.       aWindows[i].cookies = { count: 0 };
  1045.     }
  1046.     
  1047.     var _this = this;
  1048.     while (cookiesEnum.hasMoreElements()) {
  1049.       var cookie = cookiesEnum.getNext().QueryInterface(Ci.nsICookie2);
  1050.       if (cookie.isSession && cookie.host) {
  1051.         var url = "", value = "";
  1052.         aWindows.forEach(function(aWindow) {
  1053.           if (aWindow._hosts && aWindow._hosts[cookie.rawHost]) {
  1054.             // make sure to construct URL and value only once per cookie
  1055.             if (!url) {
  1056.               var url = "http" + (cookie.isSecure ? "s" : "") + "://" + cookie.host + (cookie.path || "").replace(/^(?!\/)/, "/");
  1057.               if (_this._checkPrivacyLevel(cookie.isSecure)) {
  1058.                 value = (cookie.name || "name") + "=" + (cookie.value || "") + ";";
  1059.                 value += cookie.isDomain ? "domain=" + cookie.rawHost + ";" : "";
  1060.                 value += cookie.path ? "path=" + cookie.path + ";" : "";
  1061.                 value += cookie.isSecure ? "secure;" : "";
  1062.               }
  1063.             }
  1064.             if (value) {
  1065.               // in order to not unnecessarily bloat the session file,
  1066.               // all window cookies are saved into one JS object
  1067.               var cookies = aWindow.cookies;
  1068.               cookies["domain" + ++cookies.count] = url;
  1069.               cookies["value" + cookies.count] = value;
  1070.             }
  1071.           }
  1072.         });
  1073.       }
  1074.     }
  1075.     
  1076.     // don't include empty cookie sections
  1077.     for (i = 0; i < aWindows.length; i++) {
  1078.       if (aWindows[i].cookies.count == 0) {
  1079.         delete aWindows[i].cookies;
  1080.       }
  1081.     }
  1082.   },
  1083.  
  1084.   /**
  1085.    * Store window dimensions, visibility, sidebar
  1086.    * @param aWindow
  1087.    *        Window reference
  1088.    */
  1089.   _updateWindowFeatures: function sss_updateWindowFeatures(aWindow) {
  1090.     var winData = this._windows[aWindow.__SSi];
  1091.     
  1092.     WINDOW_ATTRIBUTES.forEach(function(aAttr) {
  1093.       winData[aAttr] = this._getWindowDimension(aWindow, aAttr);
  1094.     }, this);
  1095.     
  1096.     winData.hidden = WINDOW_HIDEABLE_FEATURES.filter(function(aItem) {
  1097.       return aWindow[aItem] && !aWindow[aItem].visible;
  1098.     }).join(",");
  1099.     
  1100.     winData.sidebar = aWindow.document.getElementById("sidebar-box").getAttribute("sidebarcommand");
  1101.   },
  1102.  
  1103.   /**
  1104.    * serialize session data as Ini-formatted string
  1105.    * @returns string
  1106.    */
  1107.   _getCurrentState: function sss_getCurrentState() {
  1108.     var activeWindow = this._getMostRecentBrowserWindow();
  1109.     
  1110.     if (this._loadState == STATE_RUNNING) {
  1111.       // update the data for all windows with activities since the last save operation
  1112.       this._forEachBrowserWindow(function(aWindow) {
  1113.         if (this._dirty || this._dirtyWindows[aWindow.__SSi] || aWindow == activeWindow) {
  1114.           this._collectWindowData(aWindow);
  1115.         }
  1116.         else { // always update the window features (whose change alone never triggers a save operation)
  1117.           this._updateWindowFeatures(aWindow);
  1118.         }
  1119.       }, this);
  1120.       this._dirtyWindows = [];
  1121.       this._dirty = false;
  1122.     }
  1123.     
  1124.     // collect the data for all windows
  1125.     var total = [], windows = [];
  1126.     var ix;
  1127.     for (ix in this._windows) {
  1128.       total.push(this._windows[ix]);
  1129.       windows.push(ix);
  1130.     }
  1131.     this._updateCookies(total);
  1132.     
  1133.     // make sure that the current window is restored first
  1134.     var ix = activeWindow ? windows.indexOf(activeWindow.__SSi || "") : -1;
  1135.     if (ix > 0) {
  1136.       total.unshift(total.splice(ix, 1)[0]);
  1137.     }
  1138.  
  1139.     // if no browser window remains open, return the state of the last closed window
  1140.     if (total.length == 0 && this._lastWindowClosed) {
  1141.       total.push(this._lastWindowClosed);
  1142.     }
  1143.     
  1144.     return { windows: total };
  1145.   },
  1146.  
  1147.   /**
  1148.    * serialize session data for a window 
  1149.    * @param aWindow
  1150.    *        Window reference
  1151.    * @returns string
  1152.    */
  1153.   _getWindowState: function sss_getWindowState(aWindow) {
  1154.     if (this._loadState == STATE_RUNNING) {
  1155.       this._collectWindowData(aWindow);
  1156.     }
  1157.     
  1158.     var total = [this._windows[aWindow.__SSi]];
  1159.     this._updateCookies(total);
  1160.     
  1161.     return { windows: total };
  1162.   },
  1163.  
  1164.   _collectWindowData: function sss_collectWindowData(aWindow) {
  1165.     // update the internal state data for this window
  1166.     this._saveWindowHistory(aWindow);
  1167.     this._updateTextAndScrollData(aWindow);
  1168.     this._updateCookieHosts(aWindow);
  1169.     this._updateWindowFeatures(aWindow);
  1170.     
  1171.     this._dirtyWindows[aWindow.__SSi] = false;
  1172.   },
  1173.  
  1174. /* ........ Restoring Functionality .............. */
  1175.  
  1176.   /**
  1177.    * restore features to a single window
  1178.    * @param aWindow
  1179.    *        Window reference
  1180.    * @param aState
  1181.    *        JS object or its eval'able source
  1182.    * @param aOverwriteTabs
  1183.    *        bool overwrite existing tabs w/ new ones
  1184.    */
  1185.   restoreWindow: function sss_restoreWindow(aWindow, aState, aOverwriteTabs) {
  1186.     // initialize window if necessary
  1187.     if (aWindow && (!aWindow.__SSi || !this._windows[aWindow.__SSi]))
  1188.       this.onLoad(aWindow);
  1189.  
  1190.     try {
  1191.       var root = typeof aState == "string" ? this._safeEval(aState) : aState;
  1192.       if (!root.windows[0]) {
  1193.         return; // nothing to restore
  1194.       }
  1195.     }
  1196.     catch (ex) { // invalid state object - don't restore anything 
  1197.       debug(ex);
  1198.       return;
  1199.     }
  1200.     
  1201.     var winData;
  1202.     // open new windows for all further window entries of a multi-window session
  1203.     // (unless they don't contain any tab data)
  1204.     for (var w = 1; w < root.windows.length; w++) {
  1205.       winData = root.windows[w];
  1206.       if (winData && winData.tabs && winData.tabs[0]) {
  1207.         this._openWindowWithState({ windows: [winData], opener: aWindow });
  1208.       }
  1209.     }
  1210.     
  1211.     winData = root.windows[0];
  1212.     if (!winData.tabs) {
  1213.       winData.tabs = [];
  1214.     }
  1215.     
  1216.     var tabbrowser = aWindow.getBrowser();
  1217.     var openTabCount = aOverwriteTabs ? tabbrowser.browsers.length : -1;
  1218.     var newTabCount = winData.tabs.length;
  1219.     
  1220.     for (var t = 0; t < newTabCount; t++) {
  1221.       winData.tabs[t]._tab = t < openTabCount ? tabbrowser.mTabs[t] : tabbrowser.addTab();
  1222.       // when resuming at startup: add additionally requested pages to the end
  1223.       if (!aOverwriteTabs && root._firstTabs) {
  1224.         tabbrowser.moveTabTo(winData.tabs[t]._tab, t);
  1225.       }
  1226.     }
  1227.  
  1228.     // when overwriting tabs, remove all superflous ones
  1229.     for (t = openTabCount - 1; t >= newTabCount; t--) {
  1230.       tabbrowser.removeTab(tabbrowser.mTabs[t]);
  1231.     }
  1232.     
  1233.     if (aOverwriteTabs) {
  1234.       this.restoreWindowFeatures(aWindow, winData, root.opener || null);
  1235.     }
  1236.     if (winData.cookies) {
  1237.       this.restoreCookies(winData.cookies);
  1238.     }
  1239.     if (winData.extData) {
  1240.       if (!this._windows[aWindow.__SSi].extData) {
  1241.         this._windows[aWindow.__SSi].extData = {}
  1242.       }
  1243.       for (var key in winData.extData) {
  1244.         this._windows[aWindow.__SSi].extData[key] = winData.extData[key];
  1245.       }
  1246.     }
  1247.     if (winData._closedTabs && (root._firstTabs || aOverwriteTabs)) {
  1248.       //XXXzeniko remove the slice call as soon as _closedTabs instanceof Array
  1249.       this._windows[aWindow.__SSi]._closedTabs = winData._closedTabs.slice();
  1250.     }
  1251.     
  1252.     this.restoreHistoryPrecursor(aWindow, winData.tabs, (aOverwriteTabs ?
  1253.       (parseInt(winData.selected) || 1) : 0), 0, 0);
  1254.   },
  1255.  
  1256.   /**
  1257.    * Manage history restoration for a window
  1258.    * @param aTabs
  1259.    *        Array of tab data
  1260.    * @param aCurrentTabs
  1261.    *        Array of tab references
  1262.    * @param aSelectTab
  1263.    *        Index of selected tab
  1264.    * @param aCount
  1265.    *        Counter for number of times delaying b/c browser or history aren't ready
  1266.    */
  1267.   restoreHistoryPrecursor: function sss_restoreHistoryPrecursor(aWindow, aTabs, aSelectTab, aIx, aCount) {
  1268.     var tabbrowser = aWindow.getBrowser();
  1269.     
  1270.     // make sure that all browsers and their histories are available
  1271.     // - if one's not, resume this check in 100ms (repeat at most 10 times)
  1272.     for (var t = aIx; t < aTabs.length; t++) {
  1273.       try {
  1274.         if (!tabbrowser.getBrowserForTab(aTabs[t]._tab).webNavigation.sessionHistory) {
  1275.           throw new Error();
  1276.         }
  1277.       }
  1278.       catch (ex) { // in case browser or history aren't ready yet 
  1279.         if (aCount < 10) {
  1280.           var restoreHistoryFunc = function(self) {
  1281.             self.restoreHistoryPrecursor(aWindow, aTabs, aSelectTab, aIx, aCount + 1);
  1282.           }
  1283.           aWindow.setTimeout(restoreHistoryFunc, 100, this);
  1284.           return;
  1285.         }
  1286.       }
  1287.     }
  1288.     
  1289.     // mark the tabs as loading (at this point about:blank
  1290.     // has completed loading in all tabs, so it won't interfere)
  1291.     for (t = 0; t < aTabs.length; t++) {
  1292.       var tab = aTabs[t]._tab;
  1293.       tab.setAttribute("busy", "true");
  1294.       tabbrowser.updateIcon(tab);
  1295.       tabbrowser.setTabTitleLoading(tab);
  1296.     }
  1297.     
  1298.     // make sure to restore the selected tab first (if any)
  1299.     if (aSelectTab-- && aTabs[aSelectTab]) {
  1300.         aTabs.unshift(aTabs.splice(aSelectTab, 1)[0]);
  1301.         tabbrowser.selectedTab = aTabs[0]._tab;
  1302.     }
  1303.     
  1304.     this.restoreHistory(aWindow, aTabs);
  1305.   },
  1306.  
  1307.   /**
  1308.    * Restory history for a window
  1309.    * @param aWindow
  1310.    *        Window reference
  1311.    * @param aTabs
  1312.    *        Array of tab data
  1313.    * @param aCurrentTabs
  1314.    *        Array of tab references
  1315.    * @param aSelectTab
  1316.    *        Index of selected tab
  1317.    */
  1318.   restoreHistory: function sss_restoreHistory(aWindow, aTabs, aIdMap) {
  1319.     var _this = this;
  1320.     while (aTabs.length > 0 && (!aTabs[0]._tab || !aTabs[0]._tab.parentNode)) {
  1321.       aTabs.shift(); // this tab got removed before being completely restored
  1322.     }
  1323.     if (aTabs.length == 0) {
  1324.       return; // no more tabs to restore
  1325.     }
  1326.     
  1327.     var tabData = aTabs.shift();
  1328.  
  1329.     // helper hash for ensuring unique frame IDs
  1330.     var idMap = { used: {} };
  1331.     
  1332.     var tab = tabData._tab;
  1333.     var browser = aWindow.getBrowser().getBrowserForTab(tab);
  1334.     var history = browser.webNavigation.sessionHistory;
  1335.     
  1336.     if (history.count > 0) {
  1337.       history.PurgeHistory(history.count);
  1338.     }
  1339.     history.QueryInterface(Ci.nsISHistoryInternal);
  1340.     
  1341.     if (!tabData.entries) {
  1342.       tabData.entries = [];
  1343.     }
  1344.     if (tabData.extData) {
  1345.       tab.__SS_extdata = tabData.extData;
  1346.     }
  1347.     
  1348.     browser.markupDocumentViewer.textZoom = parseFloat(tabData.zoom || 1);
  1349.     
  1350.     for (var i = 0; i < tabData.entries.length; i++) {
  1351.       history.addEntry(this._deserializeHistoryEntry(tabData.entries[i], idMap), true);
  1352.     }
  1353.     
  1354.     // make sure to reset the capabilities and attributes, in case this tab gets reused
  1355.     var disallow = (tabData.disallow)?tabData.disallow.split(","):[];
  1356.     CAPABILITIES.forEach(function(aCapability) {
  1357.       browser.docShell["allow" + aCapability] = disallow.indexOf(aCapability) == -1;
  1358.     });
  1359.     Array.filter(tab.attributes, function(aAttr) {
  1360.       return (_this.xulAttributes.indexOf(aAttr.name) > -1);
  1361.     }).forEach(tab.removeAttribute, tab);
  1362.     if (tabData.xultab) {
  1363.       tabData.xultab.split(" ").forEach(function(aAttr) {
  1364.         if (/^([^\s=]+)=(.*)/.test(aAttr)) {
  1365.           tab.setAttribute(RegExp.$1, decodeURI(RegExp.$2));
  1366.         }
  1367.       });
  1368.     }
  1369.     
  1370.     // notify the tabbrowser that the tab chrome has been restored
  1371.     var event = aWindow.document.createEvent("Events");
  1372.     event.initEvent("SSTabRestoring", true, false);
  1373.     tab.dispatchEvent(event);
  1374.     
  1375.     var activeIndex = (tabData.index || tabData.entries.length) - 1;
  1376.     try {
  1377.       browser.webNavigation.gotoIndex(activeIndex);
  1378.     }
  1379.     catch (ex) { } // ignore an invalid tabData.index
  1380.     
  1381.     // restore those aspects of the currently active documents
  1382.     // which are not preserved in the plain history entries
  1383.     // (mainly scroll state and text data)
  1384.     browser.__SS_restore_data = tabData.entries[activeIndex] || {};
  1385.     browser.__SS_restore_text = tabData.text || "";
  1386.     browser.__SS_restore_tab = tab;
  1387.     browser.__SS_restore = this.restoreDocument_proxy;
  1388.     browser.addEventListener("load", browser.__SS_restore, true);
  1389.     
  1390.     aWindow.setTimeout(function(){ _this.restoreHistory(aWindow, aTabs, aIdMap); }, 0);
  1391.   },
  1392.  
  1393.   /**
  1394.    * expands serialized history data into a session-history-entry instance
  1395.    * @param aEntry
  1396.    *        Object containing serialized history data for a URL
  1397.    * @param aIdMap
  1398.    *        Hash for ensuring unique frame IDs
  1399.    * @returns nsISHEntry
  1400.    */
  1401.   _deserializeHistoryEntry: function sss_deserializeHistoryEntry(aEntry, aIdMap) {
  1402.     var shEntry = Cc["@mozilla.org/browser/session-history-entry;1"].
  1403.                   createInstance(Ci.nsISHEntry);
  1404.     
  1405.     var ioService = Cc["@mozilla.org/network/io-service;1"].
  1406.                     getService(Ci.nsIIOService);
  1407.     shEntry.setURI(ioService.newURI(aEntry.url, null, null));
  1408.     shEntry.setTitle(aEntry.title || aEntry.url);
  1409.     shEntry.setIsSubFrame(aEntry.subframe || false);
  1410.     shEntry.loadType = Ci.nsIDocShellLoadInfo.loadHistory;
  1411.     
  1412.     if (aEntry.cacheKey) {
  1413.       var cacheKey = Cc["@mozilla.org/supports-PRUint32;1"].
  1414.                      createInstance(Ci.nsISupportsPRUint32);
  1415.       cacheKey.data = aEntry.cacheKey;
  1416.       shEntry.cacheKey = cacheKey;
  1417.     }
  1418.     if (aEntry.ID) {
  1419.       // get a new unique ID for this frame (since the one from the last
  1420.       // start might already be in use)
  1421.       var id = aIdMap[aEntry.ID] || 0;
  1422.       if (!id) {
  1423.         for (id = Date.now(); aIdMap.used[id]; id++);
  1424.         aIdMap[aEntry.ID] = id;
  1425.         aIdMap.used[id] = true;
  1426.       }
  1427.       shEntry.ID = id;
  1428.     }
  1429.     
  1430.     var scrollPos = (aEntry.scroll || "0,0").split(",");
  1431.     scrollPos = [parseInt(scrollPos[0]) || 0, parseInt(scrollPos[1]) || 0];
  1432.     shEntry.setScrollPosition(scrollPos[0], scrollPos[1]);
  1433.     
  1434.     if (aEntry.postdata) {
  1435.       var stream = Cc["@mozilla.org/io/string-input-stream;1"].
  1436.                    createInstance(Ci.nsIStringInputStream);
  1437.       stream.setData(aEntry.postdata, -1);
  1438.       shEntry.postData = stream;
  1439.     }
  1440.     
  1441.     if (aEntry.children && shEntry instanceof Ci.nsISHContainer) {
  1442.       for (var i = 0; i < aEntry.children.length; i++) {
  1443.         shEntry.AddChild(this._deserializeHistoryEntry(aEntry.children[i], aIdMap), i);
  1444.       }
  1445.     }
  1446.     
  1447.     return shEntry;
  1448.   },
  1449.  
  1450.   /**
  1451.    * Restore properties to a loaded document
  1452.    */
  1453.   restoreDocument_proxy: function sss_restoreDocument_proxy(aEvent) {
  1454.     // wait for the top frame to be loaded completely
  1455.     if (!aEvent || !aEvent.originalTarget || !aEvent.originalTarget.defaultView || aEvent.originalTarget.defaultView != aEvent.originalTarget.defaultView.top) {
  1456.       return;
  1457.     }
  1458.     
  1459.     var textArray = this.__SS_restore_text ? this.__SS_restore_text.split(" ") : [];
  1460.     function restoreTextData(aContent, aPrefix) {
  1461.       textArray.forEach(function(aEntry) {
  1462.         if (/^((?:\d+\|)*)(#?)([^\s=]+)=(.*)$/.test(aEntry) && (!RegExp.$1 || RegExp.$1 == aPrefix)) {
  1463.           var document = aContent.document;
  1464.           var node = RegExp.$2 ? document.getElementById(RegExp.$3) : document.getElementsByName(RegExp.$3)[0] || null;
  1465.           if (node && "value" in node) {
  1466.             node.value = decodeURI(RegExp.$4);
  1467.             
  1468.             var event = document.createEvent("UIEvents");
  1469.             event.initUIEvent("input", true, true, aContent, 0);
  1470.             node.dispatchEvent(event);
  1471.           }
  1472.         }
  1473.       });
  1474.     }
  1475.     
  1476.     function restoreTextDataAndScrolling(aContent, aData, aPrefix) {
  1477.       restoreTextData(aContent, aPrefix);
  1478.       if (aData.innerHTML) {
  1479.         aContent.setTimeout(function(aHTML) { if (this.document.designMode == "on") { this.document.body.innerHTML = aHTML; } }, 0, aData.innerHTML);
  1480.       }
  1481.       if (aData.scroll && /(\d+),(\d+)/.test(aData.scroll)) {
  1482.         aContent.scrollTo(RegExp.$1, RegExp.$2);
  1483.       }
  1484.       for (var i = 0; i < aContent.frames.length; i++) {
  1485.         if (aData.children && aData.children[i]) {
  1486.           restoreTextDataAndScrolling(aContent.frames[i], aData.children[i], i + "|" + aPrefix);
  1487.         }
  1488.       }
  1489.     }
  1490.     
  1491.     var content = XPCNativeWrapper(aEvent.originalTarget).defaultView;
  1492.     if (this.currentURI.spec == "about:config") {
  1493.       // unwrap the document for about:config because otherwise the properties
  1494.       // of the XBL bindings - as the textbox - aren't accessible (see bug 350718)
  1495.       content = content.wrappedJSObject;
  1496.     }
  1497.     restoreTextDataAndScrolling(content, this.__SS_restore_data, "");
  1498.     
  1499.     // notify the tabbrowser that this document has been completely restored
  1500.     var event = this.ownerDocument.createEvent("Events");
  1501.     event.initEvent("SSTabRestored", true, false);
  1502.     this.__SS_restore_tab.dispatchEvent(event);
  1503.     
  1504.     this.removeEventListener("load", this.__SS_restore, true);
  1505.     delete this.__SS_restore_data;
  1506.     delete this.__SS_restore_text;
  1507.     delete this.__SS_restore_tab;
  1508.     delete this.__SS_restore;
  1509.   },
  1510.  
  1511.   /**
  1512.    * Restore visibility and dimension features to a window
  1513.    * @param aWindow
  1514.    *        Window reference
  1515.    * @param aWinData
  1516.    *        Object containing session data for the window
  1517.    * @param aOpener
  1518.    *        Opening window, for refocusing
  1519.    */
  1520.   restoreWindowFeatures: function sss_restoreWindowFeatures(aWindow, aWinData, aOpener) {
  1521.     var hidden = (aWinData.hidden)?aWinData.hidden.split(","):[];
  1522.     WINDOW_HIDEABLE_FEATURES.forEach(function(aItem) {
  1523.       aWindow[aItem].visible = hidden.indexOf(aItem) == -1;
  1524.     });
  1525.     
  1526.     var _this = this;
  1527.     aWindow.setTimeout(function() {
  1528.       _this.restoreDimensions_proxy.apply(_this, [aWindow, aOpener, aWinData.width || 0, 
  1529.         aWinData.height || 0, "screenX" in aWinData ? aWinData.screenX : NaN,
  1530.         "screenY" in aWinData ? aWinData.screenY : NaN,
  1531.         aWinData.sizemode || "", aWinData.sidebar || ""]);
  1532.     }, 0);
  1533.   },
  1534.  
  1535.   /**
  1536.    * Restore a window's dimensions
  1537.    * @param aOpener
  1538.    *        Opening window, for refocusing
  1539.    * @param aWidth
  1540.    *        Window width
  1541.    * @param aHeight
  1542.    *        Window height
  1543.    * @param aLeft
  1544.    *        Window left
  1545.    * @param aTop
  1546.    *        Window top
  1547.    * @param aSizeMode
  1548.    *        Window size mode (eg: maximized)
  1549.    * @param aSidebar
  1550.    *        Sidebar command
  1551.    */
  1552.   restoreDimensions_proxy: function sss_restoreDimensions_proxy(aWindow, aOpener, aWidth, aHeight, aLeft, aTop, aSizeMode, aSidebar) {
  1553.     var win = aWindow;
  1554.     var _this = this;
  1555.     function win_(aName) { return _this._getWindowDimension(win, aName); }
  1556.     
  1557.     // only modify those aspects which aren't correct yet
  1558.     if (aWidth && aHeight && (aWidth != win_("width") || aHeight != win_("height"))) {
  1559.       aWindow.resizeTo(aWidth, aHeight);
  1560.     }
  1561.     if (!isNaN(aLeft) && !isNaN(aTop) && (aLeft != win_("screenX") || aTop != win_("screenY"))) {
  1562.       aWindow.moveTo(aLeft, aTop);
  1563.     }
  1564.     if (aSizeMode == "maximized" && win_("sizemode") != "maximized") {
  1565.       aWindow.maximize();
  1566.     }
  1567.     else if (aSizeMode && aSizeMode != "maximized" && win_("sizemode") != "normal") {
  1568.       aWindow.restore();
  1569.     }
  1570.     var sidebar = aWindow.document.getElementById("sidebar-box");
  1571.     if (sidebar.getAttribute("sidebarcommand") != aSidebar) {
  1572.       aWindow.toggleSidebar(aSidebar);
  1573.     }
  1574.     // since resizing/moving a window brings it to the foreground,
  1575.     // we might want to re-focus the window which created this one
  1576.     if (aOpener) {
  1577.       aOpener.focus();
  1578.     }
  1579.   },
  1580.  
  1581.   /**
  1582.    * Restores cookies to cookie service
  1583.    * @param aCookies
  1584.    *        Array of cookie data
  1585.    */
  1586.   restoreCookies: function sss_restoreCookies(aCookies) {
  1587.     var cookieService = Cc["@mozilla.org/cookieService;1"].
  1588.                         getService(Ci.nsICookieService);
  1589.     var ioService = Cc["@mozilla.org/network/io-service;1"].
  1590.                     getService(Ci.nsIIOService);
  1591.     
  1592.     for (var i = 1; i <= aCookies.count; i++) {
  1593.       try {
  1594.         cookieService.setCookieString(ioService.newURI(aCookies["domain" + i], null, null), null, aCookies["value" + i] + "expires=0;", null);
  1595.       }
  1596.       catch (ex) { debug(ex); } // don't let a single cookie stop recovering (might happen if a user tried to edit the session file)
  1597.     }
  1598.   },
  1599.  
  1600.   /**
  1601.    * Restart incomplete downloads
  1602.    * @param aWindow
  1603.    *        Window reference
  1604.    */
  1605.   retryDownloads: function sss_retryDownloads(aWindow) {
  1606.     var downloadManager = Cc["@mozilla.org/download-manager;1"].
  1607.                           getService(Ci.nsIDownloadManager);
  1608.     var rdfService = Cc["@mozilla.org/rdf/rdf-service;1"].
  1609.                      getService(Ci.nsIRDFService);
  1610.     var ioService = Cc["@mozilla.org/network/io-service;1"].
  1611.                     getService(Ci.nsIIOService);
  1612.     
  1613.     var rdfContainer = Cc["@mozilla.org/rdf/container;1"].
  1614.                        createInstance(Ci.nsIRDFContainer);
  1615.     var datasource = downloadManager.datasource;
  1616.     
  1617.     try {
  1618.       rdfContainer.Init(datasource, rdfService.GetResource("NC:DownloadsRoot"));
  1619.     }
  1620.     catch (ex) { // missing downloads datasource
  1621.       return;
  1622.     }
  1623.     
  1624.     // iterate through all downloads currently available in the RDF store
  1625.     // and restart the ones which were in progress before the crash
  1626.     var downloads = rdfContainer.GetElements();
  1627.     while (downloads.hasMoreElements()) {
  1628.       var download = downloads.getNext().QueryInterface(Ci.nsIRDFResource);
  1629.  
  1630.       // restart only if the download's in progress
  1631.       var node = datasource.GetTarget(download, rdfService.GetResource("http://home.netscape.com/NC-rdf#DownloadState"), true);
  1632.       if (node) {
  1633.         node.QueryInterface(Ci.nsIRDFInt);
  1634.       }
  1635.       if (!node || node.Value != Ci.nsIDownloadManager.DOWNLOAD_DOWNLOADING) {
  1636.         continue;
  1637.       }
  1638.  
  1639.       // URL being downloaded
  1640.       node = datasource.GetTarget(download, rdfService.GetResource("http://home.netscape.com/NC-rdf#URL"), true);
  1641.       var url = node.QueryInterface(Ci.nsIRDFResource).Value;
  1642.       
  1643.       // location where download's being saved
  1644.       node = datasource.GetTarget(download, rdfService.GetResource("http://home.netscape.com/NC-rdf#File"), true);
  1645.  
  1646.       // nsIRDFResource.Value is a string that's a URI; the downloads.rdf from
  1647.       // which this was created will have a string in one of the following two
  1648.       // forms, depending on platform:
  1649.       //
  1650.       //    /home/lumpy/dogtreat.txt
  1651.       //    C:\lumpy\dogtreat.txt
  1652.       //
  1653.       // During RDF loading, the string *appears* to be converted to a URL if
  1654.       // necessary.  Strings in the first form are not URLs and are converted to
  1655.       // file: URLs; strings in the latter form seem to be treated as if they
  1656.       // already are URLs and thus are not modified.  Consequently, on platforms
  1657.       // where paths aren't URLs, we need to extract the path from the file:
  1658.       // URL.
  1659.       //
  1660.       // See also bug 335725, bug 239948, and bug 349971.
  1661.       var savedTo = node.QueryInterface(Ci.nsIRDFResource).Value;
  1662.       try {
  1663.         var savedToURI = Cc["@mozilla.org/network/io-service;1"].
  1664.                          getService(Ci.nsIIOService).
  1665.                          newURI(savedTo, null, null);
  1666.         if (savedToURI.schemeIs("file"))
  1667.           savedTo = savedToURI.path;
  1668.       }
  1669.       catch (e) { /* not a URI, assume it was a string of form #1 */ }
  1670.  
  1671.       var linkChecker = Cc["@mozilla.org/network/urichecker;1"].
  1672.                         createInstance(Ci.nsIURIChecker);
  1673.       linkChecker.init(ioService.newURI(url, null, null));
  1674.       linkChecker.loadFlags = Ci.nsIRequest.LOAD_BACKGROUND;
  1675.       linkChecker.asyncCheck(new AutoDownloader(url, savedTo, aWindow), null);
  1676.     }
  1677.   },
  1678.  
  1679. /* ........ Disk Access .............. */
  1680.  
  1681.   /**
  1682.    * save state delayed by N ms
  1683.    * marks window as dirty (i.e. data update can't be skipped)
  1684.    * @param aWindow
  1685.    *        Window reference
  1686.    * @param aDelay
  1687.    *        Milliseconds to delay
  1688.    */
  1689.   saveStateDelayed: function sss_saveStateDelayed(aWindow, aDelay) {
  1690.     if (aWindow) {
  1691.       this._dirtyWindows[aWindow.__SSi] = true;
  1692.     }
  1693.  
  1694.     if (!this._saveTimer && this._resume_from_crash) {
  1695.       // interval until the next disk operation is allowed
  1696.       var minimalDelay = this._lastSaveTime + this._interval - Date.now();
  1697.       
  1698.       // if we have to wait, set a timer, otherwise saveState directly
  1699.       aDelay = Math.max(minimalDelay, aDelay || 2000);
  1700.       if (aDelay > 0) {
  1701.         this._saveTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  1702.         this._saveTimer.init(this, aDelay, Ci.nsITimer.TYPE_ONE_SHOT);
  1703.       }
  1704.       else {
  1705.         this.saveState();
  1706.       }
  1707.     }
  1708.   },
  1709.  
  1710.   /**
  1711.    * save state to disk
  1712.    * @param aUpdateAll
  1713.    *        Bool update all windows 
  1714.    */
  1715.   saveState: function sss_saveState(aUpdateAll) {
  1716.     // if crash recovery is disabled, only save session resuming information
  1717.     if (!this._resume_from_crash && this._loadState == STATE_RUNNING)
  1718.       return;
  1719.     
  1720.     this._dirty = aUpdateAll;
  1721.     var oState = this._getCurrentState();
  1722.     oState.session = { state: ((this._loadState == STATE_RUNNING) ? STATE_RUNNING_STR : STATE_STOPPED_STR) };
  1723.     this._writeFile(this._sessionFile, oState.toSource());
  1724.     this._lastSaveTime = Date.now();
  1725.   },
  1726.  
  1727.   /**
  1728.    * delete session datafile and backup
  1729.    */
  1730.   _clearDisk: function sss_clearDisk() {
  1731.     if (this._sessionFile.exists()) {
  1732.       try {
  1733.         this._sessionFile.remove(false);
  1734.       }
  1735.       catch (ex) { dump(ex + '\n'); } // couldn't remove the file - what now?
  1736.     }
  1737.     if (this._sessionFileBackup.exists()) {
  1738.       try {
  1739.         this._sessionFileBackup.remove(false);
  1740.       }
  1741.       catch (ex) { dump(ex + '\n'); } // couldn't remove the file - what now?
  1742.     }
  1743.   },
  1744.  
  1745. /* ........ Auxiliary Functions .............. */
  1746.  
  1747.   /**
  1748.    * call a callback for all currently opened browser windows
  1749.    * (might miss the most recent one)
  1750.    * @param aFunc
  1751.    *        Callback each window is passed to
  1752.    */
  1753.   _forEachBrowserWindow: function sss_forEachBrowserWindow(aFunc) {
  1754.     var windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"].
  1755.                          getService(Ci.nsIWindowMediator);
  1756.     var windowsEnum = windowMediator.getEnumerator("navigator:browser");
  1757.     
  1758.     while (windowsEnum.hasMoreElements()) {
  1759.       var window = windowsEnum.getNext();
  1760.       if (window.__SSi) {
  1761.         aFunc.call(this, window);
  1762.       }
  1763.     }
  1764.   },
  1765.  
  1766.   /**
  1767.    * Returns most recent window
  1768.    * @returns Window reference
  1769.    */
  1770.   _getMostRecentBrowserWindow: function sss_getMostRecentBrowserWindow() {
  1771.     var windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"].
  1772.                          getService(Ci.nsIWindowMediator);
  1773.     return windowMediator.getMostRecentWindow("navigator:browser");
  1774.   },
  1775.  
  1776.   /**
  1777.    * open a new browser window for a given session state
  1778.    * called when restoring a multi-window session
  1779.    * @param aState
  1780.    *        Object containing session data
  1781.    */
  1782.   _openWindowWithState: function sss_openWindowWithState(aState) {
  1783.     
  1784.     var argString = Cc["@mozilla.org/supports-string;1"].
  1785.                     createInstance(Ci.nsISupportsString);
  1786.     argString.data = "";
  1787.  
  1788.     //XXXzeniko shouldn't it be possible to set the window's dimensions here (as feature)?
  1789.     var window = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  1790.                  getService(Ci.nsIWindowWatcher).
  1791.                  openWindow(null, this._getPref("chromeURL", null), "_blank", "chrome,dialog=no,all", argString);
  1792.     
  1793.     window.__SS_state = aState;
  1794.     var _this = this;
  1795.     window.addEventListener("load", function(aEvent) {
  1796.       aEvent.currentTarget.removeEventListener("load", arguments.callee, true);
  1797.       _this.restoreWindow(aEvent.currentTarget, aEvent.currentTarget.__SS_state, true, true);
  1798.       delete aEvent.currentTarget.__SS_state;
  1799.     }, true);
  1800.   },
  1801.  
  1802.   /**
  1803.    * Whether or not to resume session, if not recovering from a crash.
  1804.    * @returns bool
  1805.    */
  1806.   _doResumeSession: function sss_doResumeSession() {
  1807.     return this._getPref("startup.page", 1) == 3 ||
  1808.       this._getPref("sessionstore.resume_session_once", DEFAULT_RESUME_SESSION_ONCE);
  1809.   },
  1810.  
  1811.   /**
  1812.    * whether the user wants to load any other page at startup
  1813.    * (except the homepage) - needed for determining whether to overwrite the current tabs
  1814.    * @returns bool
  1815.    */
  1816.   _isCmdLineEmpty: function sss_isCmdLineEmpty(aWindow) {
  1817.     var defaultArgs = Cc["@mozilla.org/browser/clh;1"].
  1818.                       getService(Ci.nsIBrowserHandler).defaultArgs;
  1819.     if (aWindow.arguments && aWindow.arguments[0] &&
  1820.         aWindow.arguments[0] == defaultArgs)
  1821.       aWindow.arguments[0] = null;
  1822.  
  1823.     return !aWindow.arguments || !aWindow.arguments[0];
  1824.   },
  1825.  
  1826.   /**
  1827.    * don't save sensitive data if the user doesn't want to
  1828.    * (distinguishes between encrypted and non-encrypted sites)
  1829.    * @param aIsHTTPS
  1830.    *        Bool is encrypted
  1831.    * @returns bool
  1832.    */
  1833.   _checkPrivacyLevel: function sss_checkPrivacyLevel(aIsHTTPS) {
  1834.     return this._getPref("sessionstore.privacy_level", DEFAULT_PRIVACY_LEVEL) < (aIsHTTPS ? PRIVACY_ENCRYPTED : PRIVACY_FULL);
  1835.   },
  1836.  
  1837.   /**
  1838.    * on popup windows, the XULWindow's attributes seem not to be set correctly
  1839.    * we use thus JSDOMWindow attributes for sizemode and normal window attributes
  1840.    * (and hope for reasonable values when maximized/minimized - since then
  1841.    * outerWidth/outerHeight aren't the dimensions of the restored window)
  1842.    * @param aWindow
  1843.    *        Window reference
  1844.    * @param aAttribute
  1845.    *        String sizemode | width | height | other window attribute
  1846.    * @returns string
  1847.    */
  1848.   _getWindowDimension: function sss_getWindowDimension(aWindow, aAttribute) {
  1849.     if (aAttribute == "sizemode") {
  1850.       switch (aWindow.windowState) {
  1851.       case aWindow.STATE_MAXIMIZED:
  1852.         return "maximized";
  1853.       case aWindow.STATE_MINIMIZED:
  1854.         return "minimized";
  1855.       default:
  1856.         return "normal";
  1857.       }
  1858.     }
  1859.     
  1860.     var dimension;
  1861.     switch (aAttribute) {
  1862.     case "width":
  1863.       dimension = aWindow.outerWidth;
  1864.       break;
  1865.     case "height":
  1866.       dimension = aWindow.outerHeight;
  1867.       break;
  1868.     default:
  1869.       dimension = aAttribute in aWindow ? aWindow[aAttribute] : "";
  1870.       break;
  1871.     }
  1872.     
  1873.     if (aWindow.windowState == aWindow.STATE_NORMAL) {
  1874.       return dimension;
  1875.     }
  1876.     return aWindow.document.documentElement.getAttribute(aAttribute) || dimension;
  1877.   },
  1878.  
  1879.   /**
  1880.    * Convenience method to get localized string bundles
  1881.    * @param aURI
  1882.    * @returns nsIStringBundle
  1883.    */
  1884.   _getStringBundle: function sss_getStringBundle(aURI) {
  1885.      var bundleService = Cc["@mozilla.org/intl/stringbundle;1"].
  1886.                          getService(Ci.nsIStringBundleService);
  1887.      var appLocale = Cc["@mozilla.org/intl/nslocaleservice;1"].
  1888.                      getService(Ci.nsILocaleService).getApplicationLocale();
  1889.      return bundleService.createBundle(aURI, appLocale);
  1890.   },
  1891.  
  1892.   /**
  1893.    * Get nsIURI from string
  1894.    * @param string
  1895.    * @returns nsIURI
  1896.    */
  1897.    _getURIFromString: function sss_getURIFromString(aString) {
  1898.      var ioService = Cc["@mozilla.org/network/io-service;1"].
  1899.                      getService(Ci.nsIIOService);
  1900.      return ioService.newURI(aString, null, null);
  1901.    },
  1902.  
  1903.   /**
  1904.    * safe eval'ing
  1905.    */
  1906.   _safeEval: function sss_safeEval(aStr) {
  1907.     var s = new Components.utils.Sandbox("about:blank");
  1908.     return Components.utils.evalInSandbox(aStr, s);
  1909.   },
  1910.  
  1911.   /**
  1912.    * Converts a JavaScript object into a JSON string
  1913.    * (see http://www.json.org/ for the full grammar).
  1914.    *
  1915.    * The inverse operation consists of eval("(" + JSON_string + ")");
  1916.    * and should be provably safe.
  1917.    *
  1918.    * @param aJSObject is the object to be converted
  1919.    * @return the object's JSON representation
  1920.    */
  1921.   _toJSONString: function sss_toJSONString(aJSObject) {
  1922.     // these characters have a special escape notation
  1923.     const charMap = { "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f",
  1924.                       "\r": "\\r", '"': '\\"', "\\": "\\\\" };
  1925.     // we use a single string builder for efficiency reasons
  1926.     var parts = [];
  1927.     
  1928.     // this recursive function walks through all objects and appends their
  1929.     // JSON representation to the string builder
  1930.     function jsonIfy(aObj) {
  1931.       if (typeof aObj == "boolean") {
  1932.         parts.push(aObj ? "true" : "false");
  1933.       }
  1934.       else if (typeof aObj == "number" && isFinite(aObj)) {
  1935.         // there is no representation for infinite numbers or for NaN!
  1936.         parts.push(aObj.toString());
  1937.       }
  1938.       else if (typeof aObj == "string") {
  1939.         aObj = aObj.replace(/[\\"\x00-\x1F\u0080-\uFFFF]/g, function($0) {
  1940.           // use the special escape notation if one exists, otherwise
  1941.           // produce a general unicode escape sequence
  1942.           return charMap[$0] ||
  1943.             "\\u" + ("0000" + $0.charCodeAt(0).toString(16)).slice(-4);
  1944.         });
  1945.         parts.push('"' + aObj + '"')
  1946.       }
  1947.       else if (aObj == null) {
  1948.         parts.push("null");
  1949.       }
  1950.       else if (aObj instanceof Array) {
  1951.         parts.push("[");
  1952.         for (var i = 0; i < aObj.length; i++) {
  1953.           jsonIfy(aObj[i]);
  1954.           parts.push(",");
  1955.         }
  1956.         if (parts[parts.length - 1] == ",")
  1957.           parts.pop(); // drop the trailing colon
  1958.         parts.push("]");
  1959.       }
  1960.       else if (typeof aObj == "object") {
  1961.         parts.push("{");
  1962.         for (var key in aObj) {
  1963.           jsonIfy(key.toString());
  1964.           parts.push(":");
  1965.           jsonIfy(aObj[key]);
  1966.           parts.push(",");
  1967.         }
  1968.         if (parts[parts.length - 1] == ",")
  1969.           parts.pop(); // drop the trailing colon
  1970.         parts.push("}");
  1971.       }
  1972.       else {
  1973.         throw new Error("No JSON representation for this object!");
  1974.       }
  1975.     }
  1976.     jsonIfy(aJSObject);
  1977.     
  1978.     var newJSONString = parts.join(" ");
  1979.     // sanity check - so that API consumers can just eval this string
  1980.     if (/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
  1981.       newJSONString.replace(/"(\\.|[^"\\])*"/g, "")
  1982.     ))
  1983.       throw new Error("JSON conversion failed unexpectedly!");
  1984.     
  1985.     return newJSONString;
  1986.   },
  1987.  
  1988. /* ........ Storage API .............. */
  1989.  
  1990.   /**
  1991.    * basic pref reader
  1992.    * @param aName
  1993.    * @param aDefault
  1994.    * @param aUseRootBranch
  1995.    */
  1996.   _getPref: function sss_getPref(aName, aDefault) {
  1997.     var pb = this._prefBranch;
  1998.     try {
  1999.       switch (pb.getPrefType(aName)) {
  2000.       case pb.PREF_STRING:
  2001.         return pb.getCharPref(aName);
  2002.       case pb.PREF_BOOL:
  2003.         return pb.getBoolPref(aName);
  2004.       case pb.PREF_INT:
  2005.         return pb.getIntPref(aName);
  2006.       default:
  2007.         return aDefault;
  2008.       }
  2009.     }
  2010.     catch(ex) {
  2011.       return aDefault;
  2012.     }
  2013.   },
  2014.  
  2015.   /**
  2016.    * write file to disk
  2017.    * @param aFile
  2018.    *        nsIFile
  2019.    * @param aData
  2020.    *        String data
  2021.    */
  2022.   _writeFile: function sss_writeFile(aFile, aData) {
  2023.     // init stream
  2024.     var stream = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  2025.                  createInstance(Ci.nsIFileOutputStream);
  2026.     stream.init(aFile, 0x02 | 0x08 | 0x20, 0600, 0);
  2027.  
  2028.     // convert to UTF-8
  2029.     var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
  2030.                     createInstance(Ci.nsIScriptableUnicodeConverter);
  2031.     converter.charset = "UTF-8";
  2032.     var convertedData = converter.ConvertFromUnicode(aData);
  2033.     convertedData += converter.Finish();
  2034.  
  2035.     // write and close stream
  2036.     stream.write(convertedData, convertedData.length);
  2037.     if (stream instanceof Ci.nsISafeOutputStream) {
  2038.       stream.finish();
  2039.     } else {
  2040.       stream.close();
  2041.     }
  2042.   },
  2043.  
  2044. /* ........ QueryInterface .............. */
  2045.  
  2046.   QueryInterface: function(aIID) {
  2047.     if (!aIID.equals(Ci.nsISupports) && 
  2048.       !aIID.equals(Ci.nsIObserver) && 
  2049.       !aIID.equals(Ci.nsISupportsWeakReference) && 
  2050.       !aIID.equals(Ci.nsIDOMEventListener) &&
  2051.       !aIID.equals(Ci.nsISessionStore)) {
  2052.       Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
  2053.       return null;
  2054.     }
  2055.     
  2056.     return this;
  2057.   }
  2058. };
  2059.  
  2060. /* :::::::::: Asynchronous File Downloader :::::::::::::: */
  2061.  
  2062. function AutoDownloader(aURL, aFilename, aWindow) {
  2063.    this._URL = aURL;
  2064.    this._filename = aFilename;
  2065.    this._window = aWindow;
  2066. }
  2067.  
  2068. AutoDownloader.prototype = {
  2069.   onStartRequest: function(aRequest, aContext) { },
  2070.   onStopRequest: function(aRequest, aContext, aStatus) {
  2071.     if (Components.isSuccessCode(aStatus)) {
  2072.       var file =
  2073.         Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
  2074.       file.initWithPath(this._filename);
  2075.       if (file.exists()) {
  2076.         file.remove(false);
  2077.       }
  2078.       
  2079.       this._window.saveURL(this._URL, this._filename, null, true, true, null);
  2080.     }
  2081.   }
  2082. };
  2083.  
  2084. /* :::::::: Service Registration & Initialization ::::::::::::::: */
  2085.  
  2086. /* ........ nsIModule .............. */
  2087.  
  2088. const SessionStoreModule = {
  2089.  
  2090.   getClassObject: function(aCompMgr, aCID, aIID) {
  2091.     if (aCID.equals(CID)) {
  2092.       return SessionStoreFactory;
  2093.     }
  2094.     
  2095.     Components.returnCode = Cr.NS_ERROR_NOT_REGISTERED;
  2096.     return null;
  2097.   },
  2098.  
  2099.   registerSelf: function(aCompMgr, aFileSpec, aLocation, aType) {
  2100.     aCompMgr.QueryInterface(Ci.nsIComponentRegistrar);
  2101.     aCompMgr.registerFactoryLocation(CID, CLASS_NAME, CONTRACT_ID, aFileSpec, aLocation, aType);
  2102.  
  2103.     var catMan = Cc["@mozilla.org/categorymanager;1"].
  2104.                  getService(Ci.nsICategoryManager);
  2105.     catMan.addCategoryEntry("app-startup", CLASS_NAME, "service," + CONTRACT_ID, true, true);
  2106.   },
  2107.  
  2108.   unregisterSelf: function(aCompMgr, aLocation, aType) {
  2109.     aCompMgr.QueryInterface(Ci.nsIComponentRegistrar);
  2110.     aCompMgr.unregisterFactoryLocation(CID, aLocation);
  2111.  
  2112.     var catMan = Cc["@mozilla.org/categorymanager;1"].
  2113.                  getService(Ci.nsICategoryManager);
  2114.     catMan.deleteCategoryEntry( "app-startup", "service," + CONTRACT_ID, true);
  2115.   },
  2116.  
  2117.   canUnload: function(aCompMgr) {
  2118.     return true;
  2119.   }
  2120. }
  2121.  
  2122. /* ........ nsIFactory .............. */
  2123.  
  2124. const SessionStoreFactory = {
  2125.  
  2126.   createInstance: function(aOuter, aIID) {
  2127.     if (aOuter != null) {
  2128.       Components.returnCode = Cr.NS_ERROR_NO_AGGREGATION;
  2129.       return null;
  2130.     }
  2131.     
  2132.     return (new SessionStoreService()).QueryInterface(aIID);
  2133.   },
  2134.  
  2135.   lockFactory: function(aLock) { },
  2136.  
  2137.   QueryInterface: function(aIID) {
  2138.     if (!aIID.equals(Ci.nsISupports) && !aIID.equals(Ci.nsIModule) &&
  2139.         !aIID.equals(Ci.nsIFactory) && !aIID.equals(Ci.nsISessionStore)) {
  2140.       Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
  2141.       return null;
  2142.     }
  2143.     
  2144.     return this;
  2145.   }
  2146. };
  2147.  
  2148. function NSGetModule(aComMgr, aFileSpec) {
  2149.   return SessionStoreModule;
  2150. }
  2151.