forked from coldKey1/mouse-hooks
-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
87 lines (73 loc) · 2.59 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
"use strict";
const { EventEmitter } = require("events");
const addon = require("bindings")("global_mouse_events");
let paused = true;
class MouseEvents extends EventEmitter {
constructor() {
super();
if (require("os").platform() !== "win32")
return;
let createdListener = false;
let registeredEvents = [];
this.on("newListener", event => {
if (registeredEvents.indexOf(event) !== -1)
return;
// Enable WM_MOUSEMOVE capture if requested
if(event === "mousemove") {
addon.enableMouseMove();
}
if ((event === "mouseup" || event === "mousedown" || event === "mousemove" || event === "mousewheel") && !createdListener) {
// Careful: this currently "leaks" a thread every time it's called.
// We should probably get around to fixing that.
createdListener = addon.createMouseHook((event, x, y, button, delta) => {
const payload = { x, y };
if (event === "mousewheel") {
payload.delta = FromInt32(delta) / 120;
payload.axis = button;
} else if(event === "mousedown" || event === "mouseup") {
payload.button = button;
const mouseData = FromInt32(delta);
if(mouseData) payload.button = 3 + mouseData;
}
this.emit(event, payload);
});
if (createdListener) {
this.resumeMouseEvents();
}
} else {
return;
}
registeredEvents.push(event);
});
this.on("removeListener", event => {
if (this.listenerCount(event) > 0)
return;
registeredEvents = registeredEvents.filter(x => x !== event);
if (event === "mousemove") {
addon.disableMouseMove();
}
});
}
getPaused() {
return paused;
}
pauseMouseEvents() {
if(paused) return false;
paused = true;
return addon.pauseMouseEvents();
}
resumeMouseEvents() {
if(!paused) return false;
paused = false;
return addon.resumeMouseEvents();
}
}
function FromInt32(x) {
var uint32 = x - Math.floor(x / 4294967296) * 4294967296;
if (uint32 >= 2147483648) {
return (uint32 - 4294967296) / 65536
} else {
return uint32 / 65536;
}
}
module.exports = new MouseEvents();