-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyboard_remapper.c
338 lines (293 loc) · 10.5 KB
/
keyboard_remapper.c
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
#define VERSION "1.1.2"
#include <windows.h>
#include <stdio.h>
#include <ctype.h>
#include <stdint.h>
#include <time.h>
#include "input.h"
#include "keys.c"
#include "remap.c"
#include "mouse.c"
#pragma comment(lib, "winmm.lib") // for timeGetTime()
// Globals
// ----------------
HHOOK g_keyboard_hook;
HHOOK g_mouse_hook;
HANDLE ghEvent;
HANDLE ghTimerQueue = NULL;
struct InputBuffer g_input_buffer;
void debug_file(const char * message) {
FILE * log_file = fopen("debug.log", "a");
if (log_file == NULL) {
return;
}
time_t now = time(NULL);
char * timestamp = ctime(&now);
timestamp[strlen(timestamp) - 1] = '\0';
fprintf(log_file, "[%s] %s\n", timestamp, message);
fclose(log_file);
}
void debug_print(const char * color, const char * format, ...) {
va_list args;
va_start(args, format);
printf("%s", color);
vprintf(format, args);
printf("%s", RESET);
va_end(args);
}
void send_input(int scan_code, int virt_code, enum Direction direction, int remap_id, struct InputBuffer * input_buffer) {
if (virt_code) {
uint32_t n, tail;
int index;
n = input_buffer_move_prod_head(input_buffer, &tail);
index = tail & INPUT_BUFFER_MASK;
if (n == 0) {
if (g_debug) debug_print(RED, "\nError: input buffer is full!");
debug_file("Error: input buffer is full!");
return;
}
ZeroMemory(&input_buffer->inputs[index], sizeof(INPUT));
input_buffer->inputs[index].type = INPUT_KEYBOARD;
input_buffer->inputs[index].ki.time = 0;
input_buffer->inputs[index].ki.dwExtraInfo = (ULONG_PTR)(INJECTED_KEY_ID | remap_id);
input_buffer->inputs[index].ki.wScan = scan_code;
input_buffer->inputs[index].ki.wVk = ((g_scancode && scan_code != 0x00) ? 0 : virt_code);
// Per MS Docs: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-keybd_even
// we need to flag whether "the scan code was preceded by a prefix byte having the value 0xE0 (224)"
int is_extended_key = scan_code>>8 == 0xE0;
input_buffer->inputs[index].ki.dwFlags = (direction == UP ? KEYEVENTF_KEYUP : 0) |
(is_extended_key ? KEYEVENTF_EXTENDEDKEY : 0) |
((g_scancode && scan_code != 0x00) ? KEYEVENTF_SCANCODE : 0);
input_buffer_update_tail(&input_buffer->prod, tail, n);
} else {
mouse_emulation(scan_code, direction, remap_id, &g_input_buffer);
}
}
LRESULT CALLBACK mouse_callback(int msg_code, WPARAM w_param, LPARAM l_param) {
int block_input = 0;
// Per MS docs we should only act for HC_ACTION's
if (msg_code == HC_ACTION) {
MSLLHOOKSTRUCT * data = (MSLLHOOKSTRUCT *)l_param;
int is_injected = ((LLMHF_INJECTED & data->flags) && data->dwExtraInfo != 0x00) ? 1 : 0;
switch (w_param) {
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_XBUTTONDOWN:
case WM_MOUSEWHEEL:
// Since no key corresponds to the mouse inputs; use a dummy input
block_input = handle_input(
w_param,
MOUSE_DUMMY_VK,
DOWN,
data->time,
is_injected,
data->flags,
data->dwExtraInfo,
&g_input_buffer);
}
if (block_input == -1) {
uint32_t n, tail;
int index;
n = input_buffer_move_prod_head(&g_input_buffer, &tail);
index = tail & INPUT_BUFFER_MASK;
if (n == 0) {
if (g_debug) debug_print(RED, "\nError: input buffer is full!");
debug_file("Error: input buffer is full!");
return 1;
}
ZeroMemory(&g_input_buffer.inputs[index], sizeof(INPUT));
g_input_buffer.inputs[index].type = INPUT_MOUSE;
g_input_buffer.inputs[index].mi.dwExtraInfo = (ULONG_PTR)INJECTED_KEY_ID;
switch (w_param) {
case WM_LBUTTONDOWN:
g_input_buffer.inputs[index].mi.dwFlags |= MOUSEEVENTF_LEFTDOWN;
break;
case WM_RBUTTONDOWN:
g_input_buffer.inputs[index].mi.dwFlags |= MOUSEEVENTF_RIGHTDOWN;
break;
case WM_MBUTTONDOWN:
g_input_buffer.inputs[index].mi.dwFlags |= MOUSEEVENTF_MIDDLEDOWN;
break;
case WM_XBUTTONDOWN:
g_input_buffer.inputs[index].mi.dwFlags |= MOUSEEVENTF_XDOWN;
g_input_buffer.inputs[index].mi.mouseData = data->mouseData;
break;
case WM_MOUSEWHEEL:
g_input_buffer.inputs[index].mi.dwFlags |= MOUSEEVENTF_WHEEL;
g_input_buffer.inputs[index].mi.mouseData = ((int)data->mouseData)>>16;
break;
}
input_buffer_update_tail(&g_input_buffer.prod, tail, n);
}
}
if (!input_buffer_empty(&g_input_buffer)) {
SetEvent(ghEvent);
}
return (block_input) ? 1 : CallNextHookEx(NULL, msg_code, w_param, l_param);
}
LRESULT CALLBACK keyboard_callback(int msg_code, WPARAM w_param, LPARAM l_param) {
int block_input = 0;
// Per MS docs we should only act for HC_ACTION's
if (msg_code == HC_ACTION) {
KBDLLHOOKSTRUCT * data = (KBDLLHOOKSTRUCT *)l_param;
enum Direction direction = (LLKHF_UP & data->flags) ? UP : DOWN;
int is_injected = (LLKHF_INJECTED & data->flags) ? 1 : 0;
block_input = handle_input(
data->scanCode,
data->vkCode,
direction,
data->time,
is_injected,
data->flags,
data->dwExtraInfo,
&g_input_buffer
);
if (block_input == -1) {
send_input(data->scanCode, data->vkCode, direction, 0, &g_input_buffer);
}
if (!input_buffer_empty(&g_input_buffer)) {
SetEvent(ghEvent);
}
}
return (block_input) ? 1 : CallNextHookEx(NULL, msg_code, w_param, l_param);
}
void enable_ansi_support() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hConsole, &mode);
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hConsole, mode);
}
void create_console() {
if (AllocConsole()) {
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
enable_ansi_support();
}
}
void destroy_console() {
fclose(stdout);
fclose(stderr);
FreeConsole();
}
int load_config_file(wchar_t * path) {
FILE * file;
char line[255];
if (_wfopen_s(&file, path, L"r") > 0) {
printf("Cannot open configuration file '%ws'. Make sure it is in the same directory as 'keyboard_remapper.exe'.\n",
path);
return 1;
}
int linenum = 1;
while (fgets(line, 255, file)) {
if (load_config_line((char *)&line, linenum++)) {
fclose(file);
return 1;
}
};
fclose(file);
return load_config_line(NULL, linenum++);
}
void put_config_path(wchar_t * path) {
HMODULE module = GetModuleHandleW(NULL);
GetModuleFileNameW(module, path, MAX_PATH);
path[wcslen(path) - strlen("keyboard_remapper.exe")] = '\0';
wcscat(path, L"config.txt");
}
void rehook() {
UnhookWindowsHookEx(g_keyboard_hook);
UnhookWindowsHookEx(g_mouse_hook);
g_mouse_hook = SetWindowsHookEx(WH_MOUSE_LL, mouse_callback, NULL, 0);
g_keyboard_hook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboard_callback, NULL, 0);
DEBUG(1, debug_print(RED, "\nRehooked!"));
}
DWORD WINAPI send_input_thread(LPVOID arg) {
uint32_t n, tail;
int index;
struct InputBuffer * input_buffer = (struct InputBuffer *)arg;
while (1) {
WaitForSingleObject(ghEvent, INFINITE);
ResetEvent(ghEvent);
while (!input_buffer_empty(input_buffer)) {
n = input_buffer_move_cons_head(input_buffer, -2, &tail);
index = tail & INPUT_BUFFER_MASK;
if (n > 0) {
SendInput(n, &input_buffer->inputs[index], sizeof(INPUT));
input_buffer_update_tail(&input_buffer->cons, tail, n);
}
}
}
}
void close_all() {
UnhookWindowsHookEx(g_keyboard_hook);
UnhookWindowsHookEx(g_mouse_hook);
if (g_active) g_active = 0;
if (ghTimer) DeleteTimerQueueTimer(ghTimerQueue, ghTimer, NULL);
CloseHandle(ghEvent);
DeleteTimerQueue(ghTimerQueue);
unlock_all(&g_input_buffer);
free_all();
}
int main() {
HANDLE threadHandle;
DWORD threadId;
// Initialization may print errors to stdout, create a console to show that output.
create_console();
debug_print(GREEN, "== keyboard_remapper %s ==\n\n", VERSION);
HANDLE mutex = CreateMutex(NULL, TRUE, "keyboard_remapper.single-instance");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
printf("keyboard_remapper.exe is already running!\n");
goto end;
}
wchar_t config_path[MAX_PATH];
put_config_path(config_path);
int err = load_config_file(config_path);
if (err) {
goto end;
}
if (g_priority) {
if (!SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS)) {
printf("Error setting process priority: %d\n", GetLastError());
goto end;
}
if (!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)) {
printf("Error setting thread priority: %d\n", GetLastError());
goto end;
}
}
ghEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (ghEvent == NULL) {
printf("CreateEvent error: %d\n", GetLastError());
goto end;
}
input_buffer_init(&g_input_buffer);
threadHandle = CreateThread(NULL, 0, send_input_thread, &g_input_buffer, 0, &threadId);
if (threadHandle == NULL) {
printf("Error creating the thread: %d\n", GetLastError());
goto end;
}
ghTimerQueue = CreateTimerQueue();
g_debug = g_debug || getenv("DEBUG") != NULL;
g_mouse_hook = SetWindowsHookEx(WH_MOUSE_LL, mouse_callback, NULL, 0);
g_keyboard_hook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboard_callback, NULL, 0);
// We're all good if we got this far. Hide the console window unless we're debugging.
if (g_debug) {
printf("-- DEBUG MODE --\n");
} else {
destroy_console();
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
close_all();
return 0;
end:
printf("\nPress any key to exit...\n");
getch();
return 1;
}