summaryrefslogtreecommitdiffstats
path: root/comm/suite/chatzilla/js/lib/events.js
blob: b48de11edeb60a4a39edd873407d658968b03914 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * 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/. */

/**
 * Event class for |CEventPump|.
 */
function CEvent (set, type, destObject, destMethod)
{
    this.set = set;
    this.type = type;
    this.destObject = destObject;
    this.destMethod = destMethod;
    this.hooks = new Array();

}

/**
 * The event pump keeps a queue of pending events, processing them on-demand.
 *
 * You should never need to create an instance of this prototype; access the
 * event pump through |client.eventPump|. Most code should only need to use the
 * |addHook|, |getHook| and |removeHookByName| methods.
 */
function CEventPump (eventsPerStep)
{
    /* event routing stops after this many levels, safety valve */
    this.MAX_EVENT_DEPTH = 50;
    /* When there are this many 'used' items in a queue, always clean up. At
     * this point it is MUCH more effecient to remove a block than a single
     * item (i.e. removing 1000 is much much faster than removing 1 item 1000
     * times [1]).
     */
    this.FORCE_CLEANUP_PTR = 1000;
    /* If there are less than this many items in a queue, clean up. This keeps
     * the queue empty normally, and is not that ineffecient [1].
     */
    this.MAX_AUTO_CLEANUP_LEN = 100;
    this.eventsPerStep = eventsPerStep;
    this.queue = new Array();
    this.queuePointer = 0;
    this.bulkQueue = new Array();
    this.bulkQueuePointer = 0;
    this.hooks = new Array();

    /* [1] The delay when removing items from an array (with unshift or splice,
     * and probably most operations) is NOT perportional to the number of items
     * being removed, instead it is proportional to the number of items LEFT.
     * Because of this, it is better to only remove small numbers of items when
     * the queue is small (MAX_AUTO_CLEANUP_LEN), and when it is large remove
     * only large chunks at a time (FORCE_CLEANUP_PTR), reducing the number of
     * resizes being done.
     */
}

CEventPump.prototype.onHook =
function ep_hook(e, hooks)
{
    var h;

    if (typeof hooks == "undefined")
        hooks = this.hooks;

  hook_loop:
    for (h = hooks.length - 1; h >= 0; h--)
    {
        if (!hooks[h].enabled ||
            !matchObject (e, hooks[h].pattern, hooks[h].neg))
            continue hook_loop;

        e.hooks.push(hooks[h]);
        try
        {
            var rv = hooks[h].f(e);
        }
        catch(ex)
        {
            dd("hook #" + h + " '" +
               ((typeof hooks[h].name != "undefined") ? hooks[h].name :
                "") + "' had an error!");
            dd(formatException(ex));
        }
        if ((typeof rv == "boolean") &&
            (rv == false))
        {
            dd("hook #" + h + " '" +
               ((typeof hooks[h].name != "undefined") ? hooks[h].name :
                "") + "' stopped hook processing.");
            return true;
        }
    }

    return false;
}

/**
 * Adds an event hook to be called when matching events are processed.
 *
 * All hooks should be given a meaningful name, to aid removal and debugging.
 * For plugins, an ideal technique for the name is to use |plugin.id| as a
 * prefix (e.g. <tt>plugin.id + "-my-super-hook"</tt>).
 *
 * @param f The function to call when an event matches |pattern|.
 * @param name A unique name for the hook. Used for removing the hook and
 *             debugging.
 * @param neg Optional. If specified with a |true| value, the hook will be
 *            called for events *not* matching |pattern|. Otherwise, the hook
 *            will be called for events matching |pattern|.
 * @param enabled Optional. If specified, sets the initial enabled/disabled
 *                state of the hook. By default, hooks are enabled. See
 *                |getHook|.
 * @param hooks Internal. Do not use.
 */
CEventPump.prototype.addHook =
function ep_addhook(pattern, f, name, neg, enabled, hooks)
{
    if (typeof hooks == "undefined")
        hooks = this.hooks;

    if (typeof f != "function")
        return false;

    if (typeof enabled == "undefined")
        enabled = true;
    else
        enabled = Boolean(enabled);

    neg = Boolean(neg);

    var hook = {
        pattern: pattern,
        f: f,
        name: name,
        neg: neg,
        enabled: enabled
    };

    hooks.push(hook);

    return hook;

}

/**
 * Finds and returns data about a named event hook.
 *
 * You can use |getHook| to change the enabled state of an existing event hook:
 *   <tt>client.eventPump.getHook(myHookName).enabled = false;</tt>
 *   <tt>client.eventPump.getHook(myHookName).enabled = true;</tt>
 *
 * @param name The unique hook name to find and return data about.
 * @param hooks Internal. Do not use.
 * @returns If a match is found, an |Object| with properties matching the
 *          arguments to |addHook| is returned. Otherwise, |null| is returned.
 */
