summaryrefslogtreecommitdiffstats
path: root/mobile/android/modules/geckoview/GeckoViewSessionStore.sys.mjs
blob: faa5c5f280a5da81e39809c89ed31398334bd4f1 (plain)
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
/* 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/. */

import { GeckoViewUtils } from "resource://gre/modules/GeckoViewUtils.sys.mjs";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  SessionHistory: "resource://gre/modules/sessionstore/SessionHistory.sys.mjs",
});

const { debug, warn } = GeckoViewUtils.initLogging("SessionStore");
const kNoIndex = Number.MAX_SAFE_INTEGER;
const kLastIndex = Number.MAX_SAFE_INTEGER - 1;

class SHistoryListener {
  constructor(browsingContext) {
    this.QueryInterface = ChromeUtils.generateQI([
      "nsISHistoryListener",
      "nsISupportsWeakReference",
    ]);

    this._browserId = browsingContext.browserId;
    this._fromIndex = kNoIndex;
  }

  unregister(permanentKey) {
    const bc = BrowsingContext.getCurrentTopByBrowserId(this._browserId);
    bc?.sessionHistory?.removeSHistoryListener(this);
    GeckoViewSessionStore._browserSHistoryListener?.delete(permanentKey);
  }

  collect(
    permanentKey, // eslint-disable-line no-shadow
    browsingContext, // eslint-disable-line no-shadow
    { collectFull = true, writeToCache = false }
  ) {
    // Don't bother doing anything if we haven't seen any navigations.
    if (!collectFull && this._fromIndex === kNoIndex) {
      return null;
    }

    const fromIndex = collectFull ? -1 : this._fromIndex;
    this._fromIndex = kNoIndex;

    const historychange = lazy.SessionHistory.collectFromParent(
      browsingContext.currentURI?.spec,
      true, // Bug 1704574
      browsingContext.sessionHistory,
      fromIndex
    );

    if (writeToCache) {
      const win =
        browsingContext.embedderElement?.ownerGlobal ||
        browsingContext.currentWindowGlobal?.browsingContext?.window;

      GeckoViewSessionStore.onTabStateUpdate(permanentKey, win, {
        data: { historychange },
      });
    }

    return historychange;
  }

  collectFrom(index) {
    if (this._fromIndex <= index) {
      // If we already know that we need to update history from index N we
      // can ignore any changes that happened with an element with index
      // larger than N.
      //
      // Note: initially we use kNoIndex which is MAX_SAFE_INTEGER which
      // means we don't ignore anything here, and in case of navigation in
      // the history back and forth cases we use kLastIndex which ignores
      // only the subsequent navigations, but not any new elements added.
      return;
    }

    const bc = BrowsingContext.getCurrentTopByBrowserId(this._browserId);
    if (bc?.embedderElement?.frameLoader) {
      this._fromIndex = index;

      // Queue a tab state update on the |browser.sessionstore.interval|
      // timer. We'll call this.collect() when we receive the update.
      bc.embedderElement.frameLoader.requestSHistoryUpdate();
    }
  }

  OnHistoryNewEntry(newURI, oldIndex) {
    // We use oldIndex - 1 to collect the current entry as well. This makes
    // sure to collect any changes that were made to the entry while the
    // document was active.
    this.collectFrom(oldIndex == -1 ? oldIndex : oldIndex - 1);
  }
  OnHistoryGotoIndex() {
    this.collectFrom(kLastIndex);
  }
  OnHistoryPurge() {
    this.collectFrom(-1);
  }
  OnHistoryReload() {
    this.collectFrom(-1);
    return true;
  }
  OnHistoryReplaceEntry() {
    this.collectFrom(-1);
  }
}

export var GeckoViewSessionStore = {
  // For each <browser> element, records the SHistoryListener.
  _browserSHistoryListener: new WeakMap(),

  observe(aSubject, aTopic) {
    debug`observe ${aTopic}`;

    switch (aTopic) {
      case "browsing-context-did-set-embedder": {
        if (
          aSubject &&
          aSubject === aSubject.top &&
          aSubject.isContent &&
          aSubject.embedderElement &&
          aSubject.embedderElement.permanentKey
        ) {
          const permanentKey = aSubject.embedderElement.permanentKey;
          this._browserSHistoryListener
            .get(permanentKey)
            ?.unregister(permanentKey);

          this.getOrCreateSHistoryListener(permanentKey, aSubject, true);
        }
        break;
      }
      case "browsing-context-discarded":
        const permanentKey = aSubject?.embedderElement?.permanentKey;
        if (permanentKey) {
          this._browserSHistoryListener
            .get(permanentKey)
            ?.unregister(permanentKey);
        }
        break;
    }
  },

  onTabStateUpdate(permanentKey, win, data) {
    win.WindowEventDispatcher.sendRequest({
      type: "GeckoView:StateUpdated",
      data: data.data,
    });
  },

  getOrCreateSHistoryListener(
    permanentKey,
    browsingContext,
    collectImmediately = false
  ) {
    if (!permanentKey || browsingContext !== browsingContext.top) {
      return null;
    }

    const sessionHistory = browsingContext.sessionHistory;
    if (!sessionHistory) {
      return null;
    }

    let listener = this._browserSHistoryListener.get(permanentKey);
    if (listener) {
      return listener;
    }

    listener = new SHistoryListener(browsingContext);
    sessionHistory.addSHistoryListener(listener);
    this._browserSHistoryListener.set(permanentKey, listener);

    if (
      collectImmediately &&
      (!(browsingContext.currentURI?.spec === "about:blank") ||
        sessionHistory.count !== 0)
    ) {
      listener.collect(permanentKey, browsingContext, { writeToCache: true });
    }

    return listener;
  },
};