summaryrefslogtreecommitdiffstats
path: root/toolkit/jetpack/sdk/system/events.js
blob: 0cf525aa199065bac91e5b74a152682f63ff8e85 (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
/* 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/. */

'use strict';

module.metadata = {
  'stability': 'unstable'
};

const { Cc, Ci, Cu } = require('chrome');
const { Unknown } = require('../platform/xpcom');
const { Class } = require('../core/heritage');
const { ns } = require('../core/namespace');
const observerService =
  Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
const { addObserver, removeObserver, notifyObservers } = observerService;
const { ShimWaiver } = Cu.import("resource://gre/modules/ShimWaiver.jsm");
const addObserverNoShim = ShimWaiver.getProperty(observerService, "addObserver");
const removeObserverNoShim = ShimWaiver.getProperty(observerService, "removeObserver");
const notifyObserversNoShim = ShimWaiver.getProperty(observerService, "notifyObservers");
const unloadSubject = require('@loader/unload');

const Subject = Class({
  extends: Unknown,
  initialize: function initialize(object) {
    // Double-wrap the object and set a property identifying the
    // wrappedJSObject as one of our wrappers to distinguish between
    // subjects that are one of our wrappers (which we should unwrap
    // when notifying our observers) and those that are real JS XPCOM
    // components (which we should pass through unaltered).
    this.wrappedJSObject = {
      observersModuleSubjectWrapper: true,
      object: object
    };
  },
  getScriptableHelper: function() {},
  getInterfaces: function() {}
});

function emit(type, event, shimmed = false) {
  // From bug 910599
  // We must test to see if 'subject' or 'data' is a defined property
  // of the event object, but also allow primitives to be passed in,
  // which the `in` operator breaks, yet `null` is an object, hence
  // the long conditional
  let subject = event && typeof event === 'object' && 'subject' in event ?
    Subject(event.subject) :
    null;
  let data = event && typeof event === 'object' ?
    // An object either returns its `data` property or null
    ('data' in event ? event.data : null) :
    // All other types return themselves (and cast to strings/null
    // via observer service)
    event;
  if (shimmed) {
    notifyObservers(subject, type, data);
  } else {
    notifyObserversNoShim(subject, type, data);
  }
}
exports.emit = emit;

const Observer = Class({
  extends: Unknown,
  initialize: function initialize(listener) {
    this.listener = listener;
  },
  interfaces: [ 'nsIObserver', 'nsISupportsWeakReference' ],
  observe: function(subject, topic, data) {
    // Extract the wrapped object for subjects that are one of our
    // wrappers around a JS object.  This way we support both wrapped
    // subjects created using this module and those that are real
    // XPCOM components.
    if (subject && typeof(subject) == 'object' &&
        ('wrappedJSObject' in subject) &&
        ('observersModuleSubjectWrapper' in subject.wrappedJSObject))
      subject = subject.wrappedJSObject.object;

    try {
      this.listener({
        type: topic,
        subject: subject,
        data: data
      });
    }
    catch (error) {
      console.exception(error);
    }
  }
});

const subscribers = ns();

function on(type, listener, strong, shimmed = false) {
  // Unless last optional argument is `true` we use a weak reference to a
  // listener.
  let weak = !strong;
  // Take list of observers associated with given `listener` function.
  let observers = subscribers(listener);
  // If `observer` for the given `type` is not registered yet, then
  // associate an `observer` and register it.
  if (!(type in observers)) {
    let observer = Observer(listener);
    observers[type] = observer;
    if (shimmed) {
      addObserver(observer, type, weak);
    } else {
      addObserverNoShim(observer, type, weak);
    }
    // WeakRef gymnastics to remove all alive observers on unload
    let ref = Cu.getWeakReference(observer);
    weakRefs.set(observer, ref);
    stillAlive.set(ref, type);
    wasShimmed.set(ref, shimmed);
  }
}
exports.on = on;

function once(type, listener, shimmed = false) {
  // Note: this code assumes order in which listeners are called, which is fine
  // as long as dispatch happens in same order as listener registration which
  // is the case now. That being said we should be aware that this may break
  // in a future if order will change.
  on(type, listener, shimmed);
  on(type, function cleanup() {
    off(type, listener, shimmed);
    off(type, cleanup, shimmed);
  }, true, shimmed);
}
exports.once = once;

function off(type, listener, shimmed = false) {
  // Take list of observers as with the given `listener`.
  let observers = subscribers(listener);
  // If `observer` for the given `type` is registered, then
  // remove it & unregister.
  if (type in observers) {
    let observer = observers[type];
    delete observers[type];
    if (shimmed) {
      removeObserver(observer, type);
    } else {
      removeObserverNoShim(observer, type);
    }
    stillAlive.delete(weakRefs.get(observer));
    wasShimmed.delete(weakRefs.get(observer));
  }
}
exports.off = off;

// must use WeakMap to keep reference to all the WeakRefs (!), see bug 986115
var weakRefs = new WeakMap();

// and we're out of beta, we're releasing on time!
var stillAlive = new Map();

var wasShimmed = new Map();

on('sdk:loader:destroy', function onunload({ subject, data: reason }) {
  // using logic from ./unload, to avoid a circular module reference
  if (subject.wrappedJSObject === unloadSubject) {
    off('sdk:loader:destroy', onunload, false);

    // don't bother
    if (reason === 'shutdown') 
      return;

    stillAlive.forEach( (type, ref) => {
      let observer = ref.get();
      if (observer) {
        if (wasShimmed.get(ref)) {
          removeObserver(observer, type);
        } else {
          removeObserverNoShim(observer, type);
        }
      }
    })
  }
  // a strong reference
}, true, false);