CEventPump.prototype.getHook =
function ep_gethook(name, hooks)
{
    if (typeof hooks == "undefined")
        hooks = this.hooks;

    for (var h in hooks)
        if (hooks[h].name.toLowerCase() == name.toLowerCase())
            return hooks[h];

    return null;

}

/**
 * Removes an existing event hook by its name.
 *
 * @param name The unique hook name to find and remove.
 * @param hooks Internal. Do not use.
 * @returns |true| if the hook was found and removed, |false| otherwise.
 */
CEventPump.prototype.removeHookByName =
function ep_remhookname(name, hooks)
{
    if (typeof hooks == "undefined")
        hooks = this.hooks;

    for (var h in hooks)
        if (hooks[h].name.toLowerCase() == name.toLowerCase())
        {
            arrayRemoveAt (hooks, h);
            return true;
        }

    return false;

}

CEventPump.prototype.removeHookByIndex =
function ep_remhooki(idx, hooks)
{
    if (typeof hooks == "undefined")
        hooks = this.hooks;

    return arrayRemoveAt (hooks, idx);

}

CEventPump.prototype.addEvent =
function ep_addevent (e)
{
    e.queuedAt = new Date();
    this.queue.push(e);
    return true;
}

CEventPump.prototype.addBulkEvent =
function ep_addevent (e)
{
    e.queuedAt = new Date();
    this.bulkQueue.push(e);
    return true;
}

CEventPump.prototype.routeEvent =
function ep_routeevent (e)
{
    var count = 0;

    this.currentEvent = e;

    e.level = 0;
    while (e.destObject)
    {
        e.level++;
        this.onHook (e);
        var destObject = e.destObject;
        e.currentObject = destObject;
        e.destObject = (void 0);

        switch (typeof destObject[e.destMethod])
        {
            case "function":
                if (1)
                    try
                    {
                        destObject[e.destMethod] (e);
                    }
                    catch (ex)
                    {
                        if (typeof ex == "string")
                        {
                            dd ("Error routing event " + e.set + "." +
                                e.type + ": " + ex);
                        }
                        else
                        {
                            dd ("Error routing event " + e.set + "." +
                                e.type + ": " + dumpObjectTree(ex) +
                                " in " + e.destMethod + "\n" + ex);
                            if ("stack" in ex)
                                dd(ex.stack);
                        }
                    }
                else
                    destObject[e.destMethod] (e);

                if (count++ > this.MAX_EVENT_DEPTH)
                    throw "Too many events in chain";
                break;

            case "undefined":
                //dd ("** " + e.destMethod + " does not exist.");
                break;

            default:
                dd ("** " + e.destMethod + " is not a function.");
        }

        if ((e.type != "event-end") && (!e.destObject))
        {
            e.lastSet = e.set;
            e.set = "eventpump";
            e.lastType = e.type;
            e.type = "event-end";
            e.destMethod = "onEventEnd";
            e.destObject = this;
        }

    }

    delete this.currentEvent;

    return true;

}

CEventPump.prototype.stepEvents =
function ep_stepevents()
{
    var i = 0;
    var st, en, e;

    st = new Date();
    while (i < this.eventsPerStep)
    {
        if (this.queuePointer >= this.queue.length)
            break;

        e = this.queue[this.queuePointer++];

        if (e.type == "yield")
            break;

        this.routeEvent(e);
        i++;
    }
    while (i < this.eventsPerStep)
    {
        if (this.bulkQueuePointer >= this.bulkQueue.length)
            break;

        e = this.bulkQueue[this.bulkQueuePointer++];

        if (e.type == "yield")
            break;

        this.routeEvent(e);
        i++;
    }
    en = new Date();

    // i == number of items handled this time.
    // We only want to do this if we handled at least 25% of our step-limit
    // and if we have a sane interval between st and en (not zero).
    if ((i * 4 >= this.eventsPerStep) && (en - st > 0))
    {
        // Calculate the number of events that can be processed in 400ms.
        var newVal = (400 * i) / (en - st);

        // If anything skews it majorly, limit it to a minimum value.
        if (newVal < 10)
            newVal = 10;

        // Adjust the step-limit based on this "target" limit, but only do a 
        // 25% change (underflow filter).
        this.eventsPerStep += Math.round((newVal - this.eventsPerStep) / 4);
    }

    // Clean up if we've handled a lot, or the queue is small.
    if ((this.queuePointer >= this.FORCE_CLEANUP_PTR) ||
        (this.queue.length <= this.MAX_AUTO_CLEANUP_LEN))
    {
        this.queue.splice(0, this.queuePointer);
        this.queuePointer = 0;
    }

    // Clean up if we've handled a lot, or the queue is small.
    if ((this.bulkQueuePointer >= this.FORCE_CLEANUP_PTR) ||
        (this.bulkQueue.length <= this.MAX_AUTO_CLEANUP_LEN))
    {
        this.bulkQueue.splice(0, this.bulkQueuePointer);
        this.bulkQueuePointer = 0;
    }

    return i;

}