summaryrefslogtreecommitdiffstats
path: root/browser/components/urlbar/UrlbarProviderOpenTabs.sys.mjs
blob: 8e76ad53dbc9af7a748b6eecf6ccf7984c61b0b6 (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
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
/* 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/. */

/**
 * This module exports a provider, returning open tabs matches for the urlbar.
 * It is also used to register and unregister open tabs.
 */

import {
  UrlbarProvider,
  UrlbarUtils,
} from "resource:///modules/UrlbarUtils.sys.mjs";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
  UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.sys.mjs",
  UrlbarResult: "resource:///modules/UrlbarResult.sys.mjs",
});

ChromeUtils.defineLazyGetter(lazy, "logger", () =>
  UrlbarUtils.getLogger({ prefix: "Provider.OpenTabs" })
);

const PRIVATE_USER_CONTEXT_ID = -1;

/**
 * Maps the open tabs by userContextId.
 * Each entry is a Map of url => count.
 */
var gOpenTabUrls = new Map();

/**
 * Class used to create the provider.
 */
export class UrlbarProviderOpenTabs extends UrlbarProvider {
  constructor() {
    super();
  }

  /**
   * Returns the name of this provider.
   *
   * @returns {string} the name of this provider.
   */
  get name() {
    return "OpenTabs";
  }

  /**
   * Returns the type of this provider.
   *
   * @returns {integer} one of the types from UrlbarUtils.PROVIDER_TYPE.*
   */
  get type() {
    return UrlbarUtils.PROVIDER_TYPE.PROFILE;
  }

  /**
   * Whether this provider should be invoked for the given context.
   * If this method returns false, the providers manager won't start a query
   * with this provider, to save on resources.
   *
   * @returns {boolean} Whether this provider should be invoked for the search.
   */
  isActive() {
    // For now we don't actually use this provider to query open tabs, instead
    // we join the temp table in UrlbarProviderPlaces.
    return false;
  }

  /**
   * Tracks whether the memory tables have been initialized yet. Until this
   * happens tabs are only stored in openTabs and later copied over to the
   * memory table.
   */
  static memoryTableInitialized = false;

