Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-window

Source of release 0.6.3

0.6.3 / src / window / linux / appearance.lucb

#==============================================================================================
#
#   appearance - Light or dark on Linux, from the XDG desktop portal
#
#   DESCRIPTION:
#       GNOME, KDE and other desktops publish the user's choice as the portal setting
#       org.freedesktop.appearance color-scheme, read over the session D-Bus with
#       org.freedesktop.portal.Settings.ReadOne (Read on portals before version 2, which
#       wraps the value in one more variant) and announced by its SettingChanged signal.
#       libdbus-1 is opened at run time on a private connection of the process's own, so
#       nothing is linked and no other library's messages are taken; without libdbus, a
#       session bus or the portal, the appearance is light. The connection's descriptor
#       joins the window's wait, and its signals are read when windows pump.
#
#==============================================================================================

## DBusError and DBusMessageIter, opaque storage larger than libdbus's own (32 and 72 bytes).
extern struct DBusErrorBuffer:
    words: u64[8]

extern struct DBusIterBuffer:
    words: u64[16]

## The libdbus functions the setting needs.
struct DBusApi:
    var error_init: func(DBusErrorBuffer*) -> unit
    var error_free: func(DBusErrorBuffer*) -> unit
    var bus_get_private: func(i32, DBusErrorBuffer*) -> void*?
    var set_exit_on_disconnect: func(void*, u32) -> unit
    var add_match: func(void*, c.str, DBusErrorBuffer*) -> unit
    var get_unix_fd: func(void*, i32*) -> u32
    var read_write: func(void*, i32) -> u32
    var pop_message: func(void*) -> void*?
    var new_method_call: func(c.str, c.str, c.str, c.str) -> void*?
    var send_with_reply_and_block: func(void*, void*, i32, DBusErrorBuffer*) -> void*?
    var message_unref: func(void*) -> unit
    var is_signal: func(void*, c.str, c.str) -> u32
    var iter_init_append: func(void*, DBusIterBuffer*) -> unit
    var iter_append_basic: func(DBusIterBuffer*, i32, const void*) -> u32
    var iter_init: func(void*, DBusIterBuffer*) -> u32
    var iter_arg_type: func(DBusIterBuffer*) -> i32
    var iter_recurse: func(DBusIterBuffer*, DBusIterBuffer*) -> unit
    var iter_get_basic: func(DBusIterBuffer*, void*) -> unit
    var iter_next: func(DBusIterBuffer*) -> u32

## The portal connection, once tried: `connection` stays none when it could not be made.
struct DBusLink:
    var api: DBusApi
    var connection: void*?
    var descriptor: i32
    var scheme: input.Appearance

var dbus_tried: bool
var dbus_link: DBusLink? = none

let dbus_type_string: i32 = 115
let dbus_type_variant: i32 = 118
let dbus_type_uint32: i32 = 117
let dbus_type_int32: i32 = 105

func dbus_symbol(library: void*, name: c.str) -> void*!:
    return dlsym(library, name) else error(unsupported, "the installed libdbus lacks a function the appearance needs")

func dbus_load(library: void*) -> DBusApi!:
    return DBusApi(
        error_init = (func(DBusErrorBuffer*) -> unit)(try dbus_symbol(library, "dbus_error_init")),
        error_free = (func(DBusErrorBuffer*) -> unit)(try dbus_symbol(library, "dbus_error_free")),
        bus_get_private = (func(i32, DBusErrorBuffer*) -> void*?)(try dbus_symbol(library, "dbus_bus_get_private")),
        set_exit_on_disconnect = (func(void*, u32) -> unit)(try dbus_symbol(library, "dbus_connection_set_exit_on_disconnect")),
        add_match = (func(void*, c.str, DBusErrorBuffer*) -> unit)(try dbus_symbol(library, "dbus_bus_add_match")),
        get_unix_fd = (func(void*, i32*) -> u32)(try dbus_symbol(library, "dbus_connection_get_unix_fd")),
        read_write = (func(void*, i32) -> u32)(try dbus_symbol(library, "dbus_connection_read_write")),
        pop_message = (func(void*) -> void*?)(try dbus_symbol(library, "dbus_connection_pop_message")),
        new_method_call = (func(c.str, c.str, c.str, c.str) -> void*?)(try dbus_symbol(library, "dbus_message_new_method_call")),
        send_with_reply_and_block = (func(void*, void*, i32, DBusErrorBuffer*) -> void*?)(try dbus_symbol(library, "dbus_connection_send_with_reply_and_block")),
        message_unref = (func(void*) -> unit)(try dbus_symbol(library, "dbus_message_unref")),
        is_signal = (func(void*, c.str, c.str) -> u32)(try dbus_symbol(library, "dbus_message_is_signal")),
        iter_init_append = (func(void*, DBusIterBuffer*) -> unit)(try dbus_symbol(library, "dbus_message_iter_init_append")),
        iter_append_basic = (func(DBusIterBuffer*, i32, const void*) -> u32)(try dbus_symbol(library, "dbus_message_iter_append_basic")),
        iter_init = (func(void*, DBusIterBuffer*) -> u32)(try dbus_symbol(library, "dbus_message_iter_init")),
        iter_arg_type = (func(DBusIterBuffer*) -> i32)(try dbus_symbol(library, "dbus_message_iter_get_arg_type")),
        iter_recurse = (func(DBusIterBuffer*, DBusIterBuffer*) -> unit)(try dbus_symbol(library, "dbus_message_iter_recurse")),
        iter_get_basic = (func(DBusIterBuffer*, void*) -> unit)(try dbus_symbol(library, "dbus_message_iter_get_basic")),
        iter_next = (func(DBusIterBuffer*) -> u32)(try dbus_symbol(library, "dbus_message_iter_next")))

## The session bus and the setting, on first use; none without them.
func dbus_connect() -> DBusLink?:
    if dbus_tried:
        return dbus_link
    dbus_tried = true
    # RTLD_NOW | RTLD_LOCAL.
    let library = dlopen("libdbus-1.so.3", 2) else return none
    let api = dbus_load(library) catch failure:
        _ = failure
        return none
    var problem: DBusErrorBuffer
    api.error_init(&problem)
    defer api.error_free(&problem)
    # DBUS_BUS_SESSION, on a connection of our own: popping its messages takes no one else's.
    let connection = api.bus_get_private(0, &problem) else return none
    # libdbus would otherwise end the process when the bus goes away.
    api.set_exit_on_disconnect(connection, 0)
    var link = DBusLink(api = api, connection = connection, descriptor = -1, scheme = dbus_read_scheme(api, connection))
    api.add_match(connection, "type='signal',interface='org.freedesktop.portal.Settings',member='SettingChanged',arg0='org.freedesktop.appearance',arg1='color-scheme'", &problem)
    var descriptor: i32 = -1
    if api.get_unix_fd(connection, &descriptor) != 0:
        link.descriptor = descriptor
    dbus_link = link
    return link

## Ask the portal for color-scheme: ReadOne, then Read for portals that lack it.
func dbus_read_scheme(api: DBusApi, connection: void*) -> input.Appearance:
    if let scheme = dbus_call_read(api, connection, "ReadOne"):
        return portal_appearance(scheme)
    if let scheme = dbus_call_read(api, connection, "Read"):
        return portal_appearance(scheme)
    return input.Appearance.light

func dbus_call_read(api: DBusApi, connection: void*, method: c.str) -> u32?:
    let message = api.new_method_call("org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Settings", method) else return none
    defer api.message_unref(message)
    var arguments: DBusIterBuffer
    api.iter_init_append(message, &arguments)
    var space: c.str = "org.freedesktop.appearance"
    var key: c.str = "color-scheme"
    if api.iter_append_basic(&arguments, dbus_type_string, (const void*)&space) == 0 or api.iter_append_basic(&arguments, dbus_type_string, (const void*)&key) == 0:
        return none
    var problem: DBusErrorBuffer
    api.error_init(&problem)
    defer api.error_free(&problem)
    # A portal that is starting can take a moment; a missing one answers at once.
    let reply = api.send_with_reply_and_block(connection, message, 2000, &problem) else return none
    defer api.message_unref(reply)
    var values: DBusIterBuffer
    if api.iter_init(reply, &values) == 0:
        return none
    return dbus_scheme_value(api, &values)

## The number inside a value of one or more variants (Read nests two), or none.
func dbus_scheme_value(api: DBusApi, iterator: DBusIterBuffer*) -> u32?:
    var current = *iterator
    var depth = 0
    while depth < 4:
        let kind = api.iter_arg_type(&current)
        if kind == dbus_type_uint32 or kind == dbus_type_int32:
            var number: u32 = 0
            api.iter_get_basic(&current, (void*)&number)
            return number
        if kind != dbus_type_variant:
            return none
        var inner: DBusIterBuffer
        api.iter_recurse(&current, &inner)
        current = inner
        depth += 1
    return none

## Read what the bus sent without blocking; a SettingChanged for color-scheme updates
## the setting. Returns whether it changed.
func dbus_drain() -> bool:
    var link = dbus_link else return false
    let connection = link.connection else return false
    let api = link.api
    let before = link.scheme
    _ = api.read_write(connection, 0)
    var count = 0
    while count < 64:
        let message = api.pop_message(connection) else break
        count += 1
        if api.is_signal(message, "org.freedesktop.portal.Settings", "SettingChanged") != 0:
            if let scheme = dbus_changed_scheme(api, message):
                link.scheme = portal_appearance(scheme)
        api.message_unref(message)
    dbus_link = link
    return link.scheme != before

## SettingChanged(namespace s, key s, value v): the value, when it is color-scheme's.
func dbus_changed_scheme(api: DBusApi, message: void*) -> u32?:
    var arguments: DBusIterBuffer
    if api.iter_init(message, &arguments) == 0:
        return none
    for expected in ["org.freedesktop.appearance", "color-scheme"]:
        if api.iter_arg_type(&arguments) != dbus_type_string:
            return none
        var text: c.str? = none
        api.iter_get_basic(&arguments, (void*)&text)
        let name = text else return none
        if not c_text_equals(name, expected):
            return none
        if api.iter_next(&arguments) == 0:
            return none
    return dbus_scheme_value(api, &arguments)

func c_text_equals(text: c.str, expected: str) -> bool:
    let bytes = (const u8*)text
    for index in 0..<expected.length:
        if bytes[index] != expected.bytes[index]:
            return false
    return bytes[expected.length] == 0

func linux_system_appearance() -> input.Appearance:
    let link = dbus_connect() else return input.Appearance.light
    if dbus_drain():
        linux_announce_appearance()
    return (dbus_link else link).scheme

## The bus's descriptor for the window's wait, or -1.
func dbus_descriptor() -> i32:
    let link = dbus_link else return -1
    return link.descriptor

## Tell every open window the setting changed.
func linux_announce_appearance():
    let link = dbus_link else return
    for slot in x11_windows:
        if let state = slot:
            note_appearance(state, link.scheme)