aboutsummaryrefslogtreecommitdiff
path: root/src/carbon.c
blob: 687820c9d2e11b11fb8964e9e0249c8bea0aaeff (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
#include "carbon.h"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
static inline char *
find_process_name_for_psn(ProcessSerialNumber *psn)
{
    CFStringRef process_name_ref;
    if (CopyProcessName(psn, &process_name_ref) == noErr) {
        char *process_name = copy_cfstring(process_name_ref);
        for (char *s = process_name; *s; ++s) *s = tolower(*s);
        CFRelease(process_name_ref);
        return process_name;
    }
    return NULL;
}

inline char *
find_process_name_for_pid(pid_t pid)
{
    ProcessSerialNumber psn;
    GetProcessForPID(pid, &psn);
    return find_process_name_for_psn(&psn);
}

static inline char *
find_active_process_name(void)
{
    ProcessSerialNumber psn;
    GetFrontProcess(&psn);
    return find_process_name_for_psn(&psn);
}
#pragma clang diagnostic pop

static OSStatus
carbon_event_handler(EventHandlerCallRef ref, EventRef event, void *context)
{
    struct carbon_event *carbon = (struct carbon_event *) context;

    ProcessSerialNumber psn;
    if (GetEventParameter(event,
                          kEventParamProcessID,
                          typeProcessSerialNumber,
                          NULL,
                          sizeof(psn),
                          NULL,
                          &psn) != noErr) {
        return -1;
    }

    if (carbon->process_name) {
        free(carbon->process_name);
        carbon->process_name = NULL;
    }

    carbon->process_name = find_process_name_for_psn(&psn);

    return noErr;
}

bool carbon_event_init(struct carbon_event *carbon)
{
    carbon->target = GetApplicationEventTarget();
    carbon->handler = NewEventHandlerUPP(carbon_event_handler);
    carbon->type.eventClass = kEventClassApplication;
    carbon->type.eventKind = kEventAppFrontSwitched;
    carbon->process_name = find_active_process_name();

    return InstallEventHandler(carbon->target,
                               carbon->handler,
                               1,
                               &carbon->type,
                               carbon,
                               &carbon->handler_ref) == noErr;
}