nsSHistory.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "nsSHistory.h"
  6. #include <algorithm>
  7. // Helper Classes
  8. #include "mozilla/Preferences.h"
  9. #include "mozilla/StaticPtr.h"
  10. // Interfaces Needed
  11. #include "nsILayoutHistoryState.h"
  12. #include "nsIDocShell.h"
  13. #include "nsIDocShellLoadInfo.h"
  14. #include "nsISHContainer.h"
  15. #include "nsIDocShellTreeItem.h"
  16. #include "nsIURI.h"
  17. #include "nsIContentViewer.h"
  18. #include "nsIObserverService.h"
  19. #include "prclist.h"
  20. #include "mozilla/Services.h"
  21. #include "nsTArray.h"
  22. #include "nsCOMArray.h"
  23. #include "nsDocShell.h"
  24. #include "mozilla/Attributes.h"
  25. #include "nsISHEntry.h"
  26. #include "nsISHTransaction.h"
  27. #include "nsISHistoryListener.h"
  28. #include "nsComponentManagerUtils.h"
  29. // For calculating max history entries and max cachable contentviewers
  30. #include "prsystem.h"
  31. #include "mozilla/MathAlgorithms.h"
  32. using namespace mozilla;
  33. #define PREF_SHISTORY_SIZE "browser.sessionhistory.max_entries"
  34. #define PREF_SHISTORY_MAX_TOTAL_VIEWERS "browser.sessionhistory.max_total_viewers"
  35. static const char* kObservedPrefs[] = {
  36. PREF_SHISTORY_SIZE,
  37. PREF_SHISTORY_MAX_TOTAL_VIEWERS,
  38. nullptr
  39. };
  40. static int32_t gHistoryMaxSize = 50;
  41. // Max viewers allowed per SHistory objects
  42. static const int32_t gHistoryMaxViewers = 3;
  43. // List of all SHistory objects, used for content viewer cache eviction
  44. static PRCList gSHistoryList;
  45. // Max viewers allowed total, across all SHistory objects - negative default
  46. // means we will calculate how many viewers to cache based on total memory
  47. int32_t nsSHistory::sHistoryMaxTotalViewers = -1;
  48. // A counter that is used to be able to know the order in which
  49. // entries were touched, so that we can evict older entries first.
  50. static uint32_t gTouchCounter = 0;
  51. static LazyLogModule gSHistoryLog("nsSHistory");
  52. #define LOG(format) MOZ_LOG(gSHistoryLog, mozilla::LogLevel::Debug, format)
  53. // This macro makes it easier to print a log message which includes a URI's
  54. // spec. Example use:
  55. //
  56. // nsIURI *uri = [...];
  57. // LOG_SPEC(("The URI is %s.", _spec), uri);
  58. //
  59. #define LOG_SPEC(format, uri) \
  60. PR_BEGIN_MACRO \
  61. if (MOZ_LOG_TEST(gSHistoryLog, LogLevel::Debug)) { \
  62. nsAutoCString _specStr(NS_LITERAL_CSTRING("(null)"));\
  63. if (uri) { \
  64. _specStr = uri->GetSpecOrDefault(); \
  65. } \
  66. const char* _spec = _specStr.get(); \
  67. LOG(format); \
  68. } \
  69. PR_END_MACRO
  70. // This macro makes it easy to log a message including an SHEntry's URI.
  71. // For example:
  72. //
  73. // nsCOMPtr<nsISHEntry> shentry = [...];
  74. // LOG_SHENTRY_SPEC(("shentry %p has uri %s.", shentry.get(), _spec), shentry);
  75. //
  76. #define LOG_SHENTRY_SPEC(format, shentry) \
  77. PR_BEGIN_MACRO \
  78. if (MOZ_LOG_TEST(gSHistoryLog, LogLevel::Debug)) { \
  79. nsCOMPtr<nsIURI> uri; \
  80. shentry->GetURI(getter_AddRefs(uri)); \
  81. LOG_SPEC(format, uri); \
  82. } \
  83. PR_END_MACRO
  84. // Iterates over all registered session history listeners.
  85. #define ITERATE_LISTENERS(body) \
  86. PR_BEGIN_MACRO \
  87. { \
  88. nsAutoTObserverArray<nsWeakPtr, 2>::EndLimitedIterator \
  89. iter(mListeners); \
  90. while (iter.HasMore()) { \
  91. nsCOMPtr<nsISHistoryListener> listener = \
  92. do_QueryReferent(iter.GetNext()); \
  93. if (listener) { \
  94. body \
  95. } \
  96. } \
  97. } \
  98. PR_END_MACRO
  99. // Calls a given method on all registered session history listeners.
  100. #define NOTIFY_LISTENERS(method, args) \
  101. ITERATE_LISTENERS( \
  102. listener->method args; \
  103. );
  104. // Calls a given method on all registered session history listeners.
  105. // Listeners may return 'false' to cancel an action so make sure that we
  106. // set the return value to 'false' if one of the listeners wants to cancel.
  107. #define NOTIFY_LISTENERS_CANCELABLE(method, retval, args) \
  108. PR_BEGIN_MACRO \
  109. { \
  110. bool canceled = false; \
  111. retval = true; \
  112. ITERATE_LISTENERS( \
  113. listener->method args; \
  114. if (!retval) { \
  115. canceled = true; \
  116. } \
  117. ); \
  118. if (canceled) { \
  119. retval = false; \
  120. } \
  121. } \
  122. PR_END_MACRO
  123. enum HistCmd
  124. {
  125. HIST_CMD_BACK,
  126. HIST_CMD_FORWARD,
  127. HIST_CMD_GOTOINDEX,
  128. HIST_CMD_RELOAD
  129. };
  130. class nsSHistoryObserver final : public nsIObserver
  131. {
  132. public:
  133. NS_DECL_ISUPPORTS
  134. NS_DECL_NSIOBSERVER
  135. nsSHistoryObserver() {}
  136. protected:
  137. ~nsSHistoryObserver() {}
  138. };
  139. StaticRefPtr<nsSHistoryObserver> gObserver;
  140. NS_IMPL_ISUPPORTS(nsSHistoryObserver, nsIObserver)
  141. NS_IMETHODIMP
  142. nsSHistoryObserver::Observe(nsISupports* aSubject, const char* aTopic,
  143. const char16_t* aData)
  144. {
  145. if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
  146. nsSHistory::UpdatePrefs();
  147. nsSHistory::GloballyEvictContentViewers();
  148. } else if (!strcmp(aTopic, "cacheservice:empty-cache") ||
  149. !strcmp(aTopic, "memory-pressure")) {
  150. nsSHistory::GloballyEvictAllContentViewers();
  151. }
  152. return NS_OK;
  153. }
  154. namespace {
  155. already_AddRefed<nsIContentViewer>
  156. GetContentViewerForTransaction(nsISHTransaction* aTrans)
  157. {
  158. nsCOMPtr<nsISHEntry> entry;
  159. aTrans->GetSHEntry(getter_AddRefs(entry));
  160. if (!entry) {
  161. return nullptr;
  162. }
  163. nsCOMPtr<nsISHEntry> ownerEntry;
  164. nsCOMPtr<nsIContentViewer> viewer;
  165. entry->GetAnyContentViewer(getter_AddRefs(ownerEntry),
  166. getter_AddRefs(viewer));
  167. return viewer.forget();
  168. }
  169. void
  170. EvictContentViewerForTransaction(nsISHTransaction* aTrans)
  171. {
  172. nsCOMPtr<nsISHEntry> entry;
  173. aTrans->GetSHEntry(getter_AddRefs(entry));
  174. nsCOMPtr<nsIContentViewer> viewer;
  175. nsCOMPtr<nsISHEntry> ownerEntry;
  176. entry->GetAnyContentViewer(getter_AddRefs(ownerEntry),
  177. getter_AddRefs(viewer));
  178. if (viewer) {
  179. NS_ASSERTION(ownerEntry, "Content viewer exists but its SHEntry is null");
  180. LOG_SHENTRY_SPEC(("Evicting content viewer 0x%p for "
  181. "owning SHEntry 0x%p at %s.",
  182. viewer.get(), ownerEntry.get(), _spec),
  183. ownerEntry);
  184. // Drop the presentation state before destroying the viewer, so that
  185. // document teardown is able to correctly persist the state.
  186. ownerEntry->SetContentViewer(nullptr);
  187. ownerEntry->SyncPresentationState();
  188. viewer->Destroy();
  189. }
  190. }
  191. } // namespace
  192. nsSHistory::nsSHistory()
  193. : mIndex(-1)
  194. , mLength(0)
  195. , mRequestedIndex(-1)
  196. , mIsPartial(false)
  197. , mGlobalIndexOffset(0)
  198. , mEntriesInFollowingPartialHistories(0)
  199. , mRootDocShell(nullptr)
  200. {
  201. // Add this new SHistory object to the list
  202. PR_APPEND_LINK(this, &gSHistoryList);
  203. }
  204. nsSHistory::~nsSHistory()
  205. {
  206. // Remove this SHistory object from the list
  207. PR_REMOVE_LINK(this);
  208. }
  209. NS_IMPL_ADDREF(nsSHistory)
  210. NS_IMPL_RELEASE(nsSHistory)
  211. NS_INTERFACE_MAP_BEGIN(nsSHistory)
  212. NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISHistory)
  213. NS_INTERFACE_MAP_ENTRY(nsISHistory)
  214. NS_INTERFACE_MAP_ENTRY(nsIWebNavigation)
  215. NS_INTERFACE_MAP_ENTRY(nsISHistoryInternal)
  216. NS_INTERFACE_MAP_END
  217. // static
  218. uint32_t
  219. nsSHistory::CalcMaxTotalViewers()
  220. {
  221. // Calculate an estimate of how many ContentViewers we should cache based
  222. // on RAM. This assumes that the average ContentViewer is 4MB (conservative)
  223. // and caps the max at 8 ContentViewers
  224. //
  225. // TODO: Should we split the cache memory betw. ContentViewer caching and
  226. // nsCacheService?
  227. //
  228. // RAM ContentViewers
  229. // -----------------------
  230. // 32 Mb 0
  231. // 64 Mb 1
  232. // 128 Mb 2
  233. // 256 Mb 3
  234. // 512 Mb 5
  235. // 1024 Mb 8
  236. // 2048 Mb 8
  237. // 4096 Mb 8
  238. uint64_t bytes = PR_GetPhysicalMemorySize();
  239. if (bytes == 0) {
  240. return 0;
  241. }
  242. // Conversion from unsigned int64_t to double doesn't work on all platforms.
  243. // We need to truncate the value at INT64_MAX to make sure we don't
  244. // overflow.
  245. if (bytes > INT64_MAX) {
  246. bytes = INT64_MAX;
  247. }
  248. double kBytesD = (double)(bytes >> 10);
  249. // This is essentially the same calculation as for nsCacheService,
  250. // except that we divide the final memory calculation by 4, since
  251. // we assume each ContentViewer takes on average 4MB
  252. uint32_t viewers = 0;
  253. double x = std::log(kBytesD) / std::log(2.0) - 14;
  254. if (x > 0) {
  255. viewers = (uint32_t)(x * x - x + 2.001); // add .001 for rounding
  256. viewers /= 4;
  257. }
  258. // Cap it off at 8 max
  259. if (viewers > 8) {
  260. viewers = 8;
  261. }
  262. return viewers;
  263. }
  264. // static
  265. void
  266. nsSHistory::UpdatePrefs()
  267. {
  268. Preferences::GetInt(PREF_SHISTORY_SIZE, &gHistoryMaxSize);
  269. Preferences::GetInt(PREF_SHISTORY_MAX_TOTAL_VIEWERS,
  270. &sHistoryMaxTotalViewers);
  271. // If the pref is negative, that means we calculate how many viewers
  272. // we think we should cache, based on total memory
  273. if (sHistoryMaxTotalViewers < 0) {
  274. sHistoryMaxTotalViewers = CalcMaxTotalViewers();
  275. }
  276. }
  277. // static
  278. nsresult
  279. nsSHistory::Startup()
  280. {
  281. UpdatePrefs();
  282. // The goal of this is to unbreak users who have inadvertently set their
  283. // session history size to less than the default value.
  284. int32_t defaultHistoryMaxSize =
  285. Preferences::GetDefaultInt(PREF_SHISTORY_SIZE, 50);
  286. if (gHistoryMaxSize < defaultHistoryMaxSize) {
  287. gHistoryMaxSize = defaultHistoryMaxSize;
  288. }
  289. // Allow the user to override the max total number of cached viewers,
  290. // but keep the per SHistory cached viewer limit constant
  291. if (!gObserver) {
  292. gObserver = new nsSHistoryObserver();
  293. Preferences::AddStrongObservers(gObserver, kObservedPrefs);
  294. nsCOMPtr<nsIObserverService> obsSvc =
  295. mozilla::services::GetObserverService();
  296. if (obsSvc) {
  297. // Observe empty-cache notifications so tahat clearing the disk/memory
  298. // cache will also evict all content viewers.
  299. obsSvc->AddObserver(gObserver, "cacheservice:empty-cache", false);
  300. // Same for memory-pressure notifications
  301. obsSvc->AddObserver(gObserver, "memory-pressure", false);
  302. }
  303. }
  304. // Initialize the global list of all SHistory objects
  305. PR_INIT_CLIST(&gSHistoryList);
  306. return NS_OK;
  307. }
  308. // static
  309. void
  310. nsSHistory::Shutdown()
  311. {
  312. if (gObserver) {
  313. Preferences::RemoveObservers(gObserver, kObservedPrefs);
  314. nsCOMPtr<nsIObserverService> obsSvc =
  315. mozilla::services::GetObserverService();
  316. if (obsSvc) {
  317. obsSvc->RemoveObserver(gObserver, "cacheservice:empty-cache");
  318. obsSvc->RemoveObserver(gObserver, "memory-pressure");
  319. }
  320. gObserver = nullptr;
  321. }
  322. }
  323. /* Add an entry to the History list at mIndex and
  324. * increment the index to point to the new entry
  325. */
  326. NS_IMETHODIMP
  327. nsSHistory::AddEntry(nsISHEntry* aSHEntry, bool aPersist)
  328. {
  329. NS_ENSURE_ARG(aSHEntry);
  330. nsCOMPtr<nsISHTransaction> currentTxn;
  331. if (mListRoot) {
  332. GetTransactionAtIndex(mIndex, getter_AddRefs(currentTxn));
  333. }
  334. bool currentPersist = true;
  335. if (currentTxn) {
  336. currentTxn->GetPersist(&currentPersist);
  337. }
  338. int32_t currentIndex = mIndex;
  339. if (!currentPersist) {
  340. NOTIFY_LISTENERS(OnHistoryReplaceEntry, (currentIndex));
  341. NS_ENSURE_SUCCESS(currentTxn->SetSHEntry(aSHEntry), NS_ERROR_FAILURE);
  342. currentTxn->SetPersist(aPersist);
  343. return NS_OK;
  344. }
  345. nsCOMPtr<nsISHTransaction> txn(
  346. do_CreateInstance(NS_SHTRANSACTION_CONTRACTID));
  347. NS_ENSURE_TRUE(txn, NS_ERROR_FAILURE);
  348. nsCOMPtr<nsIURI> uri;
  349. aSHEntry->GetURI(getter_AddRefs(uri));
  350. NOTIFY_LISTENERS(OnHistoryNewEntry, (uri, currentIndex));
  351. // If a listener has changed mIndex, we need to get currentTxn again,
  352. // otherwise we'll be left at an inconsistent state (see bug 320742)
  353. if (currentIndex != mIndex) {
  354. GetTransactionAtIndex(mIndex, getter_AddRefs(currentTxn));
  355. }
  356. // Set the ShEntry and parent for the transaction. setting the
  357. // parent will properly set the parent child relationship
  358. txn->SetPersist(aPersist);
  359. NS_ENSURE_SUCCESS(txn->Create(aSHEntry, currentTxn), NS_ERROR_FAILURE);
  360. // A little tricky math here... Basically when adding an object regardless of
  361. // what the length was before, it should always be set back to the current and
  362. // lop off the forward.
  363. mLength = (++mIndex + 1);
  364. NOTIFY_LISTENERS(OnLengthChange, (mLength));
  365. // Much like how mLength works above, when changing our entries, all following
  366. // partial histories should be purged, so we just reset the number to zero.
  367. mEntriesInFollowingPartialHistories = 0;
  368. // If this is the very first transaction, initialize the list
  369. if (!mListRoot) {
  370. mListRoot = txn;
  371. }
  372. // Purge History list if it is too long
  373. if (gHistoryMaxSize >= 0 && mLength > gHistoryMaxSize) {
  374. PurgeHistory(mLength - gHistoryMaxSize);
  375. }
  376. RemoveDynEntries(mIndex - 1, mIndex);
  377. return NS_OK;
  378. }
  379. NS_IMETHODIMP
  380. nsSHistory::GetIsPartial(bool* aResult)
  381. {
  382. NS_ENSURE_ARG_POINTER(aResult);
  383. *aResult = mIsPartial;
  384. return NS_OK;
  385. }
  386. /* Get size of the history list */
  387. NS_IMETHODIMP
  388. nsSHistory::GetCount(int32_t* aResult)
  389. {
  390. NS_ENSURE_ARG_POINTER(aResult);
  391. *aResult = mLength;
  392. return NS_OK;
  393. }
  394. NS_IMETHODIMP
  395. nsSHistory::GetGlobalCount(int32_t* aResult)
  396. {
  397. NS_ENSURE_ARG_POINTER(aResult);
  398. *aResult = mGlobalIndexOffset + mLength + mEntriesInFollowingPartialHistories;
  399. return NS_OK;
  400. }
  401. NS_IMETHODIMP
  402. nsSHistory::GetGlobalIndexOffset(int32_t* aResult)
  403. {
  404. NS_ENSURE_ARG_POINTER(aResult);
  405. *aResult = mGlobalIndexOffset;
  406. return NS_OK;
  407. }
  408. NS_IMETHODIMP
  409. nsSHistory::OnPartialSessionHistoryActive(int32_t aGlobalLength, int32_t aTargetIndex)
  410. {
  411. NS_ENSURE_TRUE(mIsPartial, NS_ERROR_UNEXPECTED);
  412. int32_t extraLength = aGlobalLength - mLength - mGlobalIndexOffset;
  413. NS_ENSURE_TRUE(extraLength >= 0, NS_ERROR_UNEXPECTED);
  414. if (extraLength != mEntriesInFollowingPartialHistories) {
  415. mEntriesInFollowingPartialHistories = extraLength;
  416. }
  417. if (mIndex == aTargetIndex) {
  418. // TODO When we finish OnPartialSessionHistoryDeactive, we'll need to active
  419. // the suspended document here.
  420. // Fire location change to update canGoBack / canGoForward.
  421. NS_DispatchToCurrentThread(NewRunnableMethod(static_cast<nsDocShell*>(mRootDocShell),
  422. &nsDocShell::FireDummyOnLocationChange));
  423. return NS_OK;
  424. }
  425. return LoadEntry(aTargetIndex, nsIDocShellLoadInfo::loadHistory,
  426. HIST_CMD_GOTOINDEX);
  427. }
  428. NS_IMETHODIMP
  429. nsSHistory::OnPartialSessionHistoryDeactive()
  430. {
  431. NS_ENSURE_TRUE(mIsPartial, NS_ERROR_UNEXPECTED);
  432. // TODO We need to suspend current document first. Much like what happens when
  433. // loading a new page. Move the ownership of the document to nsISHEntry or so.
  434. return NS_OK;
  435. }
  436. /* Get index of the history list */
  437. NS_IMETHODIMP
  438. nsSHistory::GetIndex(int32_t* aResult)
  439. {
  440. NS_PRECONDITION(aResult, "null out param?");
  441. *aResult = mIndex;
  442. return NS_OK;
  443. }
  444. /* Get the requestedIndex */
  445. NS_IMETHODIMP
  446. nsSHistory::GetRequestedIndex(int32_t* aResult)
  447. {
  448. NS_PRECONDITION(aResult, "null out param?");
  449. *aResult = mRequestedIndex;
  450. return NS_OK;
  451. }
  452. /* Get the entry at a given index */
  453. NS_IMETHODIMP
  454. nsSHistory::GetEntryAtIndex(int32_t aIndex, bool aModifyIndex,
  455. nsISHEntry** aResult)
  456. {
  457. nsresult rv;
  458. nsCOMPtr<nsISHTransaction> txn;
  459. /* GetTransactionAtIndex ensures aResult is valid and validates aIndex */
  460. rv = GetTransactionAtIndex(aIndex, getter_AddRefs(txn));
  461. if (NS_SUCCEEDED(rv) && txn) {
  462. // Get the Entry from the transaction
  463. rv = txn->GetSHEntry(aResult);
  464. if (NS_SUCCEEDED(rv) && (*aResult)) {
  465. // Set mIndex to the requested index, if asked to do so..
  466. if (aModifyIndex) {
  467. mIndex = aIndex;
  468. }
  469. }
  470. }
  471. return rv;
  472. }
  473. /* Get the transaction at a given index */
  474. NS_IMETHODIMP
  475. nsSHistory::GetTransactionAtIndex(int32_t aIndex, nsISHTransaction** aResult)
  476. {
  477. nsresult rv;
  478. NS_ENSURE_ARG_POINTER(aResult);
  479. if (mLength <= 0 || aIndex < 0 || aIndex >= mLength) {
  480. return NS_ERROR_FAILURE;
  481. }
  482. if (!mListRoot) {
  483. return NS_ERROR_FAILURE;
  484. }
  485. if (aIndex == 0) {
  486. *aResult = mListRoot;
  487. NS_ADDREF(*aResult);
  488. return NS_OK;
  489. }
  490. int32_t cnt = 0;
  491. nsCOMPtr<nsISHTransaction> tempPtr;
  492. rv = GetRootTransaction(getter_AddRefs(tempPtr));
  493. if (NS_FAILED(rv) || !tempPtr) {
  494. return NS_ERROR_FAILURE;
  495. }
  496. while (true) {
  497. nsCOMPtr<nsISHTransaction> ptr;
  498. rv = tempPtr->GetNext(getter_AddRefs(ptr));
  499. if (NS_SUCCEEDED(rv) && ptr) {
  500. cnt++;
  501. if (cnt == aIndex) {
  502. ptr.forget(aResult);
  503. break;
  504. } else {
  505. tempPtr = ptr;
  506. continue;
  507. }
  508. } else {
  509. return NS_ERROR_FAILURE;
  510. }
  511. }
  512. return NS_OK;
  513. }
  514. /* Get the index of a given entry */
  515. NS_IMETHODIMP
  516. nsSHistory::GetIndexOfEntry(nsISHEntry* aSHEntry, int32_t* aResult)
  517. {
  518. NS_ENSURE_ARG(aSHEntry);
  519. NS_ENSURE_ARG_POINTER(aResult);
  520. *aResult = -1;
  521. if (mLength <= 0) {
  522. return NS_ERROR_FAILURE;
  523. }
  524. nsCOMPtr<nsISHTransaction> currentTxn;
  525. int32_t cnt = 0;
  526. nsresult rv = GetRootTransaction(getter_AddRefs(currentTxn));
  527. if (NS_FAILED(rv) || !currentTxn) {
  528. return NS_ERROR_FAILURE;
  529. }
  530. while (true) {
  531. nsCOMPtr<nsISHEntry> entry;
  532. rv = currentTxn->GetSHEntry(getter_AddRefs(entry));
  533. if (NS_FAILED(rv) || !entry) {
  534. return NS_ERROR_FAILURE;
  535. }
  536. if (aSHEntry == entry) {
  537. *aResult = cnt;
  538. break;
  539. }
  540. rv = currentTxn->GetNext(getter_AddRefs(currentTxn));
  541. if (NS_FAILED(rv) || !currentTxn) {
  542. return NS_ERROR_FAILURE;
  543. }
  544. cnt++;
  545. }
  546. return NS_OK;
  547. }
  548. #ifdef DEBUG
  549. nsresult
  550. nsSHistory::PrintHistory()
  551. {
  552. nsCOMPtr<nsISHTransaction> txn;
  553. int32_t index = 0;
  554. nsresult rv;
  555. if (!mListRoot) {
  556. return NS_ERROR_FAILURE;
  557. }
  558. txn = mListRoot;
  559. while (1) {
  560. if (!txn) {
  561. break;
  562. }
  563. nsCOMPtr<nsISHEntry> entry;
  564. rv = txn->GetSHEntry(getter_AddRefs(entry));
  565. if (NS_FAILED(rv) && !entry) {
  566. return NS_ERROR_FAILURE;
  567. }
  568. nsCOMPtr<nsILayoutHistoryState> layoutHistoryState;
  569. nsCOMPtr<nsIURI> uri;
  570. nsXPIDLString title;
  571. entry->GetLayoutHistoryState(getter_AddRefs(layoutHistoryState));
  572. entry->GetURI(getter_AddRefs(uri));
  573. entry->GetTitle(getter_Copies(title));
  574. #if 0
  575. nsAutoCString url;
  576. if (uri) {
  577. uri->GetSpec(url);
  578. }
  579. printf("**** SH Transaction #%d, Entry = %x\n", index, entry.get());
  580. printf("\t\t URL = %s\n", url.get());
  581. printf("\t\t Title = %s\n", NS_LossyConvertUTF16toASCII(title).get());
  582. printf("\t\t layout History Data = %x\n", layoutHistoryState.get());
  583. #endif
  584. nsCOMPtr<nsISHTransaction> next;
  585. rv = txn->GetNext(getter_AddRefs(next));
  586. if (NS_SUCCEEDED(rv) && next) {
  587. txn = next;
  588. index++;
  589. continue;
  590. } else {
  591. break;
  592. }
  593. }
  594. return NS_OK;
  595. }
  596. #endif
  597. NS_IMETHODIMP
  598. nsSHistory::GetRootTransaction(nsISHTransaction** aResult)
  599. {
  600. NS_ENSURE_ARG_POINTER(aResult);
  601. *aResult = mListRoot;
  602. NS_IF_ADDREF(*aResult);
  603. return NS_OK;
  604. }
  605. /* Get the max size of the history list */
  606. NS_IMETHODIMP
  607. nsSHistory::GetMaxLength(int32_t* aResult)
  608. {
  609. NS_ENSURE_ARG_POINTER(aResult);
  610. *aResult = gHistoryMaxSize;
  611. return NS_OK;
  612. }
  613. /* Set the max size of the history list */
  614. NS_IMETHODIMP
  615. nsSHistory::SetMaxLength(int32_t aMaxSize)
  616. {
  617. if (aMaxSize < 0) {
  618. return NS_ERROR_ILLEGAL_VALUE;
  619. }
  620. gHistoryMaxSize = aMaxSize;
  621. if (mLength > aMaxSize) {
  622. PurgeHistory(mLength - aMaxSize);
  623. }
  624. return NS_OK;
  625. }
  626. NS_IMETHODIMP
  627. nsSHistory::PurgeHistory(int32_t aEntries)
  628. {
  629. if (mLength <= 0 || aEntries <= 0) {
  630. return NS_ERROR_FAILURE;
  631. }
  632. aEntries = std::min(aEntries, mLength);
  633. bool purgeHistory = true;
  634. NOTIFY_LISTENERS_CANCELABLE(OnHistoryPurge, purgeHistory,
  635. (aEntries, &purgeHistory));
  636. if (!purgeHistory) {
  637. // Listener asked us not to purge
  638. return NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA;
  639. }
  640. int32_t cnt = 0;
  641. while (cnt < aEntries) {
  642. nsCOMPtr<nsISHTransaction> nextTxn;
  643. if (mListRoot) {
  644. mListRoot->GetNext(getter_AddRefs(nextTxn));
  645. mListRoot->SetNext(nullptr);
  646. }
  647. mListRoot = nextTxn;
  648. if (mListRoot) {
  649. mListRoot->SetPrev(nullptr);
  650. }
  651. cnt++;
  652. }
  653. mLength -= cnt;
  654. mIndex -= cnt;
  655. NOTIFY_LISTENERS(OnLengthChange, (mLength));
  656. // All following partial histories will be deleted in this case.
  657. mEntriesInFollowingPartialHistories = 0;
  658. // Now if we were not at the end of the history, mIndex could have
  659. // become far too negative. If so, just set it to -1.
  660. if (mIndex < -1) {
  661. mIndex = -1;
  662. }
  663. if (mRootDocShell) {
  664. mRootDocShell->HistoryPurged(cnt);
  665. }
  666. return NS_OK;
  667. }
  668. NS_IMETHODIMP
  669. nsSHistory::AddSHistoryListener(nsISHistoryListener* aListener)
  670. {
  671. NS_ENSURE_ARG_POINTER(aListener);
  672. // Check if the listener supports Weak Reference. This is a must.
  673. // This listener functionality is used by embedders and we want to
  674. // have the right ownership with who ever listens to SHistory
  675. nsWeakPtr listener = do_GetWeakReference(aListener);
  676. if (!listener) {
  677. return NS_ERROR_FAILURE;
  678. }
  679. return mListeners.AppendElementUnlessExists(listener) ?
  680. NS_OK : NS_ERROR_OUT_OF_MEMORY;
  681. }
  682. NS_IMETHODIMP
  683. nsSHistory::RemoveSHistoryListener(nsISHistoryListener* aListener)
  684. {
  685. // Make sure the listener that wants to be removed is the
  686. // one we have in store.
  687. nsWeakPtr listener = do_GetWeakReference(aListener);
  688. mListeners.RemoveElement(listener);
  689. return NS_OK;
  690. }
  691. NS_IMETHODIMP
  692. nsSHistory::SetPartialSHistoryListener(nsIPartialSHistoryListener* aListener)
  693. {
  694. mPartialHistoryListener = do_GetWeakReference(aListener);
  695. return NS_OK;
  696. }
  697. /* Replace an entry in the History list at a particular index.
  698. * Do not update index or count.
  699. */
  700. NS_IMETHODIMP
  701. nsSHistory::ReplaceEntry(int32_t aIndex, nsISHEntry* aReplaceEntry)
  702. {
  703. NS_ENSURE_ARG(aReplaceEntry);
  704. nsresult rv;
  705. nsCOMPtr<nsISHTransaction> currentTxn;
  706. if (!mListRoot) {
  707. // Session History is not initialised.
  708. return NS_ERROR_FAILURE;
  709. }
  710. rv = GetTransactionAtIndex(aIndex, getter_AddRefs(currentTxn));
  711. if (currentTxn) {
  712. NOTIFY_LISTENERS(OnHistoryReplaceEntry, (aIndex));
  713. // Set the replacement entry in the transaction
  714. rv = currentTxn->SetSHEntry(aReplaceEntry);
  715. rv = currentTxn->SetPersist(true);
  716. }
  717. return rv;
  718. }
  719. NS_IMETHODIMP
  720. nsSHistory::NotifyOnHistoryReload(nsIURI* aReloadURI, uint32_t aReloadFlags,
  721. bool* aCanReload)
  722. {
  723. NOTIFY_LISTENERS_CANCELABLE(OnHistoryReload, *aCanReload,
  724. (aReloadURI, aReloadFlags, aCanReload));
  725. return NS_OK;
  726. }
  727. NS_IMETHODIMP
  728. nsSHistory::EvictOutOfRangeContentViewers(int32_t aIndex)
  729. {
  730. // Check our per SHistory object limit in the currently navigated SHistory
  731. EvictOutOfRangeWindowContentViewers(aIndex);
  732. // Check our total limit across all SHistory objects
  733. GloballyEvictContentViewers();
  734. return NS_OK;
  735. }
  736. NS_IMETHODIMP
  737. nsSHistory::EvictAllContentViewers()
  738. {
  739. // XXXbz we don't actually do a good job of evicting things as we should, so
  740. // we might have viewers quite far from mIndex. So just evict everything.
  741. nsCOMPtr<nsISHTransaction> trans = mListRoot;
  742. while (trans) {
  743. EvictContentViewerForTransaction(trans);
  744. nsCOMPtr<nsISHTransaction> temp = trans;
  745. temp->GetNext(getter_AddRefs(trans));
  746. }
  747. return NS_OK;
  748. }
  749. NS_IMETHODIMP
  750. nsSHistory::GetCanGoBack(bool* aCanGoBack)
  751. {
  752. NS_ENSURE_ARG_POINTER(aCanGoBack);
  753. if (mGlobalIndexOffset) {
  754. *aCanGoBack = true;
  755. return NS_OK;
  756. }
  757. int32_t index = -1;
  758. NS_ENSURE_SUCCESS(GetIndex(&index), NS_ERROR_FAILURE);
  759. if (index > 0) {
  760. *aCanGoBack = true;
  761. return NS_OK;
  762. }
  763. *aCanGoBack = false;
  764. return NS_OK;
  765. }
  766. NS_IMETHODIMP
  767. nsSHistory::GetCanGoForward(bool* aCanGoForward)
  768. {
  769. NS_ENSURE_ARG_POINTER(aCanGoForward);
  770. if (mEntriesInFollowingPartialHistories) {
  771. *aCanGoForward = true;
  772. return NS_OK;
  773. }
  774. int32_t index = -1;
  775. int32_t count = -1;
  776. NS_ENSURE_SUCCESS(GetIndex(&index), NS_ERROR_FAILURE);
  777. NS_ENSURE_SUCCESS(GetCount(&count), NS_ERROR_FAILURE);
  778. if (index >= 0 && index < (count - 1)) {
  779. *aCanGoForward = true;
  780. return NS_OK;
  781. }
  782. *aCanGoForward = false;
  783. return NS_OK;
  784. }
  785. NS_IMETHODIMP
  786. nsSHistory::GoBack()
  787. {
  788. bool canGoBack = false;
  789. GetCanGoBack(&canGoBack);
  790. if (!canGoBack) {
  791. return NS_ERROR_UNEXPECTED;
  792. }
  793. return LoadEntry(mIndex - 1, nsIDocShellLoadInfo::loadHistory, HIST_CMD_BACK);
  794. }
  795. NS_IMETHODIMP
  796. nsSHistory::GoForward()
  797. {
  798. bool canGoForward = false;
  799. GetCanGoForward(&canGoForward);
  800. if (!canGoForward) {
  801. return NS_ERROR_UNEXPECTED;
  802. }
  803. return LoadEntry(mIndex + 1, nsIDocShellLoadInfo::loadHistory,
  804. HIST_CMD_FORWARD);
  805. }
  806. NS_IMETHODIMP
  807. nsSHistory::Reload(uint32_t aReloadFlags)
  808. {
  809. nsDocShellInfoLoadType loadType;
  810. if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY &&
  811. aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE) {
  812. loadType = nsIDocShellLoadInfo::loadReloadBypassProxyAndCache;
  813. } else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY) {
  814. loadType = nsIDocShellLoadInfo::loadReloadBypassProxy;
  815. } else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE) {
  816. loadType = nsIDocShellLoadInfo::loadReloadBypassCache;
  817. } else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_CHARSET_CHANGE) {
  818. loadType = nsIDocShellLoadInfo::loadReloadCharsetChange;
  819. } else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_ALLOW_MIXED_CONTENT) {
  820. loadType = nsIDocShellLoadInfo::loadReloadMixedContent;
  821. } else {
  822. loadType = nsIDocShellLoadInfo::loadReloadNormal;
  823. }
  824. // We are reloading. Send Reload notifications.
  825. // nsDocShellLoadFlagType is not public, where as nsIWebNavigation
  826. // is public. So send the reload notifications with the
  827. // nsIWebNavigation flags.
  828. bool canNavigate = true;
  829. nsCOMPtr<nsIURI> currentURI;
  830. GetCurrentURI(getter_AddRefs(currentURI));
  831. NOTIFY_LISTENERS_CANCELABLE(OnHistoryReload, canNavigate,
  832. (currentURI, aReloadFlags, &canNavigate));
  833. if (!canNavigate) {
  834. return NS_OK;
  835. }
  836. return LoadEntry(mIndex, loadType, HIST_CMD_RELOAD);
  837. }
  838. NS_IMETHODIMP
  839. nsSHistory::ReloadCurrentEntry()
  840. {
  841. // Notify listeners
  842. bool canNavigate = true;
  843. nsCOMPtr<nsIURI> currentURI;
  844. GetCurrentURI(getter_AddRefs(currentURI));
  845. NOTIFY_LISTENERS_CANCELABLE(OnHistoryGotoIndex, canNavigate,
  846. (mIndex, currentURI, &canNavigate));
  847. if (!canNavigate) {
  848. return NS_OK;
  849. }
  850. return LoadEntry(mIndex, nsIDocShellLoadInfo::loadHistory, HIST_CMD_RELOAD);
  851. }
  852. void
  853. nsSHistory::EvictOutOfRangeWindowContentViewers(int32_t aIndex)
  854. {
  855. // XXX rename method to EvictContentViewersExceptAroundIndex, or something.
  856. // We need to release all content viewers that are no longer in the range
  857. //
  858. // aIndex - gHistoryMaxViewers to aIndex + gHistoryMaxViewers
  859. //
  860. // to ensure that this SHistory object isn't responsible for more than
  861. // gHistoryMaxViewers content viewers. But our job is complicated by the
  862. // fact that two transactions which are related by either hash navigations or
  863. // history.pushState will have the same content viewer.
  864. //
  865. // To illustrate the issue, suppose gHistoryMaxViewers = 3 and we have four
  866. // linked transactions in our history. Suppose we then add a new content
  867. // viewer and call into this function. So the history looks like:
  868. //
  869. // A A A A B
  870. // + *
  871. //
  872. // where the letters are content viewers and + and * denote the beginning and
  873. // end of the range aIndex +/- gHistoryMaxViewers.
  874. //
  875. // Although one copy of the content viewer A exists outside the range, we
  876. // don't want to evict A, because it has other copies in range!
  877. //
  878. // We therefore adjust our eviction strategy to read:
  879. //
  880. // Evict each content viewer outside the range aIndex -/+
  881. // gHistoryMaxViewers, unless that content viewer also appears within the
  882. // range.
  883. //
  884. // (Note that it's entirely legal to have two copies of one content viewer
  885. // separated by a different content viewer -- call pushState twice, go back
  886. // once, and refresh -- so we can't rely on identical viewers only appearing
  887. // adjacent to one another.)
  888. if (aIndex < 0) {
  889. return;
  890. }
  891. NS_ENSURE_TRUE_VOID(aIndex < mLength);
  892. // Calculate the range that's safe from eviction.
  893. int32_t startSafeIndex = std::max(0, aIndex - gHistoryMaxViewers);
  894. int32_t endSafeIndex = std::min(mLength, aIndex + gHistoryMaxViewers);
  895. LOG(("EvictOutOfRangeWindowContentViewers(index=%d), "
  896. "mLength=%d. Safe range [%d, %d]",
  897. aIndex, mLength, startSafeIndex, endSafeIndex));
  898. // The content viewers in range aIndex -/+ gHistoryMaxViewers will not be
  899. // evicted. Collect a set of them so we don't accidentally evict one of them
  900. // if it appears outside this range.
  901. nsCOMArray<nsIContentViewer> safeViewers;
  902. nsCOMPtr<nsISHTransaction> trans;
  903. GetTransactionAtIndex(startSafeIndex, getter_AddRefs(trans));
  904. for (int32_t i = startSafeIndex; trans && i <= endSafeIndex; i++) {
  905. nsCOMPtr<nsIContentViewer> viewer = GetContentViewerForTransaction(trans);
  906. safeViewers.AppendObject(viewer);
  907. nsCOMPtr<nsISHTransaction> temp = trans;
  908. temp->GetNext(getter_AddRefs(trans));
  909. }
  910. // Walk the SHistory list and evict any content viewers that aren't safe.
  911. GetTransactionAtIndex(0, getter_AddRefs(trans));
  912. while (trans) {
  913. nsCOMPtr<nsIContentViewer> viewer = GetContentViewerForTransaction(trans);
  914. if (safeViewers.IndexOf(viewer) == -1) {
  915. EvictContentViewerForTransaction(trans);
  916. }
  917. nsCOMPtr<nsISHTransaction> temp = trans;
  918. temp->GetNext(getter_AddRefs(trans));
  919. }
  920. }
  921. namespace {
  922. class TransactionAndDistance
  923. {
  924. public:
  925. TransactionAndDistance(nsISHTransaction* aTrans, uint32_t aDist)
  926. : mTransaction(aTrans)
  927. , mLastTouched(0)
  928. , mDistance(aDist)
  929. {
  930. mViewer = GetContentViewerForTransaction(aTrans);
  931. NS_ASSERTION(mViewer, "Transaction should have a content viewer");
  932. nsCOMPtr<nsISHEntry> shentry;
  933. mTransaction->GetSHEntry(getter_AddRefs(shentry));
  934. nsCOMPtr<nsISHEntryInternal> shentryInternal = do_QueryInterface(shentry);
  935. if (shentryInternal) {
  936. shentryInternal->GetLastTouched(&mLastTouched);
  937. } else {
  938. NS_WARNING("Can't cast to nsISHEntryInternal?");
  939. }
  940. }
  941. bool operator<(const TransactionAndDistance& aOther) const
  942. {
  943. // Compare distances first, and fall back to last-accessed times.
  944. if (aOther.mDistance != this->mDistance) {
  945. return this->mDistance < aOther.mDistance;
  946. }
  947. return this->mLastTouched < aOther.mLastTouched;
  948. }
  949. bool operator==(const TransactionAndDistance& aOther) const
  950. {
  951. // This is a little silly; we need == so the default comaprator can be
  952. // instantiated, but this function is never actually called when we sort
  953. // the list of TransactionAndDistance objects.
  954. return aOther.mDistance == this->mDistance &&
  955. aOther.mLastTouched == this->mLastTouched;
  956. }
  957. nsCOMPtr<nsISHTransaction> mTransaction;
  958. nsCOMPtr<nsIContentViewer> mViewer;
  959. uint32_t mLastTouched;
  960. int32_t mDistance;
  961. };
  962. } // namespace
  963. // static
  964. void
  965. nsSHistory::GloballyEvictContentViewers()
  966. {
  967. // First, collect from each SHistory object the transactions which have a
  968. // cached content viewer. Associate with each transaction its distance from
  969. // its SHistory's current index.
  970. nsTArray<TransactionAndDistance> transactions;
  971. PRCList* listEntry = PR_LIST_HEAD(&gSHistoryList);
  972. while (listEntry != &gSHistoryList) {
  973. nsSHistory* shist = static_cast<nsSHistory*>(listEntry);
  974. // Maintain a list of the transactions which have viewers and belong to
  975. // this particular shist object. We'll add this list to the global list,
  976. // |transactions|, eventually.
  977. nsTArray<TransactionAndDistance> shTransactions;
  978. // Content viewers are likely to exist only within shist->mIndex -/+
  979. // gHistoryMaxViewers, so only search within that range.
  980. //
  981. // A content viewer might exist outside that range due to either:
  982. //
  983. // * history.pushState or hash navigations, in which case a copy of the
  984. // content viewer should exist within the range, or
  985. //
  986. // * bugs which cause us not to call nsSHistory::EvictContentViewers()
  987. // often enough. Once we do call EvictContentViewers() for the
  988. // SHistory object in question, we'll do a full search of its history
  989. // and evict the out-of-range content viewers, so we don't bother here.
  990. //
  991. int32_t startIndex = std::max(0, shist->mIndex - gHistoryMaxViewers);
  992. int32_t endIndex = std::min(shist->mLength - 1,
  993. shist->mIndex + gHistoryMaxViewers);
  994. nsCOMPtr<nsISHTransaction> trans;
  995. shist->GetTransactionAtIndex(startIndex, getter_AddRefs(trans));
  996. for (int32_t i = startIndex; trans && i <= endIndex; i++) {
  997. nsCOMPtr<nsIContentViewer> contentViewer =
  998. GetContentViewerForTransaction(trans);
  999. if (contentViewer) {
  1000. // Because one content viewer might belong to multiple SHEntries, we
  1001. // have to search through shTransactions to see if we already know
  1002. // about this content viewer. If we find the viewer, update its
  1003. // distance from the SHistory's index and continue.
  1004. bool found = false;
  1005. for (uint32_t j = 0; j < shTransactions.Length(); j++) {
  1006. TransactionAndDistance& container = shTransactions[j];
  1007. if (container.mViewer == contentViewer) {
  1008. container.mDistance = std::min(container.mDistance,
  1009. DeprecatedAbs(i - shist->mIndex));
  1010. found = true;
  1011. break;
  1012. }
  1013. }
  1014. // If we didn't find a TransactionAndDistance for this content viewer,
  1015. // make a new one.
  1016. if (!found) {
  1017. TransactionAndDistance container(trans,
  1018. DeprecatedAbs(i - shist->mIndex));
  1019. shTransactions.AppendElement(container);
  1020. }
  1021. }
  1022. nsCOMPtr<nsISHTransaction> temp = trans;
  1023. temp->GetNext(getter_AddRefs(trans));
  1024. }
  1025. // We've found all the transactions belonging to shist which have viewers.
  1026. // Add those transactions to our global list and move on.
  1027. transactions.AppendElements(shTransactions);
  1028. listEntry = PR_NEXT_LINK(shist);
  1029. }
  1030. // We now have collected all cached content viewers. First check that we
  1031. // have enough that we actually need to evict some.
  1032. if ((int32_t)transactions.Length() <= sHistoryMaxTotalViewers) {
  1033. return;
  1034. }
  1035. // If we need to evict, sort our list of transactions and evict the largest
  1036. // ones. (We could of course get better algorithmic complexity here by using
  1037. // a heap or something more clever. But sHistoryMaxTotalViewers isn't large,
  1038. // so let's not worry about it.)
  1039. transactions.Sort();
  1040. for (int32_t i = transactions.Length() - 1; i >= sHistoryMaxTotalViewers;
  1041. --i) {
  1042. EvictContentViewerForTransaction(transactions[i].mTransaction);
  1043. }
  1044. }
  1045. nsresult
  1046. nsSHistory::EvictExpiredContentViewerForEntry(nsIBFCacheEntry* aEntry)
  1047. {
  1048. int32_t startIndex = std::max(0, mIndex - gHistoryMaxViewers);
  1049. int32_t endIndex = std::min(mLength - 1, mIndex + gHistoryMaxViewers);
  1050. nsCOMPtr<nsISHTransaction> trans;
  1051. GetTransactionAtIndex(startIndex, getter_AddRefs(trans));
  1052. int32_t i;
  1053. for (i = startIndex; trans && i <= endIndex; ++i) {
  1054. nsCOMPtr<nsISHEntry> entry;
  1055. trans->GetSHEntry(getter_AddRefs(entry));
  1056. // Does entry have the same BFCacheEntry as the argument to this method?
  1057. if (entry->HasBFCacheEntry(aEntry)) {
  1058. break;
  1059. }
  1060. nsCOMPtr<nsISHTransaction> temp = trans;
  1061. temp->GetNext(getter_AddRefs(trans));
  1062. }
  1063. if (i > endIndex) {
  1064. return NS_OK;
  1065. }
  1066. if (i == mIndex) {
  1067. NS_WARNING("How did the current SHEntry expire?");
  1068. return NS_OK;
  1069. }
  1070. EvictContentViewerForTransaction(trans);
  1071. return NS_OK;
  1072. }
  1073. // Evicts all content viewers in all history objects. This is very
  1074. // inefficient, because it requires a linear search through all SHistory
  1075. // objects for each viewer to be evicted. However, this method is called
  1076. // infrequently -- only when the disk or memory cache is cleared.
  1077. // static
  1078. void
  1079. nsSHistory::GloballyEvictAllContentViewers()
  1080. {
  1081. int32_t maxViewers = sHistoryMaxTotalViewers;
  1082. sHistoryMaxTotalViewers = 0;
  1083. GloballyEvictContentViewers();
  1084. sHistoryMaxTotalViewers = maxViewers;
  1085. }
  1086. void
  1087. GetDynamicChildren(nsISHContainer* aContainer,
  1088. nsTArray<uint64_t>& aDocshellIDs,
  1089. bool aOnlyTopLevelDynamic)
  1090. {
  1091. int32_t count = 0;
  1092. aContainer->GetChildCount(&count);
  1093. for (int32_t i = 0; i < count; ++i) {
  1094. nsCOMPtr<nsISHEntry> child;
  1095. aContainer->GetChildAt(i, getter_AddRefs(child));
  1096. if (child) {
  1097. bool dynAdded = false;
  1098. child->IsDynamicallyAdded(&dynAdded);
  1099. if (dynAdded) {
  1100. uint64_t docshellID = 0;
  1101. child->GetDocshellID(&docshellID);
  1102. aDocshellIDs.AppendElement(docshellID);
  1103. }
  1104. if (!dynAdded || !aOnlyTopLevelDynamic) {
  1105. nsCOMPtr<nsISHContainer> childAsContainer = do_QueryInterface(child);
  1106. if (childAsContainer) {
  1107. GetDynamicChildren(childAsContainer, aDocshellIDs,
  1108. aOnlyTopLevelDynamic);
  1109. }
  1110. }
  1111. }
  1112. }
  1113. }
  1114. bool
  1115. RemoveFromSessionHistoryContainer(nsISHContainer* aContainer,
  1116. nsTArray<uint64_t>& aDocshellIDs)
  1117. {
  1118. nsCOMPtr<nsISHEntry> root = do_QueryInterface(aContainer);
  1119. NS_ENSURE_TRUE(root, false);
  1120. bool didRemove = false;
  1121. int32_t childCount = 0;
  1122. aContainer->GetChildCount(&childCount);
  1123. for (int32_t i = childCount - 1; i >= 0; --i) {
  1124. nsCOMPtr<nsISHEntry> child;
  1125. aContainer->GetChildAt(i, getter_AddRefs(child));
  1126. if (child) {
  1127. uint64_t docshelldID = 0;
  1128. child->GetDocshellID(&docshelldID);
  1129. if (aDocshellIDs.Contains(docshelldID)) {
  1130. didRemove = true;
  1131. aContainer->RemoveChild(child);
  1132. } else {
  1133. nsCOMPtr<nsISHContainer> container = do_QueryInterface(child);
  1134. if (container) {
  1135. bool childRemoved =
  1136. RemoveFromSessionHistoryContainer(container, aDocshellIDs);
  1137. if (childRemoved) {
  1138. didRemove = true;
  1139. }
  1140. }
  1141. }
  1142. }
  1143. }
  1144. return didRemove;
  1145. }
  1146. bool
  1147. RemoveChildEntries(nsISHistory* aHistory, int32_t aIndex,
  1148. nsTArray<uint64_t>& aEntryIDs)
  1149. {
  1150. nsCOMPtr<nsISHEntry> rootHE;
  1151. aHistory->GetEntryAtIndex(aIndex, false, getter_AddRefs(rootHE));
  1152. nsCOMPtr<nsISHContainer> root = do_QueryInterface(rootHE);
  1153. return root ? RemoveFromSessionHistoryContainer(root, aEntryIDs) : false;
  1154. }
  1155. bool
  1156. IsSameTree(nsISHEntry* aEntry1, nsISHEntry* aEntry2)
  1157. {
  1158. if (!aEntry1 && !aEntry2) {
  1159. return true;
  1160. }
  1161. if ((!aEntry1 && aEntry2) || (aEntry1 && !aEntry2)) {
  1162. return false;
  1163. }
  1164. uint32_t id1, id2;
  1165. aEntry1->GetID(&id1);
  1166. aEntry2->GetID(&id2);
  1167. if (id1 != id2) {
  1168. return false;
  1169. }
  1170. nsCOMPtr<nsISHContainer> container1 = do_QueryInterface(aEntry1);
  1171. nsCOMPtr<nsISHContainer> container2 = do_QueryInterface(aEntry2);
  1172. int32_t count1, count2;
  1173. container1->GetChildCount(&count1);
  1174. container2->GetChildCount(&count2);
  1175. // We allow null entries in the end of the child list.
  1176. int32_t count = std::max(count1, count2);
  1177. for (int32_t i = 0; i < count; ++i) {
  1178. nsCOMPtr<nsISHEntry> child1, child2;
  1179. container1->GetChildAt(i, getter_AddRefs(child1));
  1180. container2->GetChildAt(i, getter_AddRefs(child2));
  1181. if (!IsSameTree(child1, child2)) {
  1182. return false;
  1183. }
  1184. }
  1185. return true;
  1186. }
  1187. bool
  1188. nsSHistory::RemoveDuplicate(int32_t aIndex, bool aKeepNext)
  1189. {
  1190. NS_ASSERTION(aIndex >= 0, "aIndex must be >= 0!");
  1191. NS_ASSERTION(aIndex != 0 || aKeepNext,
  1192. "If we're removing index 0 we must be keeping the next");
  1193. NS_ASSERTION(aIndex != mIndex, "Shouldn't remove mIndex!");
  1194. int32_t compareIndex = aKeepNext ? aIndex + 1 : aIndex - 1;
  1195. nsCOMPtr<nsISHEntry> root1, root2;
  1196. GetEntryAtIndex(aIndex, false, getter_AddRefs(root1));
  1197. GetEntryAtIndex(compareIndex, false, getter_AddRefs(root2));
  1198. if (IsSameTree(root1, root2)) {
  1199. nsCOMPtr<nsISHTransaction> txToRemove, txToKeep, txNext, txPrev;
  1200. GetTransactionAtIndex(aIndex, getter_AddRefs(txToRemove));
  1201. GetTransactionAtIndex(compareIndex, getter_AddRefs(txToKeep));
  1202. if (!txToRemove) {
  1203. return false;
  1204. }
  1205. NS_ENSURE_TRUE(txToKeep, false);
  1206. txToRemove->GetNext(getter_AddRefs(txNext));
  1207. txToRemove->GetPrev(getter_AddRefs(txPrev));
  1208. txToRemove->SetNext(nullptr);
  1209. txToRemove->SetPrev(nullptr);
  1210. if (aKeepNext) {
  1211. if (txPrev) {
  1212. txPrev->SetNext(txToKeep);
  1213. } else {
  1214. txToKeep->SetPrev(nullptr);
  1215. }
  1216. } else {
  1217. txToKeep->SetNext(txNext);
  1218. }
  1219. if (aIndex == 0 && aKeepNext) {
  1220. NS_ASSERTION(txToRemove == mListRoot,
  1221. "Transaction at index 0 should be mListRoot!");
  1222. // We're removing the very first session history transaction!
  1223. mListRoot = txToKeep;
  1224. }
  1225. if (mRootDocShell) {
  1226. static_cast<nsDocShell*>(mRootDocShell)->HistoryTransactionRemoved(aIndex);
  1227. }
  1228. // Adjust our indices to reflect the removed transaction
  1229. if (mIndex > aIndex) {
  1230. mIndex = mIndex - 1;
  1231. }
  1232. // NB: If the transaction we are removing is the transaction currently
  1233. // being navigated to (mRequestedIndex) then we adjust the index
  1234. // only if we're not keeping the next entry (because if we are keeping
  1235. // the next entry (because the current is a duplicate of the next), then
  1236. // that entry slides into the spot that we're currently pointing to.
  1237. // We don't do this adjustment for mIndex because mIndex cannot equal
  1238. // aIndex.
  1239. // NB: We don't need to guard on mRequestedIndex being nonzero here,
  1240. // because either they're strictly greater than aIndex which is at least
  1241. // zero, or they are equal to aIndex in which case aKeepNext must be true
  1242. // if aIndex is zero.
  1243. if (mRequestedIndex > aIndex || (mRequestedIndex == aIndex && !aKeepNext)) {
  1244. mRequestedIndex = mRequestedIndex - 1;
  1245. }
  1246. --mLength;
  1247. mEntriesInFollowingPartialHistories = 0;
  1248. NOTIFY_LISTENERS(OnLengthChange, (mLength));
  1249. return true;
  1250. }
  1251. return false;
  1252. }
  1253. NS_IMETHODIMP_(void)
  1254. nsSHistory::RemoveEntries(nsTArray<uint64_t>& aIDs, int32_t aStartIndex)
  1255. {
  1256. int32_t index = aStartIndex;
  1257. while (index >= 0 && RemoveChildEntries(this, --index, aIDs)) {
  1258. }
  1259. int32_t minIndex = index;
  1260. index = aStartIndex;
  1261. while (index >= 0 && RemoveChildEntries(this, index++, aIDs)) {
  1262. }
  1263. // We need to remove duplicate nsSHEntry trees.
  1264. bool didRemove = false;
  1265. while (index > minIndex) {
  1266. if (index != mIndex) {
  1267. didRemove = RemoveDuplicate(index, index < mIndex) || didRemove;
  1268. }
  1269. --index;
  1270. }
  1271. if (didRemove && mRootDocShell) {
  1272. NS_DispatchToCurrentThread(NewRunnableMethod(static_cast<nsDocShell*>(mRootDocShell),
  1273. &nsDocShell::FireDummyOnLocationChange));
  1274. }
  1275. }
  1276. void
  1277. nsSHistory::RemoveDynEntries(int32_t aOldIndex, int32_t aNewIndex)
  1278. {
  1279. // Search for the entries which are in the current index,
  1280. // but not in the new one.
  1281. nsCOMPtr<nsISHEntry> originalSH;
  1282. GetEntryAtIndex(aOldIndex, false, getter_AddRefs(originalSH));
  1283. nsCOMPtr<nsISHContainer> originalContainer = do_QueryInterface(originalSH);
  1284. AutoTArray<uint64_t, 16> toBeRemovedEntries;
  1285. if (originalContainer) {
  1286. nsTArray<uint64_t> originalDynDocShellIDs;
  1287. GetDynamicChildren(originalContainer, originalDynDocShellIDs, true);
  1288. if (originalDynDocShellIDs.Length()) {
  1289. nsCOMPtr<nsISHEntry> currentSH;
  1290. GetEntryAtIndex(aNewIndex, false, getter_AddRefs(currentSH));
  1291. nsCOMPtr<nsISHContainer> newContainer = do_QueryInterface(currentSH);
  1292. if (newContainer) {
  1293. nsTArray<uint64_t> newDynDocShellIDs;
  1294. GetDynamicChildren(newContainer, newDynDocShellIDs, false);
  1295. for (uint32_t i = 0; i < originalDynDocShellIDs.Length(); ++i) {
  1296. if (!newDynDocShellIDs.Contains(originalDynDocShellIDs[i])) {
  1297. toBeRemovedEntries.AppendElement(originalDynDocShellIDs[i]);
  1298. }
  1299. }
  1300. }
  1301. }
  1302. }
  1303. if (toBeRemovedEntries.Length()) {
  1304. RemoveEntries(toBeRemovedEntries, aOldIndex);
  1305. }
  1306. }
  1307. NS_IMETHODIMP
  1308. nsSHistory::UpdateIndex()
  1309. {
  1310. // Update the actual index with the right value.
  1311. if (mIndex != mRequestedIndex && mRequestedIndex != -1) {
  1312. RemoveDynEntries(mIndex, mRequestedIndex);
  1313. mIndex = mRequestedIndex;
  1314. }
  1315. mRequestedIndex = -1;
  1316. return NS_OK;
  1317. }
  1318. NS_IMETHODIMP
  1319. nsSHistory::Stop(uint32_t aStopFlags)
  1320. {
  1321. // Not implemented
  1322. return NS_OK;
  1323. }
  1324. NS_IMETHODIMP
  1325. nsSHistory::GetDocument(nsIDOMDocument** aDocument)
  1326. {
  1327. // Not implemented
  1328. return NS_OK;
  1329. }
  1330. NS_IMETHODIMP
  1331. nsSHistory::GetCurrentURI(nsIURI** aResultURI)
  1332. {
  1333. NS_ENSURE_ARG_POINTER(aResultURI);
  1334. nsresult rv;
  1335. nsCOMPtr<nsISHEntry> currentEntry;
  1336. rv = GetEntryAtIndex(mIndex, false, getter_AddRefs(currentEntry));
  1337. if (NS_FAILED(rv) && !currentEntry) {
  1338. return rv;
  1339. }
  1340. rv = currentEntry->GetURI(aResultURI);
  1341. return rv;
  1342. }
  1343. NS_IMETHODIMP
  1344. nsSHistory::GetReferringURI(nsIURI** aURI)
  1345. {
  1346. *aURI = nullptr;
  1347. // Not implemented
  1348. return NS_OK;
  1349. }
  1350. NS_IMETHODIMP
  1351. nsSHistory::SetSessionHistory(nsISHistory* aSessionHistory)
  1352. {
  1353. // Not implemented
  1354. return NS_OK;
  1355. }
  1356. NS_IMETHODIMP
  1357. nsSHistory::GetSessionHistory(nsISHistory** aSessionHistory)
  1358. {
  1359. // Not implemented
  1360. return NS_OK;
  1361. }
  1362. NS_IMETHODIMP
  1363. nsSHistory::LoadURIWithOptions(const char16_t* aURI,
  1364. uint32_t aLoadFlags,
  1365. nsIURI* aReferringURI,
  1366. uint32_t aReferrerPolicy,
  1367. nsIInputStream* aPostStream,
  1368. nsIInputStream* aExtraHeaderStream,
  1369. nsIURI* aBaseURI,
  1370. nsIPrincipal* aTriggeringPrincipal)
  1371. {
  1372. return NS_OK;
  1373. }
  1374. NS_IMETHODIMP
  1375. nsSHistory::SetOriginAttributesBeforeLoading(JS::HandleValue aOriginAttributes)
  1376. {
  1377. return NS_OK;
  1378. }
  1379. NS_IMETHODIMP
  1380. nsSHistory::LoadURI(const char16_t* aURI,
  1381. uint32_t aLoadFlags,
  1382. nsIURI* aReferringURI,
  1383. nsIInputStream* aPostStream,
  1384. nsIInputStream* aExtraHeaderStream)
  1385. {
  1386. return NS_OK;
  1387. }
  1388. NS_IMETHODIMP
  1389. nsSHistory::GotoIndex(int32_t aGlobalIndex)
  1390. {
  1391. // We provide abstraction of grouped session history for nsIWebNavigation
  1392. // functions, so the index passed in here is global index.
  1393. return LoadEntry(aGlobalIndex - mGlobalIndexOffset, nsIDocShellLoadInfo::loadHistory,
  1394. HIST_CMD_GOTOINDEX);
  1395. }
  1396. nsresult
  1397. nsSHistory::LoadNextPossibleEntry(int32_t aNewIndex, long aLoadType,
  1398. uint32_t aHistCmd)
  1399. {
  1400. mRequestedIndex = -1;
  1401. if (aNewIndex < mIndex) {
  1402. return LoadEntry(aNewIndex - 1, aLoadType, aHistCmd);
  1403. }
  1404. if (aNewIndex > mIndex) {
  1405. return LoadEntry(aNewIndex + 1, aLoadType, aHistCmd);
  1406. }
  1407. return NS_ERROR_FAILURE;
  1408. }
  1409. NS_IMETHODIMP
  1410. nsSHistory::LoadEntry(int32_t aIndex, long aLoadType, uint32_t aHistCmd)
  1411. {
  1412. if (!mRootDocShell) {
  1413. return NS_ERROR_FAILURE;
  1414. }
  1415. if (aIndex < 0 || aIndex >= mLength) {
  1416. if (aIndex + mGlobalIndexOffset < 0) {
  1417. // The global index is negative.
  1418. return NS_ERROR_FAILURE;
  1419. }
  1420. if (aIndex - mLength >= mEntriesInFollowingPartialHistories) {
  1421. // The global index exceeds max possible value.
  1422. return NS_ERROR_FAILURE;
  1423. }
  1424. // The global index is valid. trigger cross browser navigation.
  1425. nsCOMPtr<nsIPartialSHistoryListener> listener =
  1426. do_QueryReferent(mPartialHistoryListener);
  1427. if (!listener) {
  1428. return NS_ERROR_FAILURE;
  1429. }
  1430. return listener->OnRequestCrossBrowserNavigation(aIndex + mGlobalIndexOffset);
  1431. }
  1432. // Keep note of requested history index in mRequestedIndex.
  1433. mRequestedIndex = aIndex;
  1434. nsCOMPtr<nsISHEntry> prevEntry;
  1435. GetEntryAtIndex(mIndex, false, getter_AddRefs(prevEntry));
  1436. nsCOMPtr<nsISHEntry> nextEntry;
  1437. GetEntryAtIndex(mRequestedIndex, false, getter_AddRefs(nextEntry));
  1438. if (!nextEntry || !prevEntry) {
  1439. mRequestedIndex = -1;
  1440. return NS_ERROR_FAILURE;
  1441. }
  1442. // Remember that this entry is getting loaded at this point in the sequence
  1443. nsCOMPtr<nsISHEntryInternal> entryInternal = do_QueryInterface(nextEntry);
  1444. if (entryInternal) {
  1445. entryInternal->SetLastTouched(++gTouchCounter);
  1446. }
  1447. // Send appropriate listener notifications
  1448. bool canNavigate = true;
  1449. // Get the uri for the entry we are about to visit
  1450. nsCOMPtr<nsIURI> nextURI;
  1451. nextEntry->GetURI(getter_AddRefs(nextURI));
  1452. if (aHistCmd == HIST_CMD_BACK) {
  1453. // We are going back one entry. Send GoBack notifications
  1454. NOTIFY_LISTENERS_CANCELABLE(OnHistoryGoBack, canNavigate,
  1455. (nextURI, &canNavigate));
  1456. } else if (aHistCmd == HIST_CMD_FORWARD) {
  1457. // We are going forward. Send GoForward notification
  1458. NOTIFY_LISTENERS_CANCELABLE(OnHistoryGoForward, canNavigate,
  1459. (nextURI, &canNavigate));
  1460. } else if (aHistCmd == HIST_CMD_GOTOINDEX) {
  1461. // We are going somewhere else. This is not reload either
  1462. NOTIFY_LISTENERS_CANCELABLE(OnHistoryGotoIndex, canNavigate,
  1463. (aIndex, nextURI, &canNavigate));
  1464. }
  1465. if (!canNavigate) {
  1466. // If the listener asked us not to proceed with
  1467. // the operation, simply return.
  1468. mRequestedIndex = -1;
  1469. return NS_OK; // XXX Maybe I can return some other error code?
  1470. }
  1471. if (mRequestedIndex == mIndex) {
  1472. // Possibly a reload case
  1473. return InitiateLoad(nextEntry, mRootDocShell, aLoadType);
  1474. }
  1475. // Going back or forward.
  1476. bool differenceFound = false;
  1477. nsresult rv = LoadDifferingEntries(prevEntry, nextEntry, mRootDocShell,
  1478. aLoadType, differenceFound);
  1479. if (!differenceFound) {
  1480. // We did not find any differences. Go further in the history.
  1481. return LoadNextPossibleEntry(aIndex, aLoadType, aHistCmd);
  1482. }
  1483. return rv;
  1484. }
  1485. nsresult
  1486. nsSHistory::LoadDifferingEntries(nsISHEntry* aPrevEntry, nsISHEntry* aNextEntry,
  1487. nsIDocShell* aParent, long aLoadType,
  1488. bool& aDifferenceFound)
  1489. {
  1490. if (!aPrevEntry || !aNextEntry || !aParent) {
  1491. return NS_ERROR_FAILURE;
  1492. }
  1493. nsresult result = NS_OK;
  1494. uint32_t prevID, nextID;
  1495. aPrevEntry->GetID(&prevID);
  1496. aNextEntry->GetID(&nextID);
  1497. // Check the IDs to verify if the pages are different.
  1498. if (prevID != nextID) {
  1499. aDifferenceFound = true;
  1500. // Set the Subframe flag if not navigating the root docshell.
  1501. aNextEntry->SetIsSubFrame(aParent != mRootDocShell);
  1502. return InitiateLoad(aNextEntry, aParent, aLoadType);
  1503. }
  1504. // The entries are the same, so compare any child frames
  1505. int32_t pcnt = 0;
  1506. int32_t ncnt = 0;
  1507. int32_t dsCount = 0;
  1508. nsCOMPtr<nsISHContainer> prevContainer(do_QueryInterface(aPrevEntry));
  1509. nsCOMPtr<nsISHContainer> nextContainer(do_QueryInterface(aNextEntry));
  1510. if (!prevContainer || !nextContainer) {
  1511. return NS_ERROR_FAILURE;
  1512. }
  1513. prevContainer->GetChildCount(&pcnt);
  1514. nextContainer->GetChildCount(&ncnt);
  1515. aParent->GetChildCount(&dsCount);
  1516. // Create an array for child docshells.
  1517. nsCOMArray<nsIDocShell> docshells;
  1518. for (int32_t i = 0; i < dsCount; ++i) {
  1519. nsCOMPtr<nsIDocShellTreeItem> treeItem;
  1520. aParent->GetChildAt(i, getter_AddRefs(treeItem));
  1521. nsCOMPtr<nsIDocShell> shell = do_QueryInterface(treeItem);
  1522. if (shell) {
  1523. docshells.AppendElement(shell.forget());
  1524. }
  1525. }
  1526. // Search for something to load next.
  1527. for (int32_t i = 0; i < ncnt; ++i) {
  1528. // First get an entry which may cause a new page to be loaded.
  1529. nsCOMPtr<nsISHEntry> nChild;
  1530. nextContainer->GetChildAt(i, getter_AddRefs(nChild));
  1531. if (!nChild) {
  1532. continue;
  1533. }
  1534. uint64_t docshellID = 0;
  1535. nChild->GetDocshellID(&docshellID);
  1536. // Then find the associated docshell.
  1537. nsIDocShell* dsChild = nullptr;
  1538. int32_t count = docshells.Count();
  1539. for (int32_t j = 0; j < count; ++j) {
  1540. uint64_t shellID = 0;
  1541. nsIDocShell* shell = docshells[j];
  1542. shell->GetHistoryID(&shellID);
  1543. if (shellID == docshellID) {
  1544. dsChild = shell;
  1545. break;
  1546. }
  1547. }
  1548. if (!dsChild) {
  1549. continue;
  1550. }
  1551. // Then look at the previous entries to see if there was
  1552. // an entry for the docshell.
  1553. nsCOMPtr<nsISHEntry> pChild;
  1554. for (int32_t k = 0; k < pcnt; ++k) {
  1555. nsCOMPtr<nsISHEntry> child;
  1556. prevContainer->GetChildAt(k, getter_AddRefs(child));
  1557. if (child) {
  1558. uint64_t dID = 0;
  1559. child->GetDocshellID(&dID);
  1560. if (dID == docshellID) {
  1561. pChild = child;
  1562. break;
  1563. }
  1564. }
  1565. }
  1566. // Finally recursively call this method.
  1567. // This will either load a new page to shell or some subshell or
  1568. // do nothing.
  1569. LoadDifferingEntries(pChild, nChild, dsChild, aLoadType, aDifferenceFound);
  1570. }
  1571. return result;
  1572. }
  1573. nsresult
  1574. nsSHistory::InitiateLoad(nsISHEntry* aFrameEntry, nsIDocShell* aFrameDS,
  1575. long aLoadType)
  1576. {
  1577. NS_ENSURE_STATE(aFrameDS && aFrameEntry);
  1578. nsCOMPtr<nsIDocShellLoadInfo> loadInfo;
  1579. /* Set the loadType in the SHEntry too to what was passed on.
  1580. * This will be passed on to child subframes later in nsDocShell,
  1581. * so that proper loadType is maintained through out a frameset
  1582. */
  1583. aFrameEntry->SetLoadType(aLoadType);
  1584. aFrameDS->CreateLoadInfo(getter_AddRefs(loadInfo));
  1585. loadInfo->SetLoadType(aLoadType);
  1586. loadInfo->SetSHEntry(aFrameEntry);
  1587. nsCOMPtr<nsIURI> originalURI;
  1588. aFrameEntry->GetOriginalURI(getter_AddRefs(originalURI));
  1589. loadInfo->SetOriginalURI(originalURI);
  1590. bool loadReplace;
  1591. aFrameEntry->GetLoadReplace(&loadReplace);
  1592. loadInfo->SetLoadReplace(loadReplace);
  1593. nsCOMPtr<nsIURI> nextURI;
  1594. aFrameEntry->GetURI(getter_AddRefs(nextURI));
  1595. // Time to initiate a document load
  1596. return aFrameDS->LoadURI(nextURI, loadInfo,
  1597. nsIWebNavigation::LOAD_FLAGS_NONE, false);
  1598. }
  1599. NS_IMETHODIMP
  1600. nsSHistory::SetRootDocShell(nsIDocShell* aDocShell)
  1601. {
  1602. mRootDocShell = aDocShell;
  1603. return NS_OK;
  1604. }
  1605. NS_IMETHODIMP
  1606. nsSHistory::GetSHistoryEnumerator(nsISimpleEnumerator** aEnumerator)
  1607. {
  1608. NS_ENSURE_ARG_POINTER(aEnumerator);
  1609. RefPtr<nsSHEnumerator> iterator = new nsSHEnumerator(this);
  1610. iterator.forget(aEnumerator);
  1611. return NS_OK;
  1612. }
  1613. NS_IMETHODIMP
  1614. nsSHistory::OnAttachGroupedSessionHistory(int32_t aOffset)
  1615. {
  1616. NS_ENSURE_TRUE(!mIsPartial, NS_ERROR_UNEXPECTED);
  1617. NS_ENSURE_TRUE(aOffset >= 0, NS_ERROR_ILLEGAL_VALUE);
  1618. mIsPartial = true;
  1619. mGlobalIndexOffset = aOffset;
  1620. // The last attached history is always at the end of the group.
  1621. mEntriesInFollowingPartialHistories = 0;
  1622. // Setting grouped history info may change canGoBack / canGoForward.
  1623. // Send a location change to update these values.
  1624. NS_DispatchToCurrentThread(NewRunnableMethod(static_cast<nsDocShell*>(mRootDocShell),
  1625. &nsDocShell::FireDummyOnLocationChange));
  1626. return NS_OK;
  1627. }
  1628. nsSHEnumerator::nsSHEnumerator(nsSHistory* aSHistory) : mIndex(-1)
  1629. {
  1630. mSHistory = aSHistory;
  1631. }
  1632. nsSHEnumerator::~nsSHEnumerator()
  1633. {
  1634. mSHistory = nullptr;
  1635. }
  1636. NS_IMPL_ISUPPORTS(nsSHEnumerator, nsISimpleEnumerator)
  1637. NS_IMETHODIMP
  1638. nsSHEnumerator::HasMoreElements(bool* aReturn)
  1639. {
  1640. int32_t cnt;
  1641. *aReturn = false;
  1642. mSHistory->GetCount(&cnt);
  1643. if (mIndex >= -1 && mIndex < (cnt - 1)) {
  1644. *aReturn = true;
  1645. }
  1646. return NS_OK;
  1647. }
  1648. NS_IMETHODIMP
  1649. nsSHEnumerator::GetNext(nsISupports** aItem)
  1650. {
  1651. NS_ENSURE_ARG_POINTER(aItem);
  1652. int32_t cnt = 0;
  1653. nsresult result = NS_ERROR_FAILURE;
  1654. mSHistory->GetCount(&cnt);
  1655. if (mIndex < (cnt - 1)) {
  1656. mIndex++;
  1657. nsCOMPtr<nsISHEntry> hEntry;
  1658. result = mSHistory->GetEntryAtIndex(mIndex, false, getter_AddRefs(hEntry));
  1659. if (hEntry) {
  1660. result = CallQueryInterface(hEntry, aItem);
  1661. }
  1662. }
  1663. return result;
  1664. }