Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}

Expand All @@ -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
Expand All @@ -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()) {
Expand Down Expand Up @@ -519,6 +505,7 @@ internal class WindowsTrayManager(
}

private fun cleanupTray() {
trayThreadId = 0
if (initialized.get()) {
try {
log("Calling nativeExitTray()")
Expand Down Expand Up @@ -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
Expand Down
70 changes: 47 additions & 23 deletions src/native/linux/sni.c
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <limits.h>
#include <poll.h>
#include <stdatomic.h>
#include <sys/eventfd.h>

#include <time.h>
#include <systemd/sd-bus.h>
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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) {
Expand All @@ -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);
}

/* ========================================================================== */
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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 */
Expand All @@ -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. */
Expand All @@ -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);
Expand Down
27 changes: 27 additions & 0 deletions src/native/windows/jni_bridge.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down