Skip to content

Commit

Permalink
fix: prevent resource leaks in mouse event handling
Browse files Browse the repository at this point in the history
  • Loading branch information
2mawi2 committed Jan 18, 2025
1 parent 2c8a52f commit 804b1d4
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions MiddleClick/Controller.m
Original file line number Diff line number Diff line change
Expand Up @@ -164,20 +164,18 @@ - (void)registerMouseCallback:(NSAutoreleasePool*)pool

/// create eventTap which listens for core grpahic events with the filter
/// specified above (so left mouse down and up again)
CFMachPortRef eventTap = CGEventTapCreate(
currentEventTap = CGEventTapCreate(
kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
eventMask, mouseCallback, NULL);
currentEventTap = eventTap;

if (eventTap) {
if (currentEventTap) {
// Add to the current run loop.
CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
currentRunLoopSource = runLoopSource;
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
currentRunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, currentEventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), currentRunLoopSource,
kCFRunLoopCommonModes);

// Enable the event tap.
CGEventTapEnable(eventTap, true);
CGEventTapEnable(currentEventTap, true);

// release pool before exit
[pool release];
Expand All @@ -189,13 +187,22 @@ - (void)registerMouseCallback:(NSAutoreleasePool*)pool
}
static void unregisterMouseCallback(void)
{
// Remove from the current run loop.
// Disable the event tap first
if (currentEventTap) {
CGEventTapEnable(currentEventTap, false);
}

// Remove and release the run loop source
if (currentRunLoopSource) {
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), currentRunLoopSource, kCFRunLoopCommonModes);
CFRelease(currentRunLoopSource);
currentRunLoopSource = NULL;
}
// Disable the event tap.

// Release the event tap
if (currentEventTap) {
CGEventTapEnable(currentEventTap, false);
CFRelease(currentEventTap);
currentEventTap = NULL;
}
}

Expand Down

0 comments on commit 804b1d4

Please sign in to comment.