From 753c697187ff0706250c70cf605cf5c10355c4ed Mon Sep 17 00:00:00 2001 From: nyxiereal <98595166+nyxiereal@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:02:40 +0100 Subject: [PATCH] perf: block idle Windows and Linux tray loops --- .../lib/windows/WindowsNativeBridge.kt | 6 ++ .../lib/windows/WindowsTrayManager.kt | 55 ++++++--------- src/native/linux/sni.c | 70 +++++++++++++------ src/native/windows/jni_bridge.c | 27 +++++++ 4 files changed, 101 insertions(+), 57 deletions(-) diff --git a/src/jvmMain/kotlin/dev/nucleusframework/composenativetray/lib/windows/WindowsNativeBridge.kt b/src/jvmMain/kotlin/dev/nucleusframework/composenativetray/lib/windows/WindowsNativeBridge.kt index 1c8d8fce..87c68c3e 100644 --- a/src/jvmMain/kotlin/dev/nucleusframework/composenativetray/lib/windows/WindowsNativeBridge.kt +++ b/src/jvmMain/kotlin/dev/nucleusframework/composenativetray/lib/windows/WindowsNativeBridge.kt @@ -56,6 +56,12 @@ internal object WindowsNativeBridge { @JvmStatic external fun nativeLoopTray(blocking: Int): Int + @JvmStatic external fun nativeGetCurrentThreadId(): Int + + @JvmStatic external fun nativeWakeThread(threadId: Int) + + @JvmStatic external fun nativeWaitTray(timeoutMillis: Int): Int + @JvmStatic external fun nativeUpdateTray(handle: Long) @JvmStatic external fun nativeExitTray() diff --git a/src/jvmMain/kotlin/dev/nucleusframework/composenativetray/lib/windows/WindowsTrayManager.kt b/src/jvmMain/kotlin/dev/nucleusframework/composenativetray/lib/windows/WindowsTrayManager.kt index 671f20dd..3a015534 100644 --- a/src/jvmMain/kotlin/dev/nucleusframework/composenativetray/lib/windows/WindowsTrayManager.kt +++ b/src/jvmMain/kotlin/dev/nucleusframework/composenativetray/lib/windows/WindowsTrayManager.kt @@ -31,6 +31,8 @@ internal class WindowsTrayManager( // Thread for running the tray (similar to macOS) private var trayThread: Thread? = null + @Volatile private var trayThreadId = 0 + // Coroutine scopes for callback handling private var mainScope: CoroutineScope? = null private var ioScope: CoroutineScope? = null @@ -112,6 +114,7 @@ internal class WindowsTrayManager( // Set menu-opened callback after init (TrayContext must exist) setupMenuOpenedCallback(handle) + trayThreadId = WindowsNativeBridge.nativeGetCurrentThreadId() initialized.set(true) // Signal that initialization is complete before entering the loop @@ -168,7 +171,7 @@ internal class WindowsTrayManager( // Queue the update to be processed on the tray thread synchronized(updateQueueLock) { updateQueue.add(UpdateRequest(newIconPath, newTooltip, newOnLeftClick, newOnMenuOpened, newMenuItems)) - updateQueueLock.notify() + WindowsNativeBridge.nativeWakeThread(trayThreadId) } } @@ -182,13 +185,12 @@ internal class WindowsTrayManager( ) { synchronized(updateQueueLock) { checkedUpdateQueue.add(text to isChecked) - updateQueueLock.notify() + WindowsNativeBridge.nativeWakeThread(trayThreadId) } } private fun runMessageLoop() { log("Entering message loop on tray thread") - var consecutiveErrors = 0 var initialPosCaptured = false var initialPosAttempts = 0 var positionErrorCount = 0 @@ -215,40 +217,24 @@ internal class WindowsTrayManager( when (result) { -1 -> { log("nativeLoopTray returned -1 (error or quit)") - if (running.get() && initialized.get()) { - consecutiveErrors++ - if (consecutiveErrors > 5) { - log("Too many consecutive errors, exiting loop") - break - } - Thread.sleep(100) - - // Try to recover - val handle = trayHandle - if (handle != 0L) { - try { - log("Attempting to recover tray...") - WindowsNativeBridge.nativeUpdateTray(handle) - consecutiveErrors = 0 - } catch (e: Exception) { - log("Failed to recover: ${e.message}") - e.printStackTrace() - } - } - } else { - break - } + break } - 0 -> { - // Normal operation - consecutiveErrors = 0 + + 0 -> Unit + else -> log("nativeLoopTray returned unexpected value: $result") + } + val hasPendingUpdates = + synchronized(updateQueueLock) { + updateQueue.isNotEmpty() || checkedUpdateQueue.isNotEmpty() } - else -> { - log("nativeLoopTray returned unexpected value: $result") - consecutiveErrors = 0 + if (running.get() && !hasPendingUpdates) { + // Position retries are bounded; idle trays wait indefinitely. + val retryPosition = + !initialPosCaptured && initialPosAttempts < 60 && positionErrorCount < maxPositionErrors + check(WindowsNativeBridge.nativeWaitTray(if (retryPosition) 50 else -1) == 0) { + "Failed to wait for tray messages" } } - Thread.sleep(50) } catch (e: Exception) { log("Exception in message loop: ${e.message}") if (running.get()) { @@ -519,6 +505,7 @@ internal class WindowsTrayManager( } private fun cleanupTray() { + trayThreadId = 0 if (initialized.get()) { try { log("Calling nativeExitTray()") @@ -555,7 +542,7 @@ internal class WindowsTrayManager( // Wake up the thread if it's waiting synchronized(updateQueueLock) { - updateQueueLock.notify() + WindowsNativeBridge.nativeWakeThread(trayThreadId) } // Wait for the tray thread to finish diff --git a/src/native/linux/sni.c b/src/native/linux/sni.c index edfd7084..7a8bed79 100644 --- a/src/native/linux/sni.c +++ b/src/native/linux/sni.c @@ -15,6 +15,10 @@ #include #include #include +#include +#include +#include +#include #include #include @@ -154,8 +158,8 @@ struct sni_tray { sd_bus_slot *sni_prop_slot; sd_bus_slot *menu_prop_slot; char *bus_name; /* org.kde.StatusNotifierItem-{PID}-1 */ - int running; - int quit_pipe[2]; /* write to [1] to wake the event loop */ + atomic_int running; + int wake_fd; /* updates and shutdown wake the event loop */ /* Serializes every sd_bus_* access and the tray state it reads/writes. * sd-bus objects are NOT thread-safe: the event loop thread (sd_bus_process) @@ -226,6 +230,12 @@ static int64_t now_ms(void) { static inline void bus_lock(sni_tray *tray) { pthread_mutex_lock(&tray->bus_lock); } static inline void bus_unlock(sni_tray *tray) { pthread_mutex_unlock(&tray->bus_lock); } +static void wake_loop(sni_tray *tray) { + uint64_t value = 1; + while (write(tray->wake_fd, &value, sizeof(value)) < 0 && errno == EINTR) {} + /* EAGAIN means a wakeup is already pending. */ +} + /* Enqueue a user callback to be fired by the event loop after bus_lock is * released. Called only from D-Bus handlers, i.e. with bus_lock already held * on the event loop thread, so no additional locking is required. */ @@ -404,11 +414,13 @@ static const char *no_menu_path(desktop_env de) { static void emit_new_icon(sni_tray *tray) { if (!tray->bus) return; sd_bus_emit_signal(tray->bus, SNI_PATH, SNI_IFACE, "NewIcon", ""); + wake_loop(tray); } static void emit_new_title(sni_tray *tray) { if (!tray->bus) return; sd_bus_emit_signal(tray->bus, SNI_PATH, SNI_IFACE, "NewTitle", ""); + wake_loop(tray); } static void emit_layout_updated(sni_tray *tray) { @@ -422,11 +434,13 @@ static void emit_layout_updated(sni_tray *tray) { /* Also emit properties changed for Version */ sd_bus_emit_properties_changed(tray->bus, MENU_PATH, MENU_IFACE, "Version", NULL); + wake_loop(tray); } static void emit_sni_properties_changed(sni_tray *tray, const char *prop) { if (!tray->bus) return; sd_bus_emit_properties_changed(tray->bus, SNI_PATH, SNI_IFACE, prop, NULL); + wake_loop(tray); } /* ========================================================================== */ @@ -1101,12 +1115,14 @@ sni_tray *sni_tray_create(const uint8_t *icon_data, size_t icon_len, tray->icon_pixmaps = build_pixmaps(icon_data, icon_len); } - if (pipe(tray->quit_pipe) < 0) { + tray->wake_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + if (tray->wake_fd < 0) { free(tray->tooltip_text); free(tray); return NULL; } + atomic_init(&tray->running, 1); return tray; } @@ -1167,9 +1183,6 @@ int sni_tray_run(sni_tray *tray) { /* Not fatal — some environments don't have a watcher */ } - tray->running = 1; - int bus_fd = sd_bus_get_fd(tray->bus); - bus_unlock(tray); /* Event loop: process D-Bus messages until quit is signaled */ @@ -1194,19 +1207,33 @@ int sni_tray_run(sni_tray *tray) { if (!tray->running) break; - /* Wait for bus activity or quit signal (no bus access here). */ - fd_set rfds; - FD_ZERO(&rfds); - FD_SET(bus_fd, &rfds); - FD_SET(tray->quit_pipe[0], &rfds); - int maxfd = (bus_fd > tray->quit_pipe[0]) ? bus_fd : tray->quit_pipe[0]; - - struct timeval tv = {.tv_sec = 1, .tv_usec = 0}; - int sel = select(maxfd + 1, &rfds, NULL, NULL, &tv); - if (sel < 0 && errno != EINTR) break; - if (FD_ISSET(tray->quit_pipe[0], &rfds)) { - tray->running = 0; + /* Snapshot the bus wait state under the same lock as updates. Any + * update after unlock leaves wake_fd readable, so no wakeup is lost. */ + bus_lock(tray); + uint64_t value, deadline; + while (read(tray->wake_fd, &value, sizeof(value)) < 0 && errno == EINTR) {} + int bus_fd = sd_bus_get_fd(tray->bus); + int events = sd_bus_get_events(tray->bus); + r = sd_bus_get_timeout(tray->bus, &deadline); + bus_unlock(tray); + if (bus_fd < 0 || events < 0 || r < 0) break; + + int timeout = -1; + if (deadline != UINT64_MAX) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + uint64_t now = (uint64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000; + uint64_t remaining = deadline > now ? deadline - now : 0; + uint64_t millis = remaining / 1000 + (remaining % 1000 != 0); + timeout = millis > INT_MAX ? INT_MAX : (int)millis; } + + struct pollfd fds[] = { + {.fd = bus_fd, .events = (short)events}, + {.fd = tray->wake_fd, .events = POLLIN}, + }; + if (!tray->running) break; + if (poll(fds, 2, timeout) < 0 && errno != EINTR) break; } /* Teardown under the lock so a late mutator can't touch a closing bus. */ @@ -1226,15 +1253,12 @@ int sni_tray_run(sni_tray *tray) { void sni_tray_quit(sni_tray *tray) { if (!tray) return; tray->running = 0; - /* Wake the select() */ - char c = 1; - if (write(tray->quit_pipe[1], &c, 1) < 0) { /* ignore */ } + wake_loop(tray); } void sni_tray_destroy(sni_tray *tray) { if (!tray) return; - close(tray->quit_pipe[0]); - close(tray->quit_pipe[1]); + close(tray->wake_fd); free(tray->title); free(tray->tooltip_text); free(tray->bus_name); diff --git a/src/native/windows/jni_bridge.c b/src/native/windows/jni_bridge.c index 62806791..a64a5f49 100644 --- a/src/native/windows/jni_bridge.c +++ b/src/native/windows/jni_bridge.c @@ -262,6 +262,33 @@ Java_dev_nucleusframework_composenativetray_lib_windows_WindowsNativeBridge_nati return (jint)tray_loop((int)blocking); } +JNIEXPORT jint JNICALL +Java_dev_nucleusframework_composenativetray_lib_windows_WindowsNativeBridge_nativeGetCurrentThreadId( + JNIEnv *env, jclass clazz) +{ + (void)env; (void)clazz; + return (jint)GetCurrentThreadId(); +} + +JNIEXPORT void JNICALL +Java_dev_nucleusframework_composenativetray_lib_windows_WindowsNativeBridge_nativeWakeThread( + JNIEnv *env, jclass clazz, jint threadId) +{ + (void)env; (void)clazz; + if (threadId) PostThreadMessageW((DWORD)threadId, WM_NULL, 0, 0); +} + +JNIEXPORT jint JNICALL +Java_dev_nucleusframework_composenativetray_lib_windows_WindowsNativeBridge_nativeWaitTray( + JNIEnv *env, jclass clazz, jint timeoutMillis) +{ + (void)env; (void)clazz; + DWORD timeout = timeoutMillis < 0 ? INFINITE : (DWORD)timeoutMillis; + DWORD result = MsgWaitForMultipleObjectsEx(0, NULL, timeout, QS_ALLINPUT, + MWMO_INPUTAVAILABLE); + return result == WAIT_FAILED ? -1 : 0; +} + JNIEXPORT void JNICALL Java_dev_nucleusframework_composenativetray_lib_windows_WindowsNativeBridge_nativeUpdateTray( JNIEnv *env, jclass clazz, jlong handle)