nsSessionStartup.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /**
  5. * Session Storage and Restoration
  6. *
  7. * Overview
  8. * This service reads user's session file at startup, and makes a determination
  9. * as to whether the session should be restored. It will restore the session
  10. * under the circumstances described below. If the auto-start Private Browsing
  11. * mode is active, however, the session is never restored.
  12. *
  13. * Crash Detection
  14. * The session file stores a session.state property, that
  15. * indicates whether the browser is currently running. When the browser shuts
  16. * down, the field is changed to "stopped". At startup, this field is read, and
  17. * if its value is "running", then it's assumed that the browser had previously
  18. * crashed, or at the very least that something bad happened, and that we should
  19. * restore the session.
  20. *
  21. * Forced Restarts
  22. * In the event that a restart is required due to application update or extension
  23. * installation, set the browser.sessionstore.resume_session_once pref to true,
  24. * and the session will be restored the next time the browser starts.
  25. *
  26. * Always Resume
  27. * This service will always resume the session if the integer pref
  28. * browser.startup.page is set to 3.
  29. */
  30. /* :::::::: Constants and Helpers ::::::::::::::: */
  31. const Cc = Components.classes;
  32. const Ci = Components.interfaces;
  33. const Cr = Components.results;
  34. const Cu = Components.utils;
  35. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  36. Cu.import("resource://gre/modules/Services.jsm");
  37. Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
  38. Cu.import("resource://gre/modules/Promise.jsm");
  39. XPCOMUtils.defineLazyModuleGetter(this, "_SessionFile",
  40. "resource:///modules/sessionstore/_SessionFile.jsm");
  41. const STATE_RUNNING_STR = "running";
  42. function debug(aMsg) {
  43. aMsg = ("SessionStartup: " + aMsg).replace(/\S{80}/g, "$&\n");
  44. Services.console.logStringMessage(aMsg);
  45. }
  46. var gOnceInitializedDeferred = Promise.defer();
  47. /* :::::::: The Service ::::::::::::::: */
  48. function SessionStartup() {
  49. }
  50. SessionStartup.prototype = {
  51. // the state to restore at startup
  52. _initialState: null,
  53. _sessionType: Ci.nsISessionStartup.NO_SESSION,
  54. _initialized: false,
  55. /* ........ Global Event Handlers .............. */
  56. /**
  57. * Initialize the component
  58. */
  59. init: function() {
  60. // do not need to initialize anything in auto-started private browsing sessions
  61. if (PrivateBrowsingUtils.permanentPrivateBrowsing) {
  62. this._initialized = true;
  63. gOnceInitializedDeferred.resolve();
  64. return;
  65. }
  66. if (Services.prefs.getBoolPref("browser.sessionstore.resume_session_once") ||
  67. Services.prefs.getIntPref("browser.startup.page") == 3) {
  68. this._ensureInitialized();
  69. } else {
  70. _SessionFile.read().then(
  71. this._onSessionFileRead.bind(this)
  72. );
  73. }
  74. },
  75. // Wrap a string as a nsISupports
  76. _createSupportsString: function(aData) {
  77. let string = Cc["@mozilla.org/supports-string;1"]
  78. .createInstance(Ci.nsISupportsString);
  79. string.data = aData;
  80. return string;
  81. },
  82. _onSessionFileRead: function(aStateString) {
  83. if (this._initialized) {
  84. // Initialization is complete, nothing else to do
  85. return;
  86. }
  87. try {
  88. this._initialized = true;
  89. // Let observers modify the state before it is used
  90. let supportsStateString = this._createSupportsString(aStateString);
  91. Services.obs.notifyObservers(supportsStateString, "sessionstore-state-read", "");
  92. aStateString = supportsStateString.data;
  93. // No valid session found.
  94. if (!aStateString) {
  95. this._sessionType = Ci.nsISessionStartup.NO_SESSION;
  96. return;
  97. }
  98. // parse the session state into a JS object
  99. // remove unneeded braces (added for compatibility with Firefox 2.0 and 3.0)
  100. if (aStateString.charAt(0) == '(')
  101. aStateString = aStateString.slice(1, -1);
  102. let corruptFile = false;
  103. try {
  104. this._initialState = JSON.parse(aStateString);
  105. }
  106. catch (ex) {
  107. debug("The session file contained un-parse-able JSON: " + ex);
  108. // This is not valid JSON, but this might still be valid JavaScript,
  109. // as used in FF2/FF3, so we need to eval.
  110. // evalInSandbox will throw if aStateString is not parse-able.
  111. try {
  112. var s = new Cu.Sandbox("about:blank", {sandboxName: 'nsSessionStartup'});
  113. this._initialState = Cu.evalInSandbox("(" + aStateString + ")", s);
  114. } catch(ex) {
  115. debug("The session file contained un-eval-able JSON: " + ex);
  116. corruptFile = true;
  117. }
  118. }
  119. let doResumeSessionOnce = Services.prefs.getBoolPref("browser.sessionstore.resume_session_once");
  120. let doResumeSession = doResumeSessionOnce ||
  121. Services.prefs.getIntPref("browser.startup.page") == 3;
  122. // If this is a normal restore then throw away any previous session
  123. if (!doResumeSessionOnce)
  124. delete this._initialState.lastSessionState;
  125. let resumeFromCrash = Services.prefs.getBoolPref("browser.sessionstore.resume_from_crash");
  126. let lastSessionCrashed =
  127. this._initialState && this._initialState.session &&
  128. this._initialState.session.state &&
  129. this._initialState.session.state == STATE_RUNNING_STR;
  130. // set the startup type
  131. if (lastSessionCrashed && resumeFromCrash)
  132. this._sessionType = Ci.nsISessionStartup.RECOVER_SESSION;
  133. else if (!lastSessionCrashed && doResumeSession)
  134. this._sessionType = Ci.nsISessionStartup.RESUME_SESSION;
  135. else if (this._initialState)
  136. this._sessionType = Ci.nsISessionStartup.DEFER_SESSION;
  137. else
  138. this._initialState = null; // reset the state
  139. Services.obs.addObserver(this, "sessionstore-windows-restored", true);
  140. if (this._sessionType != Ci.nsISessionStartup.NO_SESSION)
  141. Services.obs.addObserver(this, "browser:purge-session-history", true);
  142. } finally {
  143. // We're ready. Notify everyone else.
  144. Services.obs.notifyObservers(null, "sessionstore-state-finalized", "");
  145. gOnceInitializedDeferred.resolve();
  146. }
  147. },
  148. /**
  149. * Handle notifications
  150. */
  151. observe: function(aSubject, aTopic, aData) {
  152. switch (aTopic) {
  153. case "app-startup":
  154. Services.obs.addObserver(this, "final-ui-startup", true);
  155. Services.obs.addObserver(this, "quit-application", true);
  156. break;
  157. case "final-ui-startup":
  158. Services.obs.removeObserver(this, "final-ui-startup");
  159. Services.obs.removeObserver(this, "quit-application");
  160. this.init();
  161. break;
  162. case "quit-application":
  163. // no reason for initializing at this point (cf. bug 409115)
  164. Services.obs.removeObserver(this, "final-ui-startup");
  165. Services.obs.removeObserver(this, "quit-application");
  166. if (this._sessionType != Ci.nsISessionStartup.NO_SESSION)
  167. Services.obs.removeObserver(this, "browser:purge-session-history");
  168. break;
  169. case "sessionstore-windows-restored":
  170. Services.obs.removeObserver(this, "sessionstore-windows-restored");
  171. // free _initialState after nsSessionStore is done with it
  172. this._initialState = null;
  173. break;
  174. case "browser:purge-session-history":
  175. Services.obs.removeObserver(this, "browser:purge-session-history");
  176. // reset all state on sanitization
  177. this._sessionType = Ci.nsISessionStartup.NO_SESSION;
  178. break;
  179. }
  180. },
  181. /* ........ Public API ................*/
  182. get onceInitialized() {
  183. return gOnceInitializedDeferred.promise;
  184. },
  185. /**
  186. * Get the session state as a jsval
  187. */
  188. get state() {
  189. this._ensureInitialized();
  190. return this._initialState;
  191. },
  192. /**
  193. * Determines whether there is a pending session restore and makes sure that
  194. * we're initialized before returning. If we're not yet this will read the
  195. * session file synchronously.
  196. * @returns bool
  197. */
  198. doRestore: function() {
  199. this._ensureInitialized();
  200. return this._willRestore();
  201. },
  202. /**
  203. * Determines whether there is a pending session restore.
  204. * @returns bool
  205. */
  206. _willRestore: function() {
  207. return this._sessionType == Ci.nsISessionStartup.RECOVER_SESSION ||
  208. this._sessionType == Ci.nsISessionStartup.RESUME_SESSION;
  209. },
  210. /**
  211. * Returns whether we will restore a session that ends up replacing the
  212. * homepage. The browser uses this to not start loading the homepage if
  213. * we're going to stop its load anyway shortly after.
  214. *
  215. * This is meant to be an optimization for the average case that loading the
  216. * session file finishes before we may want to start loading the default
  217. * homepage. Should this be called before the session file has been read it
  218. * will just return false.
  219. *
  220. * @returns bool
  221. */
  222. get willOverrideHomepage() {
  223. if (this._initialState && this._willRestore()) {
  224. let windows = this._initialState.windows || null;
  225. // If there are valid windows with not only pinned tabs, signal that we
  226. // will override the default homepage by restoring a session.
  227. return windows && windows.some(w => w.tabs.some(t => !t.pinned));
  228. }
  229. return false;
  230. },
  231. /**
  232. * Get the type of pending session store, if any.
  233. */
  234. get sessionType() {
  235. this._ensureInitialized();
  236. return this._sessionType;
  237. },
  238. // Ensure that initialization is complete.
  239. // If initialization is not complete yet, fall back to a synchronous
  240. // initialization and kill ongoing asynchronous initialization
  241. _ensureInitialized: function() {
  242. try {
  243. if (this._initialized) {
  244. // Initialization is complete, nothing else to do
  245. return;
  246. }
  247. let contents = _SessionFile.syncRead();
  248. this._onSessionFileRead(contents);
  249. } catch(ex) {
  250. debug("ensureInitialized: could not read session " + ex + ", " + ex.stack);
  251. throw ex;
  252. }
  253. },
  254. /* ........ QueryInterface .............. */
  255. QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver,
  256. Ci.nsISupportsWeakReference,
  257. Ci.nsISessionStartup]),
  258. classID: Components.ID("{ec7a6c20-e081-11da-8ad9-0800200c9a66}")
  259. };
  260. this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SessionStartup]);