-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathremap.c
More file actions
599 lines (521 loc) · 17.2 KB
/
remap.c
File metadata and controls
599 lines (521 loc) · 17.2 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include "input.h"
#include "keys.c"
#ifdef _WIN32
# define strcasecmp _stricmp
#endif
// Types
// --------------------------------------
#define MAX_CHORD 8
#define MAX_STEPS 8
enum State {
IDLE,
HELD_DOWN_ALONE,
HELD_DOWN_WITH_OTHER,
};
struct Step {
KEY_DEF * keys[MAX_CHORD];
int count;
};
struct Remap
{
KEY_DEF * from;
KEY_DEF * suppress[MAX_CHORD];
int suppress_count;
struct Step when_alone[MAX_STEPS];
int when_alone_steps;
struct Step with_other;
int with_other_steps;
unsigned long long key_down_time;
int timeout_ms;
enum State state;
struct Remap * next;
};
// Globals
// --------------------------------------
int g_paused = 0;
int g_debug = 0;
int g_show_tray = 1;
int g_timeout_ms = 0;
char g_last_error[256] = {0};
struct Remap * g_remap_list;
struct Remap * g_remap_parsee = 0;
// Time (provided by host: dual-key-remap.c or tests.c)
extern unsigned long long (*get_time_ms)(void);
// Debug Logging
// --------------------------------------
extern int can_print(void);
#define log_error(fmt, ...) do { \
if (g_debug && can_print()) { \
printf(fmt, ##__VA_ARGS__); \
} \
snprintf(g_last_error, sizeof(g_last_error), fmt, ##__VA_ARGS__); \
} while(0)
#define log_info(fmt, ...) do { \
if (g_debug && can_print()) { \
printf(fmt, ##__VA_ARGS__); \
} \
} while(0)
char * fmt_dir(enum Direction dir)
{
return dir ? "DOWN" : "UP";
}
int log_indent_level = 0;
int log_counter = 1;
void print_log_prefix()
{
log_info("\n%03d. ", log_counter++);
for (int i = 0; i < log_indent_level; i++)
{
log_info("\t");
}
}
void log_handle_input_start(int scan_code, int virt_code, int dir, int is_injected)
{
print_log_prefix();
log_info("[%s] %s %s (scan:0x%02x virt:0x%02x)",
is_injected ? "output" : "input",
friendly_virt_code_name(virt_code),
fmt_dir(dir),
scan_code,
virt_code);
log_indent_level++;
}
void log_handle_input_end(int scan_code, int virt_code, int dir, int is_injected, int block_input)
{
log_indent_level--;
if (block_input) {
print_log_prefix();
log_info("#blocked-input# %s %s",
friendly_virt_code_name(virt_code),
fmt_dir(dir));
}
}
// Remapping
// -------------------------------------
struct Remap * new_remap(KEY_DEF * from)
{
struct Remap * remap = calloc(1, sizeof(struct Remap));
remap->from = from;
remap->state = IDLE;
remap->when_alone_steps = -1;
remap->with_other_steps = -1;
remap->timeout_ms = -1;
return remap;
}
void register_remap(struct Remap * remap)
{
if (g_remap_list) {
struct Remap * tail = g_remap_list;
while (tail->next) tail = tail->next;
tail->next = remap;
} else {
g_remap_list = remap;
}
}
struct Remap * find_remap_for_virt_code(int virt_code)
{
struct Remap * remap = g_remap_list;
while(remap) {
if (remap->from->virt_code == virt_code) {
return remap;
}
remap = remap->next;
}
return 0;
}
static void send_chord(const char *name, KEY_DEF **keys, int count, enum Direction dir)
{
if (count <= 0) return;
if (g_debug && can_print()) {
print_log_prefix();
log_info("(sending:%s) ", name);
for (int i = 0; i < count; ++i) {
log_info("%s", keys[i]->name);
if (i+1 < count) log_info("+");
}
log_info(" %s", fmt_dir(dir));
}
if (dir == DOWN) {
for (int i = 0; i < count; ++i)
send_input(keys[i]->scan_code, keys[i]->virt_code, DOWN);
} else {
for (int i = count - 1; i >= 0; --i)
send_input(keys[i]->scan_code, keys[i]->virt_code, UP);
}
}
static int parse_chord(char *value, KEY_DEF **out)
{
while (*value && isspace((unsigned char)*value)) ++value;
if (*value == '\0') return 0;
if (strcasecmp(value, "NOOP") == 0) return 0;
int count = 0;
char *p = value;
while (*p) {
while (isspace((unsigned char)*p)) ++p;
char *start = p;
while (*p && *p != '+') ++p;
char saved = *p;
*p = '\0';
size_t len = strlen(start);
while (len > 0 && isspace((unsigned char)start[len-1])) start[--len] = '\0';
if (len > 0) {
for (char *c = start; *c; c++) *c = toupper((unsigned char)*c);
KEY_DEF *k = find_key_def_by_name(start);
if (!k) return -1;
if (count >= MAX_CHORD) return -1;
out[count++] = k;
} else {
return -1;
}
if (saved == '\0') break;
*p++ = saved;
}
return count;
}
static int parse_steps(char *value, struct Step *out, int max_steps)
{
while (*value && isspace((unsigned char)*value)) ++value;
if (*value == '\0') return 0;
if (strcasecmp(value, "NOOP") == 0) return 0;
int step_count = 0;
char *p = value;
while (*p) {
while (isspace((unsigned char)*p)) ++p;
if (*p == '\0') break;
char *start = p;
while (*p && *p != ',') ++p;
char saved = *p;
*p = '\0';
if (step_count >= max_steps) return -1;
int count = parse_chord(start, out[step_count].keys);
if (count <= 0) return -1;
out[step_count].count = count;
step_count++;
if (saved == '\0') break;
*p++ = saved;
// After a comma, the next step must not be empty
while (isspace((unsigned char)*p)) ++p;
if (*p == '\0' || *p == ',') return -1;
}
return step_count;
}
/* @return block_input */
int event_remapped_key_down(struct Remap * remap)
{
if (remap->state == IDLE) {
// Release suppressed modifiers before changing state, otherwise
// the injected UPs would trigger event_other_input for this remap
for (int i = 0; i < remap->suppress_count; i++) {
send_input(remap->suppress[i]->scan_code,
remap->suppress[i]->virt_code, UP);
}
remap->state = HELD_DOWN_ALONE;
remap->key_down_time = get_time_ms();
}
return 1;
}
/* @return block_input */
int event_remapped_key_up(struct Remap * remap)
{
// If we receive a key UP while IDLE, it means our hook never saw the
// matching DOWN (e.g. the OS skipped our hook for that event). Without
// this guard we'd incorrectly fire when_alone on the orphaned UP. We
// pass it through (return 0) so the key doesn't appear stuck, since the
// DOWN already leaked through unblocked.
if (remap->state == IDLE) {
return 0;
}
if (remap->state == HELD_DOWN_WITH_OTHER) {
remap->state = IDLE;
send_chord("with_other", remap->with_other.keys, remap->with_other.count, UP);
} else {
int send_alone = 1;
unsigned long long elapsed = 0;
int timeout_ms = (remap->timeout_ms >= 0) ? remap->timeout_ms : g_timeout_ms;
if (timeout_ms > 0 && remap->key_down_time) {
elapsed = get_time_ms() - remap->key_down_time;
if (elapsed > (unsigned long long)timeout_ms) send_alone = 0;
}
remap->key_down_time = 0;
remap->state = IDLE;
if (send_alone) {
for (int i = 0; i < remap->when_alone_steps; i++) {
send_chord("when_alone", remap->when_alone[i].keys, remap->when_alone[i].count, DOWN);
send_chord("when_alone", remap->when_alone[i].keys, remap->when_alone[i].count, UP);
}
} else if (timeout_ms > 0 && elapsed > 0) {
if (g_debug && can_print()) {
print_log_prefix();
log_info("(suppressed:when_alone) held %llums > %dms", elapsed, timeout_ms);
}
}
}
return 1;
}
/* @return block_input */
int event_other_input()
{
struct Remap * remap = g_remap_list;
while(remap) {
if (remap->state == HELD_DOWN_ALONE) {
remap->state = HELD_DOWN_WITH_OTHER;
remap->key_down_time = 0;
send_chord("with_other", remap->with_other.keys, remap->with_other.count, DOWN);
}
remap = remap->next;
}
return 0;
}
/* @return block_input */
int handle_input(int scan_code, int virt_code, int direction, int is_injected)
{
log_handle_input_start(scan_code, virt_code, direction, is_injected);
if (g_paused) {
log_handle_input_end(scan_code, virt_code, direction, is_injected, 0);
return 0;
}
// Note: injected keys are not remapped to avoid recursion loops and to support key swapping
struct Remap * remap_for_input = is_injected ? 0 : find_remap_for_virt_code(virt_code);
int block_input = 0;
if (!remap_for_input) {
block_input = event_other_input();
} else {
block_input = direction == DOWN
? event_remapped_key_down(remap_for_input)
: event_remapped_key_up(remap_for_input);
}
log_handle_input_end(scan_code, virt_code, direction, is_injected, block_input);
return block_input;
}
void cleanup_held_keys()
{
int prev = g_paused;
g_paused = 1;
struct Remap * remap = g_remap_list;
while (remap) {
if (remap->state == HELD_DOWN_WITH_OTHER && remap->with_other.count > 0) {
send_chord("with_other", remap->with_other.keys, remap->with_other.count, UP);
remap->state = IDLE;
}
remap = remap->next;
}
g_paused = prev;
}
// Config
// ---------------------------------
void trim_newline(char * str)
{
str[strcspn(str, "\r\n")] = 0;
}
int parsee_is_valid()
{
return g_remap_parsee &&
g_remap_parsee->from &&
(g_remap_parsee->when_alone_steps >= 0) &&
(g_remap_parsee->with_other_steps >= 0);
}
/* @return error */
int load_config_line(char *line, int linenum)
{
char buf[256];
if (strlen(line) >= sizeof(buf) - 1) {
log_error(
"Config error (line %d): line too long (max %zu chars)\n",
linenum, sizeof(buf) - 2);
return 1;
}
strcpy(buf, line);
line = buf;
// ignore blanks / comments
trim_newline(line);
if (line[0] == '\0' || line[0] == '#')
return 0;
// split key = value
char *after_eq = strchr(line, '=');
if (!after_eq) {
log_error(
"Config error (line %d): expected key=value\n", linenum);
return 1;
}
*after_eq++ = '\0'; // terminate key, advance to value
// right-trim key, left-trim value
while (*line && isspace((unsigned char)line[strlen(line) - 1]))
line[strlen(line) - 1] = '\0';
while (isspace((unsigned char)*after_eq))
++after_eq;
// toggle debug mode
if (strcmp(line, "debug") == 0) {
if (strcmp(after_eq, "1") == 0 || strcasecmp(after_eq, "true") == 0) {
g_debug = 1;
return 0;
}
if (strcmp(after_eq, "0") == 0 || strcasecmp(after_eq, "false") == 0) {
g_debug = 0;
return 0;
}
log_error(
"Config error (line %d): debug must be 0/1/true/false\n",
linenum);
return 1;
}
// toggle tray visibility
if (strcmp(line, "show_tray") == 0) {
if (strcmp(after_eq, "1") == 0 || strcasecmp(after_eq, "true") == 0) {
g_show_tray = 1;
return 0;
}
if (strcmp(after_eq, "0") == 0 || strcasecmp(after_eq, "false") == 0) {
g_show_tray = 0;
return 0;
}
log_error(
"Config error (line %d): show_tray must be 0/1/true/false\n",
linenum);
return 1;
}
// tap timeout
if (strcmp(line, "timeout_ms") == 0) {
int value = atoi(after_eq);
if (value < 0) {
log_error(
"Config error (line %d): timeout_ms must be >= 0\n",
linenum);
return 1;
}
if (g_remap_parsee && (g_remap_parsee->from || g_remap_parsee->when_alone_steps >= 0 || g_remap_parsee->with_other_steps >= 0)) {
g_remap_parsee->timeout_ms = value;
} else {
g_timeout_ms = value;
}
return 0;
}
// remap directives
int field = 0; // 1 = remap_key, 2 = when_alone, 3 = with_other
if (strcmp(line, "remap_key") == 0) field = 1;
else if (strcmp(line, "when_alone") == 0) field = 2;
else if (strcmp(line, "with_other") == 0) field = 3;
if (field) {
if (!g_remap_parsee)
g_remap_parsee = new_remap(0);
if (field == 1) {
if (g_remap_parsee->from && !parsee_is_valid()) {
log_error(
"Config error (line %d): Incomplete remapping.\n"
"Each remap needs remap_key, when_alone and with_other\n"
"before another remap_key.\n",
linenum);
return 1;
}
// Parse remap_key: KEY or KEY-SUPPRESS1-SUPPRESS2
char *dash = strchr(after_eq, '-');
if (dash) *dash = '\0';
// right-trim key name (needed when spaces surround the dash)
{
size_t klen = strlen(after_eq);
while (klen > 0 && isspace((unsigned char)after_eq[klen-1]))
after_eq[--klen] = '\0';
}
for (char *c = after_eq; *c; c++) *c = toupper((unsigned char)*c);
KEY_DEF *key_def = find_key_def_by_name(after_eq);
if (!key_def) {
log_error(
"Config error (line %d): invalid key name '%s'\n"
"See the online docs for the latest list of key names.\n",
linenum, after_eq);
return 1;
}
g_remap_parsee->from = key_def;
if (dash) {
char *p = dash + 1;
while (isspace((unsigned char)*p)) ++p;
if (*p == '\0' || *p == '-') {
log_error("Config error (line %d): empty suppress key\n", linenum);
return 1;
}
while (*p) {
while (isspace((unsigned char)*p)) ++p;
if (*p == '\0') break;
char *start = p;
while (*p && *p != '-') ++p;
char saved = *p;
*p = '\0';
size_t len = strlen(start);
while (len > 0 && isspace((unsigned char)start[len-1]))
start[--len] = '\0';
if (len == 0) {
log_error("Config error (line %d): empty suppress key\n", linenum);
return 1;
}
for (char *c = start; *c; c++) *c = toupper((unsigned char)*c);
KEY_DEF *sk = find_key_def_by_name(start);
if (!sk) {
log_error(
"Config error (line %d): invalid suppress key '%s'\n"
"See the online docs for the latest list of key names.\n",
linenum, start);
return 1;
}
if (g_remap_parsee->suppress_count >= MAX_CHORD) {
log_error("Config error (line %d): too many suppress keys\n", linenum);
return 1;
}
g_remap_parsee->suppress[g_remap_parsee->suppress_count++] = sk;
if (saved == '\0') break;
*p++ = saved;
}
}
} else if (field == 2) {
int count = parse_steps(after_eq, g_remap_parsee->when_alone, MAX_STEPS);
if (count < 0) {
log_error(
"Config error (line %d): invalid key sequence '%s'\n"
"See the online docs for the latest list of key names.\n",
linenum, after_eq);
return 1;
}
g_remap_parsee->when_alone_steps = count;
} else {
if (strchr(after_eq, ',')) {
log_error(
"Config error (line %d): with_other does not support"
" comma-separated steps\n", linenum);
return 1;
}
int count = parse_steps(after_eq, &g_remap_parsee->with_other, 1);
if (count < 0) {
log_error(
"Config error (line %d): invalid key sequence '%s'\n"
"See the online docs for the latest list of key names.\n",
linenum, after_eq);
return 1;
}
g_remap_parsee->with_other_steps = count;
}
if (parsee_is_valid()) {
register_remap(g_remap_parsee);
g_remap_parsee = 0;
}
return 0;
}
// anything else is unknown
log_error("Config error (line %d): invalid setting '%s'\n",
linenum, line);
return 1;
}
void reset_config()
{
free(g_remap_parsee);
g_remap_parsee = 0;
while (g_remap_list) {
struct Remap * remap = g_remap_list;
g_remap_list = remap->next;
free(remap);
}
g_remap_list = 0;
g_timeout_ms = 0;
}