  /**
   * Return unique urls that are open for given user context id.
   *
   * @param {integer|string} userContextId Containers user context id
   * @param {boolean} [isInPrivateWindow] In private browsing window or not
   * @returns {Array} urls
   */
  static getOpenTabUrlsForUserContextId(
    userContextId,
    isInPrivateWindow = false
  ) {
    // It's fairly common to retrieve the value from an HTML attribute, that
    // means we're getting sometimes a string, sometimes an integer. As we're
    // using this as key of a Map, we must treat it consistently.
    userContextId = parseInt(userContextId);
    userContextId = UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
      userContextId,
      isInPrivateWindow
    );
    return Array.from(gOpenTabUrls.get(userContextId)?.keys() ?? []);
  }

  /**
   * Return unique urls that are open, along with their user context id.
   *
   * @param {boolean} [isInPrivateWindow] Whether it's for a private browsing window
   * @returns {Map} { url => Set({userContextIds}) }
   */
  static getOpenTabUrls(isInPrivateWindow = false) {
    let uniqueUrls = new Map();
    if (isInPrivateWindow) {
      let urls = UrlbarProviderOpenTabs.getOpenTabUrlsForUserContextId(
        PRIVATE_USER_CONTEXT_ID,
        true
      );
      for (let url of urls) {
        uniqueUrls.set(url, new Set([PRIVATE_USER_CONTEXT_ID]));
      }
    } else {
      for (let [userContextId, urls] of gOpenTabUrls) {
        if (userContextId == PRIVATE_USER_CONTEXT_ID) {
          continue;
        }
        for (let url of urls.keys()) {
          let userContextIds = uniqueUrls.get(url);
          if (!userContextIds) {
            userContextIds = new Set();
            uniqueUrls.set(url, userContextIds);
          }
          userContextIds.add(userContextId);
        }
      }
    }
    return uniqueUrls;
  }

  /**
   * Return urls registered in the memory table.
   * This is mostly for testing purposes.
   *
   * @returns {Array} Array of {url, userContextId, count} objects.
   */
  static async getDatabaseRegisteredOpenTabsForTests() {
    let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
    let rows = await conn.execute(
      "SELECT url, userContextId, open_count FROM moz_openpages_temp"
    );
    return rows.map(r => ({
      url: r.getResultByIndex(0),
      userContextId: r.getResultByIndex(1),
      count: r.getResultByIndex(2),
    }));
  }

  /**
   * Return userContextId that is used in the moz_openpages_temp table and
   * returned as part of the payload. It differs only for private windows.
   *
   * @param {integer} userContextId Containers user context id
   * @param {boolean} isInPrivateWindow In private browsing window or not
   * @returns {interger} userContextId
   */
  static getUserContextIdForOpenPagesTable(userContextId, isInPrivateWindow) {
    return isInPrivateWindow ? PRIVATE_USER_CONTEXT_ID : userContextId;
  }

  /**
   * Return whether the provided userContextId is for a non-private tab.
   *
   * @param {integer} userContextId the userContextId to evaluate
   * @returns {boolean}
   */
  static isNonPrivateUserContextId(userContextId) {
    return userContextId != PRIVATE_USER_CONTEXT_ID;
  }

  /**
   * Return whether the provided userContextId is for a container.
   *
   * @param {integer} userContextId the userContextId to evaluate
   * @returns {boolean}
   */
  static isContainerUserContextId(userContextId) {
    return userContextId > 0;
  }

  /**
   * Copy over cached open tabs to the memory table once the Urlbar
   * connection has been initialized.
   */
  static promiseDBPopulated =
    lazy.PlacesUtils.largeCacheDBConnDeferred.promise.then(async () => {
      // Must be set before populating.
      UrlbarProviderOpenTabs.memoryTableInitialized = true;
      // Populate the table with the current cached tabs.
      for (let [userContextId, entries] of gOpenTabUrls) {
        for (let [url, count] of entries) {
          await addToMemoryTable(url, userContextId, count).catch(
            console.error
          );
        }
      }
    });

  /**
   * Registers a tab as open.
   *
   * @param {string} url Address of the tab
   * @param {integer|string} userContextId Containers user context id
   * @param {boolean} isInPrivateWindow In private browsing window or not
   */
  static async registerOpenTab(url, userContextId, isInPrivateWindow) {
    // It's fairly common to retrieve the value from an HTML attribute, that
    // means we're getting sometimes a string, sometimes an integer. As we're
    // using this as key of a Map, we must treat it consistently.
    userContextId = parseInt(userContextId);
    if (!Number.isInteger(userContextId)) {
      lazy.logger.error("Invalid userContextId while registering openTab: ", {
        url,
        userContextId,
        isInPrivateWindow,
      });
      return;
    }
    lazy.logger.info("Registering openTab: ", {
      url,
      userContextId,
      isInPrivateWindow,
    });
    userContextId = UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
      userContextId,
      isInPrivateWindow
    );

    let entries = gOpenTabUrls.get(userContextId);
    if (!entries) {
      entries = new Map();
      gOpenTabUrls.set(userContextId, entries);
    }
    entries.set(url, (entries.get(url) ?? 0) + 1);
    await addToMemoryTable(url, userContextId).catch(console.error);
  }

  /**
   * Unregisters a previously registered open tab.
   *
   * @param {string} url Address of the tab
   * @param {integer|string} userContextId Containers user context id
   * @param {boolean} isInPrivateWindow In private browsing window or not
   */
  static async unregisterOpenTab(url, userContextId, isInPrivateWindow) {
    // It's fairly common to retrieve the value from an HTML attribute, that
    // means we're getting sometimes a string, sometimes an integer. As we're
    // using this as key of a Map, we must treat it consistently.
    userContextId = parseInt(userContextId);
    lazy.logger.info("Unregistering openTab: ", {
      url,
      userContextId,
      isInPrivateWindow,
    });
    userContextId = UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
      userContextId,
      isInPrivateWindow
    );

    let entries = gOpenTabUrls.get(userContextId);
    if (entries) {
      let oldCount = entries.get(url);
      if (oldCount == 0) {
        console.error("Tried to unregister a non registered open tab");
        return;
      }
      if (oldCount == 1) {
        entries.delete(url);
        // Note: `entries` might be an empty Map now, though we don't remove it
        // from `gOpenTabUrls` as it's likely to be reused later.
      } else {
        entries.set(url, oldCount - 1);
      }
      await removeFromMemoryTable(url, userContextId).catch(console.error);
    }
  }

  /**
   * Starts querying.
   *
   * @param {object} queryContext The query context object
   * @param {Function} addCallback Callback invoked by the provider to add a new
   *        match.
   * @returns {Promise} resolved when the query stops.
   */
  async startQuery(queryContext, addCallback) {
    // Note: this is not actually expected to be used as an internal provider,
    // because normal history search will already coalesce with the open tabs
    // temp table to return proper frecency.
    // TODO:
    //  * properly search and handle tokens, this is just a mock for now.
    let instance = this.queryInstance;
    let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
    await UrlbarProviderOpenTabs.promiseDBPopulated;
    await conn.executeCached(
      `
      SELECT url, userContextId
      FROM moz_openpages_temp
    `,
      {},
      (row, cancel) => {
        if (instance != this.queryInstance) {
          cancel();
          return;
        }
        addCallback(
          this,
          new lazy.UrlbarResult(
            UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
            UrlbarUtils.RESULT_SOURCE.TABS,
            {
              url: row.getResultByName("url"),
              userContextId: row.getResultByName("userContextId"),
            }
          )
        );
      }
    );
  }
}

/**
 * Adds an open page to the memory table.
 *
 * @param {string} url Address of the page
 * @param {number} userContextId Containers user context id
 * @param {number} [count] The number of times the page is open
 * @returns {Promise} resolved after the addition.
 */
async function addToMemoryTable(url, userContextId, count = 1) {
  if (!UrlbarProviderOpenTabs.memoryTableInitialized) {
    return;
  }
  await lazy.UrlbarProvidersManager.runInCriticalSection(async () => {
    let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
    await conn.executeCached(
      `
      INSERT OR REPLACE INTO moz_openpages_temp (url, userContextId, open_count)
      VALUES ( :url,
                :userContextId,
                IFNULL( ( SELECT open_count + 1
                          FROM moz_openpages_temp
                          WHERE url = :url
                          AND userContextId = :userContextId ),
                        :count
                      )
              )
    `,
      { url, userContextId, count }
    );
  });
}

/**
 * Removes an open page from the memory table.
 *
 * @param {string} url Address of the page
 * @param {number} userContextId Containers user context id
 * @returns {Promise} resolved after the removal.
 */
async function removeFromMemoryTable(url, userContextId) {
  if (!UrlbarProviderOpenTabs.memoryTableInitialized) {
    return;
  }
  await lazy.UrlbarProvidersManager.runInCriticalSection(async () => {
    let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
    await conn.executeCached(
      `
      UPDATE moz_openpages_temp
      SET open_count = open_count - 1
      WHERE url = :url
        AND userContextId = :userContextId
    `,
      { url, userContextId }
    );
  });
}