Skip to content

Commit

Permalink
Add a working global event handler too
Browse files Browse the repository at this point in the history
  • Loading branch information
dylwhich committed Sep 22, 2024
1 parent 6a6e4aa commit 446b4a2
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions tools/mac_events_test/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
#endif

static pascal OSErr handleOpenDocumentEvent(const AppleEvent* event, AppleEvent* reply, SRefCon handlerRef);
static OSStatus globalEventHandler(EventHandlerCallRef handler, EventRef event, void* data);
static void processEvents(const char** out);

static char pathBuffer[1024];
char pathBuffer[1024];
EventHandlerRef globalEventHandlerRef;
FILE* logFile;

int main(int argc, char** argv)
Expand Down Expand Up @@ -98,18 +100,37 @@ static pascal OSErr handleOpenDocumentEvent(const AppleEvent* event, AppleEvent*
return AEDisposeDesc(&docList);
}

static OSStatus globalEventHandler(EventHandlerCallRef handler, EventRef event, void* data)
{
LOG("globalEventHandler()!!!!!!\n");
return noErr;
}

static void processEvents(const char** out)
{
memset(pathBuffer, 0, sizeof(pathBuffer));

// Install handler
AEEventHandlerUPP handler = NewAEEventHandlerUPP(handleOpenDocumentEvent);
OSStatus result = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, handler, 0, false);
AEEventHandlerUPP openDocHandler = NewAEEventHandlerUPP(handleOpenDocumentEvent);
OSStatus result = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, openDocHandler, 0, false);

if (result != noErr)
{
LOG("Failed to install OpenDocument handler\n");
DisposeAEEventHandlerUPP(handler);
DisposeAEEventHandlerUPP(openDocHandler);
return;
}

// Install the application-level handler
const EventTypeSpec eventTypes[] = {{.eventClass = kEventClassAppleEvent, .eventKind = kEventAppleEvent}};

EventHandlerUPP globalHandler = NewEventHandlerUPP(globalEventHandler);
result = InstallApplicationEventHandler(globalHandler, 1, eventTypes, NULL, &globalEventHandlerRef);

if (result != noErr)
{
LOG("Failed to install global event handler\n");
DisposeEventHandlerUPP(globalHandler);
return;
}
// Handler successfully installed, now check for events
Expand All @@ -118,7 +139,6 @@ static void processEvents(const char** out)
EventRef eventRef;
// Half a second timeout
EventTimeout timeout = 0.5;
const EventTypeSpec eventTypes[] = {{.eventClass = kEventClassAppleEvent, .eventKind = kEventAppleEvent}};

result = ReceiveNextEvent(1, eventTypes, timeout, kEventRemoveFromQueue, &eventRef);

Expand Down Expand Up @@ -158,6 +178,8 @@ static void processEvents(const char** out)
}
} while (1);//result != eventNotHandledErr);

DisposeEventHandlerUPP(globalEventHandler);

result = AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments, handleOpenDocumentEvent, false);
if (result != noErr)
{
Expand Down

0 comments on commit 446b4a2

Please sign in to comment.