forked from wilix-team/iohook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (93 loc) · 2.18 KB
/
index.js
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
'use strict';
const os = require('os');
const EventEmitter = require('events');
const path = require('path');
// Try use handler if runtime and ABI is compatible
try {
const SegfaultHandler = require('segfault-handler');
SegfaultHandler.registerHandler("iohook-crash.log");
} catch (e) {}
const runtime = process.versions['electron'] ? 'electron' : 'node';
const essential = runtime + '-v' + process.versions.modules + '-' + process.platform + '-' + process.arch;
const modulePath = path.join(__dirname, 'builds', essential, 'build', 'Release', 'iohook.node');
console.log('Loading native binary:', modulePath);
let NodeHookAddon = require(modulePath);
const events = {
3: 'keypress',
4: 'keydown',
5: 'keyup',
6: 'mouseclick',
7: 'mousedown',
8: 'mouseup',
9: 'mousemove',
10: 'mousedrag',
11: 'mousewheel'
};
class IOHook extends EventEmitter {
constructor() {
super();
this.active = false;
this.load();
this.setDebug(false);
}
/**
* Start hook process
* @param enableLogger Turn on debug logging
*/
start(enableLogger) {
if (!this.active) {
this.active = true;
this.setDebug(enableLogger);
}
}
/**
* Shutdown event hook
*/
stop() {
if (this.active) {
this.active = false;
}
}
/**
* Load native module
*/
load() {
NodeHookAddon.startHook(this._handler.bind(this), this.debug || false);
}
/**
* Unload native module and stop hook
*/
unload() {
this.stop();
NodeHookAddon.stopHook();
}
/**
* Enable or disable native debug output
* @param {Boolean} mode
*/
setDebug(mode) {
NodeHookAddon.debugEnable(mode ? true : false);
}
/**
* Local event handler. Don't use it in your code!
* @param msg Raw event message
* @private
*/
_handler(msg) {
if (this.active === false) {
return;
}
if (!msg) {
return;
}
if (events[msg.type]) {
let event = msg.mouse || msg.keyboard || msg.wheel;
event.type = events[msg.type];
this.emit(events[msg.type], event);
} else {
console.warn('Unregistered iohook event', msg);
}
}
}
const iohook = new IOHook();
module.exports = iohook;