aboutsummaryrefslogtreecommitdiff
path: root/tools/addon-sdk-1.7/packages/api-utils/docs/xpcom.md
blob: 6d966500ecd04b00ac9c37a7b0876261b7f9b09e (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
<!-- 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/. -->

Module `xpcom` provides low level API for implementing and registering /
unregistering various XCOM interfaces.

## Implementing XPCOM interfaces

Module exports `Unknow` exemplar object, that may be extended to implement
specific XCOM interface(s). For example [nsIObserver]
(https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIObserver) may be
implemented as follows:

    const { Unknown } = require('api-utils/xpcom');
    const { Cc, Ci } = require('chrome')
    const observerService = Cc["@mozilla.org/observer-service;1"].
                            getService(Ci.nsIObserverService);

    // Create my observer exemplar
    const SleepObserver = Unknown.extend({
      interfaces: [ 'nsIObserver' ],    // Interfaces component implements
      topic: 'sleep_notification',
      initialize: function(fn) { this.fn = fn },
      register: function register() {
        observerService.addObserver(this, this.topic, false);
      },
      unregister: function() {
        addObserver.removeObserver(this, this.topic, false);
      },
      observe: function observe(subject, topic, data) {
        this.fn({
          subject: subject,
          type: topic,
          data: data
        });
      }
    });

    // create instances of observers
    let observer = SleepObserver.new(function(event) {
      console.log('Going to sleep!')
    });
    // register observer
    observer.register();

## Implementing XCOM factories

Module exports `Factory` exemplar, object that may be used to create objects
implementing
[nsIFactory](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIFactory)
interface:

    const { Factory } = require('api-utils/xpcom');
    let Request = Unknown.extend({
      interfaces: [ 'nsIRequest' ],
      initialize: function initialize() {
        this.pending = false;
        // Do some initialization
      },
      isPending: function() { return this.pending },
      resume: function() { /* Implementation */ },
      suspend: function() { /* Implementation */ },
      cancel: function() { /* Implementation */ },
      initiate: function() {
        this.pending = true;
        /* Implementation */
      }
    });

    let requestFactory = Factory.new({ component: Request });

Factories registered into a runtime may be accessed from the rest of the
application via standard XPCOM API using factory's auto generated `id`
(optionally you could specify specific `id` by passing it as an option):

    let request = Components.classesByID[requestFactory.id].
      createInstance(Ci.nsIRequest);
    request.isPending()     // => false

Be aware that traditional XPCOM API will always return a wrapped JS objects
exposing only properties defined by a given interface (`nsIRequest`) in our
case:

    request.initiate()      // TypeError: request.initiate is not a function

You still can expose unwrapped JS object, by a special `wrappedJSObject`
property of the component:

    let Request = Unknown.extend({
      get wrappedJSObject() this,
      interfaces: [ 'nsIRequest' ],
      initialize: function initialize() {
        this.pending = false;
        // Do some initialization
      },
      isPending: function() { return this.pending },
      resume: function() { /* Implementation */ },
      suspend: function() { /* Implementation */ },
      cancel: function() { /* Implementation */ },
      initiate: function() {
        this.pending = true;
        /* Implementation */
      }
    });

    let requestFactory = Factory.new({ component: Request });
    let request = Components.classesByID[requestFactory.id].
      createInstance(Ci.nsIRequest);
    request.isPending();     // => false
    request.wrappedJSObject.initiate();
    request.isPending();     // => true

Optionally `Factory.new` may be passed globally unique string in a format of:
`'@domain.com/unique/identifier;1'` as a `contract` option in order to
associate it with it:

    let namedFactory = Factory.new({
      contract: '@examples.com/request/factory;1',
      component: Request
    });

Such factories when registered can be accessed form rest of the application by
human readable `contract` strings:

    let request = Components.classes['@examples.com/request/factory;1'].
                   createInstance(Components.interfaces.nsIRequest);

In addition factories associated with a given `contract` may be replaced at
runtime:

    let renewedFactory = Factory.new({
      contract: '@examples.com/request/factory;1',
      component: Unknown.extend({ /* Implementation */ })
    })

Unfortunately commonly used `Components.classes` won't get updated at runtime
but there is an alternative, more verbose way to access last registered factory
for a given `contract`:

    let id = Components.manager.QueryInterface(Ci.nsIComponentRegistrar).
      contractIDToCID('@examples.com/request/factory;1');
    Components.classesByID[requestFactory.id].
      createInstance(Ci.nsISupports);

Module also exports `factoryByContract` function to simplify this:

    factoryByContract('@examples.com/request/factory;1').
      createInstance(Ci.nsISupports);

It's also recommended to construct factories with an optional `description`
property, providing human readable description of it:

    let factory = Factory.new({
      contract: '@examples.com/request/factory;1',
      description: 'Super duper request factory',
      component: Request
    });

## Registering / Unregistering factories

All factories created using `Factory.new` get automatically registered into
runtime unless explicitly specified otherwise by setting `register` option to
`false`:

    var factoryToRegister = Factory.new({
      register: false,
      component: Unknown.extend({ /* Implementation */ })
    });

Such factories still may be registered manually using exported `register`
function:

    const { register } = require('api-utils/xpcom');
    register(factoryToRegister);

All factories created using `Factory.new` also get unregistered automatically
when add-on is unloaded. This also can be disabled by setting `unregister`
option to `false`.

    var factoryToUnregister = Service.new({
      unregister: false,
      component: Unknown.extend({ /* Implementation */ })
    });

All registered services may be unregistered at any time using exported
`unregister` function:

    unregister(factoryToUnregister);

## Implementing XCOM services

Module exports `Service` exemplar object, that has exact same API as `Factory`
and can be used to register services:

    const { Service } = require('api-utils/xpcom');
    let service = Service.new({
      contract: '@examples/demo/service;1',
      description: 'My demo service',
      component: Unknown.extend({
        // Implementation
        get wrappedJSObject() this
      })
    });

Registered services can be accessed through the rest of the application via
standard XPCOM API:

    let s = Components.classes['@examples/demo/service;1'].
      getService(Components.interfaces.nsISupports);

In contrast to factories, services do not create instances of enclosed
components, they expose component itself. Also please note that idiomatic way
to work with a service is via `getService` method:

    s.wrappedJSObject === service.component // => true