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
|
"use strict";
const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
Cu.import("resource://gre/modules/ExtensionUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter",
"resource://devtools/shared/event-emitter.js");
XPCOMUtils.defineLazyServiceGetter(this, "idleService",
"@mozilla.org/widget/idleservice;1",
"nsIIdleService");
const {
SingletonEventManager,
} = ExtensionUtils;
// WeakMap[Extension -> Object]
var observersMap = new WeakMap();
function getObserverInfo(extension, context) {
let observerInfo = observersMap.get(extension);
if (!observerInfo) {
observerInfo = {
observer: null,
detectionInterval: 60,
};
observersMap.set(extension, observerInfo);
context.callOnClose({
close: () => {
let {observer, detectionInterval} = observersMap.get(extension);
if (observer) {
idleService.removeIdleObserver(observer, detectionInterval);
}
observersMap.delete(extension);
},
});
}
return observerInfo;
}
function getObserver(extension, context) {
let observerInfo = getObserverInfo(extension, context);
let {observer, detectionInterval} = observerInfo;
if (!observer) {
observer = {
observe: function(subject, topic, data) {
if (topic == "idle" || topic == "active") {
this.emit("stateChanged", topic);
}
},
};
EventEmitter.decorate(observer);
idleService.addIdleObserver(observer, detectionInterval);
observerInfo.observer = observer;
observerInfo.detectionInterval = detectionInterval;
}
return observer;
}
function setDetectionInterval(extension, context, newInterval) {
let observerInfo = getObserverInfo(extension, context);
let {observer, detectionInterval} = observerInfo;
if (observer) {
idleService.removeIdleObserver(observer, detectionInterval);
idleService.addIdleObserver(observer, newInterval);
}
observerInfo.detectionInterval = newInterval;
}
extensions.registerSchemaAPI("idle", "addon_parent", context => {
let {extension} = context;
return {
idle: {
queryState: function(detectionIntervalInSeconds) {
if (idleService.idleTime < detectionIntervalInSeconds * 1000) {
return Promise.resolve("active");
}
return Promise.resolve("idle");
},
setDetectionInterval: function(detectionIntervalInSeconds) {
setDetectionInterval(extension, context, detectionIntervalInSeconds);
},
onStateChanged: new SingletonEventManager(context, "idle.onStateChanged", fire => {
let listener = (event, data) => {
context.runSafe(fire, data);
};
getObserver(extension, context).on("stateChanged", listener);
return () => {
getObserver(extension, context).off("stateChanged", listener);
};
}).api(),
},
};
});
|