1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5"use strict";
6
7var EXPORTED_SYMBOLS = ["GeckoViewChildModule"];
8
9const { GeckoViewUtils } = ChromeUtils.import(
10  "resource://gre/modules/GeckoViewUtils.jsm"
11);
12
13const { debug, warn } = GeckoViewUtils.initLogging("Module[C]"); // eslint-disable-line no-unused-vars
14
15class GeckoViewChildModule {
16  static initLogging(aModuleName) {
17    this._moduleName = aModuleName;
18    const tag = aModuleName.replace("GeckoView", "") + "[C]";
19    return GeckoViewUtils.initLogging(tag);
20  }
21
22  static create(aGlobal, aModuleName) {
23    return new this(aModuleName || this._moduleName, aGlobal);
24  }
25
26  constructor(aModuleName, aGlobal) {
27    this.moduleName = aModuleName;
28    this.messageManager = aGlobal;
29    this.enabled = false;
30    this.settings = {};
31
32    if (!aGlobal._gvEventDispatcher) {
33      aGlobal._gvEventDispatcher = GeckoViewUtils.getDispatcherForWindow(
34        aGlobal.content
35      );
36      aGlobal.addEventListener(
37        "unload",
38        event => {
39          if (event.target === this.messageManager) {
40            aGlobal._gvEventDispatcher.finalize();
41          }
42        },
43        {
44          mozSystemGroup: true,
45        }
46      );
47    }
48    this.eventDispatcher = aGlobal._gvEventDispatcher;
49
50    this.messageManager.addMessageListener("GeckoView:UpdateSettings", aMsg => {
51      Object.assign(this.settings, aMsg.data);
52      this.onSettingsUpdate();
53    });
54
55    this.messageManager.addMessageListener(
56      "GeckoView:UpdateModuleState",
57      aMsg => {
58        if (aMsg.data.module !== this.moduleName) {
59          return;
60        }
61
62        const { enabled, settings } = aMsg.data;
63
64        if (settings) {
65          Object.assign(this.settings, settings);
66        }
67
68        if (enabled !== this.enabled) {
69          if (!enabled) {
70            this.onDisable();
71          }
72
73          this.enabled = enabled;
74
75          if (enabled) {
76            this.onEnable();
77          }
78        }
79
80        if (settings) {
81          this.onSettingsUpdate();
82        }
83      }
84    );
85
86    this.onInit();
87
88    this.messageManager.sendAsyncMessage("GeckoView:ContentModuleLoaded", {
89      module: this.moduleName,
90    });
91  }
92
93  // Override to initialize module.
94  onInit() {}
95
96  // Override to detect settings change. Access settings via this.settings.
97  onSettingsUpdate() {}
98
99  // Override to enable module after setting a Java delegate.
100  onEnable() {}
101
102  // Override to disable module after clearing the Java delegate.
103  onDisable() {}
104}
105