summaryrefslogtreecommitdiffstats
path: root/toolkit/components/satchel/FormHistoryStartup.sys.mjs
blob: 0ad71cd2b86140753b8ee95b537794a15d07d44f (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
/* 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/. */

const lazy = {};

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

export class FormHistoryStartup {
  classID = Components.ID("{3A0012EB-007F-4BB8-AA81-A07385F77A25}");

  QueryInterface = ChromeUtils.generateQI([
    "nsIObserver",
    "nsISupportsWeakReference",
  ]);

  observe(_subject, topic, _data) {
    switch (topic) {
      case "idle-daily":
      case "formhistory-expire-now":
        lazy.FormHistory.expireOldEntries().catch(console.error);
        break;
      case "profile-after-change":
        this.init();
        break;
    }
  }

  init() {
    if (this.inited) {
      return;
    }
    this.inited = true;

    // triggers needed service cleanup and db shutdown
    Services.obs.addObserver(this, "idle-daily", true);
    Services.obs.addObserver(this, "formhistory-expire-now", true);

    Services.ppmm.addMessageListener(
      "FormHistory:AutoCompleteSearchAsync",
      this
    );
    Services.ppmm.addMessageListener("FormHistory:RemoveEntry", this);
  }

  receiveMessage(message) {
    switch (message.name) {
      case "FormHistory:AutoCompleteSearchAsync":
        this.#onFormHistoryAutoCompleteSearchAsync({
          ...message.data,
          target: message.target,
        });
        break;

      case "FormHistory:RemoveEntry":
        this.#onFormHistoryRemoveEntry(message.data);
        break;
    }
  }

  async #onFormHistoryAutoCompleteSearchAsync({
    id,
    searchString,
    params,
    target,
  }) {
    // This case is only used for the search field. There is a
    // similar algorithm in FormHistoryParent.jsm that uses
    // sendQuery for other form fields.

    const instance = (this._queryInstance = {});
    const results = await lazy.FormHistory.getAutoCompleteResults(
      searchString,
      params,
      (_row, cancel) => {
        if (this._queryInstance != instance) {
          cancel();
        }
      }
    );

    if (this._queryInstance == instance) {
      target.sendAsyncMessage("FormHistory:AutoCompleteSearchResults", {
        id,
        results,
      });
    }
  }

  #onFormHistoryRemoveEntry({ inputName, value, guid }) {
    lazy.FormHistory.update({
      op: "remove",
      fieldname: inputName,
      value,
      guid,
    });
  }
}