@[has_globals] module main // This file is built only with -d mpris. Without it, mpris_notd_mpris.v takes // its place and libdbus is neither needed nor linked. // // libdbus is the session bus client. The declarations below follow // dbus-1.0's headers; the include path and library come from pkg-config. #pkgconfig dbus-1 #flag -ldbus-1 import libvendetta import math import net.urllib import os import sync import ui2 // The MPRIS 2.2 D-Bus interface, so the desktop's media controls, applets and // global shortcuts see vendetta as a player. The spec: // https://specifications.freedesktop.org/mpris-spec/latest/ const mpris_name = 'org.mpris.MediaPlayer2.vendetta' const mpris_root_iface = 'org.mpris.MediaPlayer2' const mpris_player_iface = 'org.mpris.MediaPlayer2.Player' const mpris_path = '/org/mpris/MediaPlayer2' const dbus_props_iface = 'org.freedesktop.DBus.Properties' const dbus_introspectable_iface = 'org.freedesktop.DBus.Introspectable' // D-Bus wire type codes from dbus-protocol.h. const dbus_type_string = i32(`s`) const dbus_type_object_path = i32(`o`) const dbus_type_double = i32(`d`) const dbus_type_boolean = i32(`b`) const dbus_type_int64 = i32(`x`) const dbus_type_variant = i32(`v`) const dbus_type_array = i32(`a`) const dbus_type_dict_entry = i32(`e`) // Name request flags and results from dbus-shared.h. const dbus_name_flag_do_not_queue = u32(0x4) const dbus_request_name_reply_primary_owner = 1 const dbus_request_name_reply_already_owner = 4 // Handler results from dbus-connection.h. const dbus_handler_handled = 0 const dbus_handler_not_yet_handled = 1 // Message types from dbus-protocol.h. const dbus_msg_method_call = 1 // Bus type from dbus-shared.h. const dbus_bus_session = 0 // Dispatch status from dbus-connection.h. const dbus_dispatch_data_remains = 0 // Error names from dbus-protocol.h. const dbus_error_unknown_property = 'org.freedesktop.DBus.Error.UnknownProperty' const dbus_error_property_readonly = 'org.freedesktop.DBus.Error.PropertyReadOnly' const dbus_error_invalid_args = 'org.freedesktop.DBus.Error.InvalidArgs' // MprisCommand is one command the D-Bus thread queues for the UI thread, // tagged with the interface member that produced it. enum MprisCommandKind { play pause toggle_play stop next previous seek set_position open_uri quit raise volume loop_status shuffle } struct MprisCommand { kind MprisCommandKind // The argument of Seek (an offset in seconds, signed), SetPosition (an // absolute position), Volume (0..1), LoopStatus (the loop code) or // Shuffle (1 or 0). arg f64 // The track id SetPosition was addressed with; empty for Seek. track string uri string } // MprisSnapshot is the state the D-Bus thread serves reads from. The UI // thread rebuilds it from the player on every change it is told about and // hands it over; the worker only ever reads it. struct MprisSnapshot { pub: // PlaybackStatus: Paused, Playing or Stopped. status string // LoopStatus: None, Track or Playlist. loop_status string shuffle bool // mpv's volume: 100 is unity gain, and the app's max may sit above it. volume f64 has_file bool can_play bool can_pause bool can_seek bool can_go_next bool can_go_prev bool position f64 duration f64 title string artist string url string // The playlist position and length, for CanGoNext/CanGoPrevious: mpv // clamps the step commands itself, but the flags let the desktop grey // out the buttons that would do nothing. playlist_pos int playlist_len int // Rate: vendetta exposes speed as mpv holds it. rate f64 } // Mpris owns the D-Bus service. It lives in the app's Player, is created by // set_media_controls and torn down on quit. The worker thread holds no // reference to the Player: state arrives as snapshots, commands leave over a // channel, and shutdown rides a plain flag the worker polls, so the D-Bus // thread can never observe the player mid-teardown. struct Mpris { mut: // The worker's queue of commands for the UI thread. The UI thread pops it // dry once per frame; the D-Bus thread pushes. Chan push and pop are // atomic, so no lock guards it. commands chan MprisCommand // The latest snapshot for reads. Swapped for a new one under the mutex; // the worker copies the pointer out under the same mutex and answers // from its own reference afterwards, so a rebuild during a read cannot // tear the object and the UI thread never waits on D-Bus work. snapshot &MprisSnapshot = unsafe { nil } snapshot_mu &sync.Mutex = unsafe { nil } // Set by the UI thread to end the worker's loop; checked each tick. stop_flag bool // Seek tracking. mpv reports a seek when it starts and playback restarts // once it lands; the next position report after the restart is where the // seek landed, which is what Seeked carries. seeking bool landing bool // The connection, once the object path and the bus name are ours. conn voidptr // The self-pipe the worker blocks on: snapshot updates and shutdown // write a byte, so an idle service answers in milliseconds instead of // on the next poll. pipe_read_fd int = -1 pipe_write_fd int = -1 } // ── libdbus ───────────────────────────────────────────────────────────────── // The declarations follow dbus-1.0's headers as installed; dbus_connection_ // read_write_dispatch is deliberately absent: the worker polls with // read_write plus dispatch and sleeps on the wake pipe between cycles. fn C.dbus_error_init(&DBusError) fn C.dbus_error_free(&DBusError) fn C.dbus_bus_get(i32, voidptr) voidptr fn C.dbus_bus_request_name(voidptr, &char, u32, voidptr) i32 fn C.dbus_connection_ref(voidptr) voidptr fn C.dbus_connection_unref(voidptr) fn C.dbus_connection_close(voidptr) fn C.dbus_connection_unregister_object_path(voidptr, &char) i32 fn C.dbus_bus_release_name(voidptr, &char, voidptr) i32 fn C.dbus_connection_register_object_path(voidptr, &char, voidptr, voidptr) i32 fn C.dbus_connection_add_filter(voidptr, DBusFilterFn, voidptr, voidptr) i32 fn C.dbus_connection_get_dispatch_status(voidptr) i32 fn C.dbus_connection_dispatch(voidptr) i32 fn C.dbus_connection_read_write(voidptr, i32) i32 fn C.dbus_connection_send(voidptr, voidptr, voidptr) i32 fn C.dbus_message_new_method_return(voidptr) voidptr fn C.dbus_message_new_error(voidptr, &char, &char) voidptr fn C.dbus_message_new_signal(voidptr, &char, &char) voidptr fn C.dbus_message_get_type(voidptr) i32 fn C.dbus_message_get_interface(voidptr) &char fn C.dbus_message_get_member(voidptr) &char fn C.dbus_message_iter_init(voidptr, &DBusMessageIter) i32 fn C.dbus_message_iter_init_append(voidptr, &DBusMessageIter) fn C.dbus_message_iter_get_arg_type(&DBusMessageIter) i32 fn C.dbus_message_iter_get_basic(&DBusMessageIter, voidptr) fn C.dbus_message_iter_next(&DBusMessageIter) i32 fn C.dbus_message_iter_recurse(&DBusMessageIter, &DBusMessageIter) fn C.dbus_message_iter_open_container(&DBusMessageIter, i32, &char, &DBusMessageIter) i32 fn C.dbus_message_iter_close_container(&DBusMessageIter, &DBusMessageIter) i32 fn C.dbus_message_iter_append_basic(&DBusMessageIter, i32, voidptr) i32 fn C.dbus_message_append_args(voidptr, i32, voidptr, i32) i32 fn C.dbus_message_unref(voidptr) fn C.dbus_message_set_serial(voidptr, u32) // The wake pipe drains through a non-blocking read, so the worker's // post-wake loop never waits for a byte that is not coming. const fcntl_f_setfl = 4 // read and write come from the C library through builtin's declarations; the // wake pipe uses them directly. // DBusError is declared with its own shape instead of including dbus-headers. // The real struct is two const char* fields, five one-bit flags and a // padding pointer — 32 bytes; a short mirror lets dbus_error_init write // past it and smash the stack, so the bit word and the padding pointer are // spelled out. struct DBusError { name &char = unsafe { nil } message &char = unsafe { nil } flagbits u32 padding1 voidptr = unsafe { nil } } // DBusMessageIter matches the opaque struct's real layout (dbus-message.h) // exactly: two pointers, a u32, nine ints and two padding pointers on // LP64 — 88 bytes. A short mirror would let init_append and friends write // past the local and corrupt the stack, so every field is spelled out even // though none is ever read. struct DBusMessageIter { dummy1 voidptr dummy2 voidptr dummy3 u32 dummy4 i32 dummy5 i32 dummy6 i32 dummy7 i32 dummy8 i32 dummy9 i32 dummy10 i32 dummy11 i32 pad1 i32 pad2 voidptr pad3 voidptr } type DBusFilterFn = fn (voidptr, voidptr, voidptr) i32 // DBusObjectPathVTable matches dbus-connection.h's real layout: the two // handlers plus four reserved pointers libdbus copies wholesale, so the // mirror must carry them or the copy reads past the local. struct DBusObjectPathVTable { unregister_function voidptr = unsafe { nil } message_function DBusFilterFn = unsafe { nil } pad1 voidptr = unsafe { nil } pad2 voidptr = unsafe { nil } pad3 voidptr = unsafe { nil } pad4 voidptr = unsafe { nil } } // ── UI-thread side ────────────────────────────────────────────────────────── // mpris_new prepares the service. The bus connect and name request run on // the worker, so nothing here can block startup. fn mpris_new() &Mpris { mut m := &Mpris{ commands: chan MprisCommand{cap: 32} snapshot_mu: sync.new_mutex() } m.snapshot = mpris_snapshot_of_empty() // The wake pipe: os.pipe gives both fds at once, and the read end is // made non-blocking, so drain_pipe never waits for a byte that is not // coming — a blocking second read would park the worker forever right // after its first wake. A failure only costs latency: the worker's // poll keeps the service alive on its tick. if pipe := os.pipe() { m.pipe_read_fd = pipe.read_fd m.pipe_write_fd = pipe.write_fd C.fcntl(m.pipe_read_fd, fcntl_f_setfl, C.O_NONBLOCK) } return m } // mpris_free asks the service to leave the bus. The worker sees the flag on its // next tick, releases the name and its object path, and returns. Called after // run_window_with_options returns, where every other thread but this one is // parked. fn (mut m Mpris) mpris_free() { m.stop_flag = true m.wake_worker() } // mpris_announce publishes the full state: at start, on a file change, and // wherever a caller would otherwise repeat a string of property pushes. The // snapshot arrives as a heap reference the caller built; the swap hands its // ownership to the worker. fn (mut m Mpris) mpris_announce(s &MprisSnapshot) { m.replace_snapshot(s) m.wake_worker() } // mpris_property publishes one changed property. fn (mut m Mpris) mpris_property(s &MprisSnapshot) { m.replace_snapshot(s) m.wake_worker() } // mpris_seek_started notes that mpv began a seek, from any source: the // keyboard, the slider, or a Seek or SetPosition from the desktop. fn (mut m Mpris) mpris_seek_started() { m.seeking = true } // mpris_seek_landed is the restart mpv reports once a seek has landed. The // next position report carries the landed position. fn (mut m Mpris) mpris_seek_landed() { if m.seeking { m.seeking = false m.landing = true } } // mpris_on_position emits Seeked for a seek that has landed. Steady playback // moves the position without a seek, so nothing is announced for it. fn (mut m Mpris) mpris_on_position(pos f64) { if m.landing { m.landing = false m.emit_seeked(pos) } } // mpris_on_volume reacts to mpv's own volume writes (keys, wheel, the // strip's slider): the snapshot the next push carries carries the new // value, and the wake makes the worker announce it at once. fn (mut m Mpris) mpris_on_volume() { m.wake_worker() } // mpris_track_position keeps the Position property current. Reads come from // the snapshot, and a client that adds an offset to a stale Position seeks // from the wrong place, so each position change swaps in a snapshot that // carries it. No signal goes out: the spec does not announce Position changes. fn (mut m Mpris) mpris_track_position(pos f64) { m.replace_snapshot(m.current_snapshot().with_position(pos)) } // with_position returns a copy of the snapshot at another position. The copy // is a heap literal like every snapshot, since the worker may still hold the // old one. fn (s &MprisSnapshot) with_position(pos f64) &MprisSnapshot { return &MprisSnapshot{ status: s.status loop_status: s.loop_status shuffle: s.shuffle volume: s.volume has_file: s.has_file can_play: s.can_play can_pause: s.can_pause can_seek: s.can_seek can_go_next: s.can_go_next can_go_prev: s.can_go_prev position: pos duration: s.duration title: s.title artist: s.artist url: s.url playlist_pos: s.playlist_pos playlist_len: s.playlist_len rate: s.rate } } // registered reports whether the service is on the bus. fn (m &Mpris) registered() bool { return m.conn != unsafe { nil } } // wake_worker interrupts the worker's poll through the self-pipe. The bytes // read back are an event counter, not data; several writes may collapse into // one drain, which only means one spurious poll. fn (mut m Mpris) wake_worker() { if m.pipe_write_fd >= 0 { one := u8(1) C.write(m.pipe_write_fd, &one, 1) } } // drain_pipe empties the wake pipe after each poll cycle. fn (mut m Mpris) drain_pipe() { for { mut b := u8(0) n := C.read(m.pipe_read_fd, &b, 1) if n <= 0 { return } } } // replace_snapshot swaps the read state for a new one. The snapshot is // built by the UI thread as a heap literal; the swap hands the worker a // pointer the UI thread no longer holds, and the mutex is held only for // that swap. fn (mut m Mpris) replace_snapshot(s &MprisSnapshot) { m.snapshot_mu.lock() m.snapshot = s m.snapshot_mu.unlock() } // current_snapshot copies the latest snapshot reference out. The read is // unsynchronized on purpose: the reference is pointer-sized, the object it // points at never changes once published, and the UI thread only ever // swaps the reference, so the worker sees either the old or the new // snapshot, both valid. fn (m &Mpris) current_snapshot() &MprisSnapshot { return m.snapshot } // mpris_snapshot_of_empty is the state before any file: Stopped, nothing // playable, the step flags off. fn mpris_snapshot_of_empty() &MprisSnapshot { return &MprisSnapshot{ status: 'Stopped' rate: 1 } } // ── Worker-thread side ────────────────────────────────────────────────────── // mpris_worker owns the D-Bus connection for its whole life: it connects, // requests the name, registers the object path, then serves reads from the // snapshot and queues commands for the UI thread until the stop flag flips. // Only a V-spawned thread runs here, so the GC knows it and every V string // and array it touches is safe. fn mpris_worker(mut m Mpris) { mut err := DBusError{} C.dbus_error_init(&err) conn := C.dbus_bus_get(dbus_bus_session, voidptr(&err)) if conn == unsafe { nil } { if err.message != unsafe { nil } { text := unsafe { cstring_to_vstring(err.message) } eprintln('vendetta: media controls: no session bus: ${text}') } else { eprintln('vendetta: media controls: no session bus') } C.dbus_error_free(&err) return } C.dbus_error_free(&err) // The name is taken with DO_NOT_QUEUE: a second vendetta must not sit in // the name queue waiting for the first to exit, because both would then // answer calls meant for whichever owns the name. Losing is reported and // the service idles; the connection stays until shutdown so the owner // keeps its unique name for any caller that wants the player anyway. rc := C.dbus_bus_request_name(conn, mpris_name.str, dbus_name_flag_do_not_queue, voidptr(&err)) if rc < 0 { if err.message != unsafe { nil } { text := unsafe { cstring_to_vstring(err.message) } eprintln('vendetta: media controls: name request failed: ${text}') } else { eprintln('vendetta: media controls: name request failed') } C.dbus_error_free(&err) return } if rc != dbus_request_name_reply_primary_owner && rc != dbus_request_name_reply_already_owner { eprintln('vendetta: media controls: another player owns ${mpris_name}') return } // The object path is registered before any call can arrive, so nothing // lands that the vtable is not there to answer. mut vtable := DBusObjectPathVTable{ unregister_function: voidptr(0) message_function: mpris_message_handler } if C.dbus_connection_register_object_path(conn, mpris_path.str, voidptr(&vtable), voidptr(m)) == 0 { eprintln('vendetta: media controls: object path registration failed') return } // The Properties interface rides the same path under a different // interface name; a filter answers its Get/Set/GetAll before the vtable // even sees the message. C.dbus_connection_add_filter(conn, mpris_filter, voidptr(m), unsafe { nil }) m.conn = conn m.wake_worker() for { if m.stop_flag { // The connection is shared process-wide and must not be closed, // so the name and the path are given back here, on the thread that // uses the connection. C.dbus_bus_release_name(conn, mpris_name.str, unsafe { nil }) C.dbus_connection_unregister_object_path(conn, mpris_path.str) return } // The per-wake work: dispatch what the bus delivered, then publish // the signals the latest snapshot calls for. for C.dbus_connection_get_dispatch_status(conn) == dbus_dispatch_data_remains { C.dbus_connection_dispatch(conn) } s := m.current_snapshot() if mpris_have_announced { mpris_emit_diff(mut m, mpris_last_snapshot, s) } else { // The first snapshot announces everything at once. mpris_emit_diff(mut m, mpris_snapshot_of_empty(), s) mpris_have_announced = true } mpris_last_snapshot = s // The sleep: read_write runs the socket work with a short timeout // and doubles as the nap. The wake pipe is read after it, so a // byte that arrived mid-nap cuts the next one short; C.read past a // wake returns immediately, and the cycle restarts. A full // read_write_dispatch would block in select on the bus sockets, // which is exactly the wait the pipe cannot interrupt. C.dbus_connection_read_write(conn, dbus_poll_ms) m.drain_pipe() } } // dbus_poll_ms is how long the worker's read_write may block on the bus // sockets between cycles: long enough that an idle service costs nothing, // short enough that the stop flag is honoured promptly. const dbus_poll_ms = 200 // mpris_last_snapshot remembers what the signals last announced; worker-local // state, written and read only on the worker thread. __global mpris_last_snapshot = mpris_snapshot_of_empty() __global mpris_have_announced = false // ── Message plumbing ──────────────────────────────────────────────────────── // queue hands one command to the UI thread and asks ui2 for a paint. The // window repaints only when asked, and the per-frame drain runs in the video // surface's draw, which a plain rebuild does not reach. The executor's own // state changes ask for a rebuild where they need one. fn (mut m Mpris) queue(cmd MprisCommand) { m.commands <- cmd ui2.request_paint() } // mpris_message_handler answers calls addressed to the object path. Runs on // the worker thread: the player is never touched, reads come from the // snapshot and writes go over the channel. fn mpris_message_handler(conn voidptr, msg voidptr, user_data voidptr) i32 { mut m := &Mpris(user_data) if C.dbus_message_get_type(msg) != dbus_msg_method_call { return dbus_handler_not_yet_handled } iface := dbus_cstring(C.dbus_message_get_interface(msg)) member := dbus_cstring(C.dbus_message_get_member(msg)) if iface == mpris_root_iface { return m.handle_root(msg, member) } if iface == mpris_player_iface { return m.handle_player(msg, member) } if iface == dbus_introspectable_iface { return m.handle_introspect(conn, msg) } return dbus_handler_not_yet_handled } // dbus_cstring reads a libdbus-owned C string, nil tolerated. fn dbus_cstring(ptr &char) string { if ptr == unsafe { nil } { return '' } return unsafe { cstring_to_vstring(ptr) } } // handle_root answers the org.mpris.MediaPlayer2 root interface's methods: // Raise and Quit. CanQuit, Identity and friends are property reads, served // by the filter below. fn (mut m Mpris) handle_root(msg voidptr, member string) i32 { match member { 'Raise' { m.queue(MprisCommand{ kind: .raise }) return m.reply_empty(msg) } 'Quit' { m.queue(MprisCommand{ kind: .quit }) return m.reply_empty(msg) } else {} } return dbus_handler_not_yet_handled } // handle_player answers the org.mpris.MediaPlayer2.Player interface's // methods. Each queues one command; the UI thread runs them where mpv lives. fn (mut m Mpris) handle_player(msg voidptr, member string) i32 { match member { 'Play' { m.queue(MprisCommand{ kind: .play }) return m.reply_empty(msg) } 'Pause' { m.queue(MprisCommand{ kind: .pause }) return m.reply_empty(msg) } 'PlayPause' { m.queue(MprisCommand{ kind: .toggle_play }) return m.reply_empty(msg) } 'Stop' { m.queue(MprisCommand{ kind: .stop }) return m.reply_empty(msg) } 'Next' { m.queue(MprisCommand{ kind: .next }) return m.reply_empty(msg) } 'Previous' { m.queue(MprisCommand{ kind: .previous }) return m.reply_empty(msg) } 'Seek' { x := dbus_iter_int64_arg(msg) or { return m.reply_error(msg, dbus_error_invalid_args, 'Seek wants an offset in microseconds') } m.queue(MprisCommand{ kind: .seek, arg: f64(x) / 1_000_000.0 }) return m.reply_empty(msg) } 'SetPosition' { res := dbus_iter_set_position(msg) or { return m.reply_error(msg, dbus_error_invalid_args, 'SetPosition wants (o trackid, x position)') } m.queue(MprisCommand{ kind: .set_position, arg: res.pos, track: res.track }) return m.reply_empty(msg) } 'OpenUri' { uri := dbus_iter_string_arg(msg) or { return m.reply_error(msg, dbus_error_invalid_args, 'OpenUri wants a URI') } target := mpris_open_target(uri) or { return m.reply_error(msg, dbus_error_invalid_args, 'Unsupported URI: ${uri}') } m.queue(MprisCommand{ kind: .open_uri, uri: target }) return m.reply_empty(msg) } else {} } return dbus_handler_not_yet_handled } // handle_introspect answers the XML desktop caches ask for once. The // Properties interface is included though it is answered by the filter, so // an introspecting caller sees the whole object. fn (mut m Mpris) handle_introspect(conn voidptr, msg voidptr) i32 { reply := C.dbus_message_new_method_return(msg) if reply == unsafe { nil } { return dbus_handler_not_yet_handled } xml := mpris_introspection_xml() C.dbus_message_append_args(reply, dbus_type_string, voidptr(&xml), 0) C.dbus_connection_send(conn, reply, unsafe { nil }) C.dbus_message_unref(reply) return dbus_handler_handled } // reply_empty answers a void method return. fn (mut m Mpris) reply_empty(msg voidptr) i32 { reply := C.dbus_message_new_method_return(msg) if reply == unsafe { nil } { return dbus_handler_not_yet_handled } C.dbus_connection_send(m.conn, reply, unsafe { nil }) C.dbus_message_unref(reply) return dbus_handler_handled } // reply_error answers with a D-Bus error: the name and a human message. fn (mut m Mpris) reply_error(msg voidptr, name string, text string) i32 { reply := C.dbus_message_new_error(msg, name.str, text.str) if reply == unsafe { nil } { return dbus_handler_not_yet_handled } C.dbus_connection_send(m.conn, reply, unsafe { nil }) C.dbus_message_unref(reply) return dbus_handler_handled } // ── Argument readers ──────────────────────────────────────────────────────── // dbus_iter_string_arg reads a one-string or one-object-path message. fn dbus_iter_string_arg(msg voidptr) ?string { mut iter := DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return none } return dbus_iter_read_string(&iter) } // dbus_iter_read_string reads a string or object path out of an iterator. fn dbus_iter_read_string(iter &DBusMessageIter) ?string { typ := C.dbus_message_iter_get_arg_type(iter) if typ != dbus_type_string && typ != dbus_type_object_path { return none } mut ptr := voidptr(0) C.dbus_message_iter_get_basic(iter, &ptr) return dbus_cstring(unsafe { &char(ptr) }) } // dbus_iter_int64_arg reads a one-int64 message. fn dbus_iter_int64_arg(msg voidptr) ?i64 { mut iter := DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return none } if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_int64 { return none } mut v := i64(0) C.dbus_message_iter_get_basic(&iter, &v) return v } // SetPositionResult carries SetPosition's two arguments. struct SetPositionResult { track string pos f64 } // dbus_iter_set_position unpacks (o trackid, x position) — two top-level // arguments, no container between them. fn dbus_iter_set_position(msg voidptr) ?SetPositionResult { mut iter := DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return none } track := dbus_iter_read_string(&iter) or { return none } if C.dbus_message_iter_next(&iter) == 0 { return none } if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_int64 { return none } mut v := i64(0) C.dbus_message_iter_get_basic(&iter, &v) return SetPositionResult{ track: track pos: f64(v) / 1_000_000.0 } } // mpris_open_target turns an OpenUri argument into what load() accepts. // file:// URIs decode back to paths, because mpv wants one; a link — any // other protocol prefix — goes through verbatim for mpv to stream. Neither // shape is an error reply, which is friendlier than a load that would fail // later with less context. fn mpris_open_target(uri string) ?string { if uri.starts_with('file://') { mut rest := uri.all_after('file://') // A host part (file://localhost/path) is tolerated; the spec's empty // host rides the same decode. Percent escapes decode into raw bytes, // which is what a path is. if rest.starts_with('localhost/') { rest = rest.all_after('localhost') } return urllib.query_unescape(rest) or { return none } } if libvendetta.source_kind(uri) == .link { return uri } return none } // ── Properties filter ─────────────────────────────────────────────────────── // mpris_filter catches the Properties calls: Get, Set and GetAll arrive // addressed to the object path but to the properties interface, and the // vtable dispatches by interface, so the filter answers them here. fn mpris_filter(_ voidptr, msg voidptr, user_data voidptr) i32 { mut m := &Mpris(user_data) if C.dbus_message_get_type(msg) != dbus_msg_method_call { return dbus_handler_not_yet_handled } if dbus_cstring(C.dbus_message_get_interface(msg)) != dbus_props_iface { return dbus_handler_not_yet_handled } member := dbus_cstring(C.dbus_message_get_member(msg)) match member { 'Get' { return m.props_get(msg) } 'Set' { return m.props_set(msg) } 'GetAll' { return m.props_get_all(msg) } else {} } return dbus_handler_not_yet_handled } // props_get answers Properties.Get with one property's value as a variant. fn (mut m Mpris) props_get(msg voidptr) i32 { mut iter := DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)') } iface := dbus_iter_read_string(&iter) or { return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)') } if C.dbus_message_iter_next(&iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)') } prop := dbus_iter_read_string(&iter) or { return m.reply_error(msg, dbus_error_invalid_args, 'Get wants (s interface, s property)') } s := m.current_snapshot() mut body := m.property_body(iface, prop, s) or { return m.reply_error(msg, dbus_error_unknown_property, 'No such property: ${prop}') } reply := C.dbus_message_new_method_return(msg) if reply == unsafe { nil } { return dbus_handler_not_yet_handled } mut rit := DBusMessageIter{} C.dbus_message_iter_init_append(reply, &rit) m.append_prop(&rit, mut body) C.dbus_connection_send(m.conn, reply, unsafe { nil }) C.dbus_message_unref(reply) return dbus_handler_handled } // props_get_all answers Properties.GetAll with the interface's whole // property dictionary: a{sv}. fn (mut m Mpris) props_get_all(msg voidptr) i32 { mut iter := DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'GetAll wants an interface name') } iface := dbus_iter_read_string(&iter) or { return m.reply_error(msg, dbus_error_invalid_args, 'GetAll wants an interface name') } s := m.current_snapshot() reply := C.dbus_message_new_method_return(msg) if reply == unsafe { nil } { return dbus_handler_not_yet_handled } mut rit := DBusMessageIter{} C.dbus_message_iter_init_append(reply, &rit) mut arr := DBusMessageIter{} C.dbus_message_iter_open_container(&rit, dbus_type_array, c'{sv}', &arr) for prop, mut body in m.property_table(iface, s) { mut entry := DBusMessageIter{} C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &entry) dbus_append_text(&entry, dbus_type_string, prop) m.append_prop(&entry, mut body) C.dbus_message_iter_close_container(&arr, &entry) } C.dbus_message_iter_close_container(&rit, &arr) C.dbus_connection_send(m.conn, reply, unsafe { nil }) C.dbus_message_unref(reply) return dbus_handler_handled } // props_set answers Properties.Set: only the writable Player properties // exist here, and each maps to a command the UI thread runs. fn (mut m Mpris) props_set(msg voidptr) i32 { mut iter := DBusMessageIter{} if C.dbus_message_iter_init(msg, &iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)') } iface := dbus_iter_read_string(&iter) or { return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)') } if C.dbus_message_iter_next(&iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)') } prop := dbus_iter_read_string(&iter) or { return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)') } if C.dbus_message_iter_next(&iter) == 0 { return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)') } if C.dbus_message_iter_get_arg_type(&iter) != dbus_type_variant { return m.reply_error(msg, dbus_error_invalid_args, 'Set wants (s interface, s property, v value)') } mut var := DBusMessageIter{} C.dbus_message_iter_recurse(&iter, &var) if iface != mpris_player_iface { // The root interface has no writable properties; Fullscreen is // optional and vendetta does not offer it. return m.reply_error(msg, dbus_error_unknown_property, 'No writable property: ${prop}') } match prop { 'LoopStatus' { value := dbus_iter_read_string(&var) or { return m.reply_error(msg, dbus_error_invalid_args, 'LoopStatus wants a string') } code := mpris_loop_code(value) or { return m.reply_error(msg, dbus_error_invalid_args, 'Not a LoopStatus: ${value}') } m.queue(MprisCommand{ kind: .loop_status, arg: code }) return m.reply_empty(msg) } 'Shuffle' { // A number is refused on purpose: the spec's type is a boolean, and // a double-encoded value is not one. if _ := dbus_iter_double_from(var) { return m.reply_error(msg, dbus_error_invalid_args, 'Shuffle wants a boolean') } b := dbus_iter_flag_from(var) or { return m.reply_error(msg, dbus_error_invalid_args, 'Shuffle wants a boolean') } m.queue(MprisCommand{ kind: .shuffle, arg: if b { 1.0 } else { 0.0 } }) return m.reply_empty(msg) } 'Volume' { value := dbus_iter_double_from(var) or { return m.reply_error(msg, dbus_error_invalid_args, 'Volume wants a double') } m.queue(MprisCommand{ kind: .volume, arg: value }) return m.reply_empty(msg) } 'Rate' { return m.reply_error(msg, dbus_error_property_readonly, 'Rate follows the speed menu') } else { return m.reply_error(msg, dbus_error_property_readonly, 'Read-only property: ${prop}') } } } // dbus_iter_double_from reads a double out of an iterator. fn dbus_iter_double_from(iter &DBusMessageIter) ?f64 { if C.dbus_message_iter_get_arg_type(iter) != dbus_type_double { return none } mut v := f64(0) C.dbus_message_iter_get_basic(iter, &v) return v } // dbus_iter_flag_from reads a boolean out of an iterator. fn dbus_iter_flag_from(iter &DBusMessageIter) ?bool { if C.dbus_message_iter_get_arg_type(iter) != dbus_type_boolean { return none } mut v := i32(0) C.dbus_message_iter_get_basic(iter, &v) return v != 0 } // ── Property table ────────────────────────────────────────────────────────── // PropBody is one property ready to append: the variant's signature, the // wire type and the value in its C form. struct PropBody { pub: signature string typ i32 str string boolean bool num f64 items []string entries []PropEntry } // PropEntry is one key/value pair of a dictionary property (Metadata). struct PropEntry { pub: key string value PropBody } // prop_string wraps a string or object-path value. fn prop_string(typ i32, value string) PropBody { return PropBody{ signature: if typ == dbus_type_object_path { 'o' } else { 's' } typ: typ str: value } } // prop_bool wraps a boolean value. fn prop_bool(value bool) PropBody { return PropBody{ signature: 'b' typ: dbus_type_boolean boolean: value } } // prop_double wraps a double value. fn prop_double(value f64) PropBody { return PropBody{ signature: 'd' typ: dbus_type_double num: value } } // prop_int wraps an int64 value. fn prop_int(value i64) PropBody { return PropBody{ signature: 'x' typ: dbus_type_int64 num: f64(value) } } // prop_string_array wraps an array of strings. fn prop_string_array(items []string) PropBody { return PropBody{ signature: 'as' typ: dbus_type_array items: items } } // prop_dict wraps a dictionary of string→variant entries (a{sv}). fn prop_dict(entries []PropEntry) PropBody { return PropBody{ signature: 'a{sv}' typ: dbus_type_array entries: entries } } // append_prop appends one property as a variant into an open iterator: the // form Properties.Get returns and each a{sv} entry carries. fn (mut m Mpris) append_prop(iter &DBusMessageIter, mut body PropBody) { mut var := DBusMessageIter{} mut sig := body.signature C.dbus_message_iter_open_container(iter, dbus_type_variant, sig.str, &var) m.append_body(&var, mut body) C.dbus_message_iter_close_container(iter, &var) } // dbus_append_text appends a string or object path. libdbus reads the text // through the address of a char* that the call holds, so the pointer lives in // a local for the call, and the append copies the bytes out before it returns. fn dbus_append_text(iter &DBusMessageIter, typ i32, value string) { mut ptr := value.str C.dbus_message_iter_append_basic(iter, typ, voidptr(&ptr)) } // append_body appends the body's value into an open container. fn (mut m Mpris) append_body(iter &DBusMessageIter, mut body PropBody) { // A failed open would leave the sub-iterator zeroed and the close would // walk off it, so opens are checked like the rest. match body.typ { dbus_type_string, dbus_type_object_path { dbus_append_text(iter, body.typ, body.str) } dbus_type_boolean { mut flag := i32(if body.boolean { 1 } else { 0 }) C.dbus_message_iter_append_basic(iter, dbus_type_boolean, voidptr(&flag)) } dbus_type_double { mut v := body.num C.dbus_message_iter_append_basic(iter, dbus_type_double, voidptr(&v)) } dbus_type_int64 { mut v := i64(body.num) C.dbus_message_iter_append_basic(iter, dbus_type_int64, voidptr(&v)) } dbus_type_array { if body.entries.len > 0 { // a{sv}: a dict entry per pair, the key a string, the value // a variant. The dict entry's own signature is the pair // 'sv'; the array's is the wrapped '{sv}'. mut arr := DBusMessageIter{} mut sig := body.signature.all_after('a') if C.dbus_message_iter_open_container(iter, dbus_type_array, sig.str, &arr) == 0 { return } for mut entry in body.entries { mut de := DBusMessageIter{} C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de) dbus_append_text(&de, dbus_type_string, entry.key) m.append_prop(&de, mut entry.value) C.dbus_message_iter_close_container(&arr, &de) } C.dbus_message_iter_close_container(iter, &arr) } else { // as: one string per element. mut arr := DBusMessageIter{} mut elem := body.signature.all_after('a') if C.dbus_message_iter_open_container(iter, dbus_type_array, elem.str, &arr) == 0 { return } for item in body.items { dbus_append_text(&arr, dbus_type_string, item) } C.dbus_message_iter_close_container(iter, &arr) } } else {} } } // property_body is property_table reduced to one property; none is the // Properties.Get error case. fn (m &Mpris) property_body(iface string, prop string, s &MprisSnapshot) ?PropBody { return m.property_table(iface, s)[prop] } // property_table builds the property dictionary an interface serves: the // root's static block, or the Player's from the snapshot. fn (m &Mpris) property_table(iface string, s &MprisSnapshot) map[string]PropBody { mut table := map[string]PropBody{} if iface == mpris_root_iface { table['CanQuit'] = prop_bool(true) table['Fullscreen'] = prop_bool(false) table['CanSetFullscreen'] = prop_bool(false) table['CanRaise'] = prop_bool(false) table['HasTrackList'] = prop_bool(false) table['Identity'] = prop_string(dbus_type_string, 'Vendetta') table['DesktopEntry'] = prop_string(dbus_type_string, 'vendetta') // The spec wants URI schemes the player can open, not file // extensions, and prefers schemes over suffix lists. table['SupportedUriSchemes'] = prop_string_array(['file', 'http', 'https', 'ftp', 'rtsp', 'srt', 'sftp']) table['SupportedMimeTypes'] = prop_string_array(['video/mp4', 'video/x-matroska', 'video/webm', 'video/x-msvideo', 'video/quicktime', 'video/mpeg', 'audio/mpeg', 'audio/ogg', 'audio/flac', 'audio/x-wav', 'audio/x-m4a', 'audio/aac']) return table } if iface != mpris_player_iface { return table } table['PlaybackStatus'] = prop_string(dbus_type_string, s.status) table['LoopStatus'] = prop_string(dbus_type_string, s.loop_status) table['Shuffle'] = prop_bool(s.shuffle) table['Metadata'] = m.metadata_body(s) table['Volume'] = prop_double(mpris_volume_fraction(s.volume)) table['Rate'] = prop_double(if s.rate > 0 { s.rate } else { 1.0 }) table['MinimumRate'] = prop_double(0.01) table['MaximumRate'] = prop_double(100.0) table['Position'] = prop_int(i64(s.position * 1_000_000.0)) table['CanPlay'] = prop_bool(s.can_play) table['CanPause'] = prop_bool(s.can_pause) table['CanSeek'] = prop_bool(s.can_seek) table['CanControl'] = prop_bool(true) table['CanGoNext'] = prop_bool(s.can_go_next) table['CanGoPrevious'] = prop_bool(s.can_go_prev) return table } // metadata_body builds the Metadata a{sv}: the fixed ids plus xesam fields // filled from what mpv holds. An empty file contributes the empty // dictionary, which is what the spec names for no track. fn (m &Mpris) metadata_body(s &MprisSnapshot) PropBody { mut entries := []PropEntry{} if s.has_file { // The trackid is an object path that must change when the track // does; the playing file's URL under /org/vendetta/track serves. entries << PropEntry{ key: 'mpris:trackid' value: prop_string(dbus_type_object_path, mpris_track_path(s.url)) } entries << PropEntry{ key: 'xesam:url' value: prop_string(dbus_type_string, s.url) } if s.title.len > 0 { entries << PropEntry{ key: 'xesam:title' value: prop_string(dbus_type_string, s.title) } } if s.artist.len > 0 { entries << PropEntry{ key: 'xesam:artist' value: prop_string_array([s.artist]) } } if s.duration > 0 { entries << PropEntry{ key: 'mpris:length' value: prop_int(i64(s.duration * 1_000_000.0)) } } } return prop_dict(entries) } // mpris_track_path names a track by a hash of its URL. An object path may // only hold [A-Za-z0-9_] between slashes, so the URL itself cannot ride in it. // The hash is stable for a URL, which is what SetPosition's stale check // compares. No URL is the spec's NoTrack path, since an empty path is not a // valid object path. fn mpris_track_path(url string) string { if url.len == 0 { return '/org/mpris/MediaPlayer2/TrackList/NoTrack' } mut h := u64(0xcbf29ce484222325) for c in url.bytes() { h ^= u64(c) h *= u64(0x100000001b3) } return '/org/vendetta/track/${h:x}' } // mpris_volume_fraction turns mpv's volume into the Volume the interface // carries. mpv's 100 is unity gain, which the spec calls 1.0 (0 dB), so the // desktop's percentage matches the app's own number whatever max the user // set. The spec allows values above 1.0, so only the floor is clamped. fn mpris_volume_fraction(volume f64) f64 { return math.max(0.0, volume / 100.0) } // mpris_loop_code translates a LoopStatus value into the loop code the // command carries: 0 none, 1 track, 2 playlist. fn mpris_loop_code(name string) ?f64 { return match name { 'None' { f64(0) } 'Track' { f64(1) } 'Playlist' { f64(2) } else { none } } } // ── Seeked signal ─────────────────────────────────────────────────────────── // emit_seeked sends a Seeked signal carrying the position in microseconds. fn (mut m Mpris) emit_seeked(pos f64) { conn := m.conn if conn == unsafe { nil } { return } msg := C.dbus_message_new_signal(mpris_path.str, mpris_player_iface.str, c'Seeked') if msg == unsafe { nil } { return } // Seeked carries one x: the position the seek landed on. mpv's property // does not move until the seek completes, so the signal rides the // position property change that follows. mut iter := DBusMessageIter{} C.dbus_message_iter_init_append(msg, &iter) mut var := DBusMessageIter{} C.dbus_message_iter_open_container(&iter, dbus_type_variant, c'x', &var) pos_us := i64(pos * 1_000_000.0) C.dbus_message_iter_append_basic(&var, dbus_type_int64, voidptr(&pos_us)) C.dbus_message_iter_close_container(&iter, &var) C.dbus_connection_send(conn, msg, unsafe { nil }) C.dbus_message_unref(msg) } // mpris_emit_diff emits the PropertiesChanged signals the move from last to // next calls for. One signal per concern: playback state, capability flags. // Desktops coalesce the bursts, and Metadata alone would otherwise arrive // as half a dozen signals on a file change. fn mpris_emit_diff(mut m Mpris, last &MprisSnapshot, next &MprisSnapshot) { mut changed := []PropEntry{} if last.status != next.status { changed << PropEntry{ key: 'PlaybackStatus' value: prop_string(dbus_type_string, next.status) } // Position stays out of this signal: the spec says Position changes // do not emit PropertiesChanged, and clients read it on demand. } if last.loop_status != next.loop_status { changed << PropEntry{ key: 'LoopStatus' value: prop_string(dbus_type_string, next.loop_status) } } if last.shuffle != next.shuffle { changed << PropEntry{ key: 'Shuffle' value: prop_bool(next.shuffle) } } if mpris_volume_fraction(last.volume) != mpris_volume_fraction(next.volume) { changed << PropEntry{ key: 'Volume' value: prop_double(mpris_volume_fraction(next.volume)) } } if last.rate != next.rate { changed << PropEntry{ key: 'Rate' value: prop_double(if next.rate > 0 { next.rate } else { 1.0 }) } } // Metadata changes wholesale: trackid, title, artist, url and length // move together on a file change, and the empty file state empties the // dictionary. if last.has_file != next.has_file || last.url != next.url || last.title != next.title || last.artist != next.artist || last.duration != next.duration { changed << PropEntry{ key: 'Metadata' value: m.metadata_body(next) } } if changed.len > 0 { m.emit_properties_changed(mpris_player_iface, mut changed, []) } // The capability flags move with the file state: a stop takes Play away, // a load brings it back, the playlist edges grey the step buttons. if last.has_file != next.has_file || last.can_play != next.can_play || last.can_pause != next.can_pause || last.can_seek != next.can_seek || last.can_go_next != next.can_go_next || last.can_go_prev != next.can_go_prev || last.playlist_pos != next.playlist_pos || last.playlist_len != next.playlist_len { mut caps := []PropEntry{} caps << PropEntry{ key: 'CanPlay', value: prop_bool(next.can_play) } caps << PropEntry{ key: 'CanPause', value: prop_bool(next.can_pause) } caps << PropEntry{ key: 'CanSeek', value: prop_bool(next.can_seek) } caps << PropEntry{ key: 'CanGoNext', value: prop_bool(next.can_go_next) } caps << PropEntry{ key: 'CanGoPrevious', value: prop_bool(next.can_go_prev) } m.emit_properties_changed(mpris_player_iface, mut caps, []) } } // emit_properties_changed sends one PropertiesChanged signal: the interface, // the changed properties as a{sv}, and the invalidated names as as. The // signal rides the session bus to whoever subscribed. fn (mut m Mpris) emit_properties_changed(iface string, mut changed []PropEntry, _ []string) { conn := m.conn if conn == unsafe { nil } || changed.len == 0 { return } msg := C.dbus_message_new_signal(mpris_path.str, dbus_props_iface.str, c'PropertiesChanged') if msg == unsafe { nil } { return } mut iter := DBusMessageIter{} C.dbus_message_iter_init_append(msg, &iter) dbus_append_text(&iter, dbus_type_string, iface) // The changed dictionary. mut arr := DBusMessageIter{} mut opened := C.dbus_message_iter_open_container(&iter, dbus_type_array, c'{sv}', &arr) if opened == 0 { C.dbus_message_unref(msg) return } for mut entry in changed { mut de := DBusMessageIter{} opened = C.dbus_message_iter_open_container(&arr, dbus_type_dict_entry, unsafe { nil }, &de) if opened == 0 { break } dbus_append_text(&de, dbus_type_string, entry.key) m.append_prop(&de, mut entry.value) C.dbus_message_iter_close_container(&arr, &de) } C.dbus_message_iter_close_container(&iter, &arr) // The invalidated array: empty, because every property here is reported // with its new value and nothing needs a re-read. mut inv := DBusMessageIter{} C.dbus_message_iter_open_container(&iter, dbus_type_array, c's', &inv) C.dbus_message_iter_close_container(&iter, &inv) C.dbus_connection_send(conn, msg, unsafe { nil }) C.dbus_message_unref(msg) } // ── Introspection ─────────────────────────────────────────────────────────── // mpris_introspection_xml is the object's D-Bus introspection. Properties // are listed on their interfaces; the signals and methods match what this // file answers, so an introspecting desktop sees a complete MPRIS object. fn mpris_introspection_xml() string { return ' ' }