[fix] fix macOS clipboard monitoring compilation error using changeCount polling

This commit is contained in:
dijunkun
2025-12-29 01:01:08 +08:00
parent 17b7ba6b72
commit 5f320af6e6

View File

@@ -70,20 +70,29 @@ void StartMacOSClipboardMonitoring() {
CFRetain(g_monitor_runloop); CFRetain(g_monitor_runloop);
} }
// Register for clipboard change notifications // Track changeCount to detect clipboard changes
id observer = // Use __block to allow modification inside the block
[[NSNotificationCenter defaultCenter] addObserverForName:NSPasteboardDidChangeNotification __block NSInteger lastChangeCount = [pasteboard changeCount];
object:pasteboard
queue:nil
usingBlock:^(NSNotification* notification) {
if (!g_monitoring.load()) {
return;
}
HandleClipboardChange();
}];
LOG_INFO("Clipboard event monitoring started (macOS)"); LOG_INFO("Clipboard event monitoring started (macOS)");
// Use a timer to periodically check changeCount
// This is more reliable than NSPasteboardDidChangeNotification which may not be available
NSTimer* timer =
[NSTimer scheduledTimerWithTimeInterval:0.1
repeats:YES
block:^(NSTimer* timer) {
if (!g_monitoring.load()) {
[timer invalidate];
return;
}
NSInteger currentChangeCount = [pasteboard changeCount];
if (currentChangeCount != lastChangeCount) {
lastChangeCount = currentChangeCount;
HandleClipboardChange();
}
}];
while (g_monitoring.load()) { while (g_monitoring.load()) {
@autoreleasepool { @autoreleasepool {
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0.1]; NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0.1];
@@ -92,9 +101,7 @@ void StartMacOSClipboardMonitoring() {
} }
// Cleanup // Cleanup
[[NSNotificationCenter defaultCenter] removeObserver:observer [timer invalidate];
name:NSPasteboardDidChangeNotification
object:pasteboard];
if (g_monitor_runloop) { if (g_monitor_runloop) {
CFRelease(g_monitor_runloop); CFRelease(g_monitor_runloop);
g_monitor_runloop = nullptr; g_monitor_runloop = nullptr;