forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsSHistory.cpp
1900 lines (1612 loc) · 59.2 KB
/
nsSHistory.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */
#include "nsSHistory.h"
#include <algorithm>
#include "nsContentUtils.h"
#include "nsCOMArray.h"
#include "nsComponentManagerUtils.h"
#include "nsDocShell.h"
#include "nsIContentViewer.h"
#include "nsIDocShell.h"
#include "nsDocShellLoadState.h"
#include "nsIDocShellTreeItem.h"
#include "nsILayoutHistoryState.h"
#include "nsIObserverService.h"
#include "nsISHEntry.h"
#include "nsISHistoryListener.h"
#include "nsIURI.h"
#include "nsIXULRuntime.h"
#include "nsNetUtil.h"
#include "nsSHEntry.h"
#include "SessionHistoryEntry.h"
#include "nsTArray.h"
#include "prsystem.h"
#include "mozilla/Attributes.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/LinkedList.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "nsIWebNavigation.h"
#include "nsDocShellLoadTypes.h"
#include "base/process.h"
using namespace mozilla;
using namespace mozilla::dom;
#define PREF_SHISTORY_SIZE "browser.sessionhistory.max_entries"
#define PREF_SHISTORY_MAX_TOTAL_VIEWERS \
"browser.sessionhistory.max_total_viewers"
#define CONTENT_VIEWER_TIMEOUT_SECONDS \
"browser.sessionhistory.contentViewerTimeout"
// Default this to time out unused content viewers after 30 minutes
#define CONTENT_VIEWER_TIMEOUT_SECONDS_DEFAULT (30 * 60)
static const char* kObservedPrefs[] = {
PREF_SHISTORY_SIZE, PREF_SHISTORY_MAX_TOTAL_VIEWERS, nullptr};
static int32_t gHistoryMaxSize = 50;
// List of all SHistory objects, used for content viewer cache eviction
static LinkedList<nsSHistory> gSHistoryList;
// Max viewers allowed total, across all SHistory objects - negative default
// means we will calculate how many viewers to cache based on total memory
int32_t nsSHistory::sHistoryMaxTotalViewers = -1;
// A counter that is used to be able to know the order in which
// entries were touched, so that we can evict older entries first.
static uint32_t gTouchCounter = 0;
LazyLogModule gSHistoryLog("nsSHistory");
#define LOG(format) MOZ_LOG(gSHistoryLog, mozilla::LogLevel::Debug, format)
extern mozilla::LazyLogModule gPageCacheLog;
// This macro makes it easier to print a log message which includes a URI's
// spec. Example use:
//
// nsIURI *uri = [...];
// LOG_SPEC(("The URI is %s.", _spec), uri);
//
#define LOG_SPEC(format, uri) \
PR_BEGIN_MACRO \
if (MOZ_LOG_TEST(gSHistoryLog, LogLevel::Debug)) { \
nsAutoCString _specStr("(null)"_ns); \
if (uri) { \
_specStr = uri->GetSpecOrDefault(); \
} \
const char* _spec = _specStr.get(); \
LOG(format); \
} \
PR_END_MACRO
// This macro makes it easy to log a message including an SHEntry's URI.
// For example:
//
// nsCOMPtr<nsISHEntry> shentry = [...];
// LOG_SHENTRY_SPEC(("shentry %p has uri %s.", shentry.get(), _spec), shentry);
//
#define LOG_SHENTRY_SPEC(format, shentry) \
PR_BEGIN_MACRO \
if (MOZ_LOG_TEST(gSHistoryLog, LogLevel::Debug)) { \
nsCOMPtr<nsIURI> uri = shentry->GetURI(); \
LOG_SPEC(format, uri); \
} \
PR_END_MACRO
// Iterates over all registered session history listeners.
#define ITERATE_LISTENERS(body) \
PR_BEGIN_MACRO { \
for (const nsWeakPtr& weakPtr : mListeners.EndLimitedRange()) { \
nsCOMPtr<nsISHistoryListener> listener = do_QueryReferent(weakPtr); \
if (listener) { \
body \
} \
} \
} \
PR_END_MACRO
// Calls a given method on all registered session history listeners.
#define NOTIFY_LISTENERS(method, args) \
ITERATE_LISTENERS(listener->method args;);
// Calls a given method on all registered session history listeners.
// Listeners may return 'false' to cancel an action so make sure that we
// set the return value to 'false' if one of the listeners wants to cancel.
#define NOTIFY_LISTENERS_CANCELABLE(method, retval, args) \
PR_BEGIN_MACRO { \
bool canceled = false; \
retval = true; \
ITERATE_LISTENERS(listener->method args; \
if (!retval) { canceled = true; }); \
if (canceled) { \
retval = false; \
} \
} \
PR_END_MACRO
class SHistoryChangeNotifier {
public:
explicit SHistoryChangeNotifier(nsSHistory* aHistory) {
// If we're already in an update, the outermost change notifier will
// update browsing context in the destructor.
if (!aHistory->HasOngoingUpdate()) {
aHistory->SetHasOngoingUpdate(true);
mSHistory = aHistory;
mInitialIndex = aHistory->Index();
mInitialLength = aHistory->Length();
}
}
~SHistoryChangeNotifier() {
if (mSHistory) {
MOZ_ASSERT(mSHistory->HasOngoingUpdate());
mSHistory->SetHasOngoingUpdate(false);
if (mSHistory->GetBrowsingContext()) {
mSHistory->GetBrowsingContext()->SessionHistoryChanged(
mSHistory->Index() - mInitialIndex,
mSHistory->Length() - mInitialLength);
}
}
}
RefPtr<nsSHistory> mSHistory;
int32_t mInitialIndex;
int32_t mInitialLength;
};
enum HistCmd { HIST_CMD_GOTOINDEX, HIST_CMD_RELOAD };
class nsSHistoryObserver final : public nsIObserver {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
nsSHistoryObserver() {}
static void PrefChanged(const char* aPref, void* aSelf);
void PrefChanged(const char* aPref);
protected:
~nsSHistoryObserver() {}
};
StaticRefPtr<nsSHistoryObserver> gObserver;
NS_IMPL_ISUPPORTS(nsSHistoryObserver, nsIObserver)
// static
void nsSHistoryObserver::PrefChanged(const char* aPref, void* aSelf) {
static_cast<nsSHistoryObserver*>(aSelf)->PrefChanged(aPref);
}
void nsSHistoryObserver::PrefChanged(const char* aPref) {
nsSHistory::UpdatePrefs();
nsSHistory::GloballyEvictContentViewers();
}
NS_IMETHODIMP
nsSHistoryObserver::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
if (!strcmp(aTopic, "cacheservice:empty-cache") ||
!strcmp(aTopic, "memory-pressure")) {
nsSHistory::GloballyEvictAllContentViewers();
}
return NS_OK;
}
void nsSHistory::EvictContentViewerForEntry(nsISHEntry* aEntry) {
nsCOMPtr<nsIContentViewer> viewer = aEntry->GetContentViewer();
if (viewer) {
LOG_SHENTRY_SPEC(("Evicting content viewer 0x%p for "
"owning SHEntry 0x%p at %s.",
viewer.get(), aEntry, _spec),
aEntry);
// Drop the presentation state before destroying the viewer, so that
// document teardown is able to correctly persist the state.
NotifyListenersContentViewerEvicted(1);
aEntry->SetContentViewer(nullptr);
aEntry->SyncPresentationState();
viewer->Destroy();
}
// When dropping bfcache, we have to remove associated dynamic entries as
// well.
int32_t index = GetIndexOfEntry(aEntry);
if (index != -1) {
RemoveDynEntries(index, aEntry);
}
}
nsSHistory::nsSHistory(BrowsingContext* aRootBC)
: mRootBC(aRootBC),
mHasOngoingUpdate(false),
mIsRemote(false),
mIndex(-1),
mRequestedIndex(-1),
mRootDocShellID(aRootBC->GetHistoryID()) {
static bool sCalledStartup = false;
if (!sCalledStartup) {
Startup();
sCalledStartup = true;
}
// Add this new SHistory object to the list
gSHistoryList.insertBack(this);
// Init mHistoryTracker on setting mRootBC so we can bind its event
// target to the tabGroup.
nsPIDOMWindowOuter* win;
if (mRootBC && (win = mRootBC->GetDOMWindow())) {
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(win);
mHistoryTracker = mozilla::MakeUnique<HistoryTracker>(
this,
mozilla::Preferences::GetUint(CONTENT_VIEWER_TIMEOUT_SECONDS,
CONTENT_VIEWER_TIMEOUT_SECONDS_DEFAULT),
global->EventTargetFor(mozilla::TaskCategory::Other));
}
}
nsSHistory::~nsSHistory() {}
NS_IMPL_ADDREF(nsSHistory)
NS_IMPL_RELEASE(nsSHistory)
NS_INTERFACE_MAP_BEGIN(nsSHistory)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISHistory)
NS_INTERFACE_MAP_ENTRY(nsISHistory)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END
// static
uint32_t nsSHistory::CalcMaxTotalViewers() {
// This value allows tweaking how fast the allowed amount of content viewers
// grows with increasing amounts of memory. Larger values mean slower growth.
#ifdef ANDROID
# define MAX_TOTAL_VIEWERS_BIAS 15.9
#else
# define MAX_TOTAL_VIEWERS_BIAS 14
#endif
// Calculate an estimate of how many ContentViewers we should cache based
// on RAM. This assumes that the average ContentViewer is 4MB (conservative)
// and caps the max at 8 ContentViewers
//
// TODO: Should we split the cache memory betw. ContentViewer caching and
// nsCacheService?
//
// RAM | ContentViewers | on Android
// -------------------------------------
// 32 Mb 0 0
// 64 Mb 1 0
// 128 Mb 2 0
// 256 Mb 3 1
// 512 Mb 5 2
// 768 Mb 6 2
// 1024 Mb 8 3
// 2048 Mb 8 5
// 3072 Mb 8 7
// 4096 Mb 8 8
uint64_t bytes = PR_GetPhysicalMemorySize();
if (bytes == 0) {
return 0;
}
// Conversion from unsigned int64_t to double doesn't work on all platforms.
// We need to truncate the value at INT64_MAX to make sure we don't
// overflow.
if (bytes > INT64_MAX) {
bytes = INT64_MAX;
}
double kBytesD = (double)(bytes >> 10);
// This is essentially the same calculation as for nsCacheService,
// except that we divide the final memory calculation by 4, since
// we assume each ContentViewer takes on average 4MB
uint32_t viewers = 0;
double x = std::log(kBytesD) / std::log(2.0) - MAX_TOTAL_VIEWERS_BIAS;
if (x > 0) {
viewers = (uint32_t)(x * x - x + 2.001); // add .001 for rounding
viewers /= 4;
}
// Cap it off at 8 max
if (viewers > 8) {
viewers = 8;
}
return viewers;
}
// static
void nsSHistory::UpdatePrefs() {
Preferences::GetInt(PREF_SHISTORY_SIZE, &gHistoryMaxSize);
if (mozilla::SessionHistoryInParent()) {
sHistoryMaxTotalViewers = 0;
return;
}
Preferences::GetInt(PREF_SHISTORY_MAX_TOTAL_VIEWERS,
&sHistoryMaxTotalViewers);
// If the pref is negative, that means we calculate how many viewers
// we think we should cache, based on total memory
if (sHistoryMaxTotalViewers < 0) {
sHistoryMaxTotalViewers = CalcMaxTotalViewers();
}
}
// static
nsresult nsSHistory::Startup() {
UpdatePrefs();
// The goal of this is to unbreak users who have inadvertently set their
// session history size to less than the default value.
int32_t defaultHistoryMaxSize =
Preferences::GetInt(PREF_SHISTORY_SIZE, 50, PrefValueKind::Default);
if (gHistoryMaxSize < defaultHistoryMaxSize) {
gHistoryMaxSize = defaultHistoryMaxSize;
}
// Allow the user to override the max total number of cached viewers,
// but keep the per SHistory cached viewer limit constant
if (!gObserver) {
gObserver = new nsSHistoryObserver();
Preferences::RegisterCallbacks(nsSHistoryObserver::PrefChanged,
kObservedPrefs, gObserver.get());
nsCOMPtr<nsIObserverService> obsSvc =
mozilla::services::GetObserverService();
if (obsSvc) {
// Observe empty-cache notifications so tahat clearing the disk/memory
// cache will also evict all content viewers.
obsSvc->AddObserver(gObserver, "cacheservice:empty-cache", false);
// Same for memory-pressure notifications
obsSvc->AddObserver(gObserver, "memory-pressure", false);
}
}
return NS_OK;
}
// static
void nsSHistory::Shutdown() {
if (gObserver) {
Preferences::UnregisterCallbacks(nsSHistoryObserver::PrefChanged,
kObservedPrefs, gObserver.get());
nsCOMPtr<nsIObserverService> obsSvc =
mozilla::services::GetObserverService();
if (obsSvc) {
obsSvc->RemoveObserver(gObserver, "cacheservice:empty-cache");
obsSvc->RemoveObserver(gObserver, "memory-pressure");
}
gObserver = nullptr;
}
}
// static
already_AddRefed<nsISHEntry> nsSHistory::GetRootSHEntry(nsISHEntry* aEntry) {
nsCOMPtr<nsISHEntry> rootEntry = aEntry;
nsCOMPtr<nsISHEntry> result = nullptr;
while (rootEntry) {
result = rootEntry;
rootEntry = result->GetParent();
}
return result.forget();
}
// static
nsresult nsSHistory::WalkHistoryEntries(nsISHEntry* aRootEntry,
BrowsingContext* aBC,
WalkHistoryEntriesFunc aCallback,
void* aData) {
NS_ENSURE_TRUE(aRootEntry, NS_ERROR_FAILURE);
int32_t childCount = aRootEntry->GetChildCount();
for (int32_t i = 0; i < childCount; i++) {
nsCOMPtr<nsISHEntry> childEntry;
aRootEntry->GetChildAt(i, getter_AddRefs(childEntry));
if (!childEntry) {
// childEntry can be null for valid reasons, for example if the
// docshell at index i never loaded anything useful.
// Remember to clone also nulls in the child array (bug 464064).
aCallback(nullptr, nullptr, i, aData);
continue;
}
BrowsingContext* childBC = nullptr;
if (aBC) {
for (BrowsingContext* child : aBC->Children()) {
// If the SH pref is on and we are in the parent process, update
// canonical BC directly
bool foundChild = false;
if (mozilla::SessionHistoryInParent() && XRE_IsParentProcess()) {
if (child->Canonical()->HasHistoryEntry(childEntry)) {
childBC = child;
foundChild = true;
}
}
nsDocShell* docshell = static_cast<nsDocShell*>(child->GetDocShell());
if (docshell && docshell->HasHistoryEntry(childEntry)) {
childBC = docshell->GetBrowsingContext();
foundChild = true;
}
// XXX Simplify this once the old and new session history
// implementations don't run at the same time.
if (foundChild) {
break;
}
}
}
nsresult rv = aCallback(childEntry, childBC, i, aData);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
// callback data for WalkHistoryEntries
struct MOZ_STACK_CLASS CloneAndReplaceData {
CloneAndReplaceData(uint32_t aCloneID, nsISHEntry* aReplaceEntry,
bool aCloneChildren, nsISHEntry* aDestTreeParent)
: cloneID(aCloneID),
cloneChildren(aCloneChildren),
replaceEntry(aReplaceEntry),
destTreeParent(aDestTreeParent) {}
uint32_t cloneID;
bool cloneChildren;
nsISHEntry* replaceEntry;
nsISHEntry* destTreeParent;
nsCOMPtr<nsISHEntry> resultEntry;
};
nsresult nsSHistory::CloneAndReplaceChild(nsISHEntry* aEntry,
BrowsingContext* aOwnerBC,
int32_t aChildIndex, void* aData) {
nsCOMPtr<nsISHEntry> dest;
CloneAndReplaceData* data = static_cast<CloneAndReplaceData*>(aData);
uint32_t cloneID = data->cloneID;
nsISHEntry* replaceEntry = data->replaceEntry;
if (!aEntry) {
if (data->destTreeParent) {
data->destTreeParent->AddChild(nullptr, aChildIndex);
}
return NS_OK;
}
uint32_t srcID = aEntry->GetID();
nsresult rv = NS_OK;
if (srcID == cloneID) {
// Replace the entry
dest = replaceEntry;
} else {
// Clone the SHEntry...
rv = aEntry->Clone(getter_AddRefs(dest));
NS_ENSURE_SUCCESS(rv, rv);
}
dest->SetIsSubFrame(true);
if (srcID != cloneID || data->cloneChildren) {
// Walk the children
CloneAndReplaceData childData(cloneID, replaceEntry, data->cloneChildren,
dest);
rv = nsSHistory::WalkHistoryEntries(aEntry, aOwnerBC, CloneAndReplaceChild,
&childData);
NS_ENSURE_SUCCESS(rv, rv);
}
if (srcID != cloneID && aOwnerBC) {
nsSHistory::HandleEntriesToSwapInDocShell(aOwnerBC, aEntry, dest);
}
if (data->destTreeParent) {
data->destTreeParent->AddChild(dest, aChildIndex);
}
data->resultEntry = dest;
return rv;
}
// static
nsresult nsSHistory::CloneAndReplace(
nsISHEntry* aSrcEntry, BrowsingContext* aOwnerBC, uint32_t aCloneID,
nsISHEntry* aReplaceEntry, bool aCloneChildren, nsISHEntry** aDestEntry) {
NS_ENSURE_ARG_POINTER(aDestEntry);
NS_ENSURE_TRUE(aReplaceEntry, NS_ERROR_FAILURE);
CloneAndReplaceData data(aCloneID, aReplaceEntry, aCloneChildren, nullptr);
nsresult rv = CloneAndReplaceChild(aSrcEntry, aOwnerBC, 0, &data);
data.resultEntry.swap(*aDestEntry);
return rv;
}
// static
void nsSHistory::WalkContiguousEntries(
nsISHEntry* aEntry, const std::function<void(nsISHEntry*)>& aCallback) {
MOZ_ASSERT(aEntry);
nsCOMPtr<nsISHistory> shistory = aEntry->GetShistory();
if (!shistory) {
// If there is no session history in the entry, it means this is not a root
// entry. So, we can return from here.
return;
}
int32_t index = shistory->GetIndexOfEntry(aEntry);
int32_t count = shistory->GetCount();
nsCOMPtr<nsIURI> targetURI = aEntry->GetURI();
// First, call the callback on the input entry.
aCallback(aEntry);
// Walk backward to find the entries that have the same origin as the
// input entry.
for (int32_t i = index - 1; i >= 0; i--) {
RefPtr<nsISHEntry> entry;
shistory->GetEntryAtIndex(i, getter_AddRefs(entry));
if (entry) {
nsCOMPtr<nsIURI> uri = entry->GetURI();
if (NS_FAILED(nsContentUtils::GetSecurityManager()->CheckSameOriginURI(
targetURI, uri, false, false))) {
break;
}
aCallback(entry);
}
}
// Then, Walk forward.
for (int32_t i = index + 1; i < count; i++) {
RefPtr<nsISHEntry> entry;
shistory->GetEntryAtIndex(i, getter_AddRefs(entry));
if (entry) {
nsCOMPtr<nsIURI> uri = entry->GetURI();
if (NS_FAILED(nsContentUtils::GetSecurityManager()->CheckSameOriginURI(
targetURI, uri, false, false))) {
break;
}
aCallback(entry);
}
}
}
NS_IMETHODIMP
nsSHistory::AddChildSHEntryHelper(nsISHEntry* aCloneRef, nsISHEntry* aNewEntry,
BrowsingContext* aRootBC,
bool aCloneChildren) {
MOZ_ASSERT(aRootBC->IsTop());
/* You are currently in the rootDocShell.
* You will get here when a subframe has a new url
* to load and you have walked up the tree all the
* way to the top to clone the current SHEntry hierarchy
* and replace the subframe where a new url was loaded with
* a new entry.
*/
nsCOMPtr<nsISHEntry> child;
nsCOMPtr<nsISHEntry> currentHE;
int32_t index = mIndex;
if (index < 0) {
return NS_ERROR_FAILURE;
}
GetEntryAtIndex(index, getter_AddRefs(currentHE));
NS_ENSURE_TRUE(currentHE, NS_ERROR_FAILURE);
nsresult rv = NS_OK;
uint32_t cloneID = aCloneRef->GetID();
rv = nsSHistory::CloneAndReplace(currentHE, aRootBC, cloneID, aNewEntry,
aCloneChildren, getter_AddRefs(child));
if (NS_SUCCEEDED(rv)) {
rv = AddEntry(child, true);
if (NS_SUCCEEDED(rv)) {
child->SetDocshellID(aRootBC->GetHistoryID());
}
}
return rv;
}
nsresult nsSHistory::SetChildHistoryEntry(nsISHEntry* aEntry,
BrowsingContext* aBC,
int32_t aEntryIndex, void* aData) {
SwapEntriesData* data = static_cast<SwapEntriesData*>(aData);
if (!aBC || aBC == data->ignoreBC) {
return NS_OK;
}
nsISHEntry* destTreeRoot = data->destTreeRoot;
nsCOMPtr<nsISHEntry> destEntry;
if (data->destTreeParent) {
// aEntry is a clone of some child of destTreeParent, but since the
// trees aren't necessarily in sync, we'll have to locate it.
// Note that we could set aShell's entry to null if we don't find a
// corresponding entry under destTreeParent.
uint32_t targetID = aEntry->GetID();
// First look at the given index, since this is the common case.
nsCOMPtr<nsISHEntry> entry;
data->destTreeParent->GetChildAt(aEntryIndex, getter_AddRefs(entry));
if (entry && entry->GetID() == targetID) {
destEntry.swap(entry);
} else {
int32_t childCount;
data->destTreeParent->GetChildCount(&childCount);
for (int32_t i = 0; i < childCount; ++i) {
data->destTreeParent->GetChildAt(i, getter_AddRefs(entry));
if (!entry) {
continue;
}
if (entry->GetID() == targetID) {
destEntry.swap(entry);
break;
}
}
}
} else {
destEntry = destTreeRoot;
}
nsSHistory::HandleEntriesToSwapInDocShell(aBC, aEntry, destEntry);
// Now handle the children of aEntry.
SwapEntriesData childData = {data->ignoreBC, destTreeRoot, destEntry};
return nsSHistory::WalkHistoryEntries(aEntry, aBC, SetChildHistoryEntry,
&childData);
}
// static
void nsSHistory::HandleEntriesToSwapInDocShell(
mozilla::dom::BrowsingContext* aBC, nsISHEntry* aOldEntry,
nsISHEntry* aNewEntry) {
bool shPref = mozilla::SessionHistoryInParent();
if (aBC->IsInProcess() || !shPref) {
nsDocShell* docshell = static_cast<nsDocShell*>(aBC->GetDocShell());
if (docshell) {
docshell->SwapHistoryEntries(aOldEntry, aNewEntry);
}
} else {
// FIXME Bug 1633988: Need to update entries?
}
// XXX Simplify this once the old and new session history implementations
// don't run at the same time.
if (shPref && XRE_IsParentProcess()) {
aBC->Canonical()->SwapHistoryEntries(aOldEntry, aNewEntry);
}
}
void nsSHistory::UpdateRootBrowsingContextState() {
if (mRootBC) {
bool sameDocument = IsEmptyOrHasEntriesForSingleTopLevelPage();
if (sameDocument != mRootBC->GetIsSingleToplevelInHistory()) {
// If the browsing context is discarded then its session history is
// invalid and will go away.
Unused << mRootBC->SetIsSingleToplevelInHistory(sameDocument);
}
}
}
NS_IMETHODIMP
nsSHistory::AddToRootSessionHistory(bool aCloneChildren, nsISHEntry* aOSHE,
BrowsingContext* aRootBC,
nsISHEntry* aEntry, uint32_t aLoadType,
bool aShouldPersist,
Maybe<int32_t>* aPreviousEntryIndex,
Maybe<int32_t>* aLoadedEntryIndex) {
MOZ_ASSERT(aRootBC->IsTop());
nsresult rv = NS_OK;
// If we need to clone our children onto the new session
// history entry, do so now.
if (aCloneChildren && aOSHE) {
uint32_t cloneID = aOSHE->GetID();
nsCOMPtr<nsISHEntry> newEntry;
nsSHistory::CloneAndReplace(aOSHE, aRootBC, cloneID, aEntry, true,
getter_AddRefs(newEntry));
NS_ASSERTION(aEntry == newEntry,
"The new session history should be in the new entry");
}
// This is the root docshell
bool addToSHistory = !LOAD_TYPE_HAS_FLAGS(
aLoadType, nsIWebNavigation::LOAD_FLAGS_REPLACE_HISTORY);
if (!addToSHistory) {
// Replace current entry in session history; If the requested index is
// valid, it indicates the loading was triggered by a history load, and
// we should replace the entry at requested index instead.
int32_t index = GetIndexForReplace();
// Replace the current entry with the new entry
if (index >= 0) {
rv = ReplaceEntry(index, aEntry);
} else {
// If we're trying to replace an inexistant shistory entry, append.
addToSHistory = true;
}
}
if (addToSHistory) {
// Add to session history
*aPreviousEntryIndex = Some(mIndex);
rv = AddEntry(aEntry, aShouldPersist);
*aLoadedEntryIndex = Some(mIndex);
MOZ_LOG(gPageCacheLog, LogLevel::Verbose,
("Previous index: %d, Loaded index: %d",
aPreviousEntryIndex->value(), aLoadedEntryIndex->value()));
}
if (NS_SUCCEEDED(rv)) {
aEntry->SetDocshellID(aRootBC->GetHistoryID());
}
return rv;
}
/* Add an entry to the History list at mIndex and
* increment the index to point to the new entry
*/
NS_IMETHODIMP
nsSHistory::AddEntry(nsISHEntry* aSHEntry, bool aPersist) {
NS_ENSURE_ARG(aSHEntry);
nsCOMPtr<nsISHistory> shistoryOfEntry = aSHEntry->GetShistory();
if (shistoryOfEntry && shistoryOfEntry != this) {
NS_WARNING(
"The entry has been associated to another nsISHistory instance. "
"Try nsISHEntry.clone() and nsISHEntry.abandonBFCacheEntry() "
"first if you're copying an entry from another nsISHistory.");
return NS_ERROR_FAILURE;
}
aSHEntry->SetShistory(this);
// If we have a root docshell, update the docshell id of the root shentry to
// match the id of that docshell
if (mRootBC) {
aSHEntry->SetDocshellID(mRootDocShellID);
}
if (mIndex >= 0) {
MOZ_ASSERT(mIndex < Length(), "Index out of range!");
if (mIndex >= Length()) {
return NS_ERROR_FAILURE;
}
if (mEntries[mIndex] && !mEntries[mIndex]->GetPersist()) {
NOTIFY_LISTENERS(OnHistoryReplaceEntry, ());
aSHEntry->SetPersist(aPersist);
mEntries[mIndex] = aSHEntry;
UpdateRootBrowsingContextState();
return NS_OK;
}
}
SHistoryChangeNotifier change(this);
nsCOMPtr<nsIURI> uri = aSHEntry->GetURI();
NOTIFY_LISTENERS(OnHistoryNewEntry, (uri, mIndex));
// Remove all entries after the current one, add the new one, and set the
// new one as the current one.
MOZ_ASSERT(mIndex >= -1);
aSHEntry->SetPersist(aPersist);
mEntries.TruncateLength(mIndex + 1);
mEntries.AppendElement(aSHEntry);
mIndex++;
// Purge History list if it is too long
if (gHistoryMaxSize >= 0 && Length() > gHistoryMaxSize) {
PurgeHistory(Length() - gHistoryMaxSize);
}
UpdateRootBrowsingContextState();
return NS_OK;
}
void
nsSHistory::NotifyOnHistoryReplaceEntry() {
NOTIFY_LISTENERS(OnHistoryReplaceEntry, ());
}
/* Get size of the history list */
NS_IMETHODIMP
nsSHistory::GetCount(int32_t* aResult) {
MOZ_ASSERT(aResult, "null out param?");
*aResult = Length();
return NS_OK;
}
NS_IMETHODIMP
nsSHistory::GetIndex(int32_t* aResult) {
MOZ_ASSERT(aResult, "null out param?");
*aResult = mIndex;
return NS_OK;
}
NS_IMETHODIMP
nsSHistory::SetIndex(int32_t aIndex) {
if (aIndex < 0 || aIndex >= Length()) {
return NS_ERROR_FAILURE;
}
mIndex = aIndex;
return NS_OK;
}
/* Get the requestedIndex */
NS_IMETHODIMP
nsSHistory::GetRequestedIndex(int32_t* aResult) {
MOZ_ASSERT(aResult, "null out param?");
*aResult = mRequestedIndex;
return NS_OK;
}
NS_IMETHODIMP_(void)
nsSHistory::InternalSetRequestedIndex(int32_t aRequestedIndex) {
MOZ_ASSERT(aRequestedIndex >= -1 && aRequestedIndex < Length());
mRequestedIndex = aRequestedIndex;
}
NS_IMETHODIMP
nsSHistory::GetEntryAtIndex(int32_t aIndex, nsISHEntry** aResult) {
NS_ENSURE_ARG_POINTER(aResult);
if (aIndex < 0 || aIndex >= Length()) {
return NS_ERROR_FAILURE;
}
*aResult = mEntries[aIndex];
NS_ADDREF(*aResult);
return NS_OK;
}
NS_IMETHODIMP_(int32_t)
nsSHistory::GetIndexOfEntry(nsISHEntry* aSHEntry) {
for (int32_t i = 0; i < Length(); i++) {
if (aSHEntry == mEntries[i]) {
return i;
}
}
return -1;
}
#ifdef DEBUG
nsresult nsSHistory::PrintHistory() {
for (int32_t i = 0; i < Length(); i++) {
nsCOMPtr<nsISHEntry> entry = mEntries[i];
nsCOMPtr<nsILayoutHistoryState> layoutHistoryState =
entry->GetLayoutHistoryState();
nsCOMPtr<nsIURI> uri = entry->GetURI();
nsString title;
entry->GetTitle(title);
# if 0
nsAutoCString url;
if (uri) {
uri->GetSpec(url);
}
printf("**** SH Entry #%d: %x\n", i, entry.get());
printf("\t\t URL = %s\n", url.get());
printf("\t\t Title = %s\n", NS_LossyConvertUTF16toASCII(title).get());
printf("\t\t layout History Data = %x\n", layoutHistoryState.get());
# endif
}
return NS_OK;
}
#endif
void nsSHistory::WindowIndices(int32_t aIndex, int32_t* aOutStartIndex,
int32_t* aOutEndIndex) {
*aOutStartIndex = std::max(0, aIndex - nsSHistory::VIEWER_WINDOW);
*aOutEndIndex = std::min(Length() - 1, aIndex + nsSHistory::VIEWER_WINDOW);
}
NS_IMETHODIMP
nsSHistory::PurgeHistory(int32_t aNumEntries) {
if (Length() <= 0 || aNumEntries <= 0) {
return NS_ERROR_FAILURE;
}
SHistoryChangeNotifier change(this);
aNumEntries = std::min(aNumEntries, Length());
NOTIFY_LISTENERS(OnHistoryPurge, ());
// Remove the first `aNumEntries` entries.
mEntries.RemoveElementsAt(0, aNumEntries);
// Adjust the indices, but don't let them go below -1.
mIndex -= aNumEntries;
mIndex = std::max(mIndex, -1);
mRequestedIndex -= aNumEntries;
mRequestedIndex = std::max(mRequestedIndex, -1);
if (mRootBC && mRootBC->GetDocShell()) {
mRootBC->GetDocShell()->HistoryPurged(aNumEntries);
}
UpdateRootBrowsingContextState();
return NS_OK;
}
NS_IMETHODIMP
nsSHistory::AddSHistoryListener(nsISHistoryListener* aListener) {
NS_ENSURE_ARG_POINTER(aListener);
// Check if the listener supports Weak Reference. This is a must.
// This listener functionality is used by embedders and we want to
// have the right ownership with who ever listens to SHistory
nsWeakPtr listener = do_GetWeakReference(aListener);
if (!listener) {
return NS_ERROR_FAILURE;
}
mListeners.AppendElementUnlessExists(listener);
return NS_OK;
}
void nsSHistory::NotifyListenersContentViewerEvicted(uint32_t aNumEvicted) {
NOTIFY_LISTENERS(OnContentViewerEvicted, (aNumEvicted));
}
NS_IMETHODIMP
nsSHistory::RemoveSHistoryListener(nsISHistoryListener* aListener) {
// Make sure the listener that wants to be removed is the
// one we have in store.
nsWeakPtr listener = do_GetWeakReference(aListener);
mListeners.RemoveElement(listener);
return NS_OK;
}
/* Replace an entry in the History list at a particular index.
* Do not update index or count.
*/
NS_IMETHODIMP
nsSHistory::ReplaceEntry(int32_t aIndex, nsISHEntry* aReplaceEntry) {
NS_ENSURE_ARG(aReplaceEntry);
if (aIndex < 0 || aIndex >= Length()) {
return NS_ERROR_FAILURE;