/
SessionStore.sys.mjs
7011 lines (6130 loc) 路 228 KB
/
SessionStore.sys.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
// Current version of the format used by Session Restore.
const FORMAT_VERSION = 1;
const TAB_CUSTOM_VALUES = new WeakMap();
const TAB_LAZY_STATES = new WeakMap();
const TAB_STATE_NEEDS_RESTORE = 1;
const TAB_STATE_RESTORING = 2;
const TAB_STATE_FOR_BROWSER = new WeakMap();
const WINDOW_RESTORE_IDS = new WeakMap();
const WINDOW_RESTORE_ZINDICES = new WeakMap();
const WINDOW_SHOWING_PROMISES = new Map();
const WINDOW_FLUSHING_PROMISES = new Map();
// A new window has just been restored. At this stage, tabs are generally
// not restored.
const NOTIFY_SINGLE_WINDOW_RESTORED = "sessionstore-single-window-restored";
const NOTIFY_WINDOWS_RESTORED = "sessionstore-windows-restored";
const NOTIFY_BROWSER_STATE_RESTORED = "sessionstore-browser-state-restored";
const NOTIFY_LAST_SESSION_CLEARED = "sessionstore-last-session-cleared";
const NOTIFY_RESTORING_ON_STARTUP = "sessionstore-restoring-on-startup";
const NOTIFY_INITIATING_MANUAL_RESTORE =
"sessionstore-initiating-manual-restore";
const NOTIFY_CLOSED_OBJECTS_CHANGED = "sessionstore-closed-objects-changed";
const NOTIFY_TAB_RESTORED = "sessionstore-debug-tab-restored"; // WARNING: debug-only
const NOTIFY_DOMWINDOWCLOSED_HANDLED =
"sessionstore-debug-domwindowclosed-handled"; // WARNING: debug-only
const NOTIFY_BROWSER_SHUTDOWN_FLUSH = "sessionstore-browser-shutdown-flush";
// Maximum number of tabs to restore simultaneously. Previously controlled by
// the browser.sessionstore.max_concurrent_tabs pref.
const MAX_CONCURRENT_TAB_RESTORES = 3;
// Minimum amount (in CSS px) by which we allow window edges to be off-screen
// when restoring a window, before we override the saved position to pull the
// window back within the available screen area.
const MIN_SCREEN_EDGE_SLOP = 8;
// global notifications observed
const OBSERVING = [
"browser-window-before-show",
"domwindowclosed",
"quit-application-granted",
"browser-lastwindow-close-granted",
"quit-application",
"browser:purge-session-history",
"browser:purge-session-history-for-domain",
"idle-daily",
"clear-origin-attributes-data",
"browsing-context-did-set-embedder",
"browsing-context-discarded",
"browser-shutdown-tabstate-updated",
];
// XUL Window properties to (re)store
// Restored in restoreDimensions()
const WINDOW_ATTRIBUTES = ["width", "height", "screenX", "screenY", "sizemode"];
const CHROME_FLAGS_MAP = [
[Ci.nsIWebBrowserChrome.CHROME_TITLEBAR, "titlebar"],
[Ci.nsIWebBrowserChrome.CHROME_WINDOW_CLOSE, "close"],
[Ci.nsIWebBrowserChrome.CHROME_TOOLBAR, "toolbar"],
[Ci.nsIWebBrowserChrome.CHROME_LOCATIONBAR, "location"],
[Ci.nsIWebBrowserChrome.CHROME_PERSONAL_TOOLBAR, "personalbar"],
[Ci.nsIWebBrowserChrome.CHROME_STATUSBAR, "status"],
[Ci.nsIWebBrowserChrome.CHROME_MENUBAR, "menubar"],
[Ci.nsIWebBrowserChrome.CHROME_WINDOW_RESIZE, "resizable"],
[Ci.nsIWebBrowserChrome.CHROME_WINDOW_MIN, "minimizable"],
[Ci.nsIWebBrowserChrome.CHROME_SCROLLBARS, "", "scrollbars=0"],
[Ci.nsIWebBrowserChrome.CHROME_PRIVATE_WINDOW, "private"],
[Ci.nsIWebBrowserChrome.CHROME_NON_PRIVATE_WINDOW, "non-private"],
// Do not inherit remoteness and fissionness from the previous session.
//[Ci.nsIWebBrowserChrome.CHROME_REMOTE_WINDOW, "remote", "non-remote"],
//[Ci.nsIWebBrowserChrome.CHROME_FISSION_WINDOW, "fission", "non-fission"],
[Ci.nsIWebBrowserChrome.CHROME_WINDOW_POPUP, "popup"],
[
Ci.nsIWebBrowserChrome.CHROME_WINDOW_POPUP |
Ci.nsIWebBrowserChrome.CHROME_TITLEBAR,
"",
"titlebar=0",
],
[
Ci.nsIWebBrowserChrome.CHROME_WINDOW_POPUP |
Ci.nsIWebBrowserChrome.CHROME_WINDOW_CLOSE,
"",
"close=0",
],
[Ci.nsIWebBrowserChrome.CHROME_WINDOW_LOWERED, "alwayslowered"],
[Ci.nsIWebBrowserChrome.CHROME_WINDOW_RAISED, "alwaysraised"],
// "chrome" and "suppressanimation" are always set.
//[Ci.nsIWebBrowserChrome.CHROME_SUPPRESS_ANIMATION, "suppressanimation"],
[Ci.nsIWebBrowserChrome.CHROME_ALWAYS_ON_TOP, "alwaysontop"],
//[Ci.nsIWebBrowserChrome.CHROME_OPENAS_CHROME, "chrome", "chrome=0"],
[Ci.nsIWebBrowserChrome.CHROME_EXTRA, "extrachrome"],
[Ci.nsIWebBrowserChrome.CHROME_CENTER_SCREEN, "centerscreen"],
[Ci.nsIWebBrowserChrome.CHROME_DEPENDENT, "dependent"],
[Ci.nsIWebBrowserChrome.CHROME_MODAL, "modal"],
[Ci.nsIWebBrowserChrome.CHROME_OPENAS_DIALOG, "dialog", "dialog=0"],
];
// Hideable window features to (re)store
// Restored in restoreWindowFeatures()
const WINDOW_HIDEABLE_FEATURES = [
"menubar",
"toolbar",
"locationbar",
"personalbar",
"statusbar",
"scrollbars",
];
const WINDOW_OPEN_FEATURES_MAP = {
locationbar: "location",
statusbar: "status",
};
// Messages that will be received via the Frame Message Manager.
const MESSAGES = [
// The content script sends us data that has been invalidated and needs to
// be saved to disk.
"SessionStore:update",
// The restoreHistory code has run. This is a good time to run SSTabRestoring.
"SessionStore:restoreHistoryComplete",
// The load for the restoring tab has begun. We update the URL bar at this
// time; if we did it before, the load would overwrite it.
"SessionStore:restoreTabContentStarted",
// All network loads for a restoring tab are done, so we should
// consider restoring another tab in the queue. The document has
// been restored, and forms have been filled. We trigger
// SSTabRestored at this time.
"SessionStore:restoreTabContentComplete",
// The content script encountered an error.
"SessionStore:error",
];
// The list of messages we accept from <xul:browser>s that have no tab
// assigned, or whose windows have gone away. Those are for example the
// ones that preload about:newtab pages, or from browsers where the window
// has just been closed.
const NOTAB_MESSAGES = new Set([
// For a description see above.
"SessionStore:update",
// For a description see above.
"SessionStore:error",
]);
// The list of messages we accept without an "epoch" parameter.
// See getCurrentEpoch() and friends to find out what an "epoch" is.
const NOEPOCH_MESSAGES = new Set([
// For a description see above.
"SessionStore:error",
]);
// The list of messages we want to receive even during the short period after a
// frame has been removed from the DOM and before its frame script has finished
// unloading.
const CLOSED_MESSAGES = new Set([
// For a description see above.
"SessionStore:update",
// For a description see above.
"SessionStore:error",
]);
// These are tab events that we listen to.
const TAB_EVENTS = [
"TabOpen",
"TabBrowserInserted",
"TabClose",
"TabSelect",
"TabShow",
"TabHide",
"TabPinned",
"TabUnpinned",
];
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
/**
* When calling restoreTabContent, we can supply a reason why
* the content is being restored. These are those reasons.
*/
const RESTORE_TAB_CONTENT_REASON = {
/**
* SET_STATE:
* We're restoring this tab's content because we're setting
* state inside this browser tab, probably because the user
* has asked us to restore a tab (or window, or entire session).
*/
SET_STATE: 0,
/**
* NAVIGATE_AND_RESTORE:
* We're restoring this tab's content because a navigation caused
* us to do a remoteness-flip.
*/
NAVIGATE_AND_RESTORE: 1,
};
// 'browser.startup.page' preference value to resume the previous session.
const BROWSER_STARTUP_RESUME_SESSION = 3;
// Used by SessionHistoryListener.
const kNoIndex = Number.MAX_SAFE_INTEGER;
const kLastIndex = Number.MAX_SAFE_INTEGER - 1;
import { PrivateBrowsingUtils } from "resource://gre/modules/PrivateBrowsingUtils.sys.mjs";
import { TelemetryTimestamps } from "resource://gre/modules/TelemetryTimestamps.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
import { GlobalState } from "resource:///modules/sessionstore/GlobalState.sys.mjs";
const lazy = {};
XPCOMUtils.defineLazyServiceGetters(lazy, {
gScreenManager: ["@mozilla.org/gfx/screenmanager;1", "nsIScreenManager"],
});
ChromeUtils.defineESModuleGetters(lazy, {
AsyncShutdown: "resource://gre/modules/AsyncShutdown.sys.mjs",
DevToolsShim: "chrome://devtools-startup/content/DevToolsShim.sys.mjs",
E10SUtils: "resource://gre/modules/E10SUtils.sys.mjs",
PrivacyFilter: "resource://gre/modules/sessionstore/PrivacyFilter.sys.mjs",
PromiseUtils: "resource://gre/modules/PromiseUtils.sys.mjs",
RunState: "resource:///modules/sessionstore/RunState.sys.mjs",
SessionCookies: "resource:///modules/sessionstore/SessionCookies.sys.mjs",
SessionFile: "resource:///modules/sessionstore/SessionFile.sys.mjs",
SessionHistory: "resource://gre/modules/sessionstore/SessionHistory.sys.mjs",
SessionSaver: "resource:///modules/sessionstore/SessionSaver.sys.mjs",
SessionStartup: "resource:///modules/sessionstore/SessionStartup.sys.mjs",
TabAttributes: "resource:///modules/sessionstore/TabAttributes.sys.mjs",
TabState: "resource:///modules/sessionstore/TabState.sys.mjs",
TabStateCache: "resource:///modules/sessionstore/TabStateCache.sys.mjs",
TabStateFlusher: "resource:///modules/sessionstore/TabStateFlusher.sys.mjs",
setTimeout: "resource://gre/modules/Timer.sys.mjs",
});
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
HomePage: "resource:///modules/HomePage.jsm",
TabCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
});
XPCOMUtils.defineLazyGetter(lazy, "blankURI", () => {
return Services.io.newURI("about:blank");
});
/**
* |true| if we are in debug mode, |false| otherwise.
* Debug mode is controlled by preference browser.sessionstore.debug
*/
var gDebuggingEnabled = false;
/**
* A global value to tell that fingerprinting resistance is enabled or not.
* If it's enabled, the session restore won't restore the window's size and
* size mode.
* This value is controlled by preference privacy.resistFingerprinting.
*/
var gResistFingerprintingEnabled = false;
/**
* @namespace SessionStore
*/
export var SessionStore = {
get promiseInitialized() {
return SessionStoreInternal.promiseInitialized;
},
get promiseAllWindowsRestored() {
return SessionStoreInternal.promiseAllWindowsRestored;
},
get canRestoreLastSession() {
return SessionStoreInternal.canRestoreLastSession;
},
set canRestoreLastSession(val) {
SessionStoreInternal.canRestoreLastSession = val;
},
get lastClosedObjectType() {
return SessionStoreInternal.lastClosedObjectType;
},
get willAutoRestore() {
return SessionStoreInternal.willAutoRestore;
},
init: function ss_init() {
SessionStoreInternal.init();
},
getBrowserState: function ss_getBrowserState() {
return SessionStoreInternal.getBrowserState();
},
setBrowserState: function ss_setBrowserState(aState) {
SessionStoreInternal.setBrowserState(aState);
},
getWindowState: function ss_getWindowState(aWindow) {
return SessionStoreInternal.getWindowState(aWindow);
},
setWindowState: function ss_setWindowState(aWindow, aState, aOverwrite) {
SessionStoreInternal.setWindowState(aWindow, aState, aOverwrite);
},
getTabState: function ss_getTabState(aTab) {
return SessionStoreInternal.getTabState(aTab);
},
setTabState: function ss_setTabState(aTab, aState) {
SessionStoreInternal.setTabState(aTab, aState);
},
// Return whether a tab is restoring.
isTabRestoring(aTab) {
return TAB_STATE_FOR_BROWSER.has(aTab.linkedBrowser);
},
getInternalObjectState(obj) {
return SessionStoreInternal.getInternalObjectState(obj);
},
duplicateTab: function ss_duplicateTab(
aWindow,
aTab,
aDelta = 0,
aRestoreImmediately = true,
aOptions = {}
) {
return SessionStoreInternal.duplicateTab(
aWindow,
aTab,
aDelta,
aRestoreImmediately,
aOptions
);
},
getLastClosedTabCount(aWindow) {
return SessionStoreInternal.getLastClosedTabCount(aWindow);
},
resetLastClosedTabCount(aWindow) {
SessionStoreInternal.resetLastClosedTabCount(aWindow);
},
getClosedTabCountForWindow: function ss_getClosedTabCountForWindow(aWindow) {
return SessionStoreInternal.getClosedTabCountForWindow(aWindow);
},
getClosedTabDataForWindow: function ss_getClosedTabDataForWindow(aWindow) {
return SessionStoreInternal.getClosedTabDataForWindow(aWindow);
},
undoCloseTab: function ss_undoCloseTab(aWindow, aIndex) {
return SessionStoreInternal.undoCloseTab(aWindow, aIndex);
},
forgetClosedTab: function ss_forgetClosedTab(aWindow, aIndex) {
return SessionStoreInternal.forgetClosedTab(aWindow, aIndex);
},
getClosedWindowCount: function ss_getClosedWindowCount() {
return SessionStoreInternal.getClosedWindowCount();
},
getClosedWindowData: function ss_getClosedWindowData() {
return SessionStoreInternal.getClosedWindowData();
},
maybeDontRestoreTabs(aWindow) {
SessionStoreInternal.maybeDontRestoreTabs(aWindow);
},
undoCloseWindow: function ss_undoCloseWindow(aIndex) {
return SessionStoreInternal.undoCloseWindow(aIndex);
},
forgetClosedWindow: function ss_forgetClosedWindow(aIndex) {
return SessionStoreInternal.forgetClosedWindow(aIndex);
},
getCustomWindowValue(aWindow, aKey) {
return SessionStoreInternal.getCustomWindowValue(aWindow, aKey);
},
setCustomWindowValue(aWindow, aKey, aStringValue) {
SessionStoreInternal.setCustomWindowValue(aWindow, aKey, aStringValue);
},
deleteCustomWindowValue(aWindow, aKey) {
SessionStoreInternal.deleteCustomWindowValue(aWindow, aKey);
},
getCustomTabValue(aTab, aKey) {
return SessionStoreInternal.getCustomTabValue(aTab, aKey);
},
setCustomTabValue(aTab, aKey, aStringValue) {
SessionStoreInternal.setCustomTabValue(aTab, aKey, aStringValue);
},
deleteCustomTabValue(aTab, aKey) {
SessionStoreInternal.deleteCustomTabValue(aTab, aKey);
},
getLazyTabValue(aTab, aKey) {
return SessionStoreInternal.getLazyTabValue(aTab, aKey);
},
getCustomGlobalValue(aKey) {
return SessionStoreInternal.getCustomGlobalValue(aKey);
},
setCustomGlobalValue(aKey, aStringValue) {
SessionStoreInternal.setCustomGlobalValue(aKey, aStringValue);
},
deleteCustomGlobalValue(aKey) {
SessionStoreInternal.deleteCustomGlobalValue(aKey);
},
persistTabAttribute: function ss_persistTabAttribute(aName) {
SessionStoreInternal.persistTabAttribute(aName);
},
restoreLastSession: function ss_restoreLastSession() {
SessionStoreInternal.restoreLastSession();
},
speculativeConnectOnTabHover(tab) {
SessionStoreInternal.speculativeConnectOnTabHover(tab);
},
getCurrentState(aUpdateAll) {
return SessionStoreInternal.getCurrentState(aUpdateAll);
},
reviveCrashedTab(aTab) {
return SessionStoreInternal.reviveCrashedTab(aTab);
},
reviveAllCrashedTabs() {
return SessionStoreInternal.reviveAllCrashedTabs();
},
updateSessionStoreFromTablistener(
aBrowser,
aBrowsingContext,
aPermanentKey,
aData,
aForStorage
) {
return SessionStoreInternal.updateSessionStoreFromTablistener(
aBrowser,
aBrowsingContext,
aPermanentKey,
aData,
aForStorage
);
},
getSessionHistory(tab, updatedCallback) {
return SessionStoreInternal.getSessionHistory(tab, updatedCallback);
},
undoCloseById(aClosedId, aIncludePrivate) {
return SessionStoreInternal.undoCloseById(aClosedId, aIncludePrivate);
},
resetBrowserToLazyState(tab) {
return SessionStoreInternal.resetBrowserToLazyState(tab);
},
maybeExitCrashedState(browser) {
SessionStoreInternal.maybeExitCrashedState(browser);
},
isBrowserInCrashedSet(browser) {
return SessionStoreInternal.isBrowserInCrashedSet(browser);
},
// this is used for testing purposes
resetNextClosedId() {
SessionStoreInternal._nextClosedId = 0;
},
/**
* Ensures that session store has registered and started tracking a given window.
* @param window
* Window reference
*/
ensureInitialized(window) {
if (SessionStoreInternal._sessionInitialized && !window.__SSi) {
/*
We need to check that __SSi is not defined on the window so that if
onLoad function is in the middle of executing we don't enter the function
again and try to redeclare the ContentSessionStore script.
*/
SessionStoreInternal.onLoad(window);
}
},
getCurrentEpoch(browser) {
return SessionStoreInternal.getCurrentEpoch(browser.permanentKey);
},
/**
* Determines whether the passed version number is compatible with
* the current version number of the SessionStore.
*
* @param version The format and version of the file, as an array, e.g.
* ["sessionrestore", 1]
*/
isFormatVersionCompatible(version) {
if (!version) {
return false;
}
if (!Array.isArray(version)) {
// Improper format.
return false;
}
if (version[0] != "sessionrestore") {
// Not a Session Restore file.
return false;
}
let number = Number.parseFloat(version[1]);
if (Number.isNaN(number)) {
return false;
}
return number <= FORMAT_VERSION;
},
/**
* Filters out not worth-saving tabs from a given browser state object.
*
* @param aState (object)
* The browser state for which we remove worth-saving tabs.
* The given object will be modified.
*/
keepOnlyWorthSavingTabs(aState) {
let closedWindowShouldRestore = null;
for (let i = aState.windows.length - 1; i >= 0; i--) {
let win = aState.windows[i];
for (let j = win.tabs.length - 1; j >= 0; j--) {
let tab = win.tabs[j];
if (!SessionStoreInternal._shouldSaveTab(tab)) {
win.tabs.splice(j, 1);
if (win.selected > j) {
win.selected--;
}
}
}
// If it's the last window (and no closedWindow that will restore), keep the window state with no tabs.
if (
!win.tabs.length &&
(aState.windows.length > 1 ||
closedWindowShouldRestore ||
(closedWindowShouldRestore == null &&
(closedWindowShouldRestore = aState._closedWindows.some(
w => w._shouldRestore
))))
) {
aState.windows.splice(i, 1);
if (aState.selectedWindow > i) {
aState.selectedWindow--;
}
}
// Floorp injections
// Remove SSB window state.
// SSB windows should be not restored, so we don't need to keep their state.
for (let j = 0; j < win.tabs.length; j++) {
if (win.tabs[j].floorpSSB || win.tabs[j].floorpWebPanel) {
win.tabs.splice(j, 1);
if (aState.selectedWindow > i) {
aState.selectedWindow--;
}
}
}
}
},
/**
* Prepares to change the remoteness of the given browser, by ensuring that
* the local instance of session history is up-to-date.
*/
async prepareToChangeRemoteness(aTab) {
await SessionStoreInternal.prepareToChangeRemoteness(aTab);
},
finishTabRemotenessChange(aTab, aSwitchId) {
SessionStoreInternal.finishTabRemotenessChange(aTab, aSwitchId);
},
};
// Freeze the SessionStore object. We don't want anyone to modify it.
Object.freeze(SessionStore);
/**
* @namespace SessionStoreInternal
*
* @description Internal implementations and helpers for the public SessionStore methods
*/
var SessionStoreInternal = {
QueryInterface: ChromeUtils.generateQI([
"nsIObserver",
"nsISupportsWeakReference",
]),
_globalState: new GlobalState(),
// A counter to be used to generate a unique ID for each closed tab or window.
_nextClosedId: 0,
// During the initial restore and setBrowserState calls tracks the number of
// windows yet to be restored
_restoreCount: -1,
// For each <browser> element, records the SHistoryListener.
_browserSHistoryListener: new WeakMap(),
// Tracks the various listeners that are used throughout the restore.
_restoreListeners: new WeakMap(),
// Records the promise created in _restoreHistory, which is used to track
// the completion of the first phase of the restore.
_tabStateRestorePromises: new WeakMap(),
// The history data needed to be restored in the parent.
_tabStateToRestore: new WeakMap(),
// For each <browser> element, records the current epoch.
_browserEpochs: new WeakMap(),
// Any browsers that fires the oop-browser-crashed event gets stored in
// here - that way we know which browsers to ignore messages from (until
// they get restored).
_crashedBrowsers: new WeakSet(),
// A map (xul:browser -> FrameLoader) that maps a browser to the last
// associated frameLoader we heard about.
_lastKnownFrameLoader: new WeakMap(),
// A map (xul:browser -> object) that maps a browser associated with a
// recently closed tab to all its necessary state information we need to
// properly handle final update message.
_closedTabs: new WeakMap(),
// A map (xul:browser -> object) that maps a browser associated with a
// recently closed tab due to a window closure to the tab state information
// that is being stored in _closedWindows for that tab.
_closedWindowTabs: new WeakMap(),
// A set of window data that has the potential to be saved in the _closedWindows
// array for the session. We will remove window data from this set whenever
// forgetClosedWindow is called for the window, or when session history is
// purged, so that we don't accidentally save that data after the flush has
// completed. Closed tabs use a more complicated mechanism for this particular
// problem. When forgetClosedTab is called, the browser is removed from the
// _closedTabs map, so its data is not recorded. In the purge history case,
// the closedTabs array per window is overwritten so that once the flush is
// complete, the tab would only ever add itself to an array that SessionStore
// no longer cares about. Bug 1230636 has been filed to make the tab case
// work more like the window case, which is more explicit, and easier to
// reason about.
_saveableClosedWindowData: new WeakSet(),
// whether a setBrowserState call is in progress
_browserSetState: false,
// time in milliseconds when the session was started (saved across sessions),
// defaults to now if no session was restored or timestamp doesn't exist
_sessionStartTime: Date.now(),
// states for all currently opened windows
_windows: {},
// counter for creating unique window IDs
_nextWindowID: 0,
// states for all recently closed windows
_closedWindows: [],
// collection of session states yet to be restored
_statesToRestore: {},
// counts the number of crashes since the last clean start
_recentCrashes: 0,
// whether the last window was closed and should be restored
_restoreLastWindow: false,
// number of tabs currently restoring
_tabsRestoringCount: 0,
_log: null,
// When starting Firefox with a single private window, this is the place
// where we keep the session we actually wanted to restore in case the user
// decides to later open a non-private window as well.
_deferredInitialState: null,
// Keeps track of whether a notification needs to be sent that closed objects have changed.
_closedObjectsChanged: false,
// A promise resolved once initialization is complete
_deferredInitialized: (function () {
let deferred = {};
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
})(),
// Whether session has been initialized
_sessionInitialized: false,
// A promise resolved once all windows are restored.
_deferredAllWindowsRestored: (function () {
let deferred = {};
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
})(),
get promiseAllWindowsRestored() {
return this._deferredAllWindowsRestored.promise;
},
// Promise that is resolved when we're ready to initialize
// and restore the session.
_promiseReadyForInitialization: null,
// Keep busy state counters per window.
_windowBusyStates: new WeakMap(),
/**
* A promise fulfilled once initialization is complete.
*/
get promiseInitialized() {
return this._deferredInitialized.promise;
},
get canRestoreLastSession() {
return LastSession.canRestore;
},
set canRestoreLastSession(val) {
// Cheat a bit; only allow false.
if (!val) {
LastSession.clear();
}
},
/**
* Returns a string describing the last closed object, either "tab" or "window".
*
* This was added to support the sessions.restore WebExtensions API.
*/
get lastClosedObjectType() {
if (this._closedWindows.length) {
// Since there are closed windows, we need to check if there's a closed tab
// in one of the currently open windows that was closed after the
// last-closed window.
let tabTimestamps = [];
for (let window of Services.wm.getEnumerator("navigator:browser")) {
let windowState = this._windows[window.__SSi];
if (windowState && windowState._closedTabs[0]) {
tabTimestamps.push(windowState._closedTabs[0].closedAt);
}
}
if (
!tabTimestamps.length ||
tabTimestamps.sort((a, b) => b - a)[0] < this._closedWindows[0].closedAt
) {
return "window";
}
}
return "tab";
},
/**
* Returns a boolean that determines whether the session will be automatically
* restored upon the _next_ startup or a restart.
*/
get willAutoRestore() {
return (
!PrivateBrowsingUtils.permanentPrivateBrowsing &&
(Services.prefs.getBoolPref("browser.sessionstore.resume_session_once") ||
Services.prefs.getIntPref("browser.startup.page") ==
BROWSER_STARTUP_RESUME_SESSION)
);
},
/**
* Initialize the sessionstore service.
*/
init() {
if (this._initialized) {
throw new Error("SessionStore.init() must only be called once!");
}
TelemetryTimestamps.add("sessionRestoreInitialized");
OBSERVING.forEach(function (aTopic) {
Services.obs.addObserver(this, aTopic, true);
}, this);
this._initPrefs();
this._initialized = true;
Services.telemetry
.getHistogramById("FX_SESSION_RESTORE_PRIVACY_LEVEL")
.add(Services.prefs.getIntPref("browser.sessionstore.privacy_level"));
},
/**
* Initialize the session using the state provided by SessionStartup
*/
initSession() {
TelemetryStopwatch.start("FX_SESSION_RESTORE_STARTUP_INIT_SESSION_MS");
let state;
let ss = lazy.SessionStartup;
if (ss.willRestore() || ss.sessionType == ss.DEFER_SESSION) {
state = ss.state;
}
if (state) {
try {
// If we're doing a DEFERRED session, then we want to pull pinned tabs
// out so they can be restored.
if (ss.sessionType == ss.DEFER_SESSION) {
let [iniState, remainingState] =
this._prepDataForDeferredRestore(state);
// If we have a iniState with windows, that means that we have windows
// with app tabs to restore.
if (iniState.windows.length) {
// Move cookies over from the remaining state so that they're
// restored right away, and pinned tabs will load correctly.
iniState.cookies = remainingState.cookies;
delete remainingState.cookies;
state = iniState;
} else {
state = null;
}
if (remainingState.windows.length) {
LastSession.setState(remainingState);
}
Services.telemetry.keyedScalarAdd(
"browser.engagement.sessionrestore_interstitial",
"deferred_restore",
1
);
} else {
// Get the last deferred session in case the user still wants to
// restore it
LastSession.setState(state.lastSessionState);
let restoreAsCrashed = ss.willRestoreAsCrashed();
if (restoreAsCrashed) {
this._recentCrashes =
((state.session && state.session.recentCrashes) || 0) + 1;
// _needsRestorePage will record sessionrestore_interstitial,
// including the specific reason we decided we needed to show
// about:sessionrestore, if that's what we do.
if (this._needsRestorePage(state, this._recentCrashes)) {
// replace the crashed session with a restore-page-only session
let url = "about:sessionrestore";
let formdata = { id: { sessionData: state }, url };
let entry = {
url,
triggeringPrincipal_base64:
lazy.E10SUtils.SERIALIZED_SYSTEMPRINCIPAL,
};
state = { windows: [{ tabs: [{ entries: [entry], formdata }] }] };
} else if (
this._hasSingleTabWithURL(state.windows, "about:welcomeback")
) {
Services.telemetry.keyedScalarAdd(
"browser.engagement.sessionrestore_interstitial",
"shown_only_about_welcomeback",
1
);
// On a single about:welcomeback URL that crashed, replace about:welcomeback
// with about:sessionrestore, to make clear to the user that we crashed.
state.windows[0].tabs[0].entries[0].url = "about:sessionrestore";
state.windows[0].tabs[0].entries[0].triggeringPrincipal_base64 =
lazy.E10SUtils.SERIALIZED_SYSTEMPRINCIPAL;
} else {
restoreAsCrashed = false;
}
}
// Floorp injections
if (
state.windows[0] == undefined
) {
let lastSessionWindows = state._closedWindows;
let closedTime = lastSessionWindows[0].closedAt;
for (let i = 0; i < lastSessionWindows.length; i++) {
let closedWindow = state._closedWindows[i];
let closedWindowTime = closedWindow.closedAt;
// If the last closed window is closed in +-1000, we will restore it
if (closedWindowTime > closedTime - 2000 && closedWindowTime < closedTime + 2000) {
state.windows.push(closedWindow);
// Remove the closed window from the closed windows
state._closedWindows.splice(i, 1);
}
}
}
// End of floorp injections
// If we didn't use about:sessionrestore, record that:
if (!restoreAsCrashed) {
Services.telemetry.keyedScalarAdd(
"browser.engagement.sessionrestore_interstitial",
"autorestore",
1
);
this._removeExplicitlyClosedTabs(state);
}
// Update the session start time using the restored session state.
this._updateSessionStartTime(state);
// Make sure that at least the first window doesn't have anything hidden.
delete state.windows[0].hidden;
// Since nothing is hidden in the first window, it cannot be a popup.
delete state.windows[0].isPopup;
// We don't want to minimize and then open a window at startup.
if (state.windows[0].sizemode == "minimized") {
state.windows[0].sizemode = "normal";
}
// clear any lastSessionWindowID attributes since those don't matter
// during normal restore
state.windows.forEach(function (aWindow) {
delete aWindow.__lastSessionWindowID;
});
}
// clear _maybeDontRestoreTabs because we have restored (or not)
// windows and so they don't matter
state?.windows?.forEach(win => delete win._maybeDontRestoreTabs);
state?._closedWindows?.forEach(win => delete win._maybeDontRestoreTabs);
} catch (ex) {
console.error(ex);
this._log.error("The session file is invalid: " + ex);
}
}
// at this point, we've as good as resumed the session, so we can
// clear the resume_session_once flag, if it's set
if (
!lazy.RunState.isQuitting &&
this._prefBranch.getBoolPref("sessionstore.resume_session_once")
) {
this._prefBranch.setBoolPref("sessionstore.resume_session_once", false);
}
TelemetryStopwatch.finish("FX_SESSION_RESTORE_STARTUP_INIT_SESSION_MS");
return state;
},
/**
* When initializing session, if we are restoring the last session at startup,
* close open tabs or close windows marked _maybeDontRestoreTabs (if they were closed
* by closing remaining tabs).
* See bug 490136
*/
_removeExplicitlyClosedTabs(state) {
// Don't restore tabs that has been explicitly closed
for (let i = 0; i < state.windows.length; ) {
const winData = state.windows[i];