forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsSHistory.cpp
1819 lines (1552 loc) · 53.5 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: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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/. */
// Local Includes
#include "nsSHistory.h"
#include <algorithm>
// Helper Classes
#include "mozilla/Preferences.h"
// Interfaces Needed
#include "nsILayoutHistoryState.h"
#include "nsIDocShell.h"
#include "nsIDocShellLoadInfo.h"
#include "nsISHContainer.h"
#include "nsIDocShellTreeItem.h"
#include "nsIDocShellTreeNode.h"
#include "nsIURI.h"
#include "nsIContentViewer.h"
#include "nsICacheService.h"
#include "nsIObserverService.h"
#include "prclist.h"
#include "mozilla/Services.h"
#include "nsTArray.h"
#include "nsCOMArray.h"
#include "nsDocShell.h"
#include "mozilla/Attributes.h"
#include "nsISHEntry.h"
#include "nsISHTransaction.h"
#include "nsISHistoryListener.h"
#include "nsComponentManagerUtils.h"
// For calculating max history entries and max cachable contentviewers
#include "prsystem.h"
#include "mozilla/MathAlgorithms.h"
using namespace mozilla;
#define PREF_SHISTORY_SIZE "browser.sessionhistory.max_entries"
#define PREF_SHISTORY_MAX_TOTAL_VIEWERS "browser.sessionhistory.max_total_viewers"
static const char* kObservedPrefs[] = {
PREF_SHISTORY_SIZE,
PREF_SHISTORY_MAX_TOTAL_VIEWERS,
nullptr
};
static int32_t gHistoryMaxSize = 50;
// Max viewers allowed per SHistory objects
static const int32_t gHistoryMaxViewers = 3;
// List of all SHistory objects, used for content viewer cache eviction
static PRCList 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;
#ifdef PR_LOGGING
static PRLogModuleInfo*
GetSHistoryLog()
{
static PRLogModuleInfo *sLog;
if (!sLog)
sLog = PR_NewLogModule("nsSHistory");
return sLog;
}
#define LOG(format) PR_LOG(GetSHistoryLog(), PR_LOG_DEBUG, format)
// 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 (PR_LOG_TEST(GetSHistoryLog(), PR_LOG_DEBUG)) { \
nsAutoCString _specStr(NS_LITERAL_CSTRING("(null)"));\
if (uri) { \
uri->GetSpec(_specStr); \
} \
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 (PR_LOG_TEST(GetSHistoryLog(), PR_LOG_DEBUG)) { \
nsCOMPtr<nsIURI> uri; \
shentry->GetURI(getter_AddRefs(uri)); \
LOG_SPEC(format, uri); \
} \
PR_END_MACRO
#else // !PR_LOGGING
#define LOG(format)
#define LOG_SPEC(format, uri)
#define LOG_SHENTRY_SPEC(format, shentry)
#endif // PR_LOGGING
// Iterates over all registered session history listeners.
#define ITERATE_LISTENERS(body) \
PR_BEGIN_MACRO \
{ \
nsAutoTObserverArray<nsWeakPtr, 2>::EndLimitedIterator \
iter(mListeners); \
while (iter.HasMore()) { \
nsCOMPtr<nsISHistoryListener> listener = \
do_QueryReferent(iter.GetNext()); \
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
enum HistCmd{
HIST_CMD_BACK,
HIST_CMD_FORWARD,
HIST_CMD_GOTOINDEX,
HIST_CMD_RELOAD
} ;
//*****************************************************************************
//*** nsSHistoryObserver
//*****************************************************************************
class nsSHistoryObserver MOZ_FINAL : public nsIObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
nsSHistoryObserver() {}
protected:
~nsSHistoryObserver() {}
};
static nsSHistoryObserver* gObserver = nullptr;
NS_IMPL_ISUPPORTS1(nsSHistoryObserver, nsIObserver)
NS_IMETHODIMP
nsSHistoryObserver::Observe(nsISupports *aSubject, const char *aTopic,
const PRUnichar *aData)
{
if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
nsSHistory::UpdatePrefs();
nsSHistory::GloballyEvictContentViewers();
} else if (!strcmp(aTopic, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID) ||
!strcmp(aTopic, "memory-pressure")) {
nsSHistory::GloballyEvictAllContentViewers();
}
return NS_OK;
}
namespace {
already_AddRefed<nsIContentViewer>
GetContentViewerForTransaction(nsISHTransaction *aTrans)
{
nsCOMPtr<nsISHEntry> entry;
aTrans->GetSHEntry(getter_AddRefs(entry));
if (!entry) {
return nullptr;
}
nsCOMPtr<nsISHEntry> ownerEntry;
nsCOMPtr<nsIContentViewer> viewer;
entry->GetAnyContentViewer(getter_AddRefs(ownerEntry),
getter_AddRefs(viewer));
return viewer.forget();
}
void
EvictContentViewerForTransaction(nsISHTransaction *aTrans)
{
nsCOMPtr<nsISHEntry> entry;
aTrans->GetSHEntry(getter_AddRefs(entry));
nsCOMPtr<nsIContentViewer> viewer;
nsCOMPtr<nsISHEntry> ownerEntry;
entry->GetAnyContentViewer(getter_AddRefs(ownerEntry),
getter_AddRefs(viewer));
if (viewer) {
NS_ASSERTION(ownerEntry,
"Content viewer exists but its SHEntry is null");
LOG_SHENTRY_SPEC(("Evicting content viewer 0x%p for "
"owning SHEntry 0x%p at %s.",
viewer.get(), ownerEntry.get(), _spec), ownerEntry);
// Drop the presentation state before destroying the viewer, so that
// document teardown is able to correctly persist the state.
ownerEntry->SetContentViewer(nullptr);
ownerEntry->SyncPresentationState();
viewer->Destroy();
}
}
} // anonymous namespace
//*****************************************************************************
//*** nsSHistory: Object Management
//*****************************************************************************
nsSHistory::nsSHistory() : mListRoot(nullptr), mIndex(-1), mLength(0), mRequestedIndex(-1)
{
// Add this new SHistory object to the list
PR_APPEND_LINK(this, &gSHistoryList);
}
nsSHistory::~nsSHistory()
{
// Remove this SHistory object from the list
PR_REMOVE_LINK(this);
}
//*****************************************************************************
// nsSHistory: nsISupports
//*****************************************************************************
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(nsIWebNavigation)
NS_INTERFACE_MAP_ENTRY(nsISHistoryInternal)
NS_INTERFACE_MAP_END
//*****************************************************************************
// nsSHistory: nsISHistory
//*****************************************************************************
// static
uint32_t
nsSHistory::CalcMaxTotalViewers()
{
// 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
// -----------------------
// 32 Mb 0
// 64 Mb 1
// 128 Mb 2
// 256 Mb 3
// 512 Mb 5
// 1024 Mb 8
// 2048 Mb 8
// 4096 Mb 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) - 14;
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);
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::GetDefaultInt(PREF_SHISTORY_SIZE, 50);
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();
NS_ADDREF(gObserver);
Preferences::AddStrongObservers(gObserver, kObservedPrefs);
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,
NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID, false);
// Same for memory-pressure notifications
obsSvc->AddObserver(gObserver, "memory-pressure", false);
}
}
// Initialize the global list of all SHistory objects
PR_INIT_CLIST(&gSHistoryList);
return NS_OK;
}
// static
void
nsSHistory::Shutdown()
{
if (gObserver) {
Preferences::RemoveObservers(gObserver, kObservedPrefs);
nsCOMPtr<nsIObserverService> obsSvc =
mozilla::services::GetObserverService();
if (obsSvc) {
obsSvc->RemoveObserver(gObserver, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID);
obsSvc->RemoveObserver(gObserver, "memory-pressure");
}
NS_RELEASE(gObserver);
}
}
/* 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<nsISHTransaction> currentTxn;
if(mListRoot)
GetTransactionAtIndex(mIndex, getter_AddRefs(currentTxn));
bool currentPersist = true;
if(currentTxn)
currentTxn->GetPersist(¤tPersist);
if(!currentPersist)
{
NS_ENSURE_SUCCESS(currentTxn->SetSHEntry(aSHEntry),NS_ERROR_FAILURE);
currentTxn->SetPersist(aPersist);
return NS_OK;
}
nsCOMPtr<nsISHTransaction> txn(do_CreateInstance(NS_SHTRANSACTION_CONTRACTID));
NS_ENSURE_TRUE(txn, NS_ERROR_FAILURE);
nsCOMPtr<nsIURI> uri;
int32_t currentIndex = mIndex;
aSHEntry->GetURI(getter_AddRefs(uri));
NOTIFY_LISTENERS(OnHistoryNewEntry, (uri));
// If a listener has changed mIndex, we need to get currentTxn again,
// otherwise we'll be left at an inconsistent state (see bug 320742)
if (currentIndex != mIndex) {
GetTransactionAtIndex(mIndex, getter_AddRefs(currentTxn));
}
// Set the ShEntry and parent for the transaction. setting the
// parent will properly set the parent child relationship
txn->SetPersist(aPersist);
NS_ENSURE_SUCCESS(txn->Create(aSHEntry, currentTxn), NS_ERROR_FAILURE);
// A little tricky math here... Basically when adding an object regardless of
// what the length was before, it should always be set back to the current and
// lop off the forward.
mLength = (++mIndex + 1);
// If this is the very first transaction, initialize the list
if(!mListRoot)
mListRoot = txn;
// Purge History list if it is too long
if ((gHistoryMaxSize >= 0) && (mLength > gHistoryMaxSize))
PurgeHistory(mLength-gHistoryMaxSize);
RemoveDynEntries(mIndex - 1, mIndex);
return NS_OK;
}
/* Get size of the history list */
NS_IMETHODIMP
nsSHistory::GetCount(int32_t * aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
*aResult = mLength;
return NS_OK;
}
/* Get index of the history list */
NS_IMETHODIMP
nsSHistory::GetIndex(int32_t * aResult)
{
NS_PRECONDITION(aResult, "null out param?");
*aResult = mIndex;
return NS_OK;
}
/* Get the requestedIndex */
NS_IMETHODIMP
nsSHistory::GetRequestedIndex(int32_t * aResult)
{
NS_PRECONDITION(aResult, "null out param?");
*aResult = mRequestedIndex;
return NS_OK;
}
/* Get the entry at a given index */
NS_IMETHODIMP
nsSHistory::GetEntryAtIndex(int32_t aIndex, bool aModifyIndex, nsISHEntry** aResult)
{
nsresult rv;
nsCOMPtr<nsISHTransaction> txn;
/* GetTransactionAtIndex ensures aResult is valid and validates aIndex */
rv = GetTransactionAtIndex(aIndex, getter_AddRefs(txn));
if (NS_SUCCEEDED(rv) && txn) {
//Get the Entry from the transaction
rv = txn->GetSHEntry(aResult);
if (NS_SUCCEEDED(rv) && (*aResult)) {
// Set mIndex to the requested index, if asked to do so..
if (aModifyIndex) {
mIndex = aIndex;
}
} //entry
} //Transaction
return rv;
}
/* Get the transaction at a given index */
NS_IMETHODIMP
nsSHistory::GetTransactionAtIndex(int32_t aIndex, nsISHTransaction ** aResult)
{
nsresult rv;
NS_ENSURE_ARG_POINTER(aResult);
if ((mLength <= 0) || (aIndex < 0) || (aIndex >= mLength))
return NS_ERROR_FAILURE;
if (!mListRoot)
return NS_ERROR_FAILURE;
if (aIndex == 0)
{
*aResult = mListRoot;
NS_ADDREF(*aResult);
return NS_OK;
}
int32_t cnt=0;
nsCOMPtr<nsISHTransaction> tempPtr;
rv = GetRootTransaction(getter_AddRefs(tempPtr));
if (NS_FAILED(rv) || !tempPtr)
return NS_ERROR_FAILURE;
while(1) {
nsCOMPtr<nsISHTransaction> ptr;
rv = tempPtr->GetNext(getter_AddRefs(ptr));
if (NS_SUCCEEDED(rv) && ptr) {
cnt++;
if (cnt == aIndex) {
*aResult = ptr;
NS_ADDREF(*aResult);
break;
}
else {
tempPtr = ptr;
continue;
}
} //NS_SUCCEEDED
else
return NS_ERROR_FAILURE;
} // while
return NS_OK;
}
#ifdef DEBUG
nsresult
nsSHistory::PrintHistory()
{
nsCOMPtr<nsISHTransaction> txn;
int32_t index = 0;
nsresult rv;
if (!mListRoot)
return NS_ERROR_FAILURE;
txn = mListRoot;
while (1) {
if (!txn)
break;
nsCOMPtr<nsISHEntry> entry;
rv = txn->GetSHEntry(getter_AddRefs(entry));
if (NS_FAILED(rv) && !entry)
return NS_ERROR_FAILURE;
nsCOMPtr<nsILayoutHistoryState> layoutHistoryState;
nsCOMPtr<nsIURI> uri;
nsXPIDLString title;
entry->GetLayoutHistoryState(getter_AddRefs(layoutHistoryState));
entry->GetURI(getter_AddRefs(uri));
entry->GetTitle(getter_Copies(title));
#if 0
nsAutoCString url;
if (uri)
uri->GetSpec(url);
printf("**** SH Transaction #%d, Entry = %x\n", index, 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
nsCOMPtr<nsISHTransaction> next;
rv = txn->GetNext(getter_AddRefs(next));
if (NS_SUCCEEDED(rv) && next) {
txn = next;
index++;
continue;
}
else
break;
}
return NS_OK;
}
#endif
NS_IMETHODIMP
nsSHistory::GetRootTransaction(nsISHTransaction ** aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
*aResult=mListRoot;
NS_IF_ADDREF(*aResult);
return NS_OK;
}
/* Get the max size of the history list */
NS_IMETHODIMP
nsSHistory::GetMaxLength(int32_t * aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
*aResult = gHistoryMaxSize;
return NS_OK;
}
/* Set the max size of the history list */
NS_IMETHODIMP
nsSHistory::SetMaxLength(int32_t aMaxSize)
{
if (aMaxSize < 0)
return NS_ERROR_ILLEGAL_VALUE;
gHistoryMaxSize = aMaxSize;
if (mLength > aMaxSize)
PurgeHistory(mLength-aMaxSize);
return NS_OK;
}
NS_IMETHODIMP
nsSHistory::PurgeHistory(int32_t aEntries)
{
if (mLength <= 0 || aEntries <= 0)
return NS_ERROR_FAILURE;
aEntries = std::min(aEntries, mLength);
bool purgeHistory = true;
NOTIFY_LISTENERS_CANCELABLE(OnHistoryPurge, purgeHistory,
(aEntries, &purgeHistory));
if (!purgeHistory) {
// Listener asked us not to purge
return NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA;
}
int32_t cnt = 0;
while (cnt < aEntries) {
nsCOMPtr<nsISHTransaction> nextTxn;
if (mListRoot) {
mListRoot->GetNext(getter_AddRefs(nextTxn));
mListRoot->SetNext(nullptr);
}
mListRoot = nextTxn;
if (mListRoot) {
mListRoot->SetPrev(nullptr);
}
cnt++;
}
mLength -= cnt;
mIndex -= cnt;
// Now if we were not at the end of the history, mIndex could have
// become far too negative. If so, just set it to -1.
if (mIndex < -1) {
mIndex = -1;
}
if (mRootDocShell)
mRootDocShell->HistoryPurged(cnt);
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;
return mListeners.AppendElementUnlessExists(listener) ?
NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
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);
nsresult rv;
nsCOMPtr<nsISHTransaction> currentTxn;
if (!mListRoot) // Session History is not initialised.
return NS_ERROR_FAILURE;
rv = GetTransactionAtIndex(aIndex, getter_AddRefs(currentTxn));
if(currentTxn)
{
// Set the replacement entry in the transaction
rv = currentTxn->SetSHEntry(aReplaceEntry);
rv = currentTxn->SetPersist(true);
}
return rv;
}
NS_IMETHODIMP
nsSHistory::NotifyOnHistoryReload(nsIURI* aReloadURI, uint32_t aReloadFlags,
bool* aCanReload)
{
NOTIFY_LISTENERS_CANCELABLE(OnHistoryReload, *aCanReload,
(aReloadURI, aReloadFlags, aCanReload));
return NS_OK;
}
NS_IMETHODIMP
nsSHistory::EvictOutOfRangeContentViewers(int32_t aIndex)
{
// Check our per SHistory object limit in the currently navigated SHistory
EvictOutOfRangeWindowContentViewers(aIndex);
// Check our total limit across all SHistory objects
GloballyEvictContentViewers();
return NS_OK;
}
NS_IMETHODIMP
nsSHistory::EvictAllContentViewers()
{
// XXXbz we don't actually do a good job of evicting things as we should, so
// we might have viewers quite far from mIndex. So just evict everything.
nsCOMPtr<nsISHTransaction> trans = mListRoot;
while (trans) {
EvictContentViewerForTransaction(trans);
nsISHTransaction *temp = trans;
temp->GetNext(getter_AddRefs(trans));
}
return NS_OK;
}
//*****************************************************************************
// nsSHistory: nsIWebNavigation
//*****************************************************************************
NS_IMETHODIMP
nsSHistory::GetCanGoBack(bool * aCanGoBack)
{
NS_ENSURE_ARG_POINTER(aCanGoBack);
*aCanGoBack = false;
int32_t index = -1;
NS_ENSURE_SUCCESS(GetIndex(&index), NS_ERROR_FAILURE);
if(index > 0)
*aCanGoBack = true;
return NS_OK;
}
NS_IMETHODIMP
nsSHistory::GetCanGoForward(bool * aCanGoForward)
{
NS_ENSURE_ARG_POINTER(aCanGoForward);
*aCanGoForward = false;
int32_t index = -1;
int32_t count = -1;
NS_ENSURE_SUCCESS(GetIndex(&index), NS_ERROR_FAILURE);
NS_ENSURE_SUCCESS(GetCount(&count), NS_ERROR_FAILURE);
if((index >= 0) && (index < (count - 1)))
*aCanGoForward = true;
return NS_OK;
}
NS_IMETHODIMP
nsSHistory::GoBack()
{
bool canGoBack = false;
GetCanGoBack(&canGoBack);
if (!canGoBack) // Can't go back
return NS_ERROR_UNEXPECTED;
return LoadEntry(mIndex-1, nsIDocShellLoadInfo::loadHistory, HIST_CMD_BACK);
}
NS_IMETHODIMP
nsSHistory::GoForward()
{
bool canGoForward = false;
GetCanGoForward(&canGoForward);
if (!canGoForward) // Can't go forward
return NS_ERROR_UNEXPECTED;
return LoadEntry(mIndex+1, nsIDocShellLoadInfo::loadHistory, HIST_CMD_FORWARD);
}
NS_IMETHODIMP
nsSHistory::Reload(uint32_t aReloadFlags)
{
nsDocShellInfoLoadType loadType;
if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY &&
aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE)
{
loadType = nsIDocShellLoadInfo::loadReloadBypassProxyAndCache;
}
else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY)
{
loadType = nsIDocShellLoadInfo::loadReloadBypassProxy;
}
else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE)
{
loadType = nsIDocShellLoadInfo::loadReloadBypassCache;
}
else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_CHARSET_CHANGE)
{
loadType = nsIDocShellLoadInfo::loadReloadCharsetChange;
}
else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_ALLOW_MIXED_CONTENT)
{
loadType = nsIDocShellLoadInfo::loadMixedContent;
}
else
{
loadType = nsIDocShellLoadInfo::loadReloadNormal;
}
// We are reloading. Send Reload notifications.
// nsDocShellLoadFlagType is not public, where as nsIWebNavigation
// is public. So send the reload notifications with the
// nsIWebNavigation flags.
bool canNavigate = true;
nsCOMPtr<nsIURI> currentURI;
GetCurrentURI(getter_AddRefs(currentURI));
NOTIFY_LISTENERS_CANCELABLE(OnHistoryReload, canNavigate,
(currentURI, aReloadFlags, &canNavigate));
if (!canNavigate)
return NS_OK;
return LoadEntry(mIndex, loadType, HIST_CMD_RELOAD);
}
NS_IMETHODIMP
nsSHistory::ReloadCurrentEntry()
{
// Notify listeners
bool canNavigate = true;
nsCOMPtr<nsIURI> currentURI;
GetCurrentURI(getter_AddRefs(currentURI));
NOTIFY_LISTENERS_CANCELABLE(OnHistoryGotoIndex, canNavigate,
(mIndex, currentURI, &canNavigate));
if (!canNavigate)
return NS_OK;
return LoadEntry(mIndex, nsIDocShellLoadInfo::loadHistory, HIST_CMD_RELOAD);
}
void
nsSHistory::EvictOutOfRangeWindowContentViewers(int32_t aIndex)
{
// XXX rename method to EvictContentViewersExceptAroundIndex, or something.
// We need to release all content viewers that are no longer in the range
//
// aIndex - gHistoryMaxViewers to aIndex + gHistoryMaxViewers
//
// to ensure that this SHistory object isn't responsible for more than
// gHistoryMaxViewers content viewers. But our job is complicated by the
// fact that two transactions which are related by either hash navigations or
// history.pushState will have the same content viewer.
//
// To illustrate the issue, suppose gHistoryMaxViewers = 3 and we have four
// linked transactions in our history. Suppose we then add a new content
// viewer and call into this function. So the history looks like:
//
// A A A A B
// + *
//
// where the letters are content viewers and + and * denote the beginning and
// end of the range aIndex +/- gHistoryMaxViewers.
//
// Although one copy of the content viewer A exists outside the range, we
// don't want to evict A, because it has other copies in range!
//
// We therefore adjust our eviction strategy to read:
//
// Evict each content viewer outside the range aIndex -/+
// gHistoryMaxViewers, unless that content viewer also appears within the
// range.
//
// (Note that it's entirely legal to have two copies of one content viewer
// separated by a different content viewer -- call pushState twice, go back
// once, and refresh -- so we can't rely on identical viewers only appearing
// adjacent to one another.)
if (aIndex < 0) {
return;
}
NS_ASSERTION(aIndex < mLength, "aIndex is out of range");
if (aIndex >= mLength) {
return;
}
// Calculate the range that's safe from eviction.
int32_t startSafeIndex = std::max(0, aIndex - gHistoryMaxViewers);
int32_t endSafeIndex = std::min(mLength, aIndex + gHistoryMaxViewers);
LOG(("EvictOutOfRangeWindowContentViewers(index=%d), "
"mLength=%d. Safe range [%d, %d]",
aIndex, mLength, startSafeIndex, endSafeIndex));
// The content viewers in range aIndex -/+ gHistoryMaxViewers will not be
// evicted. Collect a set of them so we don't accidentally evict one of them
// if it appears outside this range.
nsCOMArray<nsIContentViewer> safeViewers;
nsCOMPtr<nsISHTransaction> trans;
GetTransactionAtIndex(startSafeIndex, getter_AddRefs(trans));
for (int32_t i = startSafeIndex; trans && i <= endSafeIndex; i++) {
nsCOMPtr<nsIContentViewer> viewer = GetContentViewerForTransaction(trans);
safeViewers.AppendObject(viewer);
nsISHTransaction *temp = trans;
temp->GetNext(getter_AddRefs(trans));
}
// Walk the SHistory list and evict any content viewers that aren't safe.
GetTransactionAtIndex(0, getter_AddRefs(trans));
while (trans) {
nsCOMPtr<nsIContentViewer> viewer = GetContentViewerForTransaction(trans);
if (safeViewers.IndexOf(viewer) == -1) {
EvictContentViewerForTransaction(trans);
}
nsISHTransaction *temp = trans;
temp->GetNext(getter_AddRefs(trans));
}
}
namespace {
class TransactionAndDistance
{
public:
TransactionAndDistance(nsISHTransaction *aTrans, uint32_t aDist)
: mTransaction(aTrans)
, mDistance(aDist)
{
mViewer = GetContentViewerForTransaction(aTrans);
NS_ASSERTION(mViewer, "Transaction should have a content viewer");
nsCOMPtr<nsISHEntry> shentry;
mTransaction->GetSHEntry(getter_AddRefs(shentry));
nsCOMPtr<nsISHEntryInternal> shentryInternal = do_QueryInterface(shentry);
if (shentryInternal) {
shentryInternal->GetLastTouched(&mLastTouched);
} else {
NS_WARNING("Can't cast to nsISHEntryInternal?");