aboutsummaryrefslogtreecommitdiff
path: root/src/skhd.c
blob: c90c4b6baf632ad1da738da42f4183e2eba3e1e9 (plain) (blame)
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
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
#include <getopt.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <Carbon/Carbon.h>

#include "timing.h"
#include "log.h"
#define HASHTABLE_IMPLEMENTATION
#include "hashtable.h"
#include "sbuffer.h"
#include "hotload.h"
#include "event_tap.h"
#include "locale.h"
#include "carbon.h"
#include "tokenize.h"
#include "parse.h"
#include "hotkey.h"
#include "synthesize.h"

#include "hotload.c"
#include "event_tap.c"
#include "locale.c"
#include "carbon.c"
#include "tokenize.c"
#include "parse.c"
#include "hotkey.c"
#include "synthesize.c"

extern bool CGSIsSecureEventInputSet();
#define secure_keyboard_entry_enabled CGSIsSecureEventInputSet

#define internal static
#define global   static

#define SKHD_CONFIG_FILE ".skhdrc"

global unsigned major_version = 0;
global unsigned minor_version = 3;
global unsigned patch_version = 1;

global struct carbon_event carbon;
global struct event_tap event_tap;
global struct hotloader hotloader;
global struct mode *current_mode;
global struct table mode_map;
global struct table blacklst;
global char *config_file;

internal HOTLOADER_CALLBACK(config_handler);

internal void
parse_config_helper(char *absolutepath)
{
    struct parser parser;
    if (parser_init(&parser, &mode_map, &blacklst, absolutepath)) {
        hotloader_end(&hotloader);
        hotloader_add_file(&hotloader, absolutepath);

        if (parse_config(&parser)) {
            parser_do_directives(&parser, &hotloader);
        }
        parser_destroy(&parser);

        if (hotloader_begin(&hotloader, config_handler)) {
            debug("skhd: watching files for changes:\n", absolutepath);
            for (int i = 0; i < hotloader.watch_count; ++i) {
                debug("\t%s\n", hotloader.watch_list[i].file_info.absolutepath);
            }
        } else {
            warn("skhd: could not start watcher.. hotloading is not enabled\n");
        }
    } else {
        warn("skhd: could not open file '%s'\n", absolutepath);
    }

    current_mode = table_find(&mode_map, "default");
}

internal HOTLOADER_CALLBACK(config_handler)
{
    BEGIN_TIMED_BLOCK("hotload_config");
    debug("skhd: config-file has been modified.. reloading config\n");
    free_mode_map(&mode_map);
    free_blacklist(&blacklst);
    parse_config_helper(config_file);
    END_TIMED_BLOCK();
}

internal CF_NOTIFICATION_CALLBACK(keymap_handler)
{
    BEGIN_TIMED_BLOCK("keymap_changed");
    if (initialize_keycode_map()) {
        debug("skhd: input source changed.. reloading config\n");
        free_mode_map(&mode_map);
        free_blacklist(&blacklst);
        parse_config_helper(config_file);
    }
    END_TIMED_BLOCK();
}

internal EVENT_TAP_CALLBACK(key_handler)
{
    switch (type) {
    case kCGEventTapDisabledByTimeout:
    case kCGEventTapDisabledByUserInput: {
        debug("skhd: restarting event-tap\n");
        struct event_tap *event_tap = (struct event_tap *) reference;
        CGEventTapEnable(event_tap->handle, 1);
    } break;
    case kCGEventKeyDown: {
        if (table_find(&blacklst, carbon.process_name)) return event;
        if (!current_mode) return event;

        BEGIN_TIMED_BLOCK("handle_keypress");
        struct hotkey eventkey = create_eventkey(event);
        bool result = find_and_exec_hotkey(&eventkey, &mode_map, &current_mode, &carbon);
        END_TIMED_BLOCK();

        if (result) return NULL;
    } break;
    case NX_SYSDEFINED: {
        if (table_find(&blacklst, carbon.process_name)) return event;
        if (!current_mode) return event;

        struct hotkey eventkey;
        if (intercept_systemkey(event, &eventkey)) {
            bool result = find_and_exec_hotkey(&eventkey, &mode_map, &current_mode, &carbon);
            if (result) return NULL;
        }
    } break;
    }
    return event;
}

internal bool
parse_arguments(int argc, char **argv)
{
    int option;
    const char *short_option = "VPvc:k:t:";
    struct option long_option[] = {
        { "verbose", no_argument, NULL, 'V' },
        { "profile", no_argument, NULL, 'P' },
        { "version", no_argument, NULL, 'v' },
        { "config", required_argument, NULL, 'c' },
        { "key", required_argument, NULL, 'k' },
        { "text", required_argument, NULL, 't' },
        { NULL, 0, NULL, 0 }
    };

    while ((option = getopt_long(argc, argv, short_option, long_option, NULL)) != -1) {
        switch (option) {
        case 'V': {
            verbose = true;
        } break;
        case 'P': {
            profile = true;
        } break;
        case 'v': {
            printf("skhd version %d.%d.%d\n", major_version, minor_version, patch_version);
            return true;
        } break;
        case 'c': {
            config_file = copy_string(optarg);
        } break;
        case 'k': {
            synthesize_key(optarg);
            return true;
        } break;
        case 't': {
            synthesize_text(optarg);
            return true;
        } break;
        }
    }

    return false;
}

internal bool
check_privileges(void)
{
    bool result;
    const void *keys[] = { kAXTrustedCheckOptionPrompt };
    const void *values[] = { kCFBooleanTrue };

    CFDictionaryRef options;
    options = CFDictionaryCreate(kCFAllocatorDefault,
                                 keys, values, sizeof(keys) / sizeof(*keys),
                                 &kCFCopyStringDictionaryKeyCallBacks,
                                 &kCFTypeDictionaryValueCallBacks);

    result = AXIsProcessTrustedWithOptions(options);
    CFRelease(options);

    return result;
}

internal void
use_default_config_path(void)
{
    char *home = getenv("HOME");
    if (!home) {
        error("skhd: could not locate config because 'env HOME' was not set! abort..\n");
    }

    int home_len = strlen(home);
    int config_len = strlen("/"SKHD_CONFIG_FILE);
    int length = home_len + config_len;
    config_file = malloc(length + 1);
    memcpy(config_file, home, home_len);
    memcpy(config_file + home_len, "/"SKHD_CONFIG_FILE, config_len);
    config_file[length] = '\0';
}

int main(int argc, char **argv)
{
    if (parse_arguments(argc, argv)) {
        return EXIT_SUCCESS;
    }

    BEGIN_SCOPED_TIMED_BLOCK("total_time");
    BEGIN_SCOPED_TIMED_BLOCK("init");
    if (getuid() == 0 || geteuid() == 0) {
        error("skhd: running as root is not allowed! abort..\n");
    }

    if (secure_keyboard_entry_enabled()) {
        error("skhd: secure keyboard entry is enabled! abort..\n");
    }

    if (!check_privileges()) {
        error("skhd: must be run with accessibility access! abort..\n");
    }

    if (!initialize_keycode_map()) {
        error("skhd: could not initialize keycode map! abort..\n");
    }

    if (!carbon_event_init(&carbon)) {
        error("skhd: could not initialize carbon events! abort..\n");
    }

    if (!config_file) {
        use_default_config_path();
    }

    CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
                                    NULL,
                                    &keymap_handler,
                                    kTISNotifySelectedKeyboardInputSourceChanged,
                                    NULL,
                                    CFNotificationSuspensionBehaviorCoalesce);

    signal(SIGCHLD, SIG_IGN);
    init_shell();
    table_init(&mode_map, 13, (table_hash_func) hash_string, (table_compare_func) compare_string);
    table_init(&blacklst, 13, (table_hash_func) hash_string, (table_compare_func) compare_string);
    END_SCOPED_TIMED_BLOCK();

    BEGIN_SCOPED_TIMED_BLOCK("parse_config");
    debug("skhd: using config '%s'\n", config_file);
    parse_config_helper(config_file);
    END_SCOPED_TIMED_BLOCK();

    BEGIN_SCOPED_TIMED_BLOCK("begin_eventtap");
    event_tap.mask = (1 << kCGEventKeyDown) | (1 << NX_SYSDEFINED);
    event_tap_begin(&event_tap, key_handler);
    END_SCOPED_TIMED_BLOCK();
    END_SCOPED_TIMED_BLOCK();

    CFRunLoopRun();
    return EXIT_SUCCESS;
}