mirror of
https://github.com/fromchat-messenger/app.git
synced 2026-11-16 02:44:54 +03:00
Replace AWT XEmbed tray with native SNI tray on Linux
On any DE hosting StatusNotifierItem (GNOME 46+/55 with the AppIndicator extension, KDE, etc.) the shell now hosts both the icon and the menu: we export org.kde.StatusNotifierItem + com.canonical.dbusmenu over dbus-java (pure Kotlin) and register with StatusNotifierItemWatcher. GNOME renders the popup itself from our DbusMenu tree (Connected | sep | Show | About FromChat | sep | Quit); label changes go out as ItemsPropertiesUpdated. AWT/XEmbed stays as fallback for X11-only shells; Windows/macOS untouched. dbus-java quirks resolved in pure Kotlin (details in tray-sni/DESIGN.md): properties are served by a hand-rolled org.freedesktop.DBus.Properties impl with explicit-signature Variants (DBusBoundProperty cannot express a(iiay) from Kotlin), and outer return structs (GetLayout/AboutToShowGroup) implement DBusSerializable to dodge the erased-field export XML bug. Verified on Ubuntu ARM64 VM: registers on the real session bus; icon in the GNOME panel; native menu opens; Show/About/Quit callbacks reach the app on the EDT; hardware-accelerated rendering unchanged (0 fallbacks, 0 shader errors).
This commit is contained in:
@@ -30,6 +30,11 @@ dependencies {
|
||||
implementation(project(":utils:shared"))
|
||||
implementation(libs.kotlinx.coroutines.swing)
|
||||
implementation(libs.jna.platform)
|
||||
// StatusNotifierItem tray on Linux: pure-Java D-Bus client (no GTK/JNA), plus an slf4j
|
||||
// provider so dbus-java's internal logging does not just print a "no provider" notice.
|
||||
implementation(libs.dbus.java.core)
|
||||
implementation(libs.dbus.java.transport.native.unixsocket)
|
||||
implementation(libs.slf4j.jdk14)
|
||||
// OpenJFX publishes empty jars without a classifier; declare every module
|
||||
// with the host classifier and exclude transitive stubs.
|
||||
javafxModules.forEach { module ->
|
||||
|
||||
@@ -70,10 +70,13 @@ import java.awt.image.BufferedImage
|
||||
import javax.swing.JFrame
|
||||
import javax.swing.SwingUtilities
|
||||
import kotlin.math.roundToInt
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import ru.fromchat.Logger
|
||||
import ru.fromchat.ui.FromChatTheme
|
||||
import ru.fromchat.ui.components.Text
|
||||
import ru.fromchat.ui.isInsideWindow
|
||||
import ru.fromchat.desktop.tray.SniTrayController
|
||||
|
||||
internal enum class TrayConnectionStatus {
|
||||
Connected,
|
||||
@@ -215,9 +218,48 @@ internal fun DesktopTrayHost(
|
||||
var menuAnchor by remember { mutableStateOf<Point?>(null) }
|
||||
val closeMenu = rememberUpdatedState { menuOpen = false }
|
||||
val onShowState = rememberUpdatedState(onShow)
|
||||
val sniController = remember { mutableStateOf<SniTrayController?>(null) }
|
||||
val sniActive = sniController.value != null
|
||||
|
||||
DisposableEffect(trayImage, tooltip) {
|
||||
if (!SystemTray.isSupported()) {
|
||||
// StatusNotifierItem comes first on Linux: GNOME (45+) has no XEmbed tray host any more — the
|
||||
// AWT icon only works behind Ubuntu's `legacy-tray-enabled` switch — and the KDE Plasma tray
|
||||
// speaks SNI too. When SNI is absent (no session bus, no watcher), the AWT/XEmbed fallback
|
||||
// below stays fully operational.
|
||||
LaunchedEffect(trayImage, tooltip) {
|
||||
if (!isLinuxOs()) return@LaunchedEffect
|
||||
sniController.value = withContext(Dispatchers.IO) {
|
||||
SniTrayController.tryInstall(
|
||||
trayImage = trayImage,
|
||||
appName = tooltip,
|
||||
statusLabel = statusLabel,
|
||||
showLabel = showLabel,
|
||||
aboutLabel = aboutLabel,
|
||||
quitLabel = quitLabel,
|
||||
onShow = onShow,
|
||||
onAbout = onAbout,
|
||||
onQuit = onQuit,
|
||||
)
|
||||
}
|
||||
}
|
||||
// Connection status moves with the backend; the disabled status row is the only mutable
|
||||
// bit of the SNI menu tree, so push it down as a plain property update.
|
||||
LaunchedEffect(sniController.value, statusLabel, connectionStatus) {
|
||||
val controller = sniController.value ?: return@LaunchedEffect
|
||||
withContext(Dispatchers.IO) {
|
||||
controller.updateStatus(statusLabel)
|
||||
}
|
||||
}
|
||||
DisposableEffect(sniController.value) {
|
||||
val controller = sniController.value
|
||||
onDispose {
|
||||
if (controller != null) {
|
||||
Thread { controller.close() }.apply { isDaemon = true }.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DisposableEffect(trayImage, tooltip, sniActive) {
|
||||
if (sniActive || !SystemTray.isSupported()) {
|
||||
onDispose {}
|
||||
} else {
|
||||
val trayIcon = TrayIcon(trayImage, tooltip)
|
||||
@@ -288,7 +330,7 @@ internal fun DesktopTrayHost(
|
||||
}
|
||||
}
|
||||
|
||||
if (menuOpen) {
|
||||
if (menuOpen && !sniActive) {
|
||||
var contentSizePx by remember { mutableStateOf(IntSize.Zero) }
|
||||
var showWindow by remember { mutableStateOf(false) }
|
||||
val windowState = rememberWindowState(
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package ru.fromchat.desktop.tray
|
||||
|
||||
import org.freedesktop.dbus.annotations.DBusInterfaceName
|
||||
import org.freedesktop.dbus.interfaces.DBusInterface
|
||||
import org.freedesktop.dbus.messages.DBusSignal
|
||||
import org.freedesktop.dbus.types.UInt32
|
||||
import org.freedesktop.dbus.types.Variant
|
||||
|
||||
/**
|
||||
* D-Bus interfaces for the StatusNotifierItem (SNI) tray, bound to what the hosts we target
|
||||
* actually implement. The authoritative references for the wire contract lived — at design time —
|
||||
* in the shipped `interfaces-xml` of `ubuntu-appindicators` (see `tray-sni/DESIGN.md`).
|
||||
*
|
||||
* Deliberately method-only: dbus-java derives the wire type of `@DBusBoundProperty` getters from
|
||||
* the *raw* Java type, which cannot express typed arrays (`a(iiay)`) from Kotlin — and raw `List`
|
||||
* exports as the wrong type (`av`) or fails the export outright. All properties are therefore
|
||||
* served by our own `org.freedesktop.DBus.Properties` implementation in [SniItemImpl] and
|
||||
* [SniMenuImpl], where each value is a [Variant] built with an explicit signature.
|
||||
*/
|
||||
internal const val ITEM_IFACE_NAME = "org.kde.StatusNotifierItem"
|
||||
internal const val MENU_IFACE_NAME = "com.canonical.dbusmenu"
|
||||
internal const val WATCHER_IFACE_NAME = "org.kde.StatusNotifierWatcher"
|
||||
|
||||
@DBusInterfaceName(ITEM_IFACE_NAME)
|
||||
interface SniItemIface : DBusInterface {
|
||||
/** The shell opens the DbusMenu popup itself; nothing to do when asked. */
|
||||
fun ContextMenu(x: Int, y: Int)
|
||||
|
||||
/** Primary activation → raise the app window (double click on GNOME, single click on KDE). */
|
||||
fun Activate(x: Int, y: Int)
|
||||
|
||||
/** Middle click on GNOME; treated as a window-show like the secondary activation path. */
|
||||
fun SecondaryActivate(x: Int, y: Int)
|
||||
|
||||
fun ProvideXdgActivationToken(token: String)
|
||||
|
||||
fun Scroll(delta: Int, orientation: String)
|
||||
|
||||
class NewIcon(objectPath: String) : DBusSignal(objectPath)
|
||||
|
||||
class NewToolTip(objectPath: String, tooltip: SniToolTipStruct) : DBusSignal(objectPath, tooltip)
|
||||
}
|
||||
|
||||
@DBusInterfaceName(MENU_IFACE_NAME)
|
||||
interface SniMenuIface : DBusInterface {
|
||||
/** Wire contract: `(u revision, node)` with `node = (ia{sv}av)`, children as nested variants. */
|
||||
fun GetLayout(parentId: Int, recursionDepth: Int, propertyNames: List<String>): SniGetLayoutResult
|
||||
|
||||
fun GetGroupProperties(ids: List<Int>, propertyNames: List<String>): List<SniItemProperties>
|
||||
|
||||
fun GetProperty(id: Int, name: String): Variant<*>
|
||||
|
||||
fun Event(id: Int, eventId: String, data: Variant<*>, timestamp: UInt32)
|
||||
|
||||
fun EventGroup(events: List<SniEventStruct>): List<UInt32>
|
||||
|
||||
fun AboutToShow(id: Int): Boolean
|
||||
|
||||
fun AboutToShowGroup(ids: List<Int>): SniAboutToShowGroupResult
|
||||
|
||||
class ItemsPropertiesUpdated(
|
||||
objectPath: String,
|
||||
updatedProperties: List<SniItemProperties>,
|
||||
removedProperties: List<SniRemovedProperties>,
|
||||
) : DBusSignal(objectPath, updatedProperties, removedProperties)
|
||||
|
||||
class LayoutUpdated(objectPath: String, revision: UInt32, parent: Int) : DBusSignal(objectPath, revision, parent)
|
||||
}
|
||||
|
||||
/**
|
||||
* org.kde.StatusNotifierWatcher — the *remote* stub. Properties (host registration etc.) are read
|
||||
* through the standard `org.freedesktop.DBus.Properties` proxy instead of `@DBusBoundProperty`
|
||||
* getters, so this stub holds nothing but the register method (the only call we make).
|
||||
*/
|
||||
@DBusInterfaceName(WATCHER_IFACE_NAME)
|
||||
interface SniWatcherIface : DBusInterface {
|
||||
fun RegisterStatusNotifierItem(service: String)
|
||||
|
||||
fun RegisterStatusNotifierItemHost(service: String)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package ru.fromchat.desktop.tray
|
||||
|
||||
import org.freedesktop.dbus.DBusPath
|
||||
import org.freedesktop.dbus.types.Variant
|
||||
|
||||
/**
|
||||
* The exported `org.kde.StatusNotifierItem`. Properties are served by the hand-rolled
|
||||
* [SniPropertiesProvider] (`org.freedesktop.DBus.Properties`), so every [Variant] carries an
|
||||
* explicit signature and `Get`/`GetAll` always hand back the live values.
|
||||
*/
|
||||
internal class SniItemImpl(
|
||||
pixmaps: List<SniPixmapStruct>,
|
||||
private val appName: String,
|
||||
statusLabel: String,
|
||||
private val onShow: () -> Unit,
|
||||
private val onAbout: () -> Unit,
|
||||
private val onQuit: () -> Unit,
|
||||
) : SniItemIface, SniPropertiesProvider() {
|
||||
private val lock = Any()
|
||||
|
||||
// Fixed content; the pixmap Variant pins its wire signature (a(iiay)) explicitly, since the
|
||||
// runtime type of a List is erased and dbus-java could not infer the element type itself.
|
||||
private val pixmapVariant =
|
||||
Variant(pixmaps.toList(), PIXMAP_WIRE_SIG)
|
||||
|
||||
private var tooltip =
|
||||
SniToolTipStruct("", emptyList(), appName, statusLabel)
|
||||
|
||||
fun setToolTip(statusLabel: String) {
|
||||
synchronized(lock) {
|
||||
tooltip = SniToolTipStruct("", emptyList(), appName, statusLabel)
|
||||
}
|
||||
}
|
||||
|
||||
fun liveToolTip(): SniToolTipStruct = synchronized(lock) { tooltip }
|
||||
|
||||
override fun sniProperties(): Map<String, Variant<*>> = synchronized(lock) {
|
||||
buildMap {
|
||||
put("Category", Variant("ApplicationStatus"))
|
||||
put("Id", Variant(appName))
|
||||
put("Title", Variant(appName))
|
||||
put("Status", Variant("Active"))
|
||||
put("WindowId", Variant(0))
|
||||
put("IconThemePath", Variant(""))
|
||||
put("Menu", Variant(DBusPath(SniTrayController.MENU_PATH)))
|
||||
put("ItemIsMenu", Variant(false))
|
||||
// Empty on purpose: a non-empty IconName makes hosts prefer the (missing) theme icon.
|
||||
put("IconName", Variant(""))
|
||||
put("IconPixmap", pixmapVariant)
|
||||
put("ToolTip", Variant(tooltip))
|
||||
}
|
||||
}
|
||||
|
||||
/** The shell opens the DbusMenu popup itself; nothing to do when asked. */
|
||||
override fun ContextMenu(x: Int, y: Int) = Unit
|
||||
|
||||
/** Primary activation → raise the app window (double click on GNOME, single click on KDE). */
|
||||
override fun Activate(x: Int, y: Int) {
|
||||
onShow()
|
||||
}
|
||||
|
||||
/** Middle click on GNOME; a secondary activation can also raise the window. */
|
||||
override fun SecondaryActivate(x: Int, y: Int) {
|
||||
onShow()
|
||||
}
|
||||
|
||||
/** v1: the shell's Wayland activation token is not needed for our (existing) window. */
|
||||
override fun ProvideXdgActivationToken(token: String) = Unit
|
||||
|
||||
override fun Scroll(delta: Int, orientation: String) = Unit
|
||||
|
||||
override fun isRemote() = false
|
||||
|
||||
override fun getObjectPath() = SniTrayController.ITEM_PATH
|
||||
|
||||
companion object {
|
||||
const val PIXMAP_WIRE_SIG = "a(iiay)"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package ru.fromchat.desktop.tray
|
||||
|
||||
import org.freedesktop.dbus.types.UInt32
|
||||
import org.freedesktop.dbus.types.Variant
|
||||
import ru.fromchat.Logger
|
||||
|
||||
/**
|
||||
* The exported `com.canonical.dbusmenu` object: a fixed menu tree
|
||||
* `status | sep | Show | About | sep | Quit`, whose single mutable bit is the status label.
|
||||
*
|
||||
* The tree is static, so `revision` stays put; label changes go out as
|
||||
* [SniMenuIface.ItemsPropertiesUpdated] signals from [SniTrayController.updateStatus].
|
||||
* The object-level properties (`Version`, `TextDirection`, ...) are served by
|
||||
* [SniPropertiesProvider] like on the item, so value signatures stay explicit.
|
||||
*/
|
||||
internal class SniMenuImpl(
|
||||
statusLabel: String,
|
||||
showLabel: String,
|
||||
aboutLabel: String,
|
||||
quitLabel: String,
|
||||
private val onShow: () -> Unit,
|
||||
private val onAbout: () -> Unit,
|
||||
private val onQuit: () -> Unit,
|
||||
) : SniMenuIface, SniPropertiesProvider() {
|
||||
private val lock = Any()
|
||||
private val nodes: MutableMap<Int, SniMenuItemType> = buildMap {
|
||||
put(STATUS_ID, SniMenuItemType.Item(statusLabel, enabled = false))
|
||||
put(SEPARATOR_FIRST_ID, SniMenuItemType.Separator)
|
||||
put(SHOW_ID, SniMenuItemType.Item(showLabel, enabled = true))
|
||||
put(ABOUT_ID, SniMenuItemType.Item(aboutLabel, enabled = true))
|
||||
put(SEPARATOR_LAST_ID, SniMenuItemType.Separator)
|
||||
put(QUIT_ID, SniMenuItemType.Item(quitLabel, enabled = true))
|
||||
}.toMutableMap()
|
||||
|
||||
fun updateItemLabel(label: String) {
|
||||
synchronized(lock) {
|
||||
nodes[STATUS_ID] = SniMenuItemType.Item(label, enabled = false)
|
||||
}
|
||||
}
|
||||
|
||||
/** Property diffs to publish for the status row — the only entry whose label can change. */
|
||||
fun itemPropertyUpdates(): List<SniItemProperties> = synchronized(lock) {
|
||||
val props = nodes[STATUS_ID]?.dbusmenuProps()
|
||||
?: return@synchronized emptyList()
|
||||
listOf(SniItemProperties(STATUS_ID, props))
|
||||
}
|
||||
|
||||
override fun GetLayout(parentId: Int, recursionDepth: Int, propertyNames: List<String>): SniGetLayoutResult =
|
||||
synchronized(lock) {
|
||||
val root = parentId.takeIf { nodes.containsKey(it) } ?: ROOT_ID
|
||||
SniGetLayoutResult(UInt32(REVISION.toLong()), layoutNode(root, recursionDepth))
|
||||
}
|
||||
|
||||
override fun GetGroupProperties(ids: List<Int>, propertyNames: List<String>): List<SniItemProperties> =
|
||||
synchronized(lock) {
|
||||
val wanted = ids.takeIf { it.isNotEmpty() } ?: nodes.keys.sorted()
|
||||
wanted.mapNotNull { id ->
|
||||
nodes[id]?.let { type ->
|
||||
SniItemProperties(id, filterProps(type.dbusmenuProps(), propertyNames))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun GetProperty(id: Int, name: String): Variant<*> = synchronized(lock) {
|
||||
nodes[id]?.dbusmenuProps()?.get(name) ?: Variant("")
|
||||
}
|
||||
|
||||
override fun Event(id: Int, eventId: String, data: Variant<*>, timestamp: UInt32) {
|
||||
handleEvent(id, eventId)
|
||||
}
|
||||
|
||||
override fun EventGroup(events: List<SniEventStruct>): List<UInt32> {
|
||||
events.forEach { event -> handleEvent(event.menuId(), event.menuEventId()) }
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
* The shell sends `AboutToShow(0)` right after the menu model is built. The tree never
|
||||
* changes shape, so `false` (no re-layout needed) is always right.
|
||||
*/
|
||||
override fun AboutToShow(id: Int) = false
|
||||
|
||||
override fun AboutToShowGroup(ids: List<Int>) =
|
||||
SniAboutToShowGroupResult(emptyList(), emptyList())
|
||||
|
||||
override fun sniProperties(): Map<String, Variant<*>> = synchronized(lock) {
|
||||
mapOf(
|
||||
"Version" to Variant(UInt32(DBUSMENU_VERSION)),
|
||||
"TextDirection" to Variant("ltr"),
|
||||
"Status" to Variant("normal"),
|
||||
// Untyped theme path list; pin the wire signature since the runtime type is erased.
|
||||
"IconThemePath" to Variant(emptyList<String>(), ICON_THEME_PATH_WIRE_SIG),
|
||||
)
|
||||
}
|
||||
|
||||
override fun isRemote() = false
|
||||
|
||||
override fun getObjectPath() = SniTrayController.MENU_PATH
|
||||
|
||||
private fun layoutNode(id: Int, depth: Int): SniLayoutNode =
|
||||
SniLayoutNode(
|
||||
id,
|
||||
nodes[id]?.dbusmenuProps() ?: emptyMap(),
|
||||
if (depth == 0) {
|
||||
emptyList()
|
||||
} else {
|
||||
childrenOf(id).map { childId -> Variant(layoutNode(childId, childDepth(depth))) }
|
||||
},
|
||||
)
|
||||
|
||||
private fun childDepth(depth: Int) = if (depth < 0) depth else depth - 1
|
||||
|
||||
private fun childrenOf(id: Int): List<Int> =
|
||||
if (id != ROOT_ID) emptyList() else nodes.keys
|
||||
.filter { it != ROOT_ID }
|
||||
.sorted()
|
||||
|
||||
private fun handleEvent(id: Int, eventId: String) {
|
||||
// Only activation matters; 'opened'/'closed' carry no state the app needs.
|
||||
if (eventId != "clicked") return
|
||||
Logger.i(LOG_TAG, "menu item $id clicked")
|
||||
when (id) {
|
||||
SHOW_ID -> onShow()
|
||||
ABOUT_ID -> onAbout()
|
||||
QUIT_ID -> onQuit()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val LOG_TAG = "SniTray"
|
||||
private const val REVISION = 1
|
||||
private const val DBUSMENU_VERSION = 2L
|
||||
private const val ICON_THEME_PATH_WIRE_SIG = "as"
|
||||
|
||||
/** Keys the client may not have asked for but needs to make sense of any item. */
|
||||
private val STRUCTURAL_PROPS = setOf("type", "children-display")
|
||||
|
||||
const val ROOT_ID = 0
|
||||
const val STATUS_ID = 1
|
||||
const val SEPARATOR_FIRST_ID = 2
|
||||
const val SHOW_ID = 3
|
||||
const val ABOUT_ID = 4
|
||||
const val SEPARATOR_LAST_ID = 5
|
||||
const val QUIT_ID = 6
|
||||
|
||||
private fun filterProps(
|
||||
props: Map<String, Variant<*>>,
|
||||
propertyNames: List<String>?,
|
||||
): Map<String, Variant<*>> = when {
|
||||
propertyNames == null || propertyNames.isEmpty() -> props
|
||||
else -> props.filterKeys { key -> key in propertyNames || key in STRUCTURAL_PROPS }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ru.fromchat.desktop.tray
|
||||
|
||||
import org.freedesktop.dbus.exceptions.DBusException
|
||||
import org.freedesktop.dbus.interfaces.Properties
|
||||
import org.freedesktop.dbus.types.Variant
|
||||
|
||||
/**
|
||||
* The `org.freedesktop.DBus.Properties` surface of one exported SNI object.
|
||||
*
|
||||
* Hand-rolled (not `@DBusBoundProperty`) so each value can be a [Variant] built with an explicit
|
||||
* D-Bus signature: dbus-java binds annotated getters by their *raw* Java type, which cannot carry
|
||||
* `a(iiay)` from Kotlin. Each object serves exactly one interface, so the interface argument is
|
||||
* ignored here.
|
||||
*/
|
||||
internal abstract class SniPropertiesProvider : Properties {
|
||||
abstract fun sniProperties(): Map<String, Variant<*>>
|
||||
|
||||
override fun <A> Get(interfaceName: String, propertyName: String): A {
|
||||
val variant = sniProperties()[propertyName]
|
||||
?: throw DBusException("Unknown property: $propertyName")
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return variant as A
|
||||
}
|
||||
|
||||
override fun <A> Set(interfaceName: String, propertyName: String, value: A) = Unit
|
||||
|
||||
override fun GetAll(interfaceName: String): Map<String, Variant<*>> = sniProperties()
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package ru.fromchat.desktop.tray
|
||||
|
||||
import org.freedesktop.dbus.connections.impl.DBusConnection
|
||||
import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder
|
||||
import org.freedesktop.dbus.exceptions.DBusExecutionException
|
||||
import org.freedesktop.dbus.interfaces.DBus
|
||||
import org.freedesktop.dbus.interfaces.Properties
|
||||
import ru.fromchat.Logger
|
||||
import ru.fromchat.desktop.TrayConnectionStatus
|
||||
import java.awt.image.BufferedImage
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import javax.swing.SwingUtilities
|
||||
|
||||
/**
|
||||
* SNI (StatusNotifierItem) tray over D-Bus: the shell hosts the icon and renders our menu, so
|
||||
* nothing about the tray touches AWT's XEmbed land or a separate Compose popup scene.
|
||||
*
|
||||
* Design, click matrix and wire contract: `app/desktop/tray-sni/DESIGN.md`.
|
||||
*
|
||||
* Threading: [tryInstall] and [updateStatus] are meant to be called off the EDT (they do blocking
|
||||
* D-Bus I/O); method callbacks from the shell arrive on dbus-java threads and are hopped to the
|
||||
* EDT before being handed to the app — same contract the AWT tray clicks follow.
|
||||
*/
|
||||
internal class SniTrayController private constructor(
|
||||
private val connection: DBusConnection,
|
||||
private val itemImpl: SniItemImpl,
|
||||
private val menuImpl: SniMenuImpl,
|
||||
private val ownerChangedToken: AutoCloseable?,
|
||||
) {
|
||||
private val closed = AtomicBoolean(false)
|
||||
|
||||
/**
|
||||
* Pushes status changes: the disabled status row label, the tooltip text, and the
|
||||
* `ItemsPropertiesUpdated` signal the shell's menu client listens for. Shapes are static,
|
||||
* so no `LayoutUpdated` is needed (and `revision` never moves).
|
||||
*/
|
||||
fun updateStatus(statusLabel: String) {
|
||||
if (closed.get() || !connection.isConnected) return
|
||||
runCatching {
|
||||
itemImpl.setToolTip(statusLabel)
|
||||
menuImpl.updateItemLabel(statusLabel)
|
||||
connection.sendMessage(
|
||||
SniMenuIface.ItemsPropertiesUpdated(
|
||||
MENU_PATH,
|
||||
menuImpl.itemPropertyUpdates(),
|
||||
emptyList(),
|
||||
),
|
||||
)
|
||||
connection.sendMessage(
|
||||
SniItemIface.NewToolTip(ITEM_PATH, itemImpl.liveToolTip()),
|
||||
)
|
||||
}.onFailure {
|
||||
Logger.w(LOG_TAG, "updateStatus failed: ${it.message}")
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
if (!closed.compareAndSet(false, true)) return
|
||||
runCatching {
|
||||
ownerChangedToken?.close()
|
||||
connection.close()
|
||||
}.onFailure {
|
||||
Logger.w(LOG_TAG, "SNI connection close failed: ${it.message}")
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val LOG_TAG = "SniTray"
|
||||
const val ITEM_PATH = "/org/ayatana/NotificationItem/FromChat"
|
||||
const val MENU_PATH = "$ITEM_PATH/Menu"
|
||||
private const val WATCHER_SERVICE = "org.kde.StatusNotifierWatcher"
|
||||
private const val WATCHER_PATH = "/StatusNotifierWatcher"
|
||||
private const val HOST_REGISTERED_PROP = "IsStatusNotifierHostRegistered"
|
||||
|
||||
/** Pixmaps to ship: smallest-first matters on the shell side (`getBestPixmap`). */
|
||||
private val TRAY_PX_SIZES = listOf(32, 48)
|
||||
|
||||
/**
|
||||
* All-or-nothing install: connect, export item + menu, register with the watcher. Any
|
||||
* failure closes the connection and yields `null`; the caller keeps the AWT/XEmbed
|
||||
* fallback.
|
||||
*/
|
||||
fun tryInstall(
|
||||
trayImage: BufferedImage,
|
||||
appName: String,
|
||||
statusLabel: String,
|
||||
showLabel: String,
|
||||
aboutLabel: String,
|
||||
quitLabel: String,
|
||||
onShow: () -> Unit,
|
||||
onAbout: () -> Unit,
|
||||
onQuit: () -> Unit,
|
||||
): SniTrayController? {
|
||||
val connection = try {
|
||||
DBusConnectionBuilder.forSessionBus()
|
||||
.withShared(false)
|
||||
.build()
|
||||
} catch (failure: Exception) {
|
||||
Logger.w(LOG_TAG, "No session bus; SNI tray unavailable: ${failure.message}")
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
val itemImpl = SniItemImpl(
|
||||
pixmaps = sniPixmaps(trayImage, TRAY_PX_SIZES),
|
||||
appName = appName,
|
||||
statusLabel = statusLabel,
|
||||
onShow = { runOnEdt(onShow, "onShow") },
|
||||
onAbout = { runOnEdt(onAbout, "onAbout") },
|
||||
onQuit = { runOnEdt(onQuit, "onQuit") },
|
||||
)
|
||||
val menuImpl = SniMenuImpl(
|
||||
statusLabel = statusLabel,
|
||||
showLabel = showLabel,
|
||||
aboutLabel = aboutLabel,
|
||||
quitLabel = quitLabel,
|
||||
onShow = { runOnEdt(onShow, "menu onShow") },
|
||||
onAbout = { runOnEdt(onAbout, "menu onAbout") },
|
||||
onQuit = { runOnEdt(onQuit, "menu onQuit") },
|
||||
)
|
||||
|
||||
connection.exportObject(ITEM_PATH, itemImpl)
|
||||
connection.exportObject(MENU_PATH, menuImpl)
|
||||
|
||||
val watchProps = connection.getRemoteObject(
|
||||
WATCHER_SERVICE,
|
||||
WATCHER_PATH,
|
||||
Properties::class.java,
|
||||
)
|
||||
val hostRegistered = remoteWatcherHostRegistered(watchProps)
|
||||
if (!hostRegistered) {
|
||||
Logger.w(LOG_TAG, "No SNI host registered on the watcher")
|
||||
return null
|
||||
}
|
||||
|
||||
watcherProxy(connection).RegisterStatusNotifierItem(ITEM_PATH)
|
||||
Logger.i(LOG_TAG, "SNI item registered at $ITEM_PATH (${connection.uniqueName})")
|
||||
|
||||
connection.sendMessage(SniItemIface.NewIcon(ITEM_PATH))
|
||||
|
||||
val ownerChangedToken = subscribeToWatcherOwnerChanges(connection)
|
||||
return SniTrayController(connection, itemImpl, menuImpl, ownerChangedToken)
|
||||
} catch (failure: DBusExecutionException) {
|
||||
Logger.w(LOG_TAG, "SNI registration failed: ${failure.message}")
|
||||
} catch (failure: Exception) {
|
||||
Logger.w(LOG_TAG, "SNI setup failed: ${failure.javaClass.simpleName}: ${failure.message}")
|
||||
}
|
||||
runCatching { connection.close() }
|
||||
return null
|
||||
}
|
||||
|
||||
/** A shell restart re-renders the extension; re-register on owner changes of the watcher. */
|
||||
private fun subscribeToWatcherOwnerChanges(connection: DBusConnection) = runCatching {
|
||||
connection.addSigHandler(DBus.NameOwnerChanged::class.java) { signal ->
|
||||
if (signal.name == WATCHER_SERVICE && signal.newOwner.isNullOrBlank()) {
|
||||
Logger.i(LOG_TAG, SNI_WATCHER_LOST)
|
||||
reRegisterLater(connection)
|
||||
}
|
||||
}
|
||||
}.onFailure {
|
||||
Logger.w(LOG_TAG, "watcher NameOwnerChanged subscription failed: ${it.message}")
|
||||
}.getOrNull()
|
||||
|
||||
private fun reRegisterLater(connection: DBusConnection) {
|
||||
Thread {
|
||||
runCatching {
|
||||
val watchProps = connection.getRemoteObject(
|
||||
WATCHER_SERVICE,
|
||||
WATCHER_PATH,
|
||||
Properties::class.java,
|
||||
)
|
||||
if (remoteWatcherHostRegistered(watchProps)) {
|
||||
watcherProxy(connection).RegisterStatusNotifierItem(ITEM_PATH)
|
||||
Logger.i(LOG_TAG, "SNI re-registered after watcher owner change")
|
||||
}
|
||||
}.onFailure {
|
||||
Logger.w(LOG_TAG, "SNI re-registration failed: ${it.message}")
|
||||
}
|
||||
}.apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
private fun watcherProxy(connection: DBusConnection): SniWatcherIface =
|
||||
connection.getRemoteObject(WATCHER_SERVICE, WATCHER_PATH, SniWatcherIface::class.java)
|
||||
|
||||
/**
|
||||
* Reads `IsStatusNotifierHostRegistered` through the standard Properties proxy. The
|
||||
* interface has no annotation-constrained property getters (see [SniDBus.kt]), so the
|
||||
* generic `<A> Get` reply may arrive wrapped depending on how dbus-java coerces it.
|
||||
*/
|
||||
private fun remoteWatcherHostRegistered(properties: Properties): Boolean = runCatching {
|
||||
val requested = properties.Get<Any?>(WATCHER_IFACE_NAME, HOST_REGISTERED_PROP)
|
||||
val value = (requested as? org.freedesktop.dbus.types.Variant<*>)?.value ?: requested
|
||||
value == true
|
||||
}.getOrElse {
|
||||
Logger.w(LOG_TAG, "Watcher host check failed: ${it.message}")
|
||||
false
|
||||
}
|
||||
|
||||
/** dbus callbacks arrive on library threads; the app expects EDT like its AWT clicks. */
|
||||
private fun runOnEdt(block: () -> Unit, what: String) {
|
||||
SwingUtilities.invokeLater {
|
||||
runCatching { block() }.onFailure {
|
||||
Logger.w(LOG_TAG, "$what dispatch failed: ${it.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val SNI_WATCHER_LOST = "SNI watcher owner lost; queued re-registration"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package ru.fromchat.desktop.tray
|
||||
|
||||
import org.freedesktop.dbus.Struct
|
||||
import org.freedesktop.dbus.annotations.Position
|
||||
import org.freedesktop.dbus.exceptions.DBusException
|
||||
import org.freedesktop.dbus.interfaces.DBusSerializable
|
||||
import org.freedesktop.dbus.types.UInt32
|
||||
import org.freedesktop.dbus.types.Variant
|
||||
import java.awt.Graphics2D
|
||||
import java.awt.RenderingHints
|
||||
import java.awt.image.BufferedImage
|
||||
|
||||
/**
|
||||
* One "pixmap" of an SNI icon: an RGBA32-size struct as `a(iiay)` per the StatusNotifierItem spec.
|
||||
*
|
||||
* The pixel data is what the shell extension expects (`pixmapsUtils.js` flips ARGB→RGBA, assumes
|
||||
* `rowStride = width * 4`): four bytes per pixel in **ARGB byte order, big-endian** — exactly what
|
||||
* Java's `(alpha shl 24) or (red shl 16) or (green shl 8) or blue` reads as bytes most-significant
|
||||
* first, so the packing here is a straight shift-per-channel, no `ImageIO`.
|
||||
*/
|
||||
class SniPixmapStruct(
|
||||
@Position(0) private val width: Int,
|
||||
@Position(1) private val height: Int,
|
||||
@Position(2) private val data: ByteArray,
|
||||
) : Struct()
|
||||
|
||||
/**
|
||||
* SNI `ToolTip` struct `(sa(iiay)ss)`: theme icon name, pixmaps, title, description.
|
||||
* GNOME never reads it (shipped XML comments ToolTip out), KDE does.
|
||||
*/
|
||||
class SniToolTipStruct(
|
||||
@Position(0) private val iconName: String,
|
||||
@Position(1) private val pixmaps: List<SniPixmapStruct>,
|
||||
@Position(2) private val title: String,
|
||||
@Position(3) private val description: String,
|
||||
) : Struct()
|
||||
|
||||
/**
|
||||
* One node of the DbusMenu layout tree. The shell's client binds `GetLayout` to
|
||||
* `(u (ia{sv}av))`, i.e. children are *Variants* of recursive nodes — not the flattened form the
|
||||
* protocol spec describes. Getting this shape right is what keeps the popup from silently not
|
||||
* building.
|
||||
*/
|
||||
class SniLayoutNode(
|
||||
@Position(0) private val id: Int,
|
||||
@Position(1) private val properties: Map<String, Variant<*>>,
|
||||
/** Each element is a [Variant] wrapping another [SniLayoutNode]. */
|
||||
@Position(2) private val children: List<Variant<*>>,
|
||||
) : Struct()
|
||||
|
||||
/**
|
||||
* `GetLayout` return tuple `(u revision, node)`.
|
||||
*
|
||||
* Deliberately a [DBusSerializable] (not a `Struct`): dbus-java's exported-method return-XML
|
||||
* generator (`ExportedObject.createReturnArguments`) walks *outer* struct fields by their erased
|
||||
* `Field#getType`, so a struct with `List` fields dies on export; the serializable branch instead
|
||||
* re-derives the wire shape from the `deserialize` signature with full generic info, and the
|
||||
* runtime expands `serialize()` to exactly these reply args. `SniLayoutNode` stays a Struct — the
|
||||
* deep struct recursion is generic-aware.
|
||||
*/
|
||||
class SniGetLayoutResult(
|
||||
private var revision: UInt32,
|
||||
private var root: SniLayoutNode,
|
||||
) : DBusSerializable {
|
||||
override fun serialize(): Array<Any?> = arrayOf(revision, root)
|
||||
|
||||
fun deserialize(revision: UInt32, root: SniLayoutNode) {
|
||||
// Inbound GetLayout replies never happen (we are the server); contract requires the method.
|
||||
this.revision = revision
|
||||
this.root = root
|
||||
}
|
||||
}
|
||||
|
||||
/** `GetGroupProperties` response element: one item's full property map. */
|
||||
class SniItemProperties(
|
||||
@Position(0) private val id: Int,
|
||||
@Position(1) private val properties: Map<String, Variant<*>>,
|
||||
) : Struct()
|
||||
|
||||
/** `ItemsPropertiesUpdated` second argument element `a(ias)`: id + removed property names. */
|
||||
class SniRemovedProperties(
|
||||
@Position(0) private val id: Int,
|
||||
@Position(1) private val names: List<String>,
|
||||
) : Struct()
|
||||
|
||||
/** `EventGroup` element `a(isvu)`. */
|
||||
class SniEventStruct(
|
||||
@Position(0) private val id: Int,
|
||||
@Position(1) private val eventId: String,
|
||||
@Position(2) private val data: Variant<*>,
|
||||
@Position(3) private val timestamp: UInt32,
|
||||
) : Struct() {
|
||||
fun menuId() = id
|
||||
|
||||
fun menuEventId() = eventId
|
||||
}
|
||||
|
||||
/** `AboutToShowGroup` return tuple `(ai updatesNeeded, ai idErrors)`; see `SniGetLayoutResult`. */
|
||||
class SniAboutToShowGroupResult(
|
||||
private var updatesNeeded: List<Int>,
|
||||
private var idErrors: List<Int>,
|
||||
) : DBusSerializable {
|
||||
override fun serialize(): Array<Any?> = arrayOf(updatesNeeded, idErrors)
|
||||
|
||||
fun deserialize(updatesNeeded: List<Int>, idErrors: List<Int>) {
|
||||
// Inbound only; we always send false / empty lists (static menu tree).
|
||||
this.updatesNeeded = updatesNeeded
|
||||
this.idErrors = idErrors
|
||||
}
|
||||
}
|
||||
|
||||
/** Progressively downsizes [image] to each requested square size, keeping ARGB. */
|
||||
internal fun sniPixmaps(image: BufferedImage, sizes: List<Int>): List<SniPixmapStruct> =
|
||||
sizes.map { size ->
|
||||
val scaled = resizeSquare(image, size)
|
||||
SniPixmapStruct(scaled.width, scaled.height, argb32Bytes(scaled))
|
||||
}
|
||||
|
||||
/**
|
||||
* ARGB32 big-endian byte stream of [image] (see [SniPixmapStruct]): per pixel the four bytes
|
||||
* `alpha, red, green, blue`.
|
||||
*/
|
||||
private fun argb32Bytes(image: BufferedImage): ByteArray {
|
||||
val buffer = image.getRGB(0, 0, image.width, image.height, null, 0, image.width)
|
||||
val bytes = ByteArray(buffer.size * 4)
|
||||
var i = 0
|
||||
for (pixel in buffer) {
|
||||
bytes[i++] = (pixel ushr 24).toByte()
|
||||
bytes[i++] = (pixel ushr 16).toByte()
|
||||
bytes[i++] = (pixel ushr 8).toByte()
|
||||
bytes[i++] = pixel.toByte()
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
private fun resizeSquare(source: BufferedImage, size: Int): BufferedImage {
|
||||
if (source.width == size && source.height == size) return source
|
||||
val out = BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB)
|
||||
val graphics: Graphics2D = out.createGraphics()
|
||||
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
|
||||
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
|
||||
graphics.drawImage(source, 0, 0, size, size, null)
|
||||
graphics.dispose()
|
||||
return out
|
||||
}
|
||||
|
||||
private fun variantOf(value: Any?) = Variant(value)
|
||||
|
||||
/** Menu node property maps (string keys per the DbusMenu property catalogue). */
|
||||
internal sealed interface SniMenuItemType {
|
||||
data object Separator : SniMenuItemType
|
||||
data class Item(val label: String, val enabled: Boolean) : SniMenuItemType
|
||||
}
|
||||
|
||||
internal fun SniMenuItemType.dbusmenuProps(): Map<String, Variant<*>> =
|
||||
when (this) {
|
||||
is SniMenuItemType.Separator -> buildMap {
|
||||
put("type", variantOf("separator"))
|
||||
put("visible", variantOf(true))
|
||||
put("enabled", variantOf(true))
|
||||
}
|
||||
is SniMenuItemType.Item -> buildMap {
|
||||
put("type", variantOf("standard"))
|
||||
put("label", variantOf(label))
|
||||
put("visible", variantOf(true))
|
||||
put("enabled", variantOf(enabled))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
# SNI-over-D-Bus tray for Linux (GNOME 50+ Wayland)
|
||||
|
||||
Status: **design, not yet implemented** — all claims below were verified against the
|
||||
`ubuntu-appindicators@ubuntu.com` sources shipped on the actual target VM
|
||||
(Ubuntu 26.04.1, GNOME Shell 50.1, Parallels ARM64). Extension files referenced:
|
||||
`statusNotifierWatcher.js`, `appIndicator.js`, `dbusMenu.js`,
|
||||
`indicatorStatusIcon.js`, `interfaces-xml/*.xml`, `pixmapsUtils.js`.
|
||||
|
||||
## 1. Problem
|
||||
|
||||
The Linux tray today is Java AWT `SystemTray`/`TrayIcon` — XEmbed on Linux
|
||||
(`XTrayIconPeer`, JDK-8341144: hard-coded 24×24, no HiDPI). Every desktop moved to
|
||||
the **StatusNotifierItem (SNI)** protocol years ago; GNOME upstream removed the
|
||||
XEmbed host entirely in GNOME 45. Our tray icon only shows on GNOME today because
|
||||
Ubuntu's AppIndicator extension still shims XEmbed *behind a setting*
|
||||
(`org.gnome.shell.extensions.appindicator legacy-tray-enabled`, currently `true` on
|
||||
our VM). When Ubuntu flips that default, or on GNOME upstream, the icon vanishes
|
||||
and the custom Compose popup with it — the icon has no owner to click.
|
||||
|
||||
SNI replaces the whole XEmbed round-trip: the shell itself hosts the icon and
|
||||
renders our menu; the windows/geometry code (`DesktopTrayMenu.kt`, the whole
|
||||
translucent-window dance) is not even involved on GNOME.
|
||||
|
||||
## 2. Evidence — what the target session actually provides
|
||||
|
||||
Verified via D-Bus and by reading the extension sources on the VM:
|
||||
|
||||
- **Watcher**: `org.kde.StatusNotifierWatcher` is owned by gnome-shell (the
|
||||
extension), object path `/StatusNotifierWatcher`;
|
||||
`IsStatusNotifierHostRegistered = true`, `ProtocolVersion = 0`.
|
||||
Existing items (snapd/updater) register with *attachment-style paths*
|
||||
(`:1.42@/org/ayatana/NotificationItem/livepatch`).
|
||||
- **Registration** (`statusNotifierWatcher.js: RegisterStatusNotifierItemAsync`):
|
||||
two accepted argument styles —
|
||||
- `service` starting with `/` (ayatana style) → bus name = **caller's unique
|
||||
sender name**, object path = `service`;
|
||||
- `service` a well-known bus name (KDE style) → object path defaults to
|
||||
`/StatusNotifierItem`.
|
||||
Either works. We use the ayatana style: one unique D-Bus connection, path
|
||||
`/org/ayatana/NotificationItem/FromChat`.
|
||||
- **Click semantics** (`indicatorStatusIcon.js vfunc_button_press_event`, middle
|
||||
of the story):
|
||||
| click | shell behavior |
|
||||
|---|---|
|
||||
| left single | if `Activate` method present: **menu opens after the double-click timeout** (`_waitForDoubleClick` → `menu.toggle()`); if the item has no `Activate` method: menu opens immediately |
|
||||
| left double | `_maybeHandleDoubleClick` → `appIndicator.open(x, y)` → **`Activate(x, y)`** on our item |
|
||||
| right | `menu.toggle()` — always the shell-rendered DbusMenu popup |
|
||||
| middle | `secondaryActivate` → prefers *`XAyatanaSecondaryActivate(timestamp)`* then `SecondaryActivate(x, y)` |
|
||||
| scroll | `Scroll(delta, orientation)` |
|
||||
- **Activation token**: before calling `Activate` the shell calls
|
||||
`ProvideXdgActivationToken(token)` on our item if we have that method
|
||||
(`appIndicator.js provideActivationToken`) — relevant on Wayland when we launch
|
||||
a new window from the tray click.
|
||||
- **Menu client** (`dbusMenu.js`): implements the *client* side of
|
||||
`com.canonical.dbusmenu` (its shipped XML is authoritative for the wire
|
||||
contract — see §4). After building the root layout it calls
|
||||
`AboutToShow(0)` unconditionally ("Dropbox requires us to call AboutToShow(0)
|
||||
first"), and calls `Event(root, 'opened'/'closed', …)` when the popup opens and
|
||||
closes, `Event(id, 'clicked', …)` on activation.
|
||||
- **Icons** (`pixmapsUtils.js getBestPixmap`): data bytes are **ARGB32,
|
||||
big-endian** (`argbToRgba` flips ARGB→RGBA), `rowStride = width * 4` assumed,
|
||||
and the shell picks the **smallest pixmap ≥ preferred size**, else the largest.
|
||||
Panel tray size is ~16 logical px (Yaru/Ubuntu: 2× → 32, 3× → 48), so supply
|
||||
**32×32 and 48×48**; only one pixmap is ever read at a time (the array is
|
||||
re-fetched when we emit `NewIcon`).
|
||||
- **Tooltips**: the shipped XML comments `ToolTip`/`NewToolTip` *out* — GNOME
|
||||
shows no tooltip. KDE (which reads ToolTip) will show it, so still set it.
|
||||
- **No left-click-setting**: extension prefs only expose icon/legacy-tray pages —
|
||||
there is no "click mode" knob; the behavior matrix above is hard-coded.
|
||||
|
||||
## 3. Architecture
|
||||
|
||||
### Library (preflight-checked)
|
||||
|
||||
- **`org.freedesktop.dbus:dbus-java-core` (hypfvieh, ≥ 5.x, MIT)** +
|
||||
`dbus-java-transport-native-unixsocket`. Pure Java, no GTK/JNA, maintained;
|
||||
handles marshalling, object export, properties and signals. Note the version
|
||||
compat matrix at implementation time (dbus-java 5 needs Java 11+, ours is 21).
|
||||
- Alternatives rejected:
|
||||
- *dorkbox SystemTray* — JNA+GTK-3 bind to `libayatana-appindicator3`, a
|
||||
legacy GTK3 stack Ubuntu is actively deprecating; drags in win32/mac native
|
||||
bits; hides the protocol instead of fixing it.
|
||||
- *raw hand-rolled D-Bus client* — thousands of lines of marshalling; waste.
|
||||
- *status quo* — depends on the legacy XEmbed shim being enabled (§1).
|
||||
|
||||
### Code layout (new package `ru.fromchat.desktop.tray`)
|
||||
|
||||
| file | role |
|
||||
|---|---|
|
||||
| `SniDBus.kt` | D-Bus interfaces (`SniItemIface`, `SniMenuIface`, `SniWatcherIface`) — method-only declarations; properties live in the hand-rolled `Properties` impls below because dbus-java binds `@DBusBoundProperty` getters by their raw Java type, which cannot express `a(iiay)` from Kotlin |
|
||||
| `SniTypes.kt` | wire structs, ARGB32 pixmap packing, `sniPixmaps()` widening, menu-item property maps |
|
||||
| `SniProperties.kt` | shared `org.freedesktop.DBus.Properties` implementation served by each exported object (explicit-signed `Variant` values) |
|
||||
| `SniItemImpl.kt` | `org.kde.StatusNotifierItem` export: properties, tooltip state, `Activate`/`SecondaryActivate` → callbacks |
|
||||
| `SniMenuImpl.kt` | `com.canonical.dbusmenu` export: static tree `status | sep | Show | About | sep | Quit`, `GetLayout`/`Event` handlers, label updates via `ItemsPropertiesUpdated` |
|
||||
| `SniTray.kt` | `SniTrayController.tryInstall/updateStatus/close`: connection lifecycle, watcher registration, `NameOwnerChanged` re-register, EDT-hopped callbacks |
|
||||
| `DesktopTrayMenu.kt` | decision point in `DesktopTrayHost`: Linux → SNI first, AWT/XEmbed fallback only when the session bus / watcher is missing. Windows/macOS unchanged |
|
||||
|
||||
`Main.kt` keeps selecting Compose `Tray` on macOS, and replaces the Linux/Windows
|
||||
branch with `DesktopTrayHost` → SNI decision inside it (Windows never takes the
|
||||
SNI path; decision gated to Linux).
|
||||
|
||||
### dbus-java 5.2.2 implementation notes (two trapping quirbs, both solved in pure Kotlin)
|
||||
|
||||
1. **`@DBusBoundProperty` is unusable from Kotlin.** The annotation's `type` argument needs
|
||||
class literals like `SniPixmapStruct[].class` — not expressible as Kotlin annotation
|
||||
arguments — and the fallback binding, the getter's raw Java type, exports raw `List`
|
||||
as `av` or refuses the export. Solution: no bound properties at all; each exported object
|
||||
*also implements* `org.freedesktop.DBus.Properties` (`SniPropertiesProvider`) with values
|
||||
built as `Variant(value, "a(iiay)")` etc., so dbus-java marshals exactly the wire types of
|
||||
§4. Remote watcher properties (`IsStatusNotifierHostRegistered`) are read through the
|
||||
standard `Properties` proxy the same way; `SniWatcherIface` only carries the register call.
|
||||
2. **Exported-method return structs go through an erased-field XML generator**
|
||||
(`ExportedObject.createReturnArguments` uses `Field#getType` on the *outer* struct), so any
|
||||
`Pair`-like struct with `List`/`Map` fields dies at `exportObject` with
|
||||
`Exporting non-exportable type: java.util.List` even though deeper struct recursion is
|
||||
generic-aware. Solution: make outer return structs implement `dbus-java`'s
|
||||
`DBusSerializable` (`SniGetLayoutResult`, `SniAboutToShowGroupResult`) — the wire shape is
|
||||
then derived from the `deserialize` signature with full generic info, and the runtime
|
||||
expands `serialize()` to exactly the reply args of §4. (`GetLayout` → `u` + `(ia{sv}av)`,
|
||||
`AboutToShowGroup` → `ai` + `ai`, verified in the exported introspection XML.)
|
||||
|
||||
### Lifecycle
|
||||
|
||||
- Connection attaches lazily on first need (desktop app start, after the
|
||||
AWT/Toolkit is up), on a daemon thread, never blocking startup: tray is a nice-to-have — any D-Bus
|
||||
failure logs a warning and leaves the window-only UX intact.
|
||||
- `SystemTray.isSupported()` stays the first check for the *fallback* path only.
|
||||
- App quit → `connection.close()` so D-Bus doesn't outlive us; single-instance
|
||||
lock unaffected (no well-known name ownership; caller-side unique names are fine
|
||||
with both the extension and plasmashell).
|
||||
- Watcher restart: on `NameOwnerChanged` for the watcher, re-export (cheap) and
|
||||
re-call `RegisterStatusNotifierItem`. The shell also re-scans existing
|
||||
implementations after registration, so duplicates must be idempotent (extension
|
||||
warns but tolerates a duplicate register; we just re-register once).
|
||||
|
||||
## 4. The wire contract (exact, from the shipped XML)
|
||||
|
||||
### `org.kde.StatusNotifierItem` (export at `/org/ayatana/NotificationItem/FromChat`)
|
||||
|
||||
```
|
||||
Properties: Category "ApplicationStatus"; Id "FromChat"; Title "FromChat";
|
||||
Status "Active"; WindowId 0; IconThemePath "";
|
||||
ItemIsMenu false; Menu "/org/ayatana/NotificationItem/FromChat/Menu"
|
||||
IconPixmap a(iiay) // see §2 icon packaging
|
||||
ToolTip (sa(iiay)ss) // icon struct, title, description
|
||||
Methods: Activate(i x, i y) → showMainWindow()
|
||||
SecondaryActivate(i x, i y) → showMainWindow()
|
||||
ContextMenu(i x, i y) → no-op (shell opens our Menu itself)
|
||||
ProvideXdgActivationToken(s) → stash token, publish via GDK?
|
||||
(v1: no-op with log)
|
||||
Scroll(i, s) → no-op
|
||||
Signals: NewIcon() once after registration (pixmap refresh trigger)
|
||||
```
|
||||
|
||||
Note on `Activate` presence: with `Activate` exported, GNOME adds the
|
||||
double-click wait on single left-press (menu toggle ~0.4 s later) and double-click
|
||||
becomes "raise main window". Without it the menu opens instantly but nothing else
|
||||
can trigger show. We export `Activate` (matches Telegram/Steam behavior and KDE
|
||||
where left-click *is* activation), and give the menu a prominent "Show" row so
|
||||
single-click users are served too.
|
||||
|
||||
### `com.canonical.dbusmenu` (export at `Menu` path above)
|
||||
|
||||
Shipped XML (authoritative — the shell only calls what its own XML declares):
|
||||
|
||||
```
|
||||
GetLayout(i parentId, i recursionDepth, as propertyNames)
|
||||
→ (u revision, (ia{sv}av) layout)
|
||||
// NB: children arrive as Variants of recursive nodes — NOT the
|
||||
// spec's flattened (ia{sv}ia{sv}); dbus-java must be told the
|
||||
// (ia{sv}av) node type explicitly
|
||||
GetGroupProperties(ai ids, as propertyNames) → a(ia{sv})
|
||||
GetProperty(i id, s name) → v
|
||||
Event(i id, s eventId, v data, u timestamp) → (void)
|
||||
EventGroup(a(isvu) events) → ai idErrors
|
||||
AboutToShow(i id) → b needUpdate
|
||||
AboutToShowGroup(ai ids) → (ai updatesNeeded, ai idErrors)
|
||||
Properties: Version u (protocol v2 ⇒ respond 2); TextDirection "ltr";
|
||||
Status "normal"; IconThemePath as (empty array)
|
||||
Signals: LayoutUpdated(u revision, i parent) — on tree changes (v1: status label only → property updates, no tree change)
|
||||
ItemsPropertiesUpdated(a(ia{sv}) updated, a(ias) removed)
|
||||
ItemActivationRequested(i id, u timestamp) — optional, unused
|
||||
```
|
||||
|
||||
Client flow to expect (from `dbusMenu.js`):
|
||||
|
||||
1. `GetLayout(0, -1, ['type','children-display'])` for the skeleton;
|
||||
2. `GetGroupProperties(ids=[], propertyNames: 'label','visible','enabled','type','children-display','icon-name','icon-data','toggle-type','toggle-state',…)`;
|
||||
3. `AboutToShow(0)` — respond `needUpdate=false` once the snapshot is stable
|
||||
(returning `true` makes the client re-fetch the full layout);
|
||||
4. popup open/close → `root Event 'opened'/'closed'`; item click →
|
||||
`Event(id,'clicked', v(int 0), timestamp)`.
|
||||
|
||||
Client rendering rules worth respecting:
|
||||
|
||||
- item `type = "separator"` → separator; `children-display = "submenu"` → submenu
|
||||
(we ship both; no `AboutToShowGroup` calls expected for an empty-separator tree);
|
||||
- `label` mnemonic: client rewrites `_x` → plain `x` (first match only) — keep `_`
|
||||
out of translated labels or allow it as a mnemonic;
|
||||
- `enabled=false` renders insensitive (our status row);
|
||||
- `icon-name` is read via the **shell theme** only (`St.Icon.icon_name`), and
|
||||
`icon-data` must be **PNG bytes** (client feeds them to `GdkPixbuf`) — v1 ships
|
||||
text-only items (no icons per item) to keep the first cut small; item icons can
|
||||
come later as PNGs rendered off-screen.
|
||||
|
||||
Property-change plumbing: status row label changes → `ItemsPropertiesUpdated([ (1, {label: s}), …], [])`
|
||||
emitted by the model diff section.
|
||||
|
||||
## 5. Verification plan (hard gates, per the screenshot rule)
|
||||
|
||||
1. **D-Bus presence gates** (scripted, via MCP exec):
|
||||
- watcher props before/after registration: our item id string appears in
|
||||
`RegisteredStatusNotifierItems`;
|
||||
- `busctl --user tree`/`gdbus introspect --session --dest
|
||||
<unique-name> --object-path /org/ayatana/NotificationItem/FromChat` returns
|
||||
exported `StatusNotifierItem` + `Menu` interfaces.
|
||||
2. **Visual gate** (`parallels_vm_capture`, mandatory before claiming success):
|
||||
app running → icon visible in the top bar → open the popup (mouse press on the
|
||||
icon) → screenshot; then screenshot after closing.
|
||||
3. **Interaction gates** (execution + screenshot):
|
||||
- menu "Show" raises the main window (screenshot changes);
|
||||
- menu "Quit" exits the app (`pgrep FromChat` → 0 — historically `pkill -f`
|
||||
killed shells: never use it);
|
||||
- window-close-to-tray still re-shows from the tray.
|
||||
4. **Regression gates**: hardware-accelerated render still healthy afterwards
|
||||
(`grep -c` of `Fallback to next API`/`Shader compilation error` in
|
||||
`launch.log` must stay `0`, `healthy=1` line present) + screenshot of the main
|
||||
window; `MESA_GL_VERSION_OVERRIDE=3.0` wrapper path (`/usr/local/bin/fromchat-hwgl`)
|
||||
unaffected.
|
||||
5. **Fallback regression**: with the watcher hidden (`gdbus call … Unregister`
|
||||
is not possible; simulate by renaming host extension off) `SystemTray` path
|
||||
still compiles — unit-test the decision table instead of GUI-testing it.
|
||||
|
||||
## 6. Risks / open questions
|
||||
|
||||
- **dbus-java node typing**: `GetLayout` children being `(ia{sv}av)` (variant
|
||||
recursion) must be exactly right; a wrong signature makes the shell log
|
||||
`Failed to read layout` and drop the menu. Verify against a debug
|
||||
`busctl intercept`… realistically: iterate against the real shell and read its
|
||||
logger (`journalctl --user -u gnome-shell | grep -i appindicator`).
|
||||
- **dbus-java Properties interface**: we implement manual `Properties.Get/Set/GetAll`
|
||||
responders (the library's `DBusInterface`/`ExportedObject` may already provide it
|
||||
— confirm with a smoke test; the tool must not re-implement what it exports).
|
||||
- Deb/jpackage bundling of the 2 extra jars (dbus-java-core,
|
||||
unixsocket transport + jnr-style peer deps? none: the **hollow** native
|
||||
transport uses the same `libunixsocket-java`? check dbus-java 5's unixsocket
|
||||
transport's own dependencies at implementation time) — `createDistributable`
|
||||
already ships `lib/` jars, so it should be automatic; verify in the built deb.
|
||||
- **KDE plasma** (not our target VM) uses `com.canonical.dbusmenu` too, so the one
|
||||
implementation covers it; XFCE (X11) may still be XEmbed-hosted → keep fallback.
|
||||
- Future: item icons per menu row (PNG bytes), `Scroll`→workspace switching,
|
||||
attention state (e.g. connection-error ordering number badge on the icon),
|
||||
upstream report
|
||||
if we find extension-side bugs in `GetGroupProperties` handling (we ship the
|
||||
whole property map anyway, sidestepping partial-property merges).
|
||||
@@ -6,6 +6,7 @@ androidx-core-ktx = "1.19.1"
|
||||
androidx-exifinterface = "1.4.2"
|
||||
coilCompose = "3.6.3"
|
||||
compose-multiplatform = "1.12.1"
|
||||
dbusJava = "5.2.2"
|
||||
#noinspection NewerVersionAvailable
|
||||
constraintlayout = "0.8.0-shaded"
|
||||
coreSplashscreen = "1.2.0"
|
||||
@@ -31,6 +32,7 @@ datastore = "1.2.1"
|
||||
security-crypto = "1.1.0"
|
||||
ktor = "3.6.0"
|
||||
slf4j = "1.7.36"
|
||||
slf4jJdk14 = "2.0.17"
|
||||
kotlinxDatetime = "0.8.0"
|
||||
lifecycleRuntimeKtx = "2.11.0"
|
||||
composeBom = "2026.09.00"
|
||||
@@ -114,6 +116,9 @@ tweetnacl-java = { module = "org.purejava:tweetnacl-java", version.ref = "tweetn
|
||||
krypto = { module = "com.soywiz.korlibs.krypto:krypto", version.ref = "krypto" }
|
||||
cryptography-core = { module = "dev.whyoleg.cryptography:cryptography-core", version.ref = "cryptography-kotlin" }
|
||||
cryptography-provider-optimal = { module = "dev.whyoleg.cryptography:cryptography-provider-optimal", version.ref = "cryptography-kotlin" }
|
||||
dbus-java-core = { group = "com.github.hypfvieh", name = "dbus-java-core", version.ref = "dbusJava" }
|
||||
dbus-java-transport-native-unixsocket = { group = "com.github.hypfvieh", name = "dbus-java-transport-native-unixsocket", version.ref = "dbusJava" }
|
||||
slf4j-jdk14 = { group = "org.slf4j", name = "slf4j-jdk14", version.ref = "slf4jJdk14" }
|
||||
androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "androidxWork" }
|
||||
androidx-webkit = { module = "androidx.webkit:webkit", version.ref = "webkit" }
|
||||
#noinspection UnusedVersionCatalogEntry
|
||||
|
||||
Reference in New Issue
Block